igitman commited on
Commit
d889f8c
·
verified ·
1 Parent(s): 78215b5

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. __init__.py +0 -0
  3. chat_template.jinja +195 -0
  4. config.json +73 -0
  5. configuration_nemotron_h.py +277 -0
  6. generation_config.json +12 -0
  7. model-00002-of-00225.safetensors +3 -0
  8. model-00007-of-00225.safetensors +3 -0
  9. model-00009-of-00225.safetensors +3 -0
  10. model-00013-of-00225.safetensors +3 -0
  11. model-00016-of-00225.safetensors +3 -0
  12. model-00018-of-00225.safetensors +3 -0
  13. model-00025-of-00225.safetensors +3 -0
  14. model-00034-of-00225.safetensors +3 -0
  15. model-00045-of-00225.safetensors +3 -0
  16. model-00054-of-00225.safetensors +3 -0
  17. model-00062-of-00225.safetensors +3 -0
  18. model-00067-of-00225.safetensors +3 -0
  19. model-00073-of-00225.safetensors +3 -0
  20. model-00078-of-00225.safetensors +3 -0
  21. model-00080-of-00225.safetensors +3 -0
  22. model-00091-of-00225.safetensors +3 -0
  23. model-00094-of-00225.safetensors +3 -0
  24. model-00104-of-00225.safetensors +3 -0
  25. model-00110-of-00225.safetensors +3 -0
  26. model-00115-of-00225.safetensors +3 -0
  27. model-00123-of-00225.safetensors +3 -0
  28. model-00128-of-00225.safetensors +3 -0
  29. model-00132-of-00225.safetensors +3 -0
  30. model-00139-of-00225.safetensors +3 -0
  31. model-00143-of-00225.safetensors +3 -0
  32. model-00148-of-00225.safetensors +3 -0
  33. model-00151-of-00225.safetensors +3 -0
  34. model-00152-of-00225.safetensors +3 -0
  35. model-00157-of-00225.safetensors +3 -0
  36. model-00159-of-00225.safetensors +3 -0
  37. model-00161-of-00225.safetensors +3 -0
  38. model-00164-of-00225.safetensors +3 -0
  39. model-00170-of-00225.safetensors +3 -0
  40. model-00183-of-00225.safetensors +3 -0
  41. model-00192-of-00225.safetensors +3 -0
  42. model-00206-of-00225.safetensors +3 -0
  43. model-00211-of-00225.safetensors +3 -0
  44. model-00214-of-00225.safetensors +3 -0
  45. model-00222-of-00225.safetensors +3 -0
  46. model.safetensors.index.json +0 -0
  47. modeling_nemotron_h.py +1810 -0
  48. special_tokens_map.json +30 -0
  49. tokenizer.json +3 -0
  50. tokenizer_config.json +0 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
__init__.py ADDED
File without changes
chat_template.jinja ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro render_extra_keys(json_dict, handled_keys) %}
2
+ {%- if json_dict is mapping %}
3
+ {%- for json_key in json_dict if json_key not in handled_keys %}
4
+ {%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
5
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
6
+ {%- else %}
7
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
8
+ {%- endif %}
9
+ {%- endfor %}
10
+ {%- endif %}
11
+ {% endmacro %}
12
+ {%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
13
+ {%- set medium_effort = medium_effort if medium_effort is defined else False %}
14
+ {%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
15
+ {%- set ns = namespace(last_user_idx = -1) %}
16
+ {%- set loop_messages = messages %}
17
+ {%- for m in loop_messages %}
18
+ {%- if m["role"] == "user" %}
19
+ {%- set ns.last_user_idx = loop.index0 %}
20
+ {%- endif %}
21
+ {%- endfor %}
22
+ {%- if messages[0]["role"] == "system" %}
23
+ {%- set system_message = messages[0]["content"] %}
24
+ {%- set loop_messages = messages[1:] %}
25
+ {%- else %}
26
+ {%- set system_message = "" %}
27
+ {%- set loop_messages = messages %}
28
+ {%- endif %}
29
+ {%- if not tools is defined %}
30
+ {%- set tools = [] %}
31
+ {%- endif %}
32
+ {%- set ns = namespace(last_user_idx = -1) %}
33
+ {%- for m in loop_messages %}
34
+ {%- if m["role"] == "user" %}
35
+ {%- set ns.last_user_idx = loop.index0 %}
36
+ {%- endif %}
37
+ {%- endfor %}
38
+ {%- if system_message is defined %}
39
+ {{- "<|im_start|>system\n" + system_message }}
40
+ {%- else %}
41
+ {%- if tools is iterable and tools | length > 0 %}
42
+ {{- "<|im_start|>system\n" }}
43
+ {%- endif %}
44
+ {%- endif %}
45
+ {%- if tools is iterable and tools | length > 0 %}
46
+ {%- if system_message is defined and system_message | length > 0 %}
47
+ {{- "\n\n" }}
48
+ {%- endif %}
49
+ {{- "# Tools\n\nYou have access to the following functions:\n\n" }}
50
+ {{- "<tools>" }}
51
+ {%- for tool in tools %}
52
+ {%- if tool.function is defined %}
53
+ {%- set tool = tool.function %}
54
+ {%- endif %}
55
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
56
+ {%- if tool.description is defined %}
57
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
58
+ {%- endif %}
59
+ {{- '\n<parameters>' }}
60
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
61
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
62
+ {{- '\n<parameter>' }}
63
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
64
+ {%- if param_fields.type is defined %}
65
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
66
+ {%- endif %}
67
+ {%- if param_fields.description is defined %}
68
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
69
+ {%- endif %}
70
+ {%- if param_fields.enum is defined %}
71
+ {{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
72
+ {%- endif %}
73
+ {%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
74
+ {{- render_extra_keys(param_fields, handled_keys) }}
75
+ {{- '\n</parameter>' }}
76
+ {%- endfor %}
77
+ {%- endif %}
78
+ {% set handled_keys = ['type', 'properties', 'required'] %}
79
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
80
+ {%- if tool.parameters is defined and tool.parameters.required is defined %}
81
+ {{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
82
+ {%- endif %}
83
+ {{- '\n</parameters>' }}
84
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
85
+ {{- render_extra_keys(tool, handled_keys) }}
86
+ {{- '\n</function>' }}
87
+ {%- endfor %}
88
+ {{- "\n</tools>" }}
89
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
90
+ {%- endif %}
91
+ {%- if system_message is defined %}
92
+ {{- '<|im_end|>\n' }}
93
+ {%- else %}
94
+ {%- if tools is iterable and tools | length > 0 %}
95
+ {{- '<|im_end|>\n' }}
96
+ {%- endif %}
97
+ {%- endif %}
98
+ {%- for message in loop_messages %}
99
+ {%- if message.role == "assistant" %}
100
+ {%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
101
+ {%- set content = "<think>\n" ~ message.reasoning_content ~ "</think>" ~ (message.content | default('', true)) %}
102
+ {%- else %}
103
+ {%- set content = message.content | default('', true) %}
104
+ {%- if content is string -%}
105
+ {%- if '<think>' not in content and '</think>' not in content -%}
106
+ {%- set content = "<think></think>" ~ content -%}
107
+ {%- endif -%}
108
+ {%- else -%}
109
+ {%- set content = content -%}
110
+ {%- endif -%}
111
+ {%- endif %}
112
+ {%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
113
+ {{- '<|im_start|>assistant\n' }}
114
+ {%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
115
+ {%- if content is string and content | trim | length > 0 %}
116
+ {%- if include_content %}
117
+ {{- (content | trim) ~ '\n' -}}
118
+ {%- else %}
119
+ {%- set c = (content | string) %}
120
+ {%- if '</think>' in c %}
121
+ {%- set c = c.split('</think>')[-1] %}
122
+ {%- elif '<think>' in c %}
123
+ {%- set c = c.split('<think>')[0] %}
124
+ {%- endif %}
125
+ {%- set c = "<think></think>" ~ c %}
126
+ {%- if c | length > 0 %}
127
+ {{- c ~ '\n' -}}
128
+ {%- endif %}
129
+ {%- endif %}
130
+ {%- else %}
131
+ {{- "<think></think>" -}}
132
+ {%- endif %}
133
+ {%- for tool_call in message.tool_calls %}
134
+ {%- if tool_call.function is defined %}
135
+ {%- set tool_call = tool_call.function %}
136
+ {%- endif %}
137
+ {{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
138
+ {%- if tool_call.arguments is defined %}
139
+ {%- for args_name, args_value in tool_call.arguments|items %}
140
+ {{- '<parameter=' ~ args_name ~ '>\n' -}}
141
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
142
+ {{- args_value ~ '\n</parameter>\n' -}}
143
+ {%- endfor %}
144
+ {%- endif %}
145
+ {{- '</function>\n</tool_call>\n' -}}
146
+ {%- endfor %}
147
+ {{- '<|im_end|>\n' }}
148
+ {%- else %}
149
+ {%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
150
+ {{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
151
+ {%- else %}
152
+ {%- set c = (content | default('', true) | string) %}
153
+ {%- if '<think>' in c and '</think>' in c %}
154
+ {%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
155
+ {%- endif %}
156
+ {%- set c = c | trim %}
157
+ {%- if c | length > 0 %}
158
+ {{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }}
159
+ {%- else %}
160
+ {{- '<|im_start|>assistant\n<|im_end|>\n' }}
161
+ {%- endif %}
162
+ {%- endif %}
163
+ {%- endif %}
164
+ {%- elif message.role == "user" or message.role == "system" %}
165
+ {{- '<|im_start|>' + message.role + '\n' }}
166
+ {%- set content = message.content | string %}
167
+ {%- if message.role == "user" and loop.index0 == ns.last_user_idx and medium_effort %}
168
+ {{- content + '\n\n{reasoning effort: efficient}' }}
169
+ {%- else %}
170
+ {{- content }}
171
+ {%- endif %}
172
+ {{- '<|im_end|>\n' }}
173
+ {%- elif message.role == "tool" %}
174
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
175
+ {{- '<|im_start|>user\n' }}
176
+ {%- endif %}
177
+ {{- '<tool_response>\n' }}
178
+ {{- message.content }}
179
+ {{- '\n</tool_response>\n' }}
180
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
181
+ {{- '<|im_end|>\n' }}
182
+ {%- elif loop.last %}
183
+ {{- '<|im_end|>\n' }}
184
+ {%- endif %}
185
+ {%- else %}
186
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
187
+ {%- endif %}
188
+ {%- endfor %}
189
+ {%- if add_generation_prompt %}
190
+ {%- if enable_thinking %}
191
+ {{- '<|im_start|>assistant\n<think>\n' }}
192
+ {%- else %}
193
+ {{- '<|im_start|>assistant\n<think></think>' }}
194
+ {%- endif %}
195
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "NemotronHForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_nemotron_h.NemotronHConfig",
9
+ "AutoModelForCausalLM": "modeling_nemotron_h.NemotronHForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "chunk_size": 128,
13
+ "conv_kernel": 4,
14
+ "dtype": "bfloat16",
15
+ "eos_token_id": 2,
16
+ "expand": 2,
17
+ "head_dim": 128,
18
+ "hidden_dropout": 0.0,
19
+ "hidden_size": 8192,
20
+ "hybrid_override_pattern": "MEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME",
21
+ "initializer_range": 0.02,
22
+ "intermediate_size": 5120,
23
+ "layer_norm_epsilon": 1e-05,
24
+ "mamba_head_dim": 64,
25
+ "mamba_hidden_act": "silu",
26
+ "mamba_num_heads": 256,
27
+ "mamba_proj_bias": false,
28
+ "mamba_ssm_cache_dtype": "float32",
29
+ "max_position_embeddings": 262144,
30
+ "mlp_bias": false,
31
+ "mlp_hidden_act": "relu2",
32
+ "model_type": "nemotron_h",
33
+ "moe_intermediate_size": 5120,
34
+ "moe_latent_size": 2048,
35
+ "moe_shared_expert_intermediate_size": 10240,
36
+ "moe_shared_expert_overlap": false,
37
+ "mtp_hybrid_override_pattern": "*E",
38
+ "n_group": 1,
39
+ "n_groups": 8,
40
+ "n_routed_experts": 512,
41
+ "n_shared_experts": 1,
42
+ "norm_eps": 1e-05,
43
+ "norm_topk_prob": true,
44
+ "num_attention_heads": 64,
45
+ "num_experts_per_tok": 22,
46
+ "num_hidden_layers": 108,
47
+ "num_key_value_heads": 2,
48
+ "num_logits_to_keep": 1,
49
+ "num_nextn_predict_layers": 1,
50
+ "pad_token_id": 0,
51
+ "partial_rotary_factor": 1.0,
52
+ "rescale_prenorm_residual": true,
53
+ "residual_in_fp32": false,
54
+ "rope_theta": 10000,
55
+ "routed_scaling_factor": 5.0,
56
+ "sliding_window": null,
57
+ "ssm_state_size": 128,
58
+ "tie_word_embeddings": false,
59
+ "time_step_floor": 0.0001,
60
+ "time_step_limit": [
61
+ 0.0,
62
+ Infinity
63
+ ],
64
+ "time_step_max": 0.1,
65
+ "time_step_min": 0.001,
66
+ "topk_group": 1,
67
+ "transformers_version": "4.57.6",
68
+ "use_bias": false,
69
+ "use_cache": true,
70
+ "use_conv_bias": true,
71
+ "use_mamba_kernels": true,
72
+ "vocab_size": 131072
73
+ }
configuration_nemotron_h.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 AI21 Labs Ltd. and the HuggingFace Inc. team. All rights reserved.
3
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """NemotronH model configuration"""
17
+
18
+ import re
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class NemotronHConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`NemotronHModel`]. It is used to instantiate a
30
+ NemotronH model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of the NemotronH-v0.1 model.
32
+
33
+ [todo](todo)
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 131072):
41
+ Vocabulary size of the NemotronH model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`NemotronHModel`]
43
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
44
+ Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
45
+ model has a output word embedding layer.
46
+ hidden_size (`int`, *optional*, defaults to 4096):
47
+ Dimension of the hidden representations.
48
+ intermediate_size (`int`, *optional*, defaults to 21504):
49
+ Dimension of the MLP representations.
50
+ num_hidden_layers (`int`, *optional*, defaults to 52):
51
+ Number of hidden layers in the Transformer encoder.
52
+ hybrid_override_pattern (`str`, *optional*, defaults to `"M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-"`):
53
+ The pattern of the hybrid model. The pattern is a string of characters where each character represents M: Mamba2, *: Attention, -: MLP
54
+ num_attention_heads (`int`, *optional*, defaults to 32):
55
+ Number of attention heads for each attention layer in the Transformer encoder.
56
+ head_dim (`int`, *optional*, defaults to 128):
57
+ Dimension of each attention head.
58
+ num_key_value_heads (`int`, *optional*, defaults to 8):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
60
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
62
+ mlp_hidden_act (`str`, *optional*, defaults to "relu2"):
63
+ The non-linear activation function in the MLP layers.
64
+ attention_bias (`bool`, *optional*, defaults to `False`):
65
+ Whether to use bias in attention layers.
66
+ mlp_bias (`bool`, *optional*, defaults to `False`):
67
+ Whether to use bias in MLP layers.
68
+ use_bias (`bool`, *optional*, defaults to `False`):
69
+ Whether to use bias in the model.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
73
+ The epsilon used by the layer normalization layers.
74
+ residual_in_fp32 (`bool`, *optional*, defaults to `False`):
75
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
80
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
81
+ integer value, only last `num_logits_to_keep` logits will be calculated.
82
+ pad_token_id (`int`, *optional*, defaults to 0):
83
+ The id of the padding token.
84
+ bos_token_id (`int`, *optional*, defaults to 1):
85
+ The id of the "beginning-of-sequence" token.
86
+ eos_token_id (`int`, *optional*, defaults to 2):
87
+ The id of the "end-of-sequence" token.
88
+ sliding_window (`int`, *optional*, defaults to None):
89
+ Sliding window attention window size.
90
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
91
+ The maximum sequence length that this model might ever be used with.
92
+ attention_dropout (`float`, *optional*, defaults to 0.0):
93
+ The dropout ratio for the attention probabilities.
94
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
95
+ The dropout ratio for the hidden states.
96
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
97
+ Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
98
+ `causal-conv1d` are installed, and the mamba modules are running on a CUDA device.
99
+ ssm_state_size (`int`, *optional*, defaults to 128):
100
+ The dimension of the mamba state space latents.
101
+ mamba_num_heads (`int`, *optional*, defaults to 128):
102
+ Number of heads in Mamba layers.
103
+ mamba_n_groups (`int`, *optional*, defaults to 8):
104
+ Number of groups in Mamba layers.
105
+ mamba_head_dim (`int`, *optional*, defaults to 64):
106
+ Dimension of each Mamba head.
107
+ mamba_d_conv (`int`, *optional*, defaults to 4):
108
+ The size of the mamba convolution kernel.
109
+ mamba_expand (`int`, *optional*, defaults to 2):
110
+ Expanding factor used to determine the mamba intermediate size.
111
+ mamba_hidden_act (`str`, *optional*, defaults to "silu"):
112
+ The non-linear activation function in the Mamba layers.
113
+ mamba_dt_min (`float`, *optional*, defaults to 0.001):
114
+ Minimum value for the time step in Mamba.
115
+ mamba_dt_max (`float`, *optional*, defaults to 0.1):
116
+ Maximum value for the time step in Mamba.
117
+ mamba_dt_limit (`tuple`, *optional*, defaults to (0.0, float("inf"))):
118
+ Limits for the time step in Mamba.
119
+ mamba_dt_init_floor (`float`, *optional*, defaults to 1e-4):
120
+ Floor value for time step initialization in Mamba.
121
+ mamba_conv_bias (`bool`, *optional*, defaults to `True`):
122
+ Whether to use bias in the convolution layer of the mamba mixer block.
123
+ mamba_proj_bias (`bool`, *optional*, defaults to `False`):
124
+ Whether to use bias in the input and output projections of the mamba mixer block.
125
+ mamba_chunk_size (`int`, *optional*, defaults to 256):
126
+ Size of chunks for Mamba processing.
127
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
128
+ Whether to rescale the pre-normalization residual connections.
129
+ """
130
+
131
+ model_type = "nemotron_h"
132
+ keys_to_ignore_at_inference = ["past_key_values"]
133
+
134
+ def __init__(
135
+ self,
136
+ vocab_size=131072,
137
+ tie_word_embeddings=False,
138
+ hidden_size=4096,
139
+ intermediate_size=21504,
140
+ num_hidden_layers=52,
141
+ 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-",
142
+ num_attention_heads=32,
143
+ head_dim=128,
144
+ num_key_value_heads=8, # nemo: num_query_groups
145
+ mlp_hidden_act="relu2",
146
+ attention_bias=False,
147
+ mlp_bias=False,
148
+ use_bias=False,
149
+ initializer_range=0.02, # nemo: init_method_std
150
+ layer_norm_epsilon=1e-5, # nemo: layernorm_epsilon
151
+ residual_in_fp32=False, # Megatron Core default value
152
+ use_cache=True,
153
+ num_logits_to_keep=1,
154
+ pad_token_id=0,
155
+ bos_token_id=1,
156
+ eos_token_id=2,
157
+ sliding_window=None,
158
+ max_position_embeddings=4096,
159
+ attention_dropout=0.0,
160
+ hidden_dropout=0.0, # * ADDED
161
+ use_mamba_kernels=True,
162
+ ssm_state_size=128, # mamba_state_size
163
+ mamba_num_heads=128,
164
+ mamba_n_groups=8, # nemo: mamba_ssm_ngroups = num_heads
165
+ mamba_head_dim=64,
166
+ mamba_d_conv=4,
167
+ mamba_expand=2,
168
+ mamba_hidden_act="silu",
169
+ mamba_dt_min=0.001,
170
+ mamba_dt_max=0.1,
171
+ mamba_dt_limit=(0.0, float("inf")),
172
+ mamba_dt_init_floor=1e-4,
173
+ mamba_conv_bias=True,
174
+ mamba_proj_bias=False,
175
+ mamba_chunk_size=128,
176
+ rescale_prenorm_residual=True,
177
+ n_routed_experts=8,
178
+ n_shared_experts=1,
179
+ moe_intermediate_size=7688,
180
+ moe_shared_expert_intermediate_size=7688,
181
+ moe_latent_size=None,
182
+ moe_shared_expert_overlap=True,
183
+ num_experts_per_tok=2,
184
+ routed_scaling_factor=1.0,
185
+ n_group=1,
186
+ topk_group=1,
187
+ norm_topk_prob=True,
188
+ mamba_ssm_cache_dtype="float32",
189
+ num_nextn_predict_layers=0,
190
+ mtp_hybrid_override_pattern="*E",
191
+ **kwargs,
192
+ ):
193
+ self.vocab_size = vocab_size
194
+ self.tie_word_embeddings = tie_word_embeddings
195
+ self.hidden_size = hidden_size
196
+ self.intermediate_size = intermediate_size
197
+ self.num_hidden_layers = num_hidden_layers
198
+ self.hybrid_override_pattern = hybrid_override_pattern
199
+ self.num_attention_heads = num_attention_heads
200
+ self.head_dim = head_dim
201
+ self.sliding_window = sliding_window
202
+ self.max_position_embeddings = max_position_embeddings
203
+ self.attention_dropout = attention_dropout
204
+ self.hidden_dropout = hidden_dropout
205
+
206
+ # Validate hybrid_override_pattern
207
+ # M: Mamba2, *: Attention, -: MLP
208
+ assert len(self.hybrid_override_pattern) == self.num_hidden_layers, "hybrid_override_pattern must have the same length as num_hidden_layers"
209
+ assert re.match(r"^[ME*-]+$", self.hybrid_override_pattern), "hybrid_override_pattern must only contain characters 'M', '*', 'E',or '-'"
210
+
211
+ # for backward compatibility
212
+ if num_key_value_heads is None:
213
+ num_key_value_heads = num_attention_heads
214
+
215
+ self.num_key_value_heads = num_key_value_heads
216
+ self.mlp_hidden_act = mlp_hidden_act
217
+ self.attention_bias = attention_bias
218
+ self.mlp_bias = mlp_bias
219
+ self.use_bias = use_bias
220
+ self.initializer_range = initializer_range
221
+ self.layer_norm_epsilon = layer_norm_epsilon
222
+ self.residual_in_fp32 = residual_in_fp32
223
+
224
+ self.use_cache = use_cache
225
+ self.num_logits_to_keep = num_logits_to_keep
226
+
227
+ self.use_mamba_kernels = use_mamba_kernels
228
+ self.n_groups = mamba_n_groups
229
+ self.mamba_head_dim = mamba_head_dim
230
+ self.ssm_state_size = ssm_state_size
231
+ self.mamba_num_heads = mamba_num_heads
232
+ self.conv_kernel = mamba_d_conv
233
+ self.expand = mamba_expand
234
+ self.mamba_hidden_act = mamba_hidden_act
235
+ self.time_step_min = mamba_dt_min
236
+ self.time_step_max = mamba_dt_max
237
+ self.time_step_limit = mamba_dt_limit
238
+ self.time_step_floor = mamba_dt_init_floor
239
+ self.use_conv_bias = mamba_conv_bias
240
+ self.mamba_proj_bias = mamba_proj_bias
241
+ self.chunk_size = mamba_chunk_size
242
+ self.rescale_prenorm_residual = rescale_prenorm_residual
243
+ self.n_routed_experts = n_routed_experts
244
+ self.n_shared_experts = n_shared_experts
245
+ self.moe_intermediate_size = moe_intermediate_size
246
+ self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
247
+ self.moe_latent_size = moe_latent_size
248
+ self.moe_shared_expert_overlap = moe_shared_expert_overlap
249
+ self.num_experts_per_tok = num_experts_per_tok
250
+ self.routed_scaling_factor = routed_scaling_factor
251
+ self.n_group = n_group
252
+ self.topk_group = topk_group
253
+ self.norm_topk_prob = norm_topk_prob
254
+ self.mamba_ssm_cache_dtype = mamba_ssm_cache_dtype
255
+
256
+ # MTP config
257
+ # TODO(liding):--keep-mtp-spec-in-bf16
258
+ self.num_nextn_predict_layers = num_nextn_predict_layers
259
+ self.mtp_hybrid_override_pattern = mtp_hybrid_override_pattern
260
+ if self.num_nextn_predict_layers > 0:
261
+ assert re.match(r"^[ME*-]+$", self.mtp_hybrid_override_pattern), "mtp_hybrid_override_pattern must only contain characters 'M', '*', 'E',or '-'"
262
+
263
+ super().__init__(
264
+ pad_token_id=pad_token_id,
265
+ bos_token_id=bos_token_id,
266
+ eos_token_id=eos_token_id,
267
+ tie_word_embeddings=tie_word_embeddings,
268
+ **kwargs,
269
+ )
270
+
271
+ @property
272
+ def layers_block_type(self):
273
+ return [
274
+ "mamba" if self.hybrid_override_pattern[i] == "M" else
275
+ "attention" if self.hybrid_override_pattern[i] == "*" else
276
+ "mlp" if self.hybrid_override_pattern[i] == "-" else "moe"
277
+ for i in range(self.num_hidden_layers)]
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 2,
7
+ 11
8
+ ],
9
+ "pad_token_id": 0,
10
+ "top_p": 0.95,
11
+ "transformers_version": "4.57.6"
12
+ }
model-00002-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1127265eb16e2e53e6912d66c9a04d4c0760d91e69aa0d458a78d121a60a19ff
3
+ size 4991252496
model-00007-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c17e2b3857b2c89f86a2ded1a563467de2add8b2ed32224400a4aaf365cb45ab
3
+ size 4991252600
model-00009-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50d1602029ffa9500408e0cc15ff890ef745cfb26aa5339f80d941f3902f61c4
3
+ size 4991252600
model-00013-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1f5df87ccb587062bf1d82093e8465f1c89d084dbffdc3a2e72cd3f4285db41
3
+ size 4991252600
model-00016-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2510393315fd877aafbb7252102fdf868bb9575d372b7d69323fada45a2462c6
3
+ size 4991252560
model-00018-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80efc221dee4ae44c52200348c10b137b027cad842b65df948b2b3624cbc87fa
3
+ size 4991252600
model-00025-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7903e5bdf84f53e795080be12c48f80bad2c50961d8e315ebc66e761f1f9d4be
3
+ size 4991252776
model-00034-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f14106f36d042eaf7aad06f382cdd488fe043151b653e7f571273dae402da0f
3
+ size 4991252736
model-00045-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30f30d43e148952f42b55a927a3f1a31d9a7de9f42b29a49385b2f2856e0f201
3
+ size 4991252840
model-00054-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ebaf75e5ad43099a3ba7fec02f1e3fdbcb95ba1435893e87ceb605f31decce5
3
+ size 4991252840
model-00062-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c7777339e974007cb198421e46d0e8e1e94035e59d6c3d237989722a2cf5a92
3
+ size 4991252840
model-00067-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe36684ec7aa3d516aec33cb8aafc5586bacc249a5b89eff24ed6b7da5117c87
3
+ size 4991252840
model-00073-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a1c6524d115e1ac81ac010f67bac95fb9b15e1353c488e1c58646085b646761
3
+ size 4991252840
model-00078-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ad859266dcd7f40117d63ad6d9bbbe9ef5ef989b976f14f06c26e05e4f195fe
3
+ size 4991252840
model-00080-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2674b3950ea00e199b3ac476e90aceb1ee08815ef54b7c25193ecefaa534588d
3
+ size 4991252800
model-00091-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34a10f833ba76fcb8e4eb0fde36f3fadd1947d459eeddd92b83f3c3ecfac1f82
3
+ size 4991252840
model-00094-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3855c9eecda5fab4241c58768f8470e75685ecfac3ff58def8f93954a9a4e765
3
+ size 4991252840
model-00104-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:964f8f6c0dbb8f488533fa67b237c97cc167a75947318a61048f3f57b2df8753
3
+ size 4991252840
model-00110-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2180284210e59e5b3edb27d18fbca115c014d7cb7215f022469b596d8608ba95
3
+ size 4991252840
model-00115-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17199d9ac0ce945534b6a6689a252796c2414f473bfe9426bb2d0d9158dd5b88
3
+ size 4991515464
model-00123-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8777aeff901e8c99fae7ee02ea878f7f284e0873d1e68b8d755be20b8c308ecf
3
+ size 4991252840
model-00128-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f0e70c0ff113cb8139d520cd5080b51141e79a2b161c4085a1d1e32dd67253a
3
+ size 4991252840
model-00132-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38a607341a14b225d61895580165e0f63155cfaf1d3f2d6315f7236ae671827a
3
+ size 4991252840
model-00139-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a653ba01cbb7bc1909c96611a7f18ae231e082c96f30698a26a8d22fec5453e6
3
+ size 4991252704
model-00143-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39b21b6d6c6aa101c5f90d3d37cddf2d0becfb619af04f41f0aacc19ec3a729e
3
+ size 4987305824
model-00148-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:20ed5c155e2af65225a246a1ae0b2684c010d8a8ca1ff2862ca41f143437f119
3
+ size 4991252664
model-00151-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33222f0a8f2026f884ad4e65a8b60f6d4cf5b296ecbd665be8e2abb8ebe4d97c
3
+ size 4991252840
model-00152-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d07b82937f503d97383be0ea2053125aeb11cdfc490cace61872eeed9d98cb7
3
+ size 4987305808
model-00157-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fd9c2fa2fea86a5255e3980536d3056813fd0ac9868fa4ea34a49310dcfa8b2
3
+ size 4991252624
model-00159-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90e1c7700865018559cd01ba2184711355214ac5588452944dce7b332eeadfdb
3
+ size 4991252840
model-00161-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1aed933ccf74bfbc2a0111bf2f3288b966b33a2f1f238b8cf402154afe72f8a5
3
+ size 4987305832
model-00164-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:63b6ced1d30b92ee483cf0a9481a3a98bff1ae269fef12c62c1c7c153da03f1f
3
+ size 4991252840
model-00170-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b568ef73903ce4004a232bfd572e98c794ad6475af8a8aecfcded789832941a
3
+ size 4987305888
model-00183-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a1108b62fe6741c5a6106f02720de63ef8e80e6d88aecb1a4a98a0fcbba534a
3
+ size 4991252840
model-00192-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df3bba0b19583909a7f263371180d307f2a1e0b3e51ac3d5465fbb142dff6316
3
+ size 4991252840
model-00206-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61a9f4b21de5a830e59ba0283c472ff3542292e5b467c67f06090318fa3fb09e
3
+ size 4991253080
model-00211-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f2a02ced1cd8076a265292d5ba99e716887dea83c78b2d770ab1b28091ba225
3
+ size 4987306104
model-00214-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1709389d3fb11fac4c4565f1f91b47dc5621d80558f33f5e8fe11663cb05283
3
+ size 4991253080
model-00222-of-00225.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e8fa30de71d09646e3d330800bc016b598d8863300eb9d9c05ddd086b375709
3
+ size 4991251320
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_nemotron_h.py ADDED
@@ -0,0 +1,1810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc. team.
3
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch NemotronH model."""
17
+
18
+ import copy
19
+ import math
20
+ from dataclasses import dataclass
21
+ from typing import Any, Dict, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import CrossEntropyLoss
27
+ import torch.nn.functional as F
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import DynamicCache # we need __iter__ and __len__ of pkv
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.modeling_attn_mask_utils import (
33
+ AttentionMaskConverter,
34
+ )
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.utils import (
37
+ ModelOutput,
38
+ add_code_sample_docstrings,
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ logging,
42
+ )
43
+ from transformers.utils.import_utils import (
44
+ is_causal_conv1d_available,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ is_mamba_2_ssm_available,
48
+ )
49
+ from .configuration_nemotron_h import NemotronHConfig
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ # Copied from transformers.models.mamba.modeling_mamba2.modeling_mamba2.py with MAMBA2->NEMOTRONH,Mamba2->NemotronH
56
+ # For Mamba2 components Mamba2->NemotronHMamba2
57
+ if is_mamba_2_ssm_available():
58
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
59
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
60
+ else:
61
+ mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, selective_state_update = None, None, None
62
+
63
+ try:
64
+ #from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated
65
+ from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn
66
+ except ImportError:
67
+ raise ImportError("mamba-ssm is required by the Mamba model but cannot be imported")
68
+
69
+ if is_causal_conv1d_available():
70
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
71
+ else:
72
+ causal_conv1d_update, causal_conv1d_fn = None, None
73
+
74
+ if is_flash_attn_2_available():
75
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
76
+
77
+ is_fast_path_available = all(
78
+ (
79
+ selective_state_update,
80
+ mamba_chunk_scan_combined,
81
+ mamba_split_conv1d_scan_combined,
82
+ causal_conv1d_fn,
83
+ causal_conv1d_update,
84
+ )
85
+ )
86
+
87
+
88
+ _CHECKPOINT_FOR_DOC = "nvidia/Nemotron-H-56B-Base-8K"
89
+ _CONFIG_FOR_DOC = "NemotronHConfig"
90
+
91
+
92
+ # Helper methods for segment sum computation
93
+
94
+
95
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
96
+ """
97
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
98
+
99
+ Assumes that we only have tensors of either size 4 or 3
100
+ """
101
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
102
+
103
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
104
+
105
+
106
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
107
+ """
108
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
109
+ simultaneously splitting it into chunk sequences.
110
+
111
+ Assumes that we only have tensors of either size 4 or 3
112
+ """
113
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
114
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
115
+
116
+ if len(input_tensor.shape) == 3:
117
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
118
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
119
+ else:
120
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
121
+ return input_tensor.reshape(
122
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
123
+ )
124
+
125
+
126
+ def segment_sum(input_tensor):
127
+ """
128
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
129
+ """
130
+ chunk_size = input_tensor.size(-1)
131
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
132
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
133
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
134
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
135
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
136
+ input_tensor = input_tensor.masked_fill(~mask, 0)
137
+ # 3. compute actual cumsum
138
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
139
+
140
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
141
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
142
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
143
+ return tensor_segsum
144
+
145
+
146
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
147
+ """
148
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
149
+ """
150
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
151
+ dtype = hidden_states.dtype
152
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
153
+
154
+ return hidden_states
155
+
156
+ # Copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
157
+ class HybridMambaAttentionDynamicCache(DynamicCache):
158
+ """
159
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
160
+ (which has a constant shape regardless of seq_len).
161
+
162
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
163
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
164
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
165
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
166
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
167
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
168
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
169
+ """
170
+
171
+ def __init__(self, config, batch_size, dtype=torch.float16, device=None):
172
+ super().__init__()
173
+ self.dtype = dtype
174
+ self.hybrid_override_pattern = config.hybrid_override_pattern
175
+ self.has_previous_state = False # only used by mamba
176
+ intermediate_size = config.mamba_num_heads * config.mamba_head_dim
177
+ ssm_state_size = config.ssm_state_size
178
+ conv_kernel_size = config.conv_kernel
179
+ self.conv_states = []
180
+ self.ssm_states = []
181
+ self.transformer_layers = []
182
+ for i in range(config.num_hidden_layers):
183
+ if self.hybrid_override_pattern[i] == "M":
184
+ # Mamba layer
185
+ self.conv_states += [
186
+ torch.zeros(batch_size, intermediate_size, conv_kernel_size, device=device, dtype=dtype)
187
+ ]
188
+ self.ssm_states += [
189
+ torch.zeros(batch_size, intermediate_size, ssm_state_size, device=device, dtype=dtype)
190
+ ]
191
+ else:
192
+ # Attention or MLP layer
193
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
194
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
195
+ self.transformer_layers.append(i)
196
+
197
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
198
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
199
+
200
+ def update(
201
+ self,
202
+ key_states: torch.Tensor,
203
+ value_states: torch.Tensor,
204
+ layer_idx: int,
205
+ cache_kwargs: Optional[Dict[str, Any]] = None,
206
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
207
+ # Update the cache
208
+ if self.key_cache[layer_idx].shape[-1] == 0:
209
+ self.key_cache[layer_idx] = key_states
210
+ self.value_cache[layer_idx] = value_states
211
+ else:
212
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
213
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
214
+
215
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
216
+
217
+ def reorder_cache(self, beam_idx: torch.LongTensor):
218
+ """Reorders the cache for beam search, given the selected beam indices."""
219
+ for layer_idx in range(len(self.key_cache)):
220
+ device = self.key_cache[layer_idx].device
221
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
222
+ device = self.value_cache[layer_idx].device
223
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
224
+
225
+ device = self.conv_states[layer_idx].device
226
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
227
+ device = self.ssm_states[layer_idx].device
228
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
229
+
230
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
231
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
232
+ # take any layer that contains cache and not empty tensor
233
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
234
+ if len(self.key_cache) <= layer_idx:
235
+ return 0
236
+ return self.key_cache[layer_idx].shape[-2]
237
+
238
+ def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor], Tuple[torch.Tensor]]:
239
+ raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
240
+
241
+ @classmethod
242
+ def from_legacy_cache(cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None) -> "DynamicCache":
243
+ raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
244
+
245
+ # Copied from modeling_mamba2.py
246
+ def update_conv_state(
247
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_init: bool = False
248
+ ) -> torch.Tensor:
249
+ if cache_init:
250
+ self.conv_states[layer_idx] = new_conv_state.to(self.conv_states.device)
251
+ else:
252
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(shifts=-1, dims=-1)
253
+ self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(self.conv_states.device)
254
+ return self.conv_states[layer_idx]
255
+
256
+ def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
257
+ self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
258
+ return self.ssm_states[layer_idx]
259
+
260
+ def reset(self):
261
+ self.conv_states.zero_()
262
+ self.ssm_states.zero_()
263
+
264
+ class MambaRMSNormGated(torch.nn.Module):
265
+ def __init__(self, hidden_size, group_size, eps=1e-5):
266
+ super().__init__()
267
+ self.weight = nn.Parameter(torch.ones(hidden_size))
268
+ self.variance_epsilon = eps
269
+ self.group_size = group_size
270
+
271
+ # jan28b version
272
+ def forward(self, hidden_states, gate=None):
273
+ return rmsnorm_fn(x=hidden_states,
274
+ weight=self.weight,
275
+ bias=None, # No bias
276
+ z=gate,
277
+ eps=self.variance_epsilon,
278
+ group_size=self.group_size,
279
+ norm_before_gate=False
280
+ )
281
+
282
+ class NemotronHMamba2Mixer(nn.Module):
283
+ """
284
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
285
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
286
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
287
+ and is why Mamba is called **selective** state spaces)
288
+ """
289
+
290
+ def __init__(self, config: NemotronHConfig, layer_idx: int):
291
+ super().__init__()
292
+ self.num_heads = config.mamba_num_heads
293
+ self.hidden_size = config.hidden_size
294
+ self.ssm_state_size = config.ssm_state_size
295
+ self.conv_kernel_size = config.conv_kernel
296
+ self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
297
+ self.layer_idx = layer_idx
298
+ self.use_conv_bias = config.use_conv_bias
299
+ self.activation = config.mamba_hidden_act
300
+ self.act = ACT2FN[config.mamba_hidden_act]
301
+
302
+ self.layer_norm_epsilon = config.layer_norm_epsilon
303
+
304
+ self.n_groups = config.n_groups
305
+ self.head_dim = config.mamba_head_dim
306
+ self.chunk_size = config.chunk_size
307
+
308
+ self.time_step_limit = config.time_step_limit
309
+ self.time_step_min = config.time_step_min
310
+ self.time_step_max = config.time_step_max
311
+
312
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
313
+ self.conv1d = nn.Conv1d(
314
+ in_channels=self.conv_dim,
315
+ out_channels=self.conv_dim,
316
+ bias=config.use_conv_bias,
317
+ kernel_size=config.conv_kernel,
318
+ groups=self.conv_dim,
319
+ padding=config.conv_kernel - 1,
320
+ )
321
+
322
+ # projection of the input hidden states
323
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
324
+ self.in_proj = nn.Linear(
325
+ self.hidden_size,
326
+ projection_size,
327
+ bias=config.use_bias,
328
+ )
329
+ # selective projection used to make dt, B and C input dependant
330
+
331
+ # time step projection (discretization)
332
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
333
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
334
+
335
+ # S4D real initialization. These are not discretized!
336
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
337
+ A = torch.arange(1, self.num_heads + 1)
338
+ self.A_log = nn.Parameter(torch.log(A))
339
+ self.A_log._no_weight_decay = True
340
+ self.norm = MambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon, group_size=self.intermediate_size // self.n_groups)
341
+ self.D = nn.Parameter(torch.ones(self.num_heads))
342
+ self.D._no_weight_decay = True
343
+
344
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
345
+ self.use_bias = config.use_bias
346
+
347
+ if not is_fast_path_available:
348
+ logger.warning_once(
349
+ "The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
350
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
351
+ " https://github.com/Dao-AILab/causal-conv1d"
352
+ )
353
+
354
+ def cuda_kernels_forward(
355
+ self,
356
+ hidden_states: torch.Tensor,
357
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
358
+ cache_position: Optional[torch.LongTensor] = None,
359
+ attention_mask: Optional[torch.Tensor] = None,
360
+ ):
361
+ # 1. Gated MLP's linear projection
362
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
363
+ projected_states = self.in_proj(hidden_states)
364
+
365
+ # Set up dimensions for reshapes later
366
+ batch_size, seq_len, _ = hidden_states.shape
367
+ groups_time_state_size = self.n_groups * self.ssm_state_size
368
+ d_mlp = (
369
+ projected_states.shape[-1]
370
+ - 2 * self.intermediate_size
371
+ - 2 * self.n_groups * self.ssm_state_size
372
+ - self.num_heads
373
+ ) // 2
374
+
375
+ # Single step calculations via cache
376
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
377
+ _, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
378
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
379
+ )
380
+
381
+ # 2. Convolution sequence transformation
382
+ hidden_states_B_C = causal_conv1d_update(
383
+ hidden_states_B_C,
384
+ cache_params.conv_states[self.layer_idx],
385
+ self.conv1d.weight.squeeze(1),
386
+ self.conv1d.bias,
387
+ self.activation,
388
+ )
389
+
390
+ hidden_states, B, C = torch.split(
391
+ hidden_states_B_C,
392
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
393
+ dim=-1,
394
+ )
395
+
396
+ # 3. SSM transformation
397
+ A = -torch.exp(self.A_log.float()) # (nheads,)
398
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
399
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
400
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
401
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
402
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
403
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
404
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
405
+ hidden_states = selective_state_update(
406
+ cache_params.ssm_states[self.layer_idx],
407
+ hidden_states_reshaped,
408
+ dt,
409
+ A,
410
+ B,
411
+ C,
412
+ D,
413
+ z=None,
414
+ dt_bias=dt_bias,
415
+ dt_softplus=True,
416
+ )
417
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
418
+ hidden_states = self.norm(hidden_states, gate)
419
+
420
+ # 4. Final linear projection
421
+ out = self.out_proj(hidden_states)[:, None, ...]
422
+
423
+ # Fused calculations or step by step if no initialized cache is found
424
+ else:
425
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
426
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
427
+
428
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
429
+ if self.training and cache_params is None:
430
+ out = mamba_split_conv1d_scan_combined(
431
+ projected_states,
432
+ self.conv1d.weight.squeeze(1),
433
+ self.conv1d.bias,
434
+ self.dt_bias,
435
+ A,
436
+ D=self.D,
437
+ chunk_size=self.chunk_size,
438
+ seq_idx=None, # was seq_idx
439
+ activation=self.activation,
440
+ rmsnorm_weight=self.norm.weight,
441
+ rmsnorm_eps=self.norm.variance_epsilon,
442
+ outproj_weight=self.out_proj.weight,
443
+ outproj_bias=self.out_proj.bias,
444
+ headdim=self.head_dim,
445
+ ngroups=self.n_groups,
446
+ norm_before_gate=False,
447
+ return_final_states=False,
448
+ **dt_limit_kwargs,
449
+ )
450
+
451
+ else:
452
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
453
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
454
+ )
455
+
456
+ # 2. Convolution sequence transformation
457
+ # Init cache
458
+ if cache_params is not None:
459
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
460
+ conv_states = nn.functional.pad(
461
+ hidden_states_B_C_transposed,
462
+ (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
463
+ )
464
+ cache_params.update_conv_state(
465
+ layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
466
+ )
467
+
468
+ if self.activation not in ["silu", "swish"]:
469
+ hidden_states_B_C = self.act(
470
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
471
+ )
472
+ else:
473
+ hidden_states_B_C = causal_conv1d_fn(
474
+ x=hidden_states_B_C.transpose(1, 2),
475
+ weight=self.conv1d.weight.squeeze(1),
476
+ bias=self.conv1d.bias,
477
+ activation=self.activation,
478
+ ).transpose(1, 2)
479
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
480
+ hidden_states, B, C = torch.split(
481
+ hidden_states_B_C,
482
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
483
+ dim=-1,
484
+ )
485
+
486
+ # 3. SSM transformation
487
+ scan_output, ssm_state = mamba_chunk_scan_combined(
488
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
489
+ dt,
490
+ A,
491
+ B.view(batch_size, seq_len, self.n_groups, -1),
492
+ C.view(batch_size, seq_len, self.n_groups, -1),
493
+ chunk_size=self.chunk_size,
494
+ D=self.D,
495
+ z=None,
496
+ seq_idx=None,
497
+ return_final_states=True,
498
+ dt_bias=self.dt_bias,
499
+ dt_softplus=True,
500
+ **dt_limit_kwargs,
501
+ )
502
+
503
+ # Init cache
504
+ if ssm_state is not None and cache_params is not None:
505
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
506
+
507
+ scan_output = scan_output.view(batch_size, seq_len, -1)
508
+
509
+ # Multiply "gate" branch and apply extra normalization layer
510
+ scan_output = self.norm(scan_output, gate)
511
+
512
+ # 4. Final linear projection
513
+ out = self.out_proj(scan_output)
514
+ return out
515
+
516
+ # fmt: off
517
+ def torch_forward(self, input_states, cache_params: Optional[HybridMambaAttentionDynamicCache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None):
518
+ batch_size, seq_len, _ = input_states.shape
519
+ dtype = input_states.dtype
520
+
521
+ # 1. Gated MLP's linear projection
522
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
523
+ projected_states = self.in_proj(input_states)
524
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size-self.num_heads) // 2
525
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
526
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
527
+ )
528
+
529
+ # 2. Convolution sequence transformation
530
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
531
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
532
+
533
+ # We need to guarantee that anything regarding the cache is on the same device
534
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
535
+
536
+ hidden_states_B_C = torch.sum(
537
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
538
+ )
539
+ if self.use_conv_bias:
540
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
541
+ hidden_states_B_C = self.act(hidden_states_B_C)
542
+ else:
543
+ # Init cache
544
+ if cache_params is not None:
545
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
546
+ conv_states = nn.functional.pad(
547
+ hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
548
+ )
549
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
550
+
551
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
552
+
553
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
554
+ hidden_states, B, C = torch.split(
555
+ hidden_states_B_C,
556
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
557
+ dim=-1
558
+ )
559
+
560
+ # 3. SSM transformation
561
+ A = -torch.exp(self.A_log.float()) # [num_heads]
562
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
563
+ # We need to guarantee that anything regarding the cache is on the same device
564
+ cache_device = cache_params.ssm_states.device
565
+
566
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
567
+ # for batched generation
568
+ dt = dt[:, 0, :][:, None, ...]
569
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
570
+ # [num_heads] -> [num_heads, head_dim]
571
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
572
+
573
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
574
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
575
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
576
+ # [bsz, num_heads, head_dim, state_size]
577
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
578
+
579
+ # Discretize B
580
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
581
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
582
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
583
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
584
+ B = B.reshape(batch_size, -1, B.shape[-1])
585
+ # [bsz, num_heads, head_dim, state_size]
586
+ dB = dt[..., None] * B[..., None, :]
587
+
588
+ # Discretize x into dB
589
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
590
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
591
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
592
+
593
+ # State calculation
594
+ cache_params.update_ssm_state(
595
+ layer_idx=self.layer_idx,
596
+ new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
597
+ )
598
+
599
+ # Subsequent output
600
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
601
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
602
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
603
+ C = C.reshape(batch_size, -1, C.shape[-1])
604
+ # [bsz, num_heads, head_dim]
605
+
606
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
607
+ # Reshape ssm_states to merge the first two dimensions
608
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
609
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
610
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
611
+ y = y.view(batch_size, self.num_heads, self.head_dim)
612
+
613
+ # D skip connection
614
+ # [num_heads] -> [num_heads, head_dim]
615
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
616
+ y = (y + hidden_states * D).to(y.dtype)
617
+
618
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
619
+ y = y.reshape(batch_size, -1)[:, None, ...]
620
+ else:
621
+ # begin ssd naive implementation without einsums
622
+ dt = nn.functional.softplus(dt + self.dt_bias)
623
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
624
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
625
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
626
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
627
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
628
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
629
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
630
+
631
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
632
+
633
+ # Discretize x and A
634
+ hidden_states = hidden_states * dt[..., None]
635
+ A = A.to(hidden_states.dtype) * dt
636
+
637
+ # Rearrange into blocks/chunks
638
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
639
+
640
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
641
+ A = A.permute(0, 3, 1, 2)
642
+ A_cumsum = torch.cumsum(A, dim=-1)
643
+
644
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
645
+ # This is the analog of a causal mask
646
+ L = torch.exp(segment_sum(A))
647
+
648
+ # Contraction of C and B to get G (attention-weights like)
649
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
650
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
651
+
652
+ # Compute M, equivalent to applying attention mask to weights
653
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
654
+ M = M_intermediate.sum(dim=-1)
655
+
656
+ # Compute Y_diag (apply to values)
657
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
658
+
659
+ # 2. Compute the state for each intra-chunk
660
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
661
+ decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
662
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
663
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
664
+
665
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
666
+ # (middle term of factorization of off-diag blocks; A terms)
667
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
668
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
669
+ else:
670
+ previous_states = torch.zeros_like(states[:, :1])
671
+ states = torch.cat([previous_states, states], dim=1)
672
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
673
+ decay_chunk = decay_chunk.transpose(1, 3)
674
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
675
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
676
+
677
+ # 4. Compute state -> output conversion per chunk
678
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
679
+ state_decay_out = torch.exp(A_cumsum)
680
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
681
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
682
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
683
+
684
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
685
+ y = Y_diag + Y_off
686
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
687
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
688
+
689
+ y = y + D_residual
690
+ # Cutting off padded chunks
691
+ if pad_size > 0:
692
+ y = y[:, :seq_len, :, :]
693
+ y = y.reshape(batch_size, seq_len, -1)
694
+
695
+ # Init cache
696
+ if ssm_state is not None and cache_params is not None:
697
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
698
+
699
+ scan_output = self.norm(y, gate)
700
+
701
+ # end ssd naive
702
+
703
+ # 4. Final linear projection
704
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
705
+ return contextualized_states
706
+ # fmt: on
707
+
708
+ def forward(
709
+ self,
710
+ hidden_states,
711
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
712
+ cache_position: Optional[torch.LongTensor] = None,
713
+ attention_mask: Optional[torch.Tensor] = None,
714
+ ):
715
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
716
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
717
+ dtype = hidden_states.dtype
718
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
719
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
720
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
721
+
722
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
723
+
724
+
725
+ class NemotronHRMSNorm(nn.Module):
726
+ def __init__(self, hidden_size, eps=1e-6):
727
+ """
728
+ NemotronHRMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
729
+ """
730
+ super().__init__()
731
+ self.weight = nn.Parameter(torch.ones(hidden_size))
732
+ self.variance_epsilon = eps
733
+
734
+ def forward(self, hidden_states):
735
+ input_dtype = hidden_states.dtype
736
+ hidden_states = hidden_states.to(torch.float32)
737
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
738
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
739
+ # Weights are in float32
740
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
741
+
742
+ class NemotronHBlock(nn.Module):
743
+ def __init__(self, config, layer_idx):
744
+ super().__init__()
745
+ self.config = config
746
+ self.layer_idx = layer_idx
747
+ self.residual_in_fp32 = config.residual_in_fp32
748
+ self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
749
+
750
+ # M: Mamba2, *: Attention, -: MLP
751
+ self.block_type = config.layers_block_type[layer_idx]
752
+ if self.block_type == "mamba":
753
+ self.mixer = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
754
+ elif self.block_type == "attention":
755
+ self.mixer = NEMOTRONH_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
756
+ elif self.block_type == "mlp":
757
+ self.mixer = NemotronHMLP(config, layer_idx=layer_idx)
758
+ elif self.block_type == "moe":
759
+ self.mixer = NemotronHMOE(config, layer_idx=layer_idx)
760
+ else:
761
+ raise ValueError(f"Invalid layer pattern {config.hybrid_override_pattern[layer_idx]}")
762
+
763
+ def forward(
764
+ self,
765
+ hidden_states,
766
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
767
+ cache_position: Optional[torch.LongTensor] = None,
768
+ attention_mask: Optional[torch.Tensor] = None,
769
+ ):
770
+ with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
771
+ # * Use torch.cuda.stream() to avoid NaN issues when using multiple GPUs
772
+ residual = hidden_states
773
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
774
+ if self.residual_in_fp32:
775
+ residual = residual.to(torch.float32)
776
+
777
+ if self.block_type == "mamba":
778
+ hidden_states = self.mixer(
779
+ hidden_states, cache_params=cache_params, cache_position=cache_position
780
+ )
781
+ elif self.block_type == "attention":
782
+ hidden_states = self.mixer(
783
+ hidden_states, cache_position=cache_position
784
+ )
785
+ hidden_states = hidden_states[0]
786
+ elif self.block_type in ["mlp", "moe"]:
787
+ hidden_states = self.mixer(
788
+ hidden_states
789
+ )
790
+ else:
791
+ raise ValueError(f"Invalid block_type: {self.block_type}")
792
+
793
+ hidden_states = residual + hidden_states
794
+ return hidden_states
795
+
796
+
797
+ # Copied from transformers.models.nemotron.modeling_nemotron Nemotron->NemotronH
798
+ class NemotronHMLP(nn.Module):
799
+ def __init__(self, config, intermediate_size=None, layer_idx: Optional[int] = None, is_expert=False):
800
+ super().__init__()
801
+ self.config = config
802
+ self.layer_idx = layer_idx
803
+ if layer_idx is None:
804
+ logger.warning_once(
805
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
806
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
807
+ "when creating this class."
808
+ )
809
+ use_latent_size = (self.config.moe_latent_size is not None) and is_expert
810
+ self.hidden_size = config.hidden_size
811
+ input_size = self.hidden_size if not use_latent_size else config.moe_latent_size
812
+
813
+ self.intermediate_size = intermediate_size or config.intermediate_size
814
+ self.up_proj = nn.Linear(input_size, self.intermediate_size, bias=config.mlp_bias)
815
+ self.down_proj = nn.Linear(self.intermediate_size, input_size, bias=config.mlp_bias)
816
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
817
+
818
+ def forward(self, x):
819
+ return self.down_proj(self.act_fn(self.up_proj(x)))
820
+
821
+
822
+ class NemotronHMOE(nn.Module):
823
+ def __init__(self, config, layer_idx: Optional[int] = None):
824
+ super().__init__()
825
+ self.config = config
826
+ self.experts = nn.ModuleList(
827
+ [
828
+ NemotronHMLP(config, intermediate_size=config.moe_intermediate_size, layer_idx=layer_idx, is_expert=True)
829
+ for _ in range(config.n_routed_experts)
830
+ ]
831
+ )
832
+ self.gate = NemotronHTopkRouter(config)
833
+ self.shared_experts = NemotronHMLP(
834
+ config=config, intermediate_size=config.moe_shared_expert_intermediate_size, layer_idx=layer_idx, is_expert=False
835
+ )
836
+
837
+ if config.moe_latent_size is not None:
838
+ self.fc1_latent_proj = nn.Linear(config.hidden_size, config.moe_latent_size, bias=config.mlp_bias)
839
+ self.fc2_latent_proj = nn.Linear(config.moe_latent_size, config.hidden_size, bias=config.mlp_bias)
840
+ else:
841
+ self.fc1_latent_proj = nn.Identity()
842
+ self.fc2_latent_proj = nn.Identity()
843
+
844
+ def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
845
+ r"""
846
+ CALL FOR CONTRIBUTION! I don't have time to optimise this right now, but expert weights need to be fused
847
+ to not have to do a loop here (deepseek has 256 experts soooo yeah).
848
+ """
849
+ final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
850
+ expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts))
851
+ expert_mask = expert_mask.permute(2, 0, 1)
852
+
853
+ for expert_idx in range(len(self.experts)):
854
+ expert = self.experts[expert_idx]
855
+ mask = expert_mask[expert_idx]
856
+ token_indices, weight_indices = torch.where(mask)
857
+
858
+ if token_indices.numel() > 0:
859
+ expert_weights = topk_weights[token_indices, weight_indices]
860
+ expert_input = hidden_states[token_indices]
861
+ expert_output = expert(expert_input)
862
+ weighted_output = expert_output * expert_weights.unsqueeze(-1)
863
+ final_hidden_states.index_add_(0, token_indices, weighted_output)
864
+ else:
865
+ # Local empty expert: no-op compute that still marks params as used.
866
+ expert_dtype = expert.down_proj.weight.dtype
867
+ dummy_out = expert(torch.zeros_like(hidden_states[0]).unsqueeze(0).to(expert_dtype))
868
+ final_hidden_states = final_hidden_states + dummy_out
869
+
870
+
871
+ # in original deepseek, the output of the experts are gathered once we leave this module
872
+ # thus the moe module is itelsf an IsolatedParallel module
873
+ # and all expert are "local" meaning we shard but we don't gather
874
+ return final_hidden_states.type(hidden_states.dtype)
875
+
876
+ def forward(self, hidden_states):
877
+ residuals = hidden_states
878
+ orig_shape = hidden_states.shape
879
+ topk_indices, topk_weights = self.gate(hidden_states)
880
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
881
+
882
+ hidden_states = self.fc1_latent_proj(hidden_states)
883
+ hidden_states = self.moe(hidden_states, topk_indices, topk_weights)
884
+ hidden_states = self.fc2_latent_proj(hidden_states)
885
+
886
+ hidden_states = hidden_states.view(*orig_shape)
887
+
888
+ hidden_states = hidden_states + self.shared_experts(residuals)
889
+ return hidden_states
890
+
891
+
892
+ class NemotronHTopkRouter(nn.Module):
893
+ def __init__(self, config):
894
+ super().__init__()
895
+ self.config = config
896
+ self.top_k = config.num_experts_per_tok
897
+ self.n_routed_experts = config.n_routed_experts
898
+ self.routed_scaling_factor = config.routed_scaling_factor
899
+ self.n_group = config.n_group
900
+ self.topk_group = config.topk_group
901
+ self.norm_topk_prob = config.norm_topk_prob
902
+
903
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
904
+ self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts, dtype=torch.float32))
905
+
906
+ @torch.no_grad()
907
+ def get_topk_indices(self, scores):
908
+ scores_for_choice = scores.view(-1, self.n_routed_experts) + self.e_score_correction_bias.unsqueeze(0)
909
+ group_scores = (
910
+ scores_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
911
+ .topk(2, dim=-1)[0]
912
+ .sum(dim=-1)
913
+ )
914
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
915
+ group_mask = torch.zeros_like(group_scores)
916
+ group_mask.scatter_(1, group_idx, 1)
917
+ score_mask = (
918
+ group_mask.unsqueeze(-1)
919
+ .expand(-1, self.n_group, self.n_routed_experts // self.n_group)
920
+ .reshape(-1, self.n_routed_experts)
921
+ )
922
+ scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
923
+ topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
924
+ return topk_indices
925
+
926
+ def forward(self, hidden_states):
927
+ self._maintain_float32_expert_bias()
928
+
929
+ hidden_states = hidden_states.view(-1, self.config.hidden_size)
930
+ router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
931
+ scores = router_logits.sigmoid()
932
+ topk_indices = self.get_topk_indices(scores)
933
+ topk_weights = scores.gather(1, topk_indices)
934
+ if self.norm_topk_prob:
935
+ denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
936
+ topk_weights /= denominator
937
+ topk_weights = topk_weights * self.routed_scaling_factor
938
+ return topk_indices, topk_weights
939
+
940
+ def _maintain_float32_expert_bias(self):
941
+ if self.e_score_correction_bias.dtype != torch.float32:
942
+ self.e_score_correction_bias.data = self.e_score_correction_bias.data.to(torch.float32)
943
+
944
+
945
+ class NemotronHMultiTokenPredictorLayer(NemotronHBlock):
946
+ def __init__(self, config, layer_idx, is_first=False, is_last=False):
947
+ super().__init__(config, layer_idx)
948
+ self.is_first = is_first
949
+ self.is_last = is_last
950
+
951
+ if self.is_first:
952
+ self.eh_proj = nn.Linear(2*config.hidden_size, config.hidden_size, bias=config.mlp_bias)
953
+ self.enorm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
954
+ self.hnorm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
955
+
956
+ if self.is_last:
957
+ self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=config.mlp_bias)
958
+
959
+ def forward(self, x):
960
+ raise NotImplementedError("NemotronHMultiTokenPredictorLayer is not implemented in HuggingFace yet")
961
+
962
+
963
+ class NemotronHMultiTokenPredictor(nn.Module):
964
+ def __init__(self, config):
965
+ super().__init__()
966
+
967
+ config_mtp = copy.deepcopy(config)
968
+ config_mtp.hybrid_override_pattern = config.mtp_hybrid_override_pattern
969
+ config_mtp.num_hidden_layers = len(config_mtp.mtp_hybrid_override_pattern)
970
+
971
+ layers = []
972
+ for _ in range(config.num_nextn_predict_layers):
973
+ for layer_idx in range(config_mtp.num_hidden_layers):
974
+ is_first = (layer_idx == 0)
975
+ is_last = (layer_idx == config_mtp.num_hidden_layers - 1)
976
+ layers.append(
977
+ NemotronHMultiTokenPredictorLayer(
978
+ config=config_mtp,
979
+ layer_idx=layer_idx,
980
+ is_first=is_first,
981
+ is_last=is_last
982
+ )
983
+ )
984
+ self.layers = torch.nn.ModuleList(layers)
985
+
986
+ def forward(self, x):
987
+ raise NotImplementedError("NemotronHMultiTokenPredictor is not implemented in HuggingFace yet")
988
+
989
+
990
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
991
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
992
+ """
993
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
994
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
995
+ """
996
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
997
+ if n_rep == 1:
998
+ return hidden_states
999
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
1000
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
1001
+
1002
+
1003
+ class NemotronHAttention(nn.Module):
1004
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
1005
+
1006
+ def __init__(self, config: NemotronHConfig, layer_idx: Optional[int] = None):
1007
+ super().__init__()
1008
+ self.config = config
1009
+ self.layer_idx = layer_idx
1010
+ if layer_idx is None:
1011
+ logger.warning_once(
1012
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
1013
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
1014
+ "when creating this class."
1015
+ )
1016
+
1017
+ self.attention_dropout = config.attention_dropout
1018
+ self.hidden_size = config.hidden_size
1019
+ self.num_heads = config.num_attention_heads
1020
+ if config.head_dim is not None:
1021
+ self.head_dim = config.head_dim
1022
+ else:
1023
+ self.head_dim = config.hidden_size // config.num_attention_heads
1024
+ self.num_key_value_heads = config.num_key_value_heads
1025
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
1026
+ self.max_position_embeddings = config.max_position_embeddings
1027
+ self.is_causal = True
1028
+
1029
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
1030
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
1031
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
1032
+ self.o_proj = nn.Linear(self.head_dim * self.num_heads, self.hidden_size, bias=config.attention_bias)
1033
+
1034
+ def forward(
1035
+ self,
1036
+ hidden_states: torch.Tensor,
1037
+ # position_embeddings: Tuple[torch.Tensor, torch.Tensor], #TODO
1038
+ attention_mask: Optional[torch.Tensor] = None,
1039
+ position_ids: Optional[torch.LongTensor] = None,
1040
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
1041
+ output_attentions: bool = False,
1042
+ use_cache: bool = False,
1043
+ cache_position: Optional[torch.LongTensor] = None,
1044
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1045
+ bsz, q_len, _ = hidden_states.size()
1046
+
1047
+ query_states = self.q_proj(hidden_states)
1048
+ key_states = self.k_proj(hidden_states)
1049
+ value_states = self.v_proj(hidden_states)
1050
+
1051
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1052
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1053
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1054
+
1055
+ if past_key_value is not None:
1056
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
1057
+
1058
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1059
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1060
+
1061
+ causal_mask = attention_mask
1062
+ if attention_mask is not None: # no matter the length, we just slice it
1063
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
1064
+
1065
+ if query_states.device.type == "cuda" and attention_mask is not None:
1066
+ query_states = query_states.contiguous()
1067
+ key_states = key_states.contiguous()
1068
+ value_states = value_states.contiguous()
1069
+
1070
+ is_causal = True if causal_mask is None and q_len > 1 else False
1071
+
1072
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1073
+ query_states,
1074
+ key_states,
1075
+ value_states,
1076
+ attn_mask=causal_mask,
1077
+ dropout_p=self.attention_dropout if self.training else 0.0,
1078
+ is_causal=is_causal,
1079
+ )
1080
+ attn_output = attn_output.transpose(1, 2).contiguous()
1081
+ #attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1082
+ attn_output = attn_output.view(bsz, q_len, self.num_heads * self.head_dim)
1083
+
1084
+ attn_output = self.o_proj(attn_output)
1085
+
1086
+ return attn_output, None, past_key_value
1087
+
1088
+
1089
+ # Adapted from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Jamba
1090
+ #class JambaFlashAttention2(JambaAttention):
1091
+ class NemotronHFlashAttention2(NemotronHAttention):
1092
+ """
1093
+ Jamba flash attention module. This module inherits from `JambaAttention` as the weights of the module stays
1094
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
1095
+ flash attention and deal with padding tokens in case the input contains any of them.
1096
+ """
1097
+ def __init__(self, *args, **kwargs):
1098
+ super().__init__(*args, **kwargs)
1099
+
1100
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1101
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
1102
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
1103
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1104
+
1105
+ def forward(
1106
+ self,
1107
+ hidden_states: torch.Tensor,
1108
+ attention_mask: Optional[torch.Tensor] = None,
1109
+ position_ids: Optional[torch.LongTensor] = None,
1110
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
1111
+ output_attentions: bool = False,
1112
+ use_cache: bool = False,
1113
+ cache_position: Optional[torch.LongTensor] = None,
1114
+ **kwargs,
1115
+ ):
1116
+ bsz, q_len, _ = hidden_states.size()
1117
+
1118
+ query_states = self.q_proj(hidden_states)
1119
+ key_states = self.k_proj(hidden_states)
1120
+ value_states = self.v_proj(hidden_states)
1121
+
1122
+ # Flash attention requires the input to have the shape
1123
+ # batch_size x seq_length x head_dim x hidden_dim
1124
+ # therefore we just need to keep the original shape
1125
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
1126
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1127
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1128
+
1129
+ if past_key_value is not None:
1130
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
1131
+
1132
+ # repeat k/v heads if n_kv_heads < n_heads
1133
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1134
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1135
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
1136
+
1137
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1138
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1139
+ # cast them back in float16 just to be sure everything works as expected.
1140
+ input_dtype = query_states.dtype
1141
+ if input_dtype == torch.float32:
1142
+ if torch.is_autocast_enabled():
1143
+ target_dtype = torch.get_autocast_gpu_dtype()
1144
+ # Handle the case where the model is quantized
1145
+ elif hasattr(self.config, "_pre_quantization_dtype"):
1146
+ target_dtype = self.config._pre_quantization_dtype
1147
+ else:
1148
+ target_dtype = self.q_proj.weight.dtype
1149
+
1150
+ logger.warning_once(
1151
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1152
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1153
+ f" {target_dtype}."
1154
+ )
1155
+
1156
+ query_states = query_states.to(target_dtype)
1157
+ key_states = key_states.to(target_dtype)
1158
+ value_states = value_states.to(target_dtype)
1159
+
1160
+ # Reashape to the expected shape for Flash Attention
1161
+ key_states = key_states.transpose(1, 2)
1162
+ value_states = value_states.transpose(1, 2)
1163
+
1164
+ attn_output = _flash_attention_forward(
1165
+ query_states,
1166
+ key_states,
1167
+ value_states,
1168
+ attention_mask,
1169
+ q_len,
1170
+ dropout=dropout_rate,
1171
+ sliding_window=getattr(self.config, "sliding_window", None),
1172
+ is_causal=self.is_causal,
1173
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
1174
+ )
1175
+
1176
+ #attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
1177
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim).contiguous()
1178
+ attn_output = self.o_proj(attn_output)
1179
+
1180
+ if not output_attentions:
1181
+ attn_weights = None
1182
+
1183
+ return attn_output, attn_weights, past_key_value
1184
+
1185
+
1186
+ # Adapted from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Jamba
1187
+ #class JambaSdpaAttention(JambaAttention):
1188
+ class NemotronHSdpaAttention(NemotronHAttention):
1189
+ """
1190
+ Jamba attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1191
+ `JambaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1192
+ SDPA API.
1193
+ """
1194
+
1195
+ # Adapted from NemotronHAttention.forward
1196
+ def forward(
1197
+ self,
1198
+ hidden_states: torch.Tensor,
1199
+ attention_mask: Optional[torch.Tensor] = None,
1200
+ position_ids: Optional[torch.LongTensor] = None,
1201
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
1202
+ output_attentions: bool = False,
1203
+ use_cache: bool = False,
1204
+ cache_position: Optional[torch.LongTensor] = None,
1205
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1206
+ if output_attentions:
1207
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1208
+ logger.warning_once(
1209
+ "NemotronHModel is using NemotronHSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
1210
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
1211
+ )
1212
+ return super().forward(
1213
+ hidden_states=hidden_states,
1214
+ attention_mask=attention_mask,
1215
+ position_ids=position_ids,
1216
+ past_key_value=past_key_value,
1217
+ output_attentions=output_attentions,
1218
+ use_cache=use_cache,
1219
+ )
1220
+
1221
+ bsz, q_len, _ = hidden_states.size()
1222
+
1223
+ query_states = self.q_proj(hidden_states)
1224
+ key_states = self.k_proj(hidden_states)
1225
+ value_states = self.v_proj(hidden_states)
1226
+
1227
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1228
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1229
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1230
+
1231
+ if past_key_value is not None:
1232
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
1233
+
1234
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1235
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1236
+
1237
+ causal_mask = attention_mask
1238
+ if attention_mask is not None:
1239
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
1240
+
1241
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1242
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1243
+ if query_states.device.type == "cuda" and attention_mask is not None:
1244
+ query_states = query_states.contiguous()
1245
+ key_states = key_states.contiguous()
1246
+ value_states = value_states.contiguous()
1247
+
1248
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
1249
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
1250
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
1251
+ is_causal = True if self.is_causal and causal_mask is None and q_len > 1 else False
1252
+
1253
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1254
+ query_states,
1255
+ key_states,
1256
+ value_states,
1257
+ attn_mask=causal_mask,
1258
+ dropout_p=self.attention_dropout if self.training else 0.0,
1259
+ is_causal=is_causal,
1260
+ )
1261
+
1262
+ attn_output = attn_output.transpose(1, 2).contiguous()
1263
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1264
+
1265
+ attn_output = self.o_proj(attn_output)
1266
+
1267
+ return attn_output, None, past_key_value
1268
+
1269
+
1270
+ NEMOTRONH_ATTENTION_CLASSES = {
1271
+ "eager": NemotronHAttention,
1272
+ "flash_attention_2": NemotronHFlashAttention2,
1273
+ "sdpa": NemotronHSdpaAttention,
1274
+ }
1275
+
1276
+ # Copied from transformers.models.mamba.modeling_mamba2.Mamba2PreTrainedModel
1277
+ class NemotronHPreTrainedModel(PreTrainedModel):
1278
+ """
1279
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1280
+ models.
1281
+ """
1282
+
1283
+ config_class = NemotronHConfig
1284
+ base_model_prefix = "backbone"
1285
+ _no_split_modules = ["NemotronHBlock"]
1286
+ supports_gradient_checkpointing = True
1287
+ _is_stateful = True
1288
+
1289
+ def _init_weights(self, module):
1290
+ """Initialize the weights."""
1291
+ if isinstance(module, NemotronHMamba2Mixer):
1292
+ module.A_log._no_weight_decay = True
1293
+ module.D._no_weight_decay = True
1294
+
1295
+ dt = torch.exp(
1296
+ torch.rand(self.config.mamba_num_heads)
1297
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
1298
+ + math.log(self.config.time_step_min)
1299
+ ).clamp(min=self.config.time_step_floor)
1300
+
1301
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
1302
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
1303
+ with torch.no_grad():
1304
+ module.dt_bias.copy_(inv_dt)
1305
+ module.dt_bias._no_reinit = True
1306
+
1307
+ if isinstance(module, nn.Linear):
1308
+ if module.bias is not None:
1309
+ if not getattr(module.bias, "_no_reinit", False):
1310
+ nn.init.zeros_(module.bias)
1311
+ elif isinstance(module, nn.Embedding):
1312
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
1313
+
1314
+ # TODO: Check
1315
+ if self.config.rescale_prenorm_residual:
1316
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
1317
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
1318
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
1319
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
1320
+ #
1321
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
1322
+ for name, p in module.named_parameters():
1323
+ if name in ["out_proj.weight"]:
1324
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
1325
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
1326
+ # We need to reinit p since this code could be called multiple times
1327
+ # Having just p *= scale would repeatedly scale it down
1328
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
1329
+ with torch.no_grad():
1330
+ p /= math.sqrt(self.config.num_hidden_layers)
1331
+
1332
+
1333
+ @dataclass
1334
+ # Copied from transformers.models.mamba.modeling_mamba2.Mamba2Output with MAMBA2->NemotronH,Mamba2->NemotronH
1335
+ class NemotronHOutput(ModelOutput):
1336
+ """
1337
+ Class for the NemotronH model outputs.
1338
+
1339
+ Args:
1340
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1341
+ Sequence of hidden-states at the output of the last layer of the model.
1342
+ cache_params (`HybridMambaAttentionDynamicCache`):
1343
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
1344
+ avoid providing the old `input_ids`.
1345
+
1346
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
1347
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1348
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1349
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1350
+
1351
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1352
+ """
1353
+
1354
+ last_hidden_state: Optional[torch.FloatTensor] = None
1355
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None
1356
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1357
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1358
+
1359
+
1360
+ @dataclass
1361
+ # Copied from transformers.models.mamba2.modeling_mamba2.MambaCausalLMOutput with Mamba2->NemotronH
1362
+ class NemotronHCausalLMOutput(ModelOutput):
1363
+ """
1364
+ Base class for causal language model (or autoregressive) outputs.
1365
+
1366
+ Args:
1367
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1368
+ Language modeling loss (for next-token prediction).
1369
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1370
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1371
+ cache_params (`HybridMambaAttentionDynamicCache`):
1372
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
1373
+ avoid providing the old `input_ids`.
1374
+
1375
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
1376
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1377
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1378
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1379
+
1380
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1381
+ """
1382
+
1383
+ loss: Optional[torch.FloatTensor] = None
1384
+ logits: Optional[torch.FloatTensor] = None
1385
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None
1386
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1387
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1388
+
1389
+
1390
+ NEMOTRONH_START_DOCSTRING = r"""
1391
+
1392
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1393
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1394
+ etc.)
1395
+
1396
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1397
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1398
+ and behavior.
1399
+
1400
+ Parameters:
1401
+ config ([`NemotronHConfig`]): Model configuration class with all the parameters of the model.
1402
+ Initializing with a config file does not load the weights associated with the model, only the
1403
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1404
+ """
1405
+
1406
+ NEMOTRONH_INPUTS_DOCSTRING = r"""
1407
+ Args:
1408
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
1409
+ Indices of input sequence tokens in the vocabulary.
1410
+
1411
+ If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
1412
+ `input_ids`.
1413
+
1414
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1415
+ [`PreTrainedTokenizer.__call__`] for details.
1416
+
1417
+ [What are input IDs?](../glossary#input-ids)
1418
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1419
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1420
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1421
+ model's internal embedding lookup matrix.
1422
+ position_ids (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1423
+ Indices of positions of each input sequence tokens in the position embeddings.
1424
+ cache_params (`HybridMambaAttentionDynamicCache`, *optional*):
1425
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
1426
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
1427
+ use_cache (`bool`, *optional*):
1428
+ If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
1429
+ output_attentions (`bool`, *optional*):
1430
+ Whether or not to return the attentions tensors of all attention layers.
1431
+ output_hidden_states (`bool`, *optional*):
1432
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1433
+ more detail.
1434
+ return_dict (`bool`, *optional*):
1435
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1436
+ cache_position (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1437
+ The position of the current input in the cache. This is used to ensure that the cache is correctly updated.
1438
+ If `cache_params` is passed, `cache_position` should also be passed.
1439
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1440
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1441
+
1442
+ - 1 for tokens that are **not masked**,
1443
+ - 0 for tokens that are **masked**.
1444
+
1445
+ [What are attention masks?](../glossary#attention-mask)
1446
+ """
1447
+
1448
+
1449
+ @add_start_docstrings(
1450
+ "The bare NemotronH Model transformer outputting raw hidden-states without any specific head on top.",
1451
+ NEMOTRONH_START_DOCSTRING,
1452
+ )
1453
+ class NemotronHModel(NemotronHPreTrainedModel):
1454
+ def __init__(self, config):
1455
+ super().__init__(config)
1456
+
1457
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
1458
+ self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
1459
+
1460
+ self.gradient_checkpointing = False
1461
+ self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
1462
+ # Initialize weights and apply final processing
1463
+ self._register_load_state_dict_pre_hook(self.load_hook)
1464
+ self.post_init()
1465
+
1466
+ def load_hook(self, state_dict, prefix, *args):
1467
+ for k in state_dict:
1468
+ if "embedding." in k:
1469
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
1470
+ break
1471
+
1472
+ def get_input_embeddings(self):
1473
+ return self.embeddings
1474
+
1475
+ def set_input_embeddings(self, new_embeddings):
1476
+ self.embeddings = new_embeddings
1477
+
1478
+ @add_start_docstrings_to_model_forward(NEMOTRONH_INPUTS_DOCSTRING)
1479
+ @add_code_sample_docstrings(
1480
+ checkpoint=_CHECKPOINT_FOR_DOC,
1481
+ output_type=NemotronHOutput,
1482
+ config_class=_CONFIG_FOR_DOC,
1483
+ )
1484
+ def forward(
1485
+ self,
1486
+ input_ids: Optional[torch.LongTensor] = None,
1487
+ inputs_embeds: Optional[torch.LongTensor] = None,
1488
+ position_ids: Optional[torch.LongTensor] = None,
1489
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
1490
+ use_cache: Optional[bool] = None,
1491
+ output_attentions: Optional[bool] = None,
1492
+ output_hidden_states: Optional[bool] = None,
1493
+ return_dict: Optional[bool] = None,
1494
+ cache_position: Optional[torch.LongTensor] = None,
1495
+ attention_mask: Optional[torch.Tensor] = None,
1496
+ **kwargs,
1497
+ ) -> Union[Tuple, NemotronHOutput]:
1498
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1499
+ output_hidden_states = (
1500
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1501
+ )
1502
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
1503
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
1504
+
1505
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1506
+
1507
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
1508
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1509
+
1510
+ if inputs_embeds is None:
1511
+ inputs_embeds = self.embeddings(input_ids)
1512
+
1513
+ if self.gradient_checkpointing and self.training and use_cache:
1514
+ logger.warning_once(
1515
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1516
+ )
1517
+ use_cache = False
1518
+
1519
+ # From zamba_modeling.py
1520
+ if use_cache and cache_params is None:
1521
+ logger.warning_once(
1522
+ "NemotronH requires an initialized `NemotronHHybridDynamicCache` to return a cache. None was "
1523
+ "provided, so no cache will be returned."
1524
+ )
1525
+
1526
+ hidden_states = inputs_embeds
1527
+
1528
+ if cache_position is None:
1529
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
1530
+ if position_ids is None:
1531
+ position_ids = cache_position.unsqueeze(0)
1532
+
1533
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
1534
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
1535
+
1536
+ all_hidden_states = () if output_hidden_states else None
1537
+ all_self_attns = () if output_attentions else None
1538
+ # Until HERE
1539
+
1540
+ for layer_idx, mixer_block in enumerate(self.layers):
1541
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
1542
+ if mixer_block.block_type == "mamba":
1543
+ layer_mask = mamba_mask
1544
+ elif mixer_block.block_type == "attention":
1545
+ layer_mask = causal_mask
1546
+ elif mixer_block.block_type in ["mlp", "moe"]:
1547
+ layer_mask = None
1548
+ else:
1549
+ raise ValueError(f"Invalid block_type: {self.block_type}")
1550
+
1551
+ if output_hidden_states:
1552
+ all_hidden_states += (hidden_states,)
1553
+
1554
+ if self.gradient_checkpointing and self.training:
1555
+ hidden_states = self._gradient_checkpointing_func(
1556
+ mixer_block.__call__, hidden_states, cache_params, cache_position, layer_mask
1557
+ )
1558
+ else:
1559
+ hidden_states = mixer_block(
1560
+ hidden_states,
1561
+ cache_params=cache_params,
1562
+ cache_position=cache_position,
1563
+ attention_mask=layer_mask,
1564
+ )
1565
+
1566
+ # TODO: Store attentions
1567
+ # if output_attentions:
1568
+ # if layer_outputs[1] is not None:
1569
+ # # append attentions only of attention layers. Mamba layers return `None` as the attention weights
1570
+ # all_self_attns += (layer_outputs[1],)
1571
+
1572
+ # TODO (Check): should it happen before the forward pass?
1573
+ # if output_hidden_states:
1574
+ # all_hidden_states = all_hidden_states + (hidden_states,)
1575
+
1576
+ hidden_states = self.norm_f(hidden_states)
1577
+
1578
+ if output_hidden_states:
1579
+ all_hidden_states = all_hidden_states + (hidden_states,)
1580
+
1581
+ if not return_dict:
1582
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
1583
+
1584
+ return NemotronHOutput(
1585
+ last_hidden_state=hidden_states,
1586
+ cache_params=cache_params if use_cache else None,
1587
+ hidden_states=all_hidden_states,
1588
+ attentions=all_self_attns,
1589
+ )
1590
+
1591
+ # Copied from transformers.models.jamba.modeling_jamba.JambaModel._update_causal_mask
1592
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
1593
+ if self.config._attn_implementation == "flash_attention_2":
1594
+ if attention_mask is not None and 0.0 in attention_mask:
1595
+ return attention_mask
1596
+ return None
1597
+
1598
+ dtype, device = input_tensor.dtype, input_tensor.device
1599
+ min_dtype = torch.finfo(dtype).min
1600
+ sequence_length = input_tensor.shape[1]
1601
+ target_length = cache_position[-1] + 1
1602
+
1603
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
1604
+ if sequence_length != 1:
1605
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1606
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1607
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1608
+ if attention_mask is not None:
1609
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1610
+ if attention_mask.dim() == 2:
1611
+ mask_length = attention_mask.shape[-1]
1612
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1613
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1614
+
1615
+ if (
1616
+ self.config._attn_implementation == "sdpa"
1617
+ and attention_mask is not None
1618
+ and attention_mask.device.type == "cuda"
1619
+ ):
1620
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1621
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1622
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1623
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1624
+
1625
+ return causal_mask
1626
+
1627
+ def _update_mamba_mask(self, attention_mask, cache_position):
1628
+ """
1629
+ No need for zeroing states when
1630
+ 1. Cached forward
1631
+ 2. Attending to all inputs
1632
+ """
1633
+ mamba_mask = attention_mask
1634
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1635
+ mamba_mask = None
1636
+ return mamba_mask
1637
+
1638
+
1639
+ @add_start_docstrings(
1640
+ """
1641
+ The NEMOTRONH Model transformer with a language modeling head on top (linear layer with weights not tied to the input
1642
+ embeddings).
1643
+ """,
1644
+ NEMOTRONH_START_DOCSTRING,
1645
+ )
1646
+ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
1647
+ _tied_weights_keys = ["lm_head.weight"]
1648
+ _keys_to_ignore_on_load_missing = [r"mtp.*"]
1649
+
1650
+ def __init__(self, config):
1651
+ super().__init__(config)
1652
+ self.backbone = NemotronHModel(config)
1653
+ self.vocab_size = config.vocab_size
1654
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1655
+
1656
+ if config.num_nextn_predict_layers > 0:
1657
+ self.mtp = NemotronHMultiTokenPredictor(config)
1658
+
1659
+ # Initialize weights and apply final processing
1660
+ self.post_init()
1661
+
1662
+ def get_input_embeddings(self):
1663
+ return self.backbone.get_input_embeddings()
1664
+
1665
+ def set_input_embeddings(self, new_embeddings):
1666
+ return self.backbone.set_input_embeddings(new_embeddings)
1667
+
1668
+ def get_output_embeddings(self):
1669
+ return self.lm_head
1670
+
1671
+ def set_output_embeddings(self, new_embeddings):
1672
+ self.lm_head = new_embeddings
1673
+
1674
+ def get_decoder(self):
1675
+ return self.model
1676
+
1677
+ def set_decoder(self, decoder):
1678
+ self.model = decoder
1679
+
1680
+ def prepare_inputs_for_generation(
1681
+ self,
1682
+ input_ids,
1683
+ past_key_values=None,
1684
+ attention_mask=None,
1685
+ inputs_embeds=None,
1686
+ cache_position=None,
1687
+ position_ids=None,
1688
+ use_cache=True,
1689
+ **kwargs,
1690
+ ):
1691
+ # Copy from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
1692
+ # Overwitten -- uses `cache_params` as opposed to `past_key_values`
1693
+ empty_past_kv = past_key_values is None
1694
+
1695
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1696
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1697
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1698
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
1699
+ # (we can't check exception 3 while compiling)
1700
+ if not empty_past_kv:
1701
+ if (
1702
+ inputs_embeds is not None # Exception 1
1703
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
1704
+ ):
1705
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1706
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1707
+ input_ids = input_ids[:, cache_position]
1708
+ else:
1709
+ past_key_values = HybridMambaAttentionDynamicCache(
1710
+ self.config, input_ids.shape[0], self.dtype, device=self.device
1711
+ )
1712
+
1713
+ if attention_mask is not None and position_ids is None:
1714
+ # create position_ids on the fly for batch generation
1715
+ position_ids = attention_mask.long().cumsum(-1) - 1
1716
+ position_ids.masked_fill_(attention_mask == 0, 1)
1717
+ if not empty_past_kv:
1718
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1719
+
1720
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1721
+ if inputs_embeds is not None and empty_past_kv:
1722
+ model_inputs = {"inputs_embeds": inputs_embeds}
1723
+ else:
1724
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1725
+
1726
+ model_inputs.update(
1727
+ {
1728
+ "position_ids": position_ids,
1729
+ "past_key_values": past_key_values,
1730
+ "use_cache": use_cache,
1731
+ "attention_mask": attention_mask,
1732
+ "logits_to_keep": self.config.num_logits_to_keep,
1733
+ "cache_position": cache_position,
1734
+ }
1735
+ )
1736
+ return model_inputs
1737
+
1738
+ @add_start_docstrings_to_model_forward(NEMOTRONH_INPUTS_DOCSTRING)
1739
+ @add_code_sample_docstrings(
1740
+ checkpoint=_CHECKPOINT_FOR_DOC,
1741
+ output_type=NemotronHCausalLMOutput,
1742
+ config_class=_CONFIG_FOR_DOC,
1743
+ )
1744
+ def forward(
1745
+ self,
1746
+ input_ids: Optional[torch.LongTensor] = None,
1747
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1748
+ position_ids: Optional[torch.LongTensor] = None,
1749
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
1750
+ labels: Optional[torch.LongTensor] = None,
1751
+ output_attentions: Optional[bool] = None,
1752
+ output_hidden_states: Optional[bool] = None,
1753
+ return_dict: Optional[bool] = None,
1754
+ use_cache: Optional[bool] = None,
1755
+ cache_position: Optional[torch.Tensor] = None,
1756
+ attention_mask: Optional[torch.Tensor] = None,
1757
+ **kwargs, # for now we need this for generation
1758
+ ) -> Union[Tuple, NemotronHCausalLMOutput]:
1759
+ r"""
1760
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1761
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1762
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1763
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1764
+ """
1765
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1766
+
1767
+ output_hidden_states = (
1768
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1769
+ )
1770
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1771
+
1772
+ nemotron_h_outputs = self.backbone(
1773
+ input_ids,
1774
+ cache_params=cache_params,
1775
+ inputs_embeds=inputs_embeds,
1776
+ output_attentions=output_attentions,
1777
+ output_hidden_states=output_hidden_states,
1778
+ return_dict=return_dict,
1779
+ use_cache=use_cache,
1780
+ cache_position=cache_position,
1781
+ attention_mask=attention_mask,
1782
+ )
1783
+ hidden_states = nemotron_h_outputs[0]
1784
+
1785
+ # TODO: Check zamba_modeling.py: https://github.com/huggingface/transformers/blob/d7188ba600e36d3fd191b12e19f1b3bb81a8404f/src/transformers/models/zamba/modeling_zamba.py#L1284C1-L1286C2
1786
+ #logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1787
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1788
+
1789
+ loss = None
1790
+ if labels is not None:
1791
+ # move labels to correct device to enable model parallelism
1792
+ labels = labels.to(logits.device)
1793
+ # Shift so that tokens < n predict n
1794
+ shift_logits = logits[..., :-1, :].contiguous()
1795
+ shift_labels = labels[..., 1:].contiguous()
1796
+ # Flatten the tokens
1797
+ loss_fct = CrossEntropyLoss()
1798
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1799
+
1800
+ if not return_dict:
1801
+ output = (logits,) + nemotron_h_outputs[1:]
1802
+ return ((loss,) + output) if loss is not None else output
1803
+
1804
+ return NemotronHCausalLMOutput(
1805
+ loss=loss,
1806
+ logits=logits,
1807
+ cache_params=nemotron_h_outputs.cache_params,
1808
+ hidden_states=nemotron_h_outputs.hidden_states,
1809
+ attentions=nemotron_h_outputs.attentions,
1810
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|im_end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|im_end|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:623c34567aebb18582765289fbe23d901c62704d6518d71866e0e58db892b5b7
3
+ size 17077484
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff