Skip to content

Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.

6.1 KB
Raw Blame
"""QAT uses float master parameters and exact rounded forward values with STE gradients."""
import gzip
import json
import os
os.environ["CUDA_VISIBLE_DEVICES"]=""
os.environ["OMP_NUM_THREADS"]="16"
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from fixed_point import DT,MAGIC,grams,forward,embed

torch.set_num_threads(4)
torch.set_num_interop_threads(1)
torch.manual_seed(924)
torch.use_deterministic_algorithms(True)


class Data:
    def __init__(self,folder,prefix=""):
        self.names = [""]
        index = {"":0}
        self.splits = {}
        for split in ("train","cal","val","test"):
            with gzip.open(folder/(prefix+split+".jsonl.gz"),"rt") as f:
                rows = [json.loads(s) for s in f]
            steps = [[e for e in r["events"] if e["kind"]!="fork"] for r in rows]
            # Generator follows a single lineage. Every fork makes a bitwise state copy.
            # Right padding is skipped, so each final output belongs to the last real hook.
            size = (len(rows),max(map(len,steps)))
            x = np.zeros((*size,16),np.int8)
            names = np.zeros(size,np.int32)
            for i,seq in enumerate(steps):
                for j,e in enumerate(seq):
                    x[i,j] = e["x"]
                    name = e["name"]
                    if name not in index:
                        index[name]=len(self.names)
                        self.names.append(name)
                    names[i,j]=index[name]
            self.splits[split] = (torch.from_numpy(x),torch.from_numpy(names),torch.tensor(list(map(len,steps))),
                                  torch.tensor([r["labels"] for r in rows],dtype=torch.float32),
                                  np.array([r["family"] for r in rows]),np.array([r["case"] for r in rows]))
        # Compress repeat 3-grams within each bounded name for sparse pooling.
        indices,counts = [],[]
        for i,name in enumerate(self.names):
            ids,c = np.unique(grams(name),return_counts=True)
            indices.extend((i,int(v)) for v in ids)
            counts.extend(c)
        self.pool=torch.sparse_coo_tensor(torch.tensor(indices).T,torch.tensor(counts,dtype=torch.float32),
                                          (len(self.names),1024)).coalesce().to_sparse_csr()


def ste(x,discrete):
    return x + (discrete-x).detach()


def quant(x,scale):
    v=(x*scale).clamp(-128,127)
    return ste(v,v.round())


def floor(x):
    return ste(x,torch.floor(x))


class Model(nn.Module):
    def __init__(self,recurrent,table=None):
        super().__init__()
        self.recurrent=recurrent
        self.emb=nn.Parameter(torch.randn(1024,16)*0.12 if table is None else table.clone(),
                              requires_grad=table is None)
        self.l1=nn.Linear(64 if recurrent else 32,64)
        self.l2=nn.Linear(64,4)
        if recurrent:
            with torch.no_grad():
                self.l1.weight[:32,32:]+=0.55*torch.eye(32)

    def weights(self,layer):
        w=quant(layer.weight,64)
        b=layer.bias*64
        return w,ste(b,b.round())

    def forward(self,pool,x,ids,lengths,qat=True):
        emb=quant(self.emb,64) if qat else self.emb*64
        table=(torch.sparse.mm(pool,emb)/8)
        table=(floor(table) if qat else table).clamp(-128,127)
        batch=torch.cat([x,table[ids.long()]],dim=-1)
        w1,b1=self.weights(self.l1) if qat else (self.l1.weight*64,self.l1.bias*64)
        w2,b2=self.weights(self.l2) if qat else (self.l2.weight*64,self.l2.bias*64)
        h=torch.zeros(len(x),32)
        slots=torch.arange(len(x))
        if not self.recurrent:
            batch=batch[slots,lengths-1][:,None,:]
        states=[]
        for v in batch.unbind(dim=1):
            z=F.linear(torch.cat([v,h],dim=1) if self.recurrent else v,w1,b1)/64
            z=(floor(z) if qat else z).clamp(0,127)
            h=z[:,:32]
            states.append(z)
        last=torch.stack(states,dim=1)[slots,lengths-1] if self.recurrent else z
        out=F.linear(last,w2,b2)/64
        return (floor(out) if qat else out).clamp(-128,127)/8

    def packed(self):
        a=np.zeros((),dtype=DT)
        for k,v in dict(magic=MAGIC,model_gen=1,shift1=6,shift2=6,emb_shift=3,
                        thresh_deny=192,max_uncertainty=127).items():
            a[k]=v
        with torch.no_grad():
            a["emb"]=quant(self.emb,64).numpy()
            for i,layer in enumerate([self.l1,self.l2],1):
                w,b=self.weights(layer)
                a["W"+str(i)][:,:w.shape[1]]=w.numpy()
                a["b"+str(i)]=b.numpy()
        return a


def train(data,recurrent,table=None):
    model=Model(recurrent,table)
    opt=torch.optim.Adam(model.parameters(),lr=0.003)
    x,ids,lengths,y,*_=data.splits["train"]
    best,best_loss=None,float("inf")
    for epoch in range(24):
        for idx in torch.randperm(len(y)).split(256):
            logits=model(data.pool,x[idx],ids[idx],lengths[idx])
            loss=F.binary_cross_entropy_with_logits(logits,y[idx])
            opt.zero_grad()
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(),3.)
            opt.step()
        with torch.no_grad():
            vx,vi,vl,vy,*_=data.splits["val"]
            pred=model(data.pool,vx,vi,vl)
            val=F.binary_cross_entropy_with_logits(pred,vy).item()
            if val<best_loss:
                best_loss=val
                best={k:v.detach().clone() for k,v in model.state_dict().items()}
    model.load_state_dict(best)
    return model


def infer(data,split,model):
    x,ids,lengths,_,_,_=data.splits[split]
    w=model.packed()
    n=len(x)
    table=np.stack([embed(w,s) for s in data.names])
    h=np.zeros((n,32),np.int8)
    result=np.zeros((n,4),np.int32)
    for i in range(x.shape[1]):
        v=np.concatenate([x[:,i].numpy(),table[ids[:,i].numpy()]],axis=1)
        h,logits,_=forward(w,v,h if model.recurrent else np.zeros_like(h))
        mask=lengths.numpy()==i+1
        result[mask]=logits[mask]
    with torch.no_grad():
        fp=model(data.pool,x,ids,lengths,qat=False).numpy()
        exact=model(data.pool,x,ids,lengths).numpy()*8
    np.testing.assert_array_equal(exact,result)
    return result,fp