TestSubject-4 / modeling_rose_x26.py
CyanMonkey's picture
Rose X2.6 step 500
211ec82 verified
Raw History Blame Contribute Delete
12.8 kB
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel, GenerationMixin
from transformers.modeling_outputs import CausalLMOutputWithPast
from .configuration_rose_x26 import RoseX26Config
class RMSNorm(nn.Module):
def __init__(self, d, eps=1e-6):
super().__init__()
self.weight = nn.Parameter(torch.ones(d))
self.eps = eps
def forward(self, x):
return F.rms_norm(x, (x.shape[-1],), self.weight, self.eps)
def rope_tables(T, hd, theta, frac, device):
rd = int(hd * frac) // 2 * 2
inv = 1.0 / (
theta ** (torch.arange(0, rd, 2, dtype=torch.float32, device=device) / rd)
)
ang = torch.arange(T, dtype=torch.float32, device=device)[:, None] * inv[None, :]
return ang.cos(), ang.sin(), rd
def apply_rope(x, cos, sin, rd, pos):
c = cos[pos].to(x.dtype)[None, None]
s = sin[pos].to(x.dtype)[None, None]
xr, xp = x[..., :rd], x[..., rd:]
x1, x2 = xr.chunk(2, dim=-1)
return torch.cat([x1 * c - x2 * s, x2 * c + x1 * s, xp], dim=-1)
class HybridCache:
"""Full layers: growing KV. SWA layers: rolling ring capped at window."""
def __init__(self, cfg, B, device, dtype):
self.cfg = cfg
self.k = [None] * cfg.n_layers
self.v = [None] * cfg.n_layers
self.len = 0
def get_seq_length(self, layer_idx=0):
return self.len
def get_max_cache_shape(self):
return -1
def reset(self):
self.k = [None] * self.cfg.n_layers
self.v = [None] * self.cfg.n_layers
self.len = 0
def update(self, k, v, i):
if self.k[i] is None:
self.k[i] = k
self.v[i] = v
else:
self.k[i] = torch.cat([self.k[i], k], dim=2)
self.v[i] = torch.cat([self.v[i], v], dim=2)
if self.cfg.layer_pattern[i % len(self.cfg.layer_pattern)] == "swa":
W = self.cfg.sliding_window
if self.k[i].shape[2] > W:
self.k[i] = self.k[i][:, :, -W:]
self.v[i] = self.v[i][:, :, -W:]
if i == self.cfg.n_layers - 1:
self.len += k.shape[2]
return self.k[i], self.v[i]
def depth_route(sources, residual, proj, norm):
"""Delta Attention Residuals (arXiv:2605.18855).
Additive softmax routing over delta sources. At zero-init the query is
zero -> uniform softmax -> adds the MEAN of sources (bounded perturbation,
NOT exact identity). The residual stream is always preserved.
"""
V = torch.stack(sources) # (n, B, T, D)
K = norm(V)
logits = torch.einsum("d,nbtd->nbt", proj.weight[0], K)
a = logits.softmax(0)
out = residual + torch.einsum("nbt,nbtd->btd", a, V)
sharpness = a.max(dim=0).values.mean()
return out, sharpness
class Attn(nn.Module):
def __init__(self, cfg, i):
super().__init__()
self.i = i
d = cfg.d_model
hd = cfg.head_dim
self.is_full = cfg.layer_pattern[i % len(cfg.layer_pattern)] == "full"
self.nh = cfg.n_heads_full if self.is_full else cfg.n_heads_swa
self.nkv = cfg.n_kv_heads
self.hd = hd
self.rep = self.nh // self.nkv
self.q = nn.Linear(d, self.nh * hd, bias=False)
self.k = nn.Linear(d, self.nkv * hd, bias=False)
self.v = nn.Linear(d, self.nkv * hd, bias=False)
self.o = nn.Linear(self.nh * hd, d, bias=False)
self.o._std_scale = True
self.q_norm = RMSNorm(hd, cfg.rms_norm_eps)
self.k_norm = RMSNorm(hd, cfg.rms_norm_eps)
gate = cfg.gate_full if self.is_full else cfg.gate_swa
self.g_proj = nn.Linear(d, self.nh, bias=False) if gate else None
self.window = cfg.sliding_window
self.frac = cfg.partial_rope_frac
self.use_flex = cfg.use_flex_attention
self._bm_key = None
self._bm = None
def forward(self, x, cos, sin, pos, cache=None):
B, T, _ = x.shape
q = self.q_norm(self.q(x).view(B, T, self.nh, self.hd)).transpose(1, 2)
k = self.k_norm(self.k(x).view(B, T, self.nkv, self.hd)).transpose(1, 2)
v = self.v(x).view(B, T, self.nkv, self.hd).transpose(1, 2)
rd = int(self.hd * self.frac) // 2 * 2
q = apply_rope(q, cos, sin, rd, pos)
k = apply_rope(k, cos, sin, rd, pos)
if cache is not None:
k, v = cache.update(k, v, self.i)
if q.shape[2] == 1:
# Decode: the cache IS the window, no mask needed.
y = F.scaled_dot_product_attention(q, k, v, enable_gqa=self.rep > 1)
elif self.is_full:
y = F.scaled_dot_product_attention(
q, k, v, is_causal=True, enable_gqa=self.rep > 1
)
else:
Tq, Tk = q.shape[2], k.shape[2]
off = Tk - Tq
if self.use_flex and self.training:
from torch.nn.attention.flex_attention import (
flex_attention, create_block_mask,
)
key = (Tq, Tk)
if self._bm_key != key:
def m(b, h, qi, ki):
return (qi + off >= ki) & (qi + off - ki < self.window)
self._bm = create_block_mask(
m, None, None, Tq, Tk, device=q.device
)
self._bm_key = key
kr = k.repeat_interleave(self.rep, dim=1)
vr = v.repeat_interleave(self.rep, dim=1)
y = flex_attention(q, kr, vr, block_mask=self._bm)
else:
qi = torch.arange(Tq, device=q.device)[:, None] + off
ki = torch.arange(Tk, device=q.device)[None, :]
mask = (qi >= ki) & (qi - ki < self.window)
y = F.scaled_dot_product_attention(
q, k, v, attn_mask=mask, enable_gqa=self.rep > 1
)
y = y.transpose(1, 2).contiguous()
gm = None
if self.g_proj is not None:
g = torch.sigmoid(self.g_proj(x))
gm = g.mean()
y = y * g.unsqueeze(-1)
return self.o(y.view(B, T, self.nh * self.hd)), gm
class MLP(nn.Module):
def __init__(self, d, f):
super().__init__()
self.g = nn.Linear(d, f, bias=False)
self.u = nn.Linear(d, f, bias=False)
self.d = nn.Linear(f, d, bias=False)
self.d._std_scale = True
def forward(self, x):
return self.d(F.silu(self.g(x)) * self.u(x))
class Block(nn.Module):
def __init__(self, cfg, i):
super().__init__()
d = cfg.d_model
self.i = i
self.B = cfg.delta_block_size
self.n1 = RMSNorm(d, cfg.rms_norm_eps)
self.n2 = RMSNorm(d, cfg.rms_norm_eps)
self.attn = Attn(cfg, i)
self.mlp = MLP(d, cfg.ffn_dim)
self.attn_proj = nn.Linear(d, 1, bias=False)
self.attn_rn = RMSNorm(d, cfg.rms_norm_eps)
self.mlp_proj = nn.Linear(d, 1, bias=False)
self.mlp_rn = RMSNorm(d, cfg.rms_norm_eps)
nn.init.zeros_(self.attn_proj.weight)
nn.init.zeros_(self.mlp_proj.weight)
def forward(self, x, deltas, anchor, cos, sin, pos, cache=None):
# --- attention sublayer with Delta routing ---
if self.i == 0:
h = x
s1 = torch.zeros((), device=x.device)
else:
src = list(deltas) + [x - anchor]
h, s1 = depth_route(src, x, self.attn_proj, self.attn_rn)
a, gm = self.attn(self.n1(h), cos, sin, pos, cache)
x = x + a
# --- MLP sublayer with Delta routing ---
h, s2 = depth_route(
list(deltas) + [x - anchor], x, self.mlp_proj, self.mlp_rn
)
x = x + self.mlp(self.n2(h))
stats = torch.stack([
s1, s2, gm if gm is not None else torch.zeros((), device=x.device)
])
return x, x - anchor, stats
class RoseX26Model(PreTrainedModel):
config_class = RoseX26Config
def __init__(self, cfg):
super().__init__(cfg)
self.cfg = cfg
self.embed = nn.Embedding(cfg.padded_vocab_size, cfg.d_model)
self.layers = nn.ModuleList([Block(cfg, i) for i in range(cfg.n_layers)])
self.norm = RMSNorm(cfg.d_model, cfg.rms_norm_eps)
cf, sf, _ = rope_tables(
cfg.max_position_embeddings, cfg.head_dim,
cfg.rope_theta_full, cfg.partial_rope_frac, "cpu",
)
cs, ss, _ = rope_tables(
cfg.max_position_embeddings, cfg.head_dim,
cfg.rope_theta_swa, cfg.partial_rope_frac, "cpu",
)
self.register_buffer("cos_f", cf, persistent=False)
self.register_buffer("sin_f", sf, persistent=False)
self.register_buffer("cos_s", cs, persistent=False)
self.register_buffer("sin_s", ss, persistent=False)
@torch.no_grad()
def update_rope_full(self, theta):
cf, sf, _ = rope_tables(
self.cfg.max_position_embeddings, self.cfg.head_dim,
theta, self.cfg.partial_rope_frac, self.cos_f.device,
)
self.cos_f.copy_(cf)
self.sin_f.copy_(sf)
self.cfg.rope_theta_full = float(theta)
def forward(self, ids, pos, cache=None, use_ckpt=False):
x = self.embed(ids)
deltas = [x]
anchor = x
stats = []
for i, ly in enumerate(self.layers):
cos, sin = (self.cos_f, self.sin_f) if ly.attn.is_full else (self.cos_s, self.sin_s)
if use_ckpt and self.training:
from torch.utils.checkpoint import checkpoint
x, d, st = checkpoint(
ly, x, list(deltas), anchor, cos, sin, pos, cache,
use_reentrant=False,
)
else:
x, d, st = ly(x, deltas, anchor, cos, sin, pos, cache)
stats.append(st)
if (i + 1) % ly.B == 0:
deltas.append(d)
anchor = x
return self.norm(x), torch.stack(stats)
class RoseX26ForCausalLM(PreTrainedModel, GenerationMixin):
config_class = RoseX26Config
_tied_weights_keys = ["lm_head.weight"]
def __init__(self, cfg):
super().__init__(cfg)
self.model = RoseX26Model(cfg)
self.lm_head = nn.Linear(cfg.d_model, cfg.padded_vocab_size, bias=False)
if cfg.tie_embeddings:
self.lm_head.weight = self.model.embed.weight
self.apply(self._init)
if cfg.tie_embeddings:
self.lm_head.weight = self.model.embed.weight
def _init(self, m):
if isinstance(m, nn.Linear):
# Preserve zero-init routing queries (shape[0] == 1).
if m.weight.shape[0] == 1 and m.weight.abs().sum() == 0:
return
std = (
0.02 / math.sqrt(2 * self.config.n_layers)
if getattr(m, "_std_scale", False) else 0.02
)
nn.init.normal_(m.weight, std=std)
elif isinstance(m, nn.Embedding):
nn.init.normal_(m.weight, std=0.02)
def get_input_embeddings(self):
return self.model.embed
def set_input_embeddings(self, e):
self.model.embed = e
def head_weight(self):
return self.model.embed.weight
def forward(self, input_ids, attention_mask=None, position_ids=None,
past_key_values=None, use_cache=False, cache_position=None,
labels=None):
cfg = self.config
if cache_position is None:
past = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past, past + input_ids.shape[1], device=input_ids.device
)
if past_key_values is None and use_cache:
past_key_values = HybridCache(
cfg, input_ids.shape[0], input_ids.device, input_ids.dtype
)
h, _ = self.model(input_ids, cache_position, past_key_values if use_cache else None)
logits = F.linear(h, self.head_weight()[: cfg.vocab_size])
return CausalLMOutputWithPast(
loss=None, logits=logits,
past_key_values=past_key_values if use_cache else None,
)
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
cache_position=None, attention_mask=None, **kw):
if past_key_values is not None:
if cache_position is not None:
input_ids = input_ids[:, cache_position[-input_ids.shape[1]:]]
else:
input_ids = input_ids[:, -1:]
return {
"input_ids": input_ids,
"past_key_values": past_key_values,
"use_cache": True,
"cache_position": cache_position,
}