Debian Codegraph @

docs/source/usage_guides/megatron_lm.md

raw
1 <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4 the License. You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9 an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10 specific language governing permissions and limitations under the License.
11
12 ⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
13 rendered properly in your Markdown viewer.
14 -->
15
16
17 # Megatron-LM
18
19 [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) enables training large transformer language models at scale.
20 It provides efficient tensor, pipeline and sequence based model parallelism for pre-training transformer based
21 Language Models such as [GPT](https://huggingface.co/papers/2005.14165) (Decoder Only), [BERT](https://huggingface.co/papers/1810.04805) (Encoder Only) and [T5](https://huggingface.co/papers/1910.10683) (Encoder-Decoder).
22 For detailed information and how things work behind the scene please refer to the github [repo](https://github.com/NVIDIA/Megatron-LM).
23
24 ## What is integrated?
25
26 Accelerate integrates following feature of Megatron-LM to enable large scale pre-training/finetuning
27 of BERT (Encoder), GPT (Decoder) or T5 models (Encoder and Decoder):
28
29 a. **Tensor Parallelism (TP)**: Reduces memory footprint without much additional communication on intra-node ranks.
30 Each tensor is split into multiple chunks with each shard residing on separate GPU. At each step, the same mini-batch of data is processed
31 independently and in parallel by each shard followed by syncing across all GPUs (`all-reduce` operation).
32 In a simple transformer layer, this leads to 2 `all-reduces` in the forward path and 2 in the backward path.
33 For more details, please refer to the research paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using
34 Model Parallelism](https://huggingface.co/papers/1909.08053) and
35 this section of blogpost [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#tensor-parallelism).
36
37
38 b. **Pipeline Parallelism (PP)**: Reduces memory footprint and enables large scale training via inter-node parallelization.
39 Reduces the bubble of naive PP via PipeDream-Flush schedule/1F1B schedule and Interleaved 1F1B schedule.
40 Layers are distributed uniformly across PP stages. For example, if a model has `24` layers and we have `4` GPUs for
41 pipeline parallelism, each GPU will have `6` layers (24/4). For more details on schedules to reduce the idle time of PP,
42 please refer to the research paper [Efficient Large-Scale Language Model Training on GPU Clusters
43 Using Megatron-LM](https://huggingface.co/papers/2104.04473) and
44 this section of blogpost [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#pipeline-parallelism).
45
46 c. **Sequence Parallelism (SP)**: Reduces memory footprint without any additional communication. Only applicable when using TP.
47 It reduces activation memory required as it prevents the same copies to be on the tensor parallel ranks
48 post `all-reduce` by replacing them with `reduce-scatter` and `no-op` operation would be replaced by `all-gather`.
49 As `all-reduce = reduce-scatter + all-gather`, this saves a ton of activation memory at no added communication cost.
50 To put it simply, it shards the outputs of each transformer layer along sequence dimension, e.g.,
51 if the sequence length is `1024` and the TP size is `4`, each GPU will have `256` tokens (1024/4) for each sample.
52 This increases the batch size that can be supported for training. For more details, please refer to the research paper
53 [Reducing Activation Recomputation in Large Transformer Models](https://huggingface.co/papers/2205.05198).
54
55 d. **Data Parallelism (DP)** via Distributed Optimizer: Reduces the memory footprint by sharding optimizer states and gradients across DP ranks
56 (versus the traditional method of replicating the optimizer state across data parallel ranks).
57 For example, when using Adam optimizer with mixed-precision training, each parameter accounts for 12 bytes of memory.
58 This gets distributed equally across the GPUs, i.e., each parameter would account for 3 bytes (12/4) if we have 4 GPUs.
59 For more details, please refer to the research paper [ZeRO: Memory Optimizations Toward Training Trillion
60 Parameter Models](https://huggingface.co/papers/1910.02054) and following section of blog
61 [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#zero-data-parallelism).
62
63 e. **Expert Parallelism (EP)** Expert parallelism in Megatron-LM is used for Mixture-of-Experts (MoE) layers, where many “experts” (small feed-forward networks) exist but only a few are activated for each token. Instead of putting all experts on every GPU, Megatron distributes different experts across different GPUs—this is expert parallelism. During training, tokens are routed to the GPUs that host their selected experts, computed there, and then sent back, reducing memory cost. It often combines with tensor/pipeline parallelism for large-scale models.
64 f. **Full Activation Recomputation**: Reduces the memory footprint of activations significantly via smart activation checkpointing.
65 It doesn't store activations occupying large memory while being fast to recompute thereby achieving great tradeoff between memory and recomputation.
66 For example, for GPT-3, this leads to 70% reduction in required memory for activations at the expense of
67 only 2.7% FLOPs overhead for recomputation of activations. For more details, please refer to the research paper
68 [Reducing Activation Recomputation in Large Transformer Models](https://huggingface.co/papers/2205.05198).
69
70 g. **Fused Kernels**: Fused Softmax, Mixed Precision Fused Layer Norm and Fused gradient accumulation to weight gradient computation of linear layer.
71 PyTorch JIT compiled Fused GeLU and Fused Bias+Dropout+Residual addition.
72
73 h. **Support for Indexed datasets**: Efficient binary format of datasets for large scale training. Support for the `mmap`, `cached` index file and the `lazy` loader format.
74
75 i. **Checkpoint reshaping and interoperability**: Utility for reshaping Megatron-LM checkpoints of variable
76 tensor and pipeline parallel sizes to the beloved Transformers sharded checkpoints as it has great support with plethora of tools
77 such as Accelerate Big Model Inference, Megatron-DeepSpeed Inference etc.
78 Support is also available for converting Transformers sharded checkpoints to Megatron-LM checkpoint of variable tensor and pipeline parallel sizes
79 for large scale training.
80
81
82 ## Pre-Requisites
83
84 You will need to install the latest pytorch, cuda, nccl, and NVIDIA [APEX](https://github.com/NVIDIA/apex#quick-start) releases and the nltk library.
85 See [documentation](https://github.com/NVIDIA/Megatron-LM#setup) for more details.
86 Another way to setup the environment is to pull an NVIDIA PyTorch Container that comes with all the required installations from NGC.
87
88 Below is a step-by-step method to set up the conda environment:
89
90 1. Create a virtual environment
91 ```
92 conda create --name ml
93 ```
94
95 2. Assuming that the machine has CUDA 11.3 installed, installing the corresponding PyTorch GPU Version
96 ```
97 conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
98 ```
99
100 3. Install Nvidia APEX
101 ```
102 git clone https://github.com/NVIDIA/apex
103 cd apex
104 pip install -v --disable-pip-version-check --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./
105 cd ..
106 ```
107
108 4. Installing Megatron-LM
109
110 ```
111 git clone https://github.com/NVIDIA/Megatron-LM.git
112 cd Megatron-LM
113 git checkout 9a1c0d05c992c8a241da384ab27dce2021bb56dd
114 you need to manually move gpt_builders.py to megatron/training and update
115 include = [
116 "megatron.core",
117 "megatron.core.*",
118 "megatron.training",
119 "megatron.training.*",
120 "megatron.legacy",
121 "megatron.legacy.*",
122 ]
123 in pyproject.toml file to unblock yourself from using Megatron
124 pip install --no-use-pep517 -e .
125 ```
126
127 ## Prepare Megaton-LM checkpoint
128 If you want to fine-tune a model, make sure you have a torch dist format checkpoint ready. If you only have access to the huggingface model, please consider converting it to a torch dist format checkpoint acceptable to Megatron. One example can be using slime's script, take GLM models as an example:
129 ```
130 source /your/path/to/slime/scripts/models/glm4.5-355B-A32B.sh
131 srun torchrun --nproc-per-node 8 \
132 /your/path/to/slime/tools/convert_hf_to_torch_dist.py \
133 ${MODEL_ARGS[@]} \
134 --hf-checkpoint /your/path/to/huggingface/models/GLM4.5-355B-A32B \
135 --save /your/path/to/megatron/models/GLM4.5-355B-A32B_torch_dist
136
137 ```
138 After the conversion, make sure: 1. under `/your/path/to/megatron/models/GLM4.5-355B-A32B_torch_dist`: change the `latest_checkpointed_iteration.txt`'s content from `release` to `0` and rename the directory `release` to `iter_0000000`; 2: in the config, make sure `megatron_lm_no_load_optim` to be true so that no optimizer states are needed.
139
140 ## Accelerate Megatron-LM Plugin
141
142 Important features are directly supported via the `accelerate config` command.
143 An example of the corresponding questions for using Megatron-LM features is shown below:
144
145 ```bash
146 :~$ accelerate config --config_file "megatron_gpt_config.yaml"
147 In which compute environment are you running? ([0] This machine, [1] AWS (Amazon SageMaker)): 0
148 Which type of machine are you using? ([0] No distributed training, [1] multi-CPU, [2] multi-GPU, [3] TPU): 2
149 How many different machines will you use (use more than 1 for multi-node training)? [1]:
150 Do you want to use DeepSpeed? [yes/NO]:
151 Do you want to use FullyShardedDataParallel? [yes/NO]:
152 Do you want to use Megatron-LM ? [yes/NO]: yes
153 What is the Tensor Parallelism degree/size? [1]:2
154 Do you want to enable Sequence Parallelism? [YES/no]:
155 What is the Pipeline Parallelism degree/size? [1]:2
156 What is the number of micro-batches? [1]:2
157 Do you want to enable selective activation recomputation? [YES/no]:
158 Do you want to use distributed optimizer which shards optimizer state and gradients across data parallel ranks? [YES/no]:
159 What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]:
160 How many GPU(s) should be used for distributed training? [1]:4
161 Do you wish to use FP16 or BF16 (mixed precision)? [NO/fp16/bf16]: bf16
162 ```
163
164 The resulting config is shown below:
165
166 ```
167 ~$ cat megatron_gpt_config.yaml
168 compute_environment: LOCAL_MACHINE
169 deepspeed_config: {}
170 distributed_type: MEGATRON_LM
171 downcast_bf16: 'no'
172 fsdp_config: {}
173 machine_rank: 0
174 main_process_ip: null
175 main_process_port: null
176 main_training_function: main
177 megatron_lm_config:
178 megatron_lm_gradient_clipping: 1.0
179 megatron_lm_num_micro_batches: 2
180 megatron_lm_pp_degree: 2
181 megatron_lm_recompute_activations: true
182 megatron_lm_sequence_parallelism: true
183 megatron_lm_tp_degree: 2
184 megatron_lm_use_distributed_optimizer: true
185 mixed_precision: bf16
186 num_machines: 1
187 num_processes: 4
188 rdzv_backend: static
189 same_network: true
190 use_cpu: false
191 ```
192
193 We will take the example of GPT pre-training. The minimal changes required to the official `run_clm_no_trainer.py`
194 to use Megatron-LM are as follows:
195
196 1. As Megatron-LM uses its own implementation of Optimizer, the corresponding scheduler compatible with it needs to be used.
197 As such, support for only the Megatron-LM's scheduler is present. User will need to create `accelerate.utils.MegatronLMDummyScheduler`.
198 Example is given below:
199
200 ```python
201 from accelerate.utils import MegatronLMDummyScheduler
202
203 if accelerator.distributed_type == DistributedType.MEGATRON_LM:
204 lr_scheduler = MegatronLMDummyScheduler(
205 optimizer=optimizer,
206 total_num_steps=args.max_train_steps,
207 warmup_num_steps=args.num_warmup_steps,
208 )
209 else:
210 lr_scheduler = get_scheduler(
211 name=args.lr_scheduler_type,
212 optimizer=optimizer,
213 num_warmup_steps=args.num_warmup_steps * args.gradient_accumulation_steps,
214 num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
215 )
216 ```
217
218 2. Getting the details of the total batch size now needs to be cognization of tensor and pipeline parallel sizes.
219 Example of getting the effective total batch size is shown below:
220
221 ```python
222 if accelerator.distributed_type == DistributedType.MEGATRON_LM:
223 total_batch_size = accelerator.state.megatron_lm_plugin.global_batch_size
224 else:
225 total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
226 ```
227
228 3. When using Megatron-LM, the losses are already averaged across the data parallel group
229
230 ```python
231 if accelerator.distributed_type == DistributedType.MEGATRON_LM:
232 losses.append(loss)
233 else:
234 losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size)))
235
236 if accelerator.distributed_type == DistributedType.MEGATRON_LM:
237 losses = torch.tensor(losses)
238 else:
239 losses = torch.cat(losses)
240 ```
241
242 4. For Megatron-LM, we need to save the model using `accelerator.save_state`
243
244 ```python
245 if accelerator.distributed_type == DistributedType.MEGATRON_LM:
246 accelerator.save_state(args.output_dir)
247 else:
248 unwrapped_model = accelerator.unwrap_model(model)
249 unwrapped_model.save_pretrained(
250 args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
251 )
252 ```
253
254 That's it! We are good to go 🚀. Please find the example script in the examples folder at the path `accelerate/examples/by_feature/megatron_lm_gpt_pretraining.py`.
255 Let's run it for `gpt-large` model architecture using 4 A100-80GB GPUs.
256
257 ```bash
258 accelerate launch --config_file megatron_gpt_config.yaml \
259 examples/by_feature/megatron_lm_gpt_pretraining.py \
260 --config_name "gpt2-large" \
261 --tokenizer_name "gpt2-large" \
262 --dataset_name wikitext \
263 --dataset_config_name wikitext-2-raw-v1 \
264 --block_size 1024 \
265 --learning_rate 5e-5 \
266 --per_device_train_batch_size 24 \
267 --per_device_eval_batch_size 24 \
268 --num_train_epochs 5 \
269 --with_tracking \
270 --report_to "wandb" \
271 --output_dir "awesome_model"
272 ```
273
274 Below are some important excerpts from the output logs:
275
276 ```bash
277 Loading extension module fused_dense_cuda...
278 >>> done with compiling and loading fused kernels. Compilation time: 3.569 seconds
279 > padded vocab (size: 50257) with 175 dummy tokens (new size: 50432)
280 Building gpt model in the pre-training mode.
281 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.
282 Preparing dataloader
283 Preparing dataloader
284 Preparing model
285 > number of parameters on (tensor, pipeline) model parallel rank (1, 0): 210753280
286 > number of parameters on (tensor, pipeline) model parallel rank (1, 1): 209445120
287 > number of parameters on (tensor, pipeline) model parallel rank (0, 0): 210753280
288 > number of parameters on (tensor, pipeline) model parallel rank (0, 1): 209445120
289 Preparing optimizer
290 Preparing scheduler
291 > learning rate decay style: linear
292 10/10/2022 22:57:22 - INFO - __main__ - ***** Running training *****
293 10/10/2022 22:57:22 - INFO - __main__ - Num examples = 2318
294 10/10/2022 22:57:22 - INFO - __main__ - Num Epochs = 5
295 10/10/2022 22:57:22 - INFO - __main__ - Instantaneous batch size per device = 24
296 10/10/2022 22:57:22 - INFO - __main__ - Total train batch size (w. parallel, distributed & accumulation) = 48
297 10/10/2022 22:57:22 - INFO - __main__ - Gradient Accumulation steps = 1
298 10/10/2022 22:57:22 - INFO - __main__ - Total optimization steps = 245
299 20%|████████████▍ | 49/245 [01:04<04:09, 1.27s/it]
300 10/10/2022 22:58:29 - INFO - __main__ - epoch 0: perplexity: 1222.1594275215962 eval_loss: 7.10837459564209
301 40%|████████████████████████▊ | 98/245 [02:10<03:07, 1.28s/it]
302 10/10/2022 22:59:35 - INFO - __main__ - epoch 1: perplexity: 894.5236583794557 eval_loss: 6.796291351318359
303 60%|████████████████████████████████████▌ | 147/245 [03:16<02:05, 1.28s/it]
304 10/10/2022 23:00:40 - INFO - __main__ - epoch 2: perplexity: 702.8458788508042 eval_loss: 6.555137634277344
305 80%|████████████████████████████████████████████████▊ | 196/245 [04:22<01:02, 1.28s/it]
306 10/10/2022 23:01:46 - INFO - __main__ - epoch 3: perplexity: 600.3220028695281 eval_loss: 6.39746618270874
307 100%|█████████████████████████████████████████████████████████████| 245/245 [05:27<00:00, 1.28s/it]
308 ```
309
310 There are a large number of other options/features that one can set using `accelerate.utils.MegatronLMPlugin`.
311
312 ## Advanced features to leverage writing custom train step and Megatron-LM Indexed Datasets
313
314 For leveraging more features, please go through below details.
315
316 1. Below is an example of changes required to customize the Train Step while using Megatron-LM.
317 You will implement the `accelerate.utils.AbstractTrainStep` or inherit from their corresponding children
318 `accelerate.utils.GPTTrainStep`, `accelerate.utils.BertTrainStep` or `accelerate.utils.T5TrainStep`.
319
320 ```python
321 from accelerate.utils import MegatronLMDummyScheduler, GPTTrainStep, avg_losses_across_data_parallel_group
322
323
324 # Custom loss function for the Megatron model
325 class GPTTrainStepWithCustomLoss(GPTTrainStep):
326 def __init__(self, megatron_args, **kwargs):
327 super().__init__(megatron_args)
328 self.kwargs = kwargs
329
330 def get_loss_func(self):
331 def loss_func(inputs, loss_mask, output_tensor):
332 batch_size, seq_length = output_tensor.shape
333 losses = output_tensor.float()
334 loss_mask = loss_mask.view(-1).float()
335 loss = losses.view(-1) * loss_mask
336
337 # Resize and average loss per sample
338 loss_per_sample = loss.view(batch_size, seq_length).sum(axis=1)
339 loss_mask_per_sample = loss_mask.view(batch_size, seq_length).sum(axis=1)
340 loss_per_sample = loss_per_sample / loss_mask_per_sample
341
342 # Calculate and scale weighting
343 weights = torch.stack([(inputs == kt).float() for kt in self.kwargs["keytoken_ids"]]).sum(axis=[0, 2])
344 weights = 1.0 + self.kwargs["alpha"] * weights
345 # Calculate weighted average
346 weighted_loss = (loss_per_sample * weights).mean()
347
348 # Reduce loss across data parallel groups
349 averaged_loss = avg_losses_across_data_parallel_group([weighted_loss])
350
351 return weighted_loss, {"lm loss": averaged_loss[0]}
352
353 return loss_func
354
355 def get_forward_step_func(self):
356 def forward_step(data_iterator, model):
357 """Forward step."""
358 # Get the batch.
359 tokens, labels, loss_mask, attention_mask, position_ids = self.get_batch(data_iterator)
360 output_tensor = model(tokens, position_ids, attention_mask, labels=labels)
361
362 return output_tensor, partial(self.loss_func, tokens, loss_mask)
363
364 return forward_step
365
366
367 def main():
368 # Custom loss function for the Megatron model
369 keytoken_ids = []
370 keywords = ["plt", "pd", "sk", "fit", "predict", " plt", " pd", " sk", " fit", " predict"]
371 for keyword in keywords:
372 ids = tokenizer([keyword]).input_ids[0]
373 if len(ids) == 1:
374 keytoken_ids.append(ids[0])
375 accelerator.print(f"Keytoken ids: {keytoken_ids}")
376 accelerator.state.megatron_lm_plugin.custom_train_step_class = GPTTrainStepWithCustomLoss
377 accelerator.state.megatron_lm_plugin.custom_train_step_kwargs = {
378 "keytoken_ids": keytoken_ids,
379 "alpha": 0.25,
380 }
381 ```
382
383 2. For using the Megatron-LM datasets, a few more changes are required. Dataloaders for these datasets
384 are available only on rank 0 of each tensor parallel group. As such, there are rank where dataloader won't be
385 available and this requires tweaks to the training loop. Being able to do all this shows how
386 flexible and extensible Accelerate is. The changes required are as follows.
387
388 a. For Megatron-LM indexed datasets, we need to use `MegatronLMDummyDataLoader`
389 and pass the required dataset args to it such as `data_path`, `seq_length` etc.
390 See [here](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/arguments.py#L804) for the list of available args.
391
392 ```python
393 from accelerate.utils import MegatronLMDummyDataLoader
394
395 megatron_dataloader_config = {
396 "data_path": args.data_path,
397 "splits_string": args.splits_string,
398 "seq_length": args.block_size,
399 "micro_batch_size": args.per_device_train_batch_size,
400 }
401 megatron_dataloader = MegatronLMDummyDataLoader(**megatron_dataloader_config)
402 accelerator.state.megatron_lm_plugin.megatron_dataset_flag = True
403 ```
404
405 b. `megatron_dataloader` is repeated 3 times to get training, validation and test dataloaders
406 as per the `args.splits_string` proportions
407
408 ```python
409 model, optimizer, lr_scheduler, train_dataloader, eval_dataloader, _ = accelerator.prepare(
410 model, optimizer, lr_scheduler, megatron_dataloader, megatron_dataloader, megatron_dataloader
411 )
412 ```
413
414 c. Changes to training and evaluation loops as dataloader is only available on tensor parallel ranks 0
415 So, we need to iterate only if the dataloader isn't `None` else provide empty dict
416 As such, we loop using `while` loop and break when `completed_steps` is equal to `args.max_train_steps`
417 This is similar to the Megatron-LM setup wherein user has to provide `max_train_steps` when using Megaton-LM indexed datasets.
418 This displays how flexible and extensible Accelerate is.
419
420 ```python
421 while completed_steps < args.max_train_steps:
422 model.train()
423 batch = next(train_dataloader) if train_dataloader is not None else {}
424 outputs = model(**batch)
425 loss = outputs.loss
426 ...
427
428 if completed_steps % eval_interval == 0:
429 eval_completed_steps = 0
430 losses = []
431 while eval_completed_steps < eval_iters:
432 model.eval()
433 with torch.no_grad():
434 batch = next(eval_dataloader) if eval_dataloader is not None else {}
435 outputs = model(**batch)
436 ```
437
438
439 ## Utility for Checkpoint reshaping and interoperability
440
441 1. The scripts for these are present in Transformers library under respective models.
442 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)
443
444 2. Below is an example of conversion of checkpoint from Megatron-LM to universal Transformers sharded checkpoint.
445 ```bash
446 python checkpoint_reshaping_and_interoperability.py \
447 --convert_checkpoint_from_megatron_to_transformers \
448 --load_path "gpt/iter_0005000" \
449 --save_path "gpt/trfs_checkpoint" \
450 --max_shard_size "200MB" \
451 --tokenizer_name "gpt2" \
452 --print-checkpoint-structure
453 ```
454
455 3. Conversion of checkpoint from transformers to megatron with `tp_size=2`, `pp_size=2` and `dp_size=2`.
456 ```bash
457 python checkpoint_utils/megatgron_gpt2/checkpoint_reshaping_and_interoperability.py \
458 --load_path "gpt/trfs_checkpoint" \
459 --save_path "gpt/megatron_lm_checkpoint" \
460 --target_tensor_model_parallel_size 2 \
461 --target_pipeline_model_parallel_size 2 \
462 --target_data_parallel_size 2 \
463 --target_params_dtype "bf16" \
464 --make_vocab_size_divisible_by 128 \
465 --use_distributed_optimizer \
466 --print-checkpoint-structure
467 ```
468
469 ## Megatron-LM GPT models support returning logits and `megatron_generate` function for text generation
470
471 1. Returning logits require setting `require_logits=True` in MegatronLMPlugin as shown below.
472 These would be available in the last stage of pipeline.
473 ```python
474 megatron_lm_plugin = MegatronLMPlugin(return_logits=True)
475 ```
476
477 2. `megatron_generate` method for Megatron-LM GPT model: This will use Tensor and Pipeline Parallelism to complete
478 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.
479 Only a subset of features of transformers generate is supported. This will help in using large models via tensor and pipeline parallelism
480 for generation (already does key-value caching and uses fused kernels by default).
481 This requires data parallel size to be 1, sequence parallelism and activation checkpointing to be disabled.
482 It also requires specifying path to tokenizer's vocab file and merges file.
483 Below example shows how to configure and use `megatron_generate` method for Megatron-LM GPT model.
484 ```python
485 # specifying tokenizer's vocab and merges file
486 vocab_file = os.path.join(args.resume_from_checkpoint, "vocab.json")
487 merge_file = os.path.join(args.resume_from_checkpoint, "merges.txt")
488 other_megatron_args = {"vocab_file": vocab_file, "merge_file": merge_file}
489 megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)
490
491 # inference using `megatron_generate` functionality
492 tokenizer.pad_token = tokenizer.eos_token
493 max_new_tokens = 64
494 batch_texts = [
495 "Are you human?",
496 "The purpose of life is",
497 "The arsenal was constructed at the request of",
498 "How are you doing these days?",
499 ]
500 batch_encodings = tokenizer(batch_texts, return_tensors="pt", padding=True)
501
502 # top-p sampling
503 generated_tokens = model.megatron_generate(
504 batch_encodings["input_ids"],
505 batch_encodings["attention_mask"],
506 max_new_tokens=max_new_tokens,
507 top_p=0.8,
508 top_p_decay=0.5,
509 temperature=0.9,
510 )
511 decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
512 accelerator.print(decoded_preds)
513
514 # top-k sampling
515 generated_tokens = model.megatron_generate(
516 batch_encodings["input_ids"],
517 batch_encodings["attention_mask"],
518 max_new_tokens=max_new_tokens,
519 top_k=50,
520 temperature=0.9,
521 )
522 decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
523 accelerator.print(decoded_preds)
524
525 # adding `bos` token at the start
526 generated_tokens = model.megatron_generate(
527 batch_encodings["input_ids"], batch_encodings["attention_mask"], max_new_tokens=max_new_tokens, add_BOS=True
528 )
529 decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
530 accelerator.print(decoded_preds)
531
532 # beam search => only takes single prompt
533 batch_texts = ["The purpose of life is"]
534 batch_encodings = tokenizer(batch_texts, return_tensors="pt", padding=True)
535 generated_tokens = model.megatron_generate(
536 batch_encodings["input_ids"],
537 batch_encodings["attention_mask"],
538 max_new_tokens=max_new_tokens,
539 num_beams=20,
540 length_penalty=1.5,
541 )
542 decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy())
543 accelerator.print(decoded_preds)
544 ```
545
546 3. An end-to-end example of using `megatron_generate` method for Megatron-LM GPT model is available at
547 [megatron_gpt2_generation.py](https://github.com/pacman100/accelerate-megatron-test/blob/main/src/inference/megatron_gpt2_generation.py) with
548 config file [megatron_lm_gpt_generate_config.yaml](https://github.com/pacman100/accelerate-megatron-test/blob/main/src/Configs/megatron_lm_gpt_generate_config.yaml).
549 The bash script with accelerate launch command is available at [megatron_lm_gpt_generate.sh](https://github.com/pacman100/accelerate-megatron-test/blob/main/megatron_lm_gpt_generate.sh).
550 The output logs of the script are available at [megatron_lm_gpt_generate.log](https://github.com/pacman100/accelerate-megatron-test/blob/main/output_logs/megatron_lm_gpt_generate.log).
551
552 ## Support for ROPE and ALiBi Positional embeddings and Multi-Query Attention
553
554 1. For ROPE/ALiBi attention, pass `position_embedding_type` with `("absolute" | "rotary" | "alibi")` to `MegatronLMPlugin` as shown below.
555 ```python
556 other_megatron_args = {"position_embedding_type": "alibi"}
557 megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)
558 ```
559
560 2. For Multi-Query Attention, pass `attention_head_type` with `("multihead" | "multiquery")` to `MegatronLMPlugin` as shown below.
561 ```python
562 other_megatron_args = {"attention_head_type": "multiquery"}
563 megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args)
564 ```
565
566 ## Caveats
567
568 1. Supports Transformers GPT2, Megatron-BERT and T5 models.
569 This covers Decoder only, Encode only and Encoder-Decoder model classes.
570
571 2. Only loss is returned from model forward pass as
572 there is quite complex interplay of pipeline, tensor and data parallelism behind the scenes.
573 The `model(**batch_data)` call return loss(es) averaged across the data parallel ranks.
574 This is fine for most cases wherein pre-training jobs are run using Megatron-LM features and
575 you can easily compute the `perplexity` using the loss.
576 For GPT model, returning logits in addition to loss(es) is supported.
577 These logits aren't gathered across data parallel ranks. Use `accelerator.utils.gather_across_data_parallel_groups`
578 to gather logits across data parallel ranks. These logits along with labels can be used for computing various
579 performance metrics.
580
581 3. The main process is the last rank as the losses/logits are available in the last stage of pipeline.
582 `accelerator.is_main_process` and `accelerator.is_local_main_process` return `True` for last rank when using
583 Megatron-LM integration.
584
585 4. In `accelerator.prepare` call, a Megatron-LM model corresponding to a given Transformers model is created
586 with random weights. Please use `accelerator.load_state` to load the Megatron-LM checkpoint with matching TP, PP and DP partitions.
587
588 5. Currently, checkpoint reshaping and interoperability support is only available for GPT.
589 Soon it will be extended to BERT and T5.
590
591 6. `gradient_accumulation_steps` needs to be 1. When using Megatron-LM, micro batches in pipeline parallelism
592 setting is synonymous with gradient accumulation.
593
594 7. When using Megatron-LM, use `accelerator.save_state` and `accelerator.load_state` for saving and loading checkpoints.
595
596 8. Below are the mapping from Megatron-LM model architectures to the equivalent transformers model architectures.
597 Only these transformers model architectures are supported.
598
599 a. Megatron-LM [BertModel](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/bert_model.py) :
600 transformers models with `megatron-bert` in config's model type, e.g.,
601 [MegatronBERT](https://huggingface.co/docs/transformers/model_doc/megatron-bert)
602
603 b. Megatron-LM [GPTModel](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py) :
604 transformers models with `gpt2` in config's model type, e.g.,
605 [OpenAI GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2)
606
607 c. Megatron-LM [T5Model](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/t5_model.py) :
608 transformers models with `t5` in config's model type, e.g.,
609 [T5](https://huggingface.co/docs/transformers/model_doc/t5) and
610 [MT5](https://huggingface.co/docs/transformers/model_doc/mt5)