spitfire4794 commited on
Commit
7b59061
·
verified ·
1 Parent(s): 51b8c43

Blaze-Title — FFT on Qyrou 115K + Wild 130K (70/30, wild deduped), lr=0.0003, 1 epoch, seq 2048, assistant-only loss, compile default

Browse files
Files changed (2) hide show
  1. configuration_blaze.py +23 -0
  2. modeling_blaze.py +719 -0
configuration_blaze.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from transformers import LlamaConfig
3
+
4
+ class BlazeConfig(LlamaConfig):
5
+ model_type = "blaze"
6
+ def __init__(self, *args, xsa_projection=True, rope_theta=10000.0, attention_bias=False,
7
+ prelude_layers=1, recurrent_layers=12, coda_layers=1,
8
+ recurrent_passes=2,
9
+ gradient_checkpointing=False, use_flash_attn=True, **kwargs):
10
+ kwargs["num_hidden_layers"] = prelude_layers + recurrent_layers + coda_layers
11
+ kwargs.setdefault("use_cache", False)
12
+ super().__init__(*args, rope_theta=rope_theta, attention_bias=attention_bias, **kwargs)
13
+ self.xsa_projection = xsa_projection
14
+ self.rope_theta = rope_theta
15
+ self.attention_bias = attention_bias
16
+ self.prelude_layers = prelude_layers
17
+ self.recurrent_layers = recurrent_layers
18
+ self.coda_layers = coda_layers
19
+ self.recurrent_passes = recurrent_passes
20
+ self.gradient_checkpointing = gradient_checkpointing
21
+ self.use_flash_attn = use_flash_attn
22
+ if not hasattr(self, 'rope_parameters') or self.rope_parameters is None:
23
+ self.rope_parameters = {"rope_type": "default", "factor": 1.0, "rope_theta": rope_theta}
modeling_blaze.py ADDED
@@ -0,0 +1,719 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 SurjoLabs and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import math
17
+ from typing import Optional, Tuple, Union, List
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+ import torch.utils.checkpoint
23
+ from transformers import LlamaConfig, LlamaModel, LlamaForCausalLM
24
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm, LlamaMLP
25
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
26
+ from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
27
+ from transformers.cache_utils import DynamicCache, Cache
28
+
29
+ try:
30
+ from .configuration_blaze import BlazeConfig
31
+ except ImportError:
32
+ from configuration_blaze import BlazeConfig
33
+
34
+ # Safe Flash Attention imports with fallback
35
+ try:
36
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
37
+ FLASH_ATTN_AVAILABLE = True
38
+ except ImportError:
39
+ try:
40
+ from flash_attn import flash_attn_varlen_func
41
+ flash_attn_func = None
42
+ FLASH_ATTN_AVAILABLE = True
43
+ except ImportError:
44
+ flash_attn_func = None
45
+ flash_attn_varlen_func = None
46
+ FLASH_ATTN_AVAILABLE = False
47
+
48
+
49
+ @torch._dynamo.disable()
50
+ def _flash_varlen(q, k, v, cu_seqlens, max_seqlen, dropout_p):
51
+ ms = int(max_seqlen.item()) if torch.is_tensor(max_seqlen) else int(max_seqlen)
52
+ return flash_attn_varlen_func(
53
+ q, k, v, cu_seqlens, cu_seqlens, ms, ms,
54
+ dropout_p=dropout_p, causal=True,
55
+ )
56
+
57
+
58
+ @torch._dynamo.disable()
59
+ def _flash_attn(q, k, v, dropout_p, causal):
60
+ return flash_attn_func(
61
+ q, k, v, dropout_p=dropout_p, causal=causal,
62
+ )
63
+
64
+
65
+ class ClampedLlamaMLP(LlamaMLP):
66
+ def forward(self, x):
67
+ gate = F.silu(self.gate_proj(x).clamp(-15.0, 15.0))
68
+ up = self.up_proj(x)
69
+ return self.down_proj(gate * up)
70
+
71
+
72
+ class XSAAttention(nn.Module):
73
+ def __init__(self, config, layer_idx=None):
74
+ super().__init__()
75
+ self.config = config
76
+ self.layer_idx = layer_idx
77
+ self.recurrent_cache_idx = None
78
+ self._use_recurrent_slot = False
79
+ self._current_pass = 0
80
+ self.hidden_size = config.hidden_size
81
+ self.num_heads = config.num_attention_heads
82
+ self.num_key_value_heads = config.num_key_value_heads
83
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
84
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
85
+ self.attention_bias = getattr(config, "attention_bias", False)
86
+
87
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=self.attention_bias)
88
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
89
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=self.attention_bias)
90
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=self.attention_bias)
91
+
92
+ self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
93
+ self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
94
+
95
+ def forward(
96
+ self,
97
+ hidden_states: torch.Tensor,
98
+ attention_mask: Optional[torch.Tensor] = None,
99
+ position_ids: Optional[torch.LongTensor] = None,
100
+ past_key_value: Optional[Union[Cache, Tuple[torch.Tensor]]] = None,
101
+ output_attentions: bool = False,
102
+ use_cache: bool = False,
103
+ cache_position: Optional[torch.LongTensor] = None,
104
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
105
+ expected_batch_size: Optional[int] = None,
106
+ cu_seqlens: Optional[torch.Tensor] = None,
107
+ max_seqlen: Optional[Union[int, torch.Tensor]] = None,
108
+ has_padding: bool = False,
109
+ **kwargs,
110
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
111
+ past_kv = past_key_value if past_key_value is not None else kwargs.get("past_key_values", None)
112
+
113
+ if hidden_states.ndim == 2:
114
+ if expected_batch_size is None:
115
+ raise RuntimeError(
116
+ f"XSAAttention received 2D hidden_states {hidden_states.shape} "
117
+ f"without an expected_batch_size to safely restore the batch dim."
118
+ )
119
+ hidden_states = hidden_states.reshape(expected_batch_size, -1, self.hidden_size)
120
+
121
+ bsz, q_len, _ = hidden_states.size()
122
+
123
+ if expected_batch_size is not None and bsz != expected_batch_size:
124
+ raise RuntimeError(
125
+ f"XSAAttention: hidden_states batch size {bsz} does not match "
126
+ f"expected_batch_size {expected_batch_size}."
127
+ )
128
+
129
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
130
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
131
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim)
132
+
133
+ query_states = self.q_norm(query_states)
134
+ key_states = self.k_norm(key_states)
135
+
136
+ cos, sin = position_embeddings
137
+
138
+ # 1. Packed Sequence Varlen Flash Attention
139
+ use_flash_varlen = (
140
+ cu_seqlens is not None
141
+ and past_kv is None
142
+ and (getattr(self.config, "use_flash_attn", False) or getattr(self.config, "_attn_implementation", "") == "flash_attention_2")
143
+ and FLASH_ATTN_AVAILABLE
144
+ and flash_attn_varlen_func is not None
145
+ )
146
+
147
+ if use_flash_varlen:
148
+ total = bsz * q_len
149
+ q = query_states.reshape(total, self.num_heads, self.head_dim).to(torch.bfloat16)
150
+ k = key_states.reshape(total, self.num_key_value_heads, self.head_dim).to(torch.bfloat16)
151
+ v = value_states.reshape(total, self.num_key_value_heads, self.head_dim).to(torch.bfloat16)
152
+
153
+ cos_f = cos.reshape(-1, cos.shape[-1]).to(torch.bfloat16)
154
+ sin_f = sin.reshape(-1, sin.shape[-1]).to(torch.bfloat16)
155
+ q, k = apply_rotary_pos_emb(q, k, cos_f, sin_f, unsqueeze_dim=1)
156
+
157
+ attn_output = _flash_varlen(
158
+ q, k, v, cu_seqlens, max_seqlen,
159
+ self.config.attention_dropout if self.training else 0.0,
160
+ )
161
+
162
+ if getattr(self.config, 'xsa_projection', True):
163
+ y = attn_output.view(total, self.num_key_value_heads, self.num_key_value_groups, self.head_dim)
164
+ v_grouped = v.unsqueeze(2)
165
+ dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
166
+ dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
167
+ scale = (dot_yv / dot_vv).to(y.dtype)
168
+ attn_output = (y - scale * v_grouped).reshape(total, self.num_heads, self.head_dim)
169
+
170
+ attn_output = self.o_proj(attn_output.reshape(bsz, q_len, self.hidden_size))
171
+ return (attn_output, None)
172
+
173
+ # 2. Standard Attention & KV Caching
174
+ query_states = query_states.transpose(1, 2)
175
+ key_states = key_states.transpose(1, 2)
176
+ value_states = value_states.transpose(1, 2)
177
+
178
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
179
+ current_v = value_states
180
+
181
+ target_idx = self.layer_idx
182
+ if getattr(self, "_use_recurrent_slot", False) and self.recurrent_cache_idx is not None:
183
+ pass_offset = max(0, getattr(self, "_current_pass", 1) - 1)
184
+ target_idx = self.recurrent_cache_idx + pass_offset * getattr(self.config, "recurrent_layers", 1)
185
+
186
+ # Pre-allocate cache slots in bulk without per-token Python overhead
187
+ if past_kv is not None:
188
+ if hasattr(past_kv, "layers"):
189
+ curr_len = len(past_kv.layers)
190
+ if curr_len <= target_idx:
191
+ layer_cls = getattr(past_kv, "layer_class_to_replicate", None)
192
+ if layer_cls is None and curr_len > 0:
193
+ layer_cls = past_kv.layers[0].__class__
194
+ if layer_cls is None:
195
+ from transformers.cache_utils import DynamicLayer
196
+ layer_cls = DynamicLayer
197
+ past_kv.layers.extend([layer_cls() for _ in range(target_idx - curr_len + 1)])
198
+ elif hasattr(past_kv, "key_cache"):
199
+ curr_len = len(past_kv.key_cache)
200
+ if curr_len <= target_idx:
201
+ num_to_add = target_idx - curr_len + 1
202
+ past_kv.key_cache.extend([
203
+ torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=key_states.dtype, device=key_states.device)
204
+ for _ in range(num_to_add)
205
+ ])
206
+ past_kv.value_cache.extend([
207
+ torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=value_states.dtype, device=value_states.device)
208
+ for _ in range(num_to_add)
209
+ ])
210
+ else:
211
+ while len(past_kv) <= target_idx:
212
+ past_kv.update(
213
+ torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=key_states.dtype, device=key_states.device),
214
+ torch.empty(bsz, self.num_key_value_heads, 0, self.head_dim, dtype=value_states.dtype, device=value_states.device),
215
+ len(past_kv)
216
+ )
217
+ key_states, value_states = past_kv.update(key_states, value_states, target_idx)
218
+
219
+ kv_len = key_states.shape[-2]
220
+
221
+ is_flash_enabled = getattr(self.config, "use_flash_attn", False) or getattr(self.config, "_attn_implementation", "") == "flash_attention_2"
222
+ use_flash_func = (
223
+ FLASH_ATTN_AVAILABLE
224
+ and flash_attn_func is not None
225
+ and is_flash_enabled
226
+ and query_states.is_cuda
227
+ and not has_padding
228
+ and (attention_mask is None or attention_mask.ndim == 2)
229
+ and (q_len == 1 or kv_len == q_len)
230
+ )
231
+
232
+ attn_output = None
233
+ if use_flash_func:
234
+ try:
235
+ q_fa = query_states.transpose(1, 2)
236
+ k_fa = key_states.transpose(1, 2)
237
+ v_fa = value_states.transpose(1, 2)
238
+
239
+ orig_dtype = q_fa.dtype
240
+ if orig_dtype not in (torch.float16, torch.bfloat16):
241
+ target_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
242
+ q_fa = q_fa.to(target_dtype)
243
+ k_fa = k_fa.to(target_dtype)
244
+ v_fa = v_fa.to(target_dtype)
245
+
246
+ causal = (q_len > 1 and kv_len == q_len)
247
+ drop_p = self.config.attention_dropout if self.training else 0.0
248
+ out_fa = _flash_attn(q_fa, k_fa, v_fa, drop_p, causal)
249
+ if orig_dtype not in (torch.float16, torch.bfloat16):
250
+ out_fa = out_fa.to(orig_dtype)
251
+
252
+ attn_output = out_fa.transpose(1, 2)
253
+ except Exception:
254
+ attn_output = None
255
+
256
+ if attn_output is None:
257
+ key_states_sdpa = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
258
+ value_states_sdpa = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
259
+
260
+ is_causal = False
261
+ attn_mask = None
262
+
263
+ if attention_mask is not None:
264
+ if attention_mask.ndim == 2:
265
+ if has_padding:
266
+ if attention_mask.shape[-1] < kv_len:
267
+ attention_mask = F.pad(attention_mask, (0, kv_len - attention_mask.shape[-1]), value=1)
268
+ elif attention_mask.shape[-1] > kv_len:
269
+ attention_mask = attention_mask[:, -kv_len:]
270
+
271
+ pad_mask = (1.0 - attention_mask[:, None, None, :].to(query_states.dtype)) * torch.finfo(query_states.dtype).min
272
+
273
+ if q_len > 1:
274
+ if cache_position is None:
275
+ cache_position = torch.arange(kv_len - q_len, kv_len, device=query_states.device)
276
+ kv_positions = torch.arange(kv_len, device=query_states.device)
277
+
278
+ neg_inf = torch.finfo(query_states.dtype).min
279
+ causal_mask = torch.zeros((q_len, kv_len), dtype=query_states.dtype, device=query_states.device)
280
+ causal_mask = causal_mask.masked_fill(kv_positions[None, :] > cache_position[:, None], neg_inf)
281
+ attn_mask = causal_mask[None, None, :, :] + pad_mask
282
+
283
+ diag_idx = torch.arange(q_len, device=attn_mask.device)
284
+ start_idx = attn_mask.shape[-1] - q_len
285
+ attn_mask[:, :, diag_idx, start_idx + diag_idx] = 0.0
286
+ else:
287
+ attn_mask = pad_mask
288
+ is_causal = False
289
+ else:
290
+ if q_len > 1 and kv_len == q_len:
291
+ is_causal = True
292
+ attn_mask = None
293
+ elif q_len > 1:
294
+ if cache_position is None:
295
+ cache_position = torch.arange(kv_len - q_len, kv_len, device=query_states.device)
296
+ kv_positions = torch.arange(kv_len, device=query_states.device)
297
+ causal_mask = torch.zeros((q_len, kv_len), dtype=query_states.dtype, device=query_states.device)
298
+ causal_mask = causal_mask.masked_fill(kv_positions[None, :] > cache_position[:, None], torch.finfo(query_states.dtype).min)
299
+ attn_mask = causal_mask[None, None, :, :]
300
+ is_causal = False
301
+ else:
302
+ is_causal = False
303
+ attn_mask = None
304
+ elif attention_mask.ndim == 4:
305
+ attn_mask = attention_mask.to(dtype=query_states.dtype)
306
+ is_causal = False
307
+ elif attention_mask.ndim == 3:
308
+ attn_mask = attention_mask.unsqueeze(1).to(dtype=query_states.dtype)
309
+ is_causal = False
310
+ else:
311
+ if q_len > 1 and kv_len == q_len:
312
+ is_causal = True
313
+ attn_mask = None
314
+ elif q_len > 1:
315
+ if cache_position is None:
316
+ cache_position = torch.arange(kv_len - q_len, kv_len, device=query_states.device)
317
+ kv_positions = torch.arange(kv_len, device=query_states.device)
318
+ causal_mask = torch.zeros((q_len, kv_len), dtype=query_states.dtype, device=query_states.device)
319
+ causal_mask = causal_mask.masked_fill(kv_positions[None, :] > cache_position[:, None], torch.finfo(query_states.dtype).min)
320
+ attn_mask = causal_mask[None, None, :, :]
321
+ is_causal = False
322
+ else:
323
+ # Single-token decode attends to all past tokens without causal truncation
324
+ is_causal = False
325
+ attn_mask = None
326
+
327
+ attn_output = F.scaled_dot_product_attention(
328
+ query_states, key_states_sdpa, value_states_sdpa, attn_mask=attn_mask,
329
+ dropout_p=0.0 if not self.training else self.config.attention_dropout, is_causal=is_causal
330
+ )
331
+
332
+ if getattr(self.config, 'xsa_projection', True):
333
+ y = attn_output.reshape(bsz, self.num_key_value_heads, self.num_key_value_groups, q_len, self.head_dim)
334
+ v_grouped = current_v.unsqueeze(2)
335
+ dot_yv = (y * v_grouped).sum(dim=-1, keepdim=True).float()
336
+ dot_vv = v_grouped.pow(2).sum(dim=-1, keepdim=True).clamp_min(1e-4).float()
337
+ scale = (dot_yv / dot_vv).to(y.dtype)
338
+ attn_output = (y - scale * v_grouped).reshape(bsz, self.num_heads, q_len, self.head_dim)
339
+
340
+ attn_output = attn_output.transpose(1, 2).contiguous()
341
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
342
+ attn_output = self.o_proj(attn_output)
343
+
344
+ return (attn_output, None)
345
+
346
+
347
+ @torch._dynamo.disable()
348
+ def _checkpointed_layer_forward(
349
+ layer, hidden_states, attention_mask, position_ids,
350
+ cache_position, cos, sin, expected_batch_size, cu_seqlens, max_seqlen
351
+ ):
352
+ out = layer(
353
+ hidden_states, attention_mask=attention_mask, position_ids=position_ids,
354
+ past_key_value=None, use_cache=False,
355
+ cache_position=cache_position, position_embeddings=(cos, sin),
356
+ expected_batch_size=expected_batch_size,
357
+ cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
358
+ )
359
+ hs_out = out[0] if isinstance(out, tuple) else out
360
+ if hs_out.ndim != 3 or hs_out.shape[0] != expected_batch_size:
361
+ raise RuntimeError(
362
+ f"Layer output shape {tuple(hs_out.shape)} does not match expected "
363
+ f"batch size {expected_batch_size}."
364
+ )
365
+ return hs_out
366
+
367
+
368
+ class BlazeModel(LlamaModel):
369
+ def __init__(self, config):
370
+ super().__init__(config)
371
+
372
+ assert config.prelude_layers + config.recurrent_layers + config.coda_layers == config.num_hidden_layers, \
373
+ "prelude_layers + recurrent_layers + coda_layers must equal num_hidden_layers"
374
+
375
+ p1 = config.prelude_layers
376
+ r1 = p1 + config.recurrent_layers
377
+
378
+ for i, layer in enumerate(self.layers):
379
+ layer.self_attn = XSAAttention(config, layer_idx=i)
380
+ layer.mlp = ClampedLlamaMLP(config)
381
+
382
+ for i, layer in enumerate(self.layers[p1:r1]):
383
+ layer.self_attn.recurrent_cache_idx = config.num_hidden_layers + p1 + i
384
+
385
+ self.gradient_checkpointing = getattr(config, "gradient_checkpointing", False)
386
+
387
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
388
+ self.gradient_checkpointing = True
389
+
390
+ def gradient_checkpointing_disable(self):
391
+ self.gradient_checkpointing = False
392
+
393
+ def _get_cache_seq_length(self, past_key_values) -> int:
394
+ if past_key_values is None:
395
+ return 0
396
+ if hasattr(past_key_values, "get_seq_length"):
397
+ return past_key_values.get_seq_length(0)
398
+ return past_key_values[0][0].shape[-2] if len(past_key_values) > 0 else 0
399
+
400
+ def forward(
401
+ self,
402
+ input_ids: Optional[torch.LongTensor] = None,
403
+ attention_mask: Optional[torch.Tensor] = None,
404
+ position_ids: Optional[torch.LongTensor] = None,
405
+ inputs_embeds: Optional[torch.FloatTensor] = None,
406
+ past_key_values: Optional[Union[Cache, Tuple[torch.Tensor]]] = None,
407
+ use_cache: Optional[bool] = None,
408
+ output_attentions: Optional[bool] = False,
409
+ output_hidden_states: Optional[bool] = False,
410
+ return_dict: Optional[bool] = True,
411
+ cu_seqlens: Optional[torch.Tensor] = None,
412
+ max_seqlen: Optional[Union[int, torch.Tensor]] = None,
413
+ **kwargs,
414
+ ) -> BaseModelOutputWithPast:
415
+ cache_position = kwargs.get("cache_position", None)
416
+ if use_cache is None:
417
+ use_cache = getattr(self.config, "use_cache", False)
418
+
419
+ if inputs_embeds is None:
420
+ inputs_embeds = self.embed_tokens(input_ids)
421
+
422
+ bsz, seq_len = inputs_embeds.shape[0], inputs_embeds.shape[1]
423
+
424
+ if use_cache and past_key_values is None:
425
+ past_key_values = DynamicCache()
426
+ elif past_key_values is not None and not isinstance(past_key_values, DynamicCache):
427
+ if hasattr(DynamicCache, "from_legacy_cache"):
428
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
429
+
430
+ if cache_position is None:
431
+ past_seen = self._get_cache_seq_length(past_key_values) if past_key_values is not None else 0
432
+ cache_position = torch.arange(past_seen, past_seen + seq_len, dtype=torch.long, device=inputs_embeds.device)
433
+ elif cache_position.shape[-1] > seq_len:
434
+ cache_position = cache_position[-seq_len:]
435
+
436
+ if position_ids is None:
437
+ position_ids = cache_position.unsqueeze(0).expand(bsz, -1)
438
+ elif position_ids.shape[-1] > seq_len:
439
+ position_ids = position_ids[:, -seq_len:]
440
+
441
+ hidden_states = inputs_embeds
442
+ try:
443
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
444
+ except TypeError:
445
+ position_embeddings = self.rotary_emb(hidden_states, seq_len=seq_len)
446
+ cos, sin = position_embeddings
447
+
448
+ p1 = self.config.prelude_layers
449
+ r1 = p1 + self.config.recurrent_layers
450
+ c1 = r1 + self.config.coda_layers
451
+
452
+ prelude = self.layers[:p1]
453
+ recurrent = self.layers[p1:r1]
454
+ coda = self.layers[r1:c1]
455
+
456
+ use_ckpt = self.training and self.gradient_checkpointing and not use_cache
457
+
458
+ # Check padding ONCE per forward pass to avoid per-layer GPU-to-CPU stalls
459
+ has_padding = False
460
+ if attention_mask is not None and bsz > 1 and attention_mask.ndim == 2:
461
+ has_padding = bool((attention_mask == 0).any())
462
+
463
+ def run_layer(layer, hs):
464
+ if cu_seqlens is not None:
465
+ torch._dynamo.mark_dynamic(cu_seqlens, 0)
466
+
467
+ out = layer(
468
+ hs, attention_mask=attention_mask, position_ids=position_ids,
469
+ past_key_value=past_key_values if use_cache else None, use_cache=use_cache,
470
+ cache_position=cache_position, position_embeddings=position_embeddings,
471
+ expected_batch_size=bsz, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen,
472
+ has_padding=has_padding,
473
+ )
474
+ hs_out = out[0] if isinstance(out, tuple) else out
475
+ if hs_out.ndim != 3 or hs_out.shape[0] != bsz:
476
+ raise RuntimeError(
477
+ f"Layer output shape {tuple(hs_out.shape)} does not match expected "
478
+ f"batch size {bsz}."
479
+ )
480
+ return hs_out
481
+
482
+ def run_layer_maybe_ckpt(layer, hs):
483
+ if use_ckpt:
484
+ return torch.utils.checkpoint.checkpoint(
485
+ _checkpointed_layer_forward,
486
+ layer, hs, attention_mask, position_ids, cache_position, cos, sin, bsz,
487
+ cu_seqlens, max_seqlen,
488
+ use_reentrant=False,
489
+ )
490
+ return run_layer(layer, hs)
491
+
492
+ all_hidden_states = () if output_hidden_states else None
493
+
494
+ for layer in prelude:
495
+ if output_hidden_states:
496
+ all_hidden_states += (hidden_states,)
497
+ hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
498
+
499
+ recurrent_passes = getattr(self.config, "recurrent_passes", 2)
500
+ for pass_idx in range(recurrent_passes):
501
+ if self.training:
502
+ hidden_states = hidden_states + torch.randn_like(hidden_states) * 0.02
503
+
504
+ is_recurrent_slot = pass_idx > 0
505
+
506
+ for layer in recurrent:
507
+ if output_hidden_states:
508
+ all_hidden_states += (hidden_states,)
509
+ layer.self_attn._use_recurrent_slot = is_recurrent_slot
510
+ layer.self_attn._current_pass = pass_idx
511
+ try:
512
+ hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
513
+ finally:
514
+ layer.self_attn._use_recurrent_slot = False
515
+ layer.self_attn._current_pass = 0
516
+
517
+ for layer in coda:
518
+ if output_hidden_states:
519
+ all_hidden_states += (hidden_states,)
520
+ hidden_states = run_layer_maybe_ckpt(layer, hidden_states)
521
+
522
+ hidden_states = self.norm(hidden_states)
523
+
524
+ if output_hidden_states:
525
+ all_hidden_states += (hidden_states,)
526
+
527
+ if not return_dict:
528
+ return tuple(v for v in [hidden_states, past_key_values if use_cache else None, all_hidden_states] if v is not None)
529
+
530
+ return BaseModelOutputWithPast(
531
+ last_hidden_state=hidden_states,
532
+ past_key_values=past_key_values if use_cache else None,
533
+ hidden_states=all_hidden_states,
534
+ )
535
+
536
+
537
+ class BlazeForCausalLM(LlamaForCausalLM):
538
+ config_class = BlazeConfig
539
+
540
+ def __init__(self, config):
541
+ super(LlamaForCausalLM, self).__init__(config)
542
+ self.model = BlazeModel(config)
543
+ self.vocab_size = config.vocab_size
544
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
545
+ self.post_init()
546
+
547
+ def get_input_embeddings(self):
548
+ return self.model.embed_tokens
549
+
550
+ def set_input_embeddings(self, value):
551
+ self.model.embed_tokens = value
552
+
553
+ def get_output_embeddings(self):
554
+ return self.lm_head
555
+
556
+ def set_output_embeddings(self, new_embeddings):
557
+ self.lm_head = new_embeddings
558
+
559
+ def gradient_checkpointing_enable(self, **kwargs):
560
+ self.model.gradient_checkpointing_enable(**kwargs)
561
+
562
+ def gradient_checkpointing_disable(self):
563
+ self.model.gradient_checkpointing_disable()
564
+
565
+ def _get_cache_seq_length(self, past_key_values) -> int:
566
+ return self.model._get_cache_seq_length(past_key_values)
567
+
568
+ def forward(
569
+ self,
570
+ input_ids: Optional[torch.LongTensor] = None,
571
+ attention_mask: Optional[torch.Tensor] = None,
572
+ labels: Optional[torch.LongTensor] = None,
573
+ inputs_embeds: Optional[torch.FloatTensor] = None,
574
+ use_cache: Optional[bool] = None,
575
+ num_logits_to_keep: Optional[int] = 0,
576
+ position_ids: Optional[torch.LongTensor] = None,
577
+ past_key_values: Optional[Union[Cache, Tuple[torch.Tensor]]] = None,
578
+ cu_seqlens: Optional[torch.Tensor] = None,
579
+ max_seqlen: Optional[Union[int, torch.Tensor]] = None,
580
+ return_dict: Optional[bool] = None,
581
+ **kwargs,
582
+ ) -> CausalLMOutputWithPast:
583
+ return_dict = return_dict if return_dict is not None else getattr(self.config, "return_dict", True)
584
+ if use_cache is None:
585
+ use_cache = False if (self.training or labels is not None) else True
586
+
587
+ if num_logits_to_keep is None or num_logits_to_keep == 0:
588
+ if "logits_to_keep" in kwargs:
589
+ num_logits_to_keep = kwargs.get("logits_to_keep", 0) or 0
590
+ else:
591
+ num_logits_to_keep = 0
592
+
593
+ outputs = self.model(
594
+ input_ids=input_ids,
595
+ attention_mask=attention_mask,
596
+ position_ids=position_ids,
597
+ inputs_embeds=inputs_embeds,
598
+ past_key_values=past_key_values,
599
+ use_cache=use_cache,
600
+ cu_seqlens=cu_seqlens,
601
+ max_seqlen=max_seqlen,
602
+ return_dict=return_dict,
603
+ **kwargs,
604
+ )
605
+ hidden_states = outputs[0]
606
+
607
+ expected_bsz = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
608
+ if hidden_states.ndim != 3 or hidden_states.shape[0] != expected_bsz:
609
+ raise RuntimeError(
610
+ f"BlazeModel returned hidden_states with shape {tuple(hidden_states.shape)}, "
611
+ f"expected batch size {expected_bsz}."
612
+ )
613
+
614
+ loss = None
615
+ logits = None
616
+
617
+ if labels is not None:
618
+ shift_hidden = hidden_states[..., :-1, :].contiguous()
619
+ shift_labels = labels[..., 1:].contiguous()
620
+
621
+ num_chunks = 8
622
+ h_chunks = shift_hidden.chunk(num_chunks, dim=0)
623
+ l_chunks = shift_labels.chunk(num_chunks, dim=0)
624
+
625
+ total_loss = hidden_states.new_zeros((), dtype=torch.float32)
626
+ total_tokens = 0
627
+ for h_c, l_c in zip(h_chunks, l_chunks):
628
+ if l_c.numel() == 0:
629
+ continue
630
+ logits_c = self.lm_head(h_c)
631
+ chunk_loss = F.cross_entropy(
632
+ logits_c.view(-1, logits_c.size(-1)).float(),
633
+ l_c.view(-1),
634
+ reduction="sum",
635
+ )
636
+ total_loss = total_loss + chunk_loss
637
+ total_tokens += l_c.numel()
638
+ loss = (total_loss / max(total_tokens, 1)).to(hidden_states.dtype)
639
+ else:
640
+ if num_logits_to_keep == 0:
641
+ slice_hidden = hidden_states
642
+ else:
643
+ slice_hidden = hidden_states[:, -num_logits_to_keep:, :]
644
+ logits = self.lm_head(slice_hidden)
645
+
646
+ if not return_dict:
647
+ output = (logits,) + outputs[1:]
648
+ return (loss,) + output if loss is not None else output
649
+
650
+ return CausalLMOutputWithPast(
651
+ loss=loss,
652
+ logits=logits,
653
+ past_key_values=outputs.past_key_values,
654
+ hidden_states=outputs.hidden_states,
655
+ attentions=outputs.attentions,
656
+ )
657
+
658
+ def prepare_inputs_for_generation(
659
+ self,
660
+ input_ids: torch.LongTensor,
661
+ past_key_values: Optional[Cache] = None,
662
+ attention_mask: Optional[torch.Tensor] = None,
663
+ inputs_embeds: Optional[torch.FloatTensor] = None,
664
+ position_ids: Optional[torch.LongTensor] = None,
665
+ use_cache: bool = True,
666
+ num_logits_to_keep: Optional[int] = None,
667
+ **kwargs,
668
+ ) -> dict:
669
+ cache_position = kwargs.get("cache_position", None)
670
+ past_length = 0
671
+
672
+ if past_key_values is not None:
673
+ past_length = self._get_cache_seq_length(past_key_values)
674
+
675
+ # Nanbeige & Llama strict token slicing contract
676
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
677
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
678
+ elif past_length < input_ids.shape[1]:
679
+ input_ids = input_ids[:, past_length:]
680
+ else:
681
+ input_ids = input_ids[:, -1:]
682
+
683
+ if inputs_embeds is not None and past_length == 0:
684
+ model_inputs = {"inputs_embeds": inputs_embeds}
685
+ else:
686
+ model_inputs = {"input_ids": input_ids.contiguous()}
687
+
688
+ input_length = input_ids.shape[1]
689
+
690
+ if cache_position is None:
691
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
692
+ else:
693
+ cache_position = cache_position[-input_length:]
694
+
695
+ if position_ids is None and attention_mask is not None:
696
+ position_ids = attention_mask.long().cumsum(-1) - 1
697
+ position_ids.masked_fill_(attention_mask == 0, 1)
698
+ if past_key_values is not None:
699
+ position_ids = position_ids[:, -input_length:]
700
+ elif position_ids is not None:
701
+ position_ids = position_ids[:, -input_length:]
702
+
703
+ model_inputs.update(
704
+ {
705
+ "position_ids": position_ids,
706
+ "cache_position": cache_position,
707
+ "past_key_values": past_key_values,
708
+ "use_cache": use_cache,
709
+ "attention_mask": attention_mask,
710
+ }
711
+ )
712
+ if num_logits_to_keep is not None:
713
+ model_inputs["num_logits_to_keep"] = num_logits_to_keep
714
+ return model_inputs
715
+
716
+ def _reorder_cache(self, past_key_values, beam_idx):
717
+ if hasattr(past_key_values, "reorder_cache"):
718
+ return past_key_values.reorder_cache(beam_idx)
719
+ return past_key_values