"""Recurloop Transformer inference in the checkpoint layout.""" import math from types import SimpleNamespace import torch from torch import nn from torch.nn import functional as F from transformers import GenerationMixin, PreTrainedModel from transformers.modeling_outputs import CausalLMOutput from .configuration_recurloop import RecurloopConfig class RMSNorm(nn.Module): def __init__(self, dim, eps): super().__init__() self.weight = nn.Parameter(torch.ones(dim)) self.eps = eps def forward(self, x): with torch.autocast(x.device.type, enabled=False): u = x.float() return (u * torch.rsqrt(u.square().mean(-1, keepdim=True) + self.eps)).to(x.dtype) * self.weight class Router(nn.Module): def __init__(self, d): super().__init__() self.layer_norm = nn.LayerNorm(d, eps=1e-6) self.static_alpha = nn.Parameter(torch.empty(2, 3)) self.static_beta = nn.Parameter(torch.empty(2)) self.dynamic_alpha_fn = nn.Parameter(torch.empty(d, 3)) self.dynamic_beta_fn = nn.Parameter(torch.empty(d)) self.dynamic_alpha_scale = nn.Parameter(torch.empty(1)) self.dynamic_beta_scale = nn.Parameter(torch.empty(1)) def read(self, x): with torch.autocast(x.device.type, enabled=False): h = x.float() w = None if self.layer_norm.weight is None else self.layer_norm.weight.float() bias = None if self.layer_norm.bias is None else self.layer_norm.bias.float() z = F.layer_norm(h, self.layer_norm.normalized_shape, w, bias, self.layer_norm.eps) a = self.static_alpha.float() + self.dynamic_alpha_scale.float() * torch.tanh(z @ self.dynamic_alpha_fn.float()) b = self.static_beta.float() + self.dynamic_beta_scale.float() * torch.tanh(z @ self.dynamic_beta_fn.float()) y = a.transpose(-1, -2) @ h return y[..., 0, :].to(x.dtype), (y[..., 1:, :], b) def write(self, x, update, gates): residual, beta = gates with torch.autocast(x.device.type, enabled=False): return (residual + beta.unsqueeze(-1) * update.float().unsqueeze(-2)).to(x.dtype) def attention(q, k, v): return F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True).transpose(1, 2) class Attention(nn.Module): def __init__(self, d): super().__init__() self.c_q = nn.Linear(d, d, bias=False) self.c_k = nn.Linear(d, d, bias=False) self.c_v = nn.Linear(d, d, bias=False) self.c_proj = nn.Linear(d, d, bias=False) def forward(self, x, freq, attend): q, k, v = [proj(x).unflatten(-1, (-1, 128)) for proj in (self.c_q, self.c_k, self.c_v)] with torch.autocast(x.device.type, enabled=False): r = torch.cat((q, k), dim=2).unflatten(-1, (-1, 2)).float() a, b = r.unbind(-1) c, s = freq.float().unbind(-1) rotated = torch.stack((a*c-b*s, a*s+b*c), -1).flatten(3).to(q.dtype) q, k = rotated.chunk(2, dim=2) q, k = F.rms_norm(q, (128,)), F.rms_norm(k, (128,)) return self.c_proj(attend(q, k, v).contiguous().flatten(2)) class Block(nn.Module): def __init__(self, d, eps): super().__init__() self.norm_1, self.norm_2 = RMSNorm(d, eps), RMSNorm(d, eps) self.hc_attn, self.hc_mlp = Router(d), Router(d) self.attn = Attention(d) self.mlp = nn.ModuleDict(dict(fc=nn.Linear(d, 4*d, bias=False), proj=nn.Linear(4*d, d, bias=False))) def forward(self, x, freq, attend): u, gates = self.hc_attn.read(x) x = self.hc_attn.write(x, self.attn(self.norm_1(u), freq, attend), gates) u, gates = self.hc_mlp.read(x) mid = self.mlp.fc(self.norm_2(u)) out = self.mlp.proj(F.relu(mid).square() * 0.5) return self.hc_mlp.write(x, out, gates) class Injection(nn.Module): def __init__(self, d): super().__init__() self.dt_bias = nn.Parameter(torch.empty(d)) self.A_log = nn.Parameter(torch.empty(d)) self.B = nn.Parameter(torch.empty(d, d)) def forward(self, x, p): dt = F.softplus(self.dt_bias) return x * torch.exp(-dt * torch.exp(self.A_log)) + dt * (p @ self.B.T) class Trunk(nn.Module): def __init__(self, config): super().__init__() d, eps = config.hidden_size, config.norm_eps self.config = SimpleNamespace(n_embd=d, num_attention_heads=d//128, init=SimpleNamespace(logit_scale=1.0)) self.emb_scale = 1.0 self.register_buffer("freqs_cis", torch.empty(1, config.max_position_embeddings, 1, 64, 2)) self.transformer = nn.ModuleDict(dict(wte=nn.Embedding(config.vocab_size, d), ln_prelude=RMSNorm(d, eps), adapter=Injection(d), C=nn.Linear(d,d,bias=False), ln_f=RMSNorm(d, eps))) for group in ("prelude", "core_block", "coda"): self.transformer[group] = nn.ModuleList(Block(d, eps) for _ in range(config.stage_depth)) self.lm_head = nn.Linear(d, config.vocab_size, bias=False) self.lm_head.weight = self.transformer.wte.weight def initialize_state(self, template): std = math.sqrt(2 / (5 * template.shape[-1])) state = torch.randn_like(template, memory_format=torch.contiguous_format) return nn.init.trunc_normal_(state, std=std, a=-3*std, b=3*std) class RecurloopForCausalLM(PreTrainedModel, GenerationMixin): config_class = RecurloopConfig base_model_prefix = "base" _tied_weights_keys = ["base.lm_head.weight"] def __init__(self, config): super().__init__(config) self.base = Trunk(config) self.U = nn.Linear(config.hidden_size, config.hidden_size, bias=False) self.G = nn.Linear(config.hidden_size, config.hidden_size, bias=False) self.post_init() def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs): out = {"input_ids": input_ids} if attention_mask is not None: out["attention_mask"] = attention_mask return out def get_input_embeddings(self): return self.base.transformer.wte def get_output_embeddings(self): return self.base.lm_head def inject_feedback(self, e, previous, boundary): eps = self.config.norm_eps gate = self.G(F.rms_norm(e, (e.size(-1),), eps=eps)).sigmoid() f = F.rms_norm(self.U(previous)*gate, (e.size(-1),), eps=eps) scale = (e.float().square().mean(-1, keepdim=True) + eps).sqrt() return e + 0.3 * (f * scale.to(f.dtype)).masked_fill(boundary.unsqueeze(-1), 0) def initial(self, template, update, pass_index, rank=0): devices = [template.device.index] if template.is_cuda else [] with torch.random.fork_rng(devices=devices): torch.manual_seed(42 + 100003*int(update) + 101*rank + 1009*pass_index) return self.base.initialize_state(template) def trunk(self, z, init, freq, depth, attend=attention): t = self.base.transformer for block in t.prelude: z = block(z, freq, attend) p = t.ln_prelude(z) x = torch.stack((init,init), -2) for _ in range(depth): x = t.adapter(x,p) for block in t.core_block: x = block(x, freq, attend) x = t.C(x) for block in t.coda: x = block(x, freq, attend) return t.ln_f(x.sum(-2)) def forward( self, input_ids, attention_mask=None, token_type_ids=None, use_cache=None, passes=None, depth=None, update=0, rank=0, labels=None, initial_order=None, **kwargs, ): if input_ids.shape[1] > self.config.max_position_embeddings: raise ValueError("Input exceeds the checkpoint context length") if attention_mask is not None and not bool(attention_mask.all()): raise ValueError("Score unpadded sequences, or group inputs with identical length") e = self.get_input_embeddings()(input_ids) boundary = F.pad(input_ids[:, :-1].eq(1), (1,0), value=True) freq = self.base.freqs_cis[:, :input_ids.size(1)] passes = self.config.passes if passes is None else passes depth = self.config.core_iterations if depth is None else depth if passes < 1 or depth < 1: raise ValueError("passes and depth must be positive") h = None for k in range(passes): second = e if h is None else self.inject_feedback(e, F.pad(h[:, :-1], (0,0,1,0)), boundary) init = self.initial(e, update, k, rank) if initial_order is not None: init = init.index_select(0, torch.as_tensor(initial_order, device=init.device)) h = self.trunk(torch.stack((e,second), -2), init, freq, depth) logits = (h @ self.base.lm_head.weight.T).float() loss = None if labels is None else F.cross_entropy(logits[:, :-1].flatten(0,1), labels[:, 1:].flatten()) return CausalLMOutput(loss=loss, logits=logits)