caca-650M-untrained / modeling_caca.py
Lyon28's picture
Upload modeling_caca.py with huggingface_hub
49abe35 verified
Raw
History Blame Contribute Delete
22.6 kB
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")