Accelerate documentation

Megatron-LM

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v1.16.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Megatron-LM

Megatron-LM은 대규모로 대형 transformer 언어 모델을 학습할 수 있도록 합니다. GPT (Decoder Only), BERT (Encoder Only) 및 T5 (Encoder-Decoder)와 같은 transformer 기반 언어 모델의 사전 학습을 위한 효율적인 tensor, pipeline 및 sequence 기반 모델 병렬화를 제공합니다. 자세한 정보와 내부 동작 원리는 github repo를 참고하세요.

무엇이 통합되었나요?

Accelerate는 BERT(Encoder), GPT(Decoder) 또는 T5 모델(Encoder 및 Decoder)의 대규모 사전 학습/파인튜닝을 가능하게 하기 위해 Megatron-LM의 다음 기능을 통합합니다:

a. Tensor Parallelism (TP): 노드 내 랭크 간 추가 통신을 크게 늘리지 않으면서 메모리 사용량을 줄입니다. 각 텐서는 여러 청크로 분할되며, 각 샤드는 별도의 GPU에 배치됩니다. 각 단계에서 동일한 미니배치 데이터가 각 샤드에 의해 독립적이고 병렬적으로 처리된 후, 모든 GPU 간에 동기화(all-reduce 연산)됩니다. 단순한 트랜스포머 레이어의 경우, 이는 포워드 경로에서 2개의 all-reduces와 백워드 경로에서 2개의 all-reduces를 유발합니다. 자세한 내용은 연구 논문 Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism 및 블로그 포스트의 해당 섹션 The Technology Behind BLOOM Training을 참조하십시오.

b. Pipeline Parallelism (PP): 메모리 사용량을 줄이고 노드 간 병렬화를 통해 대규모 학습을 가능하게 합니다. PipeDream-Flush schedule/1F1B schedule 및 Interleaved 1F1B schedule를 통해 naive PP의 버블을 줄입니다. 레이어는 PP 스테이지에 걸쳐 균일하게 분배됩니다. 예를 들어, 모델이 24개의 레이어를 가지고 있고 파이프라인 병렬화를 위해 4개의 GPU를 사용하는 경우, 각 GPU에는 6개의 레이어(24/4)가 할당됩니다. PP의 유휴 시간을 줄이는 스케줄에 대한 자세한 내용은 연구 논문 Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM 및 블로그 포스트의 해당 섹션 The Technology Behind BLOOM Training을 참고하십시오.

c. Sequence Parallelism (SP): 추가 통신 없이 메모리 사용량을 줄입니다. TP를 사용하는 경우에만 적용됩니다. all-reduce 이후 동일한 사본이 tensor parallel rank에 존재하는 것을 방지하여 필요한 activation memory를 줄입니다. 이를 위해 reduce-scatter로 대체하고, no-op 연산은 all-gather로 대체됩니다. all-reduce = reduce-scatter + all-gather이므로, 추가 통신 비용 없이 activation memory를 대폭 절약할 수 있습니다. 간단히 말해, 각 transformer layer의 출력을 sequence 차원별로 쉐이딩합니다. 예를 들어, sequence length가 1024이고 TP size가 4인 경우, 각 GPU는 샘플당 256개의 토큰(1024/4)을 가집니다. 이로 인해 학습에 사용할 수 있는 배치 크기가 증가합니다. 자세한 내용은 연구 논문 Reducing Activation Recomputation in Large Transformer Models을 참고하세요.

d. Distributed Optimizer를 통한 Data Parallelism (DP): DP rank에 걸쳐 옵티마이저 상태와 그래디언트를 샤딩하여 메모리 사용량을 줄입니다(데이터 병렬 rank에 걸쳐 옵티마이저 상태를 복제하는 기존 방식과 대비). 예를 들어, 혼합 정밀도 학습에서 Adam 옵티마이저를 사용할 경우 각 파라미터는 12바이트의 메모리를 차지합니다. 이는 GPU에 걸쳐 균등하게 분배되므로, 4개의 GPU를 사용하는 경우 각 파라미터는 3바이트(12/4)를 차지하게 됩니다. 자세한 내용은 연구 논문 ZeRO: Memory Optimizations Toward Training Trillion Parameter Models 및 블로그 The Technology Behind BLOOM Training의 다음 섹션을 참고하세요.

e. Expert Parallelism (EP) Megatron-LM의 expert parallelism은 Mixture-of-Experts(MoE) 레이어에 사용됩니다. MoE 레이어에는 많은 수의 “experts”(작은 feed-forward network)가 존재하지만, 각 토큰마다 소수의 expert만 활성화됩니다. 모든 expert를 모든 GPU에 배치하는 대신, Megatron은 서로 다른 expert를 서로 다른 GPU에 분배합니다. 이것이 expert parallelism입니다. 학습 중에 토큰은 선택된 expert를 호스팅하는 GPU로 라우팅되고, 해당 GPU에서 계산된 후 다시 전송되어 메모리 비용을 줄입니다. 대규모 모델의 경우 tensor/pipeline parallelism과 함께 사용되는 경우가 많습니다. f. Full Activation Recomputation: 스마트한 activation checkpointing을 통해 activation의 메모리 사용량을 크게 줄입니다. 재계산이 빠르면서 메모리를 많이 차지하는 activation을 저장하지 않음으로써 메모리와 재계산 사이의 훌륭한 트레이드오프를 달성합니다. 예를 들어, GPT-3의 경우 activation 재계산에 2.7%의 FLOPs 오버헤드만 추가하는 비용으로 activation에 필요한 메모리를 70% 줄일 수 있습니다. 자세한 내용은 연구 논문 Reducing Activation Recomputation in Large Transformer Models을 참고하세요.

g. Fused Kernels: Fused Softmax, Mixed Precision Fused Layer Norm, 그리고 linear layer의 weight gradient computation에 Fused gradient accumulation. PyTorch JIT compiled Fused GeLU와 Fused Bias+Dropout+Residual addition.

h. 인덱스된 데이터셋 지원: 대규모 학습을 위한 데이터셋의 효율적인 바이너리 형식. mmap, cached 인덱스 파일 및 lazy 로더 형식 지원.

i. Checkpoint reshaping and interoperability: 가변 텐서 및 파이프라인 병렬 크기의 Megatron-LM 체크포인트를 Accelerate Big Model Inference, Megatron-DeepSpeed Inference 등 다양한 도구와 뛰어난 호환성을 제공하는 Transformers의 분할(sharded) 체크포인트로 리셰이프하는 유틸리티입니다. 대규모 학습을 위해 가변 텐서 및 파이프라인 병렬 크기의 Megatron-LM 체크포인트로 Transformers의 분할 체크포인트를 변환하는 지원도 제공됩니다.

사전 요구 사항

최신 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 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 체크포인트 준비

모델을 fine-tune하려면 torch dist 형식의 checkpoint가 준비되어 있는지 확인하세요. huggingface 모델만 접근할 수 있는 경우, Megatron이 허용하는 torch dist 형식의 checkpoint로 변환하는 것을 고려해 보세요. 예를 들어, GLM 모델을 대상으로 slime의 스크립트를 사용할 수 있습니다:

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 기능을 사용할 때의 예시 질문은 다음과 같습니다:

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

생성된 config는 다음과 같습니다:

~$ 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 구현을 사용하므로, 이에 호환되는 스케줄러를 사용해야 합니다. 따라서 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
    )

이상으로 준비가 끝났습니다 🚀. 예제 스크립트는 accelerate/examples/by_feature/megatron_lm_gpt_pretraining.py 경로에 있는 examples 폴더에서 확인하실 수 있습니다. 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을 사용하여 설정할 수 있는 다른 옵션/기능이 많이 있습니다.

커스텀 train step 작성 및 Megatron-LM Indexed Datasets 활용을 위한 고급 기능

더 많은 기능을 활용하려면 아래 세부 내용을 확인해 주세요.

  1. 아래는 Megatron-LM을 사용하면서 Train Step을 커스터마이징하기 위해 필요한 변경 사항의 예시입니다. accelerate.utils.AbstractTrainStep을 구현하거나, 해당 하위 클래스인 accelerate.utils.GPTTrainStep, accelerate.utils.BertTrainStep 또는 accelerate.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 데이터셋을 사용하려면 몇 가지 추가 변경이 필요합니다. 이러한 데이터셋의 Dataloader는 각 tensor parallel group의 rank 0에서만 사용할 수 있습니다. 따라서 Dataloader를 사용할 수 없는 rank가 존재하며, 이는 training loop에 대한 조정을 요구합니다. 이러한 모든 작업을 수행할 수 있다는 사실은 Accelerate가 얼마나 유연하고 확장 가능한지를 보여줍니다. 필요한 변경 사항은 다음과 같습니다.

a. Megatron-LM 인덱스 데이터셋의 경우 MegatronLMDummyDataLoader를 사용해야 하며, data_path, seq_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는 args.splits_string의 비율에 따라 학습, 검증 및 테스트 dataloader를 얻기 위해 3회 반복됩니다

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

c. dataloader가 tensor parallel rank 0에서만 사용 가능하므로 학습 및 평가 루프에 대한 변경 사항 따라서 dataloader가 None이 아닌 경우에만 반복하고, 그렇지 않으면 빈 dict를 제공해야 합니다. 이처럼 while 루프를 사용하여 반복하고, completed_steps가 args.max_train_steps와 같을 때 중단합니다. 이는 Megatron-LM 설정과 유사하며, Megaton-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)

Checkpoint 리셰이핑 및 상호 운용성을 위한 유틸리티

  1. 이러한 스크립트는 Transformers 라이브러리의 해당 모델 아래에 있습니다. 현재 GPT 모델의 checkpoint_reshaping_and_interoperability.py에 사용할 수 있습니다.

  2. …

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. tp_size=2, pp_size=2, dp_size=2 설정으로 transformers에서 megatron으로의 체크포인트 변환.
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를 설정해야 합니다. 이 값들은 파이프라인의 마지막 단계에서 사용할 수 있습니다.
megatron_lm_plugin = MegatronLMPlugin(return_logits=True)
  1. Megatron-LM GPT 모델의 megatron_generate 메서드: greedy 방식에서 top_k/top_p 샘플링을 사용하거나 사용하지 않는 경우, 배치 입력에 대한 생성을 완료하기 위해 Tensor 및 Pipeline Parallelism을 사용합니다. beam search 디코딩을 사용하는 경우 개별 프롬프트 입력에 대해 적용됩니다. transformers generate의 일부 기능만 지원됩니다. 이를 통해 tensor 및 pipeline parallelism을 사용하여 대형 모델로 생성 작업을 수행하는 데 도움이 됩니다(기본적으로 key-value 캐싱을 수행하고 fused kernels를 사용합니다). 이 메서드를 사용하려면 data parallel size가 1이어야 하며, sequence parallelism과 activation checkpointing은 비활성화되어 있어야 합니다. 또한 tokenizer의 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-LM GPT 모델에서 megatron_generate 메서드를 사용하는端到端 예제는 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 위치 임베딩과 Multi-Query Attention 지원

  1. ROPE/ALiBi 어텐션의 경우, 아래에 표시된 대로 MegatronLMPlugin에 position_embedding_type를 ("absolute" | "rotary" | "alibi")으로 전달합니다.
other_megatron_args = {"position_embedding_type": "alibi"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)
  1. Multi-Query Attention의 경우, 아래에 표시된 대로 MegatronLMPlugin에 attention_head_type을 ("multihead" | "multiquery")으로 전달합니다.
other_megatron_args = {"attention_head_type": "multiquery"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)

주의 사항

  1. Transformers의 GPT2, Megatron-BERT 및 T5 모델을 지원합니다. 이것은 Decoder only, Encode only 및 Encoder-Decoder 모델 클래스를 포함합니다.

  2. 모델의 forward pass에서는 파이프라인, 텐서 및 데이터 병렬성 간의 복잡한 상호작용이 백그라운드에서 일어나기 때문에 loss만 반환됩니다. model(**batch_data) 호출은 데이터 병렬 랭크 전체에 걸쳐 평균화된 loss를 반환합니다. Megatron-LM 기능을 사용하여 사전 학습 작업을 실행하는 대부분의 경우 이는 문제가 없으며, loss를 사용하여 perplexity를 쉽게 계산할 수 있습니다. GPT 모델의 경우 loss 외에 logits를 반환하는 것도 지원됩니다. 이 logits는 데이터 병렬 랭크 전체에 걸쳐 수집되지 않습니다. 데이터 병렬 랭크 전체에 걸쳐 logits를 수집하려면 accelerator.utils.gather_across_data_parallel_groups를 사용하세요. 이 logits와 labels를 사용하여 다양한 성능 지표를 계산할 수 있습니다.

  3. 손실/로짓이 파이프라인의 마지막 단계에서 사용 가능하므로 메인 프로세스는 마지막 랭크입니다. Megatron-LM 통합을 사용할 때 accelerator.is_main_process와 accelerator.is_local_main_process는 마지막 랭크에 대해 True를 반환합니다.

  4. accelerator.prepare 호출 시, 주어진 Transformers 모델에 해당하는 Megatron-LM 모델이 무작위 가중치로 생성됩니다. 일치하는 TP, PP 및 DP 파티션을 가진 Megatron-LM 체크포인트를 로드하려면 accelerator.load_state를 사용하세요.

  5. 현재 체크포인트 리셰이핑 및 상호 운용성 지원은 GPT에만 사용할 수 있습니다. 곧 BERT와 T5로 확장될 예정입니다.

  6. gradient_accumulation_steps는 1이어야 합니다. Megatron-LM을 사용하는 경우, 파이프라인 병렬성 설정의 micro batch는 gradient accumulation과 동의어입니다.

  7. Megatron-LM을 사용할 때는 accelerator.save_state와 accelerator.load_state를 사용하여 체크포인트를 저장하고 로드합니다.

  8. 다음은 Megatron-LM 모델 아키텍처에서 transformers 모델 아키텍처로의 매핑입니다. 이 transformers 모델 아키텍처만 지원됩니다.

a. Megatron-LM BertModel: config의 model type에 megatron-bert가 포함된 transformers 모델, 예: MegatronBERT

b. Megatron-LM GPTModel: config의 model type에 gpt2가 포함된 transformers 모델, 예: OpenAI GPT2

c. Megatron-LM T5Model: config의 model type에 t5가 포함된 transformers 모델, 예: T5, MT5

Update on GitHub