Accelerate 文件

Megatron-LM

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Megatron-LM

Megatron-LM 能夠大規模地訓練大型 Transformer 語言模型。它為預訓練基於 Transformer 的語言模型,如 GPT(僅解碼器)、BERT(僅編碼器)和 T5(編碼器-解碼器),提供了高效的張量、流水線和序列並行。有關詳細資訊和幕後工作原理,請參閱 Github 倉庫

集成了什麼?

Accelerate 集成了 Megatron-LM 的以下特性,以支援 BERT(編碼器)、GPT(解碼器)或 T5 模型(編碼器和解碼器)的大規模預訓練/微調:

a. 張量並行(TP):在節點內秩上減少記憶體佔用,而無需太多額外通訊。每個張量被分成多個塊,每個分片駐留在不同的 GPU 上。在每一步中,同一個小批次資料由每個分片獨立並行處理,然後所有 GPU 進行同步(all-reduce 操作)。在一個簡單的 Transformer 層中,這會在前向傳播中產生 2 次 all-reduces,在後向傳播中產生 2 次。有關詳細資訊,請參閱研究論文 Megatron-LM:使用模型並行訓練數十億引數的語言模型 和這篇部落格文章的部分內容 BLOOM 訓練背後的技術

b. 流水線並行(PP):透過節點間並行化減少記憶體佔用並實現大規模訓練。透過 PipeDream-Flush 排程/1F1B 排程和交錯 1F1B 排程減少樸素 PP 的氣泡。層被均勻分佈在 PP 階段上。例如,如果一個模型有 24 層,而我們有 4 個 GPU 用於流水線並行,那麼每個 GPU 將有 6 層 (24/4)。有關減少 PP 空閒時間的排程的更多詳細資訊,請參閱研究論文 在 GPU 叢集上使用 Megatron-LM 進行高效的大規模語言模型訓練 和這篇部落格文章的部分內容 BLOOM 訓練背後的技術

c. 序列並行(SP):無需任何額外通訊即可減少記憶體佔用。僅在使用 TP 時適用。它透過將張量並行秩上的相同副本在 all-reduce 後替換為 reduce-scatterno-op 操作(將被 all-gather 替換)來減少所需的啟用記憶體。由於 all-reduce = reduce-scatter + all-gather,這在不增加通訊成本的情況下節省了大量的啟用記憶體。簡單來說,它將每個 Transformer 層的輸出沿序列維度分片,例如,如果序列長度為 1024,TP 大小為 4,那麼每個 GPU 將為每個樣本處理 256 個標記(1024/4)。這增加了訓練所能支援的批次大小。有關詳細資訊,請參閱研究論文 減少大型 Transformer 模型中的啟用重計算

d. 透過分散式最佳化器實現資料並行(DP):透過在 DP 秩上分片最佳化器狀態和梯度(相對於傳統方法中在資料並行秩上覆制最佳化器狀態)來減少記憶體佔用。例如,當使用 Adam 最佳化器進行混合精度訓練時,每個引數佔用 12 位元組的記憶體。這會均勻分佈在 GPU 上,即,如果我們有 4 個 GPU,每個引數將佔用 3 位元組(12/4)。有關詳細資訊,請參閱研究論文 ZeRO:邁向萬億引數模型訓練的記憶體最佳化 和部落格的以下部分 BLOOM 訓練背後的技術

e. 選擇性啟用重計算:透過智慧啟用檢查點顯著減少啟用的記憶體佔用。它不儲存佔用大量記憶體但重新計算速度快的啟用,從而在記憶體和重新計算之間實現了很好的權衡。例如,對於 GPT-3,這導致啟用所需記憶體減少了 70%,而重新計算啟用的 FLOPs 開銷僅為 2.7%。有關詳細資訊,請參閱研究論文 減少大型 Transformer 模型中的啟用重計算

f. 融合核函式:融合 Softmax、混合精度融合層歸一化和融合梯度累積到線性層的權重梯度計算。PyTorch JIT 編譯的融合 GeLU 和融合偏置+Dropout+殘差加法。

g. 支援索引資料集:用於大規模訓練的高效二進位制格式資料集。支援 mmapcached 索引檔案和 lazy 載入器格式。

h. 檢查點重塑和互操作性:用於將可變張量和流水線並行大小的 Megatron-LM 檢查點重塑為廣受歡迎的 Transformers 分片檢查點的實用程式,因為它與眾多工具(如 Accelerate Big Model Inference、Megatron-DeepSpeed Inference 等)有很好的支援。還支援將 Transformers 分片檢查點轉換為可變張量和流水線並行大小的 Megatron-LM 檢查點,以進行大規模訓練。

先決條件

您需要安裝最新的 pytorch、cuda、nccl 和 NVIDIA APEX 版本以及 nltk 庫。有關更多詳細資訊,請參見文件。另一種設定環境的方法是從 NGC 拉取一個包含所有必需安裝的 NVIDIA PyTorch 容器。

以下是設定 conda 環境的分步方法

  1. 建立一個虛擬環境
conda create --name ml
  1. 假設機器已安裝 CUDA 11.3,安裝相應的 PyTorch GPU 版本
conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
  1. 安裝 Nvidia APEX
git clone https://github.com/NVIDIA/apex
cd apex
pip install -v --disable-pip-version-check --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./
cd ..
  1. 安裝 Megatron-LM
git clone https://github.com/NVIDIA/Megatron-LM.git
cd Megatron-LM
git checkout core_r0.5.0
pip install --no-use-pep517 -e .

Accelerate Megatron-LM 外掛

重要的功能透過 accelerate config 命令直接支援。下面顯示了使用 Megatron-LM 功能的相應問題的示例

:~$ accelerate config --config_file "megatron_gpt_config.yaml"
In which compute environment are you running? ([0] This machine, [1] AWS (Amazon SageMaker)): 0
Which type of machine are you using? ([0] No distributed training, [1] multi-CPU, [2] multi-GPU, [3] TPU): 2
How many different machines will you use (use more than 1 for multi-node training)? [1]: 
Do you want to use DeepSpeed? [yes/NO]: 
Do you want to use FullyShardedDataParallel? [yes/NO]: 
Do you want to use Megatron-LM ? [yes/NO]: yes
What is the Tensor Parallelism degree/size? [1]:2
Do you want to enable Sequence Parallelism? [YES/no]: 
What is the Pipeline Parallelism degree/size? [1]:2
What is the number of micro-batches? [1]:2
Do you want to enable selective activation recomputation? [YES/no]: 
Do you want to use distributed optimizer which shards optimizer state and gradients across data parallel ranks? [YES/no]: 
What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: 
How many GPU(s) should be used for distributed training? [1]:4
Do you wish to use FP16 or BF16 (mixed precision)? [NO/fp16/bf16]: bf16

生成的配置如下所示

~$ cat megatron_gpt_config.yaml 
compute_environment: LOCAL_MACHINE
deepspeed_config: {}
distributed_type: MEGATRON_LM
downcast_bf16: 'no'
fsdp_config: {}
machine_rank: 0
main_process_ip: null
main_process_port: null
main_training_function: main
megatron_lm_config:
  megatron_lm_gradient_clipping: 1.0
  megatron_lm_num_micro_batches: 2
  megatron_lm_pp_degree: 2
  megatron_lm_recompute_activations: true
  megatron_lm_sequence_parallelism: true
  megatron_lm_tp_degree: 2
  megatron_lm_use_distributed_optimizer: true
mixed_precision: bf16
num_machines: 1
num_processes: 4
rdzv_backend: static
same_network: true
use_cpu: false

我們將以 GPT 預訓練為例。為了使用 Megatron-LM,對官方 run_clm_no_trainer.py 所需的最小更改如下

  1. 由於 Megatron-LM 使用其自己的最佳化器實現,因此需要使用與之相容的相應排程器。因此,僅支援 Megatron-LM 的排程器。使用者需要建立 accelerate.utils.MegatronLMDummyScheduler。示例如下
from accelerate.utils import MegatronLMDummyScheduler

if accelerator.distributed_type == DistributedType.MEGATRON_LM:
    lr_scheduler = MegatronLMDummyScheduler(
        optimizer=optimizer,
        total_num_steps=args.max_train_steps,
        warmup_num_steps=args.num_warmup_steps,
    )
else:
    lr_scheduler = get_scheduler(
        name=args.lr_scheduler_type,
        optimizer=optimizer,
        num_warmup_steps=args.num_warmup_steps * args.gradient_accumulation_steps,
        num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
    )
  1. 獲取總批次大小的詳細資訊現在需要考慮到張量和流水線並行的大小。下面顯示了獲取有效總批次大小的示例
if accelerator.distributed_type == DistributedType.MEGATRON_LM:
    total_batch_size = accelerator.state.megatron_lm_plugin.global_batch_size
else:
    total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
  1. 當使用 Megatron-LM 時,損失已經在資料並行組中進行了平均
if accelerator.distributed_type == DistributedType.MEGATRON_LM:
    losses.append(loss)
else:
    losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size)))

if accelerator.distributed_type == DistributedType.MEGATRON_LM:
    losses = torch.tensor(losses)
else:
    losses = torch.cat(losses)
  1. 對於 Megatron-LM,我們需要使用 accelerator.save_state 來儲存模型
if accelerator.distributed_type == DistributedType.MEGATRON_LM:
    accelerator.save_state(args.output_dir)
else:
    unwrapped_model = accelerator.unwrap_model(model)
    unwrapped_model.save_pretrained(
        args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
    )

就這樣!我們準備好了 🚀。請在 examples 資料夾中的 accelerate/examples/by_feature/megatron_lm_gpt_pretraining.py 路徑下找到示例指令碼。讓我們使用 4 個 A100-80GB GPU 為 gpt-large 模型架構執行它。

accelerate launch --config_file megatron_gpt_config.yaml \
examples/by_feature/megatron_lm_gpt_pretraining.py \
--config_name "gpt2-large" \
--tokenizer_name "gpt2-large" \
--dataset_name wikitext \
--dataset_config_name wikitext-2-raw-v1 \
--block_size 1024 \
--learning_rate 5e-5 \
--per_device_train_batch_size 24 \
--per_device_eval_batch_size 24 \
--num_train_epochs 5 \
--with_tracking \
--report_to "wandb" \
--output_dir "awesome_model"

以下是輸出日誌中的一些重要摘錄

Loading extension module fused_dense_cuda...
>>> done with compiling and loading fused kernels. Compilation time: 3.569 seconds
 > padded vocab (size: 50257) with 175 dummy tokens (new size: 50432)
Building gpt model in the pre-training mode.
The Megatron LM model weights are initialized at random in `accelerator.prepare`. Please use `accelerator.load_checkpoint` to load a pre-trained checkpoint matching the distributed setup.
Preparing dataloader
Preparing dataloader
Preparing model
 > number of parameters on (tensor, pipeline) model parallel rank (1, 0): 210753280
 > number of parameters on (tensor, pipeline) model parallel rank (1, 1): 209445120
 > number of parameters on (tensor, pipeline) model parallel rank (0, 0): 210753280
 > number of parameters on (tensor, pipeline) model parallel rank (0, 1): 209445120
Preparing optimizer
Preparing scheduler
> learning rate decay style: linear
10/10/2022 22:57:22 - INFO - __main__ - ***** Running training *****
10/10/2022 22:57:22 - INFO - __main__ -   Num examples = 2318
10/10/2022 22:57:22 - INFO - __main__ -   Num Epochs = 5
10/10/2022 22:57:22 - INFO - __main__ -   Instantaneous batch size per device = 24
10/10/2022 22:57:22 - INFO - __main__ -   Total train batch size (w. parallel, distributed & accumulation) = 48
10/10/2022 22:57:22 - INFO - __main__ -   Gradient Accumulation steps = 1
10/10/2022 22:57:22 - INFO - __main__ -   Total optimization steps = 245
 20%|████████████▍                                                 | 49/245 [01:04<04:09,  1.27s/it]
 10/10/2022 22:58:29 - INFO - __main__ - epoch 0: perplexity: 1222.1594275215962 eval_loss: 7.10837459564209
 40%|████████████████████████▊                                     | 98/245 [02:10<03:07,  1.28s/it]
 10/10/2022 22:59:35 - INFO - __main__ - epoch 1: perplexity: 894.5236583794557 eval_loss: 6.796291351318359
 60%|████████████████████████████████████▌                        | 147/245 [03:16<02:05,  1.28s/it]
 10/10/2022 23:00:40 - INFO - __main__ - epoch 2: perplexity: 702.8458788508042 eval_loss: 6.555137634277344
 80%|████████████████████████████████████████████████▊            | 196/245 [04:22<01:02,  1.28s/it]
 10/10/2022 23:01:46 - INFO - __main__ - epoch 3: perplexity: 600.3220028695281 eval_loss: 6.39746618270874
100%|█████████████████████████████████████████████████████████████| 245/245 [05:27<00:00,  1.28s/it]

還有大量其他選項/功能可以透過 accelerate.utils.MegatronLMPlugin 進行設定。

利用高階功能編寫自定義訓練步驟和 Megatron-LM 索引資料集

要利用更多功能,請閱讀以下詳細資訊。

  1. 以下是使用 Megatron-LM 時自定義訓練步驟所需的更改示例。您需要實現 accelerate.utils.AbstractTrainStep 或繼承自其相應的子類 accelerate.utils.GPTTrainStepaccelerate.utils.BertTrainStepaccelerate.utils.T5TrainStep
from accelerate.utils import MegatronLMDummyScheduler, GPTTrainStep, avg_losses_across_data_parallel_group


# Custom loss function for the Megatron model
class GPTTrainStepWithCustomLoss(GPTTrainStep):
    def __init__(self, megatron_args, **kwargs):
        super().__init__(megatron_args)
        self.kwargs = kwargs

    def get_loss_func(self):
        def loss_func(inputs, loss_mask, output_tensor):
            batch_size, seq_length = output_tensor.shape
            losses = output_tensor.float()
            loss_mask = loss_mask.view(-1).float()
            loss = losses.view(-1) * loss_mask

            # Resize and average loss per sample
            loss_per_sample = loss.view(batch_size, seq_length).sum(axis=1)
            loss_mask_per_sample = loss_mask.view(batch_size, seq_length).sum(axis=1)
            loss_per_sample = loss_per_sample / loss_mask_per_sample

            # Calculate and scale weighting
            weights = torch.stack([(inputs == kt).float() for kt in self.kwargs["keytoken_ids"]]).sum(axis=[0, 2])
            weights = 1.0 + self.kwargs["alpha"] * weights
            # Calculate weighted average
            weighted_loss = (loss_per_sample * weights).mean()

            # Reduce loss across data parallel groups
            averaged_loss = avg_losses_across_data_parallel_group([weighted_loss])

            return weighted_loss, {"lm loss": averaged_loss[0]}

        return loss_func

    def get_forward_step_func(self):
        def forward_step(data_iterator, model):
            """Forward step."""
            # Get the batch.
            tokens, labels, loss_mask, attention_mask, position_ids = self.get_batch(data_iterator)
            output_tensor = model(tokens, position_ids, attention_mask, labels=labels)

            return output_tensor, partial(self.loss_func, tokens, loss_mask)

        return forward_step


def main():
    # Custom loss function for the Megatron model
    keytoken_ids = []
    keywords = ["plt", "pd", "sk", "fit", "predict", " plt", " pd", " sk", " fit", " predict"]
    for keyword in keywords:
        ids = tokenizer([keyword]).input_ids[0]
        if len(ids) == 1:
            keytoken_ids.append(ids[0])
    accelerator.print(f"Keytoken ids: {keytoken_ids}")
    accelerator.state.megatron_lm_plugin.custom_train_step_class = GPTTrainStepWithCustomLoss
    accelerator.state.megatron_lm_plugin.custom_train_step_kwargs = {
        "keytoken_ids": keytoken_ids,
        "alpha": 0.25,
    }
  1. 要使用 Megatron-LM 資料集,需要進行一些額外的更改。這些資料集的資料載入器僅在每個張量並行組的秩 0 上可用。因此,在某些秩上資料載入器將不可用,這需要對訓練迴圈進行調整。能夠做到這一切表明 Accelerate 是多麼靈活和可擴充套件。所需的更改如下。

a. 對於 Megatron-LM 索引資料集,我們需要使用 MegatronLMDummyDataLoader 並向其傳遞所需的資料集引數,例如 data_pathseq_length 等。有關可用引數的列表,請參見此處

from accelerate.utils import MegatronLMDummyDataLoader

megatron_dataloader_config = {
    "data_path": args.data_path,
    "splits_string": args.splits_string,
    "seq_length": args.block_size,
    "micro_batch_size": args.per_device_train_batch_size,
}
megatron_dataloader = MegatronLMDummyDataLoader(**megatron_dataloader_config)
accelerator.state.megatron_lm_plugin.megatron_dataset_flag = True

b. megatron_dataloader 重複 3 次以根據 args.splits_string 的比例獲取訓練、驗證和測試資料載入器

model, optimizer, lr_scheduler, train_dataloader, eval_dataloader, _ = accelerator.prepare(
    model, optimizer, lr_scheduler, megatron_dataloader, megatron_dataloader, megatron_dataloader
)

c. 由於資料載入器僅在張量並行秩 0 上可用,因此對訓練和評估迴圈進行了更改。因此,我們僅在資料載入器不為 None 時進行迭代,否則提供空字典。因此,我們使用 while 迴圈,並在 completed_steps 等於 args.max_train_steps 時中斷。這與 Megatron-LM 的設定類似,其中使用者在使用 Megatron-LM 索引資料集時必須提供 max_train_steps。這顯示了 Accelerate 的靈活性和可擴充套件性。

while completed_steps < args.max_train_steps:
    model.train()
    batch = next(train_dataloader) if train_dataloader is not None else {}
    outputs = model(**batch)
    loss = outputs.loss
    ...

    if completed_steps % eval_interval == 0:
        eval_completed_steps = 0
        losses = []
        while eval_completed_steps < eval_iters:
            model.eval()
            with torch.no_grad():
                batch = next(eval_dataloader) if eval_dataloader is not None else {}
                outputs = model(**batch)

用於檢查點重塑和互操作性的實用工具

  1. 這些指令碼位於 Transformers 庫中相應模型的目錄下。目前,它可用於 GPT 模型 checkpoint_reshaping_and_interoperability.py

  2. 以下是將檢查點從 Megatron-LM 轉換為通用 Transformers 分片檢查點的示例。

python checkpoint_reshaping_and_interoperability.py \
--convert_checkpoint_from_megatron_to_transformers \
--load_path "gpt/iter_0005000" \
--save_path "gpt/trfs_checkpoint" \
--max_shard_size "200MB" \
--tokenizer_name "gpt2" \
--print-checkpoint-structure
  1. 將檢查點從 transformers 轉換為 megatron,其中 tp_size=2pp_size=2dp_size=2
python checkpoint_utils/megatgron_gpt2/checkpoint_reshaping_and_interoperability.py \
--load_path "gpt/trfs_checkpoint" \
--save_path "gpt/megatron_lm_checkpoint" \
--target_tensor_model_parallel_size 2 \
--target_pipeline_model_parallel_size 2 \
--target_data_parallel_size 2 \
--target_params_dtype "bf16" \
--make_vocab_size_divisible_by 128 \
--use_distributed_optimizer \
--print-checkpoint-structure

Megatron-LM GPT 模型支援返回 logits 和用於文字生成的 megatron_generate 函式

  1. 返回 logits 需要在 MegatronLMPlugin 中設定 require_logits=True,如下所示。這些 logits 將在流水線的最後階段可用。
megatron_lm_plugin = MegatronLMPlugin(return_logits=True)
  1. Megatron-LM GPT 模型的 megatron_generate 方法:當使用貪婪搜尋(有/無 top_k/top_p 取樣)時,該方法將使用張量和流水線並行來完成一批輸入的生成;當使用波束搜尋解碼時,則用於單個提示輸入。僅支援 transformers generate 的一部分功能。這將有助於使用大型模型透過張量和流水線並行進行生成(預設情況下已進行鍵值快取並使用融合核函式)。這要求資料並行大小為 1,並停用序列並行和啟用檢查點。它還需要指定分詞器的 vocab 檔案和 merges 檔案的路徑。以下示例展示瞭如何為 Megatron-LM GPT 模型配置和使用 megatron_generate 方法。
# specifying tokenizer's vocab and merges file
vocab_file = os.path.join(args.resume_from_checkpoint, "vocab.json")
merge_file = os.path.join(args.resume_from_checkpoint, "merges.txt")
other_megatron_args = {"vocab_file": vocab_file, "merge_file": merge_file}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)

# inference using `megatron_generate` functionality
tokenizer.pad_token = tokenizer.eos_token
max_new_tokens = 64
batch_texts = [
    "Are you human?",
    "The purpose of life is",
    "The arsenal was constructed at the request of",
    "How are you doing these days?",
]
batch_encodings = tokenizer(batch_texts, return_tensors="pt", padding=True)

# top-p sampling
generated_tokens = model.megatron_generate(
    batch_encodings["input_ids"],
    batch_encodings["attention_mask"],
    max_new_tokens=max_new_tokens,
    top_p=0.8,
    top_p_decay=0.5,
    temperature=0.9,
)
decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
accelerator.print(decoded_preds)

# top-k sampling
generated_tokens = model.megatron_generate(
    batch_encodings["input_ids"],
    batch_encodings["attention_mask"],
    max_new_tokens=max_new_tokens,
    top_k=50,
    temperature=0.9,
)
decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
accelerator.print(decoded_preds)

# adding `bos` token at the start
generated_tokens = model.megatron_generate(
    batch_encodings["input_ids"], batch_encodings["attention_mask"], max_new_tokens=max_new_tokens, add_BOS=True
)
decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
accelerator.print(decoded_preds)

# beam search => only takes single prompt
batch_texts = ["The purpose of life is"]
batch_encodings = tokenizer(batch_texts, return_tensors="pt", padding=True)
generated_tokens = model.megatron_generate(
    batch_encodings["input_ids"],
    batch_encodings["attention_mask"],
    max_new_tokens=max_new_tokens,
    num_beams=20,
    length_penalty=1.5,
)
decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
accelerator.print(decoded_preds)
  1. 一個端到端使用 megatron_generate 方法的 Megatron-LM GPT 模型示例可在 megatron_gpt2_generation.py 找到,其配置檔案為 megatron_lm_gpt_generate_config.yaml。帶有 accelerate launch 命令的 bash 指令碼可在 megatron_lm_gpt_generate.sh 找到。指令碼的輸出日誌可在 megatron_lm_gpt_generate.log 找到。

支援 ROPE 和 ALiBi 位置嵌入以及多查詢注意力

  1. 對於 ROPE/ALiBi 注意力,請將 position_embedding_type 設定為 ("absolute" | "rotary" | "alibi") 並傳遞給 MegatronLMPlugin,如下所示。
other_megatron_args = {"position_embedding_type": "alibi"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)
  1. 對於多查詢注意力,請將 attention_head_type 設定為 ("multihead" | "multiquery") 並傳遞給 MegatronLMPlugin,如下所示。
other_megatron_args = {"attention_head_type": "multiquery"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)

注意事項

  1. 支援 Transformers GPT2、Megatron-BERT 和 T5 模型。這涵蓋了僅解碼器、僅編碼器和編碼器-解碼器模型類。

  2. 模型前向傳播只返回損失,因為背後涉及流水線、張量和資料並行之間相當複雜的相互作用。`model(**batch_data)` 呼叫返回在資料並行秩上平均的損失。這對於大多數情況是足夠的,例如使用 Megatron-LM 功能執行預訓練任務,您可以輕鬆地使用損失計算 `perplexity`。對於 GPT 模型,支援在損失之外返回 logits。這些 logits 不會在資料並行秩上收集。使用 `accelerator.utils.gather_across_data_parallel_groups` 在資料並行秩上收集 logits。這些 logits 和標籤可用於計算各種效能指標。

  3. 主程序是最後一個秩,因為損失/logits 在流水線的最後一個階段可用。當使用 Megatron-LM 整合時,`accelerator.is_main_process` 和 `accelerator.is_local_main_process` 對最後一個秩返回 `True`。

  4. 在 `accelerator.prepare` 呼叫中,會建立一個與給定 Transformers 模型對應的 Megatron-LM 模型,其權重是隨機的。請使用 `accelerator.load_state` 載入具有匹配 TP、PP 和 DP 分割槽的 Megatron-LM 檢查點。

  5. 目前,檢查點重塑和互操作性支援僅適用於 GPT。很快將擴充套件到 BERT 和 T5。

  6. `gradient_accumulation_steps` 需要為 1。當使用 Megatron-LM 時,流水線並行設定中的微批次與梯度累積是同義詞。

  7. 使用 Megatron-LM 時,請使用 `accelerator.save_state` 和 `accelerator.load_state` 來儲存和載入檢查點。

  8. 以下是 Megatron-LM 模型架構與等效的 Transformers 模型架構的對映。僅支援這些 Transformers 模型架構。

a. Megatron-LM BertModel:在配置的模型型別中包含 `megatron-bert` 的 Transformers 模型,例如 MegatronBERT

b. Megatron-LM GPTModel:在配置的模型型別中包含 `gpt2` 的 Transformers 模型,例如 OpenAI GPT2

c. Megatron-LM T5Model:在配置的模型型別中包含 `t5` 的 Transformers 模型,例如 T5MT5

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.