# Megatron-LM

[Megatron-LM](https://github.com/NVIDIA/Megatron-LM) 支持大规模训练大型 Transformer 语言模型。它为预训练基于 Transformer 的语言模型（例如 [GPT](https://huggingface.co/papers/2005.14165)（仅解码器）、[BERT](https://huggingface.co/papers/1810.04805)（仅编码器）和 [T5](https://huggingface.co/papers/1910.10683)（编码器-解码器））提供了高效的基于张量、流水线和序列的模型并行。有关详细信息及其底层工作原理，请参阅 github [仓库](https://github.com/NVIDIA/Megatron-LM)。

## 哪些内容已集成？

Accelerate 集成了 Megatron-LM 的以下功能，以支持对 BERT（编码器）、GPT（解码器）或 T5 模型（编码器和解码器）进行大规模预训练/微调：

a. **张量并行（TP）**：在节点内各 rank 之间几乎不增加额外通信开销的情况下，降低内存占用。每个张量被拆分为多个分片，每个分片驻留在不同的 GPU 上。在每一步中，相同的数据 mini-batch 由各个分片独立且并行地处理，随后在所有 GPU 之间进行同步（`all-reduce` 操作）。在一个简单的 transformer 层中，这会导致前向路径中有 2 次 `all-reduces`，反向路径中有 2 次。更多细节请参阅研究论文 [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://huggingface.co/papers/1909.08053) 以及博客文章的这一章节 [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#tensor-parallelism)。

b. **流水线并行（PP）**：通过节点间并行化降低内存占用并支持大规模训练。通过 PipeDream-Flush 调度/1F1B 调度以及交错式 1F1B 调度，减少朴素 PP 中的气泡。层在 PP 阶段之间均匀分布。例如，如果模型有 `24` 层，并且我们有 `4` 个 GPU 用于流水线并行，则每个 GPU 将拥有 `6` 层（24/4）。有关减少 PP 空闲时间的调度的更多详细信息，请参阅研究论文 [Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM](https://huggingface.co/papers/2104.04473) 以及博客文章的这一部分 [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#pipeline-parallelism)。

c. **序列并行（SP）**：在不增加任何通信开销的情况下降低内存占用。仅在启用 TP 时适用。它通过将 `all-reduce` 之后的操作替换为 `reduce-scatter`，并将 `no-op` 操作替换为 `all-gather`，从而避免在张量并行秩上保留相同的副本，进而减少所需的激活内存。由于 `all-reduce = reduce-scatter + all-gather`，这在不增加通信成本的前提下大幅节省了激活内存。简而言之，它沿序列维度对每个 Transformer 层的输出进行分片，例如，如果序列长度为 `1024` 且 TP 大小为 `4`，则每个 GPU 将为每个样本持有 `256` 个 token（1024/4）。这提高了训练时可支持的批大小。更多细节请参阅研究论文 [Reducing Activation Recomputation in Large Transformer Models](https://huggingface.co/papers/2205.05198)。

d. 通过分布式优化器实现**数据并行（DP）**：通过在 DP 进程间分片优化器状态和梯度来减少内存占用（与传统方法在数据并行进程间复制优化器状态不同）。例如，在使用 Adam 优化器进行混合精度训练时，每个参数占用 12 字节的内存。这些内存会均匀分布在 GPU 上，即如果有 4 个 GPU，每个参数将占用 3 字节（12/4）。更多详情请参阅研究论文 [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://huggingface.co/papers/1910.02054) 以及博客 [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#zero-data-parallelism) 的后续章节。

e. **专家并行（EP）** Megatron-LM 中的专家并行用于混合专家（Mixture-of-Experts, MoE）层。在这些层中，存在许多“专家”（小型前馈网络），但每个 token 仅激活其中少数几个。Megatron 并非将所有专家放置在每一块 GPU 上，而是将不同的专家分布到不同的 GPU 上——这就是专家并行。在训练过程中，token 会被路由到承载其选定专家的 GPU 上进行计算，然后传回，从而降低内存开销。对于大规模模型，它通常与张量/流水线并行结合使用。f. **全激活重计算**：通过智能的激活检查点技术，显著降低激活值的内存占用。它不存储那些占用大量内存但重计算速度很快的激活值，从而在内存与重计算之间取得极佳的平衡。例如，对于 GPT-3，该方法将激活值所需的内存减少了 70%，而重计算激活值带来的 FLOPs 开销仅为 2.7%。更多详情请参阅研究论文 [Reducing Activation Recomputation in Large Transformer Models](https://huggingface.co/papers/2205.05198)。

g. **Fused Kernels**：融合 Softmax、混合精度融合 Layer Norm，以及将线性层的梯度累积融合到权重梯度计算中。PyTorch JIT 编译的融合 GeLU 和融合 Bias+Dropout+Residual 加法。

h. **支持索引数据集**：用于大规模训练的高效二进制数据集格式。支持 `mmap`、`cached` 索引文件以及 `lazy` 加载器格式。

i. **检查点重塑与互操作性**：用于将具有可变张量并行和流水线并行规模的 Megatron-LM 检查点重塑为广受欢迎的 Transformers 分片检查点，因为它与 Accelerate Big Model Inference、Megatron-DeepSpeed Inference 等众多工具具有出色的兼容性。同时，也支持将 Transformers 分片检查点转换为具有可变张量并行和流水线并行规模的 Megatron-LM 检查点，以用于大规模训练。

## 先决条件 

您需要安装最新的 pytorch、cuda、nccl 和 NVIDIA [APEX](https://github.com/NVIDIA/apex#quick-start) 版本以及 nltk 库。有关更多详细信息，请参阅[文档](https://github.com/NVIDIA/Megatron-LM#setup)。另一种设置环境的方法是从 NGC 拉取一个 NVIDIA PyTorch 容器，该容器已预装所有必需的组件。

以下是设置 conda 环境的分步方法：

1. 创建虚拟环境
```
conda create --name ml
```

2. 假设机器已安装 CUDA 11.3，安装对应的 PyTorch GPU 版本
```
conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
```

3. 安装 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 ..
```

4. 安装 Megatron-LM

```
git clone https://github.com/NVIDIA/Megatron-LM.git
cd Megatron-LM
git checkout 9a1c0d05c992c8a241da384ab27dce2021bb56dd
you need to manually move gpt_builders.py to megatron/training and update
include = [
    "megatron.core", 
    "megatron.core.*",
    "megatron.training",
    "megatron.training.*",
    "megatron.legacy",
    "megatron.legacy.*",
]
in pyproject.toml file to unblock yourself from using Megatron
pip install --no-use-pep517 -e .
```

## 准备 Megaton-LM 检查点
如果您想要微调模型，请确保您已准备好 torch dist 格式的 checkpoint。如果您只能访问 huggingface 模型，请考虑将其转换为 Megatron 可接受的 torch dist 格式 checkpoint。一个示例是使用 slime 的脚本，以 GLM 模型为例：
```
source /your/path/to/slime/scripts/models/glm4.5-355B-A32B.sh
srun torchrun --nproc-per-node 8 \
   /your/path/to/slime/tools/convert_hf_to_torch_dist.py \
    ${MODEL_ARGS[@]} \
    --hf-checkpoint /your/path/to/huggingface/models/GLM4.5-355B-A32B \
    --save /your/path/to/megatron/models/GLM4.5-355B-A32B_torch_dist

```
转换完成后，请确保：1. 在 `/your/path/to/megatron/models/GLM4.5-355B-A32B_torch_dist` 下：将 `latest_checkpointed_iteration.txt` 的内容从 `release` 更改为 `0`，并将目录 `release` 重命名为 `iter_0000000`；2. 在配置中，确保 `megatron_lm_no_load_optim` 为 true，以便无需加载优化器状态。

## Accelerate Megatron-LM 插件

重要功能通过 `accelerate config` 命令直接支持。以下示例展示了使用 Megatron-LM 功能时对应的提问：

```bash
:~$ 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 预训练为例。要在官方 `run_clm_no_trainer.py` 中使用 Megatron-LM，所需的最小改动如下：

1. 由于 Megatron-LM 使用了其自身的 Optimizer 实现，因此需要使用与之兼容的相应 scheduler。
因此，目前仅支持 Megatron-LM 的调度器。用户需要创建 `accelerate.utils.MegatronLMDummyScheduler`。示例如下：

```python
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,
    )
```

2. 获取总批处理大小的详细信息时，现在需要考虑张量并行和流水线并行的规模。
下面展示了获取有效总批处理大小的示例：

```python
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
```

3. 在使用 Megatron-LM 时，损失值已经在数据并行组内进行了平均

```python
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)
```

4. 对于 Megatron-LM，我们需要使用 `accelerator.save_state` 来保存模型

```python
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
    )
```

就是这样！一切准备就绪 🚀。示例脚本位于 `accelerate/examples/by_feature/megatron_lm_gpt_pretraining.py` 路径下的 examples 文件夹中。让我们使用 4 块 A100-80GB GPU 来运行 `gpt-large` 模型架构。

```bash
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"
```

以下是输出日志中的一些重要摘录：

```bash
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 时自定义 Train Step 所需更改的示例。
您将实现 `accelerate.utils.AbstractTrainStep`，或继承其对应的子类 `accelerate.utils.GPTTrainStep`、`accelerate.utils.BertTrainStep` 或 `accelerate.utils.T5TrainStep`。

```python
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,
    }
```

2. 若要使用 Megatron-LM 数据集，还需要进行一些更改。这些数据集的数据加载器
仅在张量并行组的 rank 0 上可用。因此，在某些 rank 上 dataloader 将不可用，这需要调整训练循环。能够完成所有这些操作，体现了 Accelerate 的灵活性和可扩展性。所需的更改如下。

a. 对于 Megatron-LM 索引数据集，我们需要使用 `MegatronLMDummyDataLoader` 并向其传递所需的数据集参数，例如 `data_path`、`seq_length` 等。有关可用参数的列表，请参阅[此处](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/training/arguments.py)。
    
```python
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` 的比例分别获取训练、验证和测试数据加载器
    
```python
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 的设置类似，在使用 Megaton-LM 索引数据集时，用户必须提供 `max_train_steps`。这展示了 Accelerate 的灵活性和可扩展性。

```python
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 库中各自对应的模型目录下。
Currently, it is available for GPT model [checkpoint_reshaping_and_interoperability.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py)

2. 以下是一个将 Megatron-LM 检查点转换为通用 Transformers 分片检查点的示例。
```bash
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
```

3. 将 `tp_size=2`、`pp_size=2` 和 `dp_size=2` 的 transformers 检查点转换为 megatron。
```bash
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`，如下所示。
这些将在流水线的最后阶段可用。
```python
megatron_lm_plugin = MegatronLMPlugin(return_logits=True)
```

2. Megatron-LM GPT 模型的 `megatron_generate` 方法：这将使用 Tensor 和 Pipeline Parallelism 来完成
generations for a batch of inputs when using greedy with/without top_k/top_p sampling and for individual prompt inputs when using beam search decoding. Only a subset of features of transformers generate is supported. This will help in using large models via tensor and pipeline parallelism for generation (already does key-value caching and uses fused kernels by default). This requires data parallel size to be 1, sequence parallelism and activation checkpointing to be disabled. It also requires specifying path to tokenizer's vocab file and merges file. Below example shows how to configure and use `megatron_generate` method for Megatron-LM GPT model.
```python
# 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)
```

3. 使用 `megatron_generate` 方法对 Megatron-LM GPT 模型进行端到端示例可在
[megatron_gpt2_generation.py](https://github.com/pacman100/accelerate-megatron-test/blob/main/src/inference/megatron_gpt2_generation.py) 与配置文件 [megatron_lm_gpt_generate_config.yaml](https://github.com/pacman100/accelerate-megatron-test/blob/main/src/Configs/megatron_lm_gpt_generate_config.yaml)。包含 accelerate launch 命令的 bash 脚本位于 [megatron_lm_gpt_generate.sh](https://github.com/pacman100/accelerate-megatron-test/blob/main/megatron_lm_gpt_generate.sh)。该脚本的输出日志位于 [megatron_lm_gpt_generate.log](https://github.com/pacman100/accelerate-megatron-test/blob/main/output_logs/megatron_lm_gpt_generate.log)。

## 对 ROPE 和 ALiBi 位置嵌入以及多查询注意力机制的支持

1. 对于 ROPE/ALiBi 注意力机制，请按照下图所示，将 `position_embedding_type` 设置为 `("absolute" | "rotary" | "alibi")` 并传递给 `MegatronLMPlugin`。
```python
other_megatron_args = {"position_embedding_type": "alibi"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)
```

2. 对于 Multi-Query Attention，请按照下图所示，将 `attention_head_type` 设置为 `("multihead" | "multiquery")` 并传递给 `MegatronLMPlugin`。
```python
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)` 会返回在数据并行 rank 之间取平均的损失值。对于大多数使用 Megatron-LM 功能运行预训练任务的情况，这已经足够，你可以轻松地利用该损失值计算 `perplexity`。对于 GPT 模型，支持在返回损失值的同时返回 logits。这些 logits 不会在数据并行 rank 之间进行聚合。请使用 `accelerator.utils.gather_across_data_parallel_groups` 在数据并行 rank 之间聚合 logits。这些 logits 连同 labels 可用于计算各种性能指标。

3. 主进程是最后一个 rank，因为损失/logits 在流水线的最后一个阶段可用。
`accelerator.is_main_process` 和 `accelerator.is_local_main_process` 在使用 Megatron-LM 集成时，对最后一个 rank 返回 `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 时，流水线并行中的微批次
setting 与梯度累积同义。

7. 使用 Megatron-LM 时，请使用 `accelerator.save_state` 和 `accelerator.load_state` 来保存和加载检查点。

8. 以下是 Megatron-LM 模型架构到等效 transformers 模型架构的映射。
仅支持这些 transformers 模型架构。

a. Megatron-LM [BertModel](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/models/bert/bert_model.py)：config 中 model type 包含 `megatron-bert` 的 transformers 模型，例如 [MegatronBERT](https://huggingface.co/docs/transformers/model_doc/megatron-bert)
    
b. Megatron-LM [GPTModel](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/models/gpt/gpt_model.py)：配置中模型类型为 `gpt2` 的 transformers 模型，例如 [OpenAI GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2)
   
c. Megatron-LM [T5Model](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/models/T5/t5_model.py)：config 中 model type 包含 `t5` 的 transformers 模型，例如 [T5](https://huggingface.co/docs/transformers/model_doc/t5) 和 [MT5](https://huggingface.co/docs/transformers/model_doc/mt5)

