main
py 288 lines 13.1 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4 # Copyright 2024 HuggingFace Inc. team. All rights reserved.
5 # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 """NemotronH model configuration."""
19
20 import regex as re
21 from transformers.configuration_utils import PreTrainedConfig
22 from transformers.utils import logging
23
24 logger = logging.get_logger(__name__)
25
26
27 class NemotronHConfig(PreTrainedConfig):
28 r"""This is the configuration class to store the configuration of a
29 [`NemotronHModel`]. It is used to instantiate a NemotronH model according
30 to the specified arguments, defining the model architecture. Instantiating
31 a configuration with the defaults will yield a similar configuration to
32 that of the NemotronH-v0.1 model.
33
34 Args:
35 vocab_size (`int`, *optional*, defaults to 131072):
36 Vocabulary size of the NemotronH model. Defines the number of
37 different tokens that can be represented by the `inputs_ids`
38 passed when calling [`NemotronHModel`]
39 tie_word_embeddings (`bool`, *optional*, defaults to `False`):
40 Whether the model's input and output word embeddings should be
41 tied. Note that this is only relevant if the model has an output
42 word embedding layer.
43 hidden_size (`int`, *optional*, defaults to 4096):
44 Dimension of the hidden representations.
45 intermediate_size (`int`, *optional*, defaults to 21504):
46 Dimension of the MLP representations.
47 num_hidden_layers (`int`, *optional*, defaults to 52):
48 Number of hidden layers in the Transformer encoder.
49 hybrid_override_pattern (`str`, *optional*, defaults to
50 `"M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-"`):
51 The pattern of the hybrid model. The pattern is a string of
52 characters where each character represents
53 M: Mamba2, *: Attention, -: MLP
54 mtp_hybrid_override_pattern (`str`, *optional*, defaults to `"*E"`):
55 The pattern of the MTP layers.
56 num_attention_heads (`int`, *optional*, defaults to 32):
57 Number of attention heads for each attention layer in the
58 Transformer encoder.
59 attention_head_dim (`int`, *optional*, defaults to 128):
60 Dimension of each attention head.
61 num_key_value_heads (`int`, *optional*, defaults to 8):
62 This is the number of key_value heads that should be used to
63 implement Grouped Query Attention. If
64 `num_key_value_heads=num_attention_heads`, the model will use
65 Multi Head Attention (MHA), if `num_key_value_heads=1` the model
66 will use Multi Query Attention (MQA) otherwise GQA is used.
67 mlp_hidden_act (`str`, *optional*, defaults to "relu2"):
68 The non-linear activation function in the MLP layers.
69 attention_bias (`bool`, *optional*, defaults to `False`):
70 Whether to use bias in attention layers.
71 mlp_bias (`bool`, *optional*, defaults to `False`):
72 Whether to use bias in MLP layers.
73 use_bias (`bool`, *optional*, defaults to `False`):
74 Whether to use bias in the model.
75 initializer_range (`float`, *optional*, defaults to 0.02):
76 The standard deviation of the truncated_normal_initializer for
77 initializing all weight matrices.
78 layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
79 The epsilon used by the layer normalization layers.
80 residual_in_fp32 (`bool`, *optional*, defaults to `False`):
81 Whether or not residuals should be in `float32`. If set to `False`
82 residuals will keep the same `dtype` as the rest of the model.
83 use_cache (`bool`, *optional*, defaults to `True`):
84 Whether or not the model should return the last key/values
85 attentions (not used by all models). Only relevant if
86 `config.is_decoder=True`.
87 num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
88 Number of prompt logits to calculate during generation. If `None`,
89 all logits will be calculated. If an integer value, only last
90 `num_logits_to_keep` logits will be calculated.
91 pad_token_id (`int`, *optional*, defaults to 0):
92 The id of the padding token.
93 bos_token_id (`int`, *optional*, defaults to 1):
94 The id of the "beginning-of-sequence" token.
95 eos_token_id (`int`, *optional*, defaults to 2):
96 The id of the "end-of-sequence" token.
97 sliding_window (`int`, *optional*, defaults to None):
98 Sliding window attention window size.
99 max_position_embeddings (`int`, *optional*, defaults to 4096):
100 The maximum sequence length that this model might ever be used
101 with.
102 attention_dropout (`float`, *optional*, defaults to 0.0):
103 The dropout ratio for the attention probabilities.
104 hidden_dropout (`float`, *optional*, defaults to 0.0):
105 The dropout ratio for the hidden states.
106 use_mamba_kernels (`bool`, *optional*, defaults to `True`):
107 Flag indicating whether or not to use the fast mamba kernels.
108 These are available only if `mamba-ssm` and `causal-conv1d`
109 are installed, and the mamba modules are running on a CUDA device.
110 ssm_state_size (`int`, *optional*, defaults to 128):
111 The dimension of the mamba state space latents.
112 mamba_num_heads (`int`, *optional*, defaults to 128):
113 Number of heads in Mamba layers.
114 mamba_n_groups (`int`, *optional*, defaults to 8):
115 Number of groups in Mamba layers.
116 mamba_head_dim (`int`, *optional*, defaults to 64):
117 Dimension of each Mamba head.
118 mamba_d_conv (`int`, *optional*, defaults to 4):
119 The size of the mamba convolution kernel.
120 mamba_expand (`int`, *optional*, defaults to 2):
121 Expanding factor used to determine the mamba intermediate size.
122 mamba_hidden_act (`str`, *optional*, defaults to "silu"):
123 The non-linear activation function in the Mamba layers.
124 mamba_dt_min (`float`, *optional*, defaults to 0.001):
125 Minimum value for the time step in Mamba.
126 mamba_dt_max (`float`, *optional*, defaults to 0.1):
127 Maximum value for the time step in Mamba.
128 mamba_dt_limit (`tuple`, *optional*, defaults to (0.0, float("inf"))):
129 Limits for the time step in Mamba.
130 mamba_dt_init_floor (`float`, *optional*, defaults to 1e-4):
131 Floor value for time step initialization in Mamba.
132 mamba_conv_bias (`bool`, *optional*, defaults to `True`):
133 Whether to use bias in the convolution layer of the mamba mixer
134 block.
135 mamba_proj_bias (`bool`, *optional*, defaults to `False`):
136 Whether to use bias in the input and output projections of the
137 mamba mixer block.
138 mamba_chunk_size (`int`, *optional*, defaults to 256):
139 Size of chunks for Mamba processing.
140 rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
141 Whether to rescale the pre-normalization residual connections.
142
143 """
144
145 model_type = "nemotron_h"
146 keys_to_ignore_at_inference = ["past_key_values"]
147
148 def __init__(
149 self,
150 vocab_size=131072,
151 tie_word_embeddings=False,
152 hidden_size=4096,
153 intermediate_size=21504,
154 num_hidden_layers=52,
155 hybrid_override_pattern="M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
156 mtp_hybrid_override_pattern="*E",
157 num_attention_heads=32,
158 head_dim=128,
159 num_key_value_heads=8, # nemo: num_query_groups
160 mlp_hidden_act="relu2",
161 attention_bias=False,
162 mlp_bias=False,
163 use_bias=False,
164 initializer_range=0.02, # nemo: init_method_std
165 layer_norm_epsilon=1e-5, # nemo: layernorm_epsilon
166 residual_in_fp32=False, # Megatron Core default value
167 use_cache=True,
168 num_logits_to_keep=1,
169 pad_token_id=0,
170 bos_token_id=1,
171 eos_token_id=2,
172 sliding_window=None,
173 max_position_embeddings=4096,
174 attention_dropout=0.0,
175 hidden_dropout=0.0, # * ADDED
176 use_mamba_kernels=True,
177 ssm_state_size=128, # mamba_state_size
178 mamba_num_heads=128,
179 mamba_n_groups=8, # nemo: mamba_ssm_ngroups = num_heads
180 mamba_head_dim=64,
181 mamba_d_conv=4,
182 mamba_expand=2,
183 mamba_hidden_act="silu",
184 mamba_dt_min=0.001,
185 mamba_dt_max=0.1,
186 mamba_dt_limit=(0.0, float("inf")),
187 mamba_dt_init_floor=1e-4,
188 mamba_conv_bias=True,
189 mamba_proj_bias=False,
190 mamba_chunk_size=256,
191 rescale_prenorm_residual=True,
192 n_routed_experts=8,
193 n_shared_experts=1,
194 moe_intermediate_size=7688,
195 moe_shared_expert_intermediate_size=7688,
196 moe_latent_size=None,
197 num_experts_per_tok=2,
198 routed_scaling_factor=1.0,
199 n_group=1,
200 topk_group=1,
201 norm_topk_prob=True,
202 **kwargs,
203 ):
204 self.vocab_size = vocab_size
205 self.tie_word_embeddings = tie_word_embeddings
206 self.hidden_size = hidden_size
207 self.intermediate_size = intermediate_size
208 self.num_hidden_layers = num_hidden_layers
209 self.hybrid_override_pattern = hybrid_override_pattern
210 self.mtp_hybrid_override_pattern = mtp_hybrid_override_pattern
211 self.num_attention_heads = num_attention_heads
212 self.head_dim = head_dim
213 self.sliding_window = sliding_window
214 self.max_position_embeddings = max_position_embeddings
215 self.attention_dropout = attention_dropout
216 self.hidden_dropout = hidden_dropout
217
218 # Validate hybrid_override_pattern
219 # M: Mamba2, *: Attention, -: MLP
220 assert len(self.hybrid_override_pattern) == self.num_hidden_layers, (
221 "hybrid_override_pattern must have same length as num_hidden_layers"
222 )
223 assert re.match(r"^[*-ME]+$", self.hybrid_override_pattern), (
224 "hybrid_override_pattern must only contain characters 'M', '*', '-', or 'E'"
225 )
226 # for backward compatibility
227 if num_key_value_heads is None:
228 num_key_value_heads = num_attention_heads
229
230 self.num_key_value_heads = num_key_value_heads
231 self.mlp_hidden_act = mlp_hidden_act
232 self.attention_bias = attention_bias
233 self.mlp_bias = mlp_bias
234 self.use_bias = use_bias
235 self.initializer_range = initializer_range
236 self.layer_norm_epsilon = layer_norm_epsilon
237 self.residual_in_fp32 = residual_in_fp32
238
239 self.use_cache = use_cache
240 self.num_logits_to_keep = num_logits_to_keep
241
242 self.use_mamba_kernels = use_mamba_kernels
243 self.n_groups = mamba_n_groups
244 self.mamba_head_dim = mamba_head_dim
245 self.ssm_state_size = ssm_state_size
246 self.mamba_num_heads = mamba_num_heads
247 self.conv_kernel = mamba_d_conv
248 self.expand = mamba_expand
249 self.mamba_hidden_act = mamba_hidden_act
250 self.time_step_min = mamba_dt_min
251 self.time_step_max = mamba_dt_max
252 self.time_step_limit = mamba_dt_limit
253 self.time_step_floor = mamba_dt_init_floor
254 self.use_conv_bias = mamba_conv_bias
255 self.mamba_proj_bias = mamba_proj_bias
256 self.chunk_size = mamba_chunk_size
257 self.rescale_prenorm_residual = rescale_prenorm_residual
258 self.n_routed_experts = n_routed_experts
259 self.n_shared_experts = n_shared_experts
260 self.moe_intermediate_size = moe_intermediate_size
261 self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size # noqa: E501
262 self.moe_latent_size = moe_latent_size
263 self.num_experts_per_tok = num_experts_per_tok
264 self.routed_scaling_factor = routed_scaling_factor
265 self.n_group = n_group
266 self.topk_group = topk_group
267 self.norm_topk_prob = norm_topk_prob
268
269 super().__init__(
270 pad_token_id=pad_token_id,
271 bos_token_id=bos_token_id,
272 eos_token_id=eos_token_id,
273 tie_word_embeddings=tie_word_embeddings,
274 **kwargs,
275 )
276
277 @property
278 def layers_block_type(self):
279 return [
280 "mamba"
281 if self.hybrid_override_pattern[i] == "M"
282 else "attention"
283 if self.hybrid_override_pattern[i] == "*"
284 else "mlp"
285 if self.hybrid_override_pattern[i] == "-"
286 else "moe"
287 for i in range(self.num_hidden_layers)
288 ]