Upload folder using huggingface_hub (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- third_party/BindWeave/Megatron-LM/tests/unit_tests/models/test_t5_model.pyAdded+85
- third_party/BindWeave/Megatron-LM/tests/unit_tests/pipeline_parallel/__init__.pyAdded
- third_party/BindWeave/Megatron-LM/tests/unit_tests/pipeline_parallel/test_schedules.pyAdded+212
- third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/__init__.pyAdded
- third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_cross_entropy.pyAdded+14
- third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_data.pyAdded+21
- third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_initialization.pyAdded+97
- third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_layers.pyAdded+54
- third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_mappings.pyAdded+135
- third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_random.pyAdded+44
- third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_tensor_parallel_utils.pyAdded+43
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_basic.pyAdded+3
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_imports.pyAdded+157
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_local_multi_tensor_fns.pyAdded+36
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_num_microbatches_calculator.pyAdded+128
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_optimizer.pyAdded+66
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_parallel_state.pyAdded+468
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_training.pyAdded+43
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_utilities.pyAdded+82
- third_party/BindWeave/Megatron-LM/tests/unit_tests/test_utils.pyAdded+183
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/__init__.pyAdded
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/__init__.pyAdded
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_a2a_token_dispatcher.pyAdded+84
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_aux_loss.pyAdded+97
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_grouped_mlp.pyAdded+358
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_routers.pyAdded+91
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_sequential_mlp.pyAdded+61
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_token_dispatcher.pyAdded+290
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_attention.pyAdded+111
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_attention_packed_seq.pyAdded+131
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_core_attention.pyAdded+64
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_mlp.pyAdded+58
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_module.pyAdded+98
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_retro_attention.pyAdded+207
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_rope.pyAdded+52
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_spec_customization.pyAdded+243
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_transformer_block.pyAdded+107
- third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_transformer_layer.pyAdded+106
- third_party/BindWeave/Megatron-LM/tools/autoformat.shAdded+21
- third_party/BindWeave/Megatron-LM/tools/bert_embedding/__init__.pyAdded+3
- third_party/BindWeave/Megatron-LM/tools/bert_embedding/dataset.pyAdded+55
- third_party/BindWeave/Megatron-LM/tools/bert_embedding/embed.pyAdded+278
- third_party/BindWeave/Megatron-LM/tools/bert_embedding/external_libs.pyAdded+14
- third_party/BindWeave/Megatron-LM/tools/bert_embedding/huggingface.pyAdded+126
- third_party/BindWeave/Megatron-LM/tools/checkpoint/convert.pyAdded+154
- third_party/BindWeave/Megatron-LM/tools/checkpoint/hybrid_conversion.pyAdded+398
- third_party/BindWeave/Megatron-LM/tools/checkpoint/loader_llama_mistral.pyAdded+667
- third_party/BindWeave/Megatron-LM/tools/checkpoint/loader_mcore.pyAdded+383
- third_party/BindWeave/Megatron-LM/tools/checkpoint/loader_megatron.pyAdded+371
- third_party/BindWeave/Megatron-LM/tools/checkpoint/loader_mixtral_hf.pyAdded+335
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.models.T5.t5_model import T5Modelfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.models.T5.t5_spec import (get_t5_encoder_with_transformer_engine_block_spec, get_t5_decoder_with_transformer_engine_block_spec, get_t5_encoder_with_local_block_spec, get_t5_decoder_with_local_block_spec)
class TestT5Model:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) transformer_config = TransformerConfig(num_layers=12, hidden_size=768, num_attention_heads=12, kv_channels=64, ffn_hidden_size=3072, use_cpu_initialization=True) en_block_spec = get_t5_encoder_with_transformer_engine_block_spec(12) de_block_spec = get_t5_decoder_with_transformer_engine_block_spec(12) self.t5_model = T5Model(config=transformer_config, transformer_encoder_layer_spec=en_block_spec, transformer_decoder_layer_spec=de_block_spec, vocab_size=29184, max_sequence_length=4)
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): assert isinstance(self.t5_model, T5Model)
assert self.t5_model.max_sequence_length == 4
def test_set_input_tensor(self): config: TransformerConfig = self.t5_model.config sequence_length = self.t5_model.max_sequence_length micro_batch_size = 2
# [sequence length, batch size, hidden size] input_tensor = torch.ones((sequence_length, micro_batch_size, config.hidden_size))
self.t5_model.set_input_tensor(input_tensor)
assert self.t5_model.encoder.input_tensor.shape[0] == sequence_length assert self.t5_model.encoder.input_tensor.shape[1] == micro_batch_size assert self.t5_model.encoder.input_tensor.shape[2] == config.hidden_size
def test_post_process_forward(self): config: TransformerConfig = self.t5_model.config sequence_length = self.t5_model.max_sequence_length micro_batch_size = 2
self.t5_model.cuda()
data = list(range(sequence_length)) encoder_input_ids = torch.tensor(data, dtype=torch.int64).repeat((micro_batch_size, 1)).cuda() decoder_input_ids = torch.tensor(data, dtype=torch.int64).repeat((micro_batch_size, 1)).cuda() encoder_attn_mask = torch.ones((1, sequence_length, sequence_length), dtype=bool).cuda() decoder_attn_mask = torch.ones((1, sequence_length, sequence_length), dtype=bool).cuda() encoder_decoder_attn_mask = torch.ones((1, sequence_length, sequence_length), dtype=bool).cuda()
logits = self.t5_model.forward( encoder_input_ids=encoder_input_ids, decoder_input_ids=decoder_input_ids, encoder_attn_mask=encoder_attn_mask, decoder_attn_mask=decoder_attn_mask, encoder_decoder_attn_mask=encoder_decoder_attn_mask )
assert logits.shape[0] == micro_batch_size assert logits.shape[1] == sequence_length assert logits.shape[2] == self.t5_model.vocab_size
def test_no_post_process_forward(self): pass
def test_no_preprocess_forward(self): pass
def test_state_dict_for_save_checkpoint(self): pass
def test_load_state_dict(self): pass
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212import torchfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core import ModelParallelConfigimport megatron.core.pipeline_parallel.schedules as schedulefrom pytest_mock import mocker import pytest
rank = Utils.rank def test_get_forward_backward_func(): Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=1) assert(schedule.get_forward_backward_func() == schedule.forward_backward_no_pipelining) Utils.destroy_model_parallel() Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=4) assert(schedule.get_forward_backward_func() == schedule.forward_backward_pipelining_without_interleaving) Utils.destroy_model_parallel() Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=4, virtual_pipeline_model_parallel_size=2) assert(schedule.get_forward_backward_func() == schedule.forward_backward_pipelining_with_interleaving) Utils.destroy_model_parallel() Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=2, virtual_pipeline_model_parallel_size=4) assert(schedule.get_forward_backward_func() == schedule.forward_backward_pipelining_with_interleaving) Utils.destroy_model_parallel()
def test_deallocate_output_tensor(): out = torch.tensor([[1, 2, 3], [4, 5, 6]]) schedule.deallocate_output_tensor(out) assert(out.nelement() == 6)
def test_forward_backward_func_without_pipeline_parallel(mocker): from megatron.core.pipeline_parallel import get_forward_backward_func
Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=1)
def forward_step_func(data_iterator, model): import os rank = int(os.environ['LOCAL_RANK']) dummy_data = torch.ones(1,4) def loss_func(output_tensor): return rank, {'loss_reduced':rank} return model(dummy_data), loss_func
model = torch.nn.Linear(4,1) model.model_type = 'unit-test' def set_input_tensor(input_tensor): return None model.set_input_tensor = set_input_tensor
forward_backward_func = get_forward_backward_func() assert(schedule.get_forward_backward_func() == schedule.forward_backward_no_pipelining)
mocker.patch("megatron.core.pipeline_parallel.schedules.custom_backward", return_value=2) config = ModelParallelConfig( pipeline_model_parallel_size = 1 ) model.config = config
losses_reduced = forward_backward_func( forward_step_func=forward_step_func, data_iterator=range(0,100), model=[model], num_microbatches=4, seq_length=None, micro_batch_size=None, forward_only=True)
loss_reduced_expected = [{'loss_reduced': rank}, {'loss_reduced': rank}, {'loss_reduced': rank}, {'loss_reduced': rank}] for i,j in zip(losses_reduced, loss_reduced_expected): print(losses_reduced) assert(i['loss_reduced'] == j['loss_reduced']) Utils.destroy_model_parallel()
def test_forward_backward_func_with_pipeline_parallel(mocker): from megatron.core.pipeline_parallel import get_forward_backward_func
Utils.initialize_model_parallel(tensor_model_parallel_size=1, pipeline_model_parallel_size=4)
def forward_step_func(data_iterator, model): import os rank = int(os.environ['LOCAL_RANK']) def loss_func(output_tensor): return rank, {'loss_reduced':rank} return torch.rand(512,8,256).cuda(), loss_func
model = torch.nn.Linear(4,1) model.model_type = 'unit-test' def set_input_tensor(input_tensor): return None model.set_input_tensor = set_input_tensor
forward_backward_func = get_forward_backward_func() assert(schedule.get_forward_backward_func() == schedule.forward_backward_pipelining_without_interleaving)
sequence_length = 512 micro_batch_size = 8 hidden_size = 256
config = ModelParallelConfig( pipeline_model_parallel_size = 4, sequence_parallel = False, pipeline_dtype=torch.float, ) config.hidden_size = hidden_size model.config = config losses_reduced = forward_backward_func( forward_step_func=forward_step_func, data_iterator=None, model=[model], num_microbatches= micro_batch_size, seq_length=sequence_length, micro_batch_size=micro_batch_size, forward_only=True) loss_reduced_expected = [{'loss_reduced': rank}, {'loss_reduced': rank}, {'loss_reduced': rank}, {'loss_reduced': rank}] for i,j in zip(losses_reduced, loss_reduced_expected): print(losses_reduced) assert(i['loss_reduced'] == j['loss_reduced']) Utils.destroy_model_parallel()
def test_forward_backward_func_with_interleaving(mocker): from megatron.core.pipeline_parallel import get_forward_backward_func from megatron.core.enums import ModelType
Utils.initialize_model_parallel(tensor_model_parallel_size=1, pipeline_model_parallel_size=4, virtual_pipeline_model_parallel_size=2)
def forward_step_func(data_iterator, model): import os rank = int(os.environ['LOCAL_RANK']) def loss_func(output_tensor): return rank, {'loss_reduced':rank} return torch.rand(512,8,256).cuda(), loss_func
model = torch.nn.Linear(4,1) def set_input_tensor(input_tensor): return None model.set_input_tensor = set_input_tensor
forward_backward_func = get_forward_backward_func() assert(schedule.get_forward_backward_func() == schedule.forward_backward_pipelining_with_interleaving)
sequence_length = 512 micro_batch_size = 8 hidden_size = 256
config = ModelParallelConfig( pipeline_model_parallel_size = 4, sequence_parallel = False, pipeline_dtype=torch.float, ) config.hidden_size = hidden_size model.config = config
mocker.patch("megatron.core.pipeline_parallel.schedules.custom_backward", return_value=2)
with pytest.raises(RuntimeError): model.model_type = ModelType.encoder_and_decoder forward_backward_func( forward_step_func=forward_step_func, data_iterator=[range(0,100)], model=[model, model], num_microbatches= micro_batch_size, seq_length=sequence_length, micro_batch_size=micro_batch_size, decoder_seq_length=sequence_length, forward_only=True) with pytest.raises(RuntimeError): model.model_type = ModelType.encoder_or_decoder forward_backward_func( forward_step_func=forward_step_func, data_iterator=[range(0,100)], model=[model, model], num_microbatches= micro_batch_size, seq_length=sequence_length, micro_batch_size=micro_batch_size, decoder_seq_length=256, forward_only=True) with pytest.raises(RuntimeError): model.model_type = ModelType.encoder_or_decoder forward_backward_func( forward_step_func=forward_step_func, data_iterator=[range(0,100)], model=[model, model], num_microbatches= 7, seq_length=sequence_length, micro_batch_size=micro_batch_size, decoder_seq_length=512, forward_only=True)
model.model_type = ModelType.encoder_or_decoder losses_reduced = forward_backward_func( forward_step_func=forward_step_func, data_iterator=[range(0,100), range(0,100)], model=[model, model], num_microbatches= micro_batch_size, seq_length=sequence_length, micro_batch_size=micro_batch_size, decoder_seq_length=sequence_length, forward_only=True) loss_reduced_expected = [{'loss_reduced': rank}, {'loss_reduced': rank}, {'loss_reduced': rank}, {'loss_reduced': rank}] for i,j in zip(losses_reduced, loss_reduced_expected): print(losses_reduced) assert(i['loss_reduced'] == j['loss_reduced'])
Utils.destroy_model_parallel() 1234567891011121314from megatron.core.tensor_parallel.cross_entropy import vocab_parallel_cross_entropyimport torchfrom tests.unit_tests.test_utilities import Utilsimport numpy as np
def test_vocab_parallel_cross_entropy(): Utils.initialize_model_parallel(4,2) vocab_parallel_logits = torch.range(0,7).repeat(16,4).cuda() target = torch.arange(0,32,2).cuda() output = vocab_parallel_cross_entropy(vocab_parallel_logits, target) expected_output = torch.tensor([10.2309, 8.2309, 6.2309, 4.2309, 10.2309, 8.2309, 6.2309, 4.2309, 10.2309, 8.2309, 6.2309, 4.2309, 10.2309, 8.2309, 6.2309, 4.2309]).cuda() assert(torch.equal(torch.round(expected_output), torch.round(output))) Utils.destroy_model_parallel()123456789101112131415161718192021from megatron.core.tensor_parallel.data import broadcast_dataimport torchfrom tests.unit_tests.test_utilities import Utils
def test_broadcast_data(): Utils.initialize_model_parallel(2,4) input_data = { 0 : torch.ones((8,8)).cuda() * 0.0, 1 : torch.ones((8,8)).cuda() * 1.0, 2 : torch.ones((8,8)).cuda() * 2.0, 3 : torch.ones((8,8)).cuda() * 3.0, 4 : torch.ones((8,8)).cuda() * 4.0, 5 : torch.ones((8,8)).cuda() * 5.0, 6 : torch.ones((8,8)).cuda() * 6.0, 7 : torch.ones((8,8)).cuda() * 7.0 } dtype = torch.float32 actual_output = broadcast_data([0,1],input_data, dtype) assert(torch.equal(actual_output[0], input_data[0])) assert(torch.equal(actual_output[1], input_data[1])) Utils.destroy_model_parallel()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.tensor_parallel.layers import VocabParallelEmbedding, RowParallelLinear, ColumnParallelLinearfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_local_spec
class Test:
transformer_config = TransformerConfig(num_layers=1, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True) @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.timeout(100) def test_embedding_init(self):
Utils.initialize_model_parallel(1, 1) torch.manual_seed(42) model_parallel_cuda_manual_seed(42)
tp1 = VocabParallelEmbedding(num_embeddings=16, embedding_dim=4, init_method=self.transformer_config.init_method, config=self.transformer_config).weight Utils.destroy_model_parallel()
Utils.initialize_model_parallel(4, 1) torch.manual_seed(42) model_parallel_cuda_manual_seed(41) # intentionally different. tp4 = VocabParallelEmbedding(num_embeddings=16, embedding_dim=4, init_method=self.transformer_config.init_method, config=self.transformer_config).weight
if torch.distributed.get_rank() == 0: assert tp4.shape[0] * 4 == tp1.shape[0] assert torch.allclose(tp1[:4], tp4)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.timeout(100) def test_row_init(self):
Utils.initialize_model_parallel(1, 1) torch.manual_seed(42) model_parallel_cuda_manual_seed(42)
tp1 = RowParallelLinear(input_size=16, output_size=16, init_method=self.transformer_config.init_method, bias=True, input_is_parallel=False, config=self.transformer_config, skip_bias_add=False).weight Utils.destroy_model_parallel()
Utils.initialize_model_parallel(4, 1) torch.manual_seed(42) model_parallel_cuda_manual_seed(41) # intentionally different. tp4 = RowParallelLinear(input_size=16, output_size=16, init_method=self.transformer_config.init_method, bias=True, input_is_parallel=False, config=self.transformer_config, skip_bias_add=False).weight if torch.distributed.get_rank() == 0: assert tp4.shape[1] * 4 == tp1.shape[1] assert torch.allclose(tp1[:, :4], tp4)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.timeout(100) def test_col_init(self):
Utils.initialize_model_parallel(1, 1) torch.manual_seed(42) model_parallel_cuda_manual_seed(42)
tp1 = ColumnParallelLinear(input_size=16, output_size=16, init_method=self.transformer_config.init_method, bias=True, config=self.transformer_config, skip_bias_add=False).weight Utils.destroy_model_parallel()
Utils.initialize_model_parallel(4, 1) torch.manual_seed(42) model_parallel_cuda_manual_seed(41) # intentionally different. tp4 = ColumnParallelLinear(input_size=16, output_size=16, init_method=self.transformer_config.init_method, bias=True, config=self.transformer_config, skip_bias_add=False).weight if torch.distributed.get_rank() == 0: assert tp4.shape[0] * 4 == tp1.shape[0] assert torch.allclose(tp1[:4], tp4) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.import pytestimport torch
from megatron.core.tensor_parallel.layers import linear_with_frozen_weightfrom megatron.core.tensor_parallel.mappings import gather_from_tensor_model_parallel_regionfrom tests.unit_tests.test_utilities import Utils
@pytest.mark.parametrize("tensor_parallel,allreduce_dgrad", [(1, False), (8, True)])def test_LinearWithFrozenWeight(tensor_parallel, allreduce_dgrad): Utils.initialize_model_parallel(tensor_parallel, 1)
size_per_partition = int(8 / tensor_parallel)
# Input is an 8x8 identity matrix. input_data = torch.eye(8).cuda() input_data.requires_grad = True
# Weight is an 8x8 matrix of all ones. If tensor parallelism > 1, the weight is partitioned evenly across GPUs. weight = torch.ones((size_per_partition, 8)).cuda()
# Bias is a vector of length 8 of all zeros. If tensor parallelism > 1, the bias is partitioned evenly across GPUs bias = torch.zeros((size_per_partition)).cuda()
gradient_accumulation_fusion = False async_grad_allreduce = allreduce_dgrad sequence_parallel = False grad_output_buffer = None wgrad_deferral_limit = None
output_parallel = linear_with_frozen_weight( input_data, weight, bias, gradient_accumulation_fusion, async_grad_allreduce, sequence_parallel, grad_output_buffer, wgrad_deferral_limit, allreduce_dgrad, ) output = gather_from_tensor_model_parallel_region( output_parallel ) # no-op if tensor_parallel == 1. output.sum().backward()
expected_output = torch.ones(8).cuda() expected_grad = 8 * torch.ones(8).cuda()
assert torch.allclose(output, expected_output) assert torch.allclose(input_data.grad, expected_grad)
Utils.destroy_model_parallel()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135from megatron.core.tensor_parallel import mappingsfrom tests.unit_tests.test_utilities import Utilsimport torch
def test_CopyToModelParallelRegion(): Utils.initialize_model_parallel(4,2) input_data = torch.ones((1)).cuda()*Utils.rank output_data = mappings._CopyToModelParallelRegion.backward(None, input_data) result = torch.ones(1).cuda() result = result * 22 if Utils.rank >= 4 else result * 6 assert(torch.equal(output_data, result)) assert(torch.equal(input_data, mappings.copy_to_tensor_model_parallel_region(input_data))) assert(torch.equal(input_data, mappings._CopyToModelParallelRegion.symbolic(None, input_data))) Utils.destroy_model_parallel()
def test_ReduceFromModelParallelRegion(): Utils.initialize_model_parallel(4,2) input_data = torch.ones((1)).cuda()*Utils.rank output_data = mappings._ReduceFromModelParallelRegion.symbolic(None, input_data) result = torch.ones(1).cuda() result = result * 22 if Utils.rank >= 4 else result * 6 assert(torch.equal(output_data, result)) input_data = torch.ones((1)).cuda()*Utils.rank assert(torch.equal(mappings.reduce_from_tensor_model_parallel_region(input_data), result)) assert(torch.equal(input_data, mappings._ReduceFromModelParallelRegion.backward(None, input_data))) Utils.destroy_model_parallel()
def test_ScatterToModelParallelRegion(): Utils.initialize_model_parallel(4,2) input_data = torch.rand((8,4)).cuda() output_data = mappings.scatter_to_tensor_model_parallel_region(input_data) req_dim = int(Utils.rank%(Utils.world_size/2)) assert(torch.equal(output_data, input_data[:,req_dim].reshape((8,1)))) output_data = mappings._ScatterToModelParallelRegion.symbolic(None, input_data) assert(torch.equal(output_data, input_data[:, req_dim].reshape((8,1))))
input_data = torch.ones(8).cuda() * Utils.rank actual_output_data = mappings._ScatterToModelParallelRegion.backward(None, input_data) expected_output = torch.cat(( torch.ones(8)*0, torch.ones(8)*1, torch.ones(8)*2, torch.ones(8)*3)).cuda() if (Utils.rank >= 4): expected_output = expected_output + 4 assert(torch.equal(actual_output_data, expected_output)) Utils.destroy_model_parallel()
def test_GatherFromModelParallelRegion(): Utils.initialize_model_parallel(4,2) input_data = torch.rand((8,4)).cuda() req_dim = int(Utils.rank%(Utils.world_size/2)) output_data = mappings._GatherFromModelParallelRegion.backward(None, input_data) assert(torch.equal(output_data, input_data[:, req_dim].reshape((8,1)))) input_data = torch.ones(8).cuda() * Utils.rank actual_output_data = mappings.gather_from_tensor_model_parallel_region(input_data) expected_output = torch.cat(( torch.ones(8)*0, torch.ones(8)*1, torch.ones(8)*2, torch.ones(8)*3)).cuda() if (Utils.rank >= 4): expected_output = expected_output + 4 assert(torch.equal(actual_output_data, expected_output)) assert(torch.equal(mappings._GatherFromModelParallelRegion.symbolic(None, input_data), expected_output)) Utils.destroy_model_parallel() def test_ScatterToSequenceParallelRegion(): Utils.initialize_model_parallel(4,2) input_data = torch.rand((8,4)).cuda() req_dim = int(Utils.rank%(Utils.world_size/2))*2 output_data = mappings._ScatterToSequenceParallelRegion.symbolic(None, input_data) assert(torch.equal(output_data, input_data[req_dim:req_dim+2, :])) output_data = mappings.scatter_to_sequence_parallel_region(input_data) assert(torch.equal(output_data, input_data[req_dim:req_dim+2, :])) input_data = torch.ones(4).cuda() * Utils.rank output_data = mappings._ScatterToModelParallelRegion.backward(None, input_data) expected_output = torch.concat(( torch.ones(4)*0, torch.ones(4)*1, torch.ones(4)*2, torch.ones(4)*3)).cuda() if (Utils.rank >= 4): expected_output = expected_output + 4 assert(torch.equal(output_data, expected_output)) Utils.destroy_model_parallel()
def test_GatherFromSequenceParallelRegion(): Utils.initialize_model_parallel(4,2) input_data = torch.ones(4).cuda() * Utils.rank output_data = mappings.gather_from_sequence_parallel_region(input_data) expected_output = torch.concat(( torch.ones(4)*0, torch.ones(4)*1, torch.ones(4)*2, torch.ones(4)*3)).cuda() if (Utils.rank >= 4): expected_output = expected_output + 4 assert(torch.equal(output_data, expected_output)) assert(torch.equal(mappings._GatherFromSequenceParallelRegion.symbolic(None, input_data), expected_output)) input_data = torch.vstack(( torch.ones(4)*0, torch.ones(4)*1, torch.ones(4)*2, torch.ones(4)*3)).cuda() class Ctx: tensor_parallel_output_grad = True output_data = mappings._GatherFromSequenceParallelRegion.backward(Ctx(), input_data) expected_output = torch.ones((1,4)).cuda() * 4 * int(Utils.rank % 4) assert(torch.equal(output_data[0], expected_output)) Utils.destroy_model_parallel()
def test_ReduceScatterToSequenceParallelRegion(): Utils.initialize_model_parallel(4,2) input_data = torch.vstack(( torch.ones(4)*0, torch.ones(4)*1, torch.ones(4)*2, torch.ones(4)*3)).cuda() output_data = mappings.reduce_scatter_to_sequence_parallel_region(input_data) expected_output = torch.ones(4).cuda() * 4 * int(Utils.rank % 4) assert(torch.equal(output_data[0], expected_output)) assert(torch.equal(mappings._ReduceScatterToSequenceParallelRegion.symbolic(None, input_data) , expected_output.reshape((1,4)))) input_data = torch.ones(4).cuda() * Utils.rank output_data = mappings._ReduceScatterToSequenceParallelRegion.backward(None,input_data) expected_output = torch.concat(( torch.ones(4)*0, torch.ones(4)*1, torch.ones(4)*2, torch.ones(4)*3)).cuda() if (Utils.rank >= 4): expected_output = expected_output + 4 assert(torch.equal(output_data, expected_output)) Utils.destroy_model_parallel()
1234567891011121314151617181920212223242526272829303132333435363738394041424344from megatron.core.tensor_parallel.random import CudaRNGStatesTrackerfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed,get_cuda_rng_trackerfrom megatron.core.tensor_parallel.random import checkpointfrom tests.unit_tests.test_utilities import Utilsimport pytestimport torch
def test_cuda_rng_states_tracker(): rng_tracker = CudaRNGStatesTracker() rng_tracker.set_states({"state1":1234}) assert(rng_tracker.get_states()["state1"] == 1234) rng_tracker.reset() assert(rng_tracker.get_states() == {}) seed = 1111 rng_tracker.add("state2",seed) with pytest.raises(Exception): assert(rng_tracker.add("state3",seed)) with pytest.raises(Exception): assert(rng_tracker.add("state2",111)) assert(rng_tracker.get_states()['state2'] is not None) with pytest.raises(Exception): assert() rng_tracker.fork("state2") torch.cuda.manual_seed(seed) rng_state = torch.cuda.get_rng_state() assert torch.equal(rng_tracker.get_states()['state2'], rng_state)
def test_model_parallel_cuda_manual_seed(): Utils.initialize_model_parallel(4,2) model_parallel_cuda_manual_seed(0) rng_tracker = get_cuda_rng_tracker() assert(rng_tracker.get_states()['model-parallel-rng'] is not None) Utils.destroy_model_parallel()
def test_checkpoint(): def test_forward(*input): return input[0]+input[1] assert(torch.equal(torch.ones(16)*3,checkpoint(test_forward, None, torch.ones(16), torch.ones(16)*2))) Utils.initialize_model_parallel() input1 = torch.ones((4,4)) checkpoint(test_forward, True, input1, torch.ones((4,4))*2) assert(torch.equal(torch.ones(input1.numel()).cuda(), input1)) Utils.destroy_model_parallel()12345678910111213141516171819202122232425262728293031323334353637383940414243import torchimport megatron.core.tensor_parallel.utils as utilimport megatron.core.parallel_state as psfrom tests.unit_tests.test_utilities import Utils
rank = Utils.rank
def test_split_tensor_along_last_dim(): input_tensor = torch.rand((3,4)) torch.equal(input_tensor[0:2,0:2], util.split_tensor_along_last_dim(input_tensor,2)[0]) torch.equal(input_tensor[2:,2:], util.split_tensor_along_last_dim(input_tensor,2)[1])
def test_split_tensor_into_1d_equal_chunks(): Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=4) input_tensor = torch.rand((3,4)) output_tensor = util.split_tensor_into_1d_equal_chunks(input_tensor) if rank % 2 == 0 : start = 0 end = int(input_tensor.numel()/2) else : start = int(input_tensor.numel()/2) end = input_tensor.numel() assert torch.equal(output_tensor, input_tensor.flatten()[start:end]) Utils.destroy_model_parallel()
def test_gather_split_1d_tensor(): Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=4) input_tensor = torch.ones((2,4)).cuda() * rank actual_output_tensor = util.gather_split_1d_tensor(input_tensor) if rank %2 == 0: expected_output_tensor = torch.concat((input_tensor.flatten(), input_tensor.flatten() + 1)) else : expected_output_tensor = torch.concat((input_tensor.flatten() - 1, input_tensor.flatten())) assert(torch.equal(actual_output_tensor, expected_output_tensor)) Utils.destroy_model_parallel()
def test_vocab(): global_vocab_size = 1600 per_partition_vocab_size = 1600 / Utils.world_size assert((rank * per_partition_vocab_size, (rank + 1)* per_partition_vocab_size) == (util.VocabUtility.vocab_range_from_per_partition_vocab_size(global_vocab_size // Utils.world_size, rank, Utils.world_size))) assert((rank * per_partition_vocab_size, (rank + 1)* per_partition_vocab_size) == (util.VocabUtility.vocab_range_from_global_vocab_size(global_vocab_size, rank, Utils.world_size))) 123def test_import(): import megatron
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import argparseimport importlibimport inspectimport osimport traceback
import torchimport wrapt
from megatron.core.transformer.module import MegatronModule
def import_class_by_path(path: str): paths = path.split('.') path = ".".join(paths[:-1]) class_name = paths[-1] mod = __import__(path, fromlist=[class_name]) mod = getattr(mod, class_name) return mod
def _build_import_path(subdomains: list, imp): import_path = ["megatron", "core"] import_path.extend(subdomains) import_path.append(imp) path = ".".join(import_path) return path
def _get_class_from_path(subdomains, imp): path = _build_import_path(subdomains, imp) print(path) class_ = None result = None try: class_ = import_class_by_path(path) if inspect.isclass(class_): if isinstance(class_, wrapt.FunctionWrapper): class_ = class_.__wrapped__ if issubclass(class_, (MegatronModule, torch.nn.Module)): result = class_ else: class_ = None error = None except Exception: error = traceback.format_exc() return class_, result, error
def _test_domain_module_imports(module, subdomains: list): module_list = [] failed_list = [] error_list = []
error = None if len(subdomains) > 0: basepath = module.__path__[0] megatron_index = basepath.rfind("megatron") basepath = basepath[megatron_index:].replace(os.path.sep, ".") new_path = '.'.join([basepath, *subdomains])
try: module = importlib.import_module(new_path) except Exception: print(f"Could not import `{new_path}` ; Traceback below :") error = traceback.format_exc() error_list.append(error)
if error is None: for imp in dir(module): class_, result, error = _get_class_from_path( subdomains, imp)
if result is not None: module_list.append(class_)
elif class_ is not None: failed_list.append(class_)
if error is not None: error_list.append(error)
for module in module_list: print("Module successfully imported :", module)
print() for module in failed_list: print( "Module did not match a valid signature of Megatron core Model (hence ignored):", module)
print() if len(error_list) > 0: print("Imports crashed with following traceback !")
for error in error_list: print("*" * 100) print() print(error) print() print("*" * 100) print()
if len(error_list) > 0: return False else: return True
###############################
def test_domain_mcore(): import megatron.core as mcore
all_passed = _test_domain_module_imports( mcore, subdomains=['models'])
all_passed = _test_domain_module_imports( mcore, subdomains=['pipeline_parallel'])
all_passed = _test_domain_module_imports( mcore, subdomains=['tensor_parallel'])
all_passed = _test_domain_module_imports( mcore, subdomains=['transformer'])
all_passed = _test_domain_module_imports( mcore, subdomains=['fusions'])
all_passed = _test_domain_module_imports( mcore, subdomains=['distributed'])
all_passed = _test_domain_module_imports( mcore, subdomains=['datasets'])
all_passed = _test_domain_module_imports( mcore, subdomains=['dist_checkpointing'])
if not all_passed: exit(1)
if __name__ == '__main__': test_domain_mcore()123456789101112131415161718192021222324252627282930313233343536import copyfrom megatron.core.utils import ( local_multi_tensor_applier, local_multi_tensor_l2_norm, local_multi_tensor_scale)import pytestimport torch
def test_local_multi_tensor_l2_norm_and_scale(): amp_C = pytest.importorskip("amp_C") multi_tensor_apply = pytest.importorskip("apex.multi_tensor_apply")
torch.manual_seed(42)
tensor_list = [torch.rand(5,5).cuda() for _ in range(10)] tensor_list_copy = copy.deepcopy(tensor_list)
norm_apex, _ = multi_tensor_apply.multi_tensor_applier(amp_C.multi_tensor_l2norm, torch.tensor([0], dtype=torch.int, device='cuda'), [tensor_list], False) norm_local, _ = multi_tensor_apply.multi_tensor_applier(local_multi_tensor_l2_norm, torch.tensor([0], dtype=torch.int, device='cuda'), [tensor_list_copy], False) torch.testing.assert_close(norm_apex, norm_local)
clip_coeff = 0.05 multi_tensor_apply.multi_tensor_applier(amp_C.multi_tensor_scale, torch.tensor([0], dtype=torch.int, device='cuda'), [tensor_list, tensor_list], clip_coeff) multi_tensor_apply.multi_tensor_applier(local_multi_tensor_scale, torch.tensor([0], dtype=torch.int, device='cuda'), [tensor_list_copy, tensor_list_copy], clip_coeff) torch.testing.assert_close(tensor_list, tensor_list_copy)
def test_local_multi_tensor_apply(): amp_C = pytest.importorskip("amp_C") multi_tensor_apply = pytest.importorskip("apex.multi_tensor_apply")
tensor_list = [torch.rand(5,5).cuda() for _ in range(10)]
norm_apex, _ = multi_tensor_apply.multi_tensor_applier(amp_C.multi_tensor_l2norm, torch.tensor([0], dtype=torch.int, device='cuda'), [tensor_list], False) norm_local, _ = local_multi_tensor_applier(amp_C.multi_tensor_l2norm, torch.tensor([0], dtype=torch.int, device='cuda'), [tensor_list], False) torch.testing.assert_close(norm_apex, norm_local)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128from typing import List, Optional
import pytest
import megatron.core.num_microbatches_calculator as mb_calculator
def reconfigure_num_microbatches_calculator( rank: int, rampup_batch_size: Optional[List[int]], global_batch_size: int, micro_batch_size: int, data_parallel_size: int,): """Reconfigure number of micro-batches calculator.
Args: rank (int): Rank of the GPU, only rank 0 will log the information. rampup_batch_size (Optional[List[int]]): Rampup batch size, should be in format of [start_global_batch_size, batch_size_increment, ramup_samples]. global_batch_size (int): Global batch size for the model. micro_batch_size (int): Micro batch size at initialization. data_parallel_size (int): Data parallel size. """
mb_calculator._GLOBAL_NUM_MICROBATCHES_CALCULATOR = mb_calculator.build_num_microbatches_calculator( rank, rampup_batch_size, global_batch_size, micro_batch_size, data_parallel_size )
def test_init_num_microbatches_calculator(): mb_calculator._GLOBAL_NUM_MICROBATCHES_CALCULATOR = None mb_calculator.init_num_microbatches_calculator(0, None, 32, 8, 2) assert mb_calculator.get_num_microbatches() == 2 assert mb_calculator.get_current_global_batch_size() == 32
with pytest.raises(AssertionError): mb_calculator.init_num_microbatches_calculator(0, None, 32, 8, 2)
def test_get_num_microbatches(): reconfigure_num_microbatches_calculator(0, None, 16, 8, 2) assert mb_calculator.get_num_microbatches() == 1
def test_get_current_global_batch_size(): reconfigure_num_microbatches_calculator(0, None, 16, 8, 2) assert mb_calculator.get_current_global_batch_size() == 16
def test_update_num_microbatches(): reconfigure_num_microbatches_calculator(0, [16, 8, 96], 32, 4, 2) assert mb_calculator.get_num_microbatches() == 2 mb_calculator.update_num_microbatches(48, False) assert mb_calculator.get_num_microbatches() == 3
reconfigure_num_microbatches_calculator(0, [16, 8, 96], 32, 8, 2) with pytest.raises(AssertionError): mb_calculator.update_num_microbatches(49, True)
reconfigure_num_microbatches_calculator(0, None, 32, 8, 2) mb_calculator.update_num_microbatches(16) assert mb_calculator.get_num_microbatches() == 2
def test_build_num_microbatches_calculator(): temp_calculator = mb_calculator.build_num_microbatches_calculator(0, None, 32, 8, 2) assert temp_calculator.get() == 2 assert temp_calculator.get_current_global_batch_size() == 32 assert type(temp_calculator) is mb_calculator.ConstantNumMicroBatchesCalculator
temp_calculator = mb_calculator.build_num_microbatches_calculator(0, [16, 16, 48], 32, 8, 2) assert temp_calculator.get() == 1 assert temp_calculator.get_current_global_batch_size() == 16 assert type(temp_calculator) is mb_calculator.RampupBatchsizeNumMicroBatchesCalculator
class TestConstantNumMicroBatchesCalculator: def setup_method(self, method): self.mb_calculator = mb_calculator.ConstantNumMicroBatchesCalculator(32, 8, 2)
def test_constructor(self): assert type(self.mb_calculator) is mb_calculator.ConstantNumMicroBatchesCalculator assert self.mb_calculator.num_micro_batches == 2 assert self.mb_calculator.current_global_batch_size == 32 assert self.mb_calculator.micro_batch_size == 8
def test_get(self): assert self.mb_calculator.get() == 2
def test_get_current_global_batch_size(self): assert self.mb_calculator.get_current_global_batch_size() == 32
class TestRampupBatchsizeNumMicroBatchesCalculator: def setup_method(self, method): self.mb_calculator = mb_calculator.RampupBatchsizeNumMicroBatchesCalculator( 32, 8, 2, 16, 16, 48 )
def test_constructor(self): assert type(self.mb_calculator) is mb_calculator.RampupBatchsizeNumMicroBatchesCalculator assert self.mb_calculator.global_batch_size == 32 assert self.mb_calculator.micro_batch_size == 8 assert self.mb_calculator.data_parallel_size == 2 assert self.mb_calculator.start_global_batch_size == 16 assert self.mb_calculator.batch_size_increment == 16 assert self.mb_calculator.ramup_samples == 48 assert self.mb_calculator.micro_batch_times_data_parallel_size == 16 assert self.mb_calculator.num_micro_batches == 1
def test_get(self): assert self.mb_calculator.get() == 1
def test_get_current_global_batch_size(self): assert self.mb_calculator.get_current_global_batch_size() == 16
def test_ramp_up(): reconfigure_num_microbatches_calculator(0, [16, 16, 96], 32, 8, 2) consumed_samples = 0 count = 0 expected_consumed_samples = [0, 16, 32, 48, 64, 80, 96, 128, 160, 192, 224, 256]
while consumed_samples < 256: consumed_samples += mb_calculator.get_current_global_batch_size() count += 1 assert consumed_samples == expected_consumed_samples[count] mb_calculator.update_num_microbatches(consumed_samples, True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.optim import SGD, Adam
from megatron.core.optimizer import ChainedOptimizer
class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)
def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = torch.flatten(x, 1) # flatten all dimensions except batch x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x
def test_chained_optimizer(): net = Net() optimizer_1 = Adam(list(net.parameters())[:2], lr=0.01,) optimizer_2 = SGD(list(net.parameters())[2:], lr=0.1, momentum=0.9,) chained_optimizer = ChainedOptimizer([optimizer_1, optimizer_2])
# Test the chained optimizer's param groups is a reference of the underlying optimizers' param groups assert optimizer_1.param_groups[0]["lr"] == 0.01 chained_optimizer.param_groups[0]["lr"] = 0.02 assert optimizer_1.param_groups[0]["lr"] == 0.02
# Test the chained optimizer's state is a reference of the underlying optimizers' state # 1. run step on optimizers, make sure there is state assert len(chained_optimizer.state) == 0 input = torch.randn(1, 3, 32, 32) output = net(input) output.sum().backward() optimizer_1.step() optimizer_2.step() assert len(chained_optimizer.state) != 0
# 2. check the state is a reference assert not list(optimizer_1.state.values())[0]["exp_avg"].is_cuda assert not list(optimizer_2.state.values())[0]["momentum_buffer"].is_cuda
def to_cuda(d): for k, v in d.items(): if isinstance(v, torch.Tensor): d[k] = v.to("cuda") elif isinstance(v, dict): to_cuda(v) return d
for k, v in chained_optimizer.state.items(): chained_optimizer.state[k] = to_cuda(v)
assert list(optimizer_1.state.values())[0]["exp_avg"].is_cuda assert list(optimizer_2.state.values())[0]["momentum_buffer"].is_cuda123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468import torchimport megatron.core.parallel_state as psimport pytestfrom tests.unit_tests.test_utilities import Utilsimport os
rank = Utils.rankworld_size = Utils.world_sizetest_parallel_order = ['tp-cp-ep-dp-pp', 'tp-cp-pp-ep-dp']
@pytest.mark.parametrize('order', test_parallel_order)def test_initialize_and_destroy_model_parallel(order): with pytest.raises(AssertionError): assert(ps.initialize_model_parallel(order=order)) Utils.initialize_distributed() with pytest.raises(RuntimeError): assert(ps.initialize_model_parallel(tensor_model_parallel_size=2*world_size, order=order)) with pytest.raises(RuntimeError): assert(ps.initialize_model_parallel(pipeline_model_parallel_size=2*world_size, order=order)) with pytest.raises(RuntimeError): assert(ps.initialize_model_parallel(pipeline_model_parallel_size=world_size, tensor_model_parallel_size=world_size, order=order)) with pytest.raises(RuntimeError): assert(ps.initialize_model_parallel(virtual_pipeline_model_parallel_size=2, order=order)) Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=4, order=order)
assert(ps.model_parallel_is_initialized()) assert(ps.get_model_parallel_group() is not None) assert(ps.get_tensor_model_parallel_group() is not None) assert(ps.get_pipeline_model_parallel_group() is not None) assert(ps.get_data_parallel_group() is not None) Utils.destroy_model_parallel() assert(ps._MODEL_PARALLEL_GROUP is None)
@pytest.mark.parametrize('order', test_parallel_order)def test_pipeline_parallel_initializations(order): Utils.initialize_model_parallel(tensor_model_parallel_size=2, pipeline_model_parallel_size=4, order=order) assert(ps.get_pipeline_model_parallel_first_rank() == rank % 2 ) assert(ps.get_data_parallel_src_rank() == rank) assert(ps.get_pipeline_model_parallel_next_rank() == ((rank + 2) % world_size)) assert(ps.get_pipeline_model_parallel_prev_rank() == ((rank - 2) % world_size)) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_data_parallel_initializations(order): Utils.initialize_model_parallel(pipeline_model_parallel_size=world_size, order=order) assert(ps.get_data_parallel_src_rank() == rank) assert(ps.get_data_parallel_world_size() == 1) assert(ps.get_data_parallel_rank() == 0) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_tensor_model_parellel_world_size(order): Utils.initialize_model_parallel(tensor_model_parallel_size=world_size, order=order) assert(ps.get_tensor_model_parallel_world_size() == world_size) ps.set_tensor_model_parallel_world_size(None) assert(ps.get_tensor_model_parallel_world_size() == world_size) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_pipeline_model_parallel_world_size(order): Utils.initialize_model_parallel(pipeline_model_parallel_size=world_size, order=order) assert(ps.get_pipeline_model_parallel_world_size() == world_size) ps.set_pipeline_model_parallel_world_size(None) assert(ps.get_pipeline_model_parallel_world_size() == world_size) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_tensor_model_parallel_rank(order): Utils.initialize_model_parallel(tensor_model_parallel_size=world_size, order=order) assert(ps.get_tensor_model_parallel_rank() == rank) ps.set_tensor_model_parallel_rank(None) assert(ps.get_tensor_model_parallel_rank() == rank) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_pipeline_model_parallel_rank(order): Utils.initialize_model_parallel(pipeline_model_parallel_size=world_size, order=order) assert(ps.get_pipeline_model_parallel_rank() == rank) ps.set_pipeline_model_parallel_rank(None) assert(ps.get_pipeline_model_parallel_rank() == rank) Utils.destroy_model_parallel()
def test_context_parallel_rank(): Utils.initialize_model_parallel(context_parallel_size=world_size) assert(ps.get_context_parallel_rank() == rank) Utils.destroy_model_parallel()
def test_expert_model_parallel_rank(): Utils.initialize_model_parallel(expert_model_parallel_size=world_size) assert(ps.get_expert_model_parallel_rank() == rank) ps.set_expert_model_parallel_rank(None) assert(ps.get_expert_model_parallel_rank() == rank) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_is_pipeline_first_stage(order): Utils.initialize_model_parallel(pipeline_model_parallel_size=world_size, order=order) assert(ps.is_pipeline_first_stage(ignore_virtual=True) == (rank == 0)) assert(ps.is_pipeline_first_stage() == (rank == 0)) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_is_pipeline_last_stage(order): Utils.initialize_model_parallel(pipeline_model_parallel_size=world_size, order=order) assert(ps.is_pipeline_last_stage(ignore_virtual=True) == (rank == world_size-1)) assert(ps.is_pipeline_last_stage() == (rank == world_size-1)) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_virtual_pipeline_model_parallel_rank(order): Utils.initialize_model_parallel(pipeline_model_parallel_size=world_size, order=order) ps.set_virtual_pipeline_model_parallel_rank(rank) assert(ps.get_virtual_pipeline_model_parallel_rank() == rank) Utils.destroy_model_parallel()
@pytest.mark.parametrize('order', test_parallel_order)def test_get_tensor_model_parallel_src_rank(order): Utils.initialize_model_parallel(tensor_model_parallel_size=world_size, order=order) assert(ps.get_tensor_model_parallel_src_rank() == ((rank // world_size) * world_size)) Utils.destroy_model_parallel()
@pytest.mark.parametrize( 'src_tp_pp, ep_size', [ ((1, 8), 1), ((2, 4), 1), ((4, 2), 1), ((8, 1), 1), ((4, 1), 2), ((1, 1), 8), ((1, 1), 2), ((2, 1), 4), ],)def test_different_initialize_order_consistency(src_tp_pp, ep_size): Utils.initialize_model_parallel( *src_tp_pp, expert_model_parallel_size=ep_size, order='tp-ep-dp-pp' ) tp_rank = ps.get_tensor_model_parallel_rank() dp_rank = ps.get_data_parallel_rank() pp_rank = ps.get_pipeline_model_parallel_rank() ep_rank = ps.get_expert_model_parallel_rank()
tp_g = torch.distributed.get_process_group_ranks(ps.get_tensor_model_parallel_group()) dp_g = torch.distributed.get_process_group_ranks(ps.get_data_parallel_group(False)) pp_g = torch.distributed.get_process_group_ranks(ps.get_pipeline_model_parallel_group()) dp_no_ep_g = torch.distributed.get_process_group_ranks( ps.get_data_modulo_expert_parallel_group() ) cp_g = torch.distributed.get_process_group_ranks(ps.get_context_parallel_group()) amax_g = torch.distributed.get_process_group_ranks(ps.get_amax_reduction_group(False)) mp_g = torch.distributed.get_process_group_ranks(ps.get_model_parallel_group()) tp_ep_g = torch.distributed.get_process_group_ranks(ps.get_tensor_and_expert_parallel_group()) tp_dp_g = torch.distributed.get_process_group_ranks( ps.get_tensor_and_data_parallel_group(False) )
Utils.destroy_model_parallel()
Utils.initialize_model_parallel( *src_tp_pp, expert_model_parallel_size=ep_size, order='tp-pp-ep-dp' ) assert tp_rank == ps.get_tensor_model_parallel_rank() assert dp_rank == ps.get_data_parallel_rank() assert pp_rank == ps.get_pipeline_model_parallel_rank() assert ep_rank == ps.get_expert_model_parallel_rank()
assert tp_g == torch.distributed.get_process_group_ranks(ps.get_tensor_model_parallel_group()) assert dp_g == torch.distributed.get_process_group_ranks(ps.get_data_parallel_group(False)) assert pp_g == torch.distributed.get_process_group_ranks(ps.get_pipeline_model_parallel_group()) assert dp_no_ep_g == torch.distributed.get_process_group_ranks( ps.get_data_modulo_expert_parallel_group() ) assert cp_g == torch.distributed.get_process_group_ranks(ps.get_context_parallel_group()) assert amax_g == torch.distributed.get_process_group_ranks(ps.get_amax_reduction_group(False)) assert mp_g == torch.distributed.get_process_group_ranks(ps.get_model_parallel_group()) assert tp_ep_g == torch.distributed.get_process_group_ranks( ps.get_tensor_and_expert_parallel_group() ) assert tp_dp_g == torch.distributed.get_process_group_ranks( ps.get_tensor_and_data_parallel_group(False) )
Utils.destroy_model_parallel()
@pytest.mark.parametrize( 'src_tp_pp, ep_size', [((1, 2), 1), ((1, 4), 1), ((2, 2), 1), ((1, 2), 2), ((1, 4), 2), ((2, 2), 2),],)def test_different_initialize_order_unconsistency(src_tp_pp, ep_size): Utils.initialize_model_parallel( *src_tp_pp, expert_model_parallel_size=ep_size, order='tp-ep-dp-pp' )
tp_g = torch.distributed.get_process_group_ranks(ps.get_tensor_model_parallel_group()) dp_g = torch.distributed.get_process_group_ranks(ps.get_data_parallel_group(False)) pp_g = torch.distributed.get_process_group_ranks(ps.get_pipeline_model_parallel_group()) cp_g = torch.distributed.get_process_group_ranks(ps.get_context_parallel_group()) amax_g = torch.distributed.get_process_group_ranks(ps.get_amax_reduction_group(False)) mp_g = torch.distributed.get_process_group_ranks(ps.get_model_parallel_group())
Utils.destroy_model_parallel()
Utils.initialize_model_parallel( *src_tp_pp, expert_model_parallel_size=ep_size, order='tp-pp-ep-dp' ) assert tp_g == torch.distributed.get_process_group_ranks(ps.get_tensor_model_parallel_group()) assert dp_g != torch.distributed.get_process_group_ranks(ps.get_data_parallel_group(False)) assert pp_g != torch.distributed.get_process_group_ranks(ps.get_pipeline_model_parallel_group()) assert cp_g == torch.distributed.get_process_group_ranks(ps.get_context_parallel_group()) assert amax_g == torch.distributed.get_process_group_ranks(ps.get_amax_reduction_group(False)) assert mp_g != torch.distributed.get_process_group_ranks(ps.get_model_parallel_group())
Utils.destroy_model_parallel()
@pytest.mark.parametrize( 'nodes, num_gpu, tp, pp, cp, ep', [ (1, 1, 1, 1, 1, 1), (1, 8, 8, 1, 1, 1), (1, 8, 2, 2, 1, 1), (1, 8, 2, 4, 1, 1), (3, 8, 8, 3, 1, 1), (4, 8, 2, 4, 1, 1), (8, 8, 8, 8, 1, 1), (8, 8, 2, 1, 1, 4), (8, 8, 2, 2, 2, 4), (8, 8, 2, 1, 4, 8), (8, 8, 2, 2, 2, 8), (16, 8, 4, 8, 1, 1), (16, 8, 4, 8, 1, 4), (16, 8, 4, 8, 4, 1), (16, 8, 8, 8, 1, 1), (16, 8, 4, 8, 1, 1), (16, 8, 8, 8, 1, 1), (32, 8, 4, 8, 1, 1), (32, 8, 8, 8, 1, 1), (32, 8, 4, 8, 1, 4), (32, 8, 8, 8, 4, 1), (64, 8, 4, 2, 8, 8), (64, 8, 4, 8, 1, 1), (64, 8, 8, 8, 1, 1), (96, 8, 4, 8, 1, 1), (128, 8, 4, 2, 8, 8), (128, 8, 4, 8, 1, 1), (256, 8, 4, 8, 1, 1), (316, 8, 4, 8, 1, 1), (384, 8, 4, 8, 1, 1), (512, 8, 4, 8, 1, 1), (768, 8, 4, 8, 1, 1), (1024, 8, 4, 8, 1, 1), (1280, 8, 4, 8, 1, 1), (1344, 8, 4, 8, 1, 1), ],)def test_rank_generator_for_tp_dp_pp(nodes, num_gpu, tp, pp, cp, ep): def golden_rank_result_from_past_code( world_size: int, tensor_model_parallel_size: int = 1, pipeline_model_parallel_size: int = 1, context_parallel_size: int = 1, expert_model_parallel_size: int = 1, ): data_parallel_size: int = world_size // ( tensor_model_parallel_size * pipeline_model_parallel_size * context_parallel_size ) num_tensor_model_parallel_groups: int = world_size // tensor_model_parallel_size num_pipeline_model_parallel_groups: int = world_size // pipeline_model_parallel_size
dp_groups = [] dp_groups_with_cp = []
all_data_parallel_group_ranks_with_cp = [] for i in range(pipeline_model_parallel_size): start_rank = i * num_pipeline_model_parallel_groups end_rank = (i + 1) * num_pipeline_model_parallel_groups for j in range(context_parallel_size * tensor_model_parallel_size): ranks = range( start_rank + j, end_rank, context_parallel_size * tensor_model_parallel_size ) dp_groups.append(list(ranks)) for j in range(tensor_model_parallel_size): ranks_with_cp = range(start_rank + j, end_rank, tensor_model_parallel_size) all_data_parallel_group_ranks_with_cp.append(list(ranks_with_cp)) dp_groups_with_cp.append(list(ranks_with_cp))
cp_group = [] for i in range(pipeline_model_parallel_size): for j in range(data_parallel_size): start_rank = ( i * num_pipeline_model_parallel_groups + j * tensor_model_parallel_size * context_parallel_size ) end_rank = ( i * num_pipeline_model_parallel_groups + (j + 1) * tensor_model_parallel_size * context_parallel_size ) for k in range(tensor_model_parallel_size): ranks = range(start_rank + k, end_rank, tensor_model_parallel_size) cp_group.append(list(ranks))
mp_group = [] for i in range(data_parallel_size * context_parallel_size): ranks = [ data_parallel_group_ranks_with_cp[i] for data_parallel_group_ranks_with_cp in all_data_parallel_group_ranks_with_cp ] mp_group.append(list(ranks))
tp_group = [] for i in range(num_tensor_model_parallel_groups): ranks = range(i * tensor_model_parallel_size, (i + 1) * tensor_model_parallel_size) tp_group.append(list(ranks))
pp_group = [] for i in range(num_pipeline_model_parallel_groups): ranks = range(i, world_size, num_pipeline_model_parallel_groups) pp_group.append(list(ranks))
tp_dp_group = [] tp_dp_cp_group = [] tensor_and_data_group_size_with_cp: int = tensor_model_parallel_size * data_parallel_size * context_parallel_size num_tensor_and_data_groups_with_cp: int = world_size // tensor_and_data_group_size_with_cp for i in range(num_tensor_and_data_groups_with_cp): start_rank = i * tensor_and_data_group_size_with_cp end_rank = start_rank + tensor_and_data_group_size_with_cp ranks = range(start_rank, end_rank) tp_dp_cp_group.append(list(ranks))
for j in range(context_parallel_size): ranks = [] for k in range(data_parallel_size): start_rank = ( i * tensor_and_data_group_size_with_cp + j * tensor_model_parallel_size + k * tensor_model_parallel_size * context_parallel_size ) end_rank = start_rank + tensor_model_parallel_size ranks = ranks + list(range(start_rank, end_rank)) tp_dp_group.append(list(ranks))
tp_ep_group = [] dp_no_ep_group = [] dp_no_ep_group_with_cp = []
all_ranks = torch.arange(world_size).reshape(( pipeline_model_parallel_size, data_parallel_size // expert_model_parallel_size, expert_model_parallel_size, context_parallel_size, tensor_model_parallel_size )) # 'pp edp ep cp tp -> (pp edp cp) (ep tp)' tp_ep_rearrange = torch.transpose(all_ranks, 2, 3) tp_ep_rearrange = torch.reshape(tp_ep_rearrange, (-1, expert_model_parallel_size * tensor_model_parallel_size)) tp_ep_rearrange = tp_ep_rearrange.tolist() tp_ep_rearrange.sort() for tensor_and_expert_parallel_ranks in tp_ep_rearrange: tensor_and_expert_parallel_ranks = list(tensor_and_expert_parallel_ranks) tensor_and_expert_parallel_ranks.sort() tp_ep_group.append(tensor_and_expert_parallel_ranks) # 'pp edp ep cp tp -> (pp ep cp tp) edp' edp_rearrange = torch.transpose(all_ranks, 1, 4) edp_rearrange = torch.reshape(edp_rearrange, (-1, data_parallel_size // expert_model_parallel_size)) edp_rearrange = edp_rearrange.tolist() edp_rearrange.sort() for expert_data_parallel_ranks in edp_rearrange: expert_data_parallel_ranks = list(expert_data_parallel_ranks) expert_data_parallel_ranks.sort() dp_no_ep_group.append(expert_data_parallel_ranks) # 'pp edp ep cp tp -> (pp ep tp) (cp edp)' edp_cp_rearrange = torch.transpose(all_ranks, 1, 2) edp_cp_rearrange = torch.transpose(edp_cp_rearrange, 2, 4) edp_cp_rearrange = torch.reshape( edp_cp_rearrange, (-1, context_parallel_size * data_parallel_size // expert_model_parallel_size) ) edp_cp_rearrange = edp_cp_rearrange.tolist() edp_cp_rearrange.sort() for expert_data_parallel_ranksj_with_cp in edp_cp_rearrange: expert_data_parallel_ranksj_with_cp = list(expert_data_parallel_ranksj_with_cp) expert_data_parallel_ranksj_with_cp.sort() dp_no_ep_group_with_cp.append(expert_data_parallel_ranksj_with_cp)
return ( dp_groups, dp_groups_with_cp, cp_group, mp_group, tp_group, pp_group, tp_dp_group, tp_dp_cp_group, tp_ep_group, dp_no_ep_group, dp_no_ep_group_with_cp, )
world_size = nodes * num_gpu dp = world_size // (tp * pp * cp) assert dp % ep == 0, f"dp size ({dp}) is not divisible by ep {ep} ." assert ( world_size % (tp * pp * cp) == 0 ), f"world_size ({world_size}) is not divisible by tp {tp} x pp {pp} x cp {cp}." ( dp_groups, dp_groups_with_cp, cp_group, mp_group, tp_group, pp_group, tp_dp_group, tp_dp_cp_group, tp_ep_group, dp_no_ep_group, dp_no_ep_group_with_cp, ) = golden_rank_result_from_past_code( world_size=world_size, tensor_model_parallel_size=tp, pipeline_model_parallel_size=pp, context_parallel_size=cp, expert_model_parallel_size=ep, ) rank_generator = ps.RankGenerator(tp=tp, ep=ep, dp=dp, pp=pp, cp=cp, order="tp-cp-ep-dp-pp",) assert dp_groups == rank_generator.get_ranks( "dp" ), f"{dp_groups} != {rank_generator.get_ranks('dp')}" assert dp_groups_with_cp == rank_generator.get_ranks( 'dp-cp' ), f"{dp_groups_with_cp} != {rank_generator.get_ranks('dp-cp')}" assert cp_group == rank_generator.get_ranks( "cp" ), f"{cp_group} != {rank_generator.get_ranks('cp')}." assert mp_group == rank_generator.get_ranks( "tp-pp" ), f"{mp_group} != {rank_generator.get_ranks('tp-pp')}" assert tp_group == rank_generator.get_ranks( "tp" ), f"{tp_group} != {rank_generator.get_ranks('tp')}" assert pp_group == rank_generator.get_ranks( "pp" ), f"{pp_group} != {rank_generator.get_ranks('pp')}" assert tp_dp_group == rank_generator.get_ranks( "tp-dp" ), f"{tp_dp_group} != {rank_generator.get_ranks('tp-dp')}" assert tp_dp_cp_group == rank_generator.get_ranks( "tp-dp-cp" ), f"{tp_dp_cp_group} != {rank_generator.get_ranks('tp-dp-cp')}" assert tp_ep_group == rank_generator.get_ranks( "tp-ep", independent_ep=True ), f"{tp_ep_group} != {rank_generator.get_ranks('tp-ep', independent_ep=True)}." assert dp_no_ep_group == rank_generator.get_ranks( "dp", independent_ep=True ), f"{dp_no_ep_group} != {rank_generator.get_ranks('dp', independent_ep=True)}." assert dp_no_ep_group_with_cp == rank_generator.get_ranks( "dp-cp", independent_ep=True ), f"{dp_no_ep_group_with_cp} != {rank_generator.get_ranks('dp-cp', independent_ep=True)}."12345678910111213141516171819202122232425262728293031323334353637383940414243from types import SimpleNamespace
from megatron.training.global_vars import set_argsfrom megatron.training.training import build_train_valid_test_data_iteratorsfrom tests.unit_tests.test_utilities import Utils
def mock_train_valid_test_datasets_provider(train_val_test_num_samples): return 1, 2, 3
def create_test_args(): # Set dummy values for the args. args = SimpleNamespace() args.iteration = 0 args.train_samples = 1 args.train_iters = 1 args.eval_interval = 1 args.eval_iters = 1 args.global_batch_size = 1 args.consumed_train_samples = 1 args.consumed_valid_samples = 1 args.dataloader_type = "external" args.skip_train = False
return args
class TestTraining: def setup_method(self, method): Utils.initialize_model_parallel(1, 1) args = create_test_args() set_args(args)
def test_build_train_valid_test_data_iterators(self): train_iter, valid_iter, test_iter = build_train_valid_test_data_iterators( mock_train_valid_test_datasets_provider )
assert (train_iter, valid_iter, test_iter) == (1, 2, 3)
def teardown_method(self, method): Utils.destroy_model_parallel()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import osimport torchimport megatron.core.parallel_state as ps
class TestModel(torch.nn.Module): def __init__(self, input_dim: int, output_dim: int, num_layers: int, bias: bool): super().__init__() self.layers = torch.nn.ModuleList( [torch.nn.Linear(input_dim, output_dim, bias) for _ in range(num_layers)] )
class Utils:
world_size = torch.cuda.device_count() rank = int(os.environ['LOCAL_RANK']) inited = False
@staticmethod def initialize_distributed(): if not torch.distributed.is_initialized() and Utils.rank >= 0: print( f'Initializing torch.distributed with rank: {Utils.rank}, world_size: {Utils.world_size}' ) torch.cuda.set_device(Utils.rank % torch.cuda.device_count()) init_method = 'tcp://' master_ip = os.getenv('MASTER_ADDR', 'localhost') master_port = os.getenv('MASTER_PORT', '6000') init_method += master_ip + ':' + master_port torch.distributed.init_process_group( backend='nccl', world_size=Utils.world_size, rank=Utils.rank, init_method=init_method, )
torch.distributed.barrier() Utils.inited = True
@staticmethod def set_world_size(world_size=None, rank=None): Utils.world_size = torch.cuda.device_count() if world_size is None else world_size if ( torch.distributed.is_initialized() and Utils.world_size != torch.distributed.get_world_size() ): torch.distributed.destroy_process_group()
if rank is None: Utils.rank = int(os.environ['LOCAL_RANK']) if Utils.rank >= Utils.world_size: Utils.rank = -1 else: Utils.rank = rank
@staticmethod def destroy_model_parallel(): if not Utils.inited: return ps.destroy_model_parallel() torch.distributed.barrier() Utils.inited = False
@staticmethod def initialize_model_parallel( tensor_model_parallel_size=1, pipeline_model_parallel_size=1, virtual_pipeline_model_parallel_size=None, pipeline_model_parallel_split_rank=None, **kwargs, ): ps.destroy_model_parallel() Utils.initialize_distributed() ps.initialize_model_parallel( tensor_model_parallel_size, pipeline_model_parallel_size, virtual_pipeline_model_parallel_size, pipeline_model_parallel_split_rank, **kwargs, ) Utils.inited = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import osimport timeimport urllib.request as req
import numpy as npimport pytestimport torch
import megatron.core.utils as utilfrom tests.unit_tests.test_utilities import Utils
def test_divide_properly(): assert util.divide(4,2) == 2
def test_divide_improperly(): with pytest.raises(AssertionError): util.divide(4,5)
def test_global_memory_buffer(): global_memory_buffer = util.GlobalMemoryBuffer() obtained_tensor = global_memory_buffer.get_tensor((3,2), torch.float32, "test_tensor") expected_tensor = torch.empty((3,2), dtype=torch.float32, device=torch.cuda.current_device()) assert obtained_tensor.shape == expected_tensor.shape
def test_make_viewless_tensor(): inp = torch.rand((3,4)) assert(torch.equal(inp, util.make_viewless_tensor(inp, True, True))) assert(torch.equal(inp, util.make_viewless_tensor(inp, True, False)))
def test_safely_set_viewless_tensor_data(): tensor = torch.zeros((3,4)) new_data_tensor = torch.tensor(np.random.rand(3,4)) util.safely_set_viewless_tensor_data(tensor, new_data_tensor) assert(torch.equal(tensor, new_data_tensor))
def test_assert_viewless_tensor(): tensor = torch.rand((3,4)) assert(torch.equal(util.assert_viewless_tensor(tensor), tensor)) input_tensor_list=[tensor,tensor,tensor] output_tensor_list = util.assert_viewless_tensor(input_tensor_list) for inp,out in zip(input_tensor_list, output_tensor_list): assert(torch.equal(inp,out))
# Initialize torch.distributed; do not call init_process_group here, call# Utils.initialize_distributed() instead.def _init_distributed(world, rank): Utils.initialize_distributed() assert torch.distributed.is_initialized() == True assert torch.distributed.get_rank() == rank assert torch.cuda.device_count() == world torch.distributed.barrier()
# Deinitialization and cleanup.# Do not call torch.distributed.destroy_process_group, may be needed by other tests.def _deinit_distributed(): assert torch.distributed.is_initialized() == True torch.distributed.barrier()
def test_check_param_hashes_across_dp_replicas(): world = int(os.getenv('WORLD_SIZE', '1')) rank = int(os.getenv('RANK', '0'))
# Setup. _init_distributed(world, rank) Utils.initialize_model_parallel() model = torch.nn.Linear(100, 100, bias=False)
# First check case where all replicas agree. model.weight.data.fill_(1.0) assert util.check_param_hashes_across_dp_replicas([model])
# Now check case where replica 0 disagrees with all other replicas. if rank == 0: model.weight.data.fill_(0.0) param_hashes_match = util.check_param_hashes_across_dp_replicas([model]) expected_param_hashes_match = (rank == 0) assert param_hashes_match == expected_param_hashes_match
# Teardown. _deinit_distributed()
def test_straggler_detector(): world = int(os.getenv('WORLD_SIZE', '1')) rank = int(os.getenv('RANK', '0')) master = os.getenv('MASTER_ADDR', 'localhost') port = 65535
# Checks if the instance is disabled. def straggler_detector_disabled(): assert stimer.enabled == False
# Checks if the instance is enabled. def straggler_detector_enabled(): assert stimer.enabled == True
# Enable. def straggler_detector_enable(): if rank == 0: resp = req.urlopen(f"http://{master}:{port}").read().decode().split() assert resp[3] == "ON" # Call the report function, this will propagate the change. stimer.report()
# Time an operation. def straggler_detector_timeit(): s = 2 # Sleep for 2 seconds. M = 20 K = 30 N = 40 mat1 = torch.randn(M, K, device='cuda') mat2 = torch.randn(K, N, device='cuda') # batch_data. with stimer(bdata=True): time.sleep(s) # GEMM. with stimer: res = torch.matmul(mat1, mat2) delta, batch_delta, _, _, _, _, = stimer.elapsed() assert delta > 0.0 assert batch_delta >= s
# Test function to raise ValueError def straggler_value_error(): raise ValueError("Exception value raised")
# Check that exception is not suppressed. def straggler_detector_exception_propagate(): # batch_data with pytest.raises(ZeroDivisionError): with stimer(bdata=True): x = 1 / 0 # non-batch-data with pytest.raises(ValueError, match=r".* value .*"): with stimer(): straggler_value_error()
# Reporting. def straggler_detector_report(): s = 2 # Sleep for 2 seconds. N = 20 P = 30 M = 40 mat1 = torch.randn(N, P, device='cuda') mat2 = torch.randn(P, M, device='cuda') tfp = (N * M) * (2 * P - 1) # Theoretical. iter = 10 # Mock. # batch_data. with stimer(bdata=True): time.sleep(s) # GEMM. with stimer: res = torch.matmul(mat1, mat2) r = stimer.report(total_flops=tfp, log_interval=iter) rb = True if rank == 0 else False assert r == rb
# Start test. # Setup. _init_distributed(world, rank)
# Create a straggler_detector with enabled set to false. stimer = util.StragglerDetector() stimer.configure(world, rank, enabled=False, port=port) # Check if configuration was success. assert stimer.configured == True
# Check if the instance is in disabled state. straggler_detector_disabled() # Enable it now, must call report. straggler_detector_enable() # Check if all ranks have straggler detector enabled. straggler_detector_enabled() # Time some operation. straggler_detector_timeit() # Report only from rank 0. straggler_detector_report() # Check that exception is not suppressed. straggler_detector_exception_propagate()
# Teardown. _deinit_distributed()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytestimport torch
from megatron.core.transformer.moe.moe_utils import permute, unpermutefrom tests.unit_tests.test_utilities import Utilsfrom tests.unit_tests.transformer.moe.test_token_dispatcher import MoEModelTestContainer
class TestAlltoAllDispatcher: def setup_method(self, method): pass
def teardown_method(self, method): Utils.destroy_model_parallel()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.timeout(120) @pytest.mark.parametrize("tp_size,ep_size", [ (1, 8), (8, 1), (4, 2), (1, 1), ]) def test_forward_backward(self, tp_size, ep_size): container = MoEModelTestContainer( tp_size=tp_size, ep_size=ep_size, pp_size=1, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="alltoall", ) container.dispatcher_dropless_test()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.timeout(120) @pytest.mark.parametrize("tp_size,ep_size", [ (1, 8), (8, 1), (4, 2), (1, 1), ]) def test_capacity_forward_backward(self, tp_size, ep_size): container = MoEModelTestContainer( tp_size=tp_size, ep_size=ep_size, pp_size=1, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="alltoall", moe_token_drop_policy="probs", moe_expert_capacity_factor=0.5, moe_pad_expert_input_to_capacity=False, ) container.dispacher_capacity_test()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.timeout(120) @pytest.mark.parametrize("tp_size,ep_size", [ (1, 8), (8, 1), (4, 2), (1, 1) ]) def test_capacity_padding_forward_backward(self, tp_size, ep_size): import time time.sleep(5) container = MoEModelTestContainer( tp_size=tp_size, ep_size=ep_size, pp_size=1, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="alltoall", moe_token_drop_policy="probs", moe_expert_capacity_factor=0.5, moe_pad_expert_input_to_capacity=True, ) container.dispatcher_drop_and_pad_test()
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytestimport torchfrom megatron.core.transformer.moe.moe_utils import clear_aux_losses_tracker
from tests.unit_tests.test_utilities import Utilsfrom tests.unit_tests.transformer.moe.test_token_dispatcher import MoEModelTestContainerfrom megatron.core import parallel_state
class AuxlossTestContainer(MoEModelTestContainer): def partition_input(self, input): partitioned_input = input.chunk(parallel_state.get_tensor_and_context_parallel_world_size(), dim=1)[parallel_state.get_tensor_and_context_parallel_rank()] output = partitioned_input.clone().detach() output.requires_grad = True return output
def aux_loss_test(self, input, baseline_grad): partitioned_input = self.partition_input(input) moe_layer = self.moe_layer probs, indices = moe_layer.router(partitioned_input) probs.sum().mul_(0).backward() aux_loss_grad = partitioned_input.grad torch.distributed.barrier() ans = self.partition_input(baseline_grad) assert torch.allclose(aux_loss_grad, ans), f"Diff: {(aux_loss_grad/ans).mean()}" loss = parallel_state.get_moe_layer_wise_logging_tracker()['load_balancing_loss'] clear_aux_losses_tracker()
class TestAuxLoss: def setup_method(self, method): baseline_container = AuxlossTestContainer( tp_size=1, ep_size=1, pp_size=1, cp_size=1, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="alltoall", moe_aux_loss_coeff=0.1, ) moe_layer = baseline_container.moe_layer self.input = torch.randn((32, 8, moe_layer.config.hidden_size)).cuda() self.input.requires_grad = True probs, indices = moe_layer.router(self.input) probs.sum().mul_(0).backward() # zero out the main gradients self.baseline_grad = self.input.grad self.input.grad = None clear_aux_losses_tracker()
def teardown_method(self, method): Utils.destroy_model_parallel()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.parametrize("tp_size,ep_size,cp_size", [ (8, 1, 1), (4, 2, 1), (1, 1, 8), (2, 1, 4), (2, 2, 2), ]) def test_allgather_dispatcher(self, tp_size, ep_size, cp_size): container = AuxlossTestContainer( tp_size=tp_size, ep_size=ep_size, pp_size=1, cp_size=cp_size, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="allgather", moe_aux_loss_coeff=0.1, ) container.aux_loss_test(self.input, self.baseline_grad)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.parametrize("tp_size,ep_size,cp_size", [ (8, 1, 1), (4, 2, 1), (1, 1, 8), (2, 1, 4), (2, 2, 2), ]) def test_a2a_dispatcher(self, tp_size, ep_size, cp_size): container = AuxlossTestContainer( tp_size=tp_size, ep_size=ep_size, pp_size=1, cp_size=cp_size, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="alltoall", moe_aux_loss_coeff=0.1, ) container.aux_loss_test(self.input, self.baseline_grad)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytestfrom pkg_resources import packagingfrom importlib.metadata import version
import torchimport torch.nn.functional as F
from megatron.training.arguments import parse_argsfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_specfrom megatron.core.transformer.moe import grouped_gemm_util as ggfrom megatron.core.transformer.moe.moe_layer import MoELayerfrom megatron.core.transformer.moe.experts import TEGroupedMLPfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.training.initialize import _set_random_seedfrom megatron.legacy.model import Float16Modulefrom tests.unit_tests.test_utilities import Utils
DEVICE_CAPABILITY = Noneif torch.cuda.is_available(): DEVICE_CAPABILITY = torch.cuda.get_device_capability()
_te_version = packaging.version.Version(version("transformer-engine"))
class TestParallelGroupedMLP:
def setup_method(self, method, use_cpu_initialization=False, swiglu=True): print("============") print("Test for use_cpu_initilization={} and swiglu={}.".format(use_cpu_initialization, swiglu)) print("============") Utils.initialize_model_parallel(1,1) num_layers = 1 # 2 self.hidden_size = 16 # must be an multiple of 16, otherwise trigger CUTLASS misaligned issue self.num_experts = 2 self.gated_linear_unit = swiglu self.activation_func = F.silu if swiglu else F.gelu self.use_cpu_initialization = use_cpu_initialization
tf_config = TransformerConfig( num_layers=num_layers, hidden_size=self.hidden_size, num_attention_heads=4, num_moe_experts=self.num_experts, use_cpu_initialization=self.use_cpu_initialization, add_bias_linear=False, gated_linear_unit=self.gated_linear_unit, activation_func=self.activation_func, bias_activation_fusion=False, bf16=True, params_dtype=torch.bfloat16, moe_router_load_balancing_type="sinkhorn", moe_router_topk=1)
self.fc1_ffn_hidden_size = tf_config.ffn_hidden_size self.fc2_ffn_hidden_size = tf_config.ffn_hidden_size # If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf if self.gated_linear_unit: self.fc1_ffn_hidden_size *= 2
## Vanilla sequential GEMM # Set random seed for reproducability _set_random_seed(seed_=123, data_parallel_random_init=False) transformer_layer_spec = get_gpt_layer_with_transformer_engine_spec( self.num_experts, moe_grouped_gemm=False) self.sequential_mlp = MoELayer(tf_config, transformer_layer_spec.submodules.mlp.submodules)
self.args = parse_args(ignore_unknown_args=True) self.args.bf16=True # Bias is not supported in grouped gemm currently, thus we disable the # bias in the linear layer. self.args.add_bias_linear=False self.sequential_mlp = Float16Module(self.sequential_mlp, self.args).module print("done intializing for sequential gemm")
## Grouped GEMM _set_random_seed(seed_=123, data_parallel_random_init=False) tf_config.moe_grouped_gemm = True self.grouped_mlp = MoELayer(tf_config) self.grouped_mlp = Float16Module(self.grouped_mlp, self.args).module print("done intializing for grouped gemm")
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): assert isinstance(self.sequential_mlp, MoELayer) assert isinstance(self.grouped_mlp, MoELayer)
num_weights_smm = sum([p.numel() for p in self.sequential_mlp.parameters()]) num_weights_gmm = sum([p.numel() for p in self.grouped_mlp.parameters()])
# For the same hyper-parm model configs except the `moe_grouped_gemm`, # GroupedGEMM and sequential GEMMs should hold the same number of parms. assert num_weights_smm == num_weights_gmm # expected num weights: router linear weights+bias + MLP weights(no bias) of all experts expected_num_weights = \ self.hidden_size * self.num_experts + \ self.hidden_size * (self.fc1_ffn_hidden_size + self.fc2_ffn_hidden_size) * self.num_experts assert num_weights_smm == expected_num_weights
assert torch.equal(self.sequential_mlp.router.weight, self.grouped_mlp.router.weight)
# weight1: [h, num_experts*4h] # weight2: [num_experts*4h, h] assert self.grouped_mlp.experts.weight1.shape[0] == self.hidden_size assert self.grouped_mlp.experts.weight1.shape[1] == self.num_experts * self.fc1_ffn_hidden_size if self.gated_linear_unit: assert self.grouped_mlp.experts.weight2.shape[0] == self.num_experts * self.fc2_ffn_hidden_size assert self.grouped_mlp.experts.weight2.shape[1] == self.hidden_size else: assert self.grouped_mlp.experts.weight1.shape == self.grouped_mlp.experts.weight2.t().shape
def test_weight_init_value_the_same(self): gmm_w1 = self.grouped_mlp.experts.weight1.view(self.num_experts, -1, self.hidden_size) gmm_w2 = self.grouped_mlp.experts.weight2.view(self.num_experts, self.hidden_size, -1) gmm_expert1_fc1 = gmm_w1[0] gmm_expert1_fc2 = gmm_w2[0] gmm_expert2_fc1 = gmm_w1[1] gmm_expert2_fc2 = gmm_w2[1]
smm_expert1_fc1 = self.sequential_mlp.experts.local_experts[0].linear_fc1.weight smm_expert1_fc2 = self.sequential_mlp.experts.local_experts[0].linear_fc2.weight smm_expert2_fc1 = self.sequential_mlp.experts.local_experts[1].linear_fc1.weight smm_expert2_fc2 = self.sequential_mlp.experts.local_experts[1].linear_fc2.weight
assert torch.equal(gmm_expert1_fc1, smm_expert1_fc1) if not self.use_cpu_initialization: assert torch.equal(gmm_expert1_fc2, smm_expert1_fc2) # the param init value is not exactly the same between gmm and smm (refer to test_weight_init_value_the_same.) # TODO: is it necessary to keep smm and gmm share exactly the same init params? # assert torch.equal(gmm_expert2_fc1, smm_expert2_fc1) if self.use_cpu_initialization: assert torch.equal(gmm_expert2_fc2, smm_expert2_fc2)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.skipif( not DEVICE_CAPABILITY or DEVICE_CAPABILITY[0] < 8, reason='GroupedGEMM kernels are not supported on this device.' ) def test_gpu_forward(self): self.sequential_mlp.cuda() self.grouped_mlp.cuda() # [sequence length, batch size, hidden size] seq_len = 3 #32 batch_size = 2 hidden_states = torch.rand( (seq_len, batch_size, self.sequential_mlp.config.hidden_size), dtype=torch.bfloat16) hidden_states = hidden_states.cuda() output_smm, _ = self.sequential_mlp(hidden_states) output_gmm, _ = self.grouped_mlp(hidden_states)
# The following assert fails due to the param init value is not exactly # the same between gmm and smm (refer to test_weight_init_value_the_same.) # assert torch.equal(output_smm, output_gmm)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.skipif( not DEVICE_CAPABILITY or DEVICE_CAPABILITY[0] < 8, reason='GroupedGEMM kernels are not supported on this device.' ) def test_gpu_forward_with_no_tokens_allocated(self): """Test the case when no token is allocated for groupedGEMM kernels.""" w1 = self.grouped_mlp.experts.weight1.view(self.num_experts, -1, self.hidden_size) num_allocated_tokens = 0 tokens_per_expert = torch.zeros(self.num_experts) hidden_states = torch.rand((num_allocated_tokens, self.hidden_size), dtype=torch.bfloat16) hidden_states = hidden_states.cuda() try: gg.ops.gmm(hidden_states, w1, tokens_per_expert, trans_b=False) except Exception as e: print("Expected error message from groupedGEMM:", e) assert str(e) == "Input batch_sizes should not be all zeros!"
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.skipif( not DEVICE_CAPABILITY or DEVICE_CAPABILITY[0] < 8, reason='GroupedGEMM kernels are not supported on this device.' ) def test_gradient_with_no_tokens_allocated(self): """Test that when no token is passed in, the parameters of the grouped MLP will also have gradients.""" self.grouped_mlp.cuda() num_allocated_tokens = 0 tokens_per_expert = torch.zeros(self.num_experts) hidden_states = torch.rand((num_allocated_tokens, self.hidden_size), dtype=torch.bfloat16) hidden_states = hidden_states.cuda() output_gmm, _ = self.grouped_mlp.experts( hidden_states, tokens_per_expert=tokens_per_expert, ) output_gmm.mean().backward() assert self.grouped_mlp.experts.weight1.grad is not None
@pytest.mark.skipif( _te_version < packaging.version.Version("1.9.0.dev0"), reason="TE Grouped MLP is only supported in TE 1.9.0.dev0 and later.",)class TestTEGroupedMLP:
def setup_method(self, method, use_cpu_initialization=False, swiglu=True): Utils.initialize_model_parallel(1, 1) num_layers = 1 self.hidden_size = 16 self.num_experts = 2 self.gated_linear_unit = swiglu self.activation_func = F.silu if swiglu else F.gelu self.use_cpu_initialization = use_cpu_initialization
tf_config = TransformerConfig( num_layers=num_layers, hidden_size=self.hidden_size, num_attention_heads=4, num_moe_experts=self.num_experts, use_cpu_initialization=self.use_cpu_initialization, add_bias_linear=False, gated_linear_unit=self.gated_linear_unit, activation_func=self.activation_func, bias_activation_fusion=False, bf16=True, params_dtype=torch.bfloat16, moe_router_load_balancing_type="sinkhorn", moe_router_topk=1, )
self.fc1_ffn_hidden_size = tf_config.ffn_hidden_size self.fc2_ffn_hidden_size = tf_config.ffn_hidden_size # If using swiglu double the output width, see https://arxiv.org/pdf/2002.05202.pdf if self.gated_linear_unit: self.fc1_ffn_hidden_size *= 2
## Vanilla sequential GEMM # Set random seed for reproducability _set_random_seed(seed_=123, data_parallel_random_init=False) transformer_layer_spec = get_gpt_layer_with_transformer_engine_spec( self.num_experts, moe_grouped_gemm=False ) self.sequential_mlp = MoELayer(tf_config, transformer_layer_spec.submodules.mlp.submodules)
self.args = parse_args(ignore_unknown_args=True) self.args.bf16 = True # Bias is not supported in grouped gemm currently, thus we disable the # bias in the linear layer. self.args.add_bias_linear = False self.sequential_mlp = Float16Module(self.sequential_mlp, self.args).module
## Grouped GEMM _set_random_seed(seed_=123, data_parallel_random_init=False) transformer_layer_spec = get_gpt_layer_with_transformer_engine_spec( self.num_experts, moe_grouped_gemm=True ) tf_config.moe_grouped_gemm = True self.grouped_mlp = MoELayer(tf_config, transformer_layer_spec.submodules.mlp.submodules) assert isinstance(self.grouped_mlp.experts, TEGroupedMLP) self.grouped_mlp = Float16Module(self.grouped_mlp, self.args).module
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): assert isinstance(self.sequential_mlp, MoELayer) assert isinstance(self.grouped_mlp, MoELayer)
num_weights_smm = sum([p.numel() for p in self.sequential_mlp.parameters()]) num_weights_gmm = sum([p.numel() for p in self.grouped_mlp.parameters()])
# For the same hyper-parm model configs except the `moe_grouped_gemm`, # GroupedGEMM and sequential GEMMs should hold the same number of parms. assert num_weights_smm == num_weights_gmm # expected num weights: router linear weights+bias + MLP weights(no bias) of all experts expected_num_weights = ( self.hidden_size * self.num_experts + self.hidden_size * (self.fc1_ffn_hidden_size + self.fc2_ffn_hidden_size) * self.num_experts ) assert num_weights_smm == expected_num_weights
assert torch.equal(self.sequential_mlp.router.weight, self.grouped_mlp.router.weight)
# weights of linear_fc1: [fc1_ffn_hidden_size, hidden_size] # weights of linear_fc2: [hidden_size, fc2_ffn_hidden_size] for i in range(self.num_experts): assert getattr(self.grouped_mlp.experts.linear_fc1, f"weight{i}").shape == ( self.fc1_ffn_hidden_size, self.hidden_size, ) assert getattr(self.grouped_mlp.experts.linear_fc2, f"weight{i}").shape == ( self.hidden_size, self.fc2_ffn_hidden_size, )
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_gpu_forward_backward(self): self.sequential_mlp.cuda() self.grouped_mlp.cuda() # Copy the weights to ensure the same init value with torch.no_grad(): for i in range(self.num_experts): self.sequential_mlp.experts.local_experts[i].linear_fc1.weight.copy_( getattr(self.grouped_mlp.experts.linear_fc1, f"weight{i}") ) self.sequential_mlp.experts.local_experts[i].linear_fc2.weight.copy_( getattr(self.grouped_mlp.experts.linear_fc2, f"weight{i}") ) # [sequence length, batch size, hidden size] seq_len = 32 batch_size = 2 hidden_states = torch.rand( (seq_len, batch_size, self.hidden_size), dtype=torch.bfloat16, device="cuda", requires_grad=True, ) hidden_states.retain_grad()
output_smm, _ = self.sequential_mlp(hidden_states) output_smm.mean().backward() smm_results = [output_smm, hidden_states.grad] for i in range(self.num_experts): smm_results.append(self.sequential_mlp.experts.local_experts[i].linear_fc1.weight.grad) smm_results.append(self.sequential_mlp.experts.local_experts[i].linear_fc2.weight.grad)
hidden_states.grad = None output_gmm, _ = self.grouped_mlp(hidden_states) output_gmm.mean().backward() gmm_results = [output_gmm, hidden_states.grad] for i in range(self.num_experts): gmm_results.append(getattr(self.grouped_mlp.experts.linear_fc1, f"weight{i}").grad) gmm_results.append(getattr(self.grouped_mlp.experts.linear_fc2, f"weight{i}").grad)
for smm_result, gmm_result in zip(smm_results, gmm_results): torch.testing.assert_close(smm_result, gmm_result)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_gpu_forward_backward_with_no_tokens_allocated(self): """Test the case when no token is allocated for groupedGEMM kernels.""" self.grouped_mlp.cuda() num_allocated_tokens = 0 tokens_per_expert = torch.zeros(self.num_experts, dtype=torch.int32) hidden_states = torch.rand((num_allocated_tokens, self.hidden_size), dtype=torch.bfloat16) hidden_states = hidden_states.cuda() output, _ = self.grouped_mlp.experts(hidden_states, tokens_per_expert=tokens_per_expert) assert torch.equal(output, torch.zeros_like(output)) assert output.shape == (num_allocated_tokens, self.hidden_size)
output.mean().backward() for i in range(self.num_experts): assert getattr(self.grouped_mlp.experts.linear_fc1, f"weight{i}").grad is not None assert getattr(self.grouped_mlp.experts.linear_fc2, f"weight{i}").grad is not None
if __name__ == "__main__": for use_cpu_unitilization in [True, False]: for swiglu in [True, False]: GMLP_test = TestParallelGroupedMLP() GMLP_test.setup_method( method=None, use_cpu_initialization=use_cpu_unitilization, swiglu=swiglu) GMLP_test.test_constructor() GMLP_test.test_weight_init_value_the_same() GMLP_test.test_gpu_forward() GMLP_test.test_gpu_forward_with_no_tokens_allocated() GMLP_test.teardown_method(method=None)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.transformer.moe.router import Routerfrom megatron.training.initialize import _set_random_seedfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.transformer.moe.moe_layer import MoELayerfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec
class TestTop2Router: def setup_method(self, method): Utils.initialize_model_parallel(1, 1) _set_random_seed(seed_=123, data_parallel_random_init=False) print("done intializing") num_moe_experts = 4 self.transformer_config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, num_moe_experts=num_moe_experts, use_cpu_initialization=True, moe_router_load_balancing_type="aux_loss", moe_router_topk=2, moe_aux_loss_coeff=0, ) transformer_layer_spec = get_gpt_layer_with_transformer_engine_spec( num_experts=num_moe_experts, moe_grouped_gemm=False ) self.sequential_mlp = MoELayer( self.transformer_config, transformer_layer_spec.submodules.mlp.submodules ) self.router = self.sequential_mlp.router
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): assert isinstance(self.router, Router)
num_weights = sum([p.numel() for p in self.router.parameters()]) assert num_weights == 12 * 4, num_weights
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.parametrize("moe_router_pre_softmax", [ (True), (False), ]) def test_router_forward(self, moe_router_pre_softmax): with torch.no_grad(): self.router = self.router.cuda() self.router.config.moe_router_pre_softmax = moe_router_pre_softmax # [num tokens, hidden size] hidden_states = torch.randn((32, 2, self.router.config.hidden_size)) hidden_states = hidden_states.cuda() scores, indices = self.router(hidden_states) print(scores.shape, indices.shape) assert scores.shape == (64, 2) assert indices.shape == (64, 2) print( (indices == 0).sum(), (indices == 1).sum(), (indices == 2).sum(), (indices == 3).sum() )
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_aux_loss(self): self.sequential_mlp = self.sequential_mlp.cuda() # Without aux loss hidden_states = torch.randn((32, 2, self.router.config.hidden_size)) hidden_states = hidden_states.cuda() out = self.sequential_mlp(hidden_states)[0] out.sum().mul_(0).backward() assert self.sequential_mlp.router.weight.grad.abs().sum() == 0 # With aux loss self.transformer_config.moe_aux_loss_coeff = 1 out = self.sequential_mlp(hidden_states)[0] out.sum().mul_(0).backward() assert self.sequential_mlp.router.weight.grad.abs().sum() > 0 # With Z loss self.transformer_config.moe_aux_loss_coeff = 0 self.transformer_config.moe_z_loss_coeff = 1 self.sequential_mlp.router.weight.grad.fill_(0) out = self.sequential_mlp(hidden_states)[0] out.sum().mul_(0).backward() assert self.sequential_mlp.router.weight.grad.abs().sum() > 012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.transformer.moe.moe_layer import MoELayerfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec
class TestParallelSequentialMLP:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) print("done intializing") num_moe_experts = 2 transformer_config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, num_moe_experts=num_moe_experts, use_cpu_initialization=True, activation_func=torch.nn.functional.silu, gated_linear_unit=True, bias_activation_fusion=True, moe_router_load_balancing_type="sinkhorn", moe_router_topk=1 ) transformer_layer_spec = get_gpt_layer_with_transformer_engine_spec( num_experts=num_moe_experts, moe_grouped_gemm=False) self.sequential_mlp = MoELayer(transformer_config, transformer_layer_spec.submodules.mlp.submodules)
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): assert isinstance(self.sequential_mlp, MoELayer)
num_weights = sum([p.numel() for p in self.sequential_mlp.parameters()]) assert num_weights == 3696
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_gpu_forward(self): sequential_mlp = self.sequential_mlp sequential_mlp.cuda() # [sequence length, batch size, hidden size] hidden_states = torch.ones((32, 2, sequential_mlp.config.hidden_size)) hidden_states = hidden_states.cuda() output, output_bias = sequential_mlp(hidden_states) assert output.shape[0] == 32 assert output.shape[1] == 2 assert output.shape[2] == sequential_mlp.config.hidden_size assert output_bias.shape[2] == sequential_mlp.config.hidden_size assert output.dtype == torch.float32 assert output.device.type == 'cuda' assert output_bias.device.type == 'cuda'
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytestimport torchfrom megatron.core import parallel_state
from megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_specfrom megatron.core.transformer.moe.moe_layer import MoELayerfrom megatron.core.transformer.moe.moe_utils import permute, unpermutefrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.training.initialize import _set_random_seedfrom tests.unit_tests.test_utilities import Utils
class MoEModelTestContainer: def __init__( self, tp_size, ep_size, pp_size, cp_size=1, data_parallel_random_init=False, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="alltoall", moe_expert_capacity_factor=None, moe_pad_expert_input_to_capacity=False, moe_aux_loss_coeff=0.1, **kwargs, ): self.num_local_experts = num_moe_experts // ep_size Utils.initialize_model_parallel( tensor_model_parallel_size=tp_size, pipeline_model_parallel_size=pp_size, expert_model_parallel_size=ep_size, context_parallel_size=cp_size ) _set_random_seed(seed_=123, data_parallel_random_init=data_parallel_random_init) local_expert_indices_offset = ( parallel_state.get_expert_model_parallel_rank() * self.num_local_experts ) self.local_expert_indices = [ local_expert_indices_offset + i for i in range(self.num_local_experts) ]
self.config = TransformerConfig( tensor_model_parallel_size=tp_size, expert_model_parallel_size=ep_size, pipeline_model_parallel_size=pp_size, context_parallel_size=cp_size, moe_router_topk=moe_router_topk, num_moe_experts=num_moe_experts, moe_router_load_balancing_type=moe_router_load_balancing_type, moe_token_dispatcher_type=moe_token_dispatcher_type, moe_expert_capacity_factor=moe_expert_capacity_factor, moe_pad_expert_input_to_capacity=moe_pad_expert_input_to_capacity, moe_aux_loss_coeff=moe_aux_loss_coeff, num_layers=1, moe_extended_tp=kwargs.get("moe_extended_tp", False), moe_grouped_gemm=kwargs.get("moe_grouped_gemm", False), hidden_size=kwargs.get("hidden_size", 1024), num_attention_heads=kwargs.get("num_attention_heads", 8), use_cpu_initialization=kwargs.get("use_cpu_initialization", True), sequence_parallel=tp_size > 1, add_bias_linear=kwargs.get("add_bias_linear", False), )
# init moe layer transformer_layer_spec = get_gpt_layer_with_transformer_engine_spec( num_experts=num_moe_experts, moe_grouped_gemm=kwargs.get("moe_grouped_gemm", False) ) self.moe_layer = MoELayer( self.config, transformer_layer_spec.submodules.mlp.submodules ).cuda() self.moe_layer.set_layer_number(0) def __del__(self): torch.distributed.barrier() torch.cuda.synchronize() Utils.destroy_model_parallel()
def dispatcher_dropless_test(self): moe_layer = self.moe_layer bs = 32 seql = 8 hidden_states = torch.randn((bs, seql, moe_layer.config.hidden_size)) hidden_states = hidden_states.cuda() hidden_states.requires_grad = True probs, indices = moe_layer.router(hidden_states) probs = torch.ones_like(probs) / moe_layer.router.topk
## Uncomment these lines to assist in bug location. # hidden_states = torch.ones_like(hidden_states) * torch.distributed.get_rank() # hidden_states.requires_grad = True # indices = torch.ones_like(indices) * torch.distributed.get_rank() # print(permuted_local_hidden_states)
( permuted_local_hidden_states, tokens_per_expert, ) = moe_layer.token_dispatcher.token_permutation( hidden_states, probs, indices )
permuted_local_hidden_states /= moe_layer.config.tensor_model_parallel_size
restored_hidden_states, restored_bias = moe_layer.token_dispatcher.token_unpermutation( permuted_local_hidden_states )
assert torch.allclose( restored_hidden_states, hidden_states ), "Restored hidden states do not match original hidden states"
# check if the grad of the hidden states is same as the hidden states torch.autograd.backward(restored_hidden_states, restored_hidden_states) assert torch.allclose( hidden_states.grad, hidden_states ), "Gradient of hidden states should be same as hidden states"
def dispacher_capacity_test(self): moe_layer = self.moe_layer hidden_states = torch.randn((256, moe_layer.config.hidden_size)) hidden_states = hidden_states.cuda() hidden_states.requires_grad = True probs, indices = moe_layer.router(hidden_states) tp_size = moe_layer.config.tensor_model_parallel_size tp_rank = parallel_state.get_tensor_model_parallel_rank()
# Create the answer. prob_mask = probs != 0 probs = torch.ones_like(probs) * prob_mask / moe_layer.router.topk local_probss = probs[ probs.size(0) // tp_size * (tp_rank) : probs.size(0) // tp_size * (tp_rank + 1) ] restored_hidden_states_answer = hidden_states * local_probss.sum(dim=1).unsqueeze(1)
( permuted_local_hidden_states, tokens_per_expert, ) = moe_layer.token_dispatcher.token_permutation( hidden_states, probs, indices )
print(f"Dispatched tokens per expert: {tokens_per_expert}")
permuted_local_hidden_states /= moe_layer.config.tensor_model_parallel_size
restored_hidden_states, restored_bias = moe_layer.token_dispatcher.token_unpermutation( permuted_local_hidden_states ) assert torch.allclose( restored_hidden_states, restored_hidden_states_answer ), "Restored hidden states does not match"
# check if the grad of the hidden states is same as the hidden states torch.autograd.backward(restored_hidden_states, hidden_states) assert torch.allclose( hidden_states.grad, restored_hidden_states_answer ), "Gradient of hidden states should be same as hidden states"
def dispatcher_drop_and_pad_test(self): "Test if the tokens are dropped and padded correctly" moe_layer = self.moe_layer hidden_states = torch.randn((256, moe_layer.config.hidden_size)).cuda() hidden_states.requires_grad = True
# Create the answer. moe_layer.config.moe_pad_expert_input_to_capacity = False moe_layer.token_dispatcher.drop_and_pad = False
# Uncomment these lines to help bug location. # hidden_states = torch.ones((8, moe_layer.config.hidden_size)).cuda() # hidden_states = hidden_states * torch.range(1, 8).unsqueeze(1).cuda() # hidden_states.requires_grad = True # indices_1 = torch.tensor([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7]]).cuda() # probs_1 = torch.ones_like(indices_1) # indices_2 = torch.tensor([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7]]).cuda() # probs_2 = torch.ones_like(indices_2) # num_local_tokens_per_expert = torch.tensor([2, 2, 2, 2, 2, 2, 2, 2]).cuda()
probs_1, indices_1 = moe_layer.router(hidden_states) (permuted_input_1, tokens_per_expert,) = moe_layer.token_dispatcher.token_permutation( hidden_states, probs_1, indices_1 ) torch.distributed.barrier() forward_answer, restored_bias = moe_layer.token_dispatcher.token_unpermutation( permuted_input_1 ) torch.autograd.backward(forward_answer, forward_answer) backward_answer = hidden_states.grad.clone() hidden_states.grad = None torch.cuda.synchronize() moe_layer.token_dispatcher.drop_and_pad = True moe_layer.config.moe_pad_expert_input_to_capacity = True # End
probs_2, indices_2 = moe_layer.router(hidden_states) (permuted_input_2, tokens_per_expert,) = moe_layer.token_dispatcher.token_permutation( hidden_states, probs_2, indices_2 ) restored_hidden_states, restored_bias = moe_layer.token_dispatcher.token_unpermutation( permuted_input_2 ) torch.distributed.barrier() assert torch.allclose( restored_hidden_states, forward_answer ), "Restored hidden states does not match"
# check if the grad of the hidden states is same as the hidden states torch.autograd.backward(restored_hidden_states, restored_hidden_states) assert torch.allclose( hidden_states.grad, backward_answer ), "Gradient of hidden states should be same as hidden states"
def set_params(self): # TODO: Set consistent parameters for various parallelisms. raise NotImplementedError
def destroy(self): Utils.destroy_model_parallel()
class TestAllgatherDispatcher: def setup_method(self, method): pass
def teardown_method(self, method): Utils.destroy_model_parallel()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") @pytest.mark.parametrize("tp_size,ep_size", [ (8, 1), ]) def test_forward_backward(self, tp_size, ep_size): container = MoEModelTestContainer( tp_size=tp_size, ep_size=ep_size, pp_size=1, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="allgather", ) container.dispatcher_dropless_test()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_extended_tp_forward_backward(self): container = MoEModelTestContainer( tp_size=2, ep_size=4, pp_size=1, num_moe_experts=8, moe_router_topk=2, moe_router_load_balancing_type="aux_loss", moe_token_dispatcher_type="allgather", sequence_parallel=True, moe_extended_tp=True, moe_grouped_gemm=True, use_cpu_initialization=False, ) moe_layer = container.moe_layer # [bs, seql, hidden size] hidden_states = torch.randn((32, 8, moe_layer.router.config.hidden_size)) hidden_states = hidden_states.cuda() hidden_states.requires_grad = True scores, indices = moe_layer.router(hidden_states) assert scores.shape == (256, moe_layer.router.topk), "Scores shape is not correct" assert indices.shape == (256, moe_layer.router.topk), "Indices shape is not correct" scores = torch.ones_like(scores) / 2 ( permuted_local_hidden_states, tokens_per_expert, ) = moe_layer.token_dispatcher.token_permutation(hidden_states, scores, indices) permuted_local_hidden_states /= moe_layer.config.tensor_model_parallel_size * moe_layer.config.expert_model_parallel_size restored_hidden_states, restored_bias = moe_layer.token_dispatcher.token_unpermutation( permuted_local_hidden_states, bias=torch.zeros_like(permuted_local_hidden_states), )
assert torch.allclose( restored_hidden_states, hidden_states ), "Restored hidden states do not match original hidden states"
# check if the grad of the hidden states is same as the hidden states torch.autograd.backward(restored_hidden_states, restored_hidden_states) assert torch.allclose( hidden_states.grad, hidden_states ), "Gradient of hidden states should be same as hidden states" container.destroy()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.transformer.attention import SelfAttentionfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec
class TestParallelAttention:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) self.transformer_config = TransformerConfig(num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True) self.parallel_attention = SelfAttention(self.transformer_config, get_gpt_layer_with_transformer_engine_spec().submodules.self_attention.submodules, layer_number=1)
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): assert isinstance(self.parallel_attention, SelfAttention) assert self.parallel_attention.layer_number == 1
num_weights = sum([p.numel() for p in self.parallel_attention.parameters()]) assert num_weights == 648
def test_cpu_forward(self): # we can't currently do this because the global memory buffer is on GPU pass
def test_gpu_forward(self):
config = self.parallel_attention.config sequence_length = 32 micro_batch_size = 2
self.parallel_attention.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones((sequence_length, micro_batch_size, self.parallel_attention.config.hidden_size)) hidden_states = hidden_states.cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda()
output, bias = self.parallel_attention(hidden_states, attention_mask)
assert config.recompute_granularity is None assert output.shape[0] == sequence_length assert output.shape[1] == micro_batch_size assert output.shape[2] == config.hidden_size assert bias.shape[0] == config.hidden_size
def test_fused_rope_gpu_forward(self): self.parallel_attention.config.apply_rope_fusion = True config = self.parallel_attention.config sequence_length = 32 micro_batch_size = 2
self.parallel_attention.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones((sequence_length, micro_batch_size, self.parallel_attention.config.hidden_size)) hidden_states = hidden_states.cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda() rotary_pos_emb = torch.ones(sequence_length, 1, 1, self.parallel_attention.config.kv_channels).cuda() output, bias = self.parallel_attention(hidden_states, attention_mask, rotary_pos_emb=rotary_pos_emb)
assert config.recompute_granularity is None assert output.shape[0] == sequence_length assert output.shape[1] == micro_batch_size assert output.shape[2] == config.hidden_size assert bias.shape[0] == config.hidden_size self.parallel_attention.config.apply_rope_fusion = False
def test_checkpointed_gpu_forward(self): transformer_config = self.transformer_config transformer_config.recompute_granularity='selective' checkpointed_parallel_attention = SelfAttention(transformer_config, get_gpt_layer_with_transformer_engine_spec().submodules.self_attention.submodules, layer_number=1) config = checkpointed_parallel_attention.config
sequence_length = 32 micro_batch_size = 2
checkpointed_parallel_attention.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones( (sequence_length, micro_batch_size, checkpointed_parallel_attention.config.hidden_size) ) hidden_states = hidden_states.cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda()
output, bias = checkpointed_parallel_attention(hidden_states, attention_mask)
assert config.recompute_granularity == 'selective' assert output.shape[0] == sequence_length assert output.shape[1] == micro_batch_size assert output.shape[2] == config.hidden_size assert bias.shape[0] == config.hidden_size123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.packed_seq_params import PackedSeqParamsfrom megatron.core.transformer.attention import SelfAttentionfrom megatron.core.transformer.enums import AttnMaskTypefrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec
# Note: this test requires TE >= 0.13 as well as Flash Attention to run# FIXME this unit test doesn't work in the current test container. to be fixed soon"""def make_test_packed_seq_params(sequence_length): cu_seqlens = torch.IntTensor([0, 6, 19, 22, sequence_length]).cuda() seqlens = cu_seqlens[1:] - cu_seqlens[:-1] max_seqlen, _ = seqlens.max(dim=0, keepdim=True) packed_seq_params = PackedSeqParams( cu_seqlens_q=cu_seqlens, cu_seqlens_kv=cu_seqlens, max_seqlen_q=max_seqlen, max_seqlen_kv=max_seqlen, qkv_format='thd', ) return packed_seq_params
class TestParallelAttentionWithPackedSequence:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) # use BF16 and a large enough hidden size to enable FlashAttention for thd format. self.transformer_config = TransformerConfig(num_layers=2, hidden_size=64, num_attention_heads=4, use_cpu_initialization=True, bf16=True, params_dtype=torch.bfloat16, pipeline_dtype=torch.bfloat16, autocast_dtype=torch.bfloat16) self.parallel_attention = SelfAttention(self.transformer_config, get_gpt_layer_with_transformer_engine_spec().submodules.self_attention.submodules, layer_number=1, attn_mask_type=AttnMaskType.causal)
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_cpu_forward(self): # we can't currently do this because the global memory buffer is on GPU pass
def test_gpu_forward(self):
config = self.parallel_attention.config sequence_length = 32 micro_batch_size = 1
self.parallel_attention.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones((sequence_length, micro_batch_size, self.parallel_attention.config.hidden_size)) hidden_states = hidden_states.cuda().to(torch.bfloat16)
attention_mask = None
packed_seq_params = make_test_packed_seq_params(sequence_length) output, bias = self.parallel_attention(hidden_states, attention_mask, packed_seq_params=packed_seq_params)
assert config.recompute_granularity is None assert output.shape[0] == sequence_length assert output.shape[1] == micro_batch_size assert output.shape[2] == config.hidden_size assert bias.shape[0] == config.hidden_size
def test_fused_rope_gpu_forward(self): self.parallel_attention.config.apply_rope_fusion = True config = self.parallel_attention.config sequence_length = 32 micro_batch_size = 1
self.parallel_attention.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones((sequence_length, micro_batch_size, self.parallel_attention.config.hidden_size)) hidden_states = hidden_states.cuda().to(torch.bfloat16)
attention_mask = None rotary_pos_emb = torch.ones(sequence_length, 1, 1, self.parallel_attention.config.kv_channels).cuda() packed_seq_params = make_test_packed_seq_params(sequence_length) output, bias = self.parallel_attention(hidden_states, attention_mask, packed_seq_params=packed_seq_params)
assert config.recompute_granularity is None assert output.shape[0] == sequence_length assert output.shape[1] == micro_batch_size assert output.shape[2] == config.hidden_size assert bias.shape[0] == config.hidden_size self.parallel_attention.config.apply_rope_fusion = False
def test_checkpointed_gpu_forward(self): transformer_config = self.transformer_config transformer_config.recompute_granularity='selective' checkpointed_parallel_attention = SelfAttention(transformer_config, get_gpt_layer_with_transformer_engine_spec().submodules.self_attention.submodules, layer_number=1, attn_mask_type=AttnMaskType.causal) config = checkpointed_parallel_attention.config
sequence_length = 32 micro_batch_size = 1
checkpointed_parallel_attention.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones( (sequence_length, micro_batch_size, checkpointed_parallel_attention.config.hidden_size) ) hidden_states = hidden_states.cuda().to(torch.bfloat16)
attention_mask = None
packed_seq_params = make_test_packed_seq_params(sequence_length) output, bias = checkpointed_parallel_attention(hidden_states, attention_mask, packed_seq_params=packed_seq_params)
assert config.recompute_granularity == 'selective' assert output.shape[0] == sequence_length assert output.shape[1] == micro_batch_size assert output.shape[2] == config.hidden_size assert bias.shape[0] == config.hidden_size"""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.transformer.attention import CrossAttention"""
@pytest.fixturedef core_attention(transformer_config): return CrossAttention(transformer_config)
class TestCoreAttention: def test_constructor(self, core_attention): assert isinstance(core_attention, CrossAttention) assert core_attention.layer_number == 1
num_weights = sum([p.numel() for p in core_attention.parameters()]) assert num_weights == 0
def test_cpu_forward(self, core_attention): # we can't currently do this because the global memory buffer is on GPU pass
def test_gpu_forward(self, core_attention):
# destroy_global_memory_buffer() # _set_global_memory_buffer() # model_parallel_cuda_manual_seed(123)
core_attention.cuda() config = core_attention.config sequence_length = 32 micro_batch_size = 2 # query_layer (float): [sequence_length, micro_batch_size, num_attention_heads, hidden_size / num_attention_heads] query_layer = torch.ones( ( sequence_length, micro_batch_size, config.num_attention_heads, config.hidden_size // config.num_attention_heads, ) ).cuda()
key_layer = torch.ones_like(query_layer).cuda()
value_layer = torch.ones_like(query_layer).cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda()
context_layer = core_attention( query_layer=query_layer, key_layer=key_layer, value_layer=value_layer, attention_mask=attention_mask )
assert context_layer.shape[0] == sequence_length assert context_layer.shape[1] == micro_batch_size assert context_layer.shape[2] == config.hidden_size assert context_layer.device.type == 'cuda' assert context_layer.dtype == torch.float32
"""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.transformer.mlp import MLPfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_local_spec
class TestParallelMLP:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) transformer_config = TransformerConfig(num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True) self.mlp = MLP(transformer_config, get_gpt_layer_local_spec().submodules.mlp.submodules)
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): assert isinstance(self.mlp, MLP)
num_weights = sum([p.numel() for p in self.mlp.parameters()]) assert num_weights == 1212
""" def test_cpu_forward(self, mlp): # [sequence length, micro batch size, hidden size] hidden_states = torch.ones((32, 2, mlp.config.hidden_size)) output, output_bias = mlp(hidden_states) assert output.shape[0] == 32 assert output.shape[1] == 2 assert output.shape[2] == mlp.config.hidden_size assert output_bias.shape[0] == mlp.config.hidden_size assert output.dtype == torch.float32 """
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_gpu_forward(self): mlp = self.mlp mlp.cuda() # [sequence length, batch size, hidden size] hidden_states = torch.ones((32, 2, mlp.config.hidden_size)) hidden_states = hidden_states.cuda() output, output_bias = mlp(hidden_states) assert output.shape[0] == 32 assert output.shape[1] == 2 assert output.shape[2] == mlp.config.hidden_size assert output_bias.shape[0] == mlp.config.hidden_size assert output.dtype == torch.float32 assert output.device.type == 'cuda' assert output_bias.device.type == 'cuda'
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core.transformer.module import Float16Module, MegatronModulefrom megatron.core.transformer.transformer_config import TransformerConfigfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed
DEVICE_CAPABILITY = Noneif torch.cuda.is_available(): DEVICE_CAPABILITY = torch.cuda.get_device_capability()
class DummyModule(MegatronModule): # def __init__(self, config: TransformerConfig, share_embeddings_and_output_weights=True): def __init__(self, config: TransformerConfig): super().__init__(config)
self.linear = torch.nn.modules.Linear(in_features=2, out_features=1)
def forward(self, x): return self.linear(x)
class TestMegatronModule:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) transformer_config = TransformerConfig(num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True) self.megatron_module = DummyModule(config=transformer_config).cuda()
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_megatron_module(self): megatron_module = self.megatron_module assert megatron_module assert megatron_module.config.hidden_size == 12 assert megatron_module.config.ffn_hidden_size == 48 assert megatron_module.linear.weight.dtype == torch.float32
x = torch.ones((2, 2)).cuda() assert megatron_module(x).dtype == torch.float32
# TODO: test bad configs actually fail # failed_module = megatron_module # failed_module.fp16 = True # failed_module.bf16 = True
class TestFloat16Module:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) self.transformer_config = TransformerConfig(num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True) self.megatron_module = DummyModule(config=self.transformer_config).cuda()
def teardown_method(self, method): Utils.destroy_model_parallel() def test_fp16_module(self): transformer_config = self.transformer_config megatron_module = self.megatron_module transformer_config.fp16 = True fp16_module = Float16Module(config=transformer_config, module=megatron_module)
assert fp16_module assert fp16_module.config.hidden_size == 12 assert fp16_module.config.ffn_hidden_size == 48 assert fp16_module.module.linear.weight.dtype == torch.float16
x = torch.ones((2, 2)).cuda() # inputs are converted to fp16 then outputs are converted to fp32 assert fp16_module(x).dtype == torch.float32
pytest.mark.skipif( not DEVICE_CAPABILITY or DEVICE_CAPABILITY[0] < 8, reason='bfloat16 is not supported on this device' )
def test_bf16_module(self): transformer_config = self.transformer_config megatron_module = self.megatron_module transformer_config.bf16 = True bf16_module = Float16Module(config=transformer_config, module=megatron_module)
assert bf16_module assert bf16_module.config.hidden_size == 12 assert bf16_module.config.ffn_hidden_size == 48 assert bf16_module.module.linear.weight.dtype == torch.bfloat16
x = torch.ones((2, 2)).cuda() # inputs are converted to bf16 then outputs are converted to fp32 assert bf16_module(x).dtype == torch.float32
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import torchimport types
from megatron.core.models.retro import RetroConfig, get_retro_decoder_block_specfrom megatron.core.models.retro.decoder_attention import ( RetroDecoderCrossAttention, RetroDecoderBiasDropoutAdd,)from megatron.core.models.retro.encoder_attention import ( RetroEncoderCrossAttention, RetroEncoderBiasDropoutAdd, RetroEncoderLayerNorm,)from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.transformer.transformer_block import TransformerBlockfrom tests.unit_tests.test_utilities import Utils
class TestRetroAttention:
@classmethod def get_config(cls): return RetroConfig( num_layers=12, hidden_size=16, num_attention_heads=4, use_cpu_initialization=True, retro_num_neighbors=2, retro_chunk_length=4, retro_retrieved_length=8, retro_split_preprocessing="98,2,0", )
@classmethod def get_modules(cls, config, use_transformer_engine, use_gpu):
# Retro decoder layer. decoder_block_spec = get_retro_decoder_block_spec( config, use_transformer_engine=use_transformer_engine) decoder_block = TransformerBlock(config=config, spec=decoder_block_spec) decoder_layers = [ layer for layer in decoder_block.layers if isinstance(layer.cross_attention, RetroDecoderCrossAttention) ] decoder_layer = decoder_layers[0]
# Retro encoder layer. encoder_block = decoder_layer.cross_attention.encoder encoder_layers = [ layer for layer in encoder_block.layers if isinstance(layer.cross_attention, RetroEncoderCrossAttention) ] encoder_layer = encoder_layers[0]
# Modules. modules = types.SimpleNamespace( decoder_attn = decoder_layer.cross_attention, decoder_bda = decoder_layer.cross_attn_bda, encoder_attn = encoder_layer.cross_attention, encoder_bda = encoder_layer.cross_attn_bda, encoder_norm = encoder_layer.pre_mlp_layernorm, )
# GPU. if use_gpu: [ m.cuda() for m in vars(modules).values() ]
return modules
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123)
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self):
config = self.get_config() modules = self.get_modules( config, use_transformer_engine=True, use_gpu=False, )
assert isinstance(modules.decoder_attn, RetroDecoderCrossAttention) assert isinstance(modules.decoder_bda, RetroDecoderBiasDropoutAdd) assert isinstance(modules.encoder_attn, RetroEncoderCrossAttention) assert isinstance(modules.encoder_bda, RetroEncoderBiasDropoutAdd) assert isinstance(modules.encoder_norm, RetroEncoderLayerNorm)
assert modules.decoder_attn.attn.layer_number == 6 assert modules.encoder_attn.attn.layer_number == 1
get_nparams = lambda m : sum(p.numel() for p in m.parameters()) assert get_nparams(modules.decoder_attn) == 8768 assert get_nparams(modules.decoder_bda) == 0 assert get_nparams(modules.encoder_attn) == 1088 assert get_nparams(modules.encoder_bda) == 0 assert get_nparams(modules.encoder_norm) == 32
def test_cpu_forward(self): # we can't currently do this because the global memory buffer is on GPU pass
def run_gpu_forward(self, recompute_granularity, use_transformer_engine):
config = self.get_config() config.recompute_granularity = recompute_granularity modules = self.get_modules(config, use_transformer_engine, use_gpu=True)
seq_length = 32 micro_batch_size = 2 n_chunks_per_sample = seq_length // config.retro_chunk_length
# Init tensors. hidden_states = torch.ones(( seq_length, micro_batch_size, config.hidden_size, )).cuda() attention_mask = None decoder_context = torch.ones(( config.retro_retrieved_length, config.retro_num_neighbors * micro_batch_size * n_chunks_per_sample, config.hidden_size, )).cuda() encoder_context = torch.ones(( config.retro_chunk_length, micro_batch_size * n_chunks_per_sample, config.hidden_size, )).cuda()
# Forward decoder. decoder_attn_output = modules.decoder_attn( hidden_states, attention_mask, decoder_context, ) with torch.enable_grad(): decoder_bda_output = modules.decoder_bda(True, True)( decoder_attn_output, hidden_states, config.hidden_dropout, )
# Forward encoder. encoder_attn_output_tuples = modules.encoder_attn( decoder_context, None, encoder_context, ) with torch.enable_grad(): encoder_bda_output = modules.encoder_bda(True, True)( encoder_attn_output_tuples, decoder_context, config.retro_encoder_hidden_dropout, ) encoder_norm_output = modules.encoder_norm(encoder_bda_output)
# Verify decoder. assert set(decoder_attn_output.keys()) == set([ "ns", "bs", "d", "l", "pad", "attention_output", "attention_bias", "context"]) assert decoder_attn_output["ns"] == seq_length assert decoder_attn_output["bs"] == micro_batch_size assert decoder_attn_output["d"] == config.hidden_size assert decoder_attn_output["l"] == n_chunks_per_sample assert decoder_attn_output["pad"] == 3 assert tuple(decoder_attn_output["attention_output"].shape) == ( config.retro_chunk_length, micro_batch_size * n_chunks_per_sample, config.hidden_size, ) assert tuple(decoder_attn_output["attention_bias"].shape) == ( config.hidden_size, ) assert decoder_attn_output["context"].shape == ( config.retro_retrieved_length * config.retro_num_neighbors, micro_batch_size * n_chunks_per_sample, config.hidden_size, ) assert decoder_bda_output.shape == hidden_states.shape
# Verify encoder. assert len(encoder_attn_output_tuples) == config.retro_num_neighbors for output, bias, residual in encoder_attn_output_tuples: assert tuple(output.shape) == ( config.retro_retrieved_length, micro_batch_size * n_chunks_per_sample, config.hidden_size, ) assert tuple(bias.shape) == (config.hidden_size,) assert tuple(residual.shape) == ( config.retro_retrieved_length, micro_batch_size * n_chunks_per_sample, config.hidden_size, ) assert encoder_bda_output.shape == ( config.retro_retrieved_length, config.retro_num_neighbors * micro_batch_size * n_chunks_per_sample, config.hidden_size, ) assert encoder_norm_output.shape == ( config.retro_retrieved_length, config.retro_num_neighbors * micro_batch_size * n_chunks_per_sample, config.hidden_size, )
def test_gpu_forward(self): for recompute_granularity in (None, 'selective'): for use_transformer_engine in (True, False): self.run_gpu_forward(recompute_granularity, use_transformer_engine)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
import pytestimport torch
from megatron.core.models.common.embeddings.rotary_pos_embedding import RotaryEmbeddingfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom tests.unit_tests.test_utilities import Utils
class TestRotaryEmbedding: def setup_method(self): Utils.initialize_model_parallel(1, 1) model_parallel_cuda_manual_seed(123) self.kv_channels = 8 self.rotary_percent = 1.0 self.rope_cpu_init = RotaryEmbedding( self.kv_channels, self.rotary_percent, use_cpu_initialization=True ) self.rope_gpu_init = RotaryEmbedding( self.kv_channels, self.rotary_percent, use_cpu_initialization=False )
def teardown_method(self, method): Utils.destroy_model_parallel()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_constructor(self): assert isinstance(self.rope_cpu_init, RotaryEmbedding) assert self.rope_cpu_init.inv_freq.device.type == 'cpu' assert isinstance(self.rope_gpu_init, RotaryEmbedding) assert self.rope_gpu_init.inv_freq.device.type == 'cuda'
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_gpu_forward(self): output = self.rope_gpu_init(64) assert output.shape[0] == 64 assert output.shape[1] == 1 assert output.shape[2] == 1 assert output.shape[3] == self.kv_channels assert output.dtype == torch.float32 assert output.device.type == 'cuda'
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") def test_cpu_forward(self): output = self.rope_cpu_init(64) assert output.shape[0] == 64 assert output.shape[1] == 1 assert output.shape[2] == 1 assert output.shape[3] == self.kv_channels assert output.dtype == torch.float32 assert output.device.type == 'cuda'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import sysfrom dataclasses import dataclass, fieldsfrom importlib.metadata import version
import pytestimport torchimport transformer_engine as tefrom pkg_resources import packaging
from megatron.core.fusions.fused_bias_dropout import get_bias_dropout_addfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_local_specfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.transformer.attention import SelfAttention, SelfAttentionSubmodulesfrom megatron.core.transformer.custom_layers.transformer_engine import ( TEDotProductAttention, TELayerNormColumnParallelLinear, TENorm, TERowParallelLinear,)from megatron.core.transformer.dot_product_attention import DotProductAttentionfrom megatron.core.transformer.enums import AttnMaskTypefrom megatron.core.transformer.identity_op import IdentityFuncOp, IdentityOpfrom megatron.core.transformer.spec_utils import ModuleSpec, build_module, import_modulefrom megatron.core.transformer.transformer_block import TransformerBlock, TransformerBlockSubmodulesfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.transformer.transformer_layer import TransformerLayer, TransformerLayerSubmodulesfrom tests.unit_tests.test_utilities import Utils
class TestSpecCustomization: def setup_method(self, method): Utils.initialize_model_parallel(1, 1) model_parallel_cuda_manual_seed(123) self.config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True )
# specify Transformer Layer spec with all identity ops self.transformer_layer_spec = TransformerLayerSubmodules()
# specify attention spec using already imported class self.attention_spec = ModuleSpec( module=SelfAttention, params={"attn_mask_type": AttnMaskType.causal}, submodules=SelfAttentionSubmodules( linear_qkv=TELayerNormColumnParallelLinear, core_attention=TEDotProductAttention, linear_proj=TERowParallelLinear, q_layernorm=IdentityOp, k_layernorm=IdentityOp, ), )
# specify layernorm spec with module path to test dynamic importing self.layernorm_spec = ModuleSpec( module=("megatron.core.transformer.custom_layers.transformer_engine", "TENorm"), )
# specify bias dropout add with module path self.bda_spec = ModuleSpec( module=("megatron.core.fusions.fused_bias_dropout", "get_bias_dropout_add") )
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_import_module(self): self_attention_cls = import_module( module_path=('megatron.core.transformer.attention', 'SelfAttention') ) assert id(self_attention_cls) == id(SelfAttention)
layernorm_cls = import_module(module_path=self.layernorm_spec.module) assert id(layernorm_cls) == id(TENorm)
def test_build_module(self): # Check NoOp TransformerLayer random_input = 12 noop_transformer_layer = [ build_module(getattr(self.transformer_layer_spec, field.name)) for field in fields(self.transformer_layer_spec) if field.name != 'sharded_state_dict_keys_map' ]
x = random_input for mod in noop_transformer_layer: # checking for `IdentityFuncOp` before `IdentityOp` because former # is derived from the latter and so the second if statement will # always be `True`. if isinstance(mod, IdentityFuncOp): x = mod()(x) elif isinstance(mod, IdentityOp): x = mod(x)
assert x == random_input
# Check SelfAttention self_attention = build_module(self.attention_spec, config=self.config, layer_number=1,) assert isinstance(self_attention, SelfAttention) assert self_attention.layer_number == 1 assert self_attention.attn_mask_type == self.attention_spec.params['attn_mask_type']
num_weights = sum([p.numel() for p in self_attention.parameters()]) assert num_weights == 648
# Check SelfAttention but with already initialized module # `self_attention`. In this test, `build_module` acts as a no op as it # simply returns the initialized module. # NOTE: (sudhakars) Uncomment this test once this feature gets added # back. # self_attention2 = build_module( # self_attention, config=self.config, spec=self.attention_spec, # ) # assert isinstance(self_attention2, SelfAttention) # assert self_attention2.layer_number == 1 # assert self_attention2.attn_mask_type == self.attention_spec.params['attn_mask_type']
# num_weights = sum([p.numel() for p in self_attention2.parameters()]) # assert num_weights == 648
# Check LayerNorm layernorm = build_module( self.layernorm_spec, config=self.config, hidden_size=self.config.hidden_size, eps=self.config.layernorm_epsilon, ) assert isinstance(layernorm, te.pytorch.LayerNorm)
# Check BiasDropoutAdd bda_op = build_module(self.bda_spec) assert id(bda_op) == id(get_bias_dropout_add)
def test_sliding_window_attention(self): te_version = packaging.version.Version(version("transformer-engine")) if te_version < packaging.version.Version("1.2.0"): print("SWA not tested because TE version is not >= 1.2.0", file=sys.stderr) return
config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True, window_size=[10, 0], ) # Make sure DotProductAttention throws (swa unsupported). threw = False try: attn = DotProductAttention( config, layer_number=1, attn_mask_type=AttnMaskType.causal, attention_type='self' ) except: threw = True finally: assert threw, 'Expected DotProductAttention to throw exception for SWA'
# Test TEDotProductAttention attn = TEDotProductAttention( config, layer_number=1, attn_mask_type=AttnMaskType.causal, attention_type='self' ) # Make sure window-size is what we expect. assert attn.window_size == config.window_size
# Single integer window-size unsupported, make sure it throws threw = False try: config.window_size = 11 attn = TEDotProductAttention( config, layer_number=1, attn_mask_type=AttnMaskType.causal, attention_type='self' ) except: threw = True finally: assert threw, "Expected TEDotProductAttention to throw for integer window-size"
# `None` makes this causal. config.window_size = None attn = TEDotProductAttention( config, layer_number=1, attn_mask_type=AttnMaskType.causal, attention_type='self' ) # Make sure it's causal. assert attn.window_size == (-1, 0)
def test_transformer_block_custom(self): """ This test checks that the two ways of passing `layer_spec` to a `TransformerBlock` result in an identical model: 1. ModuleSpec(module=..., submodules=...) 2. TransformerBlockSubmodules(layer_specs=...) """
transformer_config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True ) layer_local_spec = get_gpt_layer_local_spec()
# The following way can be used to pass a different `TransformerLayer` # and internally the `TransformerBlock` would fan out the single # `ModuleSpec` layer spec provided to all the layers of the block. layer_spec1 = ModuleSpec(module=TransformerLayer, submodules=layer_local_spec.submodules) model_parallel_cuda_manual_seed(123) torch.manual_seed(0) parallel_transformer_block1 = TransformerBlock(transformer_config, layer_spec1)
layer_spec2 = TransformerBlockSubmodules( layer_specs=[ ModuleSpec(module=TransformerLayer, submodules=layer_local_spec.submodules) ] * transformer_config.num_layers, layer_norm=TENorm, ) # make sure the model init conditions are identical model_parallel_cuda_manual_seed(123) torch.manual_seed(0) parallel_transformer_block2 = TransformerBlock(transformer_config, layer_spec2)
sequence_length = 32 micro_batch_size = 2 parallel_transformer_block1.cuda() parallel_transformer_block2.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones( (sequence_length, micro_batch_size, transformer_config.hidden_size) ) hidden_states = hidden_states.cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda()
out1 = parallel_transformer_block1( hidden_states=hidden_states, attention_mask=attention_mask ) out2 = parallel_transformer_block2( hidden_states=hidden_states, attention_mask=attention_mask )
assert torch.all(torch.eq(out1, out2)) assert out1.shape[0] == sequence_length == out2.shape[0] assert out1.shape[1] == micro_batch_size == out2.shape[1] assert out1.shape[2] == transformer_config.hidden_size == out2.shape[2]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import osimport pytest
import torchfrom megatron.core import dist_checkpointing
from megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.transformer.transformer_layer import TransformerLayerfrom megatron.core.transformer.transformer_block import TransformerBlockfrom tests.unit_tests.test_utilities import Utilsfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec
class TestParallelTransformerBlock:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) self.transformer_config = TransformerConfig(num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True) self.parallel_transformer_block = TransformerBlock(self.transformer_config, get_gpt_layer_with_transformer_engine_spec())
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): parallel_transformer_block = self.parallel_transformer_block assert isinstance(parallel_transformer_block, TransformerBlock) num_weights = sum([p.numel() for p in parallel_transformer_block.parameters()]) assert num_weights == 3792 assert parallel_transformer_block.num_layers_per_pipeline_rank == 2 assert len(parallel_transformer_block.layers) == 2 layer_0: TransformerLayer = parallel_transformer_block._get_layer(0) assert layer_0.layer_number == 1 layer_1: TransformerLayer = parallel_transformer_block._get_layer(1) assert layer_1.layer_number == 2
def test_gpu_forward(self): parallel_transformer_block = self.parallel_transformer_block config: TransformerConfig = parallel_transformer_block.config
sequence_length = 32 micro_batch_size = 2 parallel_transformer_block.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones((sequence_length, micro_batch_size, config.hidden_size)) hidden_states = hidden_states.cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda()
hidden_states = parallel_transformer_block(hidden_states=hidden_states, attention_mask=attention_mask) assert hidden_states.shape[0] == sequence_length assert hidden_states.shape[1] == micro_batch_size assert hidden_states.shape[2] == config.hidden_size
def test_gpu_forward_full_checkpoint(self): transformer_config = self.transformer_config config = transformer_config config.recompute_granularity = 'full' config.recompute_method = 'block' config.recompute_num_layers = config.num_layers full_transformer_block = TransformerBlock(config, get_gpt_layer_with_transformer_engine_spec()) assert full_transformer_block.config.recompute_granularity == 'full' assert full_transformer_block.config.recompute_method == 'block'
sequence_length = 32 micro_batch_size = 2 full_transformer_block.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones((sequence_length, micro_batch_size, config.hidden_size)) hidden_states = hidden_states.cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda()
hidden_states = full_transformer_block(hidden_states=hidden_states, attention_mask=attention_mask) assert hidden_states.shape[0] == sequence_length assert hidden_states.shape[1] == micro_batch_size assert hidden_states.shape[2] == config.hidden_size
def test_gpu_forward_selective_checkpoint(self): transformer_config = self.transformer_config config = transformer_config config.recompute_granularity = 'selective' selective_transformer_block = TransformerBlock(config, get_gpt_layer_with_transformer_engine_spec()) assert selective_transformer_block.config.recompute_granularity == 'selective' assert selective_transformer_block.checkpoint_core_attention
sequence_length = 32 micro_batch_size = 2 selective_transformer_block.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones((sequence_length, micro_batch_size, config.hidden_size)) hidden_states = hidden_states.cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda()
hidden_states = selective_transformer_block(hidden_states=hidden_states, attention_mask=attention_mask) assert hidden_states.shape[0] == sequence_length assert hidden_states.shape[1] == micro_batch_size assert hidden_states.shape[2] == config.hidden_size123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import pytest
import torch
from megatron.core import parallel_statefrom megatron.core.dist_checkpointing.mapping import ShardedObject, ShardedTensorfrom megatron.core.transformer.transformer_layer import TransformerLayerfrom megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seedfrom megatron.core.transformer.transformer_config import TransformerConfigfrom megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_specfrom tests.unit_tests.test_utilities import Utils
class TestParallelTransformerLayer:
def setup_method(self, method): Utils.initialize_model_parallel(1,1) model_parallel_cuda_manual_seed(123) transformer_config = TransformerConfig(num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True) self.parallel_transformer_layer = TransformerLayer(transformer_config, get_gpt_layer_with_transformer_engine_spec().submodules)
def teardown_method(self, method): Utils.destroy_model_parallel()
def test_constructor(self): parallel_transformer_layer = self.parallel_transformer_layer assert isinstance(parallel_transformer_layer, TransformerLayer) assert parallel_transformer_layer.layer_number == 1
num_weights = sum([p.numel() for p in parallel_transformer_layer.parameters()]) assert num_weights == 1884
def test_gpu_forward(self): parallel_transformer_layer = self.parallel_transformer_layer config: TransformerConfig = parallel_transformer_layer.config sequence_length = 32 micro_batch_size = 2 parallel_transformer_layer.cuda()
# [sequence length, batch size, hidden size] hidden_states = torch.ones((sequence_length, micro_batch_size, config.hidden_size)) hidden_states = hidden_states.cuda()
attention_mask = torch.ones((1, 1, sequence_length, sequence_length), dtype=bool).cuda()
hidden_states, context = parallel_transformer_layer(hidden_states=hidden_states, attention_mask=attention_mask) assert hidden_states.shape[0] == sequence_length assert hidden_states.shape[1] == micro_batch_size assert hidden_states.shape[2] == config.hidden_size
@pytest.mark.parametrize('order', ['tp-pp-dp', 'tp-dp-pp']) @pytest.mark.parametrize('tp_pp', [(4, 2), (1, 1), (8, 1), (2, 2)]) def test_sharded_state_dict(self, tp_pp, order): Utils.destroy_model_parallel() Utils.initialize_model_parallel(*tp_pp, order=order)
model_parallel_cuda_manual_seed(123) transformer_config = TransformerConfig(num_layers=2, hidden_size=128, num_attention_heads=8, use_cpu_initialization=True) parallel_transformer_layer = TransformerLayer(transformer_config, get_gpt_layer_with_transformer_engine_spec().submodules)
sharded_state_dict = parallel_transformer_layer.sharded_state_dict()
extra_states = {k: v for k, v in sharded_state_dict.items() if k.endswith('extra_state')} sharded_tensors = {k: v for k, v in sharded_state_dict.items() if not k.endswith('extra_state')} assert all(isinstance(t, ShardedObject) for t in extra_states.values()) assert all(isinstance(t, ShardedTensor) for t in sharded_tensors.values())
# Test all local shapes tensor_local_shapes = {k: v.local_shape for k, v in sharded_tensors.items()} tp_size = parallel_state.get_tensor_model_parallel_world_size() assert tensor_local_shapes == get_tensor_shapes_for_tp(transformer_config, tp_size)
# Test all global shapes. Prepend num layers in front of expected shapes tensor_global_shapes = {k: v.global_shape for k, v in sharded_tensors.items()} expected_global_shapes = get_tensor_shapes_for_tp(transformer_config, 1) assert tensor_global_shapes == expected_global_shapes
# Test ShardedTensor keys for state_dict_key, sh_ten in sharded_tensors.items(): assert state_dict_key == sh_ten.key
Utils.destroy_model_parallel() Utils.initialize_model_parallel(1, 1)
def get_tensor_shapes_for_tp(transformer_config, tp_size): hs = transformer_config.hidden_size return { 'mlp.linear_fc1.layer_norm_weight': (hs,), 'mlp.linear_fc1.layer_norm_bias': (hs,), 'mlp.linear_fc1.weight': (hs * 4 // tp_size, hs), 'mlp.linear_fc1.bias': (hs * 4 // tp_size,), 'mlp.linear_fc2.weight': (hs, hs * 4 // tp_size), 'mlp.linear_fc2.bias': (hs,), 'self_attention.linear_proj.weight': (hs, hs // tp_size), 'self_attention.linear_proj.bias': (hs,), 'self_attention.linear_qkv.layer_norm_weight': (hs,), 'self_attention.linear_qkv.layer_norm_bias': (hs,), 'self_attention.linear_qkv.weight': (hs * 3 // tp_size, hs), 'self_attention.linear_qkv.bias': (hs * 3 // tp_size,), }123456789101112131415161718192021#!/bin/bashset -euox pipefail
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )CHECK_ONLY=${CHECK_ONLY:-false}CHANGED_FILES=$(git diff --name-only --diff-filter=d --merge-base origin/main megatron/core | grep '\.py$' || true)ADDITIONAL_ARGS=""ADDITIONAL_BLACK_ARGS=""
if [[ $CHECK_ONLY == true ]]; then ADDITIONAL_ARGS="--check" ADDITIONAL_BLACK_ARGS="--diff"fi
# for now we just format coreif [[ -n "$CHANGED_FILES" ]]; then black $ADDITIONAL_ARGS $ADDITIONAL_BLACK_ARGS --verbose $CHANGED_FILES isort $ADDITIONAL_ARGS $CHANGED_FILESelse echo Changeset is empty, all good.fi123# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
from .embed import BertEmbedder, DiskDataParallelBertEmbedder12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
import numpy as npimport torch
from megatron.training import get_args, get_tokenizer
class BertEmbeddingDataset(torch.utils.data.Dataset): '''Dataset to convert a text dataset to Bert tokens.'''
def __init__(self, text_dataset, max_seq_length):
super().__init__()
args = get_args()
# Dataset, tokenizer. self.text_dataset = text_dataset self.max_seq_length = max_seq_length self.bert_tokenizer = get_tokenizer()
def __len__(self): return len(self.text_dataset)
@classmethod def build_sample(cls, tokenizer, token_ids): get_constant_array = lambda c : np.full((len(token_ids) + 2,), c, "int64") return { "text" : np.array([ tokenizer.cls, *token_ids, tokenizer.sep ], dtype="int64"), "types" : get_constant_array(0), "labels" : get_constant_array(-1), "is_random" : 0, "loss_mask" : get_constant_array(0), "padding_mask" : get_constant_array(1), "truncated" : 0, }
def __getitem__(self, idx):
# Text. text_sample = self.text_dataset[idx] text = text_sample["text"] text = text.replace("<|endoftext|>", "")
# Bert/Wordpiece tokens (+truncate). bert_token_ids = self.bert_tokenizer.tokenize(text) bert_token_ids = bert_token_ids[:self.max_seq_length - 2] # cls+sep. if not bert_token_ids: bert_token_ids = [ self.bert_tokenizer.pad_id ] # hack when empty seq
# Bert sample. sample = self.build_sample(self.bert_tokenizer, bert_token_ids)
return sample123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
from functools import partialimport numpy as npimport osimport timeimport torchfrom torch.utils.data import BatchSampler, DataLoader, SequentialSampler, Subsetfrom torch.utils.data._utils.collate import default_collatefrom tqdm import tqdm
from megatron.training import get_args, get_tokenizer, print_rank_0from megatron import corefrom megatron.training.arguments import core_transformer_config_from_argsfrom megatron.core.datasets.retro.utils import get_blocks_by_rankfrom megatron.core.enums import ModelTypefrom megatron.core.pipeline_parallel import get_forward_backward_funcfrom megatron.legacy.model import BertModelfrom megatron.training.training import setup_model_and_optimizerfrom pretrain_bert import model_provider, get_batch, loss_func, forward_step
from .dataset import BertEmbeddingDatasetfrom .external_libs import h5pyfrom .huggingface import HuggingfaceEmbedder
def collate_batch(samples): """Collate samples of various lengths.
This collate function handles samples with various sequence lengths, by padding 'text' arrays with pad_id, and other arrays with 0. """
n_samples = len(samples) keys = list(samples[0].keys()) tokenizer = get_tokenizer()
# Max sample length across all samples. max_length_map = { key:0 for key in keys } for sample in samples: for key in keys: value_length = \ len(sample[key]) if isinstance(sample[key], np.ndarray) else None max_length_map[key] = None \ if value_length is None else \ max(max_length_map[key], value_length)
# Pad samples. padded_samples = [] for sample in samples: padded_sample = {} for key in keys: padded_sample[key] = \ np.pad( sample[key], (0, max_length_map[key] - len(sample[key])), mode="constant", constant_values=tokenizer.pad_id if key == "text" else 0, ) \ if isinstance(sample[key], np.ndarray) else \ sample[key] padded_samples.append(padded_sample)
# Build batch with padded samples. batch = default_collate(padded_samples)
return batch
def get_data_loader(dataset, batch_size): """Build data loader over data subset.
Get a subset of the dataset (from start_idx -> end_idx), and wrap it in a sequential sampler and data loader. """
args = get_args()
# Sequential & batch samplers. batch_sampler = BatchSampler( sampler=SequentialSampler(dataset), batch_size=batch_size, drop_last=False, )
# Data loader. data_loader = DataLoader(dataset, batch_sampler=batch_sampler, num_workers=args.num_workers, pin_memory=True, collate_fn=collate_batch)
return data_loader
def embed_data_loader(models, data_loader, tag): '''Iterate data loader and compute embeddings.'''
# Verify no model parallelism. args = get_args() assert args.tensor_model_parallel_size == 1 and \ args.pipeline_model_parallel_size == 1, \ "since we call forward_step directly, only tp == pp == 1 allowed."
# Data iterator. data_iterator = iter(data_loader)
# Eval mode. for m in models: m.eval()
# Embed. embeddings = [] for _ in tqdm( range(len(data_loader)), " embed%s" % ("" if tag is None else " / '%s'" % tag), miniters=len(data_loader) // 10, disable=torch.distributed.get_rank() != 0, ): with torch.no_grad(): result = forward_step(data_iterator, models[0]) embeddings.append(result[0].detach().cpu().numpy())
# Concatenate embeddings. embeddings = np.concatenate(embeddings, axis=0)
return embeddings
class TextDataset(torch.utils.data.Dataset): '''Dataset that holds a list of strings.'''
def __init__(self, texts): assert isinstance(texts, list) for t in texts: assert isinstance(t, str) self.texts = texts
def __len__(self): return len(self.texts)
def __getitem__(self, i): return {"text": self.texts[i]}
class BertEmbedder: '''Compute Bert embeddings, from a text dataset.'''
def __init__(self, batch_size, max_bert_seq_length, embedder_type, warmup=True):
args = get_args()
assert args.output_bert_embeddings
self.models, optimizer, opt_param_scheduler = \ setup_model_and_optimizer(model_provider, ModelType.encoder_or_decoder) self.batch_size = batch_size self.max_bert_seq_length = max_bert_seq_length
# Init Huggingface, if in use. if embedder_type == "megatron": self.huggingface_embedder = None elif embedder_type == "huggingface": self.huggingface_embedder = HuggingfaceEmbedder(batch_size, max_bert_seq_length) else: raise Exception("specialize for embedder type '%s'." % embedder_type)
# Warm-up JIT. # - Important to separately warm up: # 1. batch_size == 1 # 2. batch_size > 1 if warmup: warmup_dataset = TextDataset([ "great fleas have lesser fleas, upon their backs to bite’em,", "and lesser fleas have lesser fleas, and so, ad infinitum,", "and those great fleas, themselves, in turn have greater fleas to go on,", "while those again have greater still, and greater still, and so on.", ]) print_rank_0("bert / warmup single.") for _ in range(3): self.embed_text("hi, bert.") # batch size == 1 print_rank_0("bert / warmup batch.") for _ in range(3): self.embed_text_dataset(warmup_dataset) # batch size > 1
def embed_text_dataset(self, text_dataset, tag=None): '''Embed a text dataset.'''
# Huggingface. if self.huggingface_embedder: return self.huggingface_embedder.embed_text_dataset(text_dataset)
# Wrap in a BertEmbeddingDataset to tokenize samples. bert_dataset = BertEmbeddingDataset(text_dataset, self.max_bert_seq_length)
# Embed. data_loader = get_data_loader(bert_dataset, self.batch_size) embeddings = embed_data_loader(self.models, data_loader, tag)
return embeddings
def embed_text(self, text): '''Embed a single text string.
Primarily used for on-the-fly embeddings, particularly during analysis or debugging. For large scale, use 'embed_text_dataset()'. '''
# Embed text. text_ds = TextDataset([ text ]) embed = self.embed_text_dataset(text_ds)[0]
return embed
class DiskDataParallelBertEmbedder: '''Process embeddings in blocks & save to disk.'''
def __init__(self, embedder, block_size): assert isinstance(embedder, BertEmbedder) self.embedder = embedder self.block_size = block_size
def embed_text_blocks(self, name, dirname, text_dataset, missing_embedding_blocks): '''Process a text dataset in blocks.'''
# Iterate blocks. for block_index, block_info in enumerate(missing_embedding_blocks):
# Missing block lists are extended with None to have equal-length # lists. Skip the Nones. if block_info is not None:
# Progress. (*note*: move world progress to here.) print_rank_0("embed '%s' block %d / %d ... %s." % ( name, block_index, len(missing_embedding_blocks), block_info["path"], ))
# Embed block. sub_dataset = Subset(text_dataset, range(*block_info["range"])) embeddings = self.embedder.embed_text_dataset(sub_dataset)
# Save embeddings. f = h5py.File(block_info["path"], "w") f.create_dataset("data", data=embeddings) f.close()
# Synchronize progress across all ranks. (for easier observation) print_rank_0(" > waiting for other ranks to finish block.") torch.distributed.barrier()
def embed_text_dataset(self, name, dirname, text_dataset): '''Embed a text dataset.'''
# Dataset dir. os.makedirs(dirname, exist_ok=True)
# Missing embedding blocks (stored on disk). def validate(f): assert f["data"].shape[1] == 1024 blocks = get_blocks_by_rank( dirname, len(text_dataset), self.block_size, validate=validate)
# Prevent missing file race condition. torch.distributed.barrier()
# Embed batches. self.embed_text_blocks(name, dirname, text_dataset, blocks.missing)1234567891011121314# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import importlib
required_libs = [ "h5py", "transformers", # for huggingface bert]
for lib in required_libs: try: globals()[lib] = importlib.import_module(lib) except ImportError as e: raise Exception(f"Missing one or more packages required for Bert embedding: {required_libs}. Tried importing '{lib}'.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import numpy as npimport torchfrom tqdm import tqdm
from .external_libs import transformers
class IterableTextDataset(torch.utils.data.IterableDataset): '''Iterable over a text dataset.'''
def __init__(self, text_dataset): self.text_dataset = text_dataset
def __iter__(self): '''Remove 'endoftext' string.''' for sample_idx in range(len(self.text_dataset)): sample = self.text_dataset[sample_idx] text = sample["text"].replace("<|endoftext|>", "") yield text
class MyFeatureExtractionPipeline(transformers.FeatureExtractionPipeline): def _forward(self, model_inputs):
# Embed inputs. model_outputs = self.model(**model_inputs)
# Attention mask. embeddings = model_outputs[0] masks = torch.sum(model_inputs['attention_mask'], dim=1)
# Collect embeddings & check for nan. outputs = [] for embedding, mask in zip(embeddings, masks): output = torch.mean(embedding[1: mask - 1], dim=0)
# Nans due to empty input sequences; so only check first element. if torch.isnan(output.view(-1)[0]).any(): output.zero_()
outputs.append(output)
# Sample. data = { "input" : model_inputs["input_ids"], "output" : outputs, }
return data
def postprocess(self, model_outputs): # Return input for analysis. return { "input" : model_outputs["input"].numpy(), "output" : model_outputs["output"].numpy(), }
class HuggingfaceEmbedder:
def __init__(self, batch_size, max_seq_length):
# Model, tokenizer. self.model = transformers.BertModel.from_pretrained("bert-large-cased") self.tokenizer = transformers.AutoTokenizer.from_pretrained( "bert-large-cased", model_max_length=max_seq_length)
# Feature extraction pipeline. self.pipe = MyFeatureExtractionPipeline( model=self.model, tokenizer=self.tokenizer, device=torch.cuda.current_device(), truncation=True, max_length=max_seq_length, )
self.batch_size = batch_size
def embed_text_dataset(self, text_dataset, verbose=True):
# Wrap dataset in iterable. dataset = IterableTextDataset(text_dataset)
# Allocate output array. n_samples = len(text_dataset) embeddings = np.zeros((n_samples, 1024), dtype="f4") start_idx = 0
# Wrap iterator in tqdm for verbose output. _iter = self.pipe(dataset, batch_size=self.batch_size) if verbose: _iter = tqdm(_iter, "hf embed", total=n_samples)
# Embed dataset. for idx, out_dict in enumerate(_iter): inp = out_dict["input"] out = out_dict["output"] embeddings[start_idx] = out start_idx += 1
return embeddings
def embed_text(self, text): '''Embed a single text string.
Primarily used for on-the-fly embeddings, particularly during analysis or debugging. For large scale, use 'embed_text_dataset()'. '''
class SingleTextDataset(torch.utils.data.Dataset): '''Dataset that holds single string.''' def __init__(self, text): assert isinstance(text, str) self.text = text def __len__(self): return 1 def __getitem__(self, i): return {"text": self.text}
# Embed text. text_ds = SingleTextDataset(text) embed = self.embed_text_dataset(text_ds, verbose=False)[0]
return embed123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import argparseimport importlibimport torch.multiprocessing as mpimport sys
# A loader is a python file with at least two functions# - add_arguments - takes in a parser and adds any arguments needed# - load_checkpoint - takes in the queue and parsed arguments
# A saver is similar but has save_checkpoint instead of# load_checkpoint
# The loader and saver process are each given a queue, the loader# should load the checkpoint and send the weights in messages in the# following order, the saver should receive them in this order and# save the checkpoints. A message consists of a python dictionary with# a "name" for error checking and an entry for each tensor as# indicated below. Note that the weight sent over the queue are the# full model weights, nothing split.
# If the loader ever sends "exit" to the queue, that means something# went wrong and it is exiting.
# - Metadata Namespace with the following attributes:# model_type - GPT, BERT, T5, etc. (Part of protocol to allow this to be deduced later instead of given on command line)# num_layers - Number of transformer layers# hidden_size# seq_length# num_attention_heads# max_position_embeddings# tokenizer_type# iteration# params_dtype# bert_binary_head - Used only if model_type is BERT# previous_tensor_parallel_size - Optional# previous_pipeline_parallel_size - Optional# true_vocab_size# make_vocab_size_divisble_by# consumed_train_samples# consumed_valid_samples# messages# {# "name": "embeddings"# "position embeddings"# "word embeddings"# }# (for each transformer layer):# {# "name": "transformer layer N"# "input norm weight"# "input norm bias"# "qkv weight"# "qkv bias"# "dense weight"# "dense bias"# "post norm weight"# "post norm bias"# "mlp l0 weight"# "mlp l0 bias"# "mlp l1 weight"# "mlp l1 bias"# }# {# "name": "final layer norm"# "weight"# "bias"# }# if present (i.e. for BERT):# {# "name": "pooler"# "weight"# "bias"# }# {# "name": "lm head"# "dense weight"# "dense bias"# "norm weight"# "norm bias"# }# {# "name": "binary head"# "weight"# "bias"# }# - "done"
def load_plugin(plugin_type, name): module_name = f"{plugin_type}_{name}" try: plugin = importlib.import_module(module_name) except ModuleNotFoundError as e: print(e) module_name = name try: plugin = importlib.import_module(module_name) except ModuleNotFoundError as e: print(e) sys.exit(f"Unable to load {plugin_type} plugin {name}. Exiting.")
if not hasattr(plugin, 'add_arguments'): sys.exit(f"{module_name} module is not a plugin. Exiting.")
print(f"Loaded {module_name} as the {plugin_type}.") return plugin
def main(): import argparse parser = argparse.ArgumentParser(description="Megatron Checkpoint Converter Arguments", allow_abbrev=False, conflict_handler='resolve')
parser.add_argument('--model-type', type=str, required=True, choices=['GPT', 'BERT'], help='Type of the model') parser.add_argument('--loader', type=str, default='megatron', help='Module name to load checkpoint, should be on python path') parser.add_argument('--saver', type=str, default='megatron', help='Module name to save checkpoint, should be on python path') parser.add_argument('--load-dir', type=str, required=True, help='Directory to load model checkpoint from') parser.add_argument('--save-dir', type=str, required=True, help='Directory to save model checkpoint to') parser.add_argument('--max-queue-size', type=int, default=50, help='Maximum number of tensors in the queue') parser.add_argument('--no-checking', action='store_false', help='Do not perform checking on the name and ordering of weights', dest='checking')
known_args, _ = parser.parse_known_args() loader = load_plugin('loader', known_args.loader) saver = load_plugin('saver', known_args.saver)
loader.add_arguments(parser) saver.add_arguments(parser)
args = parser.parse_args()
queue = mp.Queue(maxsize=args.max_queue_size)
print("Starting saver...") saver_proc = mp.Process(target=saver.save_checkpoint, args=(queue, args)) saver_proc.start()
print("Starting loader...") loader.load_checkpoint(queue, args)
print("Waiting for saver to complete...") saver_proc.join()
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
# Note (rwaleffe): This is a temporary file for hybrid mamba-transformer model checkpoint conversion.# This functionality should be integrated with the megatron core checkpoint loader/saver.
import copyimport osimport reimport shutilfrom collections import OrderedDict
import torchimport argparse
tp_split_dim = { 'word_embeddings.weight': 0, 'norm.weight': -1, 'final_norm.weight': -1, 'output_layer.weight': 0, # mamba1/2 'A_log': 0, 'D': 0, 'dt_bias': 0, 'in_proj.weight': 0, 'conv1d.weight': 0, 'conv1d.bias': 0, 'x_proj.weight': 1, 'dt_proj.weight': 0, 'dt_proj.bias': 0, 'out_proj.weight': 1, 'mixer.norm.weight': 0, # mlp 'linear_fc1.layer_norm_weight': -1, 'linear_fc1.weight': 0, 'linear_fc2.weight': 1, # attention 'self_attention.linear_proj.weight': 1, 'self_attention.linear_qkv.layer_norm_weight': -1, 'self_attention.linear_qkv.weight': 0,}
def get_split_dim(tensor_name): # norm.weight will match tensor_name of mixer.norm.weight and norm.weight, need to distinguish if 'norm.weight' in tensor_name: if 'mixer.norm.weight' in tensor_name: return tp_split_dim['mixer.norm.weight'] else: return tp_split_dim['norm.weight']
for key in tp_split_dim.keys(): if key in tensor_name: return tp_split_dim[key] raise Exception("Unknown tensor name {}".format(tensor_name))
def combine_tp_tensors(params, key, dim, tensors): tp_size = len(tensors)
if 'mixer.in_proj.weight' in key and params.mamba_version == 1: xs = []; zs = [] for tensor in tensors: x, z = torch.split(tensor, [params.mamba_d_inner//tp_size, params.mamba_d_inner//tp_size], dim=dim) xs.append(x); zs.append(z) return torch.cat([torch.cat(xs, dim=dim), torch.cat(zs, dim=dim)], dim=dim)
elif 'mixer.in_proj.weight' in key and params.mamba_version == 2: xs = []; zs = []; Bs = []; Cs = []; dts = [] for tensor in tensors: x, z, B, C, dt = torch.split(tensor, [params.mamba_d_inner // tp_size, params.mamba_d_inner // tp_size, (params.mamba2_n_groups // tp_size) * args.mamba_d_state, (params.mamba2_n_groups // tp_size) * args.mamba_d_state, params.mamba2_n_heads // tp_size], dim=dim) xs.append(x); zs.append(z); Bs.append(B); Cs.append(C); dts.append(dt)
for ii in range(len(Bs)): Bs[ii] = torch.reshape(Bs[ii], (-1, params.mamba_d_state, Bs[ii].shape[-1])) Cs[ii] = torch.reshape(Cs[ii], (-1, params.mamba_d_state, Cs[ii].shape[-1])) B = torch.cat(Bs, dim=dim); C = torch.cat(Cs, dim=dim) x = torch.cat(xs, dim=dim); z = torch.cat(zs, dim=dim); dt = torch.cat(dts, dim=dim)
return torch.cat([x, z, B.flatten(0, 1), C.flatten(0, 1), dt], dim=dim)
elif 'mixer.conv1d' in key and params.mamba_version == 2: xs = []; Bs = []; Cs = [] for tensor in tensors: x, B, C = torch.split(tensor, [params.mamba_d_inner//tp_size, (params.mamba2_n_groups // tp_size) * params.mamba_d_state, (params.mamba2_n_groups // tp_size) * params.mamba_d_state], dim=dim) xs.append(x); Bs.append(B); Cs.append(C)
for ii in range(len(Bs)): if 'weight' in key: Bs[ii] = torch.reshape(Bs[ii], (-1, params.mamba_d_state, Bs[ii].shape[-2], Bs[ii].shape[-1])) Cs[ii] = torch.reshape(Cs[ii], (-1, params.mamba_d_state, Cs[ii].shape[-2], Cs[ii].shape[-1])) elif 'bias' in key: Bs[ii] = torch.reshape(Bs[ii], (-1, params.mamba_d_state)) Cs[ii] = torch.reshape(Cs[ii], (-1, params.mamba_d_state)) else: raise Exception("Unknown key") B = torch.cat(Bs, dim=dim); C = torch.cat(Cs, dim=dim) x = torch.cat(xs, dim=dim)
return torch.cat([x, B.flatten(0, 1), C.flatten(0, 1)], dim=dim)
else: return torch.cat(tensors, dim=dim)
def split_tensor_for_tp(params, key, dim, tensor): tp_size = params.target_tp_size tensor_sliced = []
if 'mixer.in_proj.weight' in key and params.mamba_version == 1: x, z = torch.split(tensor, [params.mamba_d_inner, params.mamba_d_inner], dim=dim) x_sliced = torch.chunk(x, tp_size, dim=dim) z_sliced = torch.chunk(z, tp_size, dim=dim) for (x, z) in zip(x_sliced, z_sliced): tensor_sliced.append(torch.cat((x, z), dim=dim))
elif 'mixer.in_proj.weight' in key and params.mamba_version == 2: x, z, B, C, dt = torch.split(tensor, [params.mamba_d_inner, params.mamba_d_inner, params.mamba2_n_groups * params.mamba_d_state, params.mamba2_n_groups * params.mamba_d_state, params.mamba2_n_heads], dim=dim) B = torch.reshape(B, (-1, params.mamba_d_state, B.shape[-1])) C = torch.reshape(C, (-1, params.mamba_d_state, C.shape[-1]))
B_sliced = torch.chunk(B, tp_size, dim=dim) C_sliced = torch.chunk(C, tp_size, dim=dim) x_sliced = torch.chunk(x, tp_size, dim=dim) z_sliced = torch.chunk(z, tp_size, dim=dim) dt_sliced = torch.chunk(dt, tp_size, dim=dim)
tensor_sliced = [] for (x, z, B, C, dt) in zip(x_sliced, z_sliced, B_sliced, C_sliced, dt_sliced): tensor_sliced.append(torch.cat((x, z, B.flatten(0, 1), C.flatten(0, 1), dt), dim=dim))
elif 'mixer.conv1d' in key and params.mamba_version == 2: x, B, C = torch.split(tensor, [params.mamba_d_inner, params.mamba2_n_groups * params.mamba_d_state, params.mamba2_n_groups * params.mamba_d_state], dim=dim) if 'weight' in key: B = torch.reshape(B, (-1, params.mamba_d_state, B.shape[-2], B.shape[-1])) C = torch.reshape(C, (-1, params.mamba_d_state, C.shape[-2], C.shape[-1])) elif 'bias' in key: B = torch.reshape(B, (-1, params.mamba_d_state)) C = torch.reshape(C, (-1, params.mamba_d_state)) else: raise Exception("Unknown key")
B_sliced = torch.chunk(B, tp_size, dim=dim) C_sliced = torch.chunk(C, tp_size, dim=dim) x_sliced = torch.chunk(x, tp_size, dim=dim)
tensor_sliced = [] for (x, B, C) in zip(x_sliced, B_sliced, C_sliced): tensor_sliced.append(torch.cat((x, B.flatten(0, 1), C.flatten(0, 1)), dim=dim))
else: tensor_sliced = torch.chunk(tensor, tp_size, dim=dim)
return tensor_sliced
def finalize_checkpoint(sample_model, model, params, verbose=False): # make sure the rest of the checkpoint is how we want it from the original (i.e., other than the 'model') reset_iterations = params.reset_iterations
# checkpoint 'args' model['args'] = copy.deepcopy(sample_model['args']) model['args'].tensor_model_parallel_size = params.target_tp_size model['args'].pipeline_model_parallel_size = params.target_pp_size if reset_iterations: model['args'].iteration = 0 model['args'].consumed_valid_samples = 0 model['args'].consumed_train_samples = 0 model['args'].train_iters = 0 model['args'].train_samples = 0
# checkpoint 'checkpoint_version' model['checkpoint_version'] = copy.deepcopy(sample_model['checkpoint_version'])
# checkpoint 'iteration' model['iteration'] = copy.deepcopy(sample_model['iteration']) if reset_iterations: model['iteration'] = 0
# checkpoint 'optimizer' # ignore
# checkpoint 'opt_param_scheduler' if 'opt_param_scheduler' in sample_model.keys(): model['opt_param_scheduler'] = copy.deepcopy(sample_model['opt_param_scheduler'])
# checkpoint 'rng_state' model['rng_state'] = copy.deepcopy(sample_model['rng_state'])
# report on argument difference if verbose: original_args = sample_model['args'].__dict__ final_args = model['args'].__dict__ for key in original_args: if key in final_args: if final_args[key] != original_args[key]: print("KEY MISMATCH: {}".format(key)) print("\toriginal: {}\n\tfinal: {}".format(original_args[key], final_args[key])) else: print("KEY MISSING from final: {}, value {}".format(key, original_args[key])) print("") for key in final_args: if key not in original_args: print("KEY ADDED to final: {}, value {}".format(key, final_args[key]))
return model
def main(args): print("\n====RUNNING CHECKPOINT CONVERSION====\n")
args.mamba_d_inner = args.d_model * 2 args.mamba2_n_heads = args.mamba_d_inner // args.mamba2_head_dim
# get the latest iteration tracker_filename = os.path.join(args.load_dir, 'latest_checkpointed_iteration.txt') with open(tracker_filename, 'r') as f: metastring = f.read().strip() try: iteration = int(metastring) except ValueError: raise Exception("") out_iteration = iteration if not args.reset_iterations else 0
# get model directory and model parallel ranks input_model_dir = os.path.join(args.load_dir, 'iter_{:07d}'.format(iteration)) input_sub_models = os.listdir(input_model_dir) # input_sub_models = sorted(input_sub_models, key=lambda x: int(re.search(r'\d+', x).group()))
# load one of the model parallel ranks to get arguments sample_model_file = os.path.join(input_model_dir, input_sub_models[0], "model_optim_rng.pt") sample_model = torch.load(sample_model_file) print(f"Sample model {sample_model_file} is loaded.\n")
# input tensor and pipeline parallel size input_tp_rank = sample_model['args'].tensor_model_parallel_size input_pp_rank = sample_model['args'].pipeline_model_parallel_size num_layers_per_pipeline_rank = sample_model['args'].num_layers // input_pp_rank
# construct full model full_model = OrderedDict() for pp in range(input_pp_rank): print("[INFO] Processing input pipeline rank {}".format(pp)) tp_models = [] for tp in range(input_tp_rank): dir_name = "mp_rank_{:02d}".format(tp) if input_pp_rank > 1: dir_name += "_{:03d}".format(pp) model_file = os.path.join(input_model_dir, dir_name, "model_optim_rng.pt")
tp_models.append(torch.load(model_file)) print(f"Model {model_file} is loaded.")
if input_tp_rank > 1: combined_tp_model = OrderedDict() for ii, (key, original_tensor) in enumerate(tp_models[0]['model'].items()): if "_extra_state" in key: combined_tp_model[key] = original_tensor continue
split_dim = get_split_dim(key) original_shape = list(original_tensor.shape) combined_shape = copy.deepcopy(original_shape) combined_shape[split_dim] *= input_tp_rank # print("{}, {}, {}".format(ii, key, split_dim))
if split_dim != -1: # slice together model # print("\tshape mismatch: original {}, combined {}".format(original_shape, combined_shape)) combined_tensor = combine_tp_tensors(args, key, split_dim, [tp_models[jj]['model'][key].cpu() for jj in range(input_tp_rank)]) combined_tp_model[key] = combined_tensor else: # copy model combined_tp_model[key] = original_tensor else: combined_tp_model = tp_models[0]['model'] # print("Combined tp model: {}".format(combined_tp_model.keys()))
for ii, (key, original_tensor) in enumerate(combined_tp_model.items()): try: layer_num = int(re.findall(r'\d+', key)[0]) new_key = key.replace(str(layer_num), str(layer_num + pp*num_layers_per_pipeline_rank), 1) except: new_key = key full_model[new_key] = original_tensor # print("Combined model: {}".format(full_model.keys())) print("\n[INFO] Loaded combined model\n")
# sort by layer # full_model_sorted = dict(sorted(people.items(), key=lambda item: item[1]))
# create new split model pp_offset = 0 num_layers_per_pipeline_rank = sample_model['args'].num_layers // args.target_pp_size
for pp in range(args.target_pp_size): print("[INFO] Processing output pipeline rank {}".format(pp)) tp_models = [] for ii in range(args.target_tp_size): tp_models.append({'model': OrderedDict()})
for ii, (key, original_tensor) in enumerate(full_model.items()): try: layer_num = int(re.findall(r'\d+', key)[0]) if layer_num >= num_layers_per_pipeline_rank * (pp+1): break new_key = key.replace(str(layer_num), str(layer_num - (pp * num_layers_per_pipeline_rank)), 1) except: new_key = key
if ii < pp_offset: continue else: pp_offset += 1
if "_extra_state" in new_key: # copy for jj in range(args.target_tp_size): tp_models[jj]['model'][new_key] = original_tensor continue
split_dim = get_split_dim(new_key) original_shape = list(original_tensor.shape) v0 = original_shape[split_dim] split_size = v0 // args.target_tp_size split_shape = copy.deepcopy(original_shape) split_shape[split_dim] = split_size # print("{}, {}, {}".format(ii, new_key, split_dim))
if split_dim != -1: # split model # print("\tshape mismatch: original {}, combined {}".format(original_shape, split_shape)) tensor_sliced = split_tensor_for_tp(args, new_key, split_dim, original_tensor) for jj in range(args.target_tp_size): tp_models[jj]['model'][new_key] = tensor_sliced[jj] else: # copy model for jj in range(args.target_tp_size): tp_models[jj]['model'][new_key] = original_tensor # print(tp_models[0]['model'].keys())
for tp in range(args.target_tp_size): dir_name = "mp_rank_{:02d}".format(tp) if args.target_pp_size > 1: dir_name += "_{:03d}".format(pp)
model = finalize_checkpoint(sample_model, tp_models[tp], args, verbose=False)
save_dir = os.path.join(args.save_dir, 'iter_{:07d}'.format(out_iteration), dir_name) os.makedirs(save_dir, exist_ok=True) model_file = os.path.join(save_dir, "model_optim_rng.pt") torch.save(model, model_file) print(f"Model {model_file} is saved.")
# shutil.copyfile(tracker_filename, os.path.join(args.save_dir, 'latest_checkpointed_iteration.txt')) tracker_filename = os.path.join(args.save_dir, 'latest_checkpointed_iteration.txt') with open(tracker_filename, 'w') as f: f.write(str(out_iteration))
if __name__ == "__main__": # example run command: # python hybrid_conversion.py # --load-dir mamba2-840m-test/checkpoints/ # --save-dir mamba2-840m-test-conversion/checkpoints/ # --target-pp-size 1 # --target-tp-size 1
parser = argparse.ArgumentParser() parser.add_argument('--load-dir', type=str) parser.add_argument('--save-dir', type=str) parser.add_argument('--target-tp-size', type=int, default=1) parser.add_argument('--target-pp-size', type=int, default=1) parser.add_argument('--reset-iterations', action='store_true')
parser.add_argument('--d-model', type=int, default=4096) parser.add_argument('--mamba-version', type=int, default=2) parser.add_argument('--mamba-d-state', type=int, default=128) parser.add_argument('--mamba2-n-groups', type=int, default=8) parser.add_argument('--mamba2-head-dim', type=int, default=64)
args = parser.parse_args()
main(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import jsonimport osimport sysimport torchtry: import transformersexcept ImportError: raise ImportError("The 'transformers' package is not installed.")import gcimport shutilfrom tqdm import tqdmimport types
def add_arguments(parser): group = parser.add_argument_group(title='Llama/Mistral loader.')
# TODO(jbarker): Need assertion to make sure *exactly* one of these is used parser.add_argument('--model-size', type=str, required=True, choices=['llama2-7B', 'llama2-13B', 'llama2-70B', 'llama2-7Bf', 'llama2-13Bf', 'llama2-70Bf', 'llama3-8B', 'llama3-70B', 'llama3-8Bf', 'llama3-70Bf', 'mistral-7B', 'mistral-7Bf', 'yi-34B'], help='Model size can be `llama2-7B`, `llama2-13B`, `llama2-70B`, `llama3-8B`, `llama3-70B`, `mistral-7B` (for pretrained models), ' 'and `llama2-7Bf`, `llama2-13Bf`, `llama2-70Bf`, `llama3-8Bf`, `llama3-70bf` and `mistral-7Bf` (for chat-finetuned models).') parser.add_argument('--checkpoint-type', type=str, required=True, help='Type of checkpoint to convert, options are "meta" or "hf"') parser.add_argument('--bf16', action='store_true', help='Whether to load weights in bf16.') parser.add_argument('--fp16', action='store_true', help='Whether to load weights in fp16.') group.add_argument('--true-vocab-size', type=int, default=None, help='original size of vocab, if specified will trim padding from embedding table.') group.add_argument('--vocab-file', type=str, default=None, help='Path to the vocab file. If specified will use this to get vocab size and ' 'trim padding from the embedding table.') group.add_argument('--tokenizer-model', required=True, help='Tokenizer model file.') group.add_argument('--megatron-path', type=str, default=None, help='Base directory of Megatron repository') group.add_argument('--loader-transformer-impl', default='local', choices=['local', 'transformer_engine'], help='Which Transformer implementation to use.')
def verify_transformers_version(): major, minor, patch = map(int, transformers.__version__.split('.')) assert major >= 4 and minor >= 31
NUM_SHARDS = { "llama2-7B": 1, "llama2-7Bf": 1, "llama2-13B": 2, "llama2-13Bf": 2, "llama2-70B": 8, "llama2-70Bf": 8, "llama3-8B": 1, "llama3-8Bf": 1, "llama3-70B": 8, "llama3-70Bf": 8, "mistral-7B": 1, "mistral-7Bf": 1, "yi-34B": 8,}
def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256): return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
def read_json(path): with open(path, "r") as f: return json.load(f)
def write_json(text, path): with open(path, "w") as f: json.dump(text, f)
# This conversion is adapted from# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/convert_llama_weights_to_hf.pydef convert_to_hf(model_path, input_base_path, model_size, tokenizer_path):
if "llama2" in model_size: from transformers import LlamaConfig as ModelConfig from transformers import LlamaTokenizer, LlamaTokenizerFast elif "llama3" in model_size: from transformers import LlamaConfig as ModelConfig elif "mistral" in model_size: from transformers import MistralConfig as ModelConfig try: from mistral_common.tokens.tokenizers.mistral import MistralTokenizer except ImportError: raise ImportError("Module 'mistral-common' is required but not installed.")
# for backward compatibility, before you needed the repo to be called `my_repo/model_size` if not os.path.isfile(os.path.join(input_base_path, "params.json")): input_base_path = os.path.join(input_base_path, model_size)
os.makedirs(model_path, exist_ok=True)
params = read_json(os.path.join(input_base_path, "params.json")) num_shards = NUM_SHARDS[model_size] params = params.get("model", params) n_layers = params["n_layers"] n_heads = params["n_heads"] n_heads_per_shard = n_heads // num_shards dim = params["dim"] dims_per_head = dim // n_heads base = params.get("rope_theta", 10000.0) inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head)) if base > 10000.0: max_position_embeddings = 32768 if "mistral" in model_size else 16384 else: max_position_embeddings = 4096 if "mistral" in model_size else 2048
if "llama2" in model_size: tokenizer_class = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast elif "llama3" in model_size: try: from llama.tokenizer import Tokenizer as Llama3Tokenizer except ImportError: raise AssertionError("Module 'llama' is required but not installed.") tokenizer_class = Llama3Tokenizer elif "mistral" in model_size: tokenizer_class = MistralTokenizer else: raise AttributeError(f"model_size={model_size} not supported") if tokenizer_path is not None: if "llama" in model_size: tokenizer = tokenizer_class(tokenizer_path) if "llama2" in model_size: tokenizer.save_pretrained(model_path) vocab_size = tokenizer.vocab_size if tokenizer_path is not None else 32000 elif "mistral" in model_size: tokenizer = tokenizer_class.from_file(tokenizer_path) vocab_size = 32768 else: raise AttributeError(f"model_size={model_size} is not supported")
if params.get("n_kv_heads", None) is not None: num_key_value_heads = params["n_kv_heads"] # for GQA / MQA num_local_key_value_heads = n_heads_per_shard // num_key_value_heads key_value_dim = dim // num_key_value_heads else: # compatibility with other checkpoints num_key_value_heads = n_heads num_local_key_value_heads = n_heads_per_shard key_value_dim = dim
# permute for sliced rotary def permute(w, n_heads=n_heads, dim1=dim, dim2=dim): return w.view(n_heads, dim1 // n_heads // 2, 2, dim2).transpose(1, 2).reshape(dim1, dim2)
print(f"Fetching all parameters from the checkpoint at {input_base_path}.") # Load weights if num_shards == 1: # Not sharded # (The sharded implementation would also work, but this is simpler.) loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu") else: # Sharded loaded = [ torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu") for i in range(num_shards) ] param_count = 0 index_dict = {"weight_map": {}} for layer_i in range(n_layers): filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if num_shards == 1: # Unsharded q_proj = loaded[f"layers.{layer_i}.attention.wq.weight"] k_proj = loaded[f"layers.{layer_i}.attention.wk.weight"] if ("llama2" in model_size) or ("mistral" in model_size): q_proj = permute(q_proj) k_proj = permute(k_proj) state_dict = { f"model.layers.{layer_i}.self_attn.q_proj.weight": q_proj, f"model.layers.{layer_i}.self_attn.k_proj.weight": k_proj, f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"], f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"], f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"], f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"], f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"], f"model.layers.{layer_i}.input_layernorm.weight": loaded[f"layers.{layer_i}.attention_norm.weight"], f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
state_dict = { f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ f"layers.{layer_i}.attention_norm.weight" ].clone(), f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ f"layers.{layer_i}.ffn_norm.weight" ].clone(), } state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute( torch.cat( [ loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim) for i in range(num_shards) ], dim=0, ).reshape(dim, dim) ) state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute( torch.cat( [ loaded[i][f"layers.{layer_i}.attention.wk.weight"].view( num_local_key_value_heads, dims_per_head, dim ) for i in range(num_shards) ], dim=0, ).reshape(key_value_dim, dim), num_key_value_heads, key_value_dim, dim, ) state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat( [ loaded[i][f"layers.{layer_i}.attention.wv.weight"].view( num_local_key_value_heads, dims_per_head, dim ) for i in range(num_shards) ], dim=0, ).reshape(key_value_dim, dim)
state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat( [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1 ) state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat( [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(num_shards)], dim=0 ) state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat( [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(num_shards)], dim=1 ) state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat( [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(num_shards)], dim=0 )
state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq for k, v in state_dict.items(): index_dict["weight_map"][k] = filename param_count += v.numel() torch.save(state_dict, os.path.join(model_path, filename))
filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if num_shards == 1: # Unsharded state_dict = { "model.embed_tokens.weight": loaded["tok_embeddings.weight"], "model.norm.weight": loaded["norm.weight"], "lm_head.weight": loaded["output.weight"], } else: d = 0 if "llama3" in model_size else 1 state_dict = { "model.norm.weight": loaded[0]["norm.weight"], "model.embed_tokens.weight": torch.cat( [loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=d ), "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0), }
for k, v in state_dict.items(): index_dict["weight_map"][k] = filename param_count += v.numel() torch.save(state_dict, os.path.join(model_path, filename))
# Write configs index_dict["metadata"] = {"total_size": param_count * 2} write_json(index_dict, os.path.join(model_path, "pytorch_model.bin.index.json")) ffn_dim_multiplier = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1 multiple_of = params["multiple_of"] if "multiple_of" in params else 256 config = ModelConfig( hidden_size=dim, intermediate_size=compute_intermediate_size(dim, ffn_dim_multiplier, multiple_of), num_attention_heads=params["n_heads"], num_hidden_layers=params["n_layers"], rms_norm_eps=params["norm_eps"], num_key_value_heads=num_key_value_heads, vocab_size=vocab_size, rope_theta=base, max_position_embeddings=max_position_embeddings, ) config.save_pretrained(model_path)
# Make space so we can load the model properly now. del state_dict del loaded gc.collect()
return model_path
def load_args_from_checkpoint(args):
# Read Llama args. model_args_path = os.path.join(args.load, "config.json") with open(model_args_path) as f: model_args = json.load(f) # Update Megatron args. args.seq_length = 4096 args.max_position_embeddings = model_args["max_position_embeddings"] args.hidden_size = model_args["hidden_size"] args.num_attention_heads = model_args["num_attention_heads"] args.num_layers = model_args["num_hidden_layers"] args.global_batch_size = 1024 args.norm_epsilon = model_args["rms_norm_eps"] args.iteration = 1 # '0', 'release' don't work args.add_position_embedding = False args.use_rotary_position_embeddings = True args.swiglu = True args.normalization = "RMSNorm" args.add_bias_linear = False args.untie_embeddings_and_output_weights = True args.vocab_size = model_args["vocab_size"] args.padded_vocab_size = model_args["vocab_size"] args.ffn_hidden_size = model_args["intermediate_size"]
if "num_key_value_heads" in model_args: args.group_query_attention = True args.num_query_groups = model_args["num_key_value_heads"]
def set_preprocess_state(args, model, hf_model): '''Set embedding params.''' model.language_model.embedding.word_embeddings.weight.data.copy_( hf_model.model.embed_tokens.weight)
def set_postprocess_state(args, model, hf_model): '''Set output layer & norm params.''' model.language_model.encoder.final_norm.weight.data.copy_(hf_model.model.norm.weight) model.language_model.output_layer.weight.data.copy_(hf_model.lm_head.weight)
def set_attn_state(args, layer, hf_layer): '''Set self-attention params.'''
# Get attention layer & state. attn = layer.self_attention hf_attn = hf_layer.self_attn
# Reshape loaded weights. tp = args.tensor_model_parallel_size nh = args.num_attention_heads // tp ng = (args.num_query_groups if args.group_query_attention \ else args.num_attention_heads) // tp dim = args.kv_channels assert nh % ng == 0
# Copy weights (re-order dimensions for Megatron). attn.query_key_value.weight.data.copy_(torch.cat([ hf_attn.q_proj.weight.reshape((ng, dim*nh//ng, -1)), hf_attn.k_proj.weight.reshape((ng, dim, -1)), hf_attn.v_proj.weight.reshape((ng, dim, -1)), ], dim=1).reshape((-1, args.hidden_size))) attn.dense.weight.data.copy_(hf_attn.o_proj.weight)
def set_mlp_state(args, layer, hf_layer): '''Set MLP params.'''
mlp = layer.mlp hf_mlp = hf_layer.mlp
mlp.dense_h_to_4h.weight.data.copy_(torch.cat([ hf_mlp.gate_proj.weight, hf_mlp.up_proj.weight, ], dim=0)) mlp.dense_4h_to_h.weight.data.copy_(hf_mlp.down_proj.weight)
def set_layer_state(args, model, hf_model, layer_idx): '''Set transformer layer params.'''
layer = model.language_model.encoder.layers[layer_idx] hf_layer = hf_model.model.layers[layer_idx]
set_attn_state(args, layer, hf_layer) set_mlp_state(args, layer, hf_layer) layer.input_norm.weight.data.copy_(hf_layer.input_layernorm.weight) layer.post_attention_norm.weight.data.copy_(hf_layer.post_attention_layernorm.weight)
def load_checkpoint_to_model(args): '''Set model params.'''
from pretrain_gpt import model_provider if "llama" in args.model_size or "yi" in args.model_size: from transformers import LlamaForCausalLM as ModelForCausalLM elif "mistral" in args.model_size: from transformers import MistralForCausalLM as ModelForCausalLM else: raise AttributeError(f"args.model_size={args.model_size} not supported")
# Load Huggingface model. hf_model = ModelForCausalLM.from_pretrained(args.load, torch_dtype=args.params_dtype, low_cpu_mem_usage=True, device_map="cpu")
# Init Megatron model. model = model_provider(True, True).to(args.params_dtype)
# Set model state. set_preprocess_state(args, model, hf_model) set_postprocess_state(args, model, hf_model) for layer_idx in tqdm(range(args.num_layers), "set layer states"): set_layer_state(args, model, hf_model, layer_idx)
return model
def _load_checkpoint(queue, args):
verify_transformers_version()
# Search in directory above this. sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))) if args.megatron_path is not None: sys.path.insert(0, args.megatron_path)
# Convert Meta checkpoint to HF format as an intermediate step if args.checkpoint_type == "meta": model_tmp_path = convert_to_hf(model_path=os.path.join(args.save_dir, 'tmp'), input_base_path=args.load_dir, model_size=args.model_size, tokenizer_path=args.tokenizer_model) args.load_dir = model_tmp_path
try: from megatron.training.arguments import parse_args, validate_args from megatron.training.global_vars import set_args, set_global_variables from megatron.legacy.model import module from megatron.core import mpu from megatron.core.enums import ModelType from megatron.legacy import fused_kernels except ModuleNotFoundError: print("Unable to import Megatron, please specify the path to Megatron using --megatron-path. Exiting.") queue.put("exit") exit(1)
# We want all arguments to come from us. sys.argv = ['script.py', '--no-masked-softmax-fusion', '--no-bias-gelu-fusion', '--no-bias-dropout-fusion', '--no-async-tensor-model-parallel-allreduce', '--use-cpu-initialization', '--micro-batch-size', '1', '--no-load-optim', '--no-load-rng', '--no-save-optim', '--no-save-rng', '--mock-data', # To pass the "blend data checks" in arguments.py '--no-initialization', '--load', args.load_dir ]
margs = parse_args() margs.tokenizer_model = args.tokenizer_model load_args_from_checkpoint(margs)
if "llama2" in args.model_size or "yi" in args.model_size: margs.tokenizer_type = "Llama2Tokenizer" elif "llama3" in args.model_size: margs.tokenizer_type = "Llama3Tokenizer" elif "mistral" in args.model_size: margs.tokenizer_type = "MistralTokenizer"
# Arguments do sanity checks on the world size, but we don't care, # so trick it into thinking we are plenty of processes. margs.world_size = margs.tensor_model_parallel_size * margs.pipeline_model_parallel_size
margs = validate_args(margs)
margs.use_legacy_models = True margs.transformer_impl = args.loader_transformer_impl
def check_for_arg(arg_name, default=None): if getattr(margs, arg_name, None) is None: if default is not None: setattr(margs, arg_name, default) else: print(f"Checkpoint does not specify the argument {arg_name}. Exiting.") print(f"Arguments: {margs}") queue.put("exit") exit(1)
check_for_arg('tensor_model_parallel_size') check_for_arg('pipeline_model_parallel_size') check_for_arg('num_layers') check_for_arg('hidden_size') check_for_arg('seq_length') check_for_arg('num_attention_heads') check_for_arg('max_position_embeddings') check_for_arg('position_embedding_type') check_for_arg('iteration') check_for_arg('bert_binary_head') check_for_arg('disable_bias_linear', False) check_for_arg('params_dtype') check_for_arg('swiglu', False)
# Determine how to make our models. assert args.model_type == 'GPT', 'Llama-2, Llama-3 and Mistral are GPT models.' margs.model_type = ModelType.encoder_or_decoder margs.params_dtype = torch.bfloat16 if args.bf16 else torch.float16 if args.fp16 else torch.float32
# Suppress warning about torch.distributed not being initialized. module.MegatronModule.embedding_warning_printed = True
set_global_variables(margs, build_tokenizer=False) mpu.set_tensor_model_parallel_world_size(margs.tensor_model_parallel_size) mpu.set_pipeline_model_parallel_world_size(margs.pipeline_model_parallel_size) mpu.set_virtual_pipeline_model_parallel_world_size(margs.virtual_pipeline_model_parallel_size) fused_kernels.load(margs)
# Short aliases. tp_size = margs.tensor_model_parallel_size pp_size = margs.pipeline_model_parallel_size vp_size = margs.virtual_pipeline_model_parallel_size if vp_size is None: vp_size = 1
# Metadata. md = types.SimpleNamespace() md.model_type = args.model_type md.num_layers = margs.num_layers md.hidden_size = margs.hidden_size md.seq_length = margs.seq_length md.num_attention_heads = margs.num_attention_heads md.max_position_embeddings = margs.max_position_embeddings md.tokenizer_type = margs.tokenizer_type md.iteration = margs.iteration md.params_dtype = margs.params_dtype md.bert_binary_head = margs.bert_binary_head md.output_layer = margs.untie_embeddings_and_output_weights md.position_embedding_type = margs.position_embedding_type md.linear_bias = margs.add_bias_linear md.norm_has_bias = False md.swiglu = margs.swiglu md.previous_tensor_parallel_size = margs.tensor_model_parallel_size md.previous_pipeline_parallel_size = margs.pipeline_model_parallel_size md.make_vocab_size_divisible_by = None md.checkpoint_args = margs md.consumed_train_samples = 0 md.consumed_valid_samples = 0
margs.model_size = args.model_size
# Get true (non-padded) vocab size if margs.tokenizer_model is not None and "llama3" in args.model_size: try: from llama.tokenizer import Tokenizer as Llama3Tokenizer except ImportError: raise AssertionError("Module 'llama' is required but not installed.") tokenizer = Llama3Tokenizer(margs.tokenizer_model) md.true_vocab_size = tokenizer.vocab_size else: md.true_vocab_size = None
# Get first pipe stage. mpu.set_tensor_model_parallel_rank(0) mpu.set_pipeline_model_parallel_rank(0) model = load_checkpoint_to_model(margs)
queue.put(md)
def queue_put(name, msg): print(f"sending {name}") msg["name"] = name queue.put(msg)
# Send embeddings. message = { "word embeddings": model.language_model.embedding.word_embeddings.weight.data } if md.position_embedding_type == 'learned_absolute': message["position embeddings"] = model.language_model.embedding.position_embeddings.weight.data else: assert not hasattr(model.language_model.embedding, 'position_embeddings')
queue_put("embeddings", message)
for layer_num in range(margs.num_layers): message = {}
# Get non-parallel tensors from tp_rank 0. layer = model.language_model.encoder.layers[layer_num] message["input norm weight"] = layer.input_norm.weight.data message["post norm weight"] = layer.post_attention_norm.weight.data if md.linear_bias: message["dense bias"] = layer.self_attention.dense.bias.data message["mlp l1 bias"] = layer.mlp.dense_4h_to_h.bias.data
# Grab all parallel tensors for this layer. qkv_weight = [] qkv_bias = [] dense_weight = [] mlp_l0_weight = [] mlp_l0_bias = [] mlp_l1_weight = [] layer = model.language_model.encoder.layers[layer_num] qkv_weight.append(layer.self_attention.query_key_value.weight.data) dense_weight.append(layer.self_attention.dense.weight.data) mlp_l0_weight.append(layer.mlp.dense_h_to_4h.weight.data) mlp_l1_weight.append(layer.mlp.dense_4h_to_h.weight.data) if md.linear_bias: qkv_bias.append(layer.self_attention.query_key_value.bias.data) mlp_l0_bias.append(layer.mlp.dense_h_to_4h.bias.data)
# Handle gated linear units. if md.swiglu: # Concat all the first halves ('W's) and all the second halves ('V's). for tp_rank in range(tp_size): mlp_l0_weight[tp_rank] = torch.chunk(mlp_l0_weight[tp_rank], 2, dim=0) message["mlp l0 weight W"] = torch.cat([w[0] for w in mlp_l0_weight], dim=0) message["mlp l0 weight V"] = torch.cat([w[1] for w in mlp_l0_weight], dim=0) else: message["mlp l0 weight"] = torch.cat(mlp_l0_weight, dim=0)
# Simple concat of the rest. message["qkv weight"] = torch.cat(qkv_weight, dim=0) message["dense weight"] = torch.cat(dense_weight, dim=1) message["mlp l1 weight"] = torch.cat(mlp_l1_weight, dim=1) if md.linear_bias: message["qkv bias"] = torch.cat(qkv_bias, dim=0) if md.swiglu: for tp_rank in range(tp_size): mlp_l0_bias[tp_rank] = torch.chunk(mlp_l0_bias[tp_rank], 2, dim=0) message["mlp l0 bias W"] = torch.cat([b[0] for b in mlp_l0_bias],dim=0) message["mlp l0 bias V"] = torch.cat([b[1] for b in mlp_l0_bias],dim=0) else: message["mlp l0 bias"] = torch.cat(mlp_l0_bias, dim=0)
queue_put(f"transformer layer {layer_num}", message)
# Send final norm from tp_rank 0. message = { "weight": model.language_model.encoder.final_norm.weight.data, } queue_put("final norm", message)
if md.output_layer: message = { "weight": model.language_model.output_layer.weight.data } queue_put("output layer", message)
queue.put("done")
if args.checkpoint_type == "meta": shutil.rmtree(os.path.join(args.save_dir, 'tmp'))
def load_checkpoint(queue, args): try: _load_checkpoint(queue, args) except: queue.put("exit") raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
import jsonimport osimport sysimport torchimport types
from utils import get_mcore_transformer_block_key, print_memory_usage
def add_arguments(parser): group = parser.add_argument_group(title='Megatron loader')
group.add_argument('--true-vocab-size', type=int, default=None, help='original size of vocab, if specified will trim padding from embedding table.') group.add_argument('--vocab-file', type=str, default=None, help='Path to the vocab file. If specified will use this to get vocab size and ' 'trim padding from the embedding table.') group.add_argument('--megatron-path', type=str, default=None, help='Base directory of Megatron repository') group.add_argument('--position-embedding-type', type=str, default='learned_absolute', choices=['learned_absolute', 'rope'], help='Position embedding type.') group.add_argument('--loader-transformer-impl', default='transformer_engine', choices=['local', 'transformer_engine'], help='Which Transformer implementation to use.')
def _load_checkpoint(queue, args):
# Search in directory above this sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir))) if args.megatron_path is not None: sys.path.insert(0, args.megatron_path)
try: from megatron.training.arguments import parse_args, validate_args from megatron.training.global_vars import set_args, set_global_variables from megatron.training.checkpointing import load_args_from_checkpoint, load_checkpoint from megatron.legacy.model import module from megatron.core import mpu from megatron.core.enums import ModelType from megatron.legacy import fused_kernels except ModuleNotFoundError: print("Unable to import Megatron, please specify the path to Megatron using --megatron-path. Exiting.") queue.put("exit") exit(1)
# We want all arguments to come from us sys.argv = ['script.py', '--no-masked-softmax-fusion', '--no-bias-gelu-fusion', '--no-bias-dropout-fusion', '--no-async-tensor-model-parallel-allreduce', '--use-cpu-initialization', '--micro-batch-size', '1', '--no-load-optim', '--no-load-rng', '--no-save-optim', '--no-save-rng', '--no-initialization', '--mock-data', # To pass the "blend data checks" in arguments.py '--load', args.load_dir, '--position-embedding-type', args.position_embedding_type, ]
margs = parse_args() margs, checkpoint_args = load_args_from_checkpoint(margs, exit_on_missing_checkpoint=True)
# Arguments do sanity checks on the world size, but we don't care, # so trick it into thinking we are plenty of processes margs.world_size = margs.tensor_model_parallel_size * margs.pipeline_model_parallel_size
# Explicitly copy data types from checkpoint. margs.fp16 = checkpoint_args.fp16 margs.bf16 = checkpoint_args.bf16
# Validate margs. margs = validate_args(margs)
margs.use_legacy_models = False margs.transformer_impl = args.loader_transformer_impl
def check_for_arg(arg_name, default=None): if getattr(margs, arg_name, None) is None: if default is not None: setattr(margs, arg_name, default) else: print(f"Checkpoint does not specify the argument {arg_name}. Exiting.") print(f"Arguments: {margs}") queue.put("exit") exit(1)
check_for_arg('tensor_model_parallel_size') check_for_arg('pipeline_model_parallel_size') check_for_arg('num_layers') check_for_arg('hidden_size') check_for_arg('seq_length') check_for_arg('num_attention_heads') check_for_arg('max_position_embeddings') check_for_arg('position_embedding_type') check_for_arg('tokenizer_type') check_for_arg('iteration') check_for_arg('bert_binary_head') check_for_arg('disable_bias_linear', False) check_for_arg('params_dtype') check_for_arg('swiglu', False)
# Determine how to make our models if args.model_type == 'GPT': from pretrain_gpt import model_provider margs.model_type = ModelType.encoder_or_decoder elif args.model_type == 'BERT': from pretrain_bert import model_provider margs.model_type = ModelType.encoder_or_decoder else: raise Exception(f'unrecognized model type: {args.model_type}')
# supress warning about torch.distributed not being initialized module.MegatronModule.embedding_warning_printed = True
consumed_train_samples = None consumed_valid_samples = None def get_models(count, dtype): nonlocal consumed_train_samples nonlocal consumed_valid_samples model_array_len = margs.virtual_pipeline_model_parallel_size if model_array_len is None: model_array_len = 1 models = [[] for _ in range(model_array_len)] pre_process = mpu.is_pipeline_first_stage() post_process = mpu.is_pipeline_last_stage() for rank in range(count): mpu.set_tensor_model_parallel_rank(rank) if margs.virtual_pipeline_model_parallel_size is not None: model_ = [] for i in range(margs.virtual_pipeline_model_parallel_size): mpu.set_virtual_pipeline_model_parallel_rank(i) # Set pre_process and post_process only after virtual rank is set. pre_process = mpu.is_pipeline_first_stage() post_process = mpu.is_pipeline_last_stage() this_model = model_provider( pre_process=pre_process, post_process=post_process ).to(dtype) model_.append(this_model) else: pre_process = mpu.is_pipeline_first_stage() post_process = mpu.is_pipeline_last_stage() model_rank = 0 model_ = [model_provider(pre_process, post_process).to(dtype)] margs.consumed_train_samples = 0 margs.consumed_valid_samples = 0 margs.exit_on_missing_checkpoint = True load_checkpoint(model_, None, None)
if consumed_train_samples is not None: assert(margs.consumed_train_samples == consumed_train_samples) else: consumed_train_samples = margs.consumed_train_samples if consumed_valid_samples is not None: assert(margs.consumed_valid_samples == consumed_valid_samples) else: consumed_valid_samples = margs.consumed_valid_samples for vp_rank in range(model_array_len): models[vp_rank].append(model_[vp_rank])
# Print memory usage. print_memory_usage("loader", rank, count)
return models
set_global_variables(margs, build_tokenizer=False) mpu.set_tensor_model_parallel_world_size(margs.tensor_model_parallel_size) mpu.set_pipeline_model_parallel_world_size(margs.pipeline_model_parallel_size) mpu.set_virtual_pipeline_model_parallel_world_size(margs.virtual_pipeline_model_parallel_size) fused_kernels.load(margs)
# Get true (non-padded) vocab size if args.true_vocab_size is not None: true_vocab_size = args.true_vocab_size elif args.vocab_file is not None: vocab = json.load(open(args.vocab_file)) true_vocab_size = len(vocab) if args.true_vocab_size is not None and true_vocab_size != args.true_vocab_size: print("Both --true-vocab-size and --vocab-file specified and the vocab size does not match, aborting.") queue.put("exit") exit(1) else: true_vocab_size = None
# short aliases tp_size = margs.tensor_model_parallel_size pp_size = margs.pipeline_model_parallel_size vp_size = margs.virtual_pipeline_model_parallel_size if vp_size is None: vp_size = 1
# Layernorm has bias; RMSNorm does not. if hasattr(checkpoint_args, 'normalization'): norm_has_bias = checkpoint_args.normalization == "LayerNorm" else: # older models only supported LayerNorm norm_has_bias = True
# metadata md = types.SimpleNamespace() md.model_type = args.model_type md.num_layers = margs.num_layers md.hidden_size = margs.hidden_size md.seq_length = margs.seq_length md.num_attention_heads = margs.num_attention_heads md.max_position_embeddings = margs.max_position_embeddings md.tokenizer_type = margs.tokenizer_type md.iteration = margs.iteration md.params_dtype = margs.params_dtype md.bert_binary_head = margs.bert_binary_head md.output_layer = margs.untie_embeddings_and_output_weights md.position_embedding_type = margs.position_embedding_type md.linear_bias = margs.add_bias_linear md.norm_has_bias = norm_has_bias md.swiglu = margs.swiglu md.previous_tensor_parallel_size = margs.tensor_model_parallel_size md.previous_pipeline_parallel_size = margs.pipeline_model_parallel_size md.true_vocab_size = true_vocab_size md.make_vocab_size_divisible_by = margs.make_vocab_size_divisible_by md.checkpoint_args = checkpoint_args md.use_legacy_models = margs.use_legacy_models
# Get transformer block (named either 'encoder' or 'decoder'). transformer_block_key = get_mcore_transformer_block_key(md.model_type) def get_transformer_block(_model): return getattr(_model, transformer_block_key)
# Get first pipe stage mpu.set_pipeline_model_parallel_rank(0) all_models = [get_models(tp_size, md.params_dtype)] models = all_models[0][0]
md.consumed_train_samples = consumed_train_samples md.consumed_valid_samples = consumed_valid_samples queue.put(md)
def queue_put(name, msg): print(f"sending {name}") msg["name"] = name queue.put(msg)
# Send embeddings message = { "word embeddings": torch.cat( [models[tp_rank].embedding.word_embeddings.weight.data for tp_rank in range(tp_size)], dim = 0) } if md.position_embedding_type == 'learned_absolute': message["position embeddings"] = models[0].embedding.position_embeddings.weight.data else: assert not hasattr(models[0].embedding, 'position_embeddings')
queue_put("embeddings", message)
total_layer_num = 0 for vp_rank in range(vp_size): mpu.set_virtual_pipeline_model_parallel_rank(vp_rank) for pp_rank in range(pp_size): if pp_rank > 0: mpu.set_pipeline_model_parallel_rank(pp_rank) if vp_rank == 0: all_models.append(get_models(tp_size, md.params_dtype)) models = all_models[pp_rank][vp_rank] for layer_num in range(len(get_transformer_block(models[0]).layers)): message = {}
# Get non-parallel tensors from tp_rank 0 layer = get_transformer_block(models[0]).layers[layer_num] message["input norm weight"] = layer.self_attention.linear_qkv.layer_norm_weight.data if norm_has_bias: message["input norm bias"] = layer.self_attention.linear_qkv.layer_norm_bias.data message["post norm weight"] = layer.mlp.linear_fc1.layer_norm_weight.data if norm_has_bias: message["post norm bias"] = layer.mlp.linear_fc1.layer_norm_bias.data if md.linear_bias: message["dense bias"] = layer.self_attention.linear_proj.bias.data message["mlp l1 bias"] = layer.mlp.linear_fc2.bias.data
# Grab all parallel tensors for this layer qkv_weight = [] qkv_bias = [] dense_weight = [] mlp_l0_weight = [] mlp_l0_bias = [] mlp_l1_weight = [] for tp_rank, model in enumerate(models): layer = get_transformer_block(model).layers[layer_num] qkv_weight.append(layer.self_attention.linear_qkv.weight.data) dense_weight.append(layer.self_attention.linear_proj.weight.data) mlp_l0_weight.append(layer.mlp.linear_fc1.weight.data) mlp_l1_weight.append(layer.mlp.linear_fc2.weight.data) if md.linear_bias: qkv_bias.append(layer.self_attention.linear_qkv.bias.data) mlp_l0_bias.append(layer.mlp.linear_fc1.bias.data)
# Handle gated linear units if md.swiglu: # concat all the first halves ('W's) and all the second halves ('V's) for tp_rank in range(tp_size): mlp_l0_weight[tp_rank] = torch.chunk(mlp_l0_weight[tp_rank], 2, dim=0) message["mlp l0 weight W"] = torch.cat([w[0] for w in mlp_l0_weight], dim=0) message["mlp l0 weight V"] = torch.cat([w[1] for w in mlp_l0_weight], dim=0) else: message["mlp l0 weight"] = torch.cat(mlp_l0_weight, dim=0)
# simple concat of the rest message["qkv weight"] = torch.cat(qkv_weight, dim=0) message["dense weight"] = torch.cat(dense_weight, dim=1) message["mlp l1 weight"] = torch.cat(mlp_l1_weight, dim=1) if md.linear_bias: message["qkv bias"] = torch.cat(qkv_bias, dim=0) if md.swiglu: for tp_rank in range(tp_size): mlp_l0_bias[tp_rank] = torch.chunk(mlp_l0_bias[tp_rank], 2, dim=0) message["mlp l0 bias W"] = torch.cat([b[0] for b in mlp_l0_bias],dim=0) message["mlp l0 bias V"] = torch.cat([b[1] for b in mlp_l0_bias],dim=0) else: message["mlp l0 bias"] = torch.cat(mlp_l0_bias, dim=0)
queue_put(f"transformer layer {total_layer_num}", message)
total_layer_num = total_layer_num + 1
# Send final norm from tp_rank 0 message = { "weight": get_transformer_block(models[0]).final_layernorm.weight.data, } if norm_has_bias: message["bias"] = get_transformer_block(models[0]).final_layernorm.bias.data queue_put("final norm", message)
if md.output_layer: message = { "weight": torch.cat( [models[tp_rank].output_layer.weight.data for tp_rank in range(tp_size)], dim = 0) } queue_put("output layer", message)
# Send BERT lm head and binary head if it exists if md.model_type == 'BERT': message = { "weight": models[0].pooler.dense.weight.data, "bias": models[0].pooler.dense.bias.data } queue_put("pooler", message)
message = { "dense weight": models[0].lm_head.dense.weight.data, "dense bias": models[0].lm_head.dense.bias.data, "norm weight": models[0].lm_head.layer_norm.weight.data, } if norm_has_bias: message["norm bias"] = models[0].lm_head.layer_norm.bias.data queue_put("lm head", message)
if md.bert_binary_head: message = { "weight": models[0].binary_head.weight.data, "bias": models[0].binary_head.bias.data } queue_put("binary head", message) queue.put("done")
def load_checkpoint(queue, args): try: _load_checkpoint(queue, args) except: queue.put("exit") raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import jsonimport osimport sysimport types
import torch
def add_arguments(parser): group = parser.add_argument_group(title='Megatron loader')
group.add_argument('--true-vocab-size', type=int, default=None, help='original size of vocab, if specified will trim padding from embedding table.') group.add_argument('--vocab-file', type=str, default=None, help='Path to the vocab file. If specified will use this to get vocab size and ' 'trim padding from the embedding table.') group.add_argument('--megatron-path', type=str, default=None, help='Base directory of Megatron repository') group.add_argument('--position-embedding-type', type=str, default='learned_absolute', choices=['learned_absolute', 'rope'], help='Position embedding type.') group.add_argument('--loader-transformer-impl', default='local', choices=['local', 'transformer_engine'], help='Which Transformer implementation to use.')
def _load_checkpoint(queue, args):
# Search in directory above this sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir))) if args.megatron_path is not None: sys.path.insert(0, args.megatron_path)
try: from megatron.training.arguments import parse_args, validate_args from megatron.training.global_vars import set_args, set_global_variables from megatron.training.checkpointing import load_args_from_checkpoint, load_checkpoint from megatron.legacy.model import module from megatron.core import mpu from megatron.core.enums import ModelType from megatron.legacy import fused_kernels except ModuleNotFoundError: print("Unable to import Megatron, please specify the path to Megatron using --megatron-path. Exiting.") queue.put("exit") exit(1)
# We want all arguments to come from us sys.argv = ['script.py', '--no-masked-softmax-fusion', '--no-bias-gelu-fusion', '--no-bias-dropout-fusion', '--no-async-tensor-model-parallel-allreduce', '--use-cpu-initialization', '--micro-batch-size', '1', '--no-load-optim', '--no-load-rng', '--no-save-optim', '--no-save-rng', '--mock-data', # To pass the "blend data checks" in arguments.py '--no-initialization', '--load', args.load_dir, '--position-embedding-type', args.position_embedding_type, ]
margs = parse_args() margs, checkpoint_args = load_args_from_checkpoint(margs, exit_on_missing_checkpoint=True)
# Arguments do sanity checks on the world size, but we don't care, # so trick it into thinking we are plenty of processes margs.world_size = margs.tensor_model_parallel_size * margs.pipeline_model_parallel_size
# Explicitly copy data types from checkpoint. margs.fp16 = checkpoint_args.fp16 margs.bf16 = checkpoint_args.bf16
# Validate margs. margs = validate_args(margs)
margs.use_legacy_models = True margs.transformer_impl = args.loader_transformer_impl
def check_for_arg(arg_name, default=None): if getattr(margs, arg_name, None) is None: if default is not None: setattr(margs, arg_name, default) else: print(f"Checkpoint does not specify the argument {arg_name}. Exiting.") print(f"Arguments: {margs}") queue.put("exit") exit(1)
check_for_arg('tensor_model_parallel_size') check_for_arg('pipeline_model_parallel_size') check_for_arg('num_layers') check_for_arg('hidden_size') check_for_arg('seq_length') check_for_arg('num_attention_heads') check_for_arg('max_position_embeddings') check_for_arg('position_embedding_type') check_for_arg('tokenizer_type') check_for_arg('iteration') check_for_arg('bert_binary_head') check_for_arg('disable_bias_linear', False) check_for_arg('params_dtype') check_for_arg('swiglu', False)
# Determine how to make our models if args.model_type == 'GPT': from pretrain_gpt import model_provider margs.model_type = ModelType.encoder_or_decoder elif args.model_type == 'BERT': from pretrain_bert import model_provider margs.model_type = ModelType.encoder_or_decoder else: raise Exception(f'unrecognized model type: {args.model_type}')
# supress warning about torch.distributed not being initialized module.MegatronModule.embedding_warning_printed = True
consumed_train_samples = None consumed_valid_samples = None def get_models(count, dtype): nonlocal consumed_train_samples nonlocal consumed_valid_samples model_array_len = margs.virtual_pipeline_model_parallel_size if model_array_len is None: model_array_len = 1 models = [[] for _ in range(model_array_len)] pre_process = mpu.is_pipeline_first_stage() post_process = mpu.is_pipeline_last_stage() for rank in range(count): mpu.set_tensor_model_parallel_rank(rank) if margs.virtual_pipeline_model_parallel_size is not None: model_ = [] for i in range(margs.virtual_pipeline_model_parallel_size): mpu.set_virtual_pipeline_model_parallel_rank(i) # Set pre_process and post_process only after virtual rank is set. pre_process = mpu.is_pipeline_first_stage() post_process = mpu.is_pipeline_last_stage() this_model = model_provider( pre_process=pre_process, post_process=post_process ).to(dtype) model_.append(this_model) else: pre_process = mpu.is_pipeline_first_stage() post_process = mpu.is_pipeline_last_stage() model_rank = 0 model_ = [model_provider(pre_process, post_process).to(dtype)] margs.consumed_train_samples = 0 margs.consumed_valid_samples = 0 margs.exit_on_missing_checkpoint = True load_checkpoint(model_, None, None)
if consumed_train_samples is not None: assert(margs.consumed_train_samples == consumed_train_samples) else: consumed_train_samples = margs.consumed_train_samples if consumed_valid_samples is not None: assert(margs.consumed_valid_samples == consumed_valid_samples) else: consumed_valid_samples = margs.consumed_valid_samples for vp_rank in range(model_array_len): models[vp_rank].append(model_[vp_rank]) return models
set_global_variables(margs, build_tokenizer=False) mpu.set_tensor_model_parallel_world_size(margs.tensor_model_parallel_size) mpu.set_pipeline_model_parallel_world_size(margs.pipeline_model_parallel_size) mpu.set_virtual_pipeline_model_parallel_world_size(margs.virtual_pipeline_model_parallel_size) fused_kernels.load(margs)
# Get true (non-padded) vocab size if args.true_vocab_size is not None: true_vocab_size = args.true_vocab_size elif args.vocab_file is not None: vocab = json.load(open(args.vocab_file)) true_vocab_size = len(vocab) if args.true_vocab_size is not None and true_vocab_size != args.true_vocab_size: print("Both --true-vocab-size and --vocab-file specified and the vocab size does not match, aborting.") queue.put("exit") exit(1) else: true_vocab_size = None
# short aliases tp_size = margs.tensor_model_parallel_size pp_size = margs.pipeline_model_parallel_size vp_size = margs.virtual_pipeline_model_parallel_size if vp_size is None: vp_size = 1
# Layernorm has bias; RMSNorm does not. if hasattr(checkpoint_args, 'normalization'): norm_has_bias = checkpoint_args.normalization == "LayerNorm" else: # older models only supported LayerNorm norm_has_bias = True
# metadata md = types.SimpleNamespace() md.model_type = args.model_type md.num_layers = margs.num_layers md.hidden_size = margs.hidden_size md.seq_length = margs.seq_length md.num_attention_heads = margs.num_attention_heads md.max_position_embeddings = margs.max_position_embeddings md.tokenizer_type = margs.tokenizer_type md.iteration = margs.iteration md.params_dtype = margs.params_dtype md.bert_binary_head = margs.bert_binary_head md.output_layer = margs.untie_embeddings_and_output_weights md.position_embedding_type = margs.position_embedding_type md.linear_bias = margs.add_bias_linear md.norm_has_bias = norm_has_bias md.swiglu = margs.swiglu md.previous_tensor_parallel_size = margs.tensor_model_parallel_size md.previous_pipeline_parallel_size = margs.pipeline_model_parallel_size md.true_vocab_size = true_vocab_size md.make_vocab_size_divisible_by = margs.make_vocab_size_divisible_by md.checkpoint_args = checkpoint_args
# Get first pipe stage mpu.set_pipeline_model_parallel_rank(0) all_models = [get_models(tp_size, md.params_dtype)] models = all_models[0][0]
md.consumed_train_samples = consumed_train_samples md.consumed_valid_samples = consumed_valid_samples queue.put(md)
def queue_put(name, msg): print(f"sending {name}") msg["name"] = name queue.put(msg)
# Send embeddings message = { "word embeddings": torch.cat( [models[tp_rank].language_model.embedding.word_embeddings.weight.data for tp_rank in range(tp_size)], dim = 0) } if md.position_embedding_type == 'learned_absolute': message["position embeddings"] = models[0].language_model.embedding.position_embeddings.weight.data else: assert not hasattr(models[0].language_model.embedding, 'position_embeddings')
queue_put("embeddings", message)
total_layer_num = 0 for vp_rank in range(vp_size): mpu.set_virtual_pipeline_model_parallel_rank(vp_rank) for pp_rank in range(pp_size): if pp_rank > 0: mpu.set_pipeline_model_parallel_rank(pp_rank) if vp_rank == 0: all_models.append(get_models(tp_size, md.params_dtype)) models = all_models[pp_rank][vp_rank] for layer_num in range(len(models[0].language_model.encoder.layers)): message = {}
# Get non-parallel tensors from tp_rank 0 layer = models[0].language_model.encoder.layers[layer_num] message["input norm weight"] = layer.input_norm.weight.data if norm_has_bias: message["input norm bias"] = layer.input_norm.bias.data message["post norm weight"] = layer.post_attention_norm.weight.data if norm_has_bias: message["post norm bias"] = layer.post_attention_norm.bias.data if md.linear_bias: message["dense bias"] = layer.self_attention.dense.bias.data message["mlp l1 bias"] = layer.mlp.dense_4h_to_h.bias.data
# Grab all parallel tensors for this layer qkv_weight = [] qkv_bias = [] dense_weight = [] mlp_l0_weight = [] mlp_l0_bias = [] mlp_l1_weight = [] for tp_rank, model in enumerate(models): layer = model.language_model.encoder.layers[layer_num] qkv_weight.append(layer.self_attention.query_key_value.weight.data) dense_weight.append(layer.self_attention.dense.weight.data) mlp_l0_weight.append(layer.mlp.dense_h_to_4h.weight.data) mlp_l1_weight.append(layer.mlp.dense_4h_to_h.weight.data) if md.linear_bias: qkv_bias.append(layer.self_attention.query_key_value.bias.data) mlp_l0_bias.append(layer.mlp.dense_h_to_4h.bias.data)
# Handle gated linear units if md.swiglu: # concat all the first halves ('W's) and all the second halves ('V's) for tp_rank in range(tp_size): mlp_l0_weight[tp_rank] = torch.chunk(mlp_l0_weight[tp_rank], 2, dim=0) message["mlp l0 weight W"] = torch.cat([w[0] for w in mlp_l0_weight], dim=0) message["mlp l0 weight V"] = torch.cat([w[1] for w in mlp_l0_weight], dim=0) else: message["mlp l0 weight"] = torch.cat(mlp_l0_weight, dim=0)
# simple concat of the rest message["qkv weight"] = torch.cat(qkv_weight, dim=0) message["dense weight"] = torch.cat(dense_weight, dim=1) message["mlp l1 weight"] = torch.cat(mlp_l1_weight, dim=1) if md.linear_bias: message["qkv bias"] = torch.cat(qkv_bias, dim=0) if md.swiglu: for tp_rank in range(tp_size): mlp_l0_bias[tp_rank] = torch.chunk(mlp_l0_bias[tp_rank], 2, dim=0) message["mlp l0 bias W"] = torch.cat([b[0] for b in mlp_l0_bias],dim=0) message["mlp l0 bias V"] = torch.cat([b[1] for b in mlp_l0_bias],dim=0) else: message["mlp l0 bias"] = torch.cat(mlp_l0_bias, dim=0)
queue_put(f"transformer layer {total_layer_num}", message)
total_layer_num = total_layer_num + 1
# Send final norm from tp_rank 0 message = { "weight": models[0].language_model.encoder.final_norm.weight.data, } if norm_has_bias: message["bias"] = models[0].language_model.encoder.final_norm.bias.data queue_put("final norm", message)
if md.output_layer: message = { "weight": torch.cat( [models[tp_rank].language_model.output_layer.weight.data for tp_rank in range(tp_size)], dim = 0) } queue_put("output layer", message)
# Send BERT lm head and binary head if it exists if md.model_type == 'BERT': message = { "weight": models[0].language_model.pooler.dense.weight.data, "bias": models[0].language_model.pooler.dense.bias.data } queue_put("pooler", message)
message = { "dense weight": models[0].lm_head.dense.weight.data, "dense bias": models[0].lm_head.dense.bias.data, "norm weight": models[0].lm_head.norm.weight.data, } if norm_has_bias: message["norm bias"] = models[0].lm_head.norm.bias.data queue_put("lm head", message)
if md.bert_binary_head: message = { "weight": models[0].binary_head.weight.data, "bias": models[0].binary_head.bias.data } queue_put("binary head", message) queue.put("done")
def load_checkpoint(queue, args): try: _load_checkpoint(queue, args) except: queue.put("exit") raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
import jsonimport osimport sysimport torchimport transformersfrom tqdm import tqdmimport types
def add_arguments(parser): group = parser.add_argument_group(title='Mixtral HF loader.')
group.add_argument('--true-vocab-size', type=int, default=None, help='original size of vocab, if specified will trim padding from embedding table.') group.add_argument('--vocab-file', type=str, default=None, help='Path to the vocab file. If specified will use this to get vocab size and ' 'trim padding from the embedding table.') group.add_argument('--tokenizer-model', required=True, help='Sentencepiece tokenizer model.') group.add_argument('--megatron-path', type=str, default=None, help='Base directory of deepspeed repository')
def load_args_from_checkpoint(args): # Read Mixtral 8x7B args. from transformers import MixtralConfig mixtral_config = MixtralConfig.from_pretrained(args.load)
# Update Megatron args. args.untie_embeddings_and_output_weights = True args.seq_length = 4096 args.global_batch_size = 1024 args.iteration = 1 # '0', 'release' don't work args.add_position_embedding = False args.use_rotary_position_embeddings = True args.swiglu = True args.bf16 = True args.add_bias_linear = False args.normalization = "RMSNorm" args.tokenizer_type = "Llama2Tokenizer" args.disable_bias_linear = True
args.max_position_embeddings = mixtral_config.max_position_embeddings args.hidden_size = mixtral_config.hidden_size args.num_attention_heads = mixtral_config.num_attention_heads args.num_layers = mixtral_config.num_hidden_layers args.norm_epsilon = mixtral_config.rms_norm_eps args.vocab_size = mixtral_config.vocab_size args.padded_vocab_size = mixtral_config.vocab_size args.mixtral = mixtral_config args.ffn_hidden_size = mixtral_config.intermediate_size args.num_experts = mixtral_config.num_local_experts args.sequence_parallel = True
if mixtral_config.num_key_value_heads: args.group_query_attention = True args.num_query_groups = mixtral_config.num_key_value_heads
def verify_transformers_version(): major, minor, patch = map(int, transformers.__version__.split('.')) assert major >= 4 and minor >= 36
def set_preprocess_state(args, model, hf_model): '''Set embedding params.''' model.embedding.word_embeddings.weight.data.copy_( hf_model.model.embed_tokens.weight)
def set_postprocess_state(args, model, hf_model): '''Set output layer & norm params.''' model.decoder.final_layernorm.weight.data.copy_(hf_model.model.norm.weight) model.output_layer.weight.data.copy_(hf_model.lm_head.weight)
def set_attn_state(args, layer, hf_layer): '''Set self-attention params.'''
# Get attention layer & state. attn = layer.self_attention hf_attn = hf_layer.self_attn
# Reshape loaded weights. tp = args.tensor_model_parallel_size num_heads = args.num_attention_heads // tp num_query_groups = (args.num_query_groups if args.group_query_attention else args.num_attention_heads) // tp num_querys_per_group = num_heads // num_query_groups dim = args.kv_channels assert num_heads % num_querys_per_group == 0
# Copy weights (re-order dimensions for Megatron). attn.linear_qkv.weight.data.copy_(torch.cat([ hf_attn.q_proj.weight.reshape((num_query_groups, num_querys_per_group*dim, -1)), hf_attn.k_proj.weight.reshape((num_query_groups, dim, -1)), hf_attn.v_proj.weight.reshape((num_query_groups, dim, -1)), ], dim=1).reshape((-1, args.hidden_size))) attn.linear_proj.weight.data.copy_(hf_attn.o_proj.weight)
def set_mlp_state(args, layer, hf_layer): '''Set MLP params.'''
layer.mlp.router.weight.data.copy_(hf_layer.block_sparse_moe.gate.weight)
mcore_experts = layer.mlp.experts.local_experts hf_experts = hf_layer.block_sparse_moe.experts for expert_idx in range(args.num_experts): mcore_experts[expert_idx].linear_fc1.weight.data.copy_( torch.cat([ hf_experts[expert_idx].w1.weight, hf_experts[expert_idx].w3.weight ], dim=0) ) mcore_experts[expert_idx].linear_fc2.weight.data.copy_( hf_experts[expert_idx].w2.weight )
def set_layer_state(args, model, hf_model, layer_idx): '''Set transformer layer params.'''
layer = model.decoder.layers[layer_idx] hf_layer = hf_model.model.layers[layer_idx]
set_attn_state(args, layer, hf_layer) set_mlp_state(args, layer, hf_layer)
layer.self_attention.linear_qkv.layer_norm_weight.data.copy_(hf_layer.input_layernorm.weight) layer.pre_mlp_layernorm.weight.data.copy_(hf_layer.post_attention_layernorm.weight)
def load_checkpoint_to_model(args): '''Set model params.'''
from pretrain_gpt import model_provider from transformers import MixtralForCausalLM, MixtralConfig
# Load Huggingface model.
hf_model = MixtralForCausalLM.from_pretrained(args.load, device_map="cpu")
# Init Megatron model. model = model_provider(True, True).to(args.params_dtype)
# Set model state. set_preprocess_state(args, model, hf_model) set_postprocess_state(args, model, hf_model) for layer_idx in tqdm(range(args.num_layers), "set layer states"): set_layer_state(args, model, hf_model, layer_idx) return model
def _load_checkpoint(queue, args):
# Llama-2 requires HF transformers >=4.31.0. verify_transformers_version()
# Search in directory above this. sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))) if args.megatron_path is not None: sys.path.insert(0, args.megatron_path)
try: from megatron.training.arguments import parse_args, validate_args from megatron.training.global_vars import set_args, set_global_variables from megatron.legacy.model import module from megatron.core import mpu from megatron.core.enums import ModelType from megatron.legacy import fused_kernels except ModuleNotFoundError: print("Unable to import Megatron, please specify the path to Megatron using --megatron-path. Exiting.") queue.put("exit") exit(1)
# We want all arguments to come from us. sys.argv = ['script.py', '--use-mcore-models', '--disable-bias-linear', '--no-masked-softmax-fusion', '--no-bias-gelu-fusion', '--no-bias-dropout-fusion', '--no-async-tensor-model-parallel-allreduce', '--use-cpu-initialization', '--micro-batch-size', '1', '--no-load-optim', '--no-load-rng', '--no-save-optim', '--no-save-rng', '--no-initialization', '--mock-data', # To pass the "blend data checks" in arguments.py '--transformer-impl', 'transformer_engine', '--load', args.load_dir ]
margs = parse_args() margs.tokenizer_model = args.tokenizer_model load_args_from_checkpoint(margs)
# Arguments do sanity checks on the world size, but we don't care, # so trick it into thinking we are plenty of processes. margs.world_size = margs.tensor_model_parallel_size * margs.pipeline_model_parallel_size
margs = validate_args(margs)
def check_for_arg(arg_name, default=None): if getattr(margs, arg_name, None) is None: if default is not None: setattr(margs, arg_name, default) else: print(f"Checkpoint does not specify the argument {arg_name}. Exiting.") print(f"Arguments: {margs}") queue.put("exit") exit(1)
check_for_arg('tensor_model_parallel_size') check_for_arg('pipeline_model_parallel_size') check_for_arg('num_layers') check_for_arg('hidden_size') check_for_arg('seq_length') check_for_arg('num_attention_heads') check_for_arg('max_position_embeddings') check_for_arg('position_embedding_type') check_for_arg('tokenizer_type') check_for_arg('iteration') check_for_arg('disable_bias_linear') check_for_arg('params_dtype') check_for_arg('swiglu')
# Determine how to make our models. assert args.model_type == 'GPT', 'Llama-2 is a GPT model.' margs.model_type = ModelType.encoder_or_decoder
# Suppress warning about torch.distributed not being initialized. module.MegatronModule.embedding_warning_printed = True
set_global_variables(margs, build_tokenizer=False) mpu.set_tensor_model_parallel_world_size(margs.tensor_model_parallel_size) mpu.set_pipeline_model_parallel_world_size(margs.pipeline_model_parallel_size) mpu.set_virtual_pipeline_model_parallel_world_size(margs.virtual_pipeline_model_parallel_size) mpu.set_expert_model_parallel_world_size(margs.expert_model_parallel_size) fused_kernels.load(margs)
# Metadata. md = types.SimpleNamespace() md.model_type = args.model_type md.num_layers = margs.num_layers md.hidden_size = margs.hidden_size md.seq_length = margs.seq_length md.num_attention_heads = margs.num_attention_heads md.max_position_embeddings = margs.max_position_embeddings md.tokenizer_type = margs.tokenizer_type md.iteration = margs.iteration md.params_dtype = margs.params_dtype md.bert_binary_head = margs.bert_binary_head md.output_layer = margs.untie_embeddings_and_output_weights md.position_embedding_type = margs.position_embedding_type md.linear_bias = margs.add_bias_linear md.norm_has_bias = False md.swiglu = margs.swiglu md.previous_tensor_parallel_size = margs.tensor_model_parallel_size md.previous_pipeline_parallel_size = margs.pipeline_model_parallel_size md.true_vocab_size = margs.vocab_size # skips padding in saver md.make_vocab_size_divisible_by = None md.checkpoint_args = margs md.consumed_train_samples = 0 md.consumed_valid_samples = 0 md.num_experts = margs.num_experts
# Get first pipe stage. mpu.set_tensor_model_parallel_rank(0) mpu.set_pipeline_model_parallel_rank(0) mpu.set_expert_model_parallel_rank(0) model = load_checkpoint_to_model(margs)
queue.put(md)
def queue_put(name, msg): print(f"sending {name}") msg["name"] = name queue.put(msg)
# Send embeddings. message = { "word embeddings": model.embedding.word_embeddings.weight.data } if md.position_embedding_type == 'learned_absolute': message["position embeddings"] = model.embedding.position_embeddings.weight.data else: assert not hasattr(model.embedding, 'position_embeddings')
queue_put("embeddings", message)
for layer_idx in range(margs.num_layers): message = {}
# Get non-parallel tensors from tp_rank 0. layer = model.decoder.layers[layer_idx] message["input norm weight"] = layer.self_attention.linear_qkv.layer_norm_weight.data message["post norm weight"] = layer.pre_mlp_layernorm.weight.data
# Simple concat of the rest. message["qkv weight"] = layer.self_attention.linear_qkv.weight.data message["dense weight"] = layer.self_attention.linear_proj.weight.data
# Grab all parallel tensors for this layer. layer = model.decoder.layers[layer_idx] experts = layer.mlp.experts.local_experts
message["router weight"] = layer.mlp.router.weight.data if md.swiglu: chunked_mlp_l0_weight = [torch.chunk(local_expert.linear_fc1.weight.data, 2, dim=0) for local_expert in experts] message["mlp l0 weight W"] = torch.stack([local_weight[0] for local_weight in chunked_mlp_l0_weight], dim=0) message["mlp l0 weight V"] = torch.stack([local_weight[1] for local_weight in chunked_mlp_l0_weight], dim=0) else: message["mlp l0 weight"] = torch.stack([local_expert.linear_fc1.weight.data for local_expert in experts]) message["mlp l1 weight"] = torch.stack([local_expert.linear_fc2.weight.data for local_expert in experts], dim=0)
queue_put(f"transformer layer {layer_idx}", message)
queue_put("final norm", { "weight": model.decoder.final_layernorm.weight.data, })
if md.output_layer: queue_put("output layer", { "weight": model.output_layer.weight.data })
queue.put("done")
def load_checkpoint(queue, args): try: _load_checkpoint(queue, args) except: queue.put("exit") raisethird_party/BindWeave/Megatron-LM/tests/unit_tests/models/test_t5_model.pyAdded+85
third_party/BindWeave/Megatron-LM/tests/unit_tests/pipeline_parallel/__init__.pyAdded
third_party/BindWeave/Megatron-LM/tests/unit_tests/pipeline_parallel/test_schedules.pyAdded+212
third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/__init__.pyAdded
third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_cross_entropy.pyAdded+14
third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_data.pyAdded+21
third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_initialization.pyAdded+97
third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_layers.pyAdded+54
third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_mappings.pyAdded+135
third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_random.pyAdded+44
third_party/BindWeave/Megatron-LM/tests/unit_tests/tensor_parallel/test_tensor_parallel_utils.pyAdded+43
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_basic.pyAdded+3
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_imports.pyAdded+157
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_local_multi_tensor_fns.pyAdded+36
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_num_microbatches_calculator.pyAdded+128
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_optimizer.pyAdded+66
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_parallel_state.pyAdded+468
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_training.pyAdded+43
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_utilities.pyAdded+82
third_party/BindWeave/Megatron-LM/tests/unit_tests/test_utils.pyAdded+183
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/__init__.pyAdded
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/__init__.pyAdded
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_a2a_token_dispatcher.pyAdded+84
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_aux_loss.pyAdded+97
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_grouped_mlp.pyAdded+358
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_routers.pyAdded+91
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_sequential_mlp.pyAdded+61
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/moe/test_token_dispatcher.pyAdded+290
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_attention.pyAdded+111
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_attention_packed_seq.pyAdded+131
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_core_attention.pyAdded+64
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_mlp.pyAdded+58
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_module.pyAdded+98
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_retro_attention.pyAdded+207
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_rope.pyAdded+52
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_spec_customization.pyAdded+243
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_transformer_block.pyAdded+107
third_party/BindWeave/Megatron-LM/tests/unit_tests/transformer/test_transformer_layer.pyAdded+106
third_party/BindWeave/Megatron-LM/tools/autoformat.shAdded+21
third_party/BindWeave/Megatron-LM/tools/bert_embedding/__init__.pyAdded+3
third_party/BindWeave/Megatron-LM/tools/bert_embedding/dataset.pyAdded+55
third_party/BindWeave/Megatron-LM/tools/bert_embedding/embed.pyAdded+278
third_party/BindWeave/Megatron-LM/tools/bert_embedding/external_libs.pyAdded+14
third_party/BindWeave/Megatron-LM/tools/bert_embedding/huggingface.pyAdded+126
third_party/BindWeave/Megatron-LM/tools/checkpoint/convert.pyAdded+154
third_party/BindWeave/Megatron-LM/tools/checkpoint/hybrid_conversion.pyAdded+398
third_party/BindWeave/Megatron-LM/tools/checkpoint/loader_llama_mistral.pyAdded+667
third_party/BindWeave/Megatron-LM/tools/checkpoint/loader_mcore.pyAdded+383
third_party/BindWeave/Megatron-LM/tools/checkpoint/loader_megatron.pyAdded+371
third_party/BindWeave/Megatron-LM/tools/checkpoint/loader_mixtral_hf.pyAdded+335