""" Alus 0.5 — m.ai's from-scratch language model. Two kinds of mixing layer, stacked 3:1: Flow layer (gated retention) linear time, constant memory. A learned, data-dependent decay per head decides what to keep. Trains in parallel (chunkwise), runs as an RNN at inference. Lens layer (window attention) exact recall over the last `window` tokens, with RoPE. One code path covers training, chunked prefill and token-by-token decoding: logits, state = model.step(ids, state, pos0) `state` carries everything needed to continue, so inference memory stays flat no matter how long the conversation gets (that is how a small model streams 1M+ tokens on an 8 GB Mac). Honest limit: memory is constant, so detail from very far back fades; the Lens layers keep the last `window` tokens exact. """ import math from dataclasses import dataclass, asdict import torch import torch.nn as nn import torch.nn.functional as F # ------------------------------------------------------------------ tokens + chat format # GPT-2 BPE via tiktoken; special tokens live in the unused padded slots 50257..50303. EOT = 50256 SYS, USR, AST, END = 50257, 50258, 50259, 50260 N_REAL = 50257 # ids >= this are special / unused def get_tokenizer(): import tiktoken return tiktoken.get_encoding("gpt2") def encode_chat(enc, messages, add_generation_prompt=True): """messages: [{"role": "system"|"user"|"assistant", "content": str}, ...] Returns (ids, loss_mask). loss_mask is 1 only on assistant reply tokens and their <|end|>.""" role_tok = {"system": SYS, "user": USR, "assistant": AST} ids, mask = [], [] for m in messages: body = enc.encode(m["content"], disallowed_special=()) train = 1 if m["role"] == "assistant" else 0 ids += [role_tok[m["role"]]] + body + [END] mask += [0] + [train] * (len(body) + 1) if add_generation_prompt: ids.append(AST) mask.append(0) return ids, mask def decode(enc, ids): return enc.decode([i for i in ids if i < N_REAL]) # ------------------------------------------------------------------ config + tiers @dataclass class AlusConfig: vocab_size: int = 50304 n_layer: int = 12 n_embd: int = 768 n_head: int = 12 lens_every: int = 4 # every Nth layer is a Lens (attention) layer window: int = 1024 # Lens attention span in tokens chunk: int = 64 # Flow chunk size for parallel training / prefill rope_base: float = 10000.0 rope_cache_len: int = 2048 mlp_mult: float = 8 / 3 norm_eps: float = 1e-5 TIERS = { # the Alus family, smallest to largest "drop": dict(n_layer=8, n_embd=384, n_head=6), # ~34M phones, instant "stream": dict(n_layer=12, n_embd=768, n_head=12), # ~129M local inference target "tide": dict(n_layer=24, n_embd=1024, n_head=16), # ~380M needs ~8B tokens to shine "deep": dict(n_layer=32, n_embd=1536, n_head=16), # ~1.04B research; requires cloud training } TIER_NAMES = {"drop": "Spark", "stream": "Pulse", "tide": "Horizon", "deep": "Orbit"} def model_name(tier): return TIER_NAMES.get(tier, tier.title()) def tier_config(name, **overrides): return AlusConfig(**{**TIERS[name], **overrides}) # ------------------------------------------------------------------ building blocks class RMSNorm(nn.Module): def __init__(self, d, eps=1e-5): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(d)) def forward(self, x): xf = x.float() xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps) return xf.to(x.dtype) * self.weight class RoPE(nn.Module): """Rotary positions. Angles are computed in float64 on CPU to reduce precision loss at large positions.""" def __init__(self, hd, base, cache_len): super().__init__() self.hd, self.base = hd, base cos, sin = self._make(0, cache_len) self.register_buffer("cos", cos, persistent=False) self.register_buffer("sin", sin, persistent=False) def _make(self, pos0, T): inv = 1.0 / (self.base ** (torch.arange(0, self.hd, 2, dtype=torch.float64) / self.hd)) ang = torch.outer(torch.arange(pos0, pos0 + T, dtype=torch.float64), inv) return ang.cos().float(), ang.sin().float() def get(self, pos0, T, device): if pos0 + T <= self.cos.shape[0]: return self.cos[pos0:pos0 + T], self.sin[pos0:pos0 + T] cos, sin = self._make(pos0, T) return cos.to(device), sin.to(device) def apply_rope(x, cos, sin): # x: B,H,T,hd x1, x2 = x.chunk(2, dim=-1) cos, sin = cos.to(x.dtype), sin.to(x.dtype) return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1) def flow_scan(q, k, v, la, R0, C, want_state): # Cast BEFORE matmul. Casting a half-precision result cannot repair overflow. with torch.autocast(device_type=q.device.type, enabled=False): return _flow_scan_fp32(q.float(), k.float(), v.float(), la.float(), None if R0 is None else R0.float(), C, want_state) def _flow_scan_fp32(q, k, v, la, R0, C, want_state): """Chunkwise gated retention. out_t = sum_{j<=t} exp(c_t - c_j) (q_t . k_j) v_j, with c = cumsum(la), la = log decay < 0. q,k,v: B,H,T,D la: B,H,T (float32) R0: B,H,D,D float32 state or None. Every exponent is masked to <= 0 before exp, so it never overflows.""" B, H, T, D = q.shape C = min(C, T) pad = (-T) % C if pad: q, k, v = (F.pad(t, (0, 0, 0, pad)) for t in (q, k, v)) la = F.pad(la, (0, pad)) # log-decay 0 on padding = no decay, and k=v=0 adds nothing N = (T + pad) // C dt = q.dtype q, k, v = (t.reshape(B, H, N, C, D) for t in (q, k, v)) b = la.reshape(B, H, N, C).cumsum(-1) # cumulative log decay inside each chunk g = b[..., -1] # total log decay of each chunk tri = torch.ones(C, C, dtype=torch.bool, device=q.device).tril() Dm = (b.unsqueeze(-1) - b.unsqueeze(-2)).masked_fill(~tri, float("-inf")).exp() y = (((q @ k.transpose(-1, -2)).float() * Dm).to(dt) @ v).float() # intra-chunk wk = (k.float() * (g.unsqueeze(-1) - b).exp().unsqueeze(-1)).to(dt) S = (wk.transpose(-1, -2) @ v).float() # each chunk's state, decayed to its end # Carry one D x D state across chunks. A dense N x N chunk matrix # would make training/prefill quadratic in the number of chunks. state = torch.zeros(B, H, D, D, device=q.device, dtype=torch.float32) if R0 is None else R0 outputs = [] for n in range(N): incoming = (q[:, :, n].float() * b[:, :, n].exp().unsqueeze(-1)) @ state outputs.append(y[:, :, n] + incoming) state = g[:, :, n].exp()[..., None, None] * state + S[:, :, n] y = torch.stack(outputs, dim=2).reshape(B, H, N * C, D)[:, :, :T] Rout = state if want_state else None return y, Rout class FlowLayer(nn.Module): def __init__(self, cfg): super().__init__() d, H = cfg.n_embd, cfg.n_head self.H, self.hd, self.chunk, self.eps = H, d // H, cfg.chunk, cfg.norm_eps self.qkvg = nn.Linear(d, 4 * d, bias=False) self.decay = nn.Linear(d, H, bias=True) self.hnorm = nn.Parameter(torch.ones(H, self.hd)) self.out = nn.Linear(d, d, bias=False) def init_decay(self): # half-lives log-spaced from ~2 tokens (local heads) to ~70k tokens (long-memory heads) with torch.no_grad(): rate = torch.exp(torch.linspace(math.log(0.3), math.log(1e-5), self.H)) self.decay.bias.copy_(torch.log(torch.expm1(rate))) def forward(self, x, state, pos0, want_state, rope): B, T, d = x.shape H, hd = self.H, self.hd q, k, v, g = self.qkvg(x).split(d, dim=-1) q = q.view(B, T, H, hd).transpose(1, 2) k = k.view(B, T, H, hd).transpose(1, 2) * hd ** -0.5 v = v.view(B, T, H, hd).transpose(1, 2) la = -F.softplus(self.decay(x).float()).transpose(1, 2) y, new_state = flow_scan(q, k, v, la, state, self.chunk, want_state) y = y * torch.rsqrt(y.pow(2).mean(-1, keepdim=True) + self.eps) * self.hnorm[None, :, None, :] y = y.to(x.dtype).transpose(1, 2).reshape(B, T, d) * F.silu(g) return self.out(y), new_state class LensLayer(nn.Module): def __init__(self, cfg): super().__init__() d, H = cfg.n_embd, cfg.n_head self.H, self.hd, self.window = H, d // H, cfg.window self.qkv = nn.Linear(d, 3 * d, bias=False) self.out = nn.Linear(d, d, bias=False) def forward(self, x, state, pos0, want_state, rope): B, T, d = x.shape q, k, v = (t.view(B, T, self.H, self.hd).transpose(1, 2) for t in self.qkv(x).split(d, dim=-1)) cos, sin = rope.get(pos0, T, x.device) q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) if state is not None: k = torch.cat([state[0], k], dim=2) v = torch.cat([state[1], v], dim=2) L = k.shape[2] - T if L == 0 and T <= self.window: y = F.scaled_dot_product_attention(q, k, v, is_causal=True) else: qi = torch.arange(T, device=x.device)[:, None] + L kj = torch.arange(L + T, device=x.device)[None, :] mask = (kj <= qi) & (kj > qi - self.window) y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) new_state = None if want_state: keep = max(self.window - 1, 1) new_state = (k[:, :, -keep:].clone(), v[:, :, -keep:].clone()) return self.out(y.transpose(1, 2).reshape(B, T, d)), new_state class SwiGLU(nn.Module): def __init__(self, cfg): super().__init__() hidden = 64 * math.ceil(cfg.mlp_mult * cfg.n_embd / 64) self.w12 = nn.Linear(cfg.n_embd, 2 * hidden, bias=False) self.w3 = nn.Linear(hidden, cfg.n_embd, bias=False) def forward(self, x): a, b = self.w12(x).chunk(2, dim=-1) return self.w3(F.silu(a) * b) class Block(nn.Module): def __init__(self, cfg, lens): super().__init__() self.n1, self.n2 = RMSNorm(cfg.n_embd, cfg.norm_eps), RMSNorm(cfg.n_embd, cfg.norm_eps) self.mix = LensLayer(cfg) if lens else FlowLayer(cfg) self.mlp = SwiGLU(cfg) def forward(self, x, state, pos0, want_state, rope): h, st = self.mix(self.n1(x), state, pos0, want_state, rope) x = x + h return x + self.mlp(self.n2(x)), st # ------------------------------------------------------------------ the model class Alus(nn.Module): def __init__(self, cfg: AlusConfig): super().__init__() self.cfg = cfg self.wte = nn.Embedding(cfg.vocab_size, cfg.n_embd) self.blocks = nn.ModuleList( [Block(cfg, lens=(i + 1) % cfg.lens_every == 0) for i in range(cfg.n_layer)]) self.norm = RMSNorm(cfg.n_embd, cfg.norm_eps) self.head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False) self.head.weight = self.wte.weight # tied self.rope = RoPE(cfg.n_embd // cfg.n_head, cfg.rope_base, cfg.rope_cache_len) self.apply(self._init) for n, p in self.named_parameters(): if n.endswith("mix.out.weight") or n.endswith("mlp.w3.weight"): nn.init.normal_(p, 0.0, 0.02 / math.sqrt(2 * cfg.n_layer)) for blk in self.blocks: if isinstance(blk.mix, FlowLayer): blk.mix.init_decay() @staticmethod def _init(m): if isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0.0, 0.02) if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.Embedding): nn.init.normal_(m.weight, 0.0, 0.02) def num_params(self): return sum(p.numel() for p in self.parameters()) def _trunk(self, idx, state, pos0, want_state): x = self.wte(idx) new = [] for i, blk in enumerate(self.blocks): x, st = blk(x, None if state is None else state[i], pos0, want_state, self.rope) new.append(st) return self.norm(x), new def forward(self, idx, targets=None): """Training entry point. targets == -1 are ignored (used to mask prompts during SFT).""" x, _ = self._trunk(idx, None, 0, False) logits = self.head(x) loss = None if targets is not None: loss = F.cross_entropy(logits.float().view(-1, logits.size(-1)), targets.reshape(-1), ignore_index=-1) return logits, loss @torch.no_grad() def step(self, idx, state=None, pos0=0, last_only=True): """Inference: feed ids (B,T) on top of `state`; returns (logits, new_state).""" x, new = self._trunk(idx, state, pos0, True) return self.head(x[:, -1:] if last_only else x), new def configure_optimizer(self, weight_decay, lr, betas): decay = [p for p in self.parameters() if p.dim() >= 2] no_decay = [p for p in self.parameters() if p.dim() < 2] groups = [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}] return torch.optim.AdamW(groups, lr=lr, betas=betas) @torch.no_grad() def generate(self, ids, max_new_tokens=256, temperature=0.8, top_k=50, top_p=0.95, rep_penalty=1.1, stop=(END, EOT), watermark=None, prefill_chunk=512, cancelled=None, allow_chat_end=True): """Streams new token ids one at a time. ids: list[int].""" dev = next(self.parameters()).device if not ids or prefill_chunk < 1: raise ValueError('Provide a nonempty prompt and positive prefill chunk size') state, pos, logits = None, 0, None for i in range(0, len(ids), prefill_chunk): if cancelled is not None and cancelled(): return piece = torch.tensor([ids[i:i + prefill_chunk]], device=dev) logits, state = self.step(piece, state, pos) pos += piece.shape[1] generated = [] # Penalize repetition in the answer, not vocabulary copied from the question. recent, prev = [], ids[-1] for _ in range(max_new_tokens): if cancelled is not None and cancelled(): return l = logits[0, -1].float().cpu().clone() l[N_REAL:] = float("-inf") if allow_chat_end: l[END] = logits[0, -1, END].float().cpu() repeated = sorted(t for t in set(recent) if t < N_REAL and t not in stop) if rep_penalty != 1.0 and repeated: r = torch.tensor(repeated) l[r] = torch.where(l[r] > 0, l[r] / rep_penalty, l[r] * rep_penalty) if watermark is not None: l = watermark.bias(l, prev) if temperature <= 0: tok = int(l.argmax()) else: l = l / temperature if top_k: kth = torch.topk(l, min(top_k, l.numel())).values[-1] l[l < kth] = float("-inf") p = F.softmax(l, dim=-1) if top_p < 1.0: sp, si = torch.sort(p, descending=True) cut = sp.cumsum(0) - sp > top_p sp[cut] = 0 p = torch.zeros_like(p).scatter(0, si, sp) tok = int(torch.multinomial(p / p.sum(), 1)) if tok in stop: break candidate = generated + [tok] repeating = any( len(candidate) >= width * 3 and candidate[-width:] == candidate[-2 * width:-width] == candidate[-3 * width:-2 * width] for width in (1, 2, 3, 4, 8, 12, 16) ) if repeating: break generated.append(tok) yield tok logits, state = self.step(torch.tensor([[tok]], device=dev), state, pos) pos += 1 prev = tok recent = (recent + [tok])[-64:] # ------------------------------------------------------------------ watermark class Watermark: """Invisible text watermark (green-list method, Kirchenbauer et al. 2023). A secret key splits the vocabulary into 'green' and 'red' halves that change with every previous token; generation nudges toward green. Text reads normally, but `detect` shows a high z-score (a statistical indication, not proof of authorship) for anything long enough. Keep the key secret.""" def __init__(self, key, gamma=0.25, delta=2.0, vocab=50304): self.key, self.gamma, self.delta, self.vocab = int(key) & 0x7FFFFFFF, gamma, delta, vocab self._all = torch.arange(vocab, dtype=torch.int64) def _green(self, tok, prev): h = (tok * 0x5BD1E995 + prev * 0x27D4EB2D + self.key) & 0x7FFFFFFF h = h ^ (h >> 15) h = (h * 0x2C1B3C6D) & 0x7FFFFFFF h = h ^ (h >> 12) h = (h * 0x297A2D39) & 0x7FFFFFFF h = h ^ (h >> 15) return (h % 10000) < int(self.gamma * 10000) def bias(self, logits, prev): return logits + self.delta * self._green(self._all, torch.tensor(int(prev))).float() def detect(self, ids): if len(ids) < 2: return {"tokens": 0, "z": 0.0, "verdict": "too short"} t = torch.tensor(ids[1:], dtype=torch.int64) p = torch.tensor(ids[:-1], dtype=torch.int64) n = len(t) green = int(self._green(t, p).sum()) z = (green - self.gamma * n) / math.sqrt(n * self.gamma * (1 - self.gamma)) verdict = "m.ai" if z > 4 else ("likely m.ai" if z > 2 else "no watermark") return {"tokens": n, "green": green, "z": round(z, 2), "verdict": verdict} # ------------------------------------------------------------------ checkpoints def cpu_state(value): if isinstance(value, torch.Tensor): return value.detach().cpu() if isinstance(value, dict): return {k: cpu_state(v) for k, v in value.items()} if isinstance(value, list): return [cpu_state(v) for v in value] if isinstance(value, tuple): return tuple(cpu_state(v) for v in value) return value def save_checkpoint(path, model, step=0, tier=None, extra=None): sd = {k: v.detach().cpu() for k, v in model.state_dict().items() if k != "head.weight"} sd["head.weight"] = sd["wte.weight"] from pathlib import Path path = Path(path) temporary = path.with_suffix(path.suffix + ".tmp") torch.save({"model": sd, "config": asdict(model.cfg), "step": step, "tier": tier, **cpu_state(extra or {})}, temporary) temporary.replace(path) def load_checkpoint(path, device="cpu", dtype=torch.float32): # Memory-map weights and construct only metadata before assigning tensors. # Avoid initializing a second full fp32 model on an 8 GB machine. ck = torch.load(path, map_location="cpu", weights_only=True, mmap=True) with torch.device("meta"): model = Alus(AlusConfig(**ck["config"])) converted, shared = {}, {} for name, value in ck["model"].items(): key = (value.data_ptr(), tuple(value.shape), value.dtype) if key not in shared: shared[key] = value.to(device=device, dtype=dtype) converted[name] = shared[key] model.load_state_dict(converted, assign=True) model.head.weight = model.wte.weight model.rope = RoPE(model.cfg.n_embd // model.cfg.n_head, model.cfg.rope_base, model.cfg.rope_cache_len).to(device) return model.eval(), ck