yueqis commited on
Commit
4df9cda
·
verified ·
1 Parent(s): 75fcfd1

Upload modeling_nemotron_h.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_nemotron_h.py +1639 -0
modeling_nemotron_h.py ADDED
@@ -0,0 +1,1639 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
19
+ from dataclasses import dataclass
20
+ from typing import Any, Dict, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from transformers.activations import ACT2FN
28
+ from transformers.cache_utils import DynamicCache # we need __iter__ and __len__ of pkv
29
+ from transformers.generation import GenerationMixin
30
+ from transformers.modeling_attn_mask_utils import (
31
+ AttentionMaskConverter,
32
+ )
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (
35
+ ModelOutput,
36
+ add_code_sample_docstrings,
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ logging,
40
+ )
41
+ from transformers.utils.import_utils import (
42
+ is_causal_conv1d_available,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ is_mamba_2_ssm_available,
46
+ )
47
+ from .configuration_nemotron_h import NemotronHConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ # Copied from transformers.models.mamba.modeling_mamba2.modeling_mamba2.py with MAMBA2->NEMOTRONH,Mamba2->NemotronH
54
+ # For Mamba2 components Mamba2->NemotronHMamba2
55
+ if is_mamba_2_ssm_available():
56
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
57
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
58
+ else:
59
+ mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, selective_state_update = None, None, None
60
+
61
+ try:
62
+ #from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated
63
+ from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn
64
+ except ImportError:
65
+ raise ImportError("mamba-ssm is required by the Mamba model but cannot be imported")
66
+
67
+ if is_causal_conv1d_available():
68
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
69
+ else:
70
+ causal_conv1d_update, causal_conv1d_fn = None, None
71
+
72
+ if is_flash_attn_2_available():
73
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
74
+
75
+ is_fast_path_available = all(
76
+ (
77
+ selective_state_update,
78
+ mamba_chunk_scan_combined,
79
+ mamba_split_conv1d_scan_combined,
80
+ causal_conv1d_fn,
81
+ causal_conv1d_update,
82
+ )
83
+ )
84
+
85
+
86
+ _CHECKPOINT_FOR_DOC = "nvidia/Nemotron-H-56B-Base-8K"
87
+ _CONFIG_FOR_DOC = "NemotronHConfig"
88
+
89
+
90
+ # Helper methods for segment sum computation
91
+
92
+
93
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
94
+ """
95
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
96
+
97
+ Assumes that we only have tensors of either size 4 or 3
98
+ """
99
+ 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)
100
+
101
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
102
+
103
+
104
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
105
+ """
106
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
107
+ simultaneously splitting it into chunk sequences.
108
+
109
+ Assumes that we only have tensors of either size 4 or 3
110
+ """
111
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
112
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
113
+
114
+ if len(input_tensor.shape) == 3:
115
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
116
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
117
+ else:
118
+ # [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]
119
+ return input_tensor.reshape(
120
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
121
+ )
122
+
123
+
124
+ def segment_sum(input_tensor):
125
+ """
126
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
127
+ """
128
+ chunk_size = input_tensor.size(-1)
129
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
130
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
131
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
132
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
133
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
134
+ input_tensor = input_tensor.masked_fill(~mask, 0)
135
+ # 3. compute actual cumsum
136
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
137
+
138
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
139
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
140
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
141
+ return tensor_segsum
142
+
143
+
144
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
145
+ """
146
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
147
+ """
148
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
149
+ dtype = hidden_states.dtype
150
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
151
+
152
+ return hidden_states
153
+
154
+ # Copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
155
+ class HybridMambaAttentionDynamicCache(DynamicCache):
156
+ """
157
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
158
+ (which has a constant shape regardless of seq_len).
159
+
160
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
161
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
162
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
163
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
164
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
165
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
166
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
167
+ """
168
+
169
+ def __init__(self, config, batch_size, dtype=torch.float16, device=None):
170
+ super().__init__()
171
+ self.dtype = dtype
172
+ self.hybrid_override_pattern = config.hybrid_override_pattern
173
+ self.has_previous_state = False # only used by mamba
174
+ #intermediate_size = config.expand * config.hidden_size
175
+ intermediate_size = config.mamba_num_heads * config.mamba_head_dim
176
+ ssm_state_size = config.ssm_state_size
177
+ conv_kernel_size = config.conv_kernel
178
+ self.conv_states = []
179
+ self.ssm_states = []
180
+ self.transformer_layers = []
181
+ for i in range(config.num_hidden_layers):
182
+ if self.hybrid_override_pattern[i] == "M":
183
+ # Mamba layer
184
+ self.conv_states += [
185
+ torch.zeros(batch_size, intermediate_size, conv_kernel_size, device=device, dtype=dtype)
186
+ ]
187
+ self.ssm_states += [
188
+ torch.zeros(batch_size, intermediate_size, ssm_state_size, device=device, dtype=dtype)
189
+ ]
190
+ else:
191
+ # Attention or MLP layer
192
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
193
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
194
+ self.transformer_layers.append(i)
195
+
196
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
197
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
198
+
199
+ def update(
200
+ self,
201
+ key_states: torch.Tensor,
202
+ value_states: torch.Tensor,
203
+ layer_idx: int,
204
+ cache_kwargs: Optional[Dict[str, Any]] = None,
205
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
206
+ # Update the cache
207
+ if self.key_cache[layer_idx].shape[-1] == 0:
208
+ self.key_cache[layer_idx] = key_states
209
+ self.value_cache[layer_idx] = value_states
210
+ else:
211
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
212
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
213
+
214
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
215
+
216
+ def reorder_cache(self, beam_idx: torch.LongTensor):
217
+ """Reorders the cache for beam search, given the selected beam indices."""
218
+ for layer_idx in range(len(self.key_cache)):
219
+ device = self.key_cache[layer_idx].device
220
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
221
+ device = self.value_cache[layer_idx].device
222
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
223
+
224
+ device = self.conv_states[layer_idx].device
225
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
226
+ device = self.ssm_states[layer_idx].device
227
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
228
+
229
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
230
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
231
+ # take any layer that contains cache and not empty tensor
232
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
233
+ if len(self.key_cache) <= layer_idx:
234
+ return 0
235
+ return self.key_cache[layer_idx].shape[-2]
236
+
237
+ def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor], Tuple[torch.Tensor]]:
238
+ raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
239
+
240
+ @classmethod
241
+ def from_legacy_cache(cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None) -> "DynamicCache":
242
+ raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
243
+
244
+ # Copied from modeling_mamba2.py
245
+ def update_conv_state(
246
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_init: bool = False
247
+ ) -> torch.Tensor:
248
+ if cache_init:
249
+ self.conv_states[layer_idx] = new_conv_state.to(self.conv_states.device)
250
+ else:
251
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(shifts=-1, dims=-1)
252
+ self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(self.conv_states.device)
253
+ return self.conv_states[layer_idx]
254
+
255
+ def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
256
+ self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
257
+ return self.ssm_states[layer_idx]
258
+
259
+ def reset(self):
260
+ self.conv_states.zero_()
261
+ self.ssm_states.zero_()
262
+
263
+ class MambaRMSNormGated(torch.nn.Module):
264
+ def __init__(self, hidden_size, group_size, eps=1e-5):
265
+ super().__init__()
266
+ self.weight = nn.Parameter(torch.ones(hidden_size))
267
+ self.variance_epsilon = eps
268
+ self.group_size = group_size
269
+
270
+ # jan28b version
271
+ def forward(self, hidden_states, gate=None):
272
+ return rmsnorm_fn(x=hidden_states,
273
+ weight=self.weight,
274
+ bias=None, # No bias
275
+ z=gate,
276
+ eps=self.variance_epsilon,
277
+ group_size=self.group_size,
278
+ norm_before_gate=False
279
+ )
280
+
281
+ class NemotronHMamba2Mixer(nn.Module):
282
+ """
283
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
284
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
285
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
286
+ and is why Mamba is called **selective** state spaces)
287
+ """
288
+
289
+ def __init__(self, config: NemotronHConfig, layer_idx: int):
290
+ super().__init__()
291
+ self.num_heads = config.mamba_num_heads
292
+ self.hidden_size = config.hidden_size
293
+ self.ssm_state_size = config.ssm_state_size
294
+ self.conv_kernel_size = config.conv_kernel
295
+ self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
296
+ self.layer_idx = layer_idx
297
+ self.use_conv_bias = config.use_conv_bias
298
+ self.activation = config.mamba_hidden_act
299
+ self.act = ACT2FN[config.mamba_hidden_act]
300
+
301
+ self.layer_norm_epsilon = config.layer_norm_epsilon
302
+
303
+ self.n_groups = config.n_groups
304
+ self.head_dim = config.mamba_head_dim
305
+ self.chunk_size = config.chunk_size
306
+
307
+ self.time_step_limit = config.time_step_limit
308
+ self.time_step_min = config.time_step_min
309
+ self.time_step_max = config.time_step_max
310
+
311
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
312
+ self.conv1d = nn.Conv1d(
313
+ in_channels=self.conv_dim,
314
+ out_channels=self.conv_dim,
315
+ bias=config.use_conv_bias,
316
+ kernel_size=config.conv_kernel,
317
+ groups=self.conv_dim,
318
+ padding=config.conv_kernel - 1,
319
+ )
320
+
321
+ # projection of the input hidden states
322
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
323
+ self.in_proj = nn.Linear(
324
+ self.hidden_size,
325
+ projection_size,
326
+ bias=config.use_bias,
327
+ )
328
+ # selective projection used to make dt, B and C input dependant
329
+
330
+ # time step projection (discretization)
331
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
332
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
333
+
334
+ # S4D real initialization. These are not discretized!
335
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
336
+ A = torch.arange(1, self.num_heads + 1)
337
+ self.A_log = nn.Parameter(torch.log(A))
338
+ self.A_log._no_weight_decay = True
339
+ self.norm = MambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon, group_size=self.intermediate_size // self.n_groups)
340
+ self.D = nn.Parameter(torch.ones(self.num_heads))
341
+ self.D._no_weight_decay = True
342
+
343
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
344
+ self.use_bias = config.use_bias
345
+
346
+ if not is_fast_path_available:
347
+ logger.warning_once(
348
+ "The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
349
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
350
+ " https://github.com/Dao-AILab/causal-conv1d"
351
+ )
352
+
353
+ def cuda_kernels_forward(
354
+ self,
355
+ hidden_states: torch.Tensor,
356
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
357
+ cache_position: Optional[torch.LongTensor] = None,
358
+ attention_mask: Optional[torch.Tensor] = None,
359
+ ):
360
+ # 1. Gated MLP's linear projection
361
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
362
+ projected_states = self.in_proj(hidden_states)
363
+
364
+ # Set up dimensions for reshapes later
365
+ batch_size, seq_len, _ = hidden_states.shape
366
+ groups_time_state_size = self.n_groups * self.ssm_state_size
367
+ d_mlp = (
368
+ projected_states.shape[-1]
369
+ - 2 * self.intermediate_size
370
+ - 2 * self.n_groups * self.ssm_state_size
371
+ - self.num_heads
372
+ ) // 2
373
+
374
+ # Single step calculations via cache
375
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
376
+ _, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
377
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
378
+ )
379
+
380
+ # 2. Convolution sequence transformation
381
+ hidden_states_B_C = causal_conv1d_update(
382
+ hidden_states_B_C,
383
+ cache_params.conv_states[self.layer_idx],
384
+ self.conv1d.weight.squeeze(1),
385
+ self.conv1d.bias,
386
+ self.activation,
387
+ )
388
+
389
+ hidden_states, B, C = torch.split(
390
+ hidden_states_B_C,
391
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
392
+ dim=-1,
393
+ )
394
+
395
+ # 3. SSM transformation
396
+ A = -torch.exp(self.A_log.float()) # (nheads,)
397
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
398
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
399
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
400
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
401
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
402
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
403
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
404
+ hidden_states = selective_state_update(
405
+ cache_params.ssm_states[self.layer_idx],
406
+ hidden_states_reshaped,
407
+ dt,
408
+ A,
409
+ B,
410
+ C,
411
+ D,
412
+ z=None,
413
+ dt_bias=dt_bias,
414
+ dt_softplus=True,
415
+ )
416
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
417
+ hidden_states = self.norm(hidden_states, gate)
418
+
419
+ # 4. Final linear projection
420
+ out = self.out_proj(hidden_states)[:, None, ...]
421
+
422
+ # Fused calculations or step by step if no initialized cache is found
423
+ else:
424
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
425
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
426
+
427
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
428
+ if self.training and cache_params is None:
429
+ out = mamba_split_conv1d_scan_combined(
430
+ projected_states,
431
+ self.conv1d.weight.squeeze(1),
432
+ self.conv1d.bias,
433
+ self.dt_bias,
434
+ A,
435
+ D=self.D,
436
+ chunk_size=self.chunk_size,
437
+ seq_idx=None, # was seq_idx
438
+ activation=self.activation,
439
+ rmsnorm_weight=self.norm.weight,
440
+ rmsnorm_eps=self.norm.variance_epsilon,
441
+ outproj_weight=self.out_proj.weight,
442
+ outproj_bias=self.out_proj.bias,
443
+ headdim=self.head_dim,
444
+ ngroups=self.n_groups,
445
+ norm_before_gate=False,
446
+ return_final_states=False,
447
+ **dt_limit_kwargs,
448
+ )
449
+
450
+ else:
451
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
452
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
453
+ )
454
+
455
+ # 2. Convolution sequence transformation
456
+ # Init cache
457
+ if cache_params is not None:
458
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
459
+ conv_states = nn.functional.pad(
460
+ hidden_states_B_C_transposed,
461
+ (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
462
+ )
463
+ cache_params.update_conv_state(
464
+ layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
465
+ )
466
+
467
+ if self.activation not in ["silu", "swish"]:
468
+ hidden_states_B_C = self.act(
469
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
470
+ )
471
+ else:
472
+ hidden_states_B_C = causal_conv1d_fn(
473
+ x=hidden_states_B_C.transpose(1, 2),
474
+ weight=self.conv1d.weight.squeeze(1),
475
+ bias=self.conv1d.bias,
476
+ activation=self.activation,
477
+ ).transpose(1, 2)
478
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
479
+ hidden_states, B, C = torch.split(
480
+ hidden_states_B_C,
481
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
482
+ dim=-1,
483
+ )
484
+
485
+ # 3. SSM transformation
486
+ scan_output, ssm_state = mamba_chunk_scan_combined(
487
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
488
+ dt,
489
+ A,
490
+ B.view(batch_size, seq_len, self.n_groups, -1),
491
+ C.view(batch_size, seq_len, self.n_groups, -1),
492
+ chunk_size=self.chunk_size,
493
+ D=self.D,
494
+ z=None,
495
+ seq_idx=None,
496
+ return_final_states=True,
497
+ dt_bias=self.dt_bias,
498
+ dt_softplus=True,
499
+ **dt_limit_kwargs,
500
+ )
501
+
502
+ # Init cache
503
+ if ssm_state is not None and cache_params is not None:
504
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
505
+
506
+ scan_output = scan_output.view(batch_size, seq_len, -1)
507
+
508
+ # Multiply "gate" branch and apply extra normalization layer
509
+ scan_output = self.norm(scan_output, gate)
510
+
511
+ # 4. Final linear projection
512
+ out = self.out_proj(scan_output)
513
+ return out
514
+
515
+ # fmt: off
516
+ def torch_forward(self, input_states, cache_params: Optional[HybridMambaAttentionDynamicCache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None):
517
+ batch_size, seq_len, _ = input_states.shape
518
+ dtype = input_states.dtype
519
+
520
+ # 1. Gated MLP's linear projection
521
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
522
+ projected_states = self.in_proj(input_states)
523
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size-self.num_heads) // 2
524
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
525
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
526
+ )
527
+
528
+ # 2. Convolution sequence transformation
529
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
530
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
531
+
532
+ # We need to guarantee that anything regarding the cache is on the same device
533
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
534
+
535
+ hidden_states_B_C = torch.sum(
536
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
537
+ )
538
+ if self.use_conv_bias:
539
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
540
+ hidden_states_B_C = self.act(hidden_states_B_C)
541
+ else:
542
+ # Init cache
543
+ if cache_params is not None:
544
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
545
+ conv_states = nn.functional.pad(
546
+ hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
547
+ )
548
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
549
+
550
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
551
+
552
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
553
+ hidden_states, B, C = torch.split(
554
+ hidden_states_B_C,
555
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
556
+ dim=-1
557
+ )
558
+
559
+ # 3. SSM transformation
560
+ A = -torch.exp(self.A_log.float()) # [num_heads]
561
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
562
+ # We need to guarantee that anything regarding the cache is on the same device
563
+ cache_device = cache_params.ssm_states.device
564
+
565
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
566
+ # for batched generation
567
+ dt = dt[:, 0, :][:, None, ...]
568
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
569
+ # [num_heads] -> [num_heads, head_dim]
570
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
571
+
572
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
573
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
574
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
575
+ # [bsz, num_heads, head_dim, state_size]
576
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
577
+
578
+ # Discretize B
579
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
580
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
581
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
582
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
583
+ B = B.reshape(batch_size, -1, B.shape[-1])
584
+ # [bsz, num_heads, head_dim, state_size]
585
+ dB = dt[..., None] * B[..., None, :]
586
+
587
+ # Discretize x into dB
588
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
589
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
590
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
591
+
592
+ # State calculation
593
+ cache_params.update_ssm_state(
594
+ layer_idx=self.layer_idx,
595
+ new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
596
+ )
597
+
598
+ # Subsequent output
599
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
600
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
601
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
602
+ C = C.reshape(batch_size, -1, C.shape[-1])
603
+ # [bsz, num_heads, head_dim]
604
+
605
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
606
+ # Reshape ssm_states to merge the first two dimensions
607
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
608
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
609
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
610
+ y = y.view(batch_size, self.num_heads, self.head_dim)
611
+
612
+ # D skip connection
613
+ # [num_heads] -> [num_heads, head_dim]
614
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
615
+ y = (y + hidden_states * D).to(y.dtype)
616
+
617
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
618
+ y = y.reshape(batch_size, -1)[:, None, ...]
619
+ else:
620
+ # begin ssd naive implementation without einsums
621
+ dt = nn.functional.softplus(dt + self.dt_bias)
622
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
623
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
624
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
625
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
626
+ B = B.repeat(1, 1, self.num_heads // self.n_groups, 1)
627
+ C = C.repeat(1, 1, self.num_heads // self.n_groups, 1)
628
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
629
+
630
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
631
+
632
+ # Discretize x and A
633
+ hidden_states = hidden_states * dt[..., None]
634
+ A = A.to(hidden_states.dtype) * dt
635
+
636
+ # Rearrange into blocks/chunks
637
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
638
+
639
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
640
+ A = A.permute(0, 3, 1, 2)
641
+ A_cumsum = torch.cumsum(A, dim=-1)
642
+
643
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
644
+ # This is the analog of a causal mask
645
+ L = torch.exp(segment_sum(A))
646
+
647
+ # Contraction of C and B to get G (attention-weights like)
648
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
649
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
650
+
651
+ # Compute M, equivalent to applying attention mask to weights
652
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
653
+ M = M_intermediate.sum(dim=-1)
654
+
655
+ # Compute Y_diag (apply to values)
656
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
657
+
658
+ # 2. Compute the state for each intra-chunk
659
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
660
+ decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
661
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
662
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
663
+
664
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
665
+ # (middle term of factorization of off-diag blocks; A terms)
666
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
667
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
668
+ else:
669
+ previous_states = torch.zeros_like(states[:, :1])
670
+ states = torch.cat([previous_states, states], dim=1)
671
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
672
+ decay_chunk = decay_chunk.transpose(1, 3)
673
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
674
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
675
+
676
+ # 4. Compute state -> output conversion per chunk
677
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
678
+ state_decay_out = torch.exp(A_cumsum)
679
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
680
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
681
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
682
+
683
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
684
+ y = Y_diag + Y_off
685
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
686
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
687
+
688
+ y = y + D_residual
689
+ # Cutting off padded chunks
690
+ if pad_size > 0:
691
+ y = y[:, :seq_len, :, :]
692
+ y = y.reshape(batch_size, seq_len, -1)
693
+
694
+ # Init cache
695
+ if ssm_state is not None and cache_params is not None:
696
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
697
+
698
+ scan_output = self.norm(y, gate)
699
+
700
+ # end ssd naive
701
+
702
+ # 4. Final linear projection
703
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
704
+ return contextualized_states
705
+ # fmt: on
706
+
707
+ def forward(
708
+ self,
709
+ hidden_states,
710
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
711
+ cache_position: Optional[torch.LongTensor] = None,
712
+ attention_mask: Optional[torch.Tensor] = None,
713
+ ):
714
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
715
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
716
+ dtype = hidden_states.dtype
717
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
718
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
719
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
720
+
721
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
722
+
723
+
724
+ class NemotronHRMSNorm(nn.Module):
725
+ def __init__(self, hidden_size, eps=1e-6):
726
+ """
727
+ NemotronHRMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
728
+ """
729
+ super().__init__()
730
+ self.weight = nn.Parameter(torch.ones(hidden_size))
731
+ self.variance_epsilon = eps
732
+
733
+ def forward(self, hidden_states):
734
+ input_dtype = hidden_states.dtype
735
+ hidden_states = hidden_states.to(torch.float32)
736
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
737
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
738
+ # Weights are in float32
739
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
740
+
741
+ class NemotronHBlock(nn.Module):
742
+ def __init__(self, config, layer_idx):
743
+ super().__init__()
744
+ self.config = config
745
+ self.layer_idx = layer_idx
746
+ self.residual_in_fp32 = config.residual_in_fp32
747
+ self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
748
+
749
+ # M: Mamba2, *: Attention, -: MLP
750
+ self.block_type = config.layers_block_type[layer_idx]
751
+ if self.block_type == "mamba":
752
+ self.mixer = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
753
+ elif self.block_type == "attention":
754
+ self.mixer = NEMOTRONH_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
755
+ elif self.block_type == "mlp":
756
+ self.mixer = NemotronHMLP(config, layer_idx=layer_idx)
757
+ else:
758
+ raise ValueError(f"Invalid layer pattern {config.hybrid_override_pattern[layer_idx]}")
759
+
760
+ def forward(
761
+ self,
762
+ hidden_states,
763
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
764
+ cache_position: Optional[torch.LongTensor] = None,
765
+ attention_mask: Optional[torch.Tensor] = None,
766
+ ):
767
+ with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
768
+ # * Use torch.cuda.stream() to avoid NaN issues when using multiple GPUs
769
+ residual = hidden_states
770
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
771
+ if self.residual_in_fp32:
772
+ residual = residual.to(torch.float32)
773
+
774
+ if self.block_type == "mamba":
775
+ hidden_states = self.mixer(
776
+ hidden_states, cache_params=cache_params, cache_position=cache_position
777
+ )
778
+ elif self.block_type == "attention":
779
+ hidden_states = self.mixer(
780
+ hidden_states, cache_position=cache_position
781
+ )
782
+ hidden_states = hidden_states[0]
783
+ elif self.block_type == "mlp":
784
+ hidden_states = self.mixer(
785
+ hidden_states
786
+ )
787
+ else:
788
+ raise ValueError(f"Invalid block_type: {self.block_type}")
789
+
790
+ hidden_states = residual + hidden_states
791
+ return hidden_states
792
+
793
+
794
+ # Copied from transformers.models.nemotron.modeling_nemotron Nemotron->NemotronH
795
+ class NemotronHMLP(nn.Module):
796
+ def __init__(self, config, layer_idx: Optional[int] = None):
797
+ super().__init__()
798
+ self.config = config
799
+ self.layer_idx = layer_idx
800
+ if layer_idx is None:
801
+ logger.warning_once(
802
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
803
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
804
+ "when creating this class."
805
+ )
806
+ self.hidden_size = config.hidden_size
807
+ #intermediate_size = config.expand * config.hidden_size
808
+ self.intermediate_size = config.intermediate_size
809
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
810
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
811
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
812
+
813
+ def forward(self, x):
814
+ return self.down_proj(self.act_fn(self.up_proj(x)))
815
+
816
+
817
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
818
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
819
+ """
820
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
821
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
822
+ """
823
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
824
+ if n_rep == 1:
825
+ return hidden_states
826
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
827
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
828
+
829
+
830
+ class NemotronHAttention(nn.Module):
831
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
832
+
833
+ def __init__(self, config: NemotronHConfig, layer_idx: Optional[int] = None):
834
+ super().__init__()
835
+ self.config = config
836
+ self.layer_idx = layer_idx
837
+ if layer_idx is None:
838
+ logger.warning_once(
839
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
840
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
841
+ "when creating this class."
842
+ )
843
+
844
+ self.attention_dropout = config.attention_dropout
845
+ self.hidden_size = config.hidden_size
846
+ self.num_heads = config.num_attention_heads
847
+ if config.head_dim is not None:
848
+ self.head_dim = config.head_dim
849
+ else:
850
+ self.head_dim = config.hidden_size // config.num_attention_heads
851
+ self.num_key_value_heads = config.num_key_value_heads
852
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
853
+ self.max_position_embeddings = config.max_position_embeddings
854
+ self.is_causal = True
855
+
856
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
857
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
858
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
859
+ self.o_proj = nn.Linear(self.head_dim * self.num_heads, self.hidden_size, bias=config.attention_bias)
860
+
861
+ def forward(
862
+ self,
863
+ hidden_states: torch.Tensor,
864
+ # position_embeddings: Tuple[torch.Tensor, torch.Tensor], #TODO
865
+ attention_mask: Optional[torch.Tensor] = None,
866
+ position_ids: Optional[torch.LongTensor] = None,
867
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
868
+ output_attentions: bool = False,
869
+ use_cache: bool = False,
870
+ cache_position: Optional[torch.LongTensor] = None,
871
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
872
+ bsz, q_len, _ = hidden_states.size()
873
+
874
+ query_states = self.q_proj(hidden_states)
875
+ key_states = self.k_proj(hidden_states)
876
+ value_states = self.v_proj(hidden_states)
877
+
878
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
879
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
880
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
881
+
882
+ if past_key_value is not None:
883
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
884
+
885
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
886
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
887
+
888
+ causal_mask = attention_mask
889
+ if attention_mask is not None: # no matter the length, we just slice it
890
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
891
+
892
+ if query_states.device.type == "cuda" and attention_mask is not None:
893
+ query_states = query_states.contiguous()
894
+ key_states = key_states.contiguous()
895
+ value_states = value_states.contiguous()
896
+
897
+ is_causal = True if causal_mask is None and q_len > 1 else False
898
+
899
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
900
+ query_states,
901
+ key_states,
902
+ value_states,
903
+ attn_mask=causal_mask,
904
+ dropout_p=self.attention_dropout if self.training else 0.0,
905
+ is_causal=is_causal,
906
+ )
907
+ attn_output = attn_output.transpose(1, 2).contiguous()
908
+ #attn_output = attn_output.view(bsz, q_len, self.hidden_size)
909
+ attn_output = attn_output.view(bsz, q_len, self.num_heads * self.head_dim)
910
+
911
+ attn_output = self.o_proj(attn_output)
912
+
913
+ return attn_output, None, past_key_value
914
+
915
+
916
+ # Adapted from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Jamba
917
+ #class JambaFlashAttention2(JambaAttention):
918
+ class NemotronHFlashAttention2(NemotronHAttention):
919
+ """
920
+ Jamba flash attention module. This module inherits from `JambaAttention` as the weights of the module stays
921
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
922
+ flash attention and deal with padding tokens in case the input contains any of them.
923
+ """
924
+ def __init__(self, *args, **kwargs):
925
+ super().__init__(*args, **kwargs)
926
+
927
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
928
+ # 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.
929
+ # 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).
930
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
931
+
932
+ def forward(
933
+ self,
934
+ hidden_states: torch.Tensor,
935
+ attention_mask: Optional[torch.Tensor] = None,
936
+ position_ids: Optional[torch.LongTensor] = None,
937
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
938
+ output_attentions: bool = False,
939
+ use_cache: bool = False,
940
+ cache_position: Optional[torch.LongTensor] = None,
941
+ **kwargs,
942
+ ):
943
+ bsz, q_len, _ = hidden_states.size()
944
+
945
+ query_states = self.q_proj(hidden_states)
946
+ key_states = self.k_proj(hidden_states)
947
+ value_states = self.v_proj(hidden_states)
948
+
949
+ # Flash attention requires the input to have the shape
950
+ # batch_size x seq_length x head_dim x hidden_dim
951
+ # therefore we just need to keep the original shape
952
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
953
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
954
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
955
+
956
+ if past_key_value is not None:
957
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
958
+
959
+ # repeat k/v heads if n_kv_heads < n_heads
960
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
961
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
962
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
963
+
964
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
965
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
966
+ # cast them back in float16 just to be sure everything works as expected.
967
+ input_dtype = query_states.dtype
968
+ if input_dtype == torch.float32:
969
+ if torch.is_autocast_enabled():
970
+ target_dtype = torch.get_autocast_gpu_dtype()
971
+ # Handle the case where the model is quantized
972
+ elif hasattr(self.config, "_pre_quantization_dtype"):
973
+ target_dtype = self.config._pre_quantization_dtype
974
+ else:
975
+ target_dtype = self.q_proj.weight.dtype
976
+
977
+ logger.warning_once(
978
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
979
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
980
+ f" {target_dtype}."
981
+ )
982
+
983
+ query_states = query_states.to(target_dtype)
984
+ key_states = key_states.to(target_dtype)
985
+ value_states = value_states.to(target_dtype)
986
+
987
+ # Reashape to the expected shape for Flash Attention
988
+ key_states = key_states.transpose(1, 2)
989
+ value_states = value_states.transpose(1, 2)
990
+
991
+ attn_output = _flash_attention_forward(
992
+ query_states,
993
+ key_states,
994
+ value_states,
995
+ attention_mask,
996
+ q_len,
997
+ dropout=dropout_rate,
998
+ sliding_window=getattr(self.config, "sliding_window", None),
999
+ is_causal=self.is_causal,
1000
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
1001
+ )
1002
+
1003
+ #attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
1004
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim).contiguous()
1005
+ attn_output = self.o_proj(attn_output)
1006
+
1007
+ if not output_attentions:
1008
+ attn_weights = None
1009
+
1010
+ return attn_output, attn_weights, past_key_value
1011
+
1012
+
1013
+ # Adapted from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Jamba
1014
+ #class JambaSdpaAttention(JambaAttention):
1015
+ class NemotronHSdpaAttention(NemotronHAttention):
1016
+ """
1017
+ Jamba attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1018
+ `JambaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1019
+ SDPA API.
1020
+ """
1021
+
1022
+ # Adapted from NemotronHAttention.forward
1023
+ def forward(
1024
+ self,
1025
+ hidden_states: torch.Tensor,
1026
+ attention_mask: Optional[torch.Tensor] = None,
1027
+ position_ids: Optional[torch.LongTensor] = None,
1028
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
1029
+ output_attentions: bool = False,
1030
+ use_cache: bool = False,
1031
+ cache_position: Optional[torch.LongTensor] = None,
1032
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1033
+ if output_attentions:
1034
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1035
+ logger.warning_once(
1036
+ "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, "
1037
+ '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.'
1038
+ )
1039
+ return super().forward(
1040
+ hidden_states=hidden_states,
1041
+ attention_mask=attention_mask,
1042
+ position_ids=position_ids,
1043
+ past_key_value=past_key_value,
1044
+ output_attentions=output_attentions,
1045
+ use_cache=use_cache,
1046
+ )
1047
+
1048
+ bsz, q_len, _ = hidden_states.size()
1049
+
1050
+ query_states = self.q_proj(hidden_states)
1051
+ key_states = self.k_proj(hidden_states)
1052
+ value_states = self.v_proj(hidden_states)
1053
+
1054
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1055
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1056
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1057
+
1058
+ if past_key_value is not None:
1059
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
1060
+
1061
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1062
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1063
+
1064
+ causal_mask = attention_mask
1065
+ if attention_mask is not None:
1066
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
1067
+
1068
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1069
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1070
+ if query_states.device.type == "cuda" and attention_mask is not None:
1071
+ query_states = query_states.contiguous()
1072
+ key_states = key_states.contiguous()
1073
+ value_states = value_states.contiguous()
1074
+
1075
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
1076
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
1077
+ # 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.
1078
+ is_causal = True if self.is_causal and causal_mask is None and q_len > 1 else False
1079
+
1080
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1081
+ query_states,
1082
+ key_states,
1083
+ value_states,
1084
+ attn_mask=causal_mask,
1085
+ dropout_p=self.attention_dropout if self.training else 0.0,
1086
+ is_causal=is_causal,
1087
+ )
1088
+
1089
+ attn_output = attn_output.transpose(1, 2).contiguous()
1090
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1091
+
1092
+ attn_output = self.o_proj(attn_output)
1093
+
1094
+ return attn_output, None, past_key_value
1095
+
1096
+
1097
+ NEMOTRONH_ATTENTION_CLASSES = {
1098
+ "eager": NemotronHAttention,
1099
+ "flash_attention_2": NemotronHFlashAttention2,
1100
+ "sdpa": NemotronHSdpaAttention,
1101
+ }
1102
+
1103
+ # Copied from transformers.models.mamba.modeling_mamba2.Mamba2PreTrainedModel
1104
+ class NemotronHPreTrainedModel(PreTrainedModel):
1105
+ """
1106
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1107
+ models.
1108
+ """
1109
+
1110
+ config_class = NemotronHConfig
1111
+ base_model_prefix = "backbone"
1112
+ _no_split_modules = ["NemotronHBlock"]
1113
+ supports_gradient_checkpointing = True
1114
+ _is_stateful = True
1115
+ _supports_flash_attn_2 = True
1116
+
1117
+ def _init_weights(self, module):
1118
+ """Initialize the weights."""
1119
+ if isinstance(module, NemotronHMamba2Mixer):
1120
+ module.A_log._no_weight_decay = True
1121
+ module.D._no_weight_decay = True
1122
+
1123
+ dt = torch.exp(
1124
+ torch.rand(self.config.mamba_num_heads)
1125
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
1126
+ + math.log(self.config.time_step_min)
1127
+ ).clamp(min=self.config.time_step_floor)
1128
+
1129
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
1130
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
1131
+ with torch.no_grad():
1132
+ module.dt_bias.copy_(inv_dt)
1133
+ module.dt_bias._no_reinit = True
1134
+
1135
+ if isinstance(module, nn.Linear):
1136
+ if module.bias is not None:
1137
+ if not getattr(module.bias, "_no_reinit", False):
1138
+ nn.init.zeros_(module.bias)
1139
+ elif isinstance(module, nn.Embedding):
1140
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
1141
+
1142
+ # TODO: Check
1143
+ if self.config.rescale_prenorm_residual:
1144
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
1145
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
1146
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
1147
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
1148
+ #
1149
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
1150
+ for name, p in module.named_parameters():
1151
+ if name in ["out_proj.weight"]:
1152
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
1153
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
1154
+ # We need to reinit p since this code could be called multiple times
1155
+ # Having just p *= scale would repeatedly scale it down
1156
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
1157
+ with torch.no_grad():
1158
+ p /= math.sqrt(self.config.num_hidden_layers)
1159
+
1160
+
1161
+ @dataclass
1162
+ # Copied from transformers.models.mamba.modeling_mamba2.Mamba2Output with MAMBA2->NemotronH,Mamba2->NemotronH
1163
+ class NemotronHOutput(ModelOutput):
1164
+ """
1165
+ Class for the NemotronH model outputs.
1166
+
1167
+ Args:
1168
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1169
+ Sequence of hidden-states at the output of the last layer of the model.
1170
+ cache_params (`HybridMambaAttentionDynamicCache`):
1171
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
1172
+ avoid providing the old `input_ids`.
1173
+
1174
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
1175
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1176
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1177
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1178
+
1179
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1180
+ """
1181
+
1182
+ last_hidden_state: Optional[torch.FloatTensor] = None
1183
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None
1184
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1185
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1186
+
1187
+
1188
+ @dataclass
1189
+ # Copied from transformers.models.mamba2.modeling_mamba2.MambaCausalLMOutput with Mamba2->NemotronH
1190
+ class NemotronHCausalLMOutput(ModelOutput):
1191
+ """
1192
+ Base class for causal language model (or autoregressive) outputs.
1193
+
1194
+ Args:
1195
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1196
+ Language modeling loss (for next-token prediction).
1197
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1198
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1199
+ cache_params (`HybridMambaAttentionDynamicCache`):
1200
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
1201
+ avoid providing the old `input_ids`.
1202
+
1203
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
1204
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1205
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1206
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1207
+
1208
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1209
+ """
1210
+
1211
+ loss: Optional[torch.FloatTensor] = None
1212
+ logits: Optional[torch.FloatTensor] = None
1213
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None
1214
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1215
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1216
+
1217
+
1218
+ NEMOTRONH_START_DOCSTRING = r"""
1219
+
1220
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1221
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1222
+ etc.)
1223
+
1224
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1225
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1226
+ and behavior.
1227
+
1228
+ Parameters:
1229
+ config ([`NemotronHConfig`]): Model configuration class with all the parameters of the model.
1230
+ Initializing with a config file does not load the weights associated with the model, only the
1231
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1232
+ """
1233
+
1234
+ NEMOTRONH_INPUTS_DOCSTRING = r"""
1235
+ Args:
1236
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
1237
+ Indices of input sequence tokens in the vocabulary.
1238
+
1239
+ If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
1240
+ `input_ids`.
1241
+
1242
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1243
+ [`PreTrainedTokenizer.__call__`] for details.
1244
+
1245
+ [What are input IDs?](../glossary#input-ids)
1246
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1247
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1248
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1249
+ model's internal embedding lookup matrix.
1250
+ position_ids (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1251
+ Indices of positions of each input sequence tokens in the position embeddings.
1252
+ cache_params (`HybridMambaAttentionDynamicCache`, *optional*):
1253
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
1254
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
1255
+ use_cache (`bool`, *optional*):
1256
+ If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
1257
+ output_attentions (`bool`, *optional*):
1258
+ Whether or not to return the attentions tensors of all attention layers.
1259
+ output_hidden_states (`bool`, *optional*):
1260
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1261
+ more detail.
1262
+ return_dict (`bool`, *optional*):
1263
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1264
+ cache_position (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1265
+ The position of the current input in the cache. This is used to ensure that the cache is correctly updated.
1266
+ If `cache_params` is passed, `cache_position` should also be passed.
1267
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1268
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1269
+
1270
+ - 1 for tokens that are **not masked**,
1271
+ - 0 for tokens that are **masked**.
1272
+
1273
+ [What are attention masks?](../glossary#attention-mask)
1274
+ """
1275
+
1276
+
1277
+ @add_start_docstrings(
1278
+ "The bare NemotronH Model transformer outputting raw hidden-states without any specific head on top.",
1279
+ NEMOTRONH_START_DOCSTRING,
1280
+ )
1281
+ class NemotronHModel(NemotronHPreTrainedModel):
1282
+ def __init__(self, config):
1283
+ super().__init__(config)
1284
+
1285
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
1286
+ self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
1287
+
1288
+ self.gradient_checkpointing = False
1289
+ self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
1290
+ # Initialize weights and apply final processing
1291
+ self._register_load_state_dict_pre_hook(self.load_hook)
1292
+ self.post_init()
1293
+
1294
+ def load_hook(self, state_dict, prefix, *args):
1295
+ for k in state_dict:
1296
+ if "embedding." in k:
1297
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
1298
+ break
1299
+
1300
+ def get_input_embeddings(self):
1301
+ return self.embeddings
1302
+
1303
+ def set_input_embeddings(self, new_embeddings):
1304
+ self.embeddings = new_embeddings
1305
+
1306
+ @add_start_docstrings_to_model_forward(NEMOTRONH_INPUTS_DOCSTRING)
1307
+ @add_code_sample_docstrings(
1308
+ checkpoint=_CHECKPOINT_FOR_DOC,
1309
+ output_type=NemotronHOutput,
1310
+ config_class=_CONFIG_FOR_DOC,
1311
+ )
1312
+ def forward(
1313
+ self,
1314
+ input_ids: Optional[torch.LongTensor] = None,
1315
+ inputs_embeds: Optional[torch.LongTensor] = None,
1316
+ position_ids: Optional[torch.LongTensor] = None,
1317
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
1318
+ use_cache: Optional[bool] = None,
1319
+ output_attentions: Optional[bool] = None,
1320
+ output_hidden_states: Optional[bool] = None,
1321
+ return_dict: Optional[bool] = None,
1322
+ cache_position: Optional[torch.LongTensor] = None,
1323
+ attention_mask: Optional[torch.Tensor] = None,
1324
+ **kwargs,
1325
+ ) -> Union[Tuple, NemotronHOutput]:
1326
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1327
+ output_hidden_states = (
1328
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1329
+ )
1330
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
1331
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
1332
+
1333
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1334
+
1335
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
1336
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1337
+
1338
+ if inputs_embeds is None:
1339
+ inputs_embeds = self.embeddings(input_ids)
1340
+
1341
+ if self.gradient_checkpointing and self.training and use_cache:
1342
+ logger.warning_once(
1343
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1344
+ )
1345
+ use_cache = False
1346
+
1347
+ # From zamba_modeling.py
1348
+ if use_cache and cache_params is None:
1349
+ logger.warning_once(
1350
+ "NemotronH requires an initialized `NemotronHHybridDynamicCache` to return a cache. None was "
1351
+ "provided, so no cache will be returned."
1352
+ )
1353
+
1354
+ hidden_states = inputs_embeds
1355
+
1356
+ if cache_position is None:
1357
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
1358
+ if position_ids is None:
1359
+ position_ids = cache_position.unsqueeze(0)
1360
+
1361
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
1362
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
1363
+
1364
+ all_hidden_states = () if output_hidden_states else None
1365
+ all_self_attns = () if output_attentions else None
1366
+ # Until HERE
1367
+
1368
+ for layer_idx, mixer_block in enumerate(self.layers):
1369
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
1370
+ if mixer_block.block_type == "mamba":
1371
+ layer_mask = mamba_mask
1372
+ elif mixer_block.block_type == "attention":
1373
+ layer_mask = causal_mask
1374
+ elif mixer_block.block_type == "mlp":
1375
+ layer_mask = None
1376
+ else:
1377
+ raise ValueError(f"Invalid block_type: {self.block_type}")
1378
+
1379
+ if output_hidden_states:
1380
+ all_hidden_states += (hidden_states,)
1381
+
1382
+ if self.gradient_checkpointing and self.training:
1383
+ hidden_states = self._gradient_checkpointing_func(
1384
+ mixer_block.__call__, hidden_states, cache_params, cache_position, layer_mask
1385
+ )
1386
+ else:
1387
+ hidden_states = mixer_block(
1388
+ hidden_states,
1389
+ cache_params=cache_params,
1390
+ cache_position=cache_position,
1391
+ attention_mask=layer_mask,
1392
+ )
1393
+
1394
+ # TODO: Store attentions
1395
+ # if output_attentions:
1396
+ # if layer_outputs[1] is not None:
1397
+ # # append attentions only of attention layers. Mamba layers return `None` as the attention weights
1398
+ # all_self_attns += (layer_outputs[1],)
1399
+
1400
+ # TODO (Check): should it happen before the forward pass?
1401
+ # if output_hidden_states:
1402
+ # all_hidden_states = all_hidden_states + (hidden_states,)
1403
+
1404
+ hidden_states = self.norm_f(hidden_states)
1405
+
1406
+ if output_hidden_states:
1407
+ all_hidden_states = all_hidden_states + (hidden_states,)
1408
+
1409
+ if not return_dict:
1410
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
1411
+
1412
+ return NemotronHOutput(
1413
+ last_hidden_state=hidden_states,
1414
+ cache_params=cache_params if use_cache else None,
1415
+ hidden_states=all_hidden_states,
1416
+ attentions=all_self_attns,
1417
+ )
1418
+
1419
+ # Copied from transformers.models.jamba.modeling_jamba.JambaModel._update_causal_mask
1420
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
1421
+ if self.config._attn_implementation == "flash_attention_2":
1422
+ if attention_mask is not None and 0.0 in attention_mask:
1423
+ return attention_mask
1424
+ return None
1425
+
1426
+ dtype, device = input_tensor.dtype, input_tensor.device
1427
+ min_dtype = torch.finfo(dtype).min
1428
+ sequence_length = input_tensor.shape[1]
1429
+ target_length = cache_position[-1] + 1
1430
+
1431
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
1432
+ if sequence_length != 1:
1433
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1434
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1435
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1436
+ if attention_mask is not None:
1437
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1438
+ if attention_mask.dim() == 2:
1439
+ mask_length = attention_mask.shape[-1]
1440
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1441
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1442
+
1443
+ if (
1444
+ self.config._attn_implementation == "sdpa"
1445
+ and attention_mask is not None
1446
+ and attention_mask.device.type == "cuda"
1447
+ ):
1448
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1449
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1450
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1451
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1452
+
1453
+ return causal_mask
1454
+
1455
+ def _update_mamba_mask(self, attention_mask, cache_position):
1456
+ """
1457
+ No need for zeroing states when
1458
+ 1. Cached forward
1459
+ 2. Attending to all inputs
1460
+ """
1461
+ mamba_mask = attention_mask
1462
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1463
+ mamba_mask = None
1464
+ return mamba_mask
1465
+
1466
+
1467
+ @add_start_docstrings(
1468
+ """
1469
+ The NEMOTRONH Model transformer with a language modeling head on top (linear layer with weights not tied to the input
1470
+ embeddings).
1471
+ """,
1472
+ NEMOTRONH_START_DOCSTRING,
1473
+ )
1474
+ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
1475
+ _tied_weights_keys = ["lm_head.weight"]
1476
+
1477
+ def __init__(self, config):
1478
+ super().__init__(config)
1479
+ self.backbone = NemotronHModel(config)
1480
+ self.vocab_size = config.vocab_size
1481
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1482
+
1483
+ # Initialize weights and apply final processing
1484
+ self.post_init()
1485
+
1486
+ def get_input_embeddings(self):
1487
+ return self.backbone.get_input_embeddings()
1488
+
1489
+ def set_input_embeddings(self, new_embeddings):
1490
+ return self.backbone.set_input_embeddings(new_embeddings)
1491
+
1492
+ def get_output_embeddings(self):
1493
+ return self.lm_head
1494
+
1495
+ def set_output_embeddings(self, new_embeddings):
1496
+ self.lm_head = new_embeddings
1497
+
1498
+ def get_decoder(self):
1499
+ return self.model
1500
+
1501
+ def set_decoder(self, decoder):
1502
+ self.model = decoder
1503
+
1504
+ def prepare_inputs_for_generation(
1505
+ self,
1506
+ input_ids,
1507
+ past_key_values=None,
1508
+ attention_mask=None,
1509
+ inputs_embeds=None,
1510
+ cache_position=None,
1511
+ position_ids=None,
1512
+ use_cache=True,
1513
+ **kwargs,
1514
+ ):
1515
+ # Copy from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
1516
+ # Overwitten -- uses `cache_params` as opposed to `past_key_values`
1517
+ empty_past_kv = past_key_values is None
1518
+
1519
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1520
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1521
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1522
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
1523
+ # (we can't check exception 3 while compiling)
1524
+ if not empty_past_kv:
1525
+ if (
1526
+ inputs_embeds is not None # Exception 1
1527
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
1528
+ ):
1529
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1530
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1531
+ input_ids = input_ids[:, cache_position]
1532
+ else:
1533
+ past_key_values = HybridMambaAttentionDynamicCache(
1534
+ self.config, input_ids.shape[0], self.dtype, device=self.device
1535
+ )
1536
+
1537
+ if attention_mask is not None and position_ids is None:
1538
+ # create position_ids on the fly for batch generation
1539
+ position_ids = attention_mask.long().cumsum(-1) - 1
1540
+ position_ids.masked_fill_(attention_mask == 0, 1)
1541
+ if not empty_past_kv:
1542
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1543
+
1544
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1545
+ if inputs_embeds is not None and empty_past_kv:
1546
+ # TODO(pjin): workaround fix for properly extending inputs_embeds;
1547
+ # longer term, may be better handled elsewhere in .generate().
1548
+ if input_ids is not None and inputs_embeds.shape[1] < input_ids.shape[1]:
1549
+ new_token_embeds = self.get_input_embeddings()(input_ids[:,inputs_embeds.shape[1]:])
1550
+ inputs_embeds = torch.cat([inputs_embeds, new_token_embeds], dim=1)
1551
+ model_inputs = {"inputs_embeds": inputs_embeds}
1552
+ else:
1553
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1554
+
1555
+ model_inputs.update(
1556
+ {
1557
+ "position_ids": position_ids,
1558
+ "past_key_values": past_key_values,
1559
+ "use_cache": use_cache,
1560
+ "attention_mask": attention_mask,
1561
+ "logits_to_keep": self.config.num_logits_to_keep,
1562
+ "cache_position": cache_position,
1563
+ }
1564
+ )
1565
+ return model_inputs
1566
+
1567
+ @add_start_docstrings_to_model_forward(NEMOTRONH_INPUTS_DOCSTRING)
1568
+ @add_code_sample_docstrings(
1569
+ checkpoint=_CHECKPOINT_FOR_DOC,
1570
+ output_type=NemotronHCausalLMOutput,
1571
+ config_class=_CONFIG_FOR_DOC,
1572
+ )
1573
+ def forward(
1574
+ self,
1575
+ input_ids: Optional[torch.LongTensor] = None,
1576
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1577
+ position_ids: Optional[torch.LongTensor] = None,
1578
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
1579
+ labels: Optional[torch.LongTensor] = None,
1580
+ output_attentions: Optional[bool] = None,
1581
+ output_hidden_states: Optional[bool] = None,
1582
+ return_dict: Optional[bool] = None,
1583
+ use_cache: Optional[bool] = None,
1584
+ cache_position: Optional[torch.Tensor] = None,
1585
+ attention_mask: Optional[torch.Tensor] = None,
1586
+ **kwargs, # for now we need this for generation
1587
+ ) -> Union[Tuple, NemotronHCausalLMOutput]:
1588
+ r"""
1589
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1590
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1591
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1592
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1593
+ """
1594
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1595
+
1596
+ output_hidden_states = (
1597
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1598
+ )
1599
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1600
+
1601
+ nemotron_h_outputs = self.backbone(
1602
+ input_ids,
1603
+ cache_params=cache_params,
1604
+ inputs_embeds=inputs_embeds,
1605
+ output_attentions=output_attentions,
1606
+ output_hidden_states=output_hidden_states,
1607
+ return_dict=return_dict,
1608
+ use_cache=use_cache,
1609
+ cache_position=cache_position,
1610
+ attention_mask=attention_mask,
1611
+ )
1612
+ hidden_states = nemotron_h_outputs[0]
1613
+
1614
+ # TODO: Check zamba_modeling.py: https://github.com/huggingface/transformers/blob/d7188ba600e36d3fd191b12e19f1b3bb81a8404f/src/transformers/models/zamba/modeling_zamba.py#L1284C1-L1286C2
1615
+ #logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1616
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1617
+
1618
+ loss = None
1619
+ if labels is not None:
1620
+ # move labels to correct device to enable model parallelism
1621
+ labels = labels.to(logits.device)
1622
+ # Shift so that tokens < n predict n
1623
+ shift_logits = logits[..., :-1, :].contiguous()
1624
+ shift_labels = labels[..., 1:].contiguous()
1625
+ # Flatten the tokens
1626
+ loss_fct = CrossEntropyLoss()
1627
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1628
+
1629
+ if not return_dict:
1630
+ output = (logits,) + nemotron_h_outputs[1:]
1631
+ return ((loss,) + output) if loss is not None else output
1632
+
1633
+ return NemotronHCausalLMOutput(
1634
+ loss=loss,
1635
+ logits=logits,
1636
+ cache_params=nemotron_h_outputs.cache_params,
1637
+ hidden_states=nemotron_h_outputs.hidden_states,
1638
+ attentions=nemotron_h_outputs.attentions,
1639
+ )