Lyon28 commited on
Commit
49abe35
ยท
verified ยท
1 Parent(s): 1dfb49b

Upload modeling_caca.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_caca.py +501 -0
modeling_caca.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+ from transformers import PreTrainedModel
7
+ from transformers.generation import GenerationMixin
8
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
9
+
10
+ from configuration_caca import CacaConfig
11
+
12
+ # --- NORM & MLP ---
13
+ class CacaRMSNorm(nn.Module):
14
+ def __init__(self, dim, eps=1e-6):
15
+ super().__init__()
16
+ self.eps = eps
17
+ self.weight = nn.Parameter(torch.zeros(dim))
18
+
19
+ def _norm(self, x):
20
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
21
+
22
+ def forward(self, x):
23
+ out = self._norm(x.float())
24
+ out = out * (1.0 + self.weight.float())
25
+ return out.type_as(x)
26
+
27
+ class CacaMLP(nn.Module):
28
+
29
+ def __init__(self, config: CacaConfig, intermediate_size=None):
30
+ super().__init__()
31
+ inter = intermediate_size or config.intermediate_size
32
+ self.gate_proj = nn.Linear(config.hidden_size, inter, bias=False)
33
+ self.up_proj = nn.Linear(config.hidden_size, inter, bias=False)
34
+ self.down_proj = nn.Linear(inter, config.hidden_size, bias=False)
35
+ self.act_fn = nn.SiLU() if config.hidden_activation == "silu" else nn.GELU(approximate="tanh")
36
+ self.dropout = nn.Dropout(config.hidden_dropout)
37
+
38
+ def forward(self, x):
39
+ return self.dropout(self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)))
40
+
41
+ # --- ROTARY EMBEDDING โ€” default / linear / dynamic / YaRN ---
42
+ class CacaRotaryEmbedding(nn.Module):
43
+ def __init__(self, config: CacaConfig, dim: int, device=None):
44
+ super().__init__()
45
+ self.config = config
46
+ self.dim = dim
47
+
48
+ rope_params = getattr(config, "rope_parameters", None) or {}
49
+ self.rope_type = rope_params.get("rope_type", "default")
50
+ self.base = rope_params.get("rope_theta", getattr(config, "rope_theta", 10000.0))
51
+ self.factor = rope_params.get("factor", 1.0)
52
+ self.original_max_pos = rope_params.get(
53
+ "original_max_position_embeddings", config.max_position_embeddings
54
+ )
55
+ self.beta_fast = rope_params.get("beta_fast", 32)
56
+ self.beta_slow = rope_params.get("beta_slow", 1)
57
+ self.mscale = rope_params.get("mscale", 1.0)
58
+
59
+ if self.rope_type == "yarn":
60
+ inv_freq, self.attention_scaling = self._yarn_inv_freq(device)
61
+ else:
62
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
63
+ self.attention_scaling = 1.0
64
+
65
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
66
+ self.max_seq_len_cached = config.max_position_embeddings
67
+
68
+ def _yarn_find_correction_dim(self, num_rot):
69
+ return (self.dim * math.log(self.original_max_pos / (num_rot * 2 * math.pi))) / (2 * math.log(self.base))
70
+
71
+ def _yarn_inv_freq(self, device):
72
+ dim = self.dim
73
+ pos_freqs = self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
74
+ inv_freq_extrapolation = 1.0 / pos_freqs
75
+ inv_freq_interpolation = 1.0 / (self.factor * pos_freqs)
76
+
77
+ low = max(math.floor(self._yarn_find_correction_dim(self.beta_fast)), 0)
78
+ high = min(math.ceil(self._yarn_find_correction_dim(self.beta_slow)), dim - 1)
79
+
80
+ ramp = torch.linspace(0, 1, dim // 2, device=device)
81
+ ramp = torch.clamp((ramp * dim - low) / max(high - low, 1e-3), 0, 1)
82
+ inv_freq_mask = 1.0 - ramp
83
+
84
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
85
+
86
+ mscale = 0.1 * math.log(self.factor) + 1.0 if self.factor > 1 else 1.0
87
+ return inv_freq, mscale
88
+
89
+ @torch.no_grad()
90
+ def forward(self, x, position_ids):
91
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
92
+ pos_expanded = position_ids[:, None, :].float()
93
+ freqs = (inv_freq_expanded @ pos_expanded).transpose(1, 2)
94
+ emb = torch.cat((freqs, freqs), dim=-1)
95
+ cos = emb.cos() * self.attention_scaling
96
+ sin = emb.sin() * self.attention_scaling
97
+ return cos.to(x.dtype), sin.to(x.dtype)
98
+
99
+ def rotate_half(x):
100
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
101
+ return torch.cat((-x2, x1), dim=-1)
102
+
103
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
104
+ cos = cos.unsqueeze(unsqueeze_dim)
105
+ sin = sin.unsqueeze(unsqueeze_dim)
106
+ q_embed = (q * cos) + (rotate_half(q) * sin)
107
+ k_embed = (k * cos) + (rotate_half(k) * sin)
108
+ return q_embed, k_embed
109
+
110
+ def repeat_kv(x, n_rep):
111
+ if n_rep == 1:
112
+ return x
113
+ b, h, s, d = x.shape
114
+ x = x[:, :, None, :, :].expand(b, h, n_rep, s, d)
115
+ return x.reshape(b, h * n_rep, s, d)
116
+
117
+ # --- CACHE โ€” sederhana ---
118
+ class SimpleCache:
119
+
120
+ def __init__(self):
121
+ self.entries = {}
122
+
123
+ def update(self, layer_idx, *tensors):
124
+ if layer_idx not in self.entries:
125
+ self.entries[layer_idx] = list(tensors)
126
+ else:
127
+ self.entries[layer_idx] = [
128
+ torch.cat([old, new], dim=-2) for old, new in zip(self.entries[layer_idx], tensors)
129
+ ]
130
+ return self.entries[layer_idx]
131
+
132
+ def get_seq_length(self, layer_idx=0):
133
+ if layer_idx not in self.entries:
134
+ return 0
135
+ return self.entries[layer_idx][0].shape[-2]
136
+
137
+ # --- ATTENTION โ€” GQA (use_mla=False) ---
138
+ class CacaGQAAttention(nn.Module):
139
+ def __init__(self, config: CacaConfig, layer_idx: int):
140
+ super().__init__()
141
+ self.layer_idx = layer_idx
142
+ self.head_dim = config.head_dim
143
+ self.num_heads = config.num_attention_heads
144
+ self.num_kv_heads = config.num_key_value_heads
145
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
146
+ self.scaling = config.query_pre_attn_scalar ** -0.5
147
+ self.attn_dropout = config.attention_dropout
148
+ self.attn_softcap = config.attn_logit_softcapping
149
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
150
+
151
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
152
+ self.k_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias)
153
+ self.v_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias)
154
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
155
+
156
+ self.use_qk_norm = config.use_qk_norm
157
+ if self.use_qk_norm:
158
+ self.q_norm = CacaRMSNorm(self.head_dim, config.rms_norm_eps)
159
+ self.k_norm = CacaRMSNorm(self.head_dim, config.rms_norm_eps)
160
+
161
+ self.rotary_emb = CacaRotaryEmbedding(config, dim=self.head_dim)
162
+
163
+ def forward(self, hidden_states, attention_mask, position_ids, cache=None, **kwargs):
164
+ b, seq_len, _ = hidden_states.shape
165
+ shape = (b, seq_len, -1, self.head_dim)
166
+
167
+ q = self.q_proj(hidden_states).view(shape)
168
+ k = self.k_proj(hidden_states).view(shape)
169
+ v = self.v_proj(hidden_states).view(shape).transpose(1, 2)
170
+
171
+ if self.use_qk_norm:
172
+ q, k = self.q_norm(q), self.k_norm(k)
173
+
174
+ q, k = q.transpose(1, 2), k.transpose(1, 2)
175
+
176
+ cos, sin = self.rotary_emb(hidden_states, position_ids)
177
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
178
+
179
+ if cache is not None:
180
+ k, v = cache.update(self.layer_idx, k, v)
181
+
182
+ k = repeat_kv(k, self.num_kv_groups)
183
+ v = repeat_kv(v, self.num_kv_groups)
184
+
185
+ attn_weights = torch.matmul(q, k.transpose(2, 3)) * self.scaling
186
+ if self.attn_softcap is not None:
187
+ attn_weights = torch.tanh(attn_weights / self.attn_softcap) * self.attn_softcap
188
+ if attention_mask is not None:
189
+ attn_weights = attn_weights + attention_mask[:, :, :, : k.shape[-2]]
190
+
191
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
192
+ attn_weights = F.dropout(attn_weights, p=self.attn_dropout, training=self.training)
193
+ attn_output = torch.matmul(attn_weights, v)
194
+
195
+ attn_output = attn_output.transpose(1, 2).contiguous().reshape(b, seq_len, -1)
196
+ return self.o_proj(attn_output)
197
+
198
+ # --- ATTENTION โ€” MLA ---
199
+ class CacaMLAAttention(nn.Module):
200
+ def __init__(self, config: CacaConfig, layer_idx: int):
201
+ super().__init__()
202
+ self.layer_idx = layer_idx
203
+ self.num_heads = config.num_attention_heads
204
+ self.q_lora_rank = config.q_lora_rank
205
+ self.kv_lora_rank = config.kv_lora_rank
206
+ self.qk_nope_head_dim = config.qk_nope_head_dim
207
+ self.qk_rope_head_dim = config.qk_rope_head_dim
208
+ self.v_head_dim = config.v_head_dim
209
+ self.q_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
210
+
211
+ self.scaling = self.q_head_dim ** -0.5
212
+ self.attn_dropout = config.attention_dropout
213
+ self.attn_softcap = config.attn_logit_softcapping
214
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
215
+
216
+ if self.q_lora_rank > 0:
217
+ self.q_a_proj = nn.Linear(config.hidden_size, self.q_lora_rank, bias=False)
218
+ self.q_a_norm = CacaRMSNorm(self.q_lora_rank, config.rms_norm_eps)
219
+ self.q_b_proj = nn.Linear(self.q_lora_rank, self.num_heads * self.q_head_dim, bias=False)
220
+ else:
221
+ self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.q_head_dim, bias=False)
222
+
223
+ self.kv_a_proj_with_mqa = nn.Linear(
224
+ config.hidden_size, self.kv_lora_rank + self.qk_rope_head_dim, bias=False
225
+ )
226
+ self.kv_a_norm = CacaRMSNorm(self.kv_lora_rank, config.rms_norm_eps)
227
+ self.kv_b_proj = nn.Linear(
228
+ self.kv_lora_rank, self.num_heads * (self.qk_nope_head_dim + self.v_head_dim), bias=False
229
+ )
230
+
231
+ self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=False)
232
+
233
+ self.use_qk_norm = config.use_qk_norm
234
+ if self.use_qk_norm:
235
+ self.q_nope_norm = CacaRMSNorm(self.qk_nope_head_dim, config.rms_norm_eps)
236
+ self.k_nope_norm = CacaRMSNorm(self.qk_nope_head_dim, config.rms_norm_eps)
237
+
238
+ self.rotary_emb = CacaRotaryEmbedding(config, dim=self.qk_rope_head_dim)
239
+
240
+ def forward(self, hidden_states, attention_mask, position_ids, cache=None, **kwargs):
241
+ b, seq_len, _ = hidden_states.shape
242
+
243
+ if self.q_lora_rank > 0:
244
+ q = self.q_b_proj(self.q_a_norm(self.q_a_proj(hidden_states)))
245
+ else:
246
+ q = self.q_proj(hidden_states)
247
+ q = q.view(b, seq_len, self.num_heads, self.q_head_dim).transpose(1, 2)
248
+ q_nope, q_rope = q.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
249
+
250
+ kv_a = self.kv_a_proj_with_mqa(hidden_states)
251
+ kv_a, k_rope = kv_a.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
252
+ kv_a = self.kv_a_norm(kv_a)
253
+ k_rope = k_rope.view(b, seq_len, 1, self.qk_rope_head_dim).transpose(1, 2)
254
+
255
+ if cache is not None:
256
+ kv_a_seq, k_rope_seq = cache.update(self.layer_idx, kv_a.unsqueeze(1), k_rope)
257
+ kv_a = kv_a_seq.squeeze(1)
258
+ else:
259
+ kv_a_seq, k_rope_seq = kv_a.unsqueeze(1), k_rope
260
+
261
+ kv = self.kv_b_proj(kv_a_seq.squeeze(1) if cache is None else cache.entries[self.layer_idx][0].squeeze(1))
262
+ kv_len = kv.shape[1]
263
+ kv = kv.view(b, kv_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim).transpose(1, 2)
264
+ k_nope, value = kv.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)
265
+
266
+ if self.use_qk_norm:
267
+ q_nope = self.q_nope_norm(q_nope)
268
+ k_nope = self.k_nope_norm(k_nope)
269
+
270
+ cos, sin = self.rotary_emb(hidden_states, position_ids)
271
+ q_rope, k_rope_seq = apply_rotary_pos_emb(q_rope, k_rope_seq, cos, sin)
272
+
273
+ k_rope_expanded = k_rope_seq.expand(-1, self.num_heads, -1, -1)
274
+
275
+ q_full = torch.cat([q_nope, q_rope], dim=-1)
276
+ k_full = torch.cat([k_nope, k_rope_expanded], dim=-1)
277
+
278
+ attn_weights = torch.matmul(q_full, k_full.transpose(2, 3)) * self.scaling
279
+ if self.attn_softcap is not None:
280
+ attn_weights = torch.tanh(attn_weights / self.attn_softcap) * self.attn_softcap
281
+ if attention_mask is not None:
282
+ attn_weights = attn_weights + attention_mask[:, :, :, :kv_len]
283
+
284
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q_full.dtype)
285
+ attn_weights = F.dropout(attn_weights, p=self.attn_dropout, training=self.training)
286
+ attn_output = torch.matmul(attn_weights, value)
287
+
288
+ attn_output = attn_output.transpose(1, 2).contiguous().reshape(b, seq_len, -1)
289
+ return self.o_proj(attn_output)
290
+
291
+ # --- DECODER LAYER ---
292
+ class CacaDecoderLayer(nn.Module):
293
+ def __init__(self, config: CacaConfig, layer_idx: int):
294
+ super().__init__()
295
+ self.self_attn = CacaMLAAttention(config, layer_idx) if config.use_mla else CacaGQAAttention(config, layer_idx)
296
+ self.mlp = CacaMLP(config)
297
+ self.input_layernorm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
298
+ self.post_attention_layernorm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
299
+ self.pre_feedforward_layernorm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
300
+ self.post_feedforward_layernorm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
301
+ self.residual_dropout = nn.Dropout(config.hidden_dropout)
302
+
303
+ def forward(self, hidden_states, attention_mask, position_ids, cache=None, **kwargs):
304
+ residual = hidden_states
305
+ hidden_states = self.input_layernorm(hidden_states)
306
+ hidden_states = self.self_attn(hidden_states, attention_mask, position_ids, cache)
307
+ hidden_states = self.post_attention_layernorm(hidden_states)
308
+ hidden_states = residual + self.residual_dropout(hidden_states)
309
+
310
+ residual = hidden_states
311
+ hidden_states = self.pre_feedforward_layernorm(hidden_states)
312
+ hidden_states = self.mlp(hidden_states)
313
+ hidden_states = self.post_feedforward_layernorm(hidden_states)
314
+ hidden_states = residual + self.residual_dropout(hidden_states)
315
+ return hidden_states
316
+
317
+ # --- MASK UTILS ---
318
+ def build_attention_mask(attention_mask, seq_len, past_len, sliding_window, dtype, device):
319
+ min_val = torch.finfo(dtype).min
320
+ query_pos = torch.arange(past_len, past_len + seq_len, device=device)[:, None]
321
+ key_pos = torch.arange(past_len + seq_len, device=device)[None, :]
322
+
323
+ causal = key_pos > query_pos
324
+ mask = torch.zeros((seq_len, past_len + seq_len), dtype=dtype, device=device)
325
+ mask.masked_fill_(causal, min_val)
326
+
327
+ if sliding_window is not None:
328
+ too_far = key_pos <= (query_pos - sliding_window)
329
+ mask.masked_fill_(too_far, min_val)
330
+
331
+ mask = mask[None, None, :, :]
332
+ if attention_mask is not None:
333
+ pad = (1.0 - attention_mask[:, None, None, :].to(dtype)) * min_val
334
+ mask = mask + pad
335
+ return mask
336
+
337
+ # --- PRETRAINED BASE ---
338
+ class CacaPreTrainedModel(PreTrainedModel):
339
+ config_class = CacaConfig
340
+ base_model_prefix = "model"
341
+ supports_gradient_checkpointing = True
342
+ _no_split_modules = ["CacaDecoderLayer"]
343
+
344
+ def _init_weights(self, module):
345
+ std = self.config.initializer_range
346
+ if isinstance(module, nn.Linear):
347
+ module.weight.data.normal_(mean=0.0, std=std)
348
+ if module.bias is not None:
349
+ module.bias.data.zero_()
350
+ elif isinstance(module, nn.Embedding):
351
+ module.weight.data.normal_(mean=0.0, std=std)
352
+ if module.padding_idx is not None:
353
+ module.weight.data[module.padding_idx].zero_()
354
+
355
+ # --- MODEL BODY ---
356
+ class CacaModel(CacaPreTrainedModel):
357
+ def __init__(self, config: CacaConfig):
358
+ super().__init__(config)
359
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
360
+ self.embedding_dropout = nn.Dropout(config.embedding_dropout)
361
+ self.layers = nn.ModuleList([CacaDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
362
+ self.norm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
363
+ self.hidden_scale = config.hidden_size ** 0.5
364
+
365
+ self.post_init()
366
+
367
+ def forward(self, input_ids, attention_mask=None, position_ids=None, cache=None, use_cache=None, **kwargs):
368
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
369
+ b, seq_len = input_ids.shape
370
+
371
+ if use_cache and cache is None:
372
+ cache = SimpleCache()
373
+ past_len = cache.get_seq_length(0) if cache is not None else 0
374
+
375
+ if position_ids is None:
376
+ position_ids = torch.arange(past_len, past_len + seq_len, device=input_ids.device)[None, :].expand(b, -1)
377
+
378
+ hidden_states = self.embed_tokens(input_ids) * self.hidden_scale
379
+ hidden_states = self.embedding_dropout(hidden_states)
380
+
381
+ full_mask = build_attention_mask(attention_mask, seq_len, past_len, None, hidden_states.dtype, hidden_states.device)
382
+ sliding_mask = build_attention_mask(
383
+ attention_mask, seq_len, past_len, self.config.sliding_window, hidden_states.dtype, hidden_states.device
384
+ )
385
+
386
+ for layer in self.layers:
387
+ mask = sliding_mask if layer.self_attn.sliding_window is not None else full_mask
388
+ if self.gradient_checkpointing and self.training:
389
+ hidden_states = torch.utils.checkpoint.checkpoint(
390
+ layer, hidden_states, mask, position_ids, cache, use_reentrant=False
391
+ )
392
+ else:
393
+ hidden_states = layer(hidden_states, mask, position_ids, cache)
394
+
395
+ hidden_states = self.norm(hidden_states)
396
+ return BaseModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=cache)
397
+
398
+ # --- MULTI-TOKEN PREDICTION MODULE ---
399
+ class CacaMTPModule(nn.Module):
400
+
401
+ def __init__(self, config: CacaConfig):
402
+ super().__init__()
403
+ self.norm_prev = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
404
+ self.norm_emb = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
405
+ self.combine_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
406
+ self.decoder_layer = CacaDecoderLayer(config, layer_idx=0)
407
+
408
+ def forward(self, prev_hidden, target_embeds, attention_mask, position_ids):
409
+ combined = self.combine_proj(torch.cat([self.norm_prev(prev_hidden), self.norm_emb(target_embeds)], dim=-1))
410
+ return self.decoder_layer(combined, attention_mask, position_ids, cache=None)
411
+
412
+ # --- CAUSAL LM HEAD ---
413
+ class CacaForCausalLM(CacaPreTrainedModel, GenerationMixin):
414
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
415
+
416
+ def __init__(self, config: CacaConfig):
417
+ super().__init__(config)
418
+ self.model = CacaModel(config)
419
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
420
+
421
+ self.mtp_modules = nn.ModuleList(
422
+ [CacaMTPModule(config) for _ in range(config.num_mtp_tokens)]
423
+ ) if config.num_mtp_tokens > 0 else None
424
+
425
+ self.post_init()
426
+
427
+ def get_input_embeddings(self):
428
+ return self.model.embed_tokens
429
+
430
+ def set_input_embeddings(self, value):
431
+ self.model.embed_tokens = value
432
+
433
+ def get_output_embeddings(self):
434
+ return self.lm_head
435
+
436
+ def forward(
437
+ self, input_ids, attention_mask=None, position_ids=None, labels=None,
438
+ cache=None, use_cache=None, logits_to_keep=0, **kwargs,
439
+ ):
440
+ outputs = self.model(input_ids, attention_mask, position_ids, cache, use_cache)
441
+ hidden_states = outputs.last_hidden_state
442
+
443
+ slice_idx = slice(-logits_to_keep, None) if logits_to_keep else slice(None)
444
+ logits = self.lm_head(hidden_states[:, slice_idx, :])
445
+
446
+ if self.config.final_logit_softcapping is not None:
447
+ cap = self.config.final_logit_softcapping
448
+ logits = torch.tanh(logits / cap) * cap
449
+
450
+ loss = None
451
+ if labels is not None:
452
+ shift_logits = logits[..., :-1, :].contiguous()
453
+ shift_labels = labels[..., 1:].contiguous()
454
+ main_loss = F.cross_entropy(
455
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), ignore_index=-100
456
+ )
457
+ loss = main_loss
458
+
459
+ if self.mtp_modules is not None:
460
+ mtp_loss_total = 0.0
461
+ prev_hidden = hidden_states
462
+ b, seq_len = input_ids.shape
463
+ pos_ids = position_ids if position_ids is not None else torch.arange(seq_len, device=input_ids.device)[None, :].expand(b, -1)
464
+
465
+ for k, mtp in enumerate(self.mtp_modules, start=1):
466
+ if seq_len - k <= 1:
467
+ break
468
+ target_ids = input_ids[:, k:]
469
+ target_embeds = self.model.embed_tokens(target_ids) * self.model.hidden_scale
470
+ aligned_prev = prev_hidden[:, : target_ids.shape[1], :]
471
+ aligned_mask = None
472
+
473
+ mtp_hidden = mtp(aligned_prev, target_embeds, aligned_mask, pos_ids[:, : target_ids.shape[1]])
474
+ mtp_logits = self.lm_head(mtp_hidden)
475
+
476
+ mtp_labels = labels[:, k + 1 :]
477
+ mtp_logits_trimmed = mtp_logits[:, : mtp_labels.shape[1], :]
478
+ if mtp_labels.shape[1] > 0:
479
+ mtp_loss = F.cross_entropy(
480
+ mtp_logits_trimmed.reshape(-1, mtp_logits_trimmed.size(-1)),
481
+ mtp_labels.reshape(-1),
482
+ ignore_index=-100,
483
+ )
484
+ mtp_loss_total = mtp_loss_total + mtp_loss
485
+ prev_hidden = mtp_hidden
486
+
487
+ if isinstance(mtp_loss_total, torch.Tensor):
488
+ loss = main_loss + self.config.mtp_loss_weight * mtp_loss_total
489
+
490
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values)
491
+
492
+ def prepare_inputs_for_generation(self, input_ids, cache=None, attention_mask=None, **kwargs):
493
+ if cache is not None and cache.get_seq_length(0) > 0:
494
+ input_ids = input_ids[:, -1:]
495
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "cache": cache, "use_cache": True, "logits_to_keep": 1}
496
+
497
+
498
+ # --- AUTO-REGISTER ---
499
+ CacaConfig.register_for_auto_class()
500
+ CacaModel.register_for_auto_class("AutoModel")
501
+ CacaForCausalLM.register_for_auto_class("AutoModelForCausalLM")