Accelerate 0.24.0文档 四:Megatron-LM

参考《Megatron-LM》

文章目录

    • 一、Megatron-LM集成简介
    • 二、环境配置
        • 设置conda环境的步骤:
    • 二、Accelerate Megatron-LM Plugin
    • 三、自定义训练过程
    • 四、检查点转换
    • 五、文本生成
    • 六、支持ROPE 、 ALiBi和Multi-Query Attention
    • 七、注意事项

一、Megatron-LM集成简介

在这里插入图片描述

在大规模语言模型训练中,Accelerate通过整合Megatron-LM的特性实现了以下功能:

  1. 张量并行(TP):降低内存占用,减少节点内的通信量。每个张量被分割成多个部分,每个部分位于不同的GPU上。在每个步骤中,相同的小批量数据由每个部分独立并行处理,然后在所有GPU间进行同步(all-reduce操作)。在简单的Transformer层中,这导致前向路径有2次all-reduce操作,后向路径也有2次。详情请参阅研究论文Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism和🤗博客文章中的The Technology Behind BLOOM Training部分。

  2. 管道并行(PP):通过管道并行降低内存占用并实现大规模训练。采用PipeDream-Flush调度/1F1B调度和交错的1F1B调度来减少朴素管道并行的空闲时间。层被均匀分布到不同的管道并行阶段。例如,如果一个模型有24层,而我们有4个GPU进行管道并行,则每个GPU将有6层(24/4)。了解如何减少管道并行空闲时间的详细信息,请参阅研究论文Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM和🤗博客文章中的The Technology Behind BLOOM Training部分。

  3. 序列并行(SP):在使用TP时降低内存占用,无需额外通信。只适用于TP。它通过在序列维度上对每个transformer层的输出进行分片来减少激活内存需求。例如,如果序列长度为1024,TP大小为4,每个GPU将为每个样本拥有256个标记(1024/4)。这提高了训练所支持的批量大小。了解更多详情,请参阅研究论文Reducing Activation Recomputation in Large Transformer Models。

  4. **数据并行(DP)**通过分布式优化器:通过在DP排名之间分片优化器状态和梯度来降低内存占用。例如,使用Adam优化器进行混合精度训练时,每个参数占用12字节的内存。这会均等地分布到各个GPU,即如果有4个GPU,每个参数将占用3字节(12/4)。详情请参阅研究论文ZeRO: Memory Optimizations Toward Training Trillion Parameter Models和🤗博客文章中的The Technology Behind BLOOM Training部分。

  5. 选择性激活重新计算:通过智能激活检查点技术显著减少激活内存占用。它快速重新计算激活,不存储占用大量内存的激活,从而在内存和重新计算之间取得了很好的折衷。例如,对于GPT-3,这将导致激活所需内存减少70%,而重新计算激活仅增加2.7%的FLOPs开销。了解更多详情,请参阅研究论文Reducing Activation Recomputation in Large Transformer Models。

  6. 融合内核:包括融合Softmax、混合精度融合层归一化以及线性层权重梯度计算的融合梯度累积。此外,还有PyTorch JIT编译的融合GeLU和融合偏置+Dropout+残差添加。

  7. 支持索引数据集:为大规模训练提供了高效的二进制数据集格式。支持mmapcached索引文件以及lazy加载格式。

  8. 检查点重塑和互操作性:为了更好地与多种工具(如🤗 Accelerate Big Model Inference、Megatron-DeepSpeed Inference等)兼容,提供了将Megatron-LM检查点的可变张量和管道并行大小重塑为🤗 Transformers分片检查点的实用工具。同时也支持将🤗 Transformers分片检查点转换为Megatron-LM检查点的功能,以便进行大规模训练。

二、环境配置

  在开始之前,你需要安装最新版本的PyTorch、CUDA、NCCL以及NVIDIA APEX发行版,以及nltk库。你可以参考文档获取更多详情。另一种设置环境的方法是使用NGC提供的NVIDIA PyTorch容器,它包含所有必需的安装。

设置conda环境的步骤:
  1. 创建一个虚拟环境

  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

    pip install git+https://github.com/huggingface/Megatron-LM.git
    

二、Accelerate Megatron-LM Plugin

  在《Accelerate 0.24.0文档 二:DeepSpeed集成》中介绍过,启用deepspeed功能时可通过运行accelerate config,以问答的形式完成deepspeed的配置。启用Megatron-LM时也可以直接通过accelerate config命令来完成相关配置,以下是执行此命令时的示例问题:

:~$ 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 pralellel 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

之后会得到如下配置文件(yaml):

~$ 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

  下面是使用官方的 megatron_lm_gpt_pretraining.py脚本进行最小化修改,以使用Megatron-LM进行GPT预训练的说明。修改的要点包括:

  1. 优化器和调度器的使用: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,
        )
    
  2. 总的批量大小:现在需要考虑张量和管道并行大小来获取有效的总批量大小。

    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时,损失值已经在数据并行组内进行了平均。

    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 进行模型保存。

    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
        )
    
  5. 开始训练:下面是使用 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,以适配Megatron-LM的特定要求和功能。

    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 Dataloader:在处理Megatron-LM数据集时,数据加载器仅在张量并行组的一个特定GPU(即rank 0)上可用,在其他GPU上,数据加载器不可用。针对这种情况,需要进行一些调整:

    • 需要使用 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
      
    • 获取数据加载器: 数据加载器需要在张量并行组的rank 0上获取。为了在训练、验证和测试过程中使用不同的数据加载器,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
      )
      
    • . 处理数据加载器可用性: 在训练和评估循环中,需要考虑数据加载器在其他GPU上不可用的情况。因此,在迭代过程中,必须确保仅在数据加载器不为空时进行迭代(即仅在rank 0上有数据加载器时才执行训练或评估),否则需要提供一个空的字典作为占位符。为了实现这一点,使用了一个while循环,在达到指定的训练步数 args.max_train_steps 时结束循环。
      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)
      

  这种调整确保了在处理Megatron-LM数据集时,训练和评估循环能够正确地运行,并在必要时适应数据加载器在部分GPU上不可用的情况。这也展示了 🤗 Accelerate 在适应不同情况下的灵活性和可扩展性。

四、检查点转换

  Megatron-LM使用模型并行(model parallel)、流水线并行(pipeline parallel)和数据并行(data parallel)来支持分布式训练。而🤗Transformers使用基于参数分片(sharding)的方法。两者检查点格式并不兼容。

  使用transformers库的checkpoint_reshaping_and_interoperability.py脚本,将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

  使用 tp_size=2 、 pp_size=2 和 dp_size=2 将检查点从通用Transformers 转换到Megatron-LM:

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模型的megatron_generate方法可进行高效的文本生成。首先设置require_logits=True,可以让Megatron-LM的GPT模型返回输出层的logits,以供后续生成所用。

megatron_lm_plugin = MegatronLMPlugin(return_logits=True)

  Megatron-LM提供了megatron_generate方法专门用于GPT模型的生成,它利用了张量并行和管道并行来为一批输入完成生成。主要包括贪心采样(top-k、top-p)的批量生成,以及束搜索解码的单样本生成。

  该方法的优点在于可以利用张量并行和管道并行来进行生成,已经默认使用了键值缓存和融合内核(fused kernels)。但是,使用这个方法需要将数据并行大小设置为1,禁用序列并行性和激活检查点,并且需要指定分词器的词汇文件和合并文件。以下是配置示例:

# 定义了分词器的词汇文件和合并文件的路径
vocab_file = os.path.join(args.resume_from_checkpoint, "vocab.json")
merge_file = os.path.join(args.resume_from_checkpoint, "merges.txt")
# 创建MegatronLMPlugin实例,同时传入了额外的Megatron参数,这些参数包括分词器的词汇文件和合并文件。
other_megatron_args = {"vocab_file": vocab_file, "merge_file": merge_file}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)

# i通过 model.megatron_generate 方法进行了不同方式的文本生成
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 采样
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 采样
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)

# 在输入文本前加入bos标记
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,
)

# 生成的token被解码为文本,并通过 tokenizer.batch_decode 方法转换为可读的文本形式。
decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
accelerator.print(decoded_preds)
  1. Top-p采样

    • 使用了 top_p 参数进行文本生成,这是一种基于概率的采样方法。在每个位置,模型将根据概率动态地选择概率大于给定阈值 top_p 的token作为下一个token的候选,直到生成指定数量的token(max_new_tokens)。top_p 的值为0.8,表示每次选择token时保留概率大于0.8的候选token。此外,还有一个 top_p_decay 参数,用于在生成过程中逐步降低 top_p 的值。
  2. Top-k采样

    • 使用了 top_k 参数进行文本生成,这是另一种基于概率的采样方法。在每个位置,模型将在概率最高的 top_k 个token中进行选择作为下一个token的候选,直到生成指定数量的token(max_new_tokens)。这种方法不考虑token的概率大小,只根据排名选择概率最高的token。

  通常来说,top-p sampling可以产生更多样而新颖的文本,而top-k sampling计算简单高效,但生成内容的多样性较差,需根据实际场景需求选择使用。

  束搜索是遍历多种可能输出序列,同时保留topk个可能序列。它能更全面搜索输出空间,找到更佳解。但由于需要追踪多条序列,计算更复杂,所以一般只用于单样本。

  最后,megatron_gpt2_generation.py 提供了使用egatron_generate 方法的端到端示例,其中包含配置文件 megatron_lm_gpt_generate_config.yaml,还有启动脚本megatron_lm_gpt_generate.sh 及其输出日志megatron_lm_gpt_generate.log。

六、支持ROPE 、 ALiBi和Multi-Query Attention

对于 ROPE/ALiBi 注意力,可设置 position_embedding_type为"absolute" 、“rotary” 或"alibi":

other_megatron_args = {"position_embedding_type": "alibi"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)

对于Multi-Query Attention,可设置attention_head_type 为"multihead" 或 “multiquery”:

other_megatron_args = {"attention_head_type": "multiquery"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)

七、注意事项

这段文字主要介绍了使用Megatron-LM集成时🤗Transformers的一些使用限制和注意事项:

  1. 目前只支持GPT2、Megatron-BERT和T5这三类模型结构,涵盖了decoder-only、encoder-only和encoder-decoder三种情况。

  2. 模型forward时只返回loss,不直接返回logit,这是因为管道、张量和数据并行之间存在相当复杂的相互作用。这些损失是在数据并行排名中进行了平均。对于大多数情况,特别是在使用Megatron-LM特性运行预训练任务时,可以使用损失来轻松计算困惑度。对于GPT模型,除了损失外,还支持返回logits。这些logits并未在数据并行排名中被收集,可以使用 accelerator.utils.gather_across_data_parallel_groups 来收集跨数据并行排名的logits,然后与标签一起用于计算各种性能指标。

  3. 主进程为最后一个流水线阶段rank,is_main_process等接口按此判断。

  4. 在 accelerator.prepare 调用中,会创建一个与给定Transformers模型对应的Megatron-LM模型,具有随机权重。需要使用 accelerator.load_state 来加载具有匹配TP、PP和DP分区的Megatron-LM检查点。

  5. gradient_accumulation_steps需要为1。Megatron中的micro batch类似累积梯度。

  6. 保存和加载检查点用save_state和load_state接口。

  7. 支持Megatron和Transformers三种模型的对应关系,而其他 🤗 transformers 的模型架构则不受支持

    • Megatron-LM BertModel 对应于 🤗 transformers 中具有 megatron-bert 模型类型的模型,如 MegatronBERT。
    • Megatron-LM GPTModel 对应于 🤗 transformers 中具有 gpt2 模型类型的模型,如 OpenAI GPT2。
    • Megatron-LM T5Model 对应于 🤗 transformers 中具有 t5 模型类型的模型,如 T5 和 MT5。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/156074.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

SystemVerilog学习(8)——包的使用

目录 一、包的定义 二、导出包的内容 1、可以通过域的索引符::号直接引用 2、可以指定索引一些需要的包中定义的类型到指定的容器中 3、通过通配符*来将包中所有的类别导入到指定容器中 三、包的使用 在进行本文的学习之前&#xff0c;首先需要对SV中类相关的内容有充分的认识…

mount /dev/mapper/centos-root on sysroot failed处理

今天发现centos7重启开不进去系统 通过查看日志主要告警如下 修复挂载目录 xfs_repair /dev/mapper/centos-root不行加-L参数 xfs_repair -L /dev/mapper/centos-root重启 reboot

2023年中国开式冷却塔应用现状及行业市场规模前景分析[图]

开式塔是目前应用最广、类型最多的一种冷却系统。循环水移走工艺介质或换热设备所散发的热量后成为热水&#xff0c;热水进入冷却塔后和空气直接接触&#xff0c;大部分热水得到冷却后&#xff0c;再循环使用。开式冷却塔又可以分为逆流式冷却塔和横流式冷却塔&#xff0c;按照…

基于Vue+SpringBoot的海南旅游景点推荐系统 开源项目

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 用户端2.2 管理员端 三、系统展示四、核心代码4.1 随机景点推荐4.2 景点评价4.3 协同推荐算法4.4 网站登录4.5 查询景点美食 五、免责说明 一、摘要 1.1 项目介绍 基于VueSpringBootMySQL的海南旅游推荐系统&#xff…

【Linux】一

本文使用的是云服务器来获取Linux环境 (使用虚拟机同样可以学习使用命令), 并且介绍了常用的Linux 命令. 获取Linux环境 使用xshell连接到云服务器 1.新建会话 输入主机号(云服务器的外网ip) 2.输入用户名/密码 centos的用户名:root 密码就是在后台设置的 3.成功进入 ~描…

01ctfer 文件上传

01ctfer 文件上传 启动靶场 访问该地址 代码审计 <?php header("Content-Type:text/html; charsetutf-8"); // 每5分钟会清除一次目录下上传的文件 require_once(pclzip.lib.php);if(!$_FILES){echo <!DOCTYPE html> <html lang"zh">…

【Linux】Linux进程间通信(二)

​ ​&#x1f4dd;个人主页&#xff1a;Sherry的成长之路 &#x1f3e0;学习社区&#xff1a;Sherry的成长之路&#xff08;个人社区&#xff09; &#x1f4d6;专栏链接&#xff1a;Linux &#x1f3af;长路漫漫浩浩&#xff0c;万事皆有期待 上一篇博客&#xff1a;【Linux】…

VUE指令、computed计算属性和watch 侦听器(附带详细案例)

文章目录 前言一、指令补充1. 指令修饰符2. v-bind对于样式操作的增强 - class3. 案例 - 京东秒杀 tab 导航高亮4. v-bind对于样式操作的增强 - style5. v-model应用于其他表单元素 二、computed计算属性1. 基础语法2. 计算属性 vS method 方法3. 完整写法4. 成绩案例 三、watc…

android PopupWindow设置

记录一个小功能&#xff0c;使用场景&#xff0c;列表项点击弹出 如图&#xff1a; java类代码&#xff1a; public class PopupUtil extends PopupWindow {private Activity context;private View view;private ListView listView;private TextView m_tv_reminderm, m_tv_Wa…

4.1 Windows驱动开发:内核中进程与句柄互转

在内核开发中&#xff0c;经常需要进行进程和句柄之间的互相转换。进程通常由一个唯一的进程标识符&#xff08;PID&#xff09;来标识&#xff0c;而句柄是指对内核对象的引用。在Windows内核中&#xff0c;EProcess结构表示一个进程&#xff0c;而HANDLE是一个句柄。 为了实…

Java集合List报错,java.lang.UnsupportedOperationException

目录 一、点击Arrays.asList源码&#xff0c;一探究竟二、习惯了Arrays.asList&#xff0c;就是想用.add()添加元素&#xff0c;怎么办&#xff1f;三、又有一个同事&#xff0c;是这样写的四、重新点击Arrays.asList源码&#xff0c;一探究竟五、全是坑&#xff0c;怎么办&…

muduo源码剖析之TcpServer服务端

简介 TcpServer拥有Acceptor类&#xff0c;新连接到达时new TcpConnection后续客户端和TcpConnection类交互。TcpServer管理连接和启动线程池&#xff0c;用Acceptor接受连接。 服务端封装 - muduo的server端维护了多个tcpconnection 注意TcpServer本身不带Channel&#xff0…

element-plus使用el-date-picker组件时,如何禁止用户选择当前时间之后的日时分秒

element-plus使用el-date-picker组件时&#xff0c;如何禁止用户选择当前时间之后的日时分秒 例&#xff1a; 当前时间为2023-11-15 14.24&#xff0c;不能选择这之后的时分秒。&#xff08;禁止用户选择2023-11-15 14.28&#xff09; <el-date-pickerv-model"form.s…

腾讯混元大模型与GPT3.5代码能力对比

今日&#xff0c;别的事情不干&#xff0c;来使用一下"腾讯混元大模型"。对比一下"GPT3.5"&#xff0c;看看效果。据说"腾讯混元大模型"代码方面是强项&#xff0c;特意申请了一个来体验一波。 ✨本章仅以Python为主题&#xff0c;展开体验。最后…

解决Jira导出csv最大限度是1000的问题

JIRA为了防止过多影响性能&#xff0c; 设置了导出CSV的上线为1000&#xff0c;影响了搜索结果导出以及RestAPI。 可以通过以下配置参数修改此限制&#xff1a; 通过JIRA管理界面的"高级设置 “设置以下参数 系统管理 > 系统 > 一般设置>高级设置找到 jira.sea…

如何将图片转为excel或word?(客户端)

演示软件&#xff1a;金鸣表格文字识别大师3.6.1&#xff08;新版本界面可能会略有不同&#xff09; 第一部分 将图片转为excel或文表混合的word 一般的软件要将图片转为可编辑的excel&#xff0c;都需要待识别的图片要有明显清晰的表格线&#xff0c;但我们程序现已克服了这…

vue-组件生命周期+网络请求

​&#x1f308;个人主页&#xff1a;前端青山 &#x1f525;系列专栏&#xff1a;Vue篇 &#x1f516;人终将被年少不可得之物困其一生 依旧青山,本期给大家带来vue篇专栏内容:vue-组件生命周期网络请求 目录 组件生命周期 1. Vue的生命周期 2. Vue 子组件和父组件执行顺序…

消息通讯-MQTT WebHookSpringBoot案例

一、EMQX WebHook介绍 1、EMQX WebHook 是由 emqx_web_hook (opens new window)插件提供的将EMQX中的钩子事件通知到某个Web服务的功能。 2、WebHook 的内部实现是基于钩子&#xff0c;借助 Webhook 可以完成设备在线、上下线记录&#xff0c;订阅与消息存储、消息送达确认等诸…

【开源】基于Vue和SpringBoot的固始鹅块销售系统

项目编号&#xff1a; S 060 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S060&#xff0c;文末获取源码。} 项目编号&#xff1a;S060&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 数据中心模块2.2 鹅块类型模块2.3 固…

绕过类安全问题分析方法

什么是绕过 逻辑漏洞是指程序设计中逻辑不严密&#xff0c;使攻击者能篡改、绕过或中断程序&#xff0c;令其偏离开发人员预期的执行。 常见表现形式 1、接口&#xff08;功能类&#xff09;绕过&#xff1a;即接口或功能中通过某参数&#xff0c;绕过程序校验 2、流程类绕…