|
| 1 | +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import torch |
| 16 | +from megatron.core.models.gpt.gpt_model import GPTModel |
| 17 | +from transformers import NemotronForCausalLM |
| 18 | + |
| 19 | +from megatron.bridge.models.conversion.mapping_registry import MegatronMappingRegistry |
| 20 | +from megatron.bridge.models.conversion.model_bridge import MegatronModelBridge |
| 21 | +from megatron.bridge.models.conversion.param_mapping import ( |
| 22 | + AutoMapping, |
| 23 | + QKVMapping, |
| 24 | +) |
| 25 | +from megatron.bridge.models.hf_pretrained.causal_lm import PreTrainedCausalLM |
| 26 | +from megatron.bridge.models.nemotron.nemotron_provider import NemotronModelProvider |
| 27 | + |
| 28 | + |
| 29 | +@MegatronModelBridge.register_bridge(source=NemotronForCausalLM, target=GPTModel) |
| 30 | +class NemotronBridge(MegatronModelBridge): |
| 31 | + """ |
| 32 | + Megatron Bridge for Nemotron Causal LM. |
| 33 | +
|
| 34 | + As a user you would not use this bridge directly, but through `AutoBridge`. |
| 35 | +
|
| 36 | + Example: |
| 37 | + >>> from megatron.bridge import AutoBridge |
| 38 | + >>> bridge = AutoBridge.from_hf_pretrained("nvidia/Nemotron-4-340B-Instruct") |
| 39 | + >>> provider = bridge.to_megatron_provider() |
| 40 | + """ |
| 41 | + |
| 42 | + def provider_bridge(self, hf_pretrained: PreTrainedCausalLM) -> NemotronModelProvider: |
| 43 | + hf_config = hf_pretrained.config |
| 44 | + |
| 45 | + provider = NemotronModelProvider( |
| 46 | + num_layers=hf_config.num_hidden_layers, |
| 47 | + hidden_size=hf_config.hidden_size, |
| 48 | + ffn_hidden_size=hf_config.intermediate_size, |
| 49 | + num_attention_heads=hf_config.num_attention_heads, |
| 50 | + init_method_std=hf_config.initializer_range, |
| 51 | + layernorm_epsilon=hf_config.norm_eps, |
| 52 | + num_query_groups=hf_config.num_key_value_heads, |
| 53 | + seq_length=hf_config.max_position_embeddings, |
| 54 | + rotary_base=hf_config.rope_theta, |
| 55 | + rotary_percent=hf_config.partial_rotary_factor, |
| 56 | + kv_channels=getattr(hf_config, "head_dim", None), |
| 57 | + make_vocab_size_divisible_by=self.make_vocab_size_divisible_by(hf_config.vocab_size), |
| 58 | + share_embeddings_and_output_weights=getattr(hf_config, "tie_word_embeddings", False), |
| 59 | + fp16=(self.dtype_from_hf(hf_config, default=torch.float32) == torch.float16), |
| 60 | + bf16=(self.dtype_from_hf(hf_config, default=torch.float32) == torch.bfloat16), |
| 61 | + params_dtype=self.dtype_from_hf(hf_config, default=torch.float32), |
| 62 | + generation_config=hf_pretrained.generation_config, |
| 63 | + vocab_size=hf_config.vocab_size, |
| 64 | + ) |
| 65 | + |
| 66 | + return provider |
| 67 | + |
| 68 | + def mapping_registry(self) -> MegatronMappingRegistry: |
| 69 | + # Return MegatronMappingRegistry containing parameter mappings from Megatron to HF format |
| 70 | + # First create simple 1:1 parameter mappings using a dictionary for readability |
| 71 | + |
| 72 | + # Dictionary maps Megatron parameter names -> HF parameter names |
| 73 | + # Supports wildcard (*) patterns for layer-specific parameters |
| 74 | + param_mappings = { |
| 75 | + "embedding.word_embeddings.weight": "model.embed_tokens.weight", |
| 76 | + "output_layer.weight": "lm_head.weight", |
| 77 | + "decoder.final_layernorm.weight": "model.norm.weight", |
| 78 | + "decoder.final_layernorm.bias": "model.norm.bias", |
| 79 | + "decoder.layers.*.self_attention.linear_qkv.layer_norm_weight": "model.layers.*.input_layernorm.weight", |
| 80 | + "decoder.layers.*.self_attention.linear_qkv.layer_norm_bias": "model.layers.*.input_layernorm.bias", |
| 81 | + "decoder.layers.*.mlp.linear_fc1.layer_norm_weight": "model.layers.*.post_attention_layernorm.weight", |
| 82 | + "decoder.layers.*.mlp.linear_fc1.layer_norm_bias": "model.layers.*.post_attention_layernorm.bias", |
| 83 | + "decoder.layers.*.self_attention.linear_proj.weight": "model.layers.*.self_attn.o_proj.weight", |
| 84 | + "decoder.layers.*.mlp.linear_fc1.weight": "model.layers.*.mlp.up_proj.weight", |
| 85 | + "decoder.layers.*.mlp.linear_fc2.weight": "model.layers.*.mlp.down_proj.weight", |
| 86 | + } |
| 87 | + |
| 88 | + mapping_list = [] |
| 89 | + # Convert each dictionary entry to AutoMapping(megatron_param, hf_param) |
| 90 | + for megatron_param, hf_param in param_mappings.items(): |
| 91 | + mapping_list.append(AutoMapping(megatron_param=megatron_param, hf_param=hf_param)) |
| 92 | + |
| 93 | + # Add special mappings that require parameter concatenation/transformation |
| 94 | + mapping_list.extend( |
| 95 | + [ |
| 96 | + # QKV: Combine separate Q, K, V matrices into single QKV matrix |
| 97 | + QKVMapping( |
| 98 | + megatron_param="decoder.layers.*.self_attention.linear_qkv.weight", |
| 99 | + q="model.layers.*.self_attn.q_proj.weight", |
| 100 | + k="model.layers.*.self_attn.k_proj.weight", |
| 101 | + v="model.layers.*.self_attn.v_proj.weight", |
| 102 | + ), |
| 103 | + ] |
| 104 | + ) |
| 105 | + |
| 106 | + return MegatronMappingRegistry(*mapping_list) |
0 commit comments