Prompt48 commited on
Commit
030afd5
·
verified ·
1 Parent(s): f8e10fc

Upload edit\Qwen3-TTS-test\.venv\Lib\site-packages\transformers\models\granitemoehybrid\modeling_granitemoehybrid.py with huggingface_hub

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//granitemoehybrid//modeling_granitemoehybrid.py ADDED
@@ -0,0 +1,1841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/granitemoehybrid/modular_granitemoehybrid.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_granitemoehybrid.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2025 IBM and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Any, Callable, Optional, TypedDict, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ from torch import nn
27
+
28
+ from transformers.activations import ACT2FN
29
+
30
+ from ...cache_utils import Cache
31
+ from ...generation import GenerationMixin
32
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
33
+ from ...modeling_layers import GradientCheckpointingLayer
34
+ from ...modeling_outputs import BaseModelOutputWithPast, MoeCausalLMOutputWithPast, MoeModelOutputWithPast
35
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
36
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
+ from ...processing_utils import Unpack
38
+ from ...utils import auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
39
+ from ...utils.deprecation import deprecate_kwarg
40
+ from ...utils.import_utils import is_causal_conv1d_available, is_mamba_2_ssm_available
41
+ from .configuration_granitemoehybrid import GraniteMoeHybridConfig
42
+
43
+
44
+ if is_mamba_2_ssm_available():
45
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
46
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
47
+ else:
48
+ selective_state_update = None
49
+
50
+ if is_causal_conv1d_available():
51
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
52
+ else:
53
+ causal_conv1d_update, causal_conv1d_fn = None, None
54
+
55
+
56
+ if is_torch_flex_attn_available():
57
+ from torch.nn.attention.flex_attention import BlockMask
58
+
59
+ from ...integrations.flex_attention import make_flex_block_causal_mask
60
+
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+
65
+ def rotate_half(x):
66
+ """Rotates half the hidden dims of the input."""
67
+ x1 = x[..., : x.shape[-1] // 2]
68
+ x2 = x[..., x.shape[-1] // 2 :]
69
+ return torch.cat((-x2, x1), dim=-1)
70
+
71
+
72
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
73
+ """Applies Rotary Position Embedding to the query and key tensors.
74
+
75
+ Args:
76
+ q (`torch.Tensor`): The query tensor.
77
+ k (`torch.Tensor`): The key tensor.
78
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
79
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
80
+ position_ids (`torch.Tensor`, *optional*):
81
+ Deprecated and unused.
82
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
83
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
84
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
85
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
86
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
87
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
88
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
89
+ Returns:
90
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
91
+ """
92
+ cos = cos.unsqueeze(unsqueeze_dim)
93
+ sin = sin.unsqueeze(unsqueeze_dim)
94
+ q_embed = (q * cos) + (rotate_half(q) * sin)
95
+ k_embed = (k * cos) + (rotate_half(k) * sin)
96
+ return q_embed, k_embed
97
+
98
+
99
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
100
+ """
101
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
102
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
103
+ """
104
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
105
+ if n_rep == 1:
106
+ return hidden_states
107
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
108
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
109
+
110
+
111
+ def eager_attention_forward(
112
+ module: nn.Module,
113
+ query: torch.Tensor,
114
+ key: torch.Tensor,
115
+ value: torch.Tensor,
116
+ attention_mask: Optional[torch.Tensor],
117
+ scaling: float,
118
+ dropout: float = 0.0,
119
+ **kwargs,
120
+ ):
121
+ key_states = repeat_kv(key, module.num_key_value_groups)
122
+ value_states = repeat_kv(value, module.num_key_value_groups)
123
+
124
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
125
+ if attention_mask is not None:
126
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
127
+ attn_weights = attn_weights + causal_mask
128
+
129
+ # upcast attention to fp32
130
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
131
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
132
+ attn_output = torch.matmul(attn_weights, value_states)
133
+ attn_output = attn_output.transpose(1, 2).contiguous()
134
+
135
+ return attn_output, attn_weights
136
+
137
+
138
+ # copied from transformers.models.granite.modeling_granite.GraniteAttention with Granite->GraniteMoeHybrid
139
+ # no longer copied after attention refactors
140
+ class GraniteMoeHybridAttention(nn.Module):
141
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
142
+
143
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
144
+ super().__init__()
145
+ self.config = config
146
+ self.layer_idx = layer_idx
147
+ if layer_idx is None:
148
+ logger.warning_once(
149
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
150
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
151
+ "when creating this class."
152
+ )
153
+
154
+ self.attention_dropout = config.attention_dropout
155
+ self.hidden_size = config.hidden_size
156
+ self.num_heads = config.num_attention_heads
157
+ self.head_dim = self.hidden_size // self.num_heads
158
+ self.num_key_value_heads = config.num_key_value_heads
159
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
160
+ self.is_causal = True
161
+
162
+ self.scaling = config.attention_multiplier
163
+
164
+ if (self.head_dim * self.num_heads) != self.hidden_size:
165
+ raise ValueError(
166
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
167
+ f" and `num_heads`: {self.num_heads})."
168
+ )
169
+
170
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
171
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
172
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
173
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
174
+
175
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
176
+ def forward(
177
+ self,
178
+ hidden_states: torch.Tensor,
179
+ attention_mask: Optional[torch.Tensor] = None,
180
+ position_ids: Optional[torch.LongTensor] = None,
181
+ past_key_values: Optional[Cache] = None,
182
+ use_cache: bool = False,
183
+ cache_position: Optional[torch.LongTensor] = None,
184
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # None or rope embeddings
185
+ **kwargs,
186
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
187
+ bsz, q_len, _ = hidden_states.size()
188
+
189
+ query_states = self.q_proj(hidden_states)
190
+ key_states = self.k_proj(hidden_states)
191
+ value_states = self.v_proj(hidden_states)
192
+
193
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
194
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
195
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
196
+
197
+ cos, sin = position_embeddings if position_embeddings is not None else (None, None)
198
+ if position_embeddings is not None:
199
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
200
+
201
+ if past_key_values is not None:
202
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
203
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
204
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
205
+
206
+ attention_interface: Callable = eager_attention_forward
207
+ if self.config._attn_implementation != "eager":
208
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
209
+
210
+ attn_output, attn_weights = attention_interface(
211
+ self,
212
+ query_states,
213
+ key_states,
214
+ value_states,
215
+ attention_mask,
216
+ dropout=0.0 if not self.training else self.attention_dropout,
217
+ scaling=self.scaling,
218
+ **kwargs,
219
+ )
220
+
221
+ attn_output = attn_output.view(bsz, q_len, -1)
222
+ attn_output = self.o_proj(attn_output)
223
+
224
+ return attn_output, attn_weights
225
+
226
+
227
+ class HybridMambaAttentionDynamicCache:
228
+ """
229
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
230
+ (which has a constant shape regardless of seq_len).
231
+
232
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
233
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
234
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
235
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
236
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
237
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
238
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
239
+ """
240
+
241
+ is_compileable = False
242
+
243
+ def __init__(self, config: GraniteMoeHybridConfig, batch_size, dtype=torch.float16, device=None):
244
+ self.layers_block_type = config.layers_block_type
245
+ self.has_previous_state = False # only used by mamba
246
+ conv_kernel_size = config.mamba_d_conv
247
+ ssm_state_size = config.mamba_d_state
248
+
249
+ self.conv_states = []
250
+ self.ssm_states = []
251
+ self.transformer_layers = []
252
+ for i in range(config.num_hidden_layers):
253
+ if self.layers_block_type[i] == "mamba":
254
+ self.conv_states += [
255
+ torch.zeros(
256
+ batch_size,
257
+ (config.mamba_expand * config.hidden_size + 2 * config.mamba_n_groups * ssm_state_size),
258
+ conv_kernel_size,
259
+ device=device,
260
+ dtype=dtype,
261
+ )
262
+ ]
263
+ self.ssm_states += [
264
+ torch.zeros(
265
+ batch_size,
266
+ config.mamba_n_heads,
267
+ config.mamba_d_head,
268
+ ssm_state_size,
269
+ device=device,
270
+ dtype=dtype,
271
+ )
272
+ ]
273
+ else:
274
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
275
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
276
+ self.transformer_layers.append(i)
277
+
278
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
279
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
280
+
281
+ def update(
282
+ self,
283
+ key_states: torch.Tensor,
284
+ value_states: torch.Tensor,
285
+ layer_idx: int,
286
+ cache_kwargs: Optional[dict[str, Any]] = None,
287
+ ) -> tuple[torch.Tensor, torch.Tensor]:
288
+ # Update the cache
289
+ if self.key_cache[layer_idx].shape[-1] == 0:
290
+ self.key_cache[layer_idx] = key_states
291
+ self.value_cache[layer_idx] = value_states
292
+ else:
293
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
294
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
295
+
296
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
297
+
298
+ def reorder_cache(self, beam_idx: torch.LongTensor):
299
+ """Reorders the cache for beam search, given the selected beam indices."""
300
+ for layer_idx in range(len(self.key_cache)):
301
+ device = self.key_cache[layer_idx].device
302
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
303
+ device = self.value_cache[layer_idx].device
304
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
305
+
306
+ device = self.conv_states[layer_idx].device
307
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
308
+ device = self.ssm_states[layer_idx].device
309
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
310
+
311
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
312
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
313
+ # take any layer that contains cache and not empty tensor
314
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
315
+ if len(self.key_cache) <= layer_idx:
316
+ return 0
317
+ return self.key_cache[layer_idx].shape[-2]
318
+
319
+
320
+ # Helper methods for segment sum computation
321
+
322
+
323
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
324
+ """
325
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
326
+
327
+ Assumes that we only have tensors of either size 4 or 3
328
+ """
329
+ 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)
330
+
331
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
332
+
333
+
334
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
335
+ """
336
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
337
+ simultaneously splitting it into chunk sequences.
338
+
339
+ Assumes that we only have tensors of either size 4 or 3
340
+ """
341
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
342
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
343
+
344
+ if len(input_tensor.shape) == 3:
345
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
346
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
347
+ else:
348
+ # [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]
349
+ return input_tensor.reshape(
350
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
351
+ )
352
+
353
+
354
+ def segment_sum(input_tensor):
355
+ """
356
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
357
+ """
358
+ chunk_size = input_tensor.size(-1)
359
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
360
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
361
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
362
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
363
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
364
+ input_tensor = input_tensor.masked_fill(~mask, 0)
365
+ # 3. compute actual cumsum
366
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
367
+
368
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
369
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
370
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
371
+ return tensor_segsum
372
+
373
+
374
+ is_fast_path_available = all((selective_state_update, causal_conv1d_fn, causal_conv1d_update))
375
+
376
+
377
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
378
+ """
379
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
380
+ """
381
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
382
+ dtype = hidden_states.dtype
383
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
384
+
385
+ return hidden_states
386
+
387
+
388
+ # Adapted from transformers.models.mamba2.modeling_mamba2.Mamba2Mixer
389
+ class GraniteMoeHybridMambaLayer(nn.Module):
390
+ """
391
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
392
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
393
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
394
+ and is why Mamba is called **selective** state spaces)
395
+
396
+ The are a few differences between this and Mamba2Mixer:
397
+ - The variable use_precomputed_states is slightly different due to the hybrid cache structure
398
+ - There's a few non-obvious bugs fixed with batching in the slow path that exist in main
399
+ - Some extra variables that our layer doesn't need have been removed
400
+ - We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged
401
+ """
402
+
403
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
404
+ super().__init__()
405
+ self.num_heads = config.mamba_n_heads
406
+ self.hidden_size = config.hidden_size
407
+ self.ssm_state_size = config.mamba_d_state
408
+ self.conv_kernel_size = config.mamba_d_conv
409
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
410
+ self.layer_idx = layer_idx
411
+ self.use_conv_bias = config.mamba_conv_bias
412
+ self.activation = config.hidden_act
413
+ self.act = ACT2FN[config.hidden_act]
414
+ self.use_bias = config.mamba_proj_bias
415
+
416
+ self.layer_norm_epsilon = config.rms_norm_eps
417
+
418
+ self.n_groups = config.mamba_n_groups
419
+ self.head_dim = config.mamba_d_head
420
+ self.chunk_size = config.mamba_chunk_size
421
+
422
+ # FIXME:
423
+ self.time_step_limit = (0.0, float("inf"))
424
+ self.time_step_min = 0.001
425
+ self.time_step_max = 0.1
426
+
427
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
428
+ self.conv1d = nn.Conv1d(
429
+ in_channels=self.conv_dim,
430
+ out_channels=self.conv_dim,
431
+ bias=config.mamba_conv_bias,
432
+ kernel_size=self.conv_kernel_size,
433
+ groups=self.conv_dim,
434
+ padding=self.conv_kernel_size - 1,
435
+ )
436
+
437
+ # projection of the input hidden states
438
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
439
+ self.in_proj = nn.Linear(
440
+ self.hidden_size,
441
+ projection_size,
442
+ bias=self.use_bias,
443
+ )
444
+ # selective projection used to make dt, B and C input dependent
445
+
446
+ # time step projection (discretization)
447
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
448
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
449
+
450
+ # S4D real initialization. These are not discretized!
451
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
452
+ A = torch.arange(1, self.num_heads + 1)
453
+ self.A_log = nn.Parameter(torch.log(A))
454
+ self.norm = GraniteMoeHybridRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon)
455
+ self.D = nn.Parameter(torch.ones(self.num_heads))
456
+
457
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
458
+
459
+ if not is_fast_path_available:
460
+ logger.warning_once(
461
+ "The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
462
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
463
+ " https://github.com/Dao-AILab/causal-conv1d"
464
+ )
465
+ else:
466
+ logger.warning_once("The fast path for GraniteMoeHybrid will be used when running the model on a GPU")
467
+
468
+ def cuda_kernels_forward(
469
+ self,
470
+ hidden_states: torch.Tensor,
471
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
472
+ cache_position: Optional[torch.LongTensor] = None,
473
+ attention_mask: Optional[torch.Tensor] = None,
474
+ seq_idx: Optional[torch.IntTensor] = None,
475
+ ):
476
+ # 1. Gated MLP's linear projection
477
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
478
+ projected_states = self.in_proj(hidden_states)
479
+
480
+ # Set up dimensions for reshapes later
481
+ batch_size, seq_len, _ = hidden_states.shape
482
+ groups_time_state_size = self.n_groups * self.ssm_state_size
483
+
484
+ use_precomputed_states = (
485
+ cache_params is not None
486
+ and cache_params.has_previous_state
487
+ and seq_len == 1
488
+ and cache_params.conv_states[self.layer_idx].shape[0]
489
+ == cache_params.ssm_states[self.layer_idx].shape[0]
490
+ == batch_size
491
+ and cache_position is not None
492
+ and cache_position[0] > 0
493
+ )
494
+
495
+ # getting projected states from cache if it exists
496
+ if use_precomputed_states:
497
+ gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
498
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
499
+ )
500
+
501
+ # 2. Convolution sequence transformation
502
+ hidden_states_B_C = causal_conv1d_update(
503
+ hidden_states_B_C,
504
+ cache_params.conv_states[self.layer_idx],
505
+ self.conv1d.weight.squeeze(1),
506
+ self.conv1d.bias,
507
+ self.activation,
508
+ )
509
+
510
+ hidden_states, B, C = torch.split(
511
+ hidden_states_B_C,
512
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
513
+ dim=-1,
514
+ )
515
+
516
+ # 3. SSM transformation
517
+ A = -torch.exp(self.A_log.float()) # (nheads,)
518
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
519
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
520
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
521
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
522
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
523
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
524
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
525
+ hidden_states = selective_state_update(
526
+ cache_params.ssm_states[self.layer_idx],
527
+ hidden_states_reshaped,
528
+ dt,
529
+ A,
530
+ B,
531
+ C,
532
+ D,
533
+ z=None,
534
+ dt_bias=dt_bias,
535
+ dt_softplus=True,
536
+ )
537
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
538
+ hidden_states = self.norm(hidden_states, gate)
539
+
540
+ # 4. Final linear projection
541
+ out = self.out_proj(hidden_states)[:, None, ...]
542
+ # Fused calculations or step by step if no initialized cache is found
543
+ else:
544
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
545
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
546
+
547
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
548
+ if self.training and cache_params is None:
549
+ out = mamba_split_conv1d_scan_combined(
550
+ projected_states,
551
+ self.conv1d.weight.squeeze(1),
552
+ self.conv1d.bias,
553
+ self.dt_bias,
554
+ A,
555
+ D=self.D,
556
+ chunk_size=self.chunk_size,
557
+ seq_idx=seq_idx,
558
+ activation=self.activation,
559
+ rmsnorm_weight=self.norm.weight,
560
+ rmsnorm_eps=self.norm.variance_epsilon,
561
+ outproj_weight=self.out_proj.weight,
562
+ outproj_bias=self.out_proj.bias,
563
+ headdim=self.head_dim,
564
+ ngroups=self.n_groups,
565
+ norm_before_gate=False,
566
+ return_final_states=False,
567
+ **dt_limit_kwargs,
568
+ )
569
+
570
+ else:
571
+ gate, hidden_states_B_C, dt = projected_states.split(
572
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
573
+ )
574
+
575
+ # 2. Convolution sequence transformation
576
+ # Init cache
577
+ if cache_params is not None:
578
+ # storing the states
579
+ # If we just take xBC[:, :, -self.d_conv :], it will error if seqlen < self.d_conv
580
+ # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise.
581
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
582
+ conv_states = nn.functional.pad(
583
+ hidden_states_B_C_transposed,
584
+ (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
585
+ )
586
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
587
+
588
+ if self.activation not in ["silu", "swish"]:
589
+ hidden_states_B_C = self.act(
590
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
591
+ )
592
+ else:
593
+ hidden_states_B_C = causal_conv1d_fn(
594
+ x=hidden_states_B_C.transpose(1, 2),
595
+ weight=self.conv1d.weight.squeeze(1),
596
+ bias=self.conv1d.bias,
597
+ activation=self.activation,
598
+ seq_idx=seq_idx,
599
+ ).transpose(1, 2)
600
+
601
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
602
+ hidden_states, B, C = torch.split(
603
+ hidden_states_B_C,
604
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
605
+ dim=-1,
606
+ )
607
+
608
+ # 3. SSM transformation
609
+ scan_output, ssm_state = mamba_chunk_scan_combined(
610
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
611
+ dt,
612
+ A,
613
+ B.view(batch_size, seq_len, self.n_groups, -1),
614
+ C.view(batch_size, seq_len, self.n_groups, -1),
615
+ chunk_size=self.chunk_size,
616
+ D=self.D,
617
+ z=None,
618
+ seq_idx=seq_idx,
619
+ return_final_states=True,
620
+ dt_bias=self.dt_bias,
621
+ dt_softplus=True,
622
+ **dt_limit_kwargs,
623
+ )
624
+
625
+ # Init cache
626
+ if ssm_state is not None and cache_params is not None:
627
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
628
+
629
+ scan_output = scan_output.view(batch_size, seq_len, -1)
630
+ # Multiply "gate" branch and apply extra normalization layer
631
+ scan_output = self.norm(scan_output, gate)
632
+
633
+ # 4. Final linear projection
634
+ out = self.out_proj(scan_output)
635
+ return out
636
+
637
+ # fmt: off
638
+ def torch_forward(
639
+ self,
640
+ input_states,
641
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
642
+ cache_position: Optional[torch.LongTensor] = None,
643
+ attention_mask: Optional[torch.Tensor] = None,
644
+ ):
645
+ batch_size, seq_len, _ = input_states.shape
646
+ dtype = input_states.dtype
647
+
648
+ # 1. Gated MLP's linear projection
649
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
650
+ projected_states = self.in_proj(input_states)
651
+ gate, hidden_states_B_C, dt = projected_states.split(
652
+ [self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
653
+ )
654
+
655
+ use_precomputed_states = (
656
+ cache_params is not None
657
+ and cache_params.has_previous_state
658
+ and seq_len == 1
659
+ and cache_params.conv_states[self.layer_idx].shape[0]
660
+ == cache_params.ssm_states[self.layer_idx].shape[0]
661
+ == batch_size
662
+ and cache_position is not None
663
+ and cache_position[0] > 0
664
+ )
665
+
666
+ # 2. Convolution sequence transformation
667
+ if use_precomputed_states:
668
+ cache_params.conv_states[self.layer_idx] = cache_params.conv_states[self.layer_idx].roll(shifts=-1, dims=-1)
669
+ cache_params.conv_states[self.layer_idx][:, :, -1] = hidden_states_B_C[:, 0, :].to(cache_params.conv_states[self.layer_idx].device)
670
+
671
+ # We need to guarantee that anything regarding the cache is on the same device
672
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
673
+
674
+ hidden_states_B_C = torch.sum(
675
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
676
+ )
677
+ if self.use_conv_bias:
678
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
679
+ hidden_states_B_C = self.act(hidden_states_B_C)
680
+ else:
681
+ # Init cache
682
+ if cache_params is not None:
683
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
684
+ conv_states = nn.functional.pad(
685
+ hidden_states_B_C_transposed, (self.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
686
+ )
687
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
688
+
689
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
690
+
691
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
692
+ hidden_states, B, C = torch.split(
693
+ hidden_states_B_C,
694
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
695
+ dim=-1
696
+ )
697
+
698
+ # 3. SSM transformation
699
+ A = -torch.exp(self.A_log.float()) # [num_heads]
700
+ if use_precomputed_states:
701
+ # We need to guarantee that anything regarding the cache is on the same device
702
+ cache_device = cache_params.ssm_states[self.layer_idx].device
703
+
704
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
705
+ # for batched generation
706
+ dt = dt[:, 0, :][:, None, ...]
707
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
708
+ # [num_heads] -> [num_heads, head_dim]
709
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
710
+
711
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
712
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
713
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
714
+ # [bsz, num_heads, head_dim, state_size]
715
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
716
+
717
+ # Discretize B
718
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
719
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
720
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
721
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
722
+ B = B.reshape(batch_size, -1, B.shape[-1])
723
+ # [bsz, num_heads, head_dim, state_size]
724
+ dB = dt[..., None] * B[..., None, :]
725
+
726
+ # Discretize x into dB
727
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
728
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
729
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
730
+
731
+ # State calculation
732
+ cache_params.ssm_states[self.layer_idx].copy_(
733
+ cache_params.ssm_states[self.layer_idx] * dA + dBx
734
+ )
735
+
736
+ # Subsequent output
737
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
738
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
739
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
740
+ C = C.reshape(batch_size, -1, C.shape[-1])
741
+ # [bsz, num_heads, head_dim]
742
+
743
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
744
+ # Reshape ssm_states to merge the first two dimensions
745
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
746
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
747
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
748
+ y = y.view(batch_size, self.num_heads, self.head_dim)
749
+
750
+ # D skip connection
751
+ # [num_heads] -> [num_heads, head_dim]
752
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
753
+ y = (y + hidden_states * D).to(y.dtype)
754
+
755
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
756
+ y = y.reshape(batch_size, -1)[:, None, ...]
757
+ else:
758
+ # begin ssd naive implementation without einsums
759
+ dt = nn.functional.softplus(dt + self.dt_bias)
760
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
761
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
762
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
763
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
764
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
765
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
766
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
767
+
768
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
769
+
770
+ # Discretize x and A
771
+ hidden_states = hidden_states * dt[..., None]
772
+ A = A.to(hidden_states.dtype) * dt
773
+
774
+ # Rearrange into blocks/chunks
775
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
776
+
777
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
778
+ A = A.permute(0, 3, 1, 2)
779
+ A_cumsum = torch.cumsum(A, dim=-1)
780
+
781
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
782
+ # This is the analog of a causal mask
783
+ L = torch.exp(segment_sum(A))
784
+
785
+ # Contraction of C and B to get G (attention-weights like)
786
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
787
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
788
+
789
+ # Compute M, equivalent to applying attention mask to weights
790
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
791
+ M = M_intermediate.sum(dim=-1)
792
+
793
+ # Compute Y_diag (apply to values)
794
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
795
+
796
+ # 2. Compute the state for each intra-chunk
797
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
798
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
799
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
800
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
801
+
802
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
803
+ # (middle term of factorization of off-diag blocks; A terms)
804
+ if use_precomputed_states:
805
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
806
+ else:
807
+ previous_states = torch.zeros_like(states[:, :1])
808
+ states = torch.cat([previous_states, states], dim=1)
809
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
810
+ decay_chunk = decay_chunk.transpose(1, 3)
811
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
812
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
813
+
814
+ # 4. Compute state -> output conversion per chunk
815
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
816
+ state_decay_out = torch.exp(A_cumsum)
817
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
818
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
819
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
820
+
821
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
822
+ y = Y_diag + Y_off
823
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
824
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
825
+
826
+ y = y + D_residual
827
+ # Cutting off padded chunks
828
+ if pad_size > 0:
829
+ y = y[:, :seq_len, :, :]
830
+ y = y.reshape(batch_size, seq_len, -1)
831
+
832
+ # Init cache
833
+ if ssm_state is not None and cache_params is not None:
834
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
835
+
836
+ scan_output = self.norm(y, gate)
837
+
838
+ # end ssd naive
839
+
840
+ # 4. Final linear projection
841
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
842
+ return contextualized_states
843
+ # fmt: on
844
+
845
+ def forward(
846
+ self,
847
+ hidden_states,
848
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
849
+ cache_position: Optional[torch.LongTensor] = None,
850
+ attention_mask: Optional[torch.Tensor] = None,
851
+ seq_idx: Optional[torch.IntTensor] = None,
852
+ **kwargs,
853
+ ):
854
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
855
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask, seq_idx)
856
+ if seq_idx is not None:
857
+ raise NotImplementedError(
858
+ "`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`"
859
+ )
860
+ dtype = hidden_states.dtype
861
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
862
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
863
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
864
+
865
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
866
+
867
+
868
+ class GraniteMoeHybridRMSNormGated(torch.nn.Module):
869
+ def __init__(self, hidden_size, eps=1e-6):
870
+ super().__init__()
871
+ self.weight = nn.Parameter(torch.ones(hidden_size))
872
+ self.variance_epsilon = eps
873
+
874
+ def forward(self, hidden_states, gate=None):
875
+ input_dtype = hidden_states.dtype
876
+ hidden_states = hidden_states.to(torch.float32)
877
+
878
+ if gate is not None:
879
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
880
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
881
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
882
+
883
+ return self.weight * hidden_states.to(input_dtype)
884
+
885
+
886
+ class GraniteMoeHybridMLP(nn.Module):
887
+ """
888
+ MLP layer for shared experts
889
+
890
+ Args:
891
+ config:
892
+ Configuration object with model hyperparameters.
893
+ """
894
+
895
+ def __init__(self, config: GraniteMoeHybridConfig):
896
+ super().__init__()
897
+
898
+ self.input_size = config.hidden_size
899
+ self.hidden_size = config.shared_intermediate_size
900
+ self.activation = ACT2FN[config.hidden_act]
901
+ self.input_linear = nn.Linear(self.input_size, self.hidden_size * 2, bias=False)
902
+ self.output_linear = nn.Linear(self.hidden_size, self.input_size, bias=False)
903
+
904
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
905
+ hidden_states = self.input_linear(hidden_states)
906
+ chunked_hidden_states = hidden_states.chunk(2, dim=-1)
907
+ hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
908
+ hidden_states = self.output_linear(hidden_states)
909
+ return hidden_states
910
+
911
+
912
+ class GraniteFlashAttentionKwargs(TypedDict, total=False):
913
+ """
914
+ Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
915
+ Use cases include padding-free training and fewer `torch.compile` graph breaks.
916
+
917
+ Attributes:
918
+ cu_seq_lens_q (`torch.LongTensor`)
919
+ Gets cumulative sequence length for query state.
920
+ cu_seq_lens_k (`torch.LongTensor`)
921
+ Gets cumulative sequence length for key state.
922
+ max_length_q (`int`):
923
+ Maximum sequence length for query state.
924
+ max_length_k (`int`):
925
+ Maximum sequence length for key state.
926
+ seq_idx (`torch.IntTensor):
927
+ Index of each packed sequence.
928
+ """
929
+
930
+ cu_seq_lens_q: torch.LongTensor
931
+ cu_seq_lens_k: torch.LongTensor
932
+ max_length_q: int
933
+ max_length_k: int
934
+ seq_idx: torch.IntTensor
935
+
936
+
937
+ class GraniteMoeHybridRMSNorm(nn.Module):
938
+ def __init__(self, hidden_size, eps=1e-6):
939
+ """
940
+ GraniteMoeHybridRMSNorm is equivalent to T5LayerNorm
941
+ """
942
+ super().__init__()
943
+ self.weight = nn.Parameter(torch.ones(hidden_size))
944
+ self.variance_epsilon = eps
945
+
946
+ def forward(self, hidden_states):
947
+ input_dtype = hidden_states.dtype
948
+ hidden_states = hidden_states.to(torch.float32)
949
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
950
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
951
+ return self.weight * hidden_states.to(input_dtype)
952
+
953
+ def extra_repr(self):
954
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
955
+
956
+
957
+ class GraniteMoeHybridParallelExperts(nn.Module):
958
+ def __init__(self, num_experts: int, input_size: int, output_size: int) -> None:
959
+ """
960
+ Initialize the GraniteMoeHybridParallelExperts module.
961
+ The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
962
+ many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
963
+ [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
964
+ [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
965
+ used in vllm.
966
+
967
+ Args:
968
+ num_experts (int):
969
+ Number of experts.
970
+ input_size (int):
971
+ Size of the input.
972
+ output_size (int):
973
+ Size of the output.
974
+ """
975
+ super().__init__()
976
+ self.weight = nn.Parameter(torch.empty(num_experts, output_size, input_size))
977
+ self.num_experts = num_experts
978
+ self.input_size = input_size
979
+ self.output_size = output_size
980
+
981
+ def forward(self, inputs, expert_size):
982
+ """
983
+ Forward pass of the GraniteMoeHybridParallelExperts module.
984
+
985
+ Args:
986
+ inputs (Tensor):
987
+ Input tensor.
988
+ expert_size:
989
+ Expert size information.
990
+
991
+ Returns:
992
+ Tensor: Output tensor.
993
+ """
994
+ input_list = inputs.split(expert_size, dim=0)
995
+ output_list = []
996
+ for i in range(self.num_experts):
997
+ output_list.append(F.linear(input_list[i], self.weight[i]))
998
+ results = torch.cat(output_list, dim=0)
999
+ return results
1000
+
1001
+
1002
+ class GraniteMoeHybridTopKGating(nn.Module):
1003
+ def __init__(self, input_size: int, num_experts: int, top_k: int):
1004
+ """
1005
+ Initialize the top-k gating mechanism.
1006
+ Args:
1007
+ input_size (`int`):
1008
+ Size of the input.
1009
+ num_experts (`int`):
1010
+ Number of experts.
1011
+ top_k (`int`):
1012
+ Number of top experts to select.
1013
+ """
1014
+ super().__init__()
1015
+
1016
+ self.num_experts = num_experts
1017
+ self.input_size = input_size
1018
+ self.top_k = top_k
1019
+
1020
+ self.layer = nn.Linear(input_size, num_experts, bias=False)
1021
+
1022
+ def forward(self, hidden_states):
1023
+ # compute the top_k routing decision
1024
+ logits = self.layer(hidden_states).float() # [batch_size x seq_len, num_experts]
1025
+ top_k_logits, top_k_indices = logits.topk(self.top_k, dim=1) # [num_tokens, top_k]
1026
+ top_k_gates = torch.softmax(top_k_logits, dim=1).type_as(hidden_states) # [num_tokens, top_k]
1027
+
1028
+ # compute number of input given to each expert
1029
+ zeros = torch.zeros(
1030
+ [top_k_gates.size(0), self.num_experts], dtype=top_k_gates.dtype, device=top_k_gates.device
1031
+ ) # [num_tokens, num_experts]
1032
+ gates = zeros.scatter(1, top_k_indices, 1) # [num_tokens, num_experts]
1033
+ expert_size = gates.long().sum(0) # [num_experts,]
1034
+ # (This cause torch.compile to fail with `torch._dynamo.exc.Unsupported: Backend compiler failed with a fake tensor exception at`)
1035
+ # (and `DataDependentOutputException`)
1036
+ expert_size = expert_size.tolist()
1037
+
1038
+ # sort and group input tokens according to expert assignment
1039
+ top_k_experts = top_k_indices.flatten() # [num_tokens * top_k]
1040
+ _, index_sorted_experts = top_k_experts.sort(0) # [num_tokens * top_k]
1041
+ batch_index = index_sorted_experts.div(self.top_k, rounding_mode="trunc") # [num_tokens * top_k]
1042
+
1043
+ # gather the gate values for grouped input tokens
1044
+ top_k_gates = top_k_gates.flatten() # [num_tokens * top_k]
1045
+ batch_gates = top_k_gates[index_sorted_experts] # [num_tokens * top_k]
1046
+
1047
+ return index_sorted_experts, batch_index, batch_gates, expert_size, logits
1048
+
1049
+
1050
+ class GraniteMoeHybridMoE(nn.Module):
1051
+ """
1052
+ A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
1053
+
1054
+ Args:
1055
+ config:
1056
+ Configuration object with model hyperparameters.
1057
+ """
1058
+
1059
+ def __init__(self, config: GraniteMoeHybridConfig):
1060
+ super().__init__()
1061
+
1062
+ self.input_size = config.hidden_size
1063
+ self.hidden_size = config.intermediate_size
1064
+ self.activation = ACT2FN[config.hidden_act]
1065
+ self.input_linear = GraniteMoeHybridParallelExperts(
1066
+ config.num_local_experts, self.input_size, self.hidden_size * 2
1067
+ )
1068
+ self.output_linear = GraniteMoeHybridParallelExperts(
1069
+ config.num_local_experts, self.hidden_size, self.input_size
1070
+ )
1071
+
1072
+ self.router = GraniteMoeHybridTopKGating(
1073
+ input_size=self.input_size,
1074
+ num_experts=config.num_local_experts,
1075
+ top_k=config.num_experts_per_tok,
1076
+ )
1077
+
1078
+ def forward(self, layer_input):
1079
+ """
1080
+ Forward pass of the mixture of experts layer.
1081
+
1082
+ Args:
1083
+ layer_input (Tensor):
1084
+ Input tensor.
1085
+
1086
+ Returns:
1087
+ Tensor:
1088
+ Output tensor.
1089
+ Tensor:
1090
+ Router logits.
1091
+ """
1092
+ bsz, length, emb_size = layer_input.size()
1093
+ layer_input = layer_input.reshape(-1, emb_size)
1094
+ _, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
1095
+
1096
+ expert_inputs = layer_input[batch_index]
1097
+ hidden_states = self.input_linear(expert_inputs, expert_size)
1098
+ chunked_hidden_states = hidden_states.chunk(2, dim=-1)
1099
+ hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
1100
+ expert_outputs = self.output_linear(hidden_states, expert_size)
1101
+
1102
+ expert_outputs = expert_outputs * batch_gates[:, None]
1103
+
1104
+ zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
1105
+ layer_output = zeros.index_add(0, batch_index, expert_outputs)
1106
+ layer_output = layer_output.view(bsz, length, self.input_size)
1107
+ return layer_output, router_logits
1108
+
1109
+
1110
+ class GraniteMoeHybridDecoderLayer(GradientCheckpointingLayer):
1111
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
1112
+ super().__init__()
1113
+ self.hidden_size = config.hidden_size
1114
+ # Either attention or mamba will be initialized, depending on the layer type.
1115
+ self.self_attn = None
1116
+ if config.num_local_experts > 0:
1117
+ self.block_sparse_moe = GraniteMoeHybridMoE(config)
1118
+ self.input_layernorm = GraniteMoeHybridRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1119
+ self.post_attention_layernorm = GraniteMoeHybridRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1120
+
1121
+ self.residual_multiplier = config.residual_multiplier
1122
+ self.shared_mlp = GraniteMoeHybridMLP(config)
1123
+ self.mamba = None
1124
+
1125
+ if config.layers_block_type[layer_idx] == "mamba":
1126
+ self.mamba = GraniteMoeHybridMambaLayer(config, layer_idx)
1127
+ else:
1128
+ self.self_attn = GraniteMoeHybridAttention(config, layer_idx)
1129
+ self.layer_type = config.layers_block_type[layer_idx]
1130
+
1131
+ # Accept 0 experts: skip MoE if num_local_experts == 0
1132
+ self.has_experts = getattr(config, "num_local_experts", 0) > 0
1133
+
1134
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
1135
+ def forward(
1136
+ self,
1137
+ hidden_states: torch.Tensor,
1138
+ attention_mask: Optional[torch.Tensor] = None,
1139
+ past_key_values: Optional[Cache] = None,
1140
+ output_attentions: Optional[bool] = False,
1141
+ use_cache: Optional[bool] = False,
1142
+ cache_position: Optional[torch.LongTensor] = None,
1143
+ output_router_logits: Optional[bool] = False,
1144
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
1145
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
1146
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
1147
+ """
1148
+ Args:
1149
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1150
+ attention_mask (`torch.FloatTensor`, *optional*):
1151
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1152
+ query_sequence_length, key_sequence_length)` if default attention is used.
1153
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
1154
+ output_attentions (`bool`, *optional*):
1155
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1156
+ returned tensors for more detail.
1157
+ use_cache (`bool`, *optional*):
1158
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1159
+ (see `past_key_values`).
1160
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1161
+ Indices depicting the position of the input sequence tokens in the sequence
1162
+ output_router_logits (`bool`, *optional*):
1163
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
1164
+ should not be returned during inference.
1165
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
1166
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
1167
+ with `head_dim` being the embedding dimension of each attention head.
1168
+ kwargs (`dict`, *optional*):
1169
+ Arbitrary kwargs.Can be used to provide `GraniteFlashAttentionKwargs` for
1170
+ padding-free training and/or improve torch.compile performance.
1171
+ """
1172
+ residual = hidden_states
1173
+ hidden_states = self.input_layernorm(hidden_states)
1174
+
1175
+ if self.mamba is not None:
1176
+ hidden_states = self.mamba(
1177
+ hidden_states=hidden_states,
1178
+ cache_position=cache_position,
1179
+ cache_params=past_key_values,
1180
+ attention_mask=attention_mask,
1181
+ **kwargs,
1182
+ )
1183
+ # No attention weights for state space layers
1184
+ self_attn_weights = None
1185
+ else:
1186
+ hidden_states, self_attn_weights = self.self_attn(
1187
+ hidden_states=hidden_states,
1188
+ attention_mask=attention_mask,
1189
+ past_key_values=past_key_values,
1190
+ output_attentions=output_attentions,
1191
+ use_cache=use_cache,
1192
+ cache_position=cache_position,
1193
+ position_embeddings=position_embeddings,
1194
+ **kwargs,
1195
+ )
1196
+
1197
+ hidden_states = residual + hidden_states * self.residual_multiplier
1198
+
1199
+ # Fully Connected
1200
+ residual = hidden_states
1201
+ hidden_states = self.post_attention_layernorm(hidden_states)
1202
+
1203
+ if self.has_experts:
1204
+ moe_hidden_states, router_logits = self.block_sparse_moe(hidden_states)
1205
+ hidden_states = moe_hidden_states + self.shared_mlp(hidden_states)
1206
+ else:
1207
+ hidden_states = self.shared_mlp(hidden_states)
1208
+ router_logits = None
1209
+
1210
+ hidden_states = residual + hidden_states * self.residual_multiplier
1211
+
1212
+ outputs = (hidden_states,)
1213
+
1214
+ if output_attentions:
1215
+ outputs += (self_attn_weights,)
1216
+
1217
+ if output_router_logits:
1218
+ outputs += (router_logits,)
1219
+
1220
+ return outputs
1221
+
1222
+
1223
+ @auto_docstring
1224
+ class GraniteMoeHybridPreTrainedModel(PreTrainedModel):
1225
+ config: GraniteMoeHybridConfig
1226
+ base_model_prefix = "model"
1227
+ supports_gradient_checkpointing = True
1228
+ _no_split_modules = ["GraniteMoeHybridDecoderLayer"]
1229
+ _skip_keys_device_placement = ["past_key_values"]
1230
+ _supports_flash_attn = True
1231
+ _supports_sdpa = True
1232
+
1233
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
1234
+ _is_stateful = True
1235
+
1236
+ def _init_weights(self, module):
1237
+ super()._init_weights(module)
1238
+ if isinstance(module, GraniteMoeHybridParallelExperts):
1239
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1240
+ if isinstance(module, GraniteMoeHybridMambaLayer):
1241
+ module.dt_bias.data.fill_(1.0)
1242
+ module.A_log.data = torch.log(torch.arange(1, module.num_heads + 1))
1243
+ module.D.data.fill_(1.0)
1244
+ elif isinstance(module, GraniteMoeHybridRMSNormGated):
1245
+ module.weight.data.fill_(1.0)
1246
+
1247
+
1248
+ class GraniteMoeHybridRotaryEmbedding(nn.Module):
1249
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
1250
+
1251
+ def __init__(self, config: GraniteMoeHybridConfig, device=None):
1252
+ super().__init__()
1253
+ # BC: "rope_type" was originally "type"
1254
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
1255
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
1256
+ else:
1257
+ self.rope_type = "default"
1258
+ self.max_seq_len_cached = config.max_position_embeddings
1259
+ self.original_max_seq_len = config.max_position_embeddings
1260
+
1261
+ self.config = config
1262
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
1263
+
1264
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
1265
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
1266
+ self.original_inv_freq = self.inv_freq
1267
+
1268
+ @torch.no_grad()
1269
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
1270
+ def forward(self, x, position_ids):
1271
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
1272
+ position_ids_expanded = position_ids[:, None, :].float()
1273
+
1274
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
1275
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
1276
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
1277
+ emb = torch.cat((freqs, freqs), dim=-1)
1278
+ cos = emb.cos() * self.attention_scaling
1279
+ sin = emb.sin() * self.attention_scaling
1280
+
1281
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
1282
+
1283
+
1284
+ @auto_docstring
1285
+ class GraniteMoeHybridModel(GraniteMoeHybridPreTrainedModel):
1286
+ def __init__(self, config: GraniteMoeHybridConfig):
1287
+ super().__init__(config)
1288
+ self.padding_idx = config.pad_token_id
1289
+ self.vocab_size = config.vocab_size
1290
+
1291
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1292
+ self.layers = nn.ModuleList(
1293
+ [GraniteMoeHybridDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1294
+ )
1295
+ self.norm = GraniteMoeHybridRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1296
+ self.gradient_checkpointing = False
1297
+
1298
+ self.embedding_multiplier = config.embedding_multiplier
1299
+ self.hidden_size = config.hidden_size
1300
+ self.num_heads = config.num_attention_heads
1301
+ self.head_dim = self.hidden_size // self.num_heads
1302
+ self.max_position_embeddings = config.max_position_embeddings
1303
+ self.rope_theta = config.rope_theta
1304
+
1305
+ self.position_embedding_type = config.position_embedding_type
1306
+ self.rotary_emb = GraniteMoeHybridRotaryEmbedding(config) if self.position_embedding_type == "rope" else None
1307
+
1308
+ # Initialize weights and apply final processing
1309
+ self.post_init()
1310
+
1311
+ @can_return_tuple
1312
+ @auto_docstring
1313
+ def forward(
1314
+ self,
1315
+ input_ids: Optional[torch.LongTensor] = None,
1316
+ attention_mask: Optional[torch.Tensor] = None,
1317
+ position_ids: Optional[torch.LongTensor] = None,
1318
+ past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
1319
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1320
+ use_cache: Optional[bool] = None,
1321
+ output_attentions: Optional[bool] = None,
1322
+ output_hidden_states: Optional[bool] = None,
1323
+ output_router_logits: Optional[bool] = None,
1324
+ return_dict: Optional[bool] = None,
1325
+ cache_position: Optional[torch.LongTensor] = None,
1326
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
1327
+ ) -> Union[tuple, BaseModelOutputWithPast]:
1328
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1329
+ output_hidden_states = (
1330
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1331
+ )
1332
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
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):
1336
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1337
+
1338
+ if self.gradient_checkpointing and self.training and use_cache:
1339
+ logger.warning_once(
1340
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1341
+ )
1342
+ use_cache = False
1343
+
1344
+ if inputs_embeds is None:
1345
+ inputs_embeds = self.embed_tokens(input_ids)
1346
+
1347
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
1348
+
1349
+ ## overwritten because `HybridMambaAttentionDynamicCache` is needed
1350
+ if use_cache and past_key_values is None:
1351
+ logger.warning_once(
1352
+ "GraniteMoeHybrid requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. "
1353
+ "Because one was not provided, no cache will be returned."
1354
+ )
1355
+
1356
+ if cache_position is None:
1357
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1358
+ cache_position = torch.arange(
1359
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1360
+ )
1361
+ if position_ids is None:
1362
+ position_ids = cache_position.unsqueeze(0)
1363
+
1364
+ causal_mask = self._update_causal_mask(
1365
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1366
+ )
1367
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
1368
+
1369
+ # embed positions
1370
+ hidden_states = inputs_embeds
1371
+
1372
+ position_embeddings = None
1373
+ # create position embeddings to be shared across the decoder layers
1374
+ if self.rotary_emb is not None:
1375
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1376
+
1377
+ # decoder layers
1378
+ all_hidden_states = () if output_hidden_states else None
1379
+ all_self_attns = () if output_attentions else None
1380
+ all_router_logits = () if output_router_logits else None
1381
+
1382
+ for decoder_layer in self.layers:
1383
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
1384
+ layer_mask = mamba_mask if decoder_layer.layer_type == "mamba" else causal_mask
1385
+
1386
+ if output_hidden_states:
1387
+ all_hidden_states += (hidden_states,)
1388
+
1389
+ layer_outputs = decoder_layer(
1390
+ hidden_states,
1391
+ attention_mask=layer_mask,
1392
+ past_key_values=past_key_values,
1393
+ output_attentions=output_attentions,
1394
+ use_cache=use_cache,
1395
+ cache_position=cache_position,
1396
+ output_router_logits=output_router_logits,
1397
+ position_embeddings=position_embeddings,
1398
+ **kwargs,
1399
+ )
1400
+
1401
+ hidden_states = layer_outputs[0]
1402
+
1403
+ if output_attentions:
1404
+ if layer_outputs[1] is not None:
1405
+ # append attentions only of attention layers. Mamba layers return `None` as the attention weights
1406
+ all_self_attns += (layer_outputs[1],)
1407
+
1408
+ if output_router_logits:
1409
+ if layer_outputs[-1] is not None:
1410
+ # append router logits only of expert layers. Regular MLP layers return `None` as the router logits
1411
+ all_router_logits += (layer_outputs[-1],)
1412
+
1413
+ hidden_states = self.norm(hidden_states)
1414
+
1415
+ # add hidden states from the last decoder layer
1416
+ if output_hidden_states:
1417
+ all_hidden_states += (hidden_states,)
1418
+
1419
+ if past_key_values and not past_key_values.has_previous_state:
1420
+ past_key_values.has_previous_state = True
1421
+
1422
+ return MoeModelOutputWithPast(
1423
+ last_hidden_state=hidden_states,
1424
+ past_key_values=past_key_values,
1425
+ hidden_states=all_hidden_states,
1426
+ attentions=all_self_attns,
1427
+ router_logits=all_router_logits,
1428
+ )
1429
+
1430
+ def _update_causal_mask(
1431
+ self,
1432
+ attention_mask: Union[torch.Tensor, "BlockMask"],
1433
+ input_tensor: torch.Tensor,
1434
+ cache_position: torch.Tensor,
1435
+ past_key_values: Cache,
1436
+ output_attentions: bool = False,
1437
+ ):
1438
+ if self.config._attn_implementation == "flash_attention_2":
1439
+ if attention_mask is not None and (attention_mask == 0.0).any():
1440
+ return attention_mask
1441
+ return None
1442
+ if self.config._attn_implementation == "flex_attention":
1443
+ if isinstance(attention_mask, torch.Tensor):
1444
+ attention_mask = make_flex_block_causal_mask(attention_mask)
1445
+ return attention_mask
1446
+
1447
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1448
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1449
+ # to infer the attention mask.
1450
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1451
+ using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
1452
+
1453
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1454
+ if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
1455
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1456
+ attention_mask,
1457
+ inputs_embeds=input_tensor,
1458
+ past_key_values_length=past_seen_tokens,
1459
+ is_training=self.training,
1460
+ ):
1461
+ return None
1462
+
1463
+ dtype = input_tensor.dtype
1464
+ sequence_length = input_tensor.shape[1]
1465
+ if using_compilable_cache:
1466
+ target_length = past_key_values.get_max_cache_shape()
1467
+ else:
1468
+ target_length = (
1469
+ attention_mask.shape[-1]
1470
+ if isinstance(attention_mask, torch.Tensor)
1471
+ else past_seen_tokens + sequence_length + 1
1472
+ )
1473
+
1474
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1475
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1476
+ attention_mask,
1477
+ sequence_length=sequence_length,
1478
+ target_length=target_length,
1479
+ dtype=dtype,
1480
+ cache_position=cache_position,
1481
+ batch_size=input_tensor.shape[0],
1482
+ )
1483
+
1484
+ if (
1485
+ self.config._attn_implementation == "sdpa"
1486
+ and attention_mask is not None
1487
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
1488
+ and not output_attentions
1489
+ ):
1490
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1491
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1492
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1493
+ min_dtype = torch.finfo(dtype).min
1494
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1495
+
1496
+ return causal_mask
1497
+
1498
+ @staticmethod
1499
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1500
+ attention_mask: torch.Tensor,
1501
+ sequence_length: int,
1502
+ target_length: int,
1503
+ dtype: torch.dtype,
1504
+ cache_position: torch.Tensor,
1505
+ batch_size: int,
1506
+ **kwargs,
1507
+ ):
1508
+ """
1509
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1510
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1511
+
1512
+ Args:
1513
+ attention_mask (`torch.Tensor`):
1514
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1515
+ `(batch_size, 1, query_length, key_value_length)`.
1516
+ sequence_length (`int`):
1517
+ The sequence length being processed.
1518
+ target_length (`int`):
1519
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1520
+ to account for the 0 padding, the part of the cache that is not filled yet.
1521
+ dtype (`torch.dtype`):
1522
+ The dtype to use for the 4D attention mask.
1523
+ cache_position (`torch.Tensor`):
1524
+ Indices depicting the position of the input sequence tokens in the sequence.
1525
+ batch_size (`torch.Tensor`):
1526
+ Batch size.
1527
+ """
1528
+ if attention_mask is not None and attention_mask.dim() == 4:
1529
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1530
+ causal_mask = attention_mask
1531
+ else:
1532
+ min_dtype = torch.finfo(dtype).min
1533
+ causal_mask = torch.full(
1534
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
1535
+ )
1536
+ if sequence_length != 1:
1537
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1538
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
1539
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1540
+ if attention_mask is not None:
1541
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1542
+ mask_length = attention_mask.shape[-1]
1543
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1544
+ causal_mask.device
1545
+ )
1546
+ padding_mask = padding_mask == 0
1547
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1548
+ padding_mask, min_dtype
1549
+ )
1550
+
1551
+ return causal_mask
1552
+
1553
+ def _update_mamba_mask(self, attention_mask, cache_position):
1554
+ """
1555
+ No need for zeroing states when
1556
+ 1. Cached forward
1557
+ 2. Attending to all inputs
1558
+ """
1559
+ mamba_mask = attention_mask
1560
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1561
+ mamba_mask = None
1562
+ return mamba_mask
1563
+
1564
+
1565
+ def load_balancing_loss_func(
1566
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
1567
+ num_experts: Optional[int] = None,
1568
+ top_k=2,
1569
+ attention_mask: Optional[torch.Tensor] = None,
1570
+ ) -> Union[torch.Tensor, int]:
1571
+ r"""
1572
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
1573
+
1574
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
1575
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
1576
+ experts is too unbalanced.
1577
+
1578
+ Args:
1579
+ gate_logits:
1580
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
1581
+ shape [batch_size X sequence_length, num_experts].
1582
+ num_experts:
1583
+ Number of experts
1584
+ top_k:
1585
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
1586
+ parameter.
1587
+ attention_mask (`torch.Tensor`, *optional*):
1588
+ The attention_mask used in forward function
1589
+ shape [batch_size X sequence_length] if not None.
1590
+
1591
+ Returns:
1592
+ The auxiliary loss.
1593
+ """
1594
+ if gate_logits is None or not isinstance(gate_logits, tuple):
1595
+ return 0
1596
+
1597
+ if isinstance(gate_logits, tuple):
1598
+ compute_device = gate_logits[0].device
1599
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
1600
+
1601
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
1602
+
1603
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
1604
+
1605
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
1606
+
1607
+ if attention_mask is None:
1608
+ # Compute the percentage of tokens routed to each experts
1609
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
1610
+
1611
+ # Compute the average probability of routing to these experts
1612
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
1613
+ else:
1614
+ batch_size, sequence_length = attention_mask.shape
1615
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
1616
+
1617
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
1618
+ expert_attention_mask = (
1619
+ attention_mask[None, :, :, None, None]
1620
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
1621
+ .reshape(-1, top_k, num_experts)
1622
+ .to(compute_device)
1623
+ )
1624
+
1625
+ # Compute the percentage of tokens routed to each experts
1626
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
1627
+ expert_attention_mask, dim=0
1628
+ )
1629
+
1630
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
1631
+ router_per_expert_attention_mask = (
1632
+ attention_mask[None, :, :, None]
1633
+ .expand((num_hidden_layers, batch_size, sequence_length, routing_weights.shape[1]))
1634
+ .reshape(-1, routing_weights.shape[1])
1635
+ .to(compute_device)
1636
+ )
1637
+
1638
+ # Compute the average probability of routing to these experts
1639
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
1640
+ router_per_expert_attention_mask, dim=0
1641
+ )
1642
+
1643
+ device_index = routing_weights.device.index if routing_weights.device.index is not None else 0
1644
+ rank = routing_weights.shape[1] * int(device_index)
1645
+ overall_loss = torch.sum(
1646
+ tokens_per_expert[:, rank : rank + routing_weights.shape[1]] * router_prob_per_expert.unsqueeze(0)
1647
+ )
1648
+ return overall_loss * num_experts
1649
+
1650
+
1651
+ class GraniteMoeHybridForCausalLM(GraniteMoeHybridPreTrainedModel, GenerationMixin):
1652
+ _tied_weights_keys = ["lm_head.weight"]
1653
+
1654
+ def __init__(self, config: GraniteMoeHybridConfig):
1655
+ super().__init__(config)
1656
+ self.model = GraniteMoeHybridModel(config)
1657
+ self.vocab_size = config.vocab_size
1658
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1659
+
1660
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1661
+ self.num_experts = config.num_local_experts
1662
+ self.num_experts_per_tok = config.num_experts_per_tok
1663
+
1664
+ # Initialize weights and apply final processing
1665
+ self.post_init()
1666
+
1667
+ @auto_docstring
1668
+ def forward(
1669
+ self,
1670
+ input_ids: Optional[torch.LongTensor] = None,
1671
+ attention_mask: Optional[torch.Tensor] = None,
1672
+ position_ids: Optional[torch.LongTensor] = None,
1673
+ past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
1674
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1675
+ labels: Optional[torch.LongTensor] = None,
1676
+ use_cache: Optional[bool] = None,
1677
+ output_attentions: Optional[bool] = None,
1678
+ output_hidden_states: Optional[bool] = None,
1679
+ output_router_logits: Optional[bool] = None,
1680
+ return_dict: Optional[bool] = None,
1681
+ cache_position: Optional[torch.LongTensor] = None,
1682
+ logits_to_keep: Union[int, torch.Tensor] = 0,
1683
+ **kwargs,
1684
+ ) -> Union[tuple, MoeCausalLMOutputWithPast]:
1685
+ r"""
1686
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1687
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1688
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1689
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1690
+
1691
+ Example:
1692
+
1693
+ ```python
1694
+ >>> from transformers import AutoTokenizer, GraniteMoeHybridForCausalLM
1695
+
1696
+ >>> model = GraniteMoeHybridForCausalLM.from_pretrained("ibm/PowerMoE-3b")
1697
+ >>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")
1698
+
1699
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1700
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1701
+
1702
+ >>> # Generate
1703
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1704
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1705
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1706
+ ```"""
1707
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1708
+ output_router_logits = (
1709
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1710
+ )
1711
+ output_hidden_states = (
1712
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1713
+ )
1714
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1715
+
1716
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1717
+ outputs = self.model(
1718
+ input_ids=input_ids,
1719
+ attention_mask=attention_mask,
1720
+ position_ids=position_ids,
1721
+ past_key_values=past_key_values,
1722
+ inputs_embeds=inputs_embeds,
1723
+ use_cache=use_cache,
1724
+ output_attentions=output_attentions,
1725
+ output_hidden_states=output_hidden_states,
1726
+ output_router_logits=output_router_logits,
1727
+ return_dict=return_dict,
1728
+ cache_position=cache_position,
1729
+ **kwargs,
1730
+ )
1731
+
1732
+ # Only compute necessary logits
1733
+ hidden_states = outputs[0]
1734
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1735
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1736
+ logits = logits / self.config.logits_scaling
1737
+
1738
+ loss = None
1739
+ if labels is not None:
1740
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1741
+ logits = logits.float()
1742
+ # Flatten the tokens
1743
+ loss = self.loss_function(
1744
+ logits,
1745
+ labels,
1746
+ vocab_size=self.config.vocab_size,
1747
+ **kwargs,
1748
+ )
1749
+
1750
+ aux_loss = None
1751
+ if output_router_logits:
1752
+ aux_loss = load_balancing_loss_func(
1753
+ outputs.router_logits if return_dict else outputs[-1],
1754
+ self.num_experts,
1755
+ self.num_experts_per_tok,
1756
+ attention_mask,
1757
+ )
1758
+ if labels is not None:
1759
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1760
+
1761
+ if not return_dict:
1762
+ output = (logits,) + outputs[1:]
1763
+ if output_router_logits:
1764
+ output = (aux_loss,) + output
1765
+ return (loss,) + output if loss is not None else output
1766
+
1767
+ return MoeCausalLMOutputWithPast(
1768
+ loss=loss,
1769
+ aux_loss=aux_loss,
1770
+ logits=logits,
1771
+ past_key_values=outputs.past_key_values,
1772
+ hidden_states=outputs.hidden_states,
1773
+ attentions=outputs.attentions,
1774
+ router_logits=outputs.router_logits,
1775
+ )
1776
+
1777
+ def prepare_inputs_for_generation(
1778
+ self,
1779
+ input_ids,
1780
+ past_key_values=None,
1781
+ attention_mask=None,
1782
+ inputs_embeds=None,
1783
+ cache_position=None,
1784
+ position_ids=None,
1785
+ use_cache=True,
1786
+ **kwargs,
1787
+ ):
1788
+ # Overwritten -- has a unique cache type, `HybridMambaAttentionDynamicCache`
1789
+
1790
+ empty_past_kv = past_key_values is None
1791
+
1792
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1793
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1794
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1795
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
1796
+ # (we can't check exception 3 while compiling)
1797
+ if not empty_past_kv:
1798
+ if (
1799
+ inputs_embeds is not None # Exception 1
1800
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
1801
+ ):
1802
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1803
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1804
+ input_ids = input_ids[:, cache_position]
1805
+ elif use_cache:
1806
+ past_key_values = HybridMambaAttentionDynamicCache(
1807
+ self.config, input_ids.shape[0], self.dtype, device=self.device
1808
+ )
1809
+
1810
+ if attention_mask is not None and position_ids is None:
1811
+ # create position_ids on the fly for batch generation
1812
+ position_ids = attention_mask.long().cumsum(-1) - 1
1813
+ position_ids.masked_fill_(attention_mask == 0, 1)
1814
+ if not empty_past_kv:
1815
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1816
+
1817
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1818
+ if inputs_embeds is not None and empty_past_kv:
1819
+ model_inputs = {"inputs_embeds": inputs_embeds}
1820
+ else:
1821
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1822
+
1823
+ model_inputs.update(
1824
+ {
1825
+ "position_ids": position_ids,
1826
+ "past_key_values": past_key_values,
1827
+ "use_cache": use_cache,
1828
+ "attention_mask": attention_mask,
1829
+ "cache_position": cache_position,
1830
+ }
1831
+ )
1832
+
1833
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
1834
+ for key, value in kwargs.items():
1835
+ if key not in model_inputs:
1836
+ model_inputs[key] = value
1837
+
1838
+ return model_inputs
1839
+
1840
+
1841
+ __all__ = ["GraniteMoeHybridForCausalLM", "GraniteMoeHybridModel", "GraniteMoeHybridPreTrainedModel"]