"""Samothrace: looped Qwen3.5 with per-step LoRA and per-step gated scaling. Layout (Qwen3.5-4B, 32 layers = 8 x [DeltaNet x3 + Attn x1]): prelude = layers [0, core_start) run once, frozen core = layers [core_start, core_end) run K times coda = layers [core_end, 32) run once, frozen Step 1 of the core is the original layer stack (no adapter), so with a_k = 0 the model is bit-identical to the base model for every K. Step k >= 2: h <- h + a_k * (Core(h; W + dW_k) - h), a_k in R^hidden, init 0. Memory tricks (training): * prelude + core step 1 contain no trainable params -> run under no_grad, no activations kept. * steps 2..K and coda run with per-layer activation checkpointing. * per-step LoRA lives in one module per Linear (stacked A/B), no peft. * the LM head + CE is computed in chunks (vocab is 248k), see losses.py. """ from __future__ import annotations import copy import math from dataclasses import dataclass, field import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint # ---- memory-bounded attention (T4: no flash-attn, head_dim 256 -> SDPA falls back to math) ---- ATTN_QCHUNK = 512 def _attn_chunk(q, k, v, m, qs, scaling): # q [B,H,c,D] = query positions qs..qs+c-1 (absolute); k,v [B,H,qs+c,D]; m: 4D mask slice or None (causal) if m is None: c, Tk = q.shape[2], k.shape[2] m = torch.arange(Tk, device=q.device)[None, :] <= torch.arange(qs, qs + c, device=q.device)[:, None] return F.scaled_dot_product_attention(q, k, v, attn_mask=m, scale=scaling) def chunked_causal_attention(module, query, key, value, attention_mask, dropout=0.0, scaling=None, **kwargs): """Causal attention in query chunks; each chunk is checkpointed when grads are on, so peak memory is O(chunk * T) instead of O(T^2) in forward and backward. Short / decode calls go to plain SDPA.""" from transformers.integrations.sdpa_attention import sdpa_attention_forward B, H, Tq, D = query.shape Tk = key.shape[2] if Tq <= ATTN_QCHUNK: return sdpa_attention_forward(module, query, key, value, attention_mask, dropout=dropout, scaling=scaling, **kwargs) rep = H // key.shape[1] if rep > 1: key = key.repeat_interleave(rep, dim=1) value = value.repeat_interleave(rep, dim=1) off = Tk - Tq # cached past length m4 = attention_mask if (attention_mask is not None and attention_mask.dim() == 4) else None grad = torch.is_grad_enabled() and (query.requires_grad or key.requires_grad or value.requires_grad) outs = [] for s in range(0, Tq, ATTN_QCHUNK): e = min(s + ATTN_QCHUNK, Tq) mc = None if m4 is None else m4[:, :, s:e, :off + e] args = (query[:, :, s:e], key[:, :, :off + e], value[:, :, :off + e], mc, off + s, scaling) outs.append(checkpoint(_attn_chunk, *args, use_reentrant=False) if grad else _attn_chunk(*args)) return torch.cat(outs, 2).transpose(1, 2).contiguous(), None def register_chunked_attention(name="samo_chunked"): from transformers import AttentionInterface from transformers.masking_utils import AttentionMaskInterface, sdpa_mask AttentionInterface.register(name, chunked_causal_attention) AttentionMaskInterface.register(name, sdpa_mask) return name @dataclass class LoopConfig: core_start: int = 8 core_end: int = 20 max_steps: int = 3 # K_max (step 1 = original pass) lora_r: int = 16 lora_alpha: int = 32 lora_dropout: float = 0.0 targets: tuple = ( # full attention "q_proj", "k_proj", "v_proj", "o_proj", # gated deltanet "in_proj_qkv", "in_proj_z", "out_proj", # mlp "gate_proj", "up_proj", "down_proj", ) gate_init: float = 0.0 # a_k init checkpoint_layers: bool = True class StepState: """Shared mutable 'which loop step is running' flag (0 = no adapter).""" def __init__(self): self.step = 0 class MultiStepLoRALinear(nn.Module): """y = W x + (alpha/r) * B_s A_s x for the active step s (s >= 1).""" def __init__(self, base: nn.Linear, n_steps: int, r: int, alpha: int, state: StepState, dropout: float = 0.0): super().__init__() self.base = base for p in self.base.parameters(): p.requires_grad_(False) self.state = state self.r, self.scale = r, alpha / r dev = base.weight.device # fp32 master params; cast to activation dtype at use self.lora_A = nn.Parameter(torch.empty(n_steps, r, base.in_features, device=dev, dtype=torch.float32)) self.lora_B = nn.Parameter(torch.zeros(n_steps, base.out_features, r, device=dev, dtype=torch.float32)) for s in range(n_steps): nn.init.kaiming_uniform_(self.lora_A[s], a=math.sqrt(5)) self.drop = nn.Dropout(dropout) if dropout > 0 else nn.Identity() @property def weight(self): # some HF code peeks at .weight return self.base.weight def forward(self, x): y = self.base(x) s = self.state.step if s <= 0: return y A = self.lora_A[s - 1].to(x.dtype) B = self.lora_B[s - 1].to(x.dtype) return y + (self.drop(x) @ A.t() @ B.t()) * self.scale def _wrap_linears(module: nn.Module, cfg: LoopConfig, state: StepState): n_adapt = cfg.max_steps - 1 for name, child in list(module.named_children()): if isinstance(child, nn.Linear) and name in cfg.targets: setattr(module, name, MultiStepLoRALinear(child, n_adapt, cfg.lora_r, cfg.lora_alpha, state, cfg.lora_dropout)) else: _wrap_linears(child, cfg, state) class Samothrace(nn.Module): def __init__(self, causal_lm: nn.Module, cfg: LoopConfig): super().__init__() self.lm = causal_lm self.cfg = cfg tm = causal_lm.model # Qwen3_5TextModel self.tcfg = tm.config L = self.tcfg.num_hidden_layers assert 0 < cfg.core_start < cfg.core_end < L for p in causal_lm.parameters(): p.requires_grad_(False) self.state = StepState() for i in range(cfg.core_start, cfg.core_end): _wrap_linears(tm.layers[i], cfg, self.state) H = self.tcfg.hidden_size dev = tm.embed_tokens.weight.device self.gates = nn.Parameter(torch.full((cfg.max_steps - 1, H), cfg.gate_init, device=dev, dtype=torch.float32)) self.n_core = cfg.core_end - cfg.core_start self._orig_idx = {i: self._get_idx(tm.layers[i]) for i in range(cfg.core_start, cfg.core_end)} # ---- helpers ----------------------------------------------------------- @staticmethod def _mixer(layer): return layer.linear_attn if getattr(layer, "block_type", getattr(layer, "layer_type", None)) == "linear_attention" else layer.self_attn def _get_idx(self, layer): return self._mixer(layer).layer_idx def _set_idx(self, layer, idx): self._mixer(layer).layer_idx = idx if hasattr(layer, "layer_idx"): layer.layer_idx = idx def virtual_idx(self, layer_i: int, step: int) -> int: """Cache slot of core layer `layer_i` at loop step `step` (1-based).""" if step == 1: return layer_i L = self.tcfg.num_hidden_layers return L + (step - 2) * self.n_core + (layer_i - self.cfg.core_start) def cache_config(self, K: int): """Text config whose layer list covers every (layer, step) cache slot.""" c = copy.deepcopy(self.tcfg) L = c.num_hidden_layers extra = [c.layer_types[i] for _ in range(K - 1) for i in range(self.cfg.core_start, self.cfg.core_end)] c.layer_types = list(c.layer_types) + extra c.num_hidden_layers = L + len(extra) return c def new_cache(self, K: int): from transformers import DynamicCache return DynamicCache(config=self.cache_config(K)) def trainable_parameters(self): return [p for p in self.parameters() if p.requires_grad] # ---- forward ----------------------------------------------------------- def _run_layer(self, layer, h, ctx, ckpt, step=0, vidx=None): # step / cache slot are bound here so checkpoint recomputation sees the same config def f(x): prev_step, prev_idx = self.state.step, self._get_idx(layer) self.state.step = step if vidx is not None: self._set_idx(layer, vidx) try: return layer(x, **ctx) finally: self.state.step = prev_step self._set_idx(layer, prev_idx) if ckpt and self.training and torch.is_grad_enabled(): return checkpoint(f, h, use_reentrant=False) return f(h) def _setup(self, input_ids, attention_mask, position_ids, cache, use_cache, inputs_embeds): from transformers.masking_utils import create_causal_mask try: from transformers.masking_utils import create_recurrent_attention_mask except ImportError: create_recurrent_attention_mask = None tm = self.lm.model if inputs_embeds is None: inputs_embeds = tm.embed_tokens(input_ids) B, T, _ = inputs_embeds.shape if position_ids is None: past = cache.get_seq_length() if cache is not None else 0 position_ids = torch.arange(T, device=inputs_embeds.device)[None].expand(B, -1) + past text_pos = position_ids mrope_pos = position_ids[None].expand(3, B, -1) mk = dict(config=self.tcfg, inputs_embeds=inputs_embeds, attention_mask=attention_mask, cache=cache, position_ids=text_pos) masks = {"full_attention": create_causal_mask(**mk)} masks["linear_attention"] = create_recurrent_attention_mask(**mk) if create_recurrent_attention_mask else attention_mask pos_emb = tm.rotary_emb(inputs_embeds, mrope_pos) def ctx(i): return dict(position_embeddings=pos_emb, attention_mask=masks[self.tcfg.layer_types[i]], position_ids=text_pos, cache=cache, use_cache=use_cache) return inputs_embeds, ctx def prefix(self, input_ids=None, attention_mask=None, position_ids=None, cache=None, use_cache=False, inputs_embeds=None): """Prelude + core step 1 (frozen, no adapter). Returns (h, ctx). In training this runs without a graph.""" h, ctx = self._setup(input_ids, attention_mask, position_ids, cache, use_cache, inputs_embeds) self.state.step = 0 with torch.set_grad_enabled(torch.is_grad_enabled() and not self.training): for i in range(0, self.cfg.core_end): h = self.lm.model.layers[i](h, **ctx(i)) h = h.detach() if self.training else h return h, ctx def from_prefix(self, h, ctx, K: int): """Loop steps 2..K + coda + final norm, starting from prefix() output.""" cfg, tm = self.cfg, self.lm.model assert 1 <= K <= cfg.max_steps ck = cfg.checkpoint_layers for k in range(2, K + 1): h_in = h for i in range(cfg.core_start, cfg.core_end): h = self._run_layer(tm.layers[i], h, ctx(i), ck, step=k - 1, vidx=self.virtual_idx(i, k)) g = self.gates[k - 2].to(h.dtype) h = h_in + g * (h - h_in) for i in range(cfg.core_end, self.tcfg.num_hidden_layers): h = self._run_layer(tm.layers[i], h, ctx(i), ck) return tm.norm(h) def hidden(self, input_ids=None, K: int = None, attention_mask=None, position_ids=None, cache=None, use_cache=False, inputs_embeds=None): """Returns final-normed hidden states [B, T, H].""" K = K or self.cfg.max_steps h, ctx = self.prefix(input_ids, attention_mask, position_ids, cache, use_cache, inputs_embeds) return self.from_prefix(h, ctx, K) def forward(self, input_ids=None, K=None, **kw): h = self.hidden(input_ids, K, **kw) return self.lm.lm_head(h) # ---- save / load adapters --------------------------------------------- def adapter_state_dict(self): return {n: p.detach().cpu() for n, p in self.named_parameters() if p.requires_grad} def load_adapter_state_dict(self, sd): missing = self.load_state_dict(sd, strict=False) return missing