Veri-Base / modeling_veri.py
veriepic's picture
Super-squash branch 'main' using huggingface_hub
6d02034
Raw History Blame Contribute Delete
23.3 kB
import math
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint
# veri transformer, from scratch, no hf imports anywhere
# every function hand written, readable in one sitting
# flags let us bench variants, winner becomes the 1b config
class VeriConfig:
def __init__(
self,
vocab=65536,
layers=24,
dim=2048,
q_heads=16,
kv_heads=4,
mlp_ratio=2.67,
seq=4096,
rope_theta=10000.0,
qk_norm=False,
sliding=None,
dropout=0.0,
diff=False,
norm="rms",
rope=True,
):
# vocab is timmy size, 65536 rows in the embedding table
# layers dim heads set the size, q_heads kv_heads set gqa ratio
# mlp_ratio times dim is swiglu hidden size
# rope_theta sets long range bias, bigger sees further
# qk_norm normalizes q and k per head, qwen3 style stability
# sliding is local window size, none means full attention every layer
# diff splits heads in half, two softmaxes, subtract. noise cancels, signal stays
self.vocab = vocab
self.layers = layers
self.dim = dim
self.q_heads = q_heads
self.kv_heads = kv_heads
self.mlp_hidden = int(dim * mlp_ratio)
self.seq = seq
self.rope_theta = rope_theta
self.qk_norm = qk_norm
self.sliding = sliding
self.dropout = dropout
self.diff = diff
self.norm = norm
self.rope = rope
# old champ: llama bones plus qk norm plus interleaved sliding. retired at step 770
# 10k sounded cool but avg doc is 1 to 2k, no long sft to extend on, so 4k is the honest
# pretrain length, extend later with yarn when we have long data, saves 60 percent attention
VERI_1B = VeriConfig(seq=4096, qk_norm=True, sliding=2048)
# current champ line: same bones plus diff heads. remy-post tied 2nd in the fixed 35-arch zoo at 118M (2.28 vs 2.27 qk-post, 2.38 gemma)
# retraining from 0 on this, 10B target. remy the rat, tiny cook gourmet outputs
VERI_REMY = VeriConfig(seq=4096, qk_norm=True, sliding=2048, diff=True)
# 2048 * 2.67 = 5468.16 -> int 5468, and 5468 % 16 = 4 breaks fp8/cutlass.
# 5504 = 16 * 344, ratio 2.6875, +0.2m params, nothing. bf16 never noticed.
VERI_REMY.mlp_hidden = 5504
# bench scale presets, all roughly same param count, only flags differ
BENCH_BASE = VeriConfig(vocab=50257, layers=6, dim=192, q_heads=6, kv_heads=2, seq=96)
BENCH_QKNORM = VeriConfig(vocab=50257, layers=6, dim=192, q_heads=6, kv_heads=2, seq=96, qk_norm=True)
BENCH_SLIDING = VeriConfig(vocab=50257, layers=6, dim=192, q_heads=6, kv_heads=2, seq=96, sliding=48)
BENCH_THETA = VeriConfig(vocab=50257, layers=6, dim=192, q_heads=6, kv_heads=2, seq=96, rope_theta=500000.0)
BENCH_DEEP = VeriConfig(vocab=50257, layers=9, dim=160, q_heads=5, kv_heads=5, seq=96)
BENCH_COMBO = VeriConfig(vocab=50257, layers=6, dim=192, q_heads=6, kv_heads=2, seq=96, qk_norm=True, sliding=48)
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6, kind="rms"):
super().__init__()
self.eps = eps
self.kind = kind
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
# root mean square norm, no mean shift, cheaper than layernorm
# single float cast hoisted (was x.float() twice = 2 full copies)
# VERI_NORM=ln: cudnn fused layernorm, 1 vram pass, zero copies.
# math differs (mean-centering) — grind mode only, quality runs keep rms.
if self.kind == "ln" or os.environ.get("VERI_NORM", "rms") == "ln":
return F.layer_norm(x, (x.size(-1),), self.weight, None, self.eps)
xf = x.float()
out = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps)
return (out * self.weight.float()).to(x.dtype)
# static fp8 linears (VERI_FP8=1). fwd + dx + dw all _scaled_mm, x/W scales
# frozen after first-batch calibration, go scaled dynamically (1 amax pass).
# no torchao, no amax machinery, no image change. xq saved fp8 (half mem).
# default OFF, bf16 path untouched.
class FP8StaticLinear(torch.autograd.Function):
@staticmethod
def forward(ctx, x, w, b):
out_f = w.shape[0]
xs = x.shape
xf = x.reshape(-1, xs[-1])
if not hasattr(w, "_fp8_s"):
ax = xf.detach().abs().max().clamp_min(1e-12).float()
aw = w.detach().float().abs().max().clamp_min(1e-12)
w._fp8_s = (ax / 448.0, aw / 448.0)
sx, sw = w._fp8_s
xq = (xf / sx.to(xf.dtype)).to(torch.float8_e4m3fn)
wq = (w.t() / sw.to(w.dtype)).to(torch.float8_e4m3fn).contiguous()
y = torch._scaled_mm(xq, wq, out_dtype=x.dtype, scale_a=sx, scale_b=sw)
ctx.save_for_backward(xq, wq, sx, sw)
ctx.xs = xs
ctx.w_dtype = w.dtype
ctx.has_b = b is not None
y = y.view(*xs[:-1], out_f)
return y + b if b is not None else y
@staticmethod
def backward(ctx, go):
xq, wq, sx, sw = ctx.saved_tensors
gf = go.reshape(-1, go.shape[-1])
sgo = gf.detach().abs().max().clamp_min(1e-12).float() / 448.0
goq = (gf / sgo.to(gf.dtype)).to(torch.float8_e4m3fn)
dx = torch._scaled_mm(goq, wq.t().contiguous(), out_dtype=go.dtype,
scale_a=sgo, scale_b=sw)
gt = goq.transpose(0, 1).contiguous()
dw = torch._scaled_mm(gt, xq, out_dtype=torch.float32,
scale_a=sgo, scale_b=sx)
db = gf.sum(0).to(ctx.w_dtype) if ctx.has_b else None
return dx.view(*ctx.xs), dw.to(ctx.w_dtype), db
def may_fp8(lin, x):
if os.environ.get("VERI_FP8", "0") == "1":
return FP8StaticLinear.apply(x, lin.weight, lin.bias)
return lin(x)
# tables keyed on inputs+device. same shape every step, built ONCE.
# forward casts to model dtype after (tiny tables, one cheap copy).
_ROPE_CACHE = {}
_MASK_CACHE = {}
def build_rope(seq, head_dim, theta=10000.0, device="cpu"):
# rotary angles, outer positions times inner frequencies
key = (seq, head_dim, float(theta), str(device))
hit = _ROPE_CACHE.get(key)
if hit is not None:
return hit
pos = torch.arange(seq, dtype=torch.float, device=device)
freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float, device=device) / head_dim))
ang = torch.outer(pos, freq)
out = (torch.cos(ang), torch.sin(ang))
_ROPE_CACHE[key] = out
return out
def apply_rope(x, cos, sin):
# rotate pairs, first half with second half
# x is batch heads seq head_dim
x1, x2 = x.chunk(2, dim=-1)
c = cos[: x.size(2)].unsqueeze(0).unsqueeze(0)
s = sin[: x.size(2)].unsqueeze(0).unsqueeze(0)
return torch.cat([x1 * c - x2 * s, x1 * s + x2 * c], dim=-1)
def repeat_kv(x, n):
# grouped query attention, fewer kv heads than q heads
if n == 1:
return x
b, h, t, d = x.shape
x = x.unsqueeze(3).expand(b, h, t, n, d)
# permute before merge, plain reshape scrambles positions into replicas
return x.permute(0, 1, 3, 2, 4).reshape(b, h * n, t, d)
def causal_window_mask(t, window=None, device="cpu"):
# additive mask, future and beyond window go to negative inf
# cached: same (t, window) every step, aranges+where built once
key = (t, window, str(device))
hit = _MASK_CACHE.get(key)
if hit is not None:
return hit
row = torch.arange(t, device=device).unsqueeze(1)
col = torch.arange(t, device=device).unsqueeze(0)
ok = col <= row
if window is not None:
ok = ok & ((row - col) < window)
out = torch.where(ok, 0.0, float("-inf"))
_MASK_CACHE[key] = out
return out
class Attention(nn.Module):
def __init__(self, cfg):
super().__init__()
self.q_heads = cfg.q_heads
self.kv_heads = cfg.kv_heads
self.head_dim = cfg.dim // cfg.q_heads
self.rep = cfg.q_heads // cfg.kv_heads
assert cfg.dim % cfg.q_heads == 0
assert cfg.q_heads % cfg.kv_heads == 0
self.q = nn.Linear(cfg.dim, cfg.dim, bias=False)
self.k = nn.Linear(cfg.dim, cfg.kv_heads * self.head_dim, bias=False)
self.v = nn.Linear(cfg.dim, cfg.kv_heads * self.head_dim, bias=False)
self.o = nn.Linear(cfg.dim, cfg.dim, bias=False)
self.q_norm = RMSNorm(self.head_dim, kind=getattr(cfg, "norm", "rms")) if cfg.qk_norm else None
self.k_norm = RMSNorm(self.head_dim, kind=getattr(cfg, "norm", "rms")) if cfg.qk_norm else None
if cfg.diff:
assert cfg.q_heads % 2 == 0
self.lam = nn.Parameter(torch.zeros(cfg.q_heads // 2) + 0.5) if cfg.diff else None
self.do_rope = getattr(cfg, "rope", True)
self.drop = nn.Dropout(cfg.dropout)
def forward(self, x, cos, sin, window=None):
b, t, _ = x.shape
h, hd = self.q_heads, self.head_dim
q = may_fp8(self.q, x).view(b, t, h, hd).transpose(1, 2)
k = may_fp8(self.k, x).view(b, t, self.kv_heads, hd).transpose(1, 2)
v = may_fp8(self.v, x).view(b, t, self.kv_heads, hd).transpose(1, 2)
if self.q_norm is not None and os.environ.get("VERI_NOQK", "0") != "1":
q = self.q_norm(q)
k = self.k_norm(k)
# VERI_NOROPE=1: skip rotary (grind mode, synthetic data has no
# positions worth encoding). kills 10+ launches per pass.
# cfg.rope=False: same, constructor-level (zoo can test it clean).
if self.do_rope and os.environ.get("VERI_NOROPE", "0") != "1":
q = apply_rope(q, cos, sin)
k = apply_rope(k, cos, sin)
k = repeat_kv(k, self.rep)
v = repeat_kv(v, self.rep)
# mask must match query dtype or sdpa refuses, fp32 runs never notice
mask = causal_window_mask(t, window, x.device).to(x.dtype)
if self.lam is not None and os.environ.get("VERI_NODIFF", "0") != "1":
# pair i = y1[i] minus lam[i] times y2[i], then concat pairs
h2 = h // 2
y1 = F.scaled_dot_product_attention(q[:, :h2], k[:, :h2], v[:, :h2], attn_mask=mask)
y2 = F.scaled_dot_product_attention(q[:, h2:], k[:, h2:], v[:, h2:], attn_mask=mask)
lam = self.lam.sigmoid().view(1, h2, 1, 1)
y = torch.cat([y1 - lam * y2, y2], dim=1)
else:
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
y = y.transpose(1, 2).contiguous().view(b, t, h * hd)
return self.drop(may_fp8(self.o, y))
class SwiGLU(nn.Module):
def __init__(self, cfg):
super().__init__()
self.gate = nn.Linear(cfg.dim, cfg.mlp_hidden, bias=False)
self.up = nn.Linear(cfg.dim, cfg.mlp_hidden, bias=False)
self.down = nn.Linear(cfg.mlp_hidden, cfg.dim, bias=False)
self.drop = nn.Dropout(cfg.dropout)
def forward(self, x):
return self.drop(may_fp8(self.down, F.silu(may_fp8(self.gate, x)) * may_fp8(self.up, x)))
class Block(nn.Module):
def __init__(self, cfg, sliding=None):
super().__init__()
self.n1 = RMSNorm(cfg.dim, kind=getattr(cfg, "norm", "rms"))
self.n2 = RMSNorm(cfg.dim, kind=getattr(cfg, "norm", "rms"))
self.attn = Attention(cfg)
self.mlp = SwiGLU(cfg)
self.sliding = sliding
def forward(self, x, cos, sin):
x = x + self.attn(self.n1(x), cos, sin, self.sliding)
x = x + self.mlp(self.n2(x))
return x
class VeriTransformer(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
self.tok_emb = nn.Embedding(cfg.vocab, cfg.dim)
self.pos_drop = nn.Dropout(cfg.dropout)
# sliding on even layers only, odd layers see everything
# local plus global mix, gemma style, cheap long range
self.blocks = nn.ModuleList(
[Block(cfg, sliding=cfg.sliding if i % 2 == 0 else None) for i in range(cfg.layers)]
)
self.norm = RMSNorm(cfg.dim)
self.apply(self._init)
def _init(self, m):
if isinstance(m, nn.Linear):
nn.init.normal_(m.weight, std=0.02 / math.sqrt(2 * self.cfg.layers))
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Embedding):
nn.init.normal_(m.weight, std=0.02)
def forward(self, idx, targets=None, hidden=False):
b, t = idx.shape
cos, sin = build_rope(t, self.cfg.dim // self.cfg.q_heads, self.cfg.rope_theta, idx.device)
x = self.pos_drop(self.tok_emb(idx))
# rope tables build fp32, cast to model dtype or qk promote to fp32
# while v stays bf16 and sdpa explodes on the mismatch
cos, sin = cos.to(x.dtype), sin.to(x.dtype)
ckpt = os.environ.get("VERI_CKPT", "0") == "1"
for blk in self.blocks:
# per-block ckpt (NOT whole-model: that rebuilds everything).
# dropout is 0.0 default so recompute masks match trivially.
x = checkpoint(blk, x, cos, sin, use_reentrant=False) if ckpt else blk(x, cos, sin)
h = self.norm(x)
if hidden:
# skip the giant logit matmul, fused ce eats hidden directly
return h, None
# output head tied to embeddings, saves vocab times dim params
logits = F.linear(h, self.tok_emb.weight)
loss = None
if targets is not None:
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1))
return logits, loss
def forward_loss_chunked(self, idx, targets, mb=8, tc=2048):
# same math as forward loss, logits never fully materialize
# full logits at micro 32 seq 10k vocab 64k is 43gb transient, tiled is 2gb
# backward flows through tiles into shared hidden states, exact weighted mean
b, t = idx.shape
cos, sin = build_rope(t, self.cfg.dim // self.cfg.q_heads, self.cfg.rope_theta, idx.device)
x = self.pos_drop(self.tok_emb(idx))
cos, sin = cos.to(x.dtype), sin.to(x.dtype)
for blk in self.blocks:
x = blk(x, cos, sin)
h = self.norm(x)
W = self.tok_emb.weight
# manual tile backprop: NO autograd through the loop, NO checkpoint.
# ckptCE died because recompute rebuilds ALL tile graphs (400gb)
# before differentiating any. here autograd.grad stops AT (hs, W)
# per tile (never traverses into blocks), grads accumulate manually
# into h.grad/W.grad, tile graph frees before next tile. caller drives
# blocks via torch.autograd.backward(h, h.grad). peak = 1 tile (25gb).
# no CE recompute (faster too). leaf .grad was always bf16, same kind.
# count = b*t exact (gen drops ragged tails, full micros only).
scale = 1.0 / max(1, b * t)
total = 0.0
if W.grad is None:
W.grad = torch.zeros_like(W)
for i in range(0, b, mb):
for j in range(0, t, tc):
hs = h[i : i + mb, j : j + tc].reshape(-1, h.size(-1))
tg = targets[i : i + mb, j : j + tc].reshape(-1)
# detach+leaf: the ONLY traversal barrier. views are
# transparent (engine walks past hs into blocks, frees the
# shared graph, tile 2 dies). leaf stops it cold.
hs_leaf = hs.detach().requires_grad_(True)
logits = F.linear(hs_leaf, W).float()
lt = F.cross_entropy(logits, tg, reduction="sum")
dh_leaf, dw = torch.autograd.grad(lt * scale, (hs_leaf, W))
if h.grad is None:
h.grad = torch.zeros_like(h)
sl = h.grad[i : i + mb, j : j + tc]
sl += dh_leaf.view(sl.shape)
W.grad += dw
total += lt.item()
return total / max(1, b * t), h
def count(self):
return sum(p.numel() for p in self.parameters())
@torch.no_grad()
def generate(self, idx, max_new, temp=1.0, top_k=0):
# sampler fixed, early training logits are flat, top_k on flat
# can collapse to pad (id 0) due to tie handling, so we only
# apply top_k when the distribution actually has a peak
self.eval()
for _ in range(max_new):
use = idx[:, -self.cfg.seq :]
logits, _ = self(use)
last = logits[:, -1, :] / max(temp, 1e-6)
if top_k > 0:
# keep top_k, but if max equals median (flat), skip it
# flat distribution + top_k + multinomial is still flat,
# filtering just risks collapsing to a single tie-broken id
if last.max() > last.median() + 1e-4:
v, _ = torch.topk(last, min(top_k, last.size(-1)))
last[last < v[:, [-1]]] = float("-inf")
probs = F.softmax(last, dim=-1)
nxt = torch.multinomial(probs, 1) if temp > 0 else probs.argmax(-1, keepdim=True)
idx = torch.cat([idx, nxt], dim=1)
self.train()
return idx
if __name__ == "__main__":
for name, cfg in [
("base", BENCH_BASE),
("qknorm", BENCH_QKNORM),
("sliding", BENCH_SLIDING),
("theta", BENCH_THETA),
("deep", BENCH_DEEP),
("combo", BENCH_COMBO),
("1b", VERI_1B),
("remy", VERI_REMY),
]:
m = VeriTransformer(cfg)
print(f"{name:8s} {m.count() / 1e6:8.2f}M params")
# huggingface wrapper, optional. core file above is the exact training code.
# makes AutoModelForCausalLM.from_pretrained(path, trust_remote_code=True) work.
try:
from transformers import PreTrainedModel, PretrainedConfig
from transformers.modeling_outputs import CausalLMOutputWithPast
try:
from transformers.generation import GenerationMixin
except ImportError:
GenerationMixin = object
class VeriHFConfig(PretrainedConfig):
model_type = "veri"
def __init__(self, vocab_size=65536, hidden_size=2048, intermediate_size=5504,
num_hidden_layers=24, num_attention_heads=16, num_key_value_heads=4,
max_position_embeddings=4096, rms_norm_eps=1e-6, rope_theta=10000.0,
tie_word_embeddings=True, qk_norm=True, sliding_window=2048,
diff=True, dropout=0.0, **kwargs):
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.max_position_embeddings = max_position_embeddings
self.rms_norm_eps = rms_norm_eps
self.rope_theta = rope_theta
self.qk_norm = qk_norm
self.sliding_window = sliding_window
self.diff = diff
self.dropout = dropout
def _hf_cfg(c):
inner = VeriConfig(vocab=c.vocab_size, layers=c.num_hidden_layers, dim=c.hidden_size,
q_heads=c.num_attention_heads, kv_heads=c.num_key_value_heads,
seq=c.max_position_embeddings, rope_theta=c.rope_theta,
qk_norm=c.qk_norm, sliding=c.sliding_window,
dropout=c.dropout, diff=c.diff)
inner.mlp_hidden = c.intermediate_size
return inner
class VeriForCausalLM(PreTrainedModel, GenerationMixin):
config_class = VeriHFConfig
base_model_prefix = "backbone"
supports_gradient_checkpointing = False
def __init__(self, config):
super().__init__(config)
bb = VeriTransformer(_hf_cfg(config))
# flat names match the checkpoint exactly (no backbone. prefix)
self.tok_emb = bb.tok_emb
self.pos_drop = bb.pos_drop
self.blocks = bb.blocks
self.norm = bb.norm
# input and output share one embedding module, nothing to tie.
# set explicitly: parent init runs before submodules exist.
self.all_tied_weights_keys = {}
def get_input_embeddings(self):
return self.tok_emb
def get_output_embeddings(self):
return self.tok_emb
def tie_weights(self, *args, **kwargs):
self._tied_weights_keys = []
def forward(self, input_ids, labels=None, attention_mask=None, **kwargs):
b, t = input_ids.shape
cos, sin = build_rope(t, self.config.hidden_size // self.config.num_attention_heads,
self.config.rope_theta, input_ids.device)
x = self.pos_drop(self.tok_emb(input_ids))
cos, sin = cos.to(x.dtype), sin.to(x.dtype)
for blk in self.blocks:
x = blk(x, cos, sin)
h = self.norm(x)
logits = F.linear(h, self.tok_emb.weight)
loss = None
if labels is not None:
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), labels.reshape(-1))
return CausalLMOutputWithPast(loss=loss, logits=logits)
except ImportError:
pass
def load_gguf_veri(path, dtype=None):
# loads OUR gguf container (fp16 tensors, ckpt names, 32B aligned).
# stock llama runtimes only know stock arches, this is the loader.
import struct
f = open(path, "rb")
assert f.read(4) == b"GGUF", "not a gguf file"
ver = struct.unpack("<I", f.read(4))[0]
assert ver == 3, f"gguf v{ver}, need v3"
nt = struct.unpack("<Q", f.read(8))[0]
nkv = struct.unpack("<Q", f.read(8))[0]
sizes = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
for _ in range(nkv):
ln = struct.unpack("<Q", f.read(8))[0]
f.seek(ln, 1)
t = struct.unpack("<I", f.read(4))[0]
if t == 8:
ll = struct.unpack("<Q", f.read(8))[0]
f.seek(ll, 1)
elif t == 9:
raise ValueError("array metadata not supported by this loader")
else:
f.seek(sizes[t], 1)
infos = []
for _ in range(nt):
ln = struct.unpack("<Q", f.read(8))[0]
name = f.read(ln).decode()
nd = struct.unpack("<I", f.read(4))[0]
shape = tuple(struct.unpack("<Q", f.read(8))[0] for _ in range(nd))
tt = struct.unpack("<I", f.read(4))[0]
off = struct.unpack("<Q", f.read(8))[0]
infos.append((name, shape, tt, off))
base = f.tell()
base += (-base) % 32
sd = {}
for name, shape, tt, off in infos:
if tt != 1:
raise ValueError(f"{name}: only f16 supported, got type {tt}")
n = 1
for s in shape:
n *= s
f.seek(base + off)
sd[name] = torch.frombuffer(f.read(n * 2), dtype=torch.float16).reshape(shape).clone()
f.close()
cfg = VeriConfig(seq=4096, qk_norm=True, sliding=2048, diff=True)
cfg.mlp_hidden = 5504
net = VeriTransformer(cfg)
net.load_state_dict(sd)
if dtype is not None:
if isinstance(dtype, str):
dtype = getattr(torch, dtype)
net = net.to(dtype)
return net