"""NoTokenLM-Gen-5.5 -- PyTorch inference implementation. A faithful port of the JAX training code. Byte-level, tokenizer-free, hierarchical: bytes --(byte emb + hashed past-only n-gram emb + ROSA features)--> local encoder (conv, conv, windowed attention) --> entropy-placed patches (avg ~6, max 16 bytes) --> attention pooling --> trunk over patches: 5 super-blocks of [RWKV-7, NoPE gated attention, RWKV-7, RWKV-7] --> local decoder (4 windowed-attention blocks) --> 256-way byte logits Parameter names are identical to the dotted tensor names of the training checkpoints (e.g. ``trunk.l0.mix.Wr``, ``enc.0.conv``), so the safetensors file loads without any renaming. The frozen entropy patcher lives under the ``patcher.`` prefix. Only closed patches ever reach the decoder, so generation re-runs the (expensive) trunk only when a new patch closes. """ import math from typing import List, Optional import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from transformers import PreTrainedModel from transformers.modeling_outputs import CausalLMOutput from .configuration_notoken_gen55 import NoTokenGen55Config EOD = 0 BIG_DOC = 1 << 28 def _P(*shape): return nn.Parameter(torch.zeros(*shape)) # ============================================================================= small utilities def rms_norm(x, w, eps=1e-6): x32 = x.float() y = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + eps) * w.float() return y.to(x.dtype) def causal_conv(x, w, doc, dilation=1): """depthwise causal conv. x (B,T,D), w (K,D). Taps that fall into another document are zeroed.""" K, T = w.shape[0], x.shape[1] pad = (K - 1) * dilation xp = F.pad(x, (0, 0, pad, 0)) dp = F.pad(doc, (pad, 0), value=-1) out = 0.0 for i in range(K): sl = xp[:, i * dilation:i * dilation + T] if i != K - 1: sl = sl * (dp[:, i * dilation:i * dilation + T] == doc).unsqueeze(-1).to(x.dtype) out = out + w[i].to(x.dtype) * sl return out def rope_tables(n, dh, device): inv = 1.0 / (10000.0 ** (torch.arange(0, dh, 2, dtype=torch.float32, device=device) / dh)) ang = torch.arange(n, dtype=torch.float32, device=device)[:, None] * inv[None, :] return torch.cos(ang), torch.sin(ang) def apply_rope(x, cos, sin): dh = x.shape[-1] x1, x2 = x[..., :dh // 2], x[..., dh // 2:] c, s = cos[None, None, :, None, :].to(x.dtype), sin[None, None, :, None, :].to(x.dtype) return torch.cat([x1 * c - x2 * s, x1 * s + x2 * c], -1) def doc_ids(x): e = (x == EOD).long() return torch.cumsum(e, 1) - e class SwiGLU(nn.Module): def __init__(self, d, ff): super().__init__() self.w1, self.w3, self.w2 = _P(d, ff), _P(d, ff), _P(ff, d) def forward(self, x, scale=None): hid = F.silu(x @ self.w1.to(x.dtype)) * (x @ self.w3.to(x.dtype)) if scale is not None: hid = hid * scale.to(hid.dtype) return hid @ self.w2.to(x.dtype) # ============================================================================= entropy patcher (frozen) class PatcherLayer(nn.Module): def __init__(self, cfg): super().__init__() self.n1, self.n2, self.conv = _P(cfg.ent_d), _P(cfg.ent_d), _P(cfg.ent_k, cfg.ent_d) self.ffn = SwiGLU(cfg.ent_d, cfg.ent_ffn) class Patcher(nn.Module): """small causal TCN byte model; its next-byte entropy decides where patches start""" def __init__(self, cfg): super().__init__() self.emb, self.nf, self.head = _P(256, cfg.ent_d), _P(cfg.ent_d), _P(cfg.ent_d, 256) self.layers = nn.ModuleList([PatcherLayer(cfg) for _ in range(cfg.ent_layers)]) def forward(self, x, doc): h = self.emb[x] for i, L in enumerate(self.layers): h = h + causal_conv(rms_norm(h, L.n1), L.conv, doc, dilation=2 ** i) h = h + L.ffn(rms_norm(h, L.n2)) return rms_norm(h, self.nf) @ self.head # ============================================================================= local byte modules class LocalBlock(nn.Module): def __init__(self, kind, cfg): super().__init__() d, ff = cfg.d_loc, cfg.loc_ffn self.kind, self.heads, self.window, self.block = kind, cfg.loc_heads, cfg.loc_window, cfg.loc_block self.n1, self.n2 = _P(d), _P(d) self.ffn = SwiGLU(d, ff) if kind == "attn": self.wq, self.wk, self.wv, self.wo = _P(d, d), _P(d, d), _P(d, d), _P(d, d) else: self.conv = _P(cfg.conv_k, d) if cfg.de_byte: self.de = _P(cfg.vocab, ff) def window_attn(self, x, doc): B, T, D = x.shape w = self.window blk = max(int(self.block or w), w) dh = D // self.heads padn = (-T) % blk if padn: x = F.pad(x, (0, 0, 0, padn)) doc = F.pad(doc, (0, padn), value=-2) Tp = T + padn nb = Tp // blk H = self.heads q = (x @ self.wq).reshape(B, nb, blk, H, dh) k = (x @ self.wk).reshape(B, nb, blk, H, dh) v = (x @ self.wv).reshape(B, nb, blk, H, dh) prev = lambda t: torch.cat([torch.zeros_like(t[:, :1]), t[:, :-1]], 1) k2 = torch.cat([prev(k), k], 2) v2 = torch.cat([prev(v), v], 2) dq = doc.reshape(B, nb, blk) dk = torch.cat([torch.cat([torch.full((B, 1, blk), -1, dtype=doc.dtype, device=doc.device), dq[:, :-1]], 1), dq], 2) cos, sin = rope_tables(2 * blk, dh, x.device) q = apply_rope(q, cos[blk:], sin[blk:]) k2 = apply_rope(k2, cos, sin) sc = torch.einsum("bnqhd,bnkhd->bnhqk", q, k2).float() / math.sqrt(dh) qpos = torch.arange(blk, device=x.device)[:, None] + blk kpos = torch.arange(2 * blk, device=x.device)[None, :] m = ((kpos <= qpos) & (qpos - kpos < w))[None, None, None] & (dk[:, :, None, None, :] == dq[:, :, None, :, None]) att = torch.softmax(sc.masked_fill(~m, -1e30), -1).to(x.dtype) y = torch.einsum("bnhqk,bnkhd->bnqhd", att, v2).reshape(B, Tp, D)[:, :T] return y @ self.wo def forward(self, x, doc, xb): h = rms_norm(x, self.n1) x = x + (self.window_attn(h, doc) if self.kind == "attn" else causal_conv(h, self.conv, doc)) sc = (1.0 + self.de[xb]) if hasattr(self, "de") else None return x + self.ffn(rms_norm(x, self.n2), sc) class Pool(nn.Module): def __init__(self, cfg): super().__init__() dl, d = cfg.d_loc, cfg.d self.ws, self.wv, self.wo, self.up = _P(dl, cfg.pool_heads), _P(dl, dl), _P(dl, dl), _P(dl, d) self.len_emb, self.pool_nf = _P(16, d), _P(d) self.heads = cfg.pool_heads def forward(self, h, starts, lens): """h (1,T,dl); starts/lens (n,) of the closed patches -> (n,d)""" _, T, dl = h.shape n, K, Hp = starts.shape[0], 16, self.heads dh = dl // Hp sc = 5.0 * torch.tanh((h.float() @ self.ws) / 5.0)[0] # (T,Hp) hv = (h @ self.wv)[0] # (T,dl) idx = torch.clamp(starts[:, None] + torch.arange(K, device=h.device)[None, :], max=T - 1) ok = torch.arange(K, device=h.device)[None, :] < lens[:, None] # (n,K) scg = sc[idx] # (n,K,Hp) vg = hv[idx].reshape(n, K, Hp, dh) w = torch.softmax(scg.masked_fill(~ok[..., None], -1e30), dim=1) pooled = torch.einsum("pkh,pkhd->phd", w.to(h.dtype), vg).reshape(n, dl) out = (pooled @ self.wo) @ self.up out = out + self.len_emb[torch.clamp(lens, 1, 16) - 1] return rms_norm(out, self.pool_nf) class Rosa(nn.Module): def __init__(self, cfg): super().__init__() self.pe, self.lg, self.lb, self.boost = _P(257, cfg.d_loc), _P(16, cfg.d_loc), _P(16, cfg.d_loc), _P(16) # ============================================================================= trunk class AttnParams(nn.Module): def __init__(self, cfg): super().__init__() n, d, hd = cfg.n_block, cfg.d, cfg.head_dim H = d // hd self.wq, self.wk, self.wv, self.wo = _P(n, d, d), _P(n, d, d), _P(n, d, d), _P(n, d, d) if cfg.qk_norm: self.qn, self.kn = _P(n, hd), _P(n, hd) if cfg.attn_gate: self.gate_w, self.gate_b = _P(n, d, H), _P(n, H) class RwkvParams(nn.Module): def __init__(self, cfg): super().__init__() n, C, N = cfg.n_block, cfg.d, cfg.head_dim H = C // N for nm in ("x_r", "x_w", "x_k", "x_v", "x_a", "x_g", "w0", "a0", "k_k", "k_a", "v0", "ln_w", "ln_b"): setattr(self, nm, _P(n, C)) self.w1, self.w2 = _P(n, C, cfg.lora_decay), _P(n, cfg.lora_decay, C) self.a1, self.a2 = _P(n, C, cfg.lora_a), _P(n, cfg.lora_a, C) self.g1, self.g2 = _P(n, C, cfg.lora_g), _P(n, cfg.lora_g, C) self.v1, self.v2 = _P(n, C, cfg.lora_v), _P(n, cfg.lora_v, C) self.r_k = _P(n, H, N) self.Wr, self.Wk, self.Wv, self.Wo = _P(n, C, C), _P(n, C, C), _P(n, C, C), _P(n, C, C) class StackedFFN(nn.Module): def __init__(self, cfg): super().__init__() n, d, ff = cfg.n_block, cfg.d, cfg.ffn self.w1, self.w3, self.w2 = _P(n, d, ff), _P(n, d, ff), _P(n, ff, d) class TrunkLayer(nn.Module): """one position of the super-block pattern, parameters stacked over the n_block super-blocks""" def __init__(self, kind, cfg): super().__init__() self.kind = kind self.n1, self.n2 = _P(cfg.n_block, cfg.d), _P(cfg.n_block, cfg.d) self.mix = AttnParams(cfg) if kind == "A" else RwkvParams(cfg) self.ffn = StackedFFN(cfg) def wkv7_chunked(r, lw, k, v, kk, a, L, doc): """chunk-parallel RWKV-7 with document resets (port of the training kernel in plain XLA form). All (B,T,H,N) fp32, doc (B,T) long.""" B, T, H, N = r.shape nC = T // L assert nC * L == T dev = r.device def rs(x): return x.reshape(B, nC, L, H, N).permute(0, 3, 1, 2, 4) r, lw, k, v, kk, a = map(rs, (r, lw, k, v, kk, a)) u, b = kk, kk * a lg = torch.cumsum(lw, dim=3) lgp = lg - lw lgL = lg[:, :, :, -1:, :] Up, Rp, Kp, Bp = u * torch.exp(lgp), r * torch.exp(lg), k * torch.exp(-lg), b * torch.exp(-lg) Khat, Bhat = k * torch.exp(lgL - lg), b * torch.exp(lgL - lg) mm = lambda A, Bm: A @ Bm.transpose(-1, -2) strict = torch.tril(torch.ones(L, L, device=dev), -1) incl = torch.tril(torch.ones(L, L, device=dev)) dch = doc.reshape(B, nC, L) dc = dch[:, None] # (B,1,nC,L) same = (dc[..., :, None] == dc[..., None, :]).float() strict, incl = strict * same, incl * same d_in = torch.cat([torch.full((B, 1), -1, dtype=dch.dtype, device=dev), dch[:, :-1, -1]], 1) d_out = dch[:, :, -1] cm = (dc == d_in[:, None, :, None]).float()[..., None] om = (dc == d_out[:, None, :, None]).float()[..., None] keep = (d_in == d_out).float()[:, None, :, None, None] Kc, Bc, Kr, Br = mm(Up, Kp) * strict, mm(Up, Bp) * strict, mm(Rp, Kp) * incl, mm(Rp, Bp) * incl I = torch.eye(L, device=dev) Minv, Pw = I - Bc, Bc # (I+Bc)^-1 for nilpotent Bc for _ in range(int(math.log2(L)) - 1): Pw = Pw @ Pw Minv = Minv @ (I + Pw) Mu = Minv @ Up Cstat = Minv @ (Kc @ v) Ra = Rp - Br @ Mu Ystat = Kr @ v - Br @ Cstat expL = torch.exp(lgL[:, :, :, 0, :]) Ach = expL[..., :, None] * torch.eye(N, device=dev) - torch.einsum("...ln,...lm->...nm", Mu, Bhat) vs, Cs = v * om, Cstat * om Sst = torch.einsum("...lv,...lk->...vk", vs, Khat) - torch.einsum("...lv,...lk->...vk", Cs, Bhat) Ach = Ach * keep S = torch.zeros(B, H, N, N, device=dev) starts = [] for c in range(nC): starts.append(S) S = S @ Ach[:, :, c] + Sst[:, :, c] Sstart = torch.stack(starts, 2) # (B,H,nC,N,N) Ra = Ra * cm Y = torch.einsum("...lk,...vk->...lv", Ra, Sstart) + Ystat return Y.permute(0, 2, 3, 1, 4).reshape(B, T, H, N), S # S: state after the last token def wkv7_step(S, r, lw, k, v, kk, a): """one-token RWKV-7 recurrence. S (H,N,N) [v,k]; r,lw,k,v,kk,a (H,N). returns (y (H,N), S')""" Skk = torch.einsum("hij,hj->hi", S, kk) S = S * torch.exp(lw)[:, None, :] - Skk[..., None] * (kk * a)[:, None, :] + v[..., None] * k[:, None, :] return torch.einsum("hij,hj->hi", S, r), S def rwkv_tmix(mx, b, x, v_first, first, xprev, wkv, cfg): """x, xprev (B,T,C) (xprev = token-shifted input, already zeroed at document starts); wkv(r,lw,k,v,kk,a) -> y (B,T,H,N) on (B,T,H,N) fp32 inputs""" B, T, C = x.shape N = cfg.head_dim H = C // N g_ = lambda nm: getattr(mx, nm)[b] xx = xprev - x xr, xw, xk, xv, xa, xg = [x + xx * g_(n).to(x.dtype) for n in ("x_r", "x_w", "x_k", "x_v", "x_a", "x_g")] r, k, v = xr @ g_("Wr"), xk @ g_("Wk"), xv @ g_("Wv") wl = g_("w0") + torch.tanh(xw.float() @ g_("w1")) @ g_("w2") lw = -torch.sigmoid(wl) * math.exp(-0.5) if first: v_first = v else: v = v + (v_first - v) * torch.sigmoid(g_("v0") + (xv.float() @ g_("v1")) @ g_("v2")).to(v.dtype) a = torch.sigmoid(g_("a0") + (xa.float() @ g_("a1")) @ g_("a2")) g = torch.sigmoid(xg.float() @ g_("g1")) @ g_("g2") r32, k32, v32 = r.float(), k.float(), v.float() kk = (k32 * g_("k_k")).reshape(B, T, H, N) kk = kk / torch.sqrt((kk * kk).sum(-1, keepdim=True) + 1e-24) k32 = k32 * (1 + (a - 1) * g_("k_a")) hs = lambda t: t.reshape(B, T, H, N) y = wkv(hs(r32), hs(lw), hs(k32), hs(v32), kk, hs(a)) mu = y.mean(-1, keepdim=True) var = ((y - mu) ** 2).mean(-1, keepdim=True) y = ((y - mu) * torch.rsqrt(var + 64e-5)).reshape(B, T, C) * g_("ln_w") + g_("ln_b") y = y + ((hs(r32) * hs(k32) * g_("r_k")).sum(-1, keepdim=True) * hs(v32)).reshape(B, T, C) return (y * g).to(x.dtype) @ g_("Wo"), v_first def trunk_attention(mx, b, x, pdoc, valid, cfg): B, T, D = x.shape hd = cfg.head_dim H = D // hd q = (x @ mx.wq[b]).reshape(B, T, H, hd) k = (x @ mx.wk[b]).reshape(B, T, H, hd) v = (x @ mx.wv[b]).reshape(B, T, H, hd) if cfg.qk_norm: q, k = rms_norm(q, mx.qn[b]), rms_norm(k, mx.kn[b]) q, k, v = (t.transpose(1, 2) for t in (q, k, v)) # (B,H,T,hd) sc = (q @ k.transpose(-1, -2)).float() / math.sqrt(hd) m = (pdoc[:, :, None] == pdoc[:, None, :]) & valid[:, None, :] & torch.tril(torch.ones(T, T, dtype=torch.bool, device=x.device))[None] att = torch.softmax(sc.masked_fill(~m[:, None], -1e30), -1).to(x.dtype) y = (att @ v).transpose(1, 2) # (B,T,H,hd) if cfg.attn_gate: y = y * torch.sigmoid(x.float() @ mx.gate_w[b] + mx.gate_b[b]).to(x.dtype)[..., None] return y.reshape(B, T, D) @ mx.wo[b], k, v def trunk_attention_step(mx, b, x, kc, vc, same, cfg): """one new patch attends to the cached keys/values (kc, vc: (H,n,hd), already containing the new patch). x (1,1,D); same (n,) bool = key belongs to the same document""" D = x.shape[-1] hd = cfg.head_dim H = D // hd q = (x @ mx.wq[b]).reshape(1, 1, H, hd) if cfg.qk_norm: q = rms_norm(q, mx.qn[b]) q = q[0, 0] # (H,hd) sc = torch.einsum("hd,hnd->hn", q, kc).float() / math.sqrt(hd) att = torch.softmax(sc.masked_fill(~same[None], -1e30), -1).to(x.dtype) y = torch.einsum("hn,hnd->hd", att, vc) # (H,hd) if cfg.attn_gate: y = y * torch.sigmoid(x[0, 0].float() @ mx.gate_w[b] + mx.gate_b[b]).to(x.dtype)[:, None] return (y.reshape(1, 1, D) @ mx.wo[b]) # ============================================================================= hashed n-gram embedding (host-side, uint32 wrap-around like the training code) def _mix32(h): h = h ^ (h >> np.uint32(16)) h = h * np.uint32(0x7feb352d) h = h ^ (h >> np.uint32(15)) h = h * np.uint32(0x846ca68b) return h ^ (h >> np.uint32(16)) def hash_rows_np(x, doc, cfg): """x, doc (T,) int arrays -> rows (T,O) int64 into the concatenated hash table and valid (T,O) bool""" T = len(x) u = x.astype(np.uint32) + np.uint32(1) M = np.uint32(0x9E3779B1) h = u.copy() hs = {1: h} with np.errstate(over="ignore"): for n in range(2, max(cfg.hash_orders) + 1): h = np.concatenate([np.zeros(1, np.uint32), h[:-1]]) * M + u hs[n] = h rows, valids, off = [], [], 0 pos = np.arange(T) for n, nr in zip(cfg.hash_orders, cfg.hash_rows): g = _mix32(hs[n] ^ np.uint32((n * 0x85EBCA6B) & 0xFFFFFFFF)) rows.append((g % np.uint32(nr)).astype(np.int64) + off) off += nr dshift = np.concatenate([np.full(min(n - 1, T), -3, doc.dtype), doc[:max(T - (n - 1), 0)]]) if n > 1 else doc valids.append((pos >= n - 1) & (dshift == doc)) return np.stack(rows, -1), np.stack(valids, -1) # ============================================================================= ROSA (online suffix automaton on bytes, host-side) _EDGES = (1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 128, 256) def _bucket(m): if m <= 0: return 0 for i, e in enumerate(_EDGES): if m <= e: return i + 1 return 15 def rosa_features(x): """x: sequence of byte ids. returns (pred1, bucket) int arrays: pred1 = predicted next byte + 1 (0 = none), bucket = match-length bucket (0 = none). The automaton is reset after every EOD byte; the features at position j only depend on x[0..j].""" n = len(x) pred1 = np.zeros(n, np.int64) bkt = np.zeros(n, np.int64) nxt, link, ln, pos = [{}], [-1], [0], [-1] last = 0 for i in range(n): c = int(x[i]) if c == 0 or c > 255: nxt, link, ln, pos = [{}], [-1], [0], [-1] last = 0 continue cur = len(nxt) nxt.append({}) link.append(0) ln.append(ln[last] + 1) pos.append(i) p = last while p != -1 and c not in nxt[p]: nxt[p][c] = cur p = link[p] if p == -1: link[cur] = 0 else: q = nxt[p][c] if ln[p] + 1 == ln[q]: link[cur] = q else: cl = len(nxt) nxt.append(dict(nxt[q])) link.append(link[q]) ln.append(ln[p] + 1) pos.append(pos[q]) while p != -1 and nxt[p].get(c) == q: nxt[p][c] = cl p = link[p] link[q] = cl link[cur] = cl last = cur m = link[cur] if m > 0 and pos[m] + 1 <= i: pred1[i] = int(x[pos[m] + 1]) + 1 bkt[i] = _bucket(min(ln[m], 8192)) pos[m] = i return pred1, bkt # ============================================================================= model class NoTokenGen55PreTrainedModel(PreTrainedModel): config_class = NoTokenGen55Config base_model_prefix = "" supports_gradient_checkpointing = False _tied_weights_keys = [] _no_split_modules = [] def _init_weights(self, module): # weights always come from the checkpoint pass class NoTokenGen55ForCausalLM(NoTokenGen55PreTrainedModel): def __init__(self, config: NoTokenGen55Config): super().__init__(config) cfg = config dl, d = cfg.d_loc, cfg.d self.emb_in = _P(cfg.vocab, dl) self.enc = nn.ModuleList([LocalBlock(k, cfg) for k in cfg.enc_blocks]) self.enc_nf = _P(dl) self.pool = Pool(cfg) self.trunk = nn.ModuleDict({f"l{j}": TrunkLayer(k, cfg) for j, k in enumerate(cfg.pattern)}) self.nf = _P(d) self.down, self.down_nf, self.bos = _P(d, dl), _P(dl), _P(dl) self.dec = nn.ModuleList([LocalBlock("attn", cfg) for _ in range(cfg.n_dec)]) self.dec_nf = _P(dl) self.head = _P(dl, 256) if cfg.rosa: self.rosa = Rosa(cfg) if cfg.n_hash: self.hash_table = _P(int(sum(cfg.hash_rows)), cfg.hash_dim) self.hash_nw = _P(cfg.n_hash * cfg.hash_dim) self.hash_proj = _P(cfg.n_hash * cfg.hash_dim, dl) self.patcher = Patcher(cfg) self.post_init() # ------------------------------------------------------------------------- pieces def _embed(self, x_np, x, doc): cfg = self.config h = self.emb_in[x] if cfg.rosa: p1, bk = rosa_features(x_np) p1, bk = torch.as_tensor(p1, device=x.device), torch.as_tensor(bk, device=x.device) R = self.rosa h = h + R.pe[p1] * R.lg[bk] + R.lb[bk] else: p1 = bk = None if cfg.n_hash: rows, valid = hash_rows_np(x_np, doc.cpu().numpy(), cfg) rows, valid = torch.as_tensor(rows, device=x.device), torch.as_tensor(valid, device=x.device) e = self.hash_table[rows] * valid[..., None].to(h.dtype) # (T,O,hd) e = rms_norm(e.reshape(len(x_np), cfg.n_hash * cfg.hash_dim), self.hash_nw) h = h + e @ self.hash_proj return h[None], p1, bk def _layout(self, x, ent_logits, theta): """patch boundaries of the T bytes + whether the NEXT byte would start a patch. Everything is causal: the patcher output at position j (which only saw bytes <= j) decides whether byte j+1 starts a patch, so the open/closed state of the last patch is known at generation time.""" T = x.shape[0] L = self.config.patch_max_len lp = torch.log_softmax(ent_logits[0].float(), -1) H = -(lp.exp() * lp).sum(-1) # (T,) ent_ext = torch.cat([torch.full((1,), float("inf"), device=x.device), H]) # ent_ext[j] = entropy of the belief about byte j prev_eod = torch.cat([torch.ones(1, dtype=torch.bool, device=x.device), x == EOD]) force = prev_eod | (ent_ext > theta) idx = torch.arange(T + 1, device=x.device) fpos = torch.cummax(torch.where(force, idx, torch.full_like(idx, -1)), 0).values s_ext = force | (((idx - fpos) % L) == 0) s, s_next = s_ext[:T], s_ext[1:] starts_all = torch.nonzero(s).squeeze(1) n_closed = int(starts_all.numel()) - 1 + int(s_ext[T]) ends = torch.cat([starts_all[1:], torch.full((1,), T, device=x.device, dtype=starts_all.dtype)])[:n_closed] starts = starts_all[:n_closed] pid = torch.cumsum(s.long(), 0) - 1 didx = pid + s_next.long() # number of closed patches after byte j return dict(starts=starts, lens=ends - starts, n_closed=n_closed, didx=didx) def _lscale(self, b, j): cfg = self.config return 1.0 / math.sqrt(b * len(cfg.pattern) + j + 1) if cfg.ln_scale else 1.0 def _trunk(self, pv, pdoc, capture=None): """pv (n,d) pooled vectors of the closed patches -> (n,d) latents. Padding goes to the FRONT (with its own document id), so the recurrent state after the last chunk is exactly the state after the last real patch; `capture` (a dict) receives that state + the attention keys/values.""" cfg = self.config n, d = pv.shape Ch = cfg.chunk pad = (-n) % Ch dev = pv.device xx = F.pad(pv, (0, 0, pad, 0))[None] pd = torch.cat([torch.full((pad,), -5, dtype=pdoc.dtype, device=dev), pdoc])[None] valid = torch.cat([torch.zeros(pad, dtype=torch.bool, device=dev), torch.ones(n, dtype=torch.bool, device=dev)])[None] doc_start = torch.cat([torch.ones(1, 1, dtype=torch.bool, device=dev), pd[:, 1:] != pd[:, :-1]], 1) vf = torch.zeros_like(xx) pat = cfg.pattern if capture is not None: capture.update(S={}, xp={}, K={}, V={}) for b in range(cfg.n_block): for j, kind in enumerate(pat): Lr = self.trunk[f"l{j}"] s = self._lscale(b, j) h = rms_norm(xx, Lr.n1[b]) * s if kind == "A": y, k, v = trunk_attention(Lr.mix, b, h, pd, valid, cfg) if capture is not None: capture["K"][(b, j)], capture["V"][(b, j)] = k[0, :, pad:], v[0, :, pad:] # (H,n,hd) else: xprev = torch.where(doc_start[..., None], torch.zeros_like(h), F.pad(h, (0, 0, 1, 0))[:, :-1]) fin = {} def wkv(r, lw, k, v, kk, a, fin=fin): y, S = wkv7_chunked(r, lw, k, v, kk, a, cfg.chunk, pd) fin["S"] = S return y y, vf = rwkv_tmix(Lr.mix, b, h, vf, (b == 0 and j == 0), xprev, wkv, cfg) if capture is not None: capture["S"][(b, j)], capture["xp"][(b, j)] = fin["S"][0], h[0, -1] xx = xx + y h2 = rms_norm(xx, Lr.n2[b]) * s f = Lr.ffn xx = xx + (F.silu(h2 @ f.w1[b]) * (h2 @ f.w3[b])) @ f.w2[b] if capture is not None: capture["last_doc"] = int(pdoc[-1]) capture["pdoc"] = pdoc.clone() return rms_norm(xx, self.nf)[0, pad:] def _trunk_step(self, pv, doc_id, st): """ONE new patch (pv (d,), document id) through the trunk, updating the state `st` in place. returns its latent (d,)""" cfg = self.config N = cfg.head_dim new_doc = (doc_id != st["last_doc"]) st["pdoc"] = torch.cat([st["pdoc"], torch.full((1,), doc_id, dtype=st["pdoc"].dtype, device=pv.device)]) same = st["pdoc"] == doc_id xx = pv[None, None] vf = torch.zeros_like(xx) pat = cfg.pattern for b in range(cfg.n_block): for j, kind in enumerate(pat): Lr = self.trunk[f"l{j}"] s = self._lscale(b, j) h = rms_norm(xx, Lr.n1[b]) * s if kind == "A": mx = Lr.mix k = (h @ mx.wk[b]).reshape(1, 1, -1, cfg.head_dim) v = (h @ mx.wv[b]).reshape(1, 1, -1, cfg.head_dim) if cfg.qk_norm: k = rms_norm(k, mx.kn[b]) st["K"][(b, j)] = torch.cat([st["K"][(b, j)], k[0].transpose(0, 1)], 1) # (H,n+1,hd) st["V"][(b, j)] = torch.cat([st["V"][(b, j)], v[0].transpose(0, 1)], 1) y = trunk_attention_step(mx, b, h, st["K"][(b, j)], st["V"][(b, j)], same, cfg) else: xprev = torch.zeros_like(h) if new_doc else st["xp"][(b, j)][None, None] if new_doc: st["S"][(b, j)] = torch.zeros_like(st["S"][(b, j)]) st["xp"][(b, j)] = h[0, 0] box = {} def wkv(r, lw, k, v, kk, a, box=box, key=(b, j)): y, S = wkv7_step(st["S"][key], r[0, 0], lw[0, 0], k[0, 0], v[0, 0], kk[0, 0], a[0, 0]) st["S"][key] = S return y[None, None] y, vf = rwkv_tmix(Lr.mix, b, h, vf, (b == 0 and j == 0), xprev, wkv, cfg) xx = xx + y h2 = rms_norm(xx, Lr.n2[b]) * s f = Lr.ffn xx = xx + (F.silu(h2 @ f.w1[b]) * (h2 @ f.w3[b])) @ f.w2[b] st["last_doc"] = doc_id return rms_norm(xx, self.nf)[0, 0] # ------------------------------------------------------------------------- forward over one byte sequence def _forward_one(self, x_np, cache=None, last_only=False): cfg = self.config dev = self.head.device T = len(x_np) assert T >= 1 x = torch.as_tensor(np.asarray(x_np), dtype=torch.long, device=dev) doc = doc_ids(x[None]) theta = float(cfg.theta) ent_logits = self.patcher(x[None], doc) lay = self._layout(x, ent_logits, theta) h, p1, bk = self._embed(np.asarray(x_np), x, doc[0]) for L in self.enc: h = L(h, doc, x[None]) h = rms_norm(h, self.enc_nf) n = lay["n_closed"] pdoc_all = doc[0][lay["starts"]] if n > 0 else torch.zeros(0, dtype=torch.long, device=dev) if n == 0: gl = torch.zeros(0, cfg.d_loc, device=dev) if cache is not None: cache.clear() elif cache is not None and cache.get("st") is not None and cache["n"] <= n: # incremental: only the newly closed patches go through the trunk (the state of the earlier ones is cached) n0 = cache["n"] gl_parts = [cache["gl"]] if n > n0: pv = self.pool(h, lay["starts"][n0:], lay["lens"][n0:]) for i in range(n - n0): g = self._trunk_step(pv[i], int(pdoc_all[n0 + i]), cache["st"]) gl_parts.append(rms_norm(g @ self.down, self.down_nf)[None]) gl = torch.cat(gl_parts, 0) cache["n"], cache["gl"] = n, gl else: pv = self.pool(h, lay["starts"], lay["lens"]) st = {} if cache is not None else None g = self._trunk(pv, pdoc_all, capture=st) gl = rms_norm(g @ self.down, self.down_nf) if cache is not None: cache["st"], cache["n"], cache["gl"] = st, n, gl gext = torch.cat([self.bos[None], gl], 0) pdoc_ext = torch.cat([torch.full((1,), -1, device=dev, dtype=torch.long), doc[0][lay["starts"]]]) if n > 0 else torch.full((1,), -1, device=dev, dtype=torch.long) didx = lay["didx"] didx = torch.where(pdoc_ext[didx] == doc[0], didx, torch.zeros_like(didx)) # first bytes of a document see BOS u = h[0] + gext[didx] sl = slice(max(0, T - 192), T) if last_only else slice(0, T) # decoder receptive field is 4 x 31 bytes u, dsl, xs = u[sl][None], doc[:, sl], x[sl][None] for L in self.dec: u = L(u, dsl, xs) logits = rms_norm(u, self.dec_nf) @ (self.head - self.head.mean(1, keepdim=True)) logits = logits[0].float() if cfg.rosa: pp, bb = p1[sl], bk[sl] oh = (pp[:, None] - 1) == torch.arange(256, device=dev)[None, :] logits = logits + oh.float() * self.rosa.boost[bb][:, None] return logits[-1:] if last_only else logits # ------------------------------------------------------------------------- HF API def forward(self, input_ids=None, labels=None, **kwargs): """input_ids (B,T) byte ids (0..255; 0 = end of document). returns logits (B,T,256): logits[:,j] predict byte j+1.""" ids = input_ids.detach().cpu().numpy() logits = torch.stack([self._forward_one(row) for row in ids]) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].reshape(-1, 256), labels[:, 1:].reshape(-1).to(logits.device)) return CausalLMOutput(loss=loss, logits=logits) @torch.no_grad() def generate(self, input_ids=None, prompt: Optional[str] = None, max_new_tokens: int = 300, temperature: float = 0.8, top_p: float = 1.0, top_k: Optional[int] = 0, do_sample: bool = True, seed: Optional[int] = None, stop_at_eod: bool = True, streamer=None, **kwargs): """byte-by-byte generation. Give `input_ids` (LongTensor (1,T) / list of byte ids) or `prompt` (str). Returns a LongTensor (1, T + new) of byte ids (byte 0 = end-of-document; generation stops when it is emitted unless stop_at_eod=False). do_sample=False or temperature<=0 -> greedy. Sampling uses temperature, top_k (0/None = off) and top_p. seed makes it reproducible. `max_new_bytes` is accepted as an alias of `max_new_tokens`. The trunk state of closed patches is cached, so each new byte is cheap.""" max_new_tokens = int(kwargs.pop("max_new_bytes", max_new_tokens)) if prompt is not None: ids = list(prompt.encode("utf-8")) else: ids = [int(t) for t in (input_ids.flatten().tolist() if torch.is_tensor(input_ids) else input_ids)] if not ids: ids = [32] # never feed an empty sequence if self.config.theta is None: raise ValueError("config.theta is missing (the calibrated patch threshold). Run convert_checkpoint.py or use the official config.json.") limit = self.config.seq_len if len(ids) + max_new_tokens > limit: # stay inside the trained 4096-byte window ids = ids[-max(1, limit - max_new_tokens):] max_new_tokens = min(max_new_tokens, limit - len(ids)) gen = torch.Generator(device="cpu") if seed is not None: gen.manual_seed(int(seed)) else: gen.seed() # non-deterministic: every call gives a different sample greedy = (not do_sample) or temperature is None or temperature <= 0 cache = {} for _ in range(max_new_tokens): lg = self._forward_one(ids, cache=cache, last_only=True)[0].float().cpu() if greedy: nxt = int(lg.argmax()) else: lg = lg / temperature if top_k and top_k > 0: kth = torch.topk(lg, min(int(top_k), 256)).values[-1] lg = lg.masked_fill(lg < kth, float("-inf")) pr = torch.softmax(lg, -1) if top_p is not None and top_p < 1.0: sp, si = torch.sort(pr, descending=True) sp = sp.masked_fill(torch.cumsum(sp, 0) - sp > top_p, 0.0) pr = torch.zeros_like(pr).scatter(0, si, sp) pr = pr / pr.sum() nxt = int(torch.multinomial(pr, 1, generator=gen)) ids.append(nxt) if streamer is not None: streamer(nxt) if stop_at_eod and nxt == EOD: break return torch.tensor([ids], dtype=torch.long) def generate_text(self, prompt: str, return_prompt: bool = True, **kw) -> str: """convenience: str in, str out (the end-of-document byte is dropped; invalid UTF-8 from a cut multi-byte character becomes U+FFFD)""" out = self.generate(prompt=prompt, **kw)[0].tolist() n0 = len(prompt.encode("utf-8")) return bytes(i for i in out[(0 if return_prompt else n0):] if i != EOD).decode("utf-8", errors="replace")