|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Modifiy stated_dict and config for exporting speculative decoding in official format.""" |
| 17 | + |
| 18 | +import torch |
| 19 | +import torch.nn as nn |
| 20 | + |
| 21 | +from modelopt.torch.speculative.plugins.transformers import HFEagleModel |
| 22 | + |
| 23 | +SPECULATIVE_DECODING_MODES = ["eagle", "medusa"] |
| 24 | + |
| 25 | +EALGE_MODELOPT_TO_OFFICIAL = { |
| 26 | + "required": { |
| 27 | + "layers.0.self_attn.q_proj.weight": "midlayer.self_attn.q_proj.weight", |
| 28 | + "layers.0.self_attn.k_proj.weight": "midlayer.self_attn.k_proj.weight", |
| 29 | + "layers.0.self_attn.v_proj.weight": "midlayer.self_attn.v_proj.weight", |
| 30 | + "layers.0.self_attn.o_proj.weight": "midlayer.self_attn.o_proj.weight", |
| 31 | + "layers.0.mlp.gate_proj.weight": "midlayer.mlp.gate_proj.weight", |
| 32 | + "layers.0.mlp.up_proj.weight": "midlayer.mlp.up_proj.weight", |
| 33 | + "layers.0.mlp.down_proj.weight": "midlayer.mlp.down_proj.weight", |
| 34 | + "hidden_norm.weight": "midlayer.hidden_norm.weight", |
| 35 | + "input_embeds_norm.weight": "midlayer.input_layernorm.weight", |
| 36 | + "layers.0.post_attention_layernorm.weight": "midlayer.post_attention_layernorm.weight", |
| 37 | + "norm.weight": "norm.weight", |
| 38 | + "fc.weight": "fc.weight", |
| 39 | + }, |
| 40 | + "optional": { |
| 41 | + "d2t": "d2t", |
| 42 | + "eagle_lm_head.weight": "lm_head.weight", |
| 43 | + }, |
| 44 | +} |
| 45 | + |
| 46 | + |
| 47 | +def _check_state_dict_keys_match(draft_model: nn.Module, required_items: dict): |
| 48 | + """Check if the state dict keys match.""" |
| 49 | + draft_keys = set(draft_model.state_dict().keys()) |
| 50 | + for required_key in required_items: |
| 51 | + if required_key not in draft_keys: |
| 52 | + raise ValueError(f"State dict keys mismatch!\nMissing in draft model: {required_key}") |
| 53 | + |
| 54 | + |
| 55 | +def rename_and_prune_if_spec_decoding(model: nn.Module, post_state_dict: dict): |
| 56 | + """Only return the state dict of the draft model in official format and ignore the base model.""" |
| 57 | + # check the model has only speculative decoding |
| 58 | + opt_modes = model._modelopt_state |
| 59 | + if len(opt_modes) != 1 or opt_modes[0][0] != "eagle": |
| 60 | + # if there's other opts, return as is |
| 61 | + return post_state_dict |
| 62 | + |
| 63 | + assert isinstance(model, HFEagleModel) |
| 64 | + # Check if the state dict keys match |
| 65 | + _check_state_dict_keys_match(model.eagle_module, EALGE_MODELOPT_TO_OFFICIAL["required"]) |
| 66 | + |
| 67 | + # Convert key names and save the state dict |
| 68 | + export_state_dict = {} |
| 69 | + for ours_key, export_key in { |
| 70 | + **EALGE_MODELOPT_TO_OFFICIAL["required"], |
| 71 | + **EALGE_MODELOPT_TO_OFFICIAL["optional"], |
| 72 | + }.items(): |
| 73 | + if ours_key in model.eagle_module.state_dict(): |
| 74 | + export_state_dict[export_key] = model.eagle_module.state_dict()[ours_key] |
| 75 | + |
| 76 | + # TODO: (hg) this is a temp fix. Find cleaner way to do this. |
| 77 | + if "eagle_lm_head.weight" not in model.eagle_module.state_dict(): |
| 78 | + export_state_dict["lm_head.weight"] = model.state_dict()["lm_head.weight"] |
| 79 | + |
| 80 | + return export_state_dict |
| 81 | + |
| 82 | + |
| 83 | +def set_config_if_spec_decoding(model: nn.Module, config_data: dict): |
| 84 | + """Return the config of draft model in official format.""" |
| 85 | + if len(model._modelopt_state) != 1 or model._modelopt_state[0][0] != "eagle": |
| 86 | + # return as is |
| 87 | + return config_data |
| 88 | + |
| 89 | + assert isinstance(model, HFEagleModel) |
| 90 | + |
| 91 | + # This is the config keys in official checkpoint. |
| 92 | + template_config = { |
| 93 | + "architectures": ["LlamaForCausalLM"], |
| 94 | + "bos_token_id": None, |
| 95 | + "eos_token_id": None, |
| 96 | + "hidden_act": None, |
| 97 | + "hidden_size": None, |
| 98 | + "initializer_range": None, |
| 99 | + "intermediate_size": None, |
| 100 | + "max_position_embeddings": None, |
| 101 | + "model_type": "llama", |
| 102 | + "num_attention_heads": None, |
| 103 | + "num_key_value_heads": None, |
| 104 | + "num_hidden_layers": None, |
| 105 | + "pad_token_id": None, |
| 106 | + "rms_norm_eps": None, |
| 107 | + "tie_word_embeddings": False, |
| 108 | + "torch_dtype": None, |
| 109 | + "transformers_version": None, |
| 110 | + "use_cache": None, |
| 111 | + "vocab_size": None, |
| 112 | + "draft_vocab_size": None, |
| 113 | + "rope_scaling": None, |
| 114 | + "attention_bias": None, |
| 115 | + "attention_dropout": None, |
| 116 | + "head_dim": None, |
| 117 | + "mlp_bias": None, |
| 118 | + "pretraining_tp": None, |
| 119 | + "rope_theta": None, |
| 120 | + "eagle_config": { |
| 121 | + "eagle_aux_hidden_state_layer_ids": None, |
| 122 | + "use_aux_hidden_state": None, |
| 123 | + "use_input_layernorm_in_first_layer": None, |
| 124 | + "use_last_layernorm": None, |
| 125 | + "use_mtp_layernorm": None, |
| 126 | + }, |
| 127 | + } |
| 128 | + |
| 129 | + def _get_config_from_eagle_config_or_base_config(key: str, model: nn.Module): |
| 130 | + if getattr(model.eagle_config, key, None) is not None: |
| 131 | + return getattr(model.eagle_config, key) |
| 132 | + elif getattr(model.config, key, None) is not None: |
| 133 | + return getattr(model.config, key) |
| 134 | + else: |
| 135 | + return None |
| 136 | + |
| 137 | + for key in template_config: |
| 138 | + value = template_config[key] |
| 139 | + if isinstance(value, dict): |
| 140 | + # for eagle config, we find it in model.eagle_config |
| 141 | + for sub_key in value: |
| 142 | + value[sub_key] = _get_config_from_eagle_config_or_base_config(sub_key, model) |
| 143 | + elif value is None: |
| 144 | + # First, we try to load fron eagle config. |
| 145 | + new_value = _get_config_from_eagle_config_or_base_config(key, model) |
| 146 | + # If the value is a torch.dtype, we convert to string for serialization. |
| 147 | + if isinstance(new_value, torch.dtype): |
| 148 | + new_value = str(new_value).replace("torch.", "") |
| 149 | + template_config[key] = new_value |
| 150 | + |
| 151 | + return template_config |
0 commit comments