EvanOLeary commited on
Commit
32766c9
·
verified ·
1 Parent(s): dce1171

Upload modeling_laguna_dense.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_laguna_dense.py +752 -0
modeling_laguna_dense.py ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Poolside and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from collections.abc import Callable
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch import nn
21
+
22
+ from transformers import initialization as init
23
+ from transformers.activations import ACT2FN
24
+ from transformers.cache_utils import Cache, DynamicCache
25
+ from transformers.generation import GenerationMixin
26
+ from transformers.integrations import use_experts_implementation, use_kernel_forward_from_hub, use_kernelized_func
27
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
28
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
29
+ from transformers.modeling_layers import GradientCheckpointingLayer
30
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
31
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
32
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
33
+ from transformers.processing_utils import Unpack
34
+ from transformers.utils import auto_docstring, can_return_tuple
35
+ from transformers.utils.generic import TransformersKwargs, maybe_autocast
36
+ from transformers.utils.output_capturing import OutputRecorder, capture_outputs
37
+ from .configuration_laguna_dense import LagunaConfig
38
+
39
+
40
+ @use_kernel_forward_from_hub("RMSNorm")
41
+ class LagunaRMSNorm(nn.Module):
42
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
43
+ """
44
+ LagunaRMSNorm is equivalent to T5LayerNorm
45
+ """
46
+ super().__init__()
47
+ self.weight = nn.Parameter(torch.ones(hidden_size))
48
+ self.variance_epsilon = eps
49
+
50
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
51
+ input_dtype = hidden_states.dtype
52
+ hidden_states = hidden_states.to(torch.float32)
53
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
54
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
55
+ return self.weight * hidden_states.to(input_dtype)
56
+
57
+ def extra_repr(self):
58
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
59
+
60
+
61
+ class LagunaRotaryEmbedding(nn.Module):
62
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
63
+
64
+ def __init__(self, config: LagunaConfig, device=None, layer_type=None):
65
+ super().__init__()
66
+ self.max_seq_len_cached = config.max_position_embeddings
67
+ self.original_max_seq_len = config.max_position_embeddings
68
+
69
+ self.config = config
70
+
71
+ self.layer_types = list(set(config.layer_types))
72
+ self.rope_type = {}
73
+ for layer_type in self.layer_types:
74
+ rope_params = self.config.rope_parameters[layer_type]
75
+ if rope_params is None:
76
+ continue
77
+
78
+ self.rope_type[layer_type] = rope_params["rope_type"]
79
+ rope_init_fn: Callable = self.compute_default_rope_parameters
80
+ if self.rope_type[layer_type] != "default":
81
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
82
+ curr_inv_freq, curr_attention_scaling = rope_init_fn(self.config, device, layer_type=layer_type)
83
+ self.register_buffer(f"{layer_type}_inv_freq", curr_inv_freq, persistent=False)
84
+ self.register_buffer(f"{layer_type}_original_inv_freq", curr_inv_freq.clone(), persistent=False)
85
+ setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling)
86
+
87
+ @staticmethod
88
+ def compute_default_rope_parameters(
89
+ config: LagunaConfig | None = None,
90
+ device: Optional["torch.device"] = None,
91
+ seq_len: int | None = None,
92
+ layer_type: str | None = None,
93
+ ) -> tuple["torch.Tensor", float]:
94
+ """
95
+ Computes the inverse frequencies according to the original RoPE implementation
96
+ Args:
97
+ config ([`~transformers.PreTrainedConfig`]):
98
+ The model configuration.
99
+ device (`torch.device`):
100
+ The device to use for initialization of the inverse frequencies.
101
+ seq_len (`int`, *optional*):
102
+ The current sequence length. Unused for this type of RoPE.
103
+ layer_type (`str`, *optional*):
104
+ The current layer type if the model has different RoPE parameters per type.
105
+ Should not be used unless `config.layer_types is not None`
106
+ Returns:
107
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
108
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
109
+ """
110
+ base = config.rope_parameters[layer_type]["rope_theta"]
111
+ # key difference to gemma3: partial rope
112
+ partial_rotary_factor = config.rope_parameters[layer_type].get("partial_rotary_factor", 1.0)
113
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
114
+ dim = int(head_dim * partial_rotary_factor)
115
+
116
+ attention_factor = 1.0 # Unused in this type of RoPE
117
+
118
+ # Compute the inverse frequencies
119
+ inv_freq = 1.0 / (
120
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
121
+ )
122
+ return inv_freq, attention_factor
123
+
124
+ @torch.no_grad()
125
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
126
+ def forward(self, x, position_ids, layer_type=None):
127
+ inv_freq = getattr(self, f"{layer_type}_inv_freq")
128
+ attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
129
+
130
+ inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
131
+ position_ids_expanded = position_ids[:, None, :].float()
132
+
133
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
134
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
135
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ cos = emb.cos() * attention_scaling
138
+ sin = emb.sin() * attention_scaling
139
+
140
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
141
+
142
+
143
+ class LagunaMLP(nn.Module):
144
+ def __init__(self, config, intermediate_size=None):
145
+ super().__init__()
146
+ self.config = config
147
+ self.hidden_size = config.hidden_size
148
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
149
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
150
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
151
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
152
+ self.act_fn = ACT2FN[config.hidden_act]
153
+
154
+ def forward(self, x):
155
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
156
+ return down_proj
157
+
158
+
159
+ class LagunaTopKRouter(nn.Module):
160
+ def __init__(self, config):
161
+ super().__init__()
162
+ self.top_k = config.num_experts_per_tok
163
+ self.num_experts = config.num_experts
164
+ self.hidden_dim = config.hidden_size
165
+ self.weight = nn.Parameter(torch.zeros(self.num_experts, self.hidden_dim))
166
+ self.e_score_correction_bias = nn.Parameter(torch.zeros(config.num_experts), requires_grad=False)
167
+ self.router_logit_softcapping = config.moe_router_logit_softcapping
168
+
169
+ def forward(
170
+ self,
171
+ hidden_states: torch.Tensor,
172
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
173
+ hidden_states = hidden_states.reshape(-1, self.hidden_dim)
174
+ router_logits = F.linear(hidden_states, self.weight).float()
175
+ # Optional logits softcapping
176
+ if self.router_logit_softcapping > 0.0:
177
+ router_logits = torch.tanh(router_logits / self.router_logit_softcapping) * self.router_logit_softcapping
178
+ # Sigmoid instead of softmax normalization
179
+ routing_scores = torch.sigmoid(router_logits)
180
+
181
+ scores_for_selection = routing_scores + self.e_score_correction_bias.to(routing_scores.dtype)
182
+ _, selected_experts = torch.topk(scores_for_selection, self.top_k, dim=-1)
183
+ routing_weights = routing_scores.gather(-1, selected_experts)
184
+ routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True)
185
+ routing_weights = routing_weights.to(hidden_states.dtype)
186
+
187
+ return router_logits, routing_weights, selected_experts
188
+
189
+
190
+ @use_experts_implementation
191
+ class LagunaExperts(nn.Module):
192
+ """Collection of expert weights stored as 3D tensors."""
193
+
194
+ def __init__(self, config):
195
+ super().__init__()
196
+ self.num_experts = config.num_experts
197
+ self.hidden_dim = config.hidden_size
198
+ self.intermediate_dim = config.moe_intermediate_size
199
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
200
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
201
+ self.act_fn = ACT2FN[config.hidden_act]
202
+
203
+ def forward(
204
+ self,
205
+ hidden_states: torch.Tensor,
206
+ top_k_index: torch.Tensor,
207
+ top_k_weights: torch.Tensor,
208
+ ) -> torch.Tensor:
209
+ final_hidden_states = torch.zeros_like(hidden_states)
210
+ with torch.no_grad():
211
+ expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=self.num_experts)
212
+ expert_mask = expert_mask.permute(2, 1, 0)
213
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
214
+
215
+ for expert_idx in expert_hit:
216
+ expert_idx = expert_idx[0]
217
+ if expert_idx == self.num_experts:
218
+ continue
219
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
220
+ current_state = hidden_states[token_idx]
221
+ gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
222
+ current_hidden_states = self.act_fn(gate) * up
223
+ current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
224
+ current_hidden_states = current_hidden_states * top_k_weights[token_idx, top_k_pos, None]
225
+ final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
226
+
227
+ return final_hidden_states
228
+
229
+
230
+ class LagunaSparseMoeBlock(nn.Module):
231
+ """Dense replacement for Laguna's routed MoE block.
232
+
233
+ The class name is intentionally kept as LagunaSparseMoeBlock so the existing
234
+ LagunaDecoderLayer can instantiate it without changing the rest of the model.
235
+ """
236
+
237
+ def __init__(self, config: LagunaConfig):
238
+ super().__init__()
239
+ routed_width = config.num_experts_per_tok * config.moe_intermediate_size
240
+ self.routed_dense = LagunaMLP(config, intermediate_size=routed_width)
241
+ self.shared_experts = LagunaMLP(config, intermediate_size=config.shared_expert_intermediate_size)
242
+ self.routed_scaling_factor = config.moe_routed_scaling_factor
243
+
244
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
245
+ routed_output = self.routed_dense(hidden_states) * self.routed_scaling_factor
246
+ shared_output = self.shared_experts(hidden_states)
247
+ return routed_output + shared_output
248
+
249
+
250
+ def rotate_half(x):
251
+ """Rotates half the hidden dims of the input."""
252
+ x1 = x[..., : x.shape[-1] // 2]
253
+ x2 = x[..., x.shape[-1] // 2 :]
254
+ return torch.cat((-x2, x1), dim=-1)
255
+
256
+
257
+ # Adapted from transformers.models.glm.modular_glm.apply_rotary_pos_emb
258
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
259
+ """Applies Rotary Position Embedding to the query and key tensors.
260
+
261
+ Removes the interleaving of cos and sin from GLM
262
+
263
+ Args:
264
+ q (`torch.Tensor`): The query tensor.
265
+ k (`torch.Tensor`): The key tensor.
266
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
267
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
268
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
269
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
270
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
271
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
272
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
273
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
274
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
275
+ Returns:
276
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
277
+ """
278
+ cos = cos.unsqueeze(unsqueeze_dim)
279
+ sin = sin.unsqueeze(unsqueeze_dim)
280
+
281
+ # Keep half or full tensor for later concatenation
282
+ rotary_dim = cos.shape[-1]
283
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
284
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
285
+
286
+ # Apply rotary embeddings on the first half or full tensor
287
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
288
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
289
+
290
+ # Concatenate back to full shape
291
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
292
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
293
+ return q_embed, k_embed
294
+
295
+
296
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
297
+ """
298
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
299
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
300
+ """
301
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
302
+ if n_rep == 1:
303
+ return hidden_states
304
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
305
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
306
+
307
+
308
+ def eager_attention_forward(
309
+ module: nn.Module,
310
+ query: torch.Tensor,
311
+ key: torch.Tensor,
312
+ value: torch.Tensor,
313
+ attention_mask: torch.Tensor | None,
314
+ scaling: float,
315
+ dropout: float = 0.0,
316
+ **kwargs: Unpack[TransformersKwargs],
317
+ ):
318
+ key_states = repeat_kv(key, module.num_key_value_groups)
319
+ value_states = repeat_kv(value, module.num_key_value_groups)
320
+
321
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
322
+ if attention_mask is not None:
323
+ attn_weights = attn_weights + attention_mask
324
+
325
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
326
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
327
+ attn_output = torch.matmul(attn_weights, value_states)
328
+ attn_output = attn_output.transpose(1, 2).contiguous()
329
+
330
+ return attn_output, attn_weights
331
+
332
+
333
+ @use_kernelized_func(apply_rotary_pos_emb)
334
+ class LagunaAttention(nn.Module):
335
+ """Afmoe-style SWA/GQA attention with Laguna-specific gating and per-layer head count."""
336
+
337
+ def __init__(self, config: LagunaConfig, layer_idx: int, num_heads: int):
338
+ super().__init__()
339
+ # Number of heads is controlled via `config.num_attention_heads_per_layer` which is passed from the parent for the specific layer
340
+ self.num_heads = num_heads
341
+ self.config = config
342
+ self.layer_idx = layer_idx
343
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
344
+ self.num_key_value_groups = self.num_heads // config.num_key_value_heads
345
+ self.scaling = self.head_dim**-0.5
346
+ self.attention_dropout = config.attention_dropout
347
+ self.is_causal = True
348
+
349
+ # Per-layer head count: rebuild q_proj and o_proj using self.num_heads (parent uses config.num_attention_heads).
350
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
351
+ self.k_proj = nn.Linear(
352
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
353
+ )
354
+ self.v_proj = nn.Linear(
355
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
356
+ )
357
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
358
+ # Parent LlamaAttention already sets: layer_idx, num_heads, num_key_value_heads, num_key_value_groups, head_dim
359
+ # We only add Laguna-specific attributes
360
+ self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
361
+ self.sliding_window = config.sliding_window if self.is_local_attention else None
362
+
363
+ self.q_norm = LagunaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
364
+ self.k_norm = LagunaRMSNorm(self.head_dim, eps=config.rms_norm_eps)
365
+ self.g_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
366
+
367
+ def forward(
368
+ self,
369
+ hidden_states: torch.Tensor,
370
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
371
+ attention_mask: torch.Tensor | None,
372
+ past_key_values: Cache | None = None,
373
+ **kwargs: Unpack[FlashAttentionKwargs],
374
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
375
+ input_shape = hidden_states.shape[:-1]
376
+ hidden_shape = (*input_shape, -1, self.head_dim)
377
+
378
+ query_states = self.q_proj(hidden_states).view(hidden_shape)
379
+ key_states = self.k_proj(hidden_states).view(hidden_shape)
380
+ value_states = self.v_proj(hidden_states).view(hidden_shape)
381
+
382
+ query_states = self.q_norm(query_states).transpose(1, 2)
383
+ key_states = self.k_norm(key_states).transpose(1, 2)
384
+ value_states = value_states.transpose(1, 2)
385
+
386
+ cos, sin = position_embeddings
387
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
388
+
389
+ if past_key_values is not None:
390
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
391
+
392
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
393
+ self.config._attn_implementation, eager_attention_forward
394
+ )
395
+ attn_output, attn_weights = attention_interface(
396
+ self,
397
+ query_states,
398
+ key_states,
399
+ value_states,
400
+ attention_mask,
401
+ dropout=0.0 if not self.training else self.attention_dropout,
402
+ scaling=self.scaling,
403
+ sliding_window=self.sliding_window,
404
+ **kwargs,
405
+ )
406
+
407
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
408
+
409
+ gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
410
+ attn_output = (attn_output.view(*input_shape, -1, self.head_dim) * gate.unsqueeze(-1)).view(*input_shape, -1)
411
+
412
+ attn_output = self.o_proj(attn_output)
413
+ return attn_output, attn_weights
414
+
415
+
416
+ class LagunaDecoderLayer(GradientCheckpointingLayer):
417
+ def __init__(self, config: LagunaConfig, layer_idx: int):
418
+ super().__init__()
419
+ self.hidden_size = config.hidden_size
420
+ self.self_attn = LagunaAttention(config, layer_idx, config.num_attention_heads_per_layer[layer_idx])
421
+ if config.mlp_layer_types[layer_idx] == "sparse":
422
+ self.mlp = LagunaSparseMoeBlock(config)
423
+ else:
424
+ self.mlp = LagunaMLP(config, intermediate_size=config.intermediate_size)
425
+ self.input_layernorm = LagunaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
426
+ self.post_attention_layernorm = LagunaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
427
+
428
+ def forward(
429
+ self,
430
+ hidden_states: torch.Tensor,
431
+ attention_mask: torch.Tensor | None = None,
432
+ position_ids: torch.LongTensor | None = None,
433
+ past_key_values: Cache | None = None,
434
+ use_cache: bool | None = False,
435
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
436
+ **kwargs: Unpack[TransformersKwargs],
437
+ ) -> torch.Tensor:
438
+ residual = hidden_states
439
+ hidden_states = self.input_layernorm(hidden_states)
440
+ # Self Attention
441
+ hidden_states, _ = self.self_attn(
442
+ hidden_states=hidden_states,
443
+ attention_mask=attention_mask,
444
+ position_ids=position_ids,
445
+ past_key_values=past_key_values,
446
+ use_cache=use_cache,
447
+ position_embeddings=position_embeddings,
448
+ **kwargs,
449
+ )
450
+ hidden_states = residual + hidden_states
451
+
452
+ # Fully Connected
453
+ residual = hidden_states
454
+ hidden_states = self.post_attention_layernorm(hidden_states)
455
+ hidden_states = self.mlp(hidden_states)
456
+ hidden_states = residual + hidden_states
457
+ return hidden_states
458
+
459
+
460
+ @auto_docstring
461
+ class LagunaPreTrainedModel(PreTrainedModel):
462
+ config: LagunaConfig
463
+ base_model_prefix = "model"
464
+ supports_gradient_checkpointing = True
465
+ _no_split_modules = ["LagunaDecoderLayer"]
466
+ _skip_keys_device_placement = ["past_key_values"]
467
+ _supports_flash_attn = True
468
+ _supports_sdpa = True
469
+ _supports_flex_attn = True
470
+
471
+ _can_compile_fullgraph = True
472
+ _supports_attention_backend = True
473
+ _can_record_outputs = {
474
+ "router_logits": OutputRecorder(LagunaTopKRouter, index=0),
475
+ "hidden_states": LagunaDecoderLayer,
476
+ "attentions": LagunaAttention,
477
+ }
478
+
479
+ @torch.no_grad()
480
+ def _init_weights(self, module):
481
+ super()._init_weights(module)
482
+ std = self.config.initializer_range
483
+ if isinstance(module, LagunaExperts):
484
+ init.normal_(module.gate_up_proj, mean=0.0, std=std)
485
+ init.normal_(module.down_proj, mean=0.0, std=std)
486
+ elif isinstance(module, LagunaTopKRouter):
487
+ init.normal_(module.weight, mean=0.0, std=std)
488
+ if isinstance(module, LagunaTopKRouter):
489
+ torch.nn.init.zeros_(module.e_score_correction_bias)
490
+ elif isinstance(module, LagunaRotaryEmbedding):
491
+ for layer_type in module.layer_types:
492
+ rope_init_fn = module.compute_default_rope_parameters
493
+ if module.rope_type[layer_type] != "default":
494
+ rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]]
495
+ curr_inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type)
496
+ init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq)
497
+ init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq)
498
+
499
+
500
+ @auto_docstring
501
+ class LagunaModel(LagunaPreTrainedModel):
502
+ def __init__(self, config: LagunaConfig):
503
+ super().__init__(config)
504
+ self.padding_idx = config.pad_token_id
505
+ self.vocab_size = config.vocab_size
506
+
507
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
508
+ self.layers = nn.ModuleList(
509
+ [LagunaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
510
+ )
511
+ self.norm = LagunaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
512
+ self.rotary_emb = LagunaRotaryEmbedding(config=config)
513
+ self.gradient_checkpointing = False
514
+
515
+ # Initialize weights and apply final processing
516
+ self.post_init()
517
+
518
+ @capture_outputs
519
+ @auto_docstring
520
+ def forward(
521
+ self,
522
+ input_ids: torch.LongTensor | None = None,
523
+ attention_mask: torch.Tensor | None = None,
524
+ position_ids: torch.LongTensor | None = None,
525
+ past_key_values: Cache | None = None,
526
+ inputs_embeds: torch.FloatTensor | None = None,
527
+ use_cache: bool | None = None,
528
+ **kwargs: Unpack[TransformersKwargs],
529
+ ) -> MoeModelOutputWithPast:
530
+ if (input_ids is None) ^ (inputs_embeds is not None):
531
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
532
+
533
+ if inputs_embeds is None:
534
+ inputs_embeds = self.embed_tokens(input_ids)
535
+
536
+ if use_cache and past_key_values is None:
537
+ past_key_values = DynamicCache(config=self.config)
538
+
539
+ if position_ids is None:
540
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
541
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
542
+ position_ids = position_ids.unsqueeze(0)
543
+
544
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
545
+ mask_kwargs = {
546
+ "config": self.config,
547
+ "inputs_embeds": inputs_embeds,
548
+ "attention_mask": attention_mask,
549
+ "past_key_values": past_key_values,
550
+ "position_ids": position_ids,
551
+ }
552
+ mask_creation_functions = {
553
+ "full_attention": lambda: create_causal_mask(**mask_kwargs),
554
+ "sliding_attention": lambda: create_sliding_window_causal_mask(**mask_kwargs),
555
+ }
556
+ causal_mask_mapping = {}
557
+ for layer_type in set(self.config.layer_types):
558
+ causal_mask_mapping[layer_type] = mask_creation_functions[layer_type]()
559
+
560
+ hidden_states = inputs_embeds
561
+ position_embeddings = {}
562
+ for layer_type in set(self.config.layer_types):
563
+ position_embeddings[layer_type] = self.rotary_emb(hidden_states, position_ids, layer_type)
564
+
565
+ for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
566
+ hidden_states = decoder_layer(
567
+ hidden_states,
568
+ attention_mask=causal_mask_mapping[self.config.layer_types[i]],
569
+ position_embeddings=position_embeddings[self.config.layer_types[i]],
570
+ position_ids=position_ids,
571
+ past_key_values=past_key_values,
572
+ **kwargs,
573
+ )
574
+
575
+ hidden_states = self.norm(hidden_states)
576
+
577
+ return MoeModelOutputWithPast(
578
+ last_hidden_state=hidden_states,
579
+ past_key_values=past_key_values if use_cache else None,
580
+ )
581
+
582
+
583
+ def load_balancing_loss_func(
584
+ gate_logits: torch.Tensor | tuple[torch.Tensor] | None,
585
+ num_experts: int | None = None,
586
+ top_k=2,
587
+ attention_mask: torch.Tensor | None = None,
588
+ ) -> torch.Tensor | int:
589
+ r"""
590
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
591
+
592
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
593
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
594
+ experts is too unbalanced.
595
+
596
+ Args:
597
+ gate_logits:
598
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
599
+ shape [batch_size X sequence_length, num_experts].
600
+ num_experts:
601
+ Number of experts
602
+ top_k:
603
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
604
+ parameter.
605
+ attention_mask (`torch.Tensor`, *optional*):
606
+ The attention_mask used in forward function
607
+ shape [batch_size X sequence_length] if not None.
608
+
609
+ Returns:
610
+ The auxiliary loss.
611
+ """
612
+ if gate_logits is None or not isinstance(gate_logits, tuple):
613
+ return 0
614
+
615
+ if isinstance(gate_logits, tuple):
616
+ compute_device = gate_logits[0].device
617
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
618
+
619
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
620
+
621
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
622
+
623
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
624
+
625
+ if attention_mask is None:
626
+ # Compute the percentage of tokens routed to each experts
627
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
628
+
629
+ # Compute the average probability of routing to these experts
630
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
631
+ else:
632
+ batch_size, sequence_length = attention_mask.shape
633
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
634
+
635
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
636
+ expert_attention_mask = (
637
+ attention_mask[None, :, :, None, None]
638
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
639
+ .reshape(-1, top_k, num_experts)
640
+ .to(compute_device)
641
+ )
642
+
643
+ # Compute the percentage of tokens routed to each experts
644
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
645
+ expert_attention_mask, dim=0
646
+ )
647
+
648
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
649
+ router_per_expert_attention_mask = (
650
+ attention_mask[None, :, :, None]
651
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
652
+ .reshape(-1, num_experts)
653
+ .to(compute_device)
654
+ )
655
+
656
+ # Compute the average probability of routing to these experts
657
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
658
+ router_per_expert_attention_mask, dim=0
659
+ )
660
+
661
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
662
+ return overall_loss * num_experts
663
+
664
+
665
+ @auto_docstring
666
+ class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
667
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
668
+ _tp_plan = {"lm_head": "colwise_gather_output"}
669
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
670
+
671
+ def __init__(self, config):
672
+ super().__init__(config)
673
+ self.model = LagunaModel(config)
674
+ self.vocab_size = config.vocab_size
675
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
676
+ self.router_aux_loss_coef = config.router_aux_loss_coef
677
+ self.num_experts = config.num_experts
678
+ self.num_experts_per_tok = config.num_experts_per_tok
679
+
680
+ # Initialize weights and apply final processing
681
+ self.post_init()
682
+
683
+ @can_return_tuple
684
+ @auto_docstring
685
+ def forward(
686
+ self,
687
+ input_ids: torch.LongTensor | None = None,
688
+ attention_mask: torch.Tensor | None = None,
689
+ position_ids: torch.LongTensor | None = None,
690
+ past_key_values: Cache | None = None,
691
+ inputs_embeds: torch.FloatTensor | None = None,
692
+ labels: torch.LongTensor | None = None,
693
+ use_cache: bool | None = None,
694
+ output_router_logits: bool | None = None,
695
+ logits_to_keep: int | torch.Tensor = 0,
696
+ **kwargs: Unpack[TransformersKwargs],
697
+ ) -> MoeCausalLMOutputWithPast:
698
+ r"""
699
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
700
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
701
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
702
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
703
+ """
704
+
705
+ output_router_logits = (
706
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
707
+ )
708
+
709
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
710
+ outputs: MoeModelOutputWithPast = self.model(
711
+ input_ids=input_ids,
712
+ attention_mask=attention_mask,
713
+ position_ids=position_ids,
714
+ past_key_values=past_key_values,
715
+ inputs_embeds=inputs_embeds,
716
+ use_cache=use_cache,
717
+ output_router_logits=output_router_logits,
718
+ **kwargs,
719
+ )
720
+
721
+ hidden_states = outputs.last_hidden_state
722
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
723
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
724
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
725
+
726
+ loss = None
727
+ if labels is not None:
728
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
729
+
730
+ aux_loss = None
731
+ if output_router_logits:
732
+ aux_loss = load_balancing_loss_func(
733
+ outputs.router_logits,
734
+ self.num_experts,
735
+ self.num_experts_per_tok,
736
+ attention_mask,
737
+ )
738
+ if labels is not None:
739
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
740
+
741
+ return MoeCausalLMOutputWithPast(
742
+ loss=loss,
743
+ aux_loss=aux_loss,
744
+ logits=logits,
745
+ past_key_values=outputs.past_key_values,
746
+ hidden_states=outputs.hidden_states,
747
+ attentions=outputs.attentions,
748
+ router_logits=outputs.router_logits,
749
+ )
750
+
751
+
752
+ __all__ = ["LagunaForCausalLM", "LagunaModel", "LagunaPreTrainedModel"]