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.15.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 cho phép huấn luyện các mô hình ngôn ngữ transformer lớn ở quy mô lớn. Nó cung cấp các phương pháp song song hóa mô hình dựa trên tensor, pipeline và sequence hiệu quả để pre-training các mô hình ngôn ngữ dựa trên transformer như GPT (Chỉ Decoder), BERT (Chỉ Encoder) và T5 (Encoder-Decoder). Để biết thông tin chi tiết và cách thức hoạt động bên trong, vui lòng tham khảo repo trên github.

Những gì được tích hợp?

Accelerate tích hợp các tính năng sau của Megatron-LM để cho phép huấn luyện trước/huấn luyện lại quy mô lớn các mô hình BERT (Encoder), GPT (Decoder) hoặc T5 (Encoder và Decoder):

a. Tensor Parallelism (TP): Giảm dung lượng bộ nhớ mà không cần thêm quá nhiều giao tiếp giữa các rank trong cùng một node. Mỗi tensor được chia thành nhiều phần, mỗi phần nằm trên một GPU riêng biệt. Tại mỗi bước, cùng một mini-batch dữ liệu được xử lý độc lập và song song bởi mỗi phần, sau đó đồng bộ hóa trên tất cả các GPU (thao tác all-reduce). Trong một lớp transformer đơn giản, điều này dẫn đến 2 all-reduces trên đường truyền forward và 2 trên đường truyền backward. Để biết thêm chi tiết, vui lòng tham khảo bài nghiên cứu Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism và phần này của bài blog The Technology Behind BLOOM Training.

b. Pipeline Parallelism (PP): Giảm dung lượng bộ nhớ và cho phép huấn luyện quy mô lớn thông qua song song hóa giữa các node. Giảm bubble của PP đơn giản thông qua lịch PipeDream-Flush/1F1B và lịch Interleaved 1F1B. Các lớp được phân phối đều giữa các giai đoạn PP. Ví dụ, nếu một mô hình có 24 lớp và chúng ta có 4 GPU cho pipeline parallelism, mỗi GPU sẽ có 6 lớp (24/4). Để biết thêm chi tiết về các lịch để giảm thời gian nhàn rỗi của PP, vui lòng tham khảo bài nghiên cứu Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM và phần này của blogpost The Technology Behind BLOOM Training.

c. Sequence Parallelism (SP): Giảm dung lượng bộ nhớ mà không cần thêm bất kỳ giao tiếp nào. Chỉ áp dụng được khi sử dụng TP. Nó giảm bộ nhớ kích hoạt cần thiết bằng cách ngăn các bản sao giống nhau nằm trên các rank tensor parallel sau all-reduce bằng cách thay thế chúng bằng reduce-scatter và thao tác no-op sẽ được thay thế bằng all-gather. Vì all-reduce = reduce-scatter + all-gather, điều này tiết kiệm một lượng lớn bộ nhớ kích hoạt mà không phát sinh chi phí giao tiếp thêm. Nói một cách đơn giản, nó chia nhỏ đầu ra của mỗi lớp transformer dọc theo chiều sequence, ví dụ, nếu độ dài sequence là 1024 và kích thước TP là 4, mỗi GPU sẽ có 256 token (1024/4) cho mỗi mẫu. Điều này làm tăng kích thước batch có thể hỗ trợ cho việc huấn luyện. Để biết thêm chi tiết, vui lòng tham khảo bài nghiên cứu Reducing Activation Recomputation in Large Transformer Models.

d. Data Parallelism (DP) thông qua Distributed Optimizer: Giảm lượng bộ nhớ sử dụng bằng cách chia nhỏ trạng thái optimizer và gradient trên các rank DP (thay vì phương pháp truyền thống là nhân bản trạng thái optimizer trên các rank data parallel). Ví dụ, khi sử dụng optimizer Adam với huấn luyện mixed-precision, mỗi tham số chiếm 12 byte bộ nhớ. Phần này được phân bổ đều trên các GPU, tức là mỗi tham số sẽ chiếm 3 byte (12/4) nếu chúng ta có 4 GPU. Để biết thêm chi tiết, vui lòng tham khảo bài nghiên cứu ZeRO: Memory Optimizations Toward Training Trillion Parameter Models và phần tiếp theo của blog The Technology Behind BLOOM Training.

e. Expert Parallelism (EP) Expert parallelism trong Megatron-LM được sử dụng cho các lớp Mixture-of-Experts (MoE), nơi tồn tại nhiều “experts” (các mạng feed-forward nhỏ) nhưng chỉ một vài expert được kích hoạt cho mỗi token. Thay vì đặt tất cả các expert trên mỗi GPU, Megatron phân phối các expert khác nhau sang các GPU khác nhau—đây là expert parallelism. Trong quá trình huấn luyện, các token được định tuyến đến các GPU chứa các expert được chọn, được tính toán tại đó, sau đó được gửi trở lại, giúp giảm chi phí bộ nhớ. Phương pháp này thường được kết hợp với tensor/pipeline parallelism cho các mô hình quy mô lớn. f. Full Activation Recomputation: Giảm đáng kể dung lượng bộ nhớ của activations thông qua activation checkpointing thông minh. Nó không lưu trữ các activations chiếm nhiều bộ nhớ nhưng lại nhanh để tính toán lại, từ đó đạt được sự đánh đổi tuyệt vời giữa bộ nhớ và chi phí tính toán lại. Ví dụ, đối với GPT-3, điều này dẫn đến việc giảm 70% bộ nhớ cần thiết cho activations với chi phí chỉ là 2.7% FLOPs cho việc tính toán lại activations. Để biết thêm chi tiết, vui lòng tham khảo bài nghiên cứu Reducing Activation Recomputation in Large Transformer Models.

g. Fused Kernels: Fused Softmax, Mixed Precision Fused Layer Norm và Fused gradient accumulation cho phép tính toán weight gradient của linear layer. PyTorch JIT compiled Fused GeLU và Fused Bias+Dropout+Residual addition.

h. Hỗ trợ bộ dữ liệu có chỉ mục: Định dạng nhị phân hiệu quả cho các bộ dữ liệu phục vụ huấn luyện quy mô lớn. Hỗ trợ tệp chỉ mục mmap, cached và định dạng trình nạp lazy.

i. Định dạng lại checkpoint và khả năng tương tác: Tiện ích để định dạng lại các checkpoint của Megatron-LM có kích thước song song tensor và pipeline thay đổi thành các checkpoint phân mảnh của Transformers được yêu thích, vì nó có sự hỗ trợ tuyệt vời với nhiều công cụ như Accelerate Big Model Inference, Megatron-DeepSpeed Inference, v.v. Cũng có sẵn hỗ trợ để chuyển đổi các checkpoint phân mảnh của Transformers thành checkpoint Megatron-LM có kích thước song song tensor và pipeline thay đổi cho việc huấn luyện quy mô lớn.

Yêu cầu tiên quyết

Bạn cần cài đặt các bản phát hành mới nhất của pytorch, cuda, nccl và NVIDIA APEX cùng thư viện nltk. Xem tài liệu để biết thêm chi tiết. Một cách khác để thiết lập môi trường là kéo một NVIDIA PyTorch Container có sẵn tất cả các cài đặt cần thiết từ NGC.

Dưới đây là phương pháp từng bước để thiết lập môi trường conda:

  1. Tạo môi trường ảo
conda create --name ml
  1. Giả sử máy đã cài đặt CUDA 11.3, việc cài đặt phiên bản PyTorch GPU tương ứng
conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
  1. Cài đặt 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. Cài đặt 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 .

Chuẩn bị checkpoint Megaton-LM

Nếu bạn muốn tinh chỉnh một mô hình, hãy đảm bảo bạn đã có sẵn checkpoint ở định dạng torch dist. Nếu bạn chỉ có quyền truy cập vào mô hình huggingface, hãy cân nhắc chuyển đổi nó thành checkpoint ở định dạng torch dist được Megatron chấp nhận. Một ví dụ là sử dụng script của slime, lấy các mô hình GLM làm ví dụ:

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

Sau khi chuyển đổi, hãy đảm bảo: 1. trong /your/path/to/megatron/models/GLM4.5-355B-A32B_torch_dist: thay đổi nội dung của latest_checkpointed_iteration.txt từ release thành 0 và đổi tên thư mục release thành iter_0000000; 2: trong cấu hình, hãy đảm bảo megatron_lm_no_load_optim là true để không cần các trạng thái optimizer.

Tích hợp Megatron-LM của Accelerate

Các tính năng quan trọng được hỗ trợ trực tiếp thông qua lệnh accelerate config. Một ví dụ về các câu hỏi tương ứng khi sử dụng các tính năng của Megatron-LM được hiển thị bên dưới:

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

Cấu hình kết quả được hiển thị bên dưới:

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

Chúng ta sẽ lấy ví dụ về tiền huấn luyện GPT. Những thay đổi tối thiểu cần thiết đối với run_clm_no_trainer.py chính thức để sử dụng Megatron-LM như sau:

  1. Vì Megatron-LM sử dụng triển khai Optimizer riêng, cần dùng scheduler tương thích với nó. Do đó, chỉ có hỗ trợ scheduler của Megatron-LM. Người dùng cần tạo accelerate.utils.MegatronLMDummyScheduler. Ví dụ được đưa ra bên dưới:
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. Việc lấy chi tiết về kích thước lô (batch) tổng hiện cần phải tính đến kích thước song song tensor và pipeline. Ví dụ về việc lấy kích thước lô tổng hiệu dụng được hiển thị bên dưới:
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. Khi sử dụng Megatron-LM, các giá trị loss đã được trung bình hóa trên nhóm data parallel
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. Đối với Megatron-LM, chúng ta cần lưu mô hình bằng 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
    )

Xong rồi! Chúng ta đã sẵn sàng 🚀. Bạn có thể tìm script mẫu trong thư mục examples tại đường dẫn accelerate/examples/by_feature/megatron_lm_gpt_pretraining.py. Hãy chạy nó cho kiến trúc mô hình gpt-large sử dụng 4 GPU A100-80GB.

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"

Dưới đây là một số trích đoạn quan trọng từ nhật ký đầu ra:

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]

Có rất nhiều tùy chọn/tính năng khác mà bạn có thể thiết lập bằng cách sử dụng accelerate.utils.MegatronLMPlugin.

Các tính năng nâng cao để tận dụng việc viết bước huấn luyện tùy chỉnh và Bộ dữ liệu có chỉ mục của Megatron-LM

Để tận dụng nhiều tính năng hơn, vui lòng xem chi tiết bên dưới.

  1. Dưới đây là một ví dụ về các thay đổi cần thiết để tùy chỉnh Train Step khi sử dụng Megatron-LM. Bạn sẽ triển khai accelerate.utils.AbstractTrainStep hoặc kế thừa từ các lớp con tương ứng accelerate.utils.GPTTrainStep, accelerate.utils.BertTrainStep hoặc 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. Để sử dụng các bộ dữ liệu Megatron-LM, cần thực hiện thêm một vài thay đổi. Dataloader cho các bộ dữ liệu này chỉ khả dụng trên rank 0 của mỗi nhóm tensor parallel. Do đó, sẽ có những rank mà dataloader không khả dụng, điều này đòi hỏi phải điều chỉnh vòng lặp huấn luyện. Việc có thể thực hiện tất cả những điều này cho thấy Accelerate linh hoạt và có khả năng mở rộng đến mức nào. Các thay đổi cần thiết như sau.

a. Đối với các bộ dữ liệu có chỉ mục của Megatron-LM, chúng ta cần sử dụng MegatronLMDummyDataLoader và truyền các đối số bộ dữ liệu cần thiết vào đó, chẳng hạn như data_path, seq_length, v.v. Xem tại đây để biết danh sách các đối số khả dụng.

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 được lặp lại 3 lần để tạo ra các dataloader cho tập huấn luyện, kiểm tra và kiểm định, theo tỷ lệ của args.splits_string

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

c. Những thay đổi đối với vòng lặp huấn luyện và đánh giá vì dataloader chỉ khả dụng trên các rank tensor parallel 0 Do đó, chúng ta chỉ cần lặp lại nếu dataloader không phải là None, ngược lại thì cung cấp dict rỗng Như vậy, chúng ta lặp bằng vòng lặp while và thoát khi completed_steps bằng với args.max_train_steps. Điều này tương tự như cấu hình của Megatron-LM, trong đó người dùng phải cung cấp max_train_steps khi sử dụng các bộ dữ liệu có chỉ số của Megaton-LM. Điều này cho thấy Accelerate linh hoạt và có khả năng mở rộng đến mức nào.

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)

Công cụ để định hình lại điểm kiểm tra và tương tác

  1. Các script cho những mục này có sẵn trong thư viện Transformers dưới các model tương ứng. Hiện tại, tính năng này khả dụng cho model GPT checkpoint_reshaping_and_interoperability.py

  2. Dưới đây là một ví dụ về việc chuyển đổi checkpoint từ Megatron-LM sang checkpoint phân mảnh phổ quát của 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. Chuyển đổi checkpoint từ transformers sang megatron với tp_size=2, pp_size=2 và dp_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

Mô hình GPT của Megatron-LM hỗ trợ trả về logits và hàm megatron_generate để tạo văn bản

  1. Việc trả về logits yêu cầu đặt require_logits=True trong MegatronLMPlugin như minh họa bên dưới. Các giá trị này sẽ có sẵn ở giai đoạn cuối của pipeline.
megatron_lm_plugin = MegatronLMPlugin(return_logits=True)
  1. megatron_generate method for Megatron-LM GPT model: Phương thức này sẽ sử dụng Tensor và Pipeline Parallelism để hoàn thành việc tạo văn bản cho một lô (batch) các đầu vào khi sử dụng greedy có hoặc không có top_k/top_p sampling, và cho các đầu vào prompt riêng lẻ khi sử dụng beam search decoding. Chỉ một tập con các tính năng của transformers generate được hỗ trợ. Điều này sẽ giúp sử dụng các mô hình lớn thông qua tensor và pipeline parallelism cho việc tạo văn bản (đã thực hiện key-value caching và sử dụng fused kernels theo mặc định). Điều này yêu cầu data parallel size phải là 1, sequence parallelism và activation checkpointing phải bị vô hiệu hóa. Nó cũng yêu cầu chỉ định đường dẫn đến tệp vocab và tệp merges của tokenizer. Ví dụ bên dưới cho thấy cách cấu hình và sử dụng phương thức megatron_generate cho mô hình GPT của Megatron-LM.
# 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. Một ví dụ đầu-cuối về việc sử dụng phương thức megatron_generate cho mô hình GPT của Megatron-LM có sẵn tại megatron_gpt2_generation.py với tệp cấu hình megatron_lm_gpt_generate_config.yaml. Tệp bash chứa lệnh accelerate launch có sẵn tại megatron_lm_gpt_generate.sh. Nhật ký đầu ra của tệp này có sẵn tại megatron_lm_gpt_generate.log.

Hỗ trợ nhúng vị trí ROPE và ALiBi cùng với Multi-Query Attention

  1. Đối với chú ý ROPE/ALiBi, hãy truyền position_embedding_type với ("absolute" | "rotary" | "alibi") vào MegatronLMPlugin như minh họa bên dưới.
other_megatron_args = {"position_embedding_type": "alibi"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)
  1. Đối với Multi-Query Attention, hãy truyền attention_head_type với ("multihead" | "multiquery") vào MegatronLMPlugin như minh họa bên dưới.
other_megatron_args = {"attention_head_type": "multiquery"}
megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)

Lưu ý

  1. Hỗ trợ các mô hình GPT2, Megatron-BERT và T5 của Transformers. Điều này bao gồm các lớp mô hình chỉ có Decoder, chỉ có Encoder và Encoder-Decoder.

  2. Chỉ loss được trả về từ bước forward của model vì có sự tương tác khá phức tạp giữa pipeline, tensor và data parallelism diễn ra phía sau. Gọi model(**batch_data) sẽ trả về loss(es) được trung bình hóa trên các rank data parallel. Điều này phù hợp cho hầu hết các trường hợp trong đó các tác vụ pre-training được chạy bằng các tính năng của Megatron-LM và bạn có thể dễ dàng tính toán perplexity bằng loss. Đối với model GPT, việc trả về logits ngoài loss(es) cũng được hỗ trợ. Các logits này không được gom lại trên các rank data parallel. Hãy dùng accelerator.utils.gather_across_data_parallel_groups để gom logits trên các rank data parallel. Các logits này cùng với labels có thể được dùng để tính toán các chỉ số hiệu năng khác nhau.

  3. Quy trình chính là rank cuối cùng vì các loss/logits có sẵn ở giai đoạn cuối của pipeline. accelerator.is_main_process và accelerator.is_local_main_process trả về True cho rank cuối cùng khi sử dụng tích hợp Megatron-LM.

  4. Trong lời gọi accelerator.prepare, một mô hình Megatron-LM tương ứng với một mô hình Transformers nhất định sẽ được tạo ra với các trọng số ngẫu nhiên. Vui lòng sử dụng accelerator.load_state để nạp checkpoint Megatron-LM có các phân vùng TP, PP và DP khớp nhau.

  5. Hiện tại, tính năng định dạng lại checkpoint và hỗ trợ tương tác chỉ khả dụng cho GPT. Sắp tới, tính năng này sẽ được mở rộng cho BERT và T5.

  6. gradient_accumulation_steps phải bằng 1. Khi sử dụng Megatron-LM, micro batches trong pipeline parallelism có nghĩa tương đương với gradient accumulation.

  7. Khi sử dụng Megatron-LM, hãy dùng accelerator.save_state và accelerator.load_state để lưu và nạp checkpoint.

  8. Dưới đây là bảng ánh xạ từ kiến trúc mô hình Megatron-LM sang các kiến trúc mô hình transformers tương đương. Chỉ các kiến trúc mô hình transformers này được hỗ trợ.

a. Megatron-LM BertModel : các model transformers có megatron-bert trong model type của config, ví dụ: MegatronBERT

b. Megatron-LM GPTModel : các model transformers có gpt2 trong model type của config, ví dụ: OpenAI GPT2

c. Megatron-LM T5Model : các mô hình transformers có t5 trong model type của config, ví dụ: T5 và MT5

Update on GitHub