File size: 22,618 Bytes
49abe35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

from transformers import PreTrainedModel
from transformers.generation import GenerationMixin
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast

from configuration_caca import CacaConfig

# --- NORM & MLP ---
class CacaRMSNorm(nn.Module):
    def __init__(self, dim, eps=1e-6):
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.zeros(dim))

    def _norm(self, x):
        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

    def forward(self, x):
        out = self._norm(x.float())
        out = out * (1.0 + self.weight.float())
        return out.type_as(x)

class CacaMLP(nn.Module):

    def __init__(self, config: CacaConfig, intermediate_size=None):
        super().__init__()
        inter = intermediate_size or config.intermediate_size
        self.gate_proj = nn.Linear(config.hidden_size, inter, bias=False)
        self.up_proj = nn.Linear(config.hidden_size, inter, bias=False)
        self.down_proj = nn.Linear(inter, config.hidden_size, bias=False)
        self.act_fn = nn.SiLU() if config.hidden_activation == "silu" else nn.GELU(approximate="tanh")
        self.dropout = nn.Dropout(config.hidden_dropout)

    def forward(self, x):
        return self.dropout(self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)))

# --- ROTARY EMBEDDING โ€” default / linear / dynamic / YaRN ---
class CacaRotaryEmbedding(nn.Module):
    def __init__(self, config: CacaConfig, dim: int, device=None):
        super().__init__()
        self.config = config
        self.dim = dim

        rope_params = getattr(config, "rope_parameters", None) or {}
        self.rope_type = rope_params.get("rope_type", "default")
        self.base = rope_params.get("rope_theta", getattr(config, "rope_theta", 10000.0))
        self.factor = rope_params.get("factor", 1.0)
        self.original_max_pos = rope_params.get(
            "original_max_position_embeddings", config.max_position_embeddings
        )
        self.beta_fast = rope_params.get("beta_fast", 32)
        self.beta_slow = rope_params.get("beta_slow", 1)
        self.mscale = rope_params.get("mscale", 1.0)

        if self.rope_type == "yarn":
            inv_freq, self.attention_scaling = self._yarn_inv_freq(device)
        else:
            inv_freq = 1.0 / (self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
            self.attention_scaling = 1.0

        self.register_buffer("inv_freq", inv_freq, persistent=False)
        self.max_seq_len_cached = config.max_position_embeddings

    def _yarn_find_correction_dim(self, num_rot):
        return (self.dim * math.log(self.original_max_pos / (num_rot * 2 * math.pi))) / (2 * math.log(self.base))

    def _yarn_inv_freq(self, device):
        dim = self.dim
        pos_freqs = self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
        inv_freq_extrapolation = 1.0 / pos_freqs
        inv_freq_interpolation = 1.0 / (self.factor * pos_freqs)

        low = max(math.floor(self._yarn_find_correction_dim(self.beta_fast)), 0)
        high = min(math.ceil(self._yarn_find_correction_dim(self.beta_slow)), dim - 1)

        ramp = torch.linspace(0, 1, dim // 2, device=device)
        ramp = torch.clamp((ramp * dim - low) / max(high - low, 1e-3), 0, 1)
        inv_freq_mask = 1.0 - ramp

        inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask

        mscale = 0.1 * math.log(self.factor) + 1.0 if self.factor > 1 else 1.0
        return inv_freq, mscale

    @torch.no_grad()
    def forward(self, x, position_ids):
        inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
        pos_expanded = position_ids[:, None, :].float()
        freqs = (inv_freq_expanded @ pos_expanded).transpose(1, 2)
        emb = torch.cat((freqs, freqs), dim=-1)
        cos = emb.cos() * self.attention_scaling
        sin = emb.sin() * self.attention_scaling
        return cos.to(x.dtype), sin.to(x.dtype)

def rotate_half(x):
    x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
    return torch.cat((-x2, x1), dim=-1)

def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
    cos = cos.unsqueeze(unsqueeze_dim)
    sin = sin.unsqueeze(unsqueeze_dim)
    q_embed = (q * cos) + (rotate_half(q) * sin)
    k_embed = (k * cos) + (rotate_half(k) * sin)
    return q_embed, k_embed

def repeat_kv(x, n_rep):
    if n_rep == 1:
        return x
    b, h, s, d = x.shape
    x = x[:, :, None, :, :].expand(b, h, n_rep, s, d)
    return x.reshape(b, h * n_rep, s, d)

# --- CACHE โ€” sederhana ---
class SimpleCache:

    def __init__(self):
        self.entries = {}

    def update(self, layer_idx, *tensors):
        if layer_idx not in self.entries:
            self.entries[layer_idx] = list(tensors)
        else:
            self.entries[layer_idx] = [
                torch.cat([old, new], dim=-2) for old, new in zip(self.entries[layer_idx], tensors)
            ]
        return self.entries[layer_idx]

    def get_seq_length(self, layer_idx=0):
        if layer_idx not in self.entries:
            return 0
        return self.entries[layer_idx][0].shape[-2]

# --- ATTENTION โ€” GQA (use_mla=False) ---
class CacaGQAAttention(nn.Module):
    def __init__(self, config: CacaConfig, layer_idx: int):
        super().__init__()
        self.layer_idx = layer_idx
        self.head_dim = config.head_dim
        self.num_heads = config.num_attention_heads
        self.num_kv_heads = config.num_key_value_heads
        self.num_kv_groups = self.num_heads // self.num_kv_heads
        self.scaling = config.query_pre_attn_scalar ** -0.5
        self.attn_dropout = config.attention_dropout
        self.attn_softcap = config.attn_logit_softcapping
        self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None

        self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
        self.k_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias)
        self.v_proj = nn.Linear(config.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias)
        self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)

        self.use_qk_norm = config.use_qk_norm
        if self.use_qk_norm:
            self.q_norm = CacaRMSNorm(self.head_dim, config.rms_norm_eps)
            self.k_norm = CacaRMSNorm(self.head_dim, config.rms_norm_eps)

        self.rotary_emb = CacaRotaryEmbedding(config, dim=self.head_dim)

    def forward(self, hidden_states, attention_mask, position_ids, cache=None, **kwargs):
        b, seq_len, _ = hidden_states.shape
        shape = (b, seq_len, -1, self.head_dim)

        q = self.q_proj(hidden_states).view(shape)
        k = self.k_proj(hidden_states).view(shape)
        v = self.v_proj(hidden_states).view(shape).transpose(1, 2)

        if self.use_qk_norm:
            q, k = self.q_norm(q), self.k_norm(k)

        q, k = q.transpose(1, 2), k.transpose(1, 2)

        cos, sin = self.rotary_emb(hidden_states, position_ids)
        q, k = apply_rotary_pos_emb(q, k, cos, sin)

        if cache is not None:
            k, v = cache.update(self.layer_idx, k, v)

        k = repeat_kv(k, self.num_kv_groups)
        v = repeat_kv(v, self.num_kv_groups)

        attn_weights = torch.matmul(q, k.transpose(2, 3)) * self.scaling
        if self.attn_softcap is not None:
            attn_weights = torch.tanh(attn_weights / self.attn_softcap) * self.attn_softcap
        if attention_mask is not None:
            attn_weights = attn_weights + attention_mask[:, :, :, : k.shape[-2]]

        attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
        attn_weights = F.dropout(attn_weights, p=self.attn_dropout, training=self.training)
        attn_output = torch.matmul(attn_weights, v)

        attn_output = attn_output.transpose(1, 2).contiguous().reshape(b, seq_len, -1)
        return self.o_proj(attn_output)

# --- ATTENTION โ€” MLA ---
class CacaMLAAttention(nn.Module):
    def __init__(self, config: CacaConfig, layer_idx: int):
        super().__init__()
        self.layer_idx = layer_idx
        self.num_heads = config.num_attention_heads
        self.q_lora_rank = config.q_lora_rank
        self.kv_lora_rank = config.kv_lora_rank
        self.qk_nope_head_dim = config.qk_nope_head_dim
        self.qk_rope_head_dim = config.qk_rope_head_dim
        self.v_head_dim = config.v_head_dim
        self.q_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim

        self.scaling = self.q_head_dim ** -0.5
        self.attn_dropout = config.attention_dropout
        self.attn_softcap = config.attn_logit_softcapping
        self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None

        if self.q_lora_rank > 0:
            self.q_a_proj = nn.Linear(config.hidden_size, self.q_lora_rank, bias=False)
            self.q_a_norm = CacaRMSNorm(self.q_lora_rank, config.rms_norm_eps)
            self.q_b_proj = nn.Linear(self.q_lora_rank, self.num_heads * self.q_head_dim, bias=False)
        else:
            self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.q_head_dim, bias=False)

        self.kv_a_proj_with_mqa = nn.Linear(
            config.hidden_size, self.kv_lora_rank + self.qk_rope_head_dim, bias=False
        )
        self.kv_a_norm = CacaRMSNorm(self.kv_lora_rank, config.rms_norm_eps)
        self.kv_b_proj = nn.Linear(
            self.kv_lora_rank, self.num_heads * (self.qk_nope_head_dim + self.v_head_dim), bias=False
        )

        self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=False)

        self.use_qk_norm = config.use_qk_norm
        if self.use_qk_norm:
            self.q_nope_norm = CacaRMSNorm(self.qk_nope_head_dim, config.rms_norm_eps)
            self.k_nope_norm = CacaRMSNorm(self.qk_nope_head_dim, config.rms_norm_eps)

        self.rotary_emb = CacaRotaryEmbedding(config, dim=self.qk_rope_head_dim)

    def forward(self, hidden_states, attention_mask, position_ids, cache=None, **kwargs):
        b, seq_len, _ = hidden_states.shape

        if self.q_lora_rank > 0:
            q = self.q_b_proj(self.q_a_norm(self.q_a_proj(hidden_states)))
        else:
            q = self.q_proj(hidden_states)
        q = q.view(b, seq_len, self.num_heads, self.q_head_dim).transpose(1, 2)
        q_nope, q_rope = q.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)

        kv_a = self.kv_a_proj_with_mqa(hidden_states)
        kv_a, k_rope = kv_a.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
        kv_a = self.kv_a_norm(kv_a)
        k_rope = k_rope.view(b, seq_len, 1, self.qk_rope_head_dim).transpose(1, 2)

        if cache is not None:
            kv_a_seq, k_rope_seq = cache.update(self.layer_idx, kv_a.unsqueeze(1), k_rope)
            kv_a = kv_a_seq.squeeze(1)
        else:
            kv_a_seq, k_rope_seq = kv_a.unsqueeze(1), k_rope

        kv = self.kv_b_proj(kv_a_seq.squeeze(1) if cache is None else cache.entries[self.layer_idx][0].squeeze(1))
        kv_len = kv.shape[1]
        kv = kv.view(b, kv_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim).transpose(1, 2)
        k_nope, value = kv.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)

        if self.use_qk_norm:
            q_nope = self.q_nope_norm(q_nope)
            k_nope = self.k_nope_norm(k_nope)

        cos, sin = self.rotary_emb(hidden_states, position_ids)
        q_rope, k_rope_seq = apply_rotary_pos_emb(q_rope, k_rope_seq, cos, sin)

        k_rope_expanded = k_rope_seq.expand(-1, self.num_heads, -1, -1)

        q_full = torch.cat([q_nope, q_rope], dim=-1)
        k_full = torch.cat([k_nope, k_rope_expanded], dim=-1)

        attn_weights = torch.matmul(q_full, k_full.transpose(2, 3)) * self.scaling
        if self.attn_softcap is not None:
            attn_weights = torch.tanh(attn_weights / self.attn_softcap) * self.attn_softcap
        if attention_mask is not None:
            attn_weights = attn_weights + attention_mask[:, :, :, :kv_len]

        attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q_full.dtype)
        attn_weights = F.dropout(attn_weights, p=self.attn_dropout, training=self.training)
        attn_output = torch.matmul(attn_weights, value)

        attn_output = attn_output.transpose(1, 2).contiguous().reshape(b, seq_len, -1)
        return self.o_proj(attn_output)

# --- DECODER LAYER ---
class CacaDecoderLayer(nn.Module):
    def __init__(self, config: CacaConfig, layer_idx: int):
        super().__init__()
        self.self_attn = CacaMLAAttention(config, layer_idx) if config.use_mla else CacaGQAAttention(config, layer_idx)
        self.mlp = CacaMLP(config)
        self.input_layernorm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.post_attention_layernorm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.pre_feedforward_layernorm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.post_feedforward_layernorm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.residual_dropout = nn.Dropout(config.hidden_dropout)

    def forward(self, hidden_states, attention_mask, position_ids, cache=None, **kwargs):
        residual = hidden_states
        hidden_states = self.input_layernorm(hidden_states)
        hidden_states = self.self_attn(hidden_states, attention_mask, position_ids, cache)
        hidden_states = self.post_attention_layernorm(hidden_states)
        hidden_states = residual + self.residual_dropout(hidden_states)

        residual = hidden_states
        hidden_states = self.pre_feedforward_layernorm(hidden_states)
        hidden_states = self.mlp(hidden_states)
        hidden_states = self.post_feedforward_layernorm(hidden_states)
        hidden_states = residual + self.residual_dropout(hidden_states)
        return hidden_states

# --- MASK UTILS ---
def build_attention_mask(attention_mask, seq_len, past_len, sliding_window, dtype, device):
    min_val = torch.finfo(dtype).min
    query_pos = torch.arange(past_len, past_len + seq_len, device=device)[:, None]
    key_pos = torch.arange(past_len + seq_len, device=device)[None, :]

    causal = key_pos > query_pos
    mask = torch.zeros((seq_len, past_len + seq_len), dtype=dtype, device=device)
    mask.masked_fill_(causal, min_val)

    if sliding_window is not None:
        too_far = key_pos <= (query_pos - sliding_window)
        mask.masked_fill_(too_far, min_val)

    mask = mask[None, None, :, :]
    if attention_mask is not None:
        pad = (1.0 - attention_mask[:, None, None, :].to(dtype)) * min_val
        mask = mask + pad
    return mask

# --- PRETRAINED BASE ---
class CacaPreTrainedModel(PreTrainedModel):
    config_class = CacaConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = True
    _no_split_modules = ["CacaDecoderLayer"]

    def _init_weights(self, module):
        std = self.config.initializer_range
        if isinstance(module, nn.Linear):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.Embedding):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.padding_idx is not None:
                module.weight.data[module.padding_idx].zero_()

# --- MODEL BODY ---
class CacaModel(CacaPreTrainedModel):
    def __init__(self, config: CacaConfig):
        super().__init__(config)
        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
        self.embedding_dropout = nn.Dropout(config.embedding_dropout)
        self.layers = nn.ModuleList([CacaDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
        self.norm = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.hidden_scale = config.hidden_size ** 0.5

        self.post_init()

    def forward(self, input_ids, attention_mask=None, position_ids=None, cache=None, use_cache=None, **kwargs):
        use_cache = use_cache if use_cache is not None else self.config.use_cache
        b, seq_len = input_ids.shape

        if use_cache and cache is None:
            cache = SimpleCache()
        past_len = cache.get_seq_length(0) if cache is not None else 0

        if position_ids is None:
            position_ids = torch.arange(past_len, past_len + seq_len, device=input_ids.device)[None, :].expand(b, -1)

        hidden_states = self.embed_tokens(input_ids) * self.hidden_scale
        hidden_states = self.embedding_dropout(hidden_states)

        full_mask = build_attention_mask(attention_mask, seq_len, past_len, None, hidden_states.dtype, hidden_states.device)
        sliding_mask = build_attention_mask(
            attention_mask, seq_len, past_len, self.config.sliding_window, hidden_states.dtype, hidden_states.device
        )

        for layer in self.layers:
            mask = sliding_mask if layer.self_attn.sliding_window is not None else full_mask
            if self.gradient_checkpointing and self.training:
                hidden_states = torch.utils.checkpoint.checkpoint(
                    layer, hidden_states, mask, position_ids, cache, use_reentrant=False
                )
            else:
                hidden_states = layer(hidden_states, mask, position_ids, cache)

        hidden_states = self.norm(hidden_states)
        return BaseModelOutputWithPast(last_hidden_state=hidden_states, past_key_values=cache)

# --- MULTI-TOKEN PREDICTION MODULE ---
class CacaMTPModule(nn.Module):

    def __init__(self, config: CacaConfig):
        super().__init__()
        self.norm_prev = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.norm_emb = CacaRMSNorm(config.hidden_size, config.rms_norm_eps)
        self.combine_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
        self.decoder_layer = CacaDecoderLayer(config, layer_idx=0)

    def forward(self, prev_hidden, target_embeds, attention_mask, position_ids):
        combined = self.combine_proj(torch.cat([self.norm_prev(prev_hidden), self.norm_emb(target_embeds)], dim=-1))
        return self.decoder_layer(combined, attention_mask, position_ids, cache=None)

# --- CAUSAL LM HEAD ---
class CacaForCausalLM(CacaPreTrainedModel, GenerationMixin):
    _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}

    def __init__(self, config: CacaConfig):
        super().__init__(config)
        self.model = CacaModel(config)
        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        self.mtp_modules = nn.ModuleList(
            [CacaMTPModule(config) for _ in range(config.num_mtp_tokens)]
        ) if config.num_mtp_tokens > 0 else None

        self.post_init()

    def get_input_embeddings(self):
        return self.model.embed_tokens

    def set_input_embeddings(self, value):
        self.model.embed_tokens = value

    def get_output_embeddings(self):
        return self.lm_head

    def forward(
        self, input_ids, attention_mask=None, position_ids=None, labels=None,
        cache=None, use_cache=None, logits_to_keep=0, **kwargs,
    ):
        outputs = self.model(input_ids, attention_mask, position_ids, cache, use_cache)
        hidden_states = outputs.last_hidden_state

        slice_idx = slice(-logits_to_keep, None) if logits_to_keep else slice(None)
        logits = self.lm_head(hidden_states[:, slice_idx, :])

        if self.config.final_logit_softcapping is not None:
            cap = self.config.final_logit_softcapping
            logits = torch.tanh(logits / cap) * cap

        loss = None
        if labels is not None:
            shift_logits = logits[..., :-1, :].contiguous()
            shift_labels = labels[..., 1:].contiguous()
            main_loss = F.cross_entropy(
                shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), ignore_index=-100
            )
            loss = main_loss

            if self.mtp_modules is not None:
                mtp_loss_total = 0.0
                prev_hidden = hidden_states
                b, seq_len = input_ids.shape
                pos_ids = position_ids if position_ids is not None else torch.arange(seq_len, device=input_ids.device)[None, :].expand(b, -1)

                for k, mtp in enumerate(self.mtp_modules, start=1):
                    if seq_len - k <= 1:
                        break
                    target_ids = input_ids[:, k:]
                    target_embeds = self.model.embed_tokens(target_ids) * self.model.hidden_scale
                    aligned_prev = prev_hidden[:, : target_ids.shape[1], :]
                    aligned_mask = None  
                    
                    mtp_hidden = mtp(aligned_prev, target_embeds, aligned_mask, pos_ids[:, : target_ids.shape[1]])
                    mtp_logits = self.lm_head(mtp_hidden)

                    mtp_labels = labels[:, k + 1 :]
                    mtp_logits_trimmed = mtp_logits[:, : mtp_labels.shape[1], :]
                    if mtp_labels.shape[1] > 0:
                        mtp_loss = F.cross_entropy(
                            mtp_logits_trimmed.reshape(-1, mtp_logits_trimmed.size(-1)),
                            mtp_labels.reshape(-1),
                            ignore_index=-100,
                        )
                        mtp_loss_total = mtp_loss_total + mtp_loss
                    prev_hidden = mtp_hidden

                if isinstance(mtp_loss_total, torch.Tensor):
                    loss = main_loss + self.config.mtp_loss_weight * mtp_loss_total

        return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values)

    def prepare_inputs_for_generation(self, input_ids, cache=None, attention_mask=None, **kwargs):
        if cache is not None and cache.get_seq_length(0) > 0:
            input_ids = input_ids[:, -1:]
        return {"input_ids": input_ids, "attention_mask": attention_mask, "cache": cache, "use_cache": True, "logits_to_keep": 1}


# --- AUTO-REGISTER ---
CacaConfig.register_for_auto_class()
CacaModel.register_for_auto_class("AutoModel")
CacaForCausalLM.register_for_auto_class("AutoModelForCausalLM")