inferencerlabs commited on
Commit
b86adae
·
verified ·
1 Parent(s): 3cb2fbe

Upload model file

Browse files
Files changed (1) hide show
  1. configuration_nemotron_h.py +410 -0
configuration_nemotron_h.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 NVIDIA Corporation and The HuggingFace Inc. team. 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
+ """NemotronH model configuration"""
15
+
16
+ from transformers.configuration_utils import PretrainedConfig
17
+ from transformers.utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class NemotronHConfig(PretrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`NemotronHModel`]. It is used to instantiate a
26
+ NemotronH model according to the specified arguments, defining the model architecture. Instantiating a configuration
27
+ with the defaults will yield a similar configuration to that of NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 [nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16](https://huggingface.co/nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16).
28
+
29
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
30
+ documentation from [`PretrainedConfig`] for more information.
31
+
32
+
33
+ Args:
34
+ vocab_size (`int`, *optional*, defaults to 131072):
35
+ Vocabulary size of the NemotronH model. Defines the number of different tokens that can be represented by
36
+ the `inputs_ids` passed when calling [`NemotronHModel`].
37
+ hidden_size (`int`, *optional*, defaults to 4096):
38
+ Dimension of the hidden representations.
39
+ layers_block_type (`list`, *optional*):
40
+ Explicit list of layer types for each layer. Each element must be one of: "mamba", "attention", or "moe".
41
+ The number of layers is determined by the length of this list.
42
+ num_hidden_layers (`int`, *optional*):
43
+ Number of hidden layers in the Transformer encoder. This parameter is deprecated and only kept for
44
+ backward compatibility. The number of layers is now determined by the length of `layers_block_type`.
45
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
46
+ Whether the model's input and output word embeddings should be tied.
47
+ use_cache (`bool`, *optional*, defaults to `True`):
48
+ Whether or not the model should return the last key/values attentions.
49
+ num_logits_to_keep (`int`, *optional*, defaults to 1):
50
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated.
51
+ pad_token_id (`int`, *optional*, defaults to 0):
52
+ The id of the padding token.
53
+ bos_token_id (`int`, *optional*, defaults to 1):
54
+ The id of the "beginning-of-sequence" token.
55
+ eos_token_id (`int`, *optional*, defaults to 2):
56
+ The id of the "end-of-sequence" token.
57
+ num_attention_heads (`int`, *optional*, defaults to 32):
58
+ Number of attention heads for each attention layer in the Transformer encoder.
59
+ num_key_value_heads (`int`, *optional*, defaults to 8):
60
+ This is the number of key_value heads that should be used to implement Grouped Query Attention.
61
+ head_dim (`int`, *optional*, defaults to 128):
62
+ Dimension of each attention head.
63
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
64
+ The maximum sequence length that this model might ever be used with.
65
+ attention_bias (`bool`, *optional*, defaults to `False`):
66
+ Whether to use bias in attention layers.
67
+ attention_dropout (`float`, *optional*, defaults to 0.0):
68
+ The dropout ratio for the attention probabilities.
69
+ sliding_window (`int`, *optional*):
70
+ Sliding window attention window size.
71
+ intermediate_size (`int`, *optional*, defaults to 21504):
72
+ Dimension of the MLP representations.
73
+ mlp_hidden_act (`str`, *optional*, defaults to `"relu2"`):
74
+ The non-linear activation function in the MLP layers.
75
+ mlp_bias (`bool`, *optional*, defaults to `False`):
76
+ Whether to use bias in MLP layers.
77
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
78
+ Flag indicating whether or not to use the fast mamba kernels.
79
+ ssm_state_size (`int`, *optional*, defaults to 128):
80
+ The dimension of the mamba state space latents.
81
+ mamba_num_heads (`int`, *optional*, defaults to 128):
82
+ Number of heads in Mamba layers.
83
+ mamba_n_groups (`int`, *optional*, defaults to 8):
84
+ Number of groups in Mamba layers.
85
+ mamba_head_dim (`int`, *optional*, defaults to 64):
86
+ Dimension of each Mamba head.
87
+ mamba_d_conv (`int`, *optional*, defaults to 4):
88
+ The size of the mamba convolution kernel.
89
+ mamba_expand (`int`, *optional*, defaults to 2):
90
+ Expanding factor used to determine the mamba intermediate size.
91
+ mamba_hidden_act (`str`, *optional*, defaults to `"silu"`):
92
+ The non-linear activation function in the Mamba layers.
93
+ mamba_dt_min (`float`, *optional*, defaults to 0.001):
94
+ Minimum value for the time step in Mamba.
95
+ mamba_dt_max (`float`, *optional*, defaults to 0.1):
96
+ Maximum value for the time step in Mamba.
97
+ mamba_dt_limit (`tuple`, *optional*, defaults to `(0.0, inf)`):
98
+ Limits for the time step in Mamba.
99
+ mamba_dt_init_floor (`float`, *optional*, defaults to 0.0001):
100
+ Floor value for time step initialization in Mamba.
101
+ mamba_conv_bias (`bool`, *optional*, defaults to `True`):
102
+ Whether to use bias in the convolution layer of the mamba mixer block.
103
+ mamba_proj_bias (`bool`, *optional*, defaults to `False`):
104
+ Whether to use bias in the input and output projections of the mamba mixer block.
105
+ mamba_chunk_size (`int`, *optional*, defaults to 128):
106
+ Size of chunks for Mamba processing.
107
+ mamba_ssm_cache_dtype (`str`, *optional*, defaults to `"float32"`):
108
+ Data type for Mamba SSM cache states.
109
+ n_routed_experts (`int`, *optional*, defaults to 8):
110
+ Number of routed experts in MoE layers.
111
+ n_shared_experts (`int`, *optional*, defaults to 1):
112
+ Number of shared experts that are always activated in MoE layers.
113
+ moe_intermediate_size (`int`, *optional*, defaults to 7688):
114
+ Dimension of the MLP representations in routed experts.
115
+ moe_shared_expert_intermediate_size (`int`, *optional*, defaults to 7688):
116
+ Dimension of the MLP representations in shared experts.
117
+ moe_latent_size (`int`, *optional*):
118
+ Latent size for MoE expert projections. If `None`, uses `hidden_size`.
119
+ moe_shared_expert_overlap (`bool`, *optional*, defaults to `True`):
120
+ Whether shared experts overlap with routed experts.
121
+ num_experts_per_tok (`int`, *optional*, defaults to 2):
122
+ The number of experts to route per token (top-k routing parameter).
123
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
124
+ Scaling factor applied to routed expert outputs.
125
+ n_group (`int`, *optional*, defaults to 1):
126
+ Number of groups for expert routing.
127
+ topk_group (`int`, *optional*, defaults to 1):
128
+ Top-k group parameter for expert selection.
129
+ norm_topk_prob (`bool`, *optional*, defaults to `True`):
130
+ Whether to normalize top-k probabilities in expert routing.
131
+ num_nextn_predict_layers (`int`, *optional*, defaults to 0):
132
+ Number of additional layers for multi-token prediction. If 0, multi-token prediction is disabled.
133
+ mtp_layers_block_type (`list`, *optional*, defaults to `['attention', 'moe']`):
134
+ Explicit list of layer types for multi-token prediction layers when `num_nextn_predict_layers` > 0.
135
+ use_bias (`bool`, *optional*, defaults to `False`):
136
+ Whether to use bias in the model.
137
+ initializer_range (`float`, *optional*, defaults to 0.02):
138
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
139
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
140
+ The epsilon used by the layer normalization layers.
141
+ residual_in_fp32 (`bool`, *optional*, defaults to `False`):
142
+ Whether or not residuals should be in `float32`.
143
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
144
+ The dropout ratio for the hidden states.
145
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
146
+ Whether to rescale the pre-normalization residual connections.
147
+
148
+ ```python
149
+ >>> from transformers import NemotronHModel, NemotronHConfig
150
+
151
+ >>> # Initializing a NemotronH configuration
152
+ >>> configuration = NemotronHConfig()
153
+
154
+ >>> # Initializing a model (with random weights) from the configuration
155
+ >>> model = NemotronHModel(configuration)
156
+
157
+ >>> # Accessing the model configuration
158
+ >>> configuration = model.config
159
+ ```"""
160
+
161
+ model_type = "nemotron_h"
162
+ keys_to_ignore_at_inference = ["past_key_values"]
163
+
164
+ @staticmethod
165
+ def _validate_layers_block_type(layers_block_type, expected_length=None, param_name="layers_block_type"):
166
+ """
167
+ Validate layers_block_type list.
168
+
169
+ Args:
170
+ layers_block_type: List of layer types to validate
171
+ expected_length: If provided, validate the list has this length
172
+ param_name: Parameter name for error messages
173
+
174
+ Raises:
175
+ ValueError: If validation fails
176
+ """
177
+ if not isinstance(layers_block_type, list):
178
+ raise ValueError(f"{param_name} must be a list of strings. Got type: {type(layers_block_type)}")
179
+
180
+ if expected_length is not None and len(layers_block_type) != expected_length:
181
+ raise ValueError(f"{param_name} must have length {expected_length}. Got length {len(layers_block_type)}.")
182
+
183
+ valid_types = {"mamba", "attention", "moe"}
184
+ if not all(block_type in valid_types for block_type in layers_block_type):
185
+ invalid = set(layers_block_type) - valid_types
186
+ raise ValueError(f"{param_name} contains invalid types: {invalid}. Must be one of: {valid_types}")
187
+
188
+ def __init__(
189
+ self,
190
+ # General model config
191
+ vocab_size=131072,
192
+ hidden_size=4096,
193
+ layers_block_type=None,
194
+ num_hidden_layers=None, # Deprecated, only for backward compatibility
195
+ tie_word_embeddings=False,
196
+ use_cache=True,
197
+ num_logits_to_keep=1,
198
+ # Token IDs
199
+ pad_token_id=0,
200
+ bos_token_id=1,
201
+ eos_token_id=2,
202
+ # Attention layer config
203
+ num_attention_heads=32,
204
+ num_key_value_heads=8,
205
+ head_dim=128,
206
+ max_position_embeddings=4096,
207
+ attention_bias=False,
208
+ attention_dropout=0.0,
209
+ sliding_window=None,
210
+ # MLP layer config
211
+ intermediate_size=21504,
212
+ mlp_hidden_act="relu2",
213
+ mlp_bias=False,
214
+ # Mamba layer config
215
+ use_mamba_kernels=True,
216
+ ssm_state_size=128,
217
+ mamba_num_heads=128,
218
+ mamba_n_groups=8,
219
+ mamba_head_dim=64,
220
+ mamba_d_conv=4,
221
+ mamba_expand=2,
222
+ mamba_hidden_act="silu",
223
+ mamba_dt_min=0.001,
224
+ mamba_dt_max=0.1,
225
+ mamba_dt_limit=(0.0, float("inf")),
226
+ mamba_dt_init_floor=1e-4,
227
+ mamba_conv_bias=True,
228
+ mamba_proj_bias=False,
229
+ mamba_chunk_size=128,
230
+ mamba_ssm_cache_dtype="float32",
231
+ # MoE config
232
+ n_routed_experts=8,
233
+ n_shared_experts=1,
234
+ moe_intermediate_size=7688,
235
+ moe_shared_expert_intermediate_size=7688,
236
+ moe_latent_size=None,
237
+ moe_shared_expert_overlap=True,
238
+ num_experts_per_tok=2,
239
+ routed_scaling_factor=1.0,
240
+ n_group=1,
241
+ topk_group=1,
242
+ norm_topk_prob=True,
243
+ # Multi-token prediction config
244
+ num_nextn_predict_layers=0,
245
+ mtp_layers_block_type=["attention", "moe"],
246
+ # General training config
247
+ use_bias=False,
248
+ initializer_range=0.02,
249
+ layer_norm_epsilon=1e-5,
250
+ residual_in_fp32=False,
251
+ hidden_dropout=0.0,
252
+ rescale_prenorm_residual=True,
253
+ **kwargs,
254
+ ):
255
+ # Backward compatibility: convert hybrid_override_pattern to layers_block_type
256
+ # Always pop hybrid_override_pattern from kwargs to prevent it from being set as an attribute
257
+ if "hybrid_override_pattern" in kwargs:
258
+ pattern = kwargs.pop("hybrid_override_pattern")
259
+ if layers_block_type is None:
260
+ layers_block_type = self._pattern_to_list(pattern)
261
+ elif layers_block_type is None:
262
+ # Default layers_block_type if not provided
263
+ layers_block_type = ["mamba", "moe", "attention", "moe"]
264
+
265
+ # Note: num_hidden_layers is deprecated and ignored if layers_block_type is explicitly provided
266
+ # It's only kept for backward compatibility when loading old configs
267
+ if num_hidden_layers is not None:
268
+ # Warn if num_hidden_layers is provided but doesn't match layers_block_type
269
+ if len(layers_block_type) != num_hidden_layers:
270
+ logger.warning(
271
+ f"num_hidden_layers ({num_hidden_layers}) is deprecated and doesn't match "
272
+ f"layers_block_type length ({len(layers_block_type)}). Using layers_block_type length."
273
+ )
274
+
275
+ # Backward compatibility: convert mtp_hybrid_override_pattern to mtp_layers_block_type
276
+ # Always pop mtp_hybrid_override_pattern from kwargs to prevent it from being set as an attribute
277
+ if "mtp_hybrid_override_pattern" in kwargs:
278
+ pattern = kwargs.pop("mtp_hybrid_override_pattern")
279
+ if mtp_layers_block_type is None or mtp_layers_block_type == ["attention", "moe"]:
280
+ mtp_layers_block_type = self._pattern_to_list(pattern)
281
+
282
+ self.vocab_size = vocab_size
283
+ self.tie_word_embeddings = tie_word_embeddings
284
+ self.hidden_size = hidden_size
285
+ self.intermediate_size = intermediate_size
286
+ self.num_attention_heads = num_attention_heads
287
+ self.head_dim = head_dim
288
+ self.sliding_window = sliding_window
289
+ self.max_position_embeddings = max_position_embeddings
290
+ self.attention_dropout = attention_dropout
291
+ self.hidden_dropout = hidden_dropout
292
+
293
+ # Validate layers_block_type (no longer checking length against num_hidden_layers)
294
+ self._validate_layers_block_type(layers_block_type, expected_length=None, param_name="layers_block_type")
295
+ self.layers_block_type = layers_block_type
296
+
297
+ # for backward compatibility
298
+ if num_key_value_heads is None:
299
+ num_key_value_heads = num_attention_heads
300
+
301
+ self.num_key_value_heads = num_key_value_heads
302
+ self.mlp_hidden_act = mlp_hidden_act
303
+ self.attention_bias = attention_bias
304
+ self.mlp_bias = mlp_bias
305
+ self.use_bias = use_bias
306
+ self.initializer_range = initializer_range
307
+ self.layer_norm_epsilon = layer_norm_epsilon
308
+ self.residual_in_fp32 = residual_in_fp32
309
+
310
+ self.use_cache = use_cache
311
+ self.num_logits_to_keep = num_logits_to_keep
312
+
313
+ self.use_mamba_kernels = use_mamba_kernels
314
+ self.n_groups = mamba_n_groups
315
+ self.mamba_head_dim = mamba_head_dim
316
+ self.ssm_state_size = ssm_state_size
317
+ self.mamba_num_heads = mamba_num_heads
318
+ self.conv_kernel = mamba_d_conv
319
+ self.expand = mamba_expand
320
+ self.mamba_hidden_act = mamba_hidden_act
321
+ self.time_step_min = mamba_dt_min
322
+ self.time_step_max = mamba_dt_max
323
+ self.time_step_limit = mamba_dt_limit
324
+ self.time_step_floor = mamba_dt_init_floor
325
+ self.use_conv_bias = mamba_conv_bias
326
+ self.mamba_proj_bias = mamba_proj_bias
327
+ self.chunk_size = mamba_chunk_size
328
+ self.rescale_prenorm_residual = rescale_prenorm_residual
329
+ self.n_routed_experts = n_routed_experts
330
+ self.n_shared_experts = n_shared_experts
331
+ self.moe_intermediate_size = moe_intermediate_size
332
+ self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
333
+ self.moe_latent_size = moe_latent_size
334
+ self.moe_shared_expert_overlap = moe_shared_expert_overlap
335
+ self.num_experts_per_tok = num_experts_per_tok
336
+ self.routed_scaling_factor = routed_scaling_factor
337
+ self.n_group = n_group
338
+ self.topk_group = topk_group
339
+ self.norm_topk_prob = norm_topk_prob
340
+ self.mamba_ssm_cache_dtype = mamba_ssm_cache_dtype
341
+
342
+ # MTP config
343
+ self.num_nextn_predict_layers = num_nextn_predict_layers
344
+
345
+ # Validate mtp_layers_block_type is provided when MTP is enabled
346
+ if self.num_nextn_predict_layers > 0:
347
+ if mtp_layers_block_type is None:
348
+ raise ValueError(
349
+ "mtp_layers_block_type is required when num_nextn_predict_layers > 0. "
350
+ "Please provide an explicit list of layer types for MTP layers. "
351
+ "Example: mtp_layers_block_type=['attention', 'moe']"
352
+ )
353
+ self._validate_layers_block_type(mtp_layers_block_type, None, "mtp_layers_block_type")
354
+ self.mtp_layers_block_type = mtp_layers_block_type
355
+
356
+ super().__init__(
357
+ pad_token_id=pad_token_id,
358
+ bos_token_id=bos_token_id,
359
+ eos_token_id=eos_token_id,
360
+ tie_word_embeddings=tie_word_embeddings,
361
+ **kwargs,
362
+ )
363
+
364
+ @property
365
+ def num_hidden_layers(self) -> int:
366
+ """
367
+ Number of hidden layers derived from the length of layers_block_type.
368
+ This property replaces the deprecated num_hidden_layers parameter.
369
+ """
370
+ return len(self.layers_block_type)
371
+
372
+ @num_hidden_layers.setter
373
+ def num_hidden_layers(self, value):
374
+ """
375
+ Setter for backward compatibility when loading configs.
376
+ The value is ignored since num_hidden_layers is computed from layers_block_type.
377
+ """
378
+ # Ignore the value - num_hidden_layers is always derived from layers_block_type
379
+ pass
380
+
381
+ @property
382
+ def hybrid_override_pattern(self) -> str:
383
+ """
384
+ Backward compatibility property.
385
+ Returns the pattern string representation of layers_block_type.
386
+ """
387
+ return self._list_to_pattern(self.layers_block_type)
388
+
389
+ @property
390
+ def mtp_hybrid_override_pattern(self) -> str:
391
+ """
392
+ Backward compatibility property.
393
+ Returns the pattern string representation of mtp_layers_block_type.
394
+ """
395
+ return self._list_to_pattern(self.mtp_layers_block_type)
396
+
397
+ @staticmethod
398
+ def _list_to_pattern(layers_list: list) -> str:
399
+ """Convert list of layer types back to pattern string (for backward compatibility)."""
400
+ reverse_mapping = {"mamba": "M", "moe": "E", "attention": "*"}
401
+ return "".join(reverse_mapping[layer_type] for layer_type in layers_list)
402
+
403
+ @staticmethod
404
+ def _pattern_to_list(pattern: str) -> list:
405
+ """Convert pattern string to list of layer types (for backward compatibility)."""
406
+ pattern_mapping = {"M": "mamba", "E": "moe", "*": "attention"}
407
+ return [pattern_mapping[char] for char in pattern]
408
+
409
+
410
+ __all__ = ["NemotronHConfig"]