File size: 4,282 Bytes
fdddde2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""Torch-FREE checkpoint verifier (NumPy only). Reads the real .pt file, re-implements the
VictusTinyLM forward pass, and runs the engine's own prompt/stop/cleanup logic on the real weights.
It exists to check a checkpoint on machines without PyTorch. It is NOT the production inference path
(server.py + inference.py use PyTorch and model.py).

    python tools/verify_checkpoint_numpy.py [path/to/checkpoint.pt]
"""
import collections, math, pickle, sys, zipfile
from math import erf
from pathlib import Path
import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent))
from inference import build_prompt_plan, _ends_turn, finalize_text, UNK_TOKEN  # noqa: E402


DT={'FloatStorage':np.float32,'LongStorage':np.int64,'DoubleStorage':np.float64,'HalfStorage':np.float16}
class Storage:
    def __init__(s,arr): s.arr=arr
def rebuild(storage,offset,size,stride,*a,**k):
    n=int(np.prod(size)) if size else 1
    flat=storage.arr[offset:offset+n]
    return np.lib.stride_tricks.as_strided(flat,shape=size,strides=[x*flat.itemsize for x in stride]).copy() if size else flat[0]
def load(path):
    z=zipfile.ZipFile(path); names=z.namelist(); root=names[0].split('/')[0]
    class U(pickle.Unpickler):
        def find_class(s,mod,name):
            if name=='_rebuild_tensor_v2': return rebuild
            if name=='OrderedDict': return collections.OrderedDict
            if mod=='torch' and name.endswith('Storage'): return name
            if mod=='torch._utils' or mod.startswith('torch'): return lambda *a,**k:None
            return super().find_class(mod,name)
        def persistent_load(s,pid):
            _,stype,key,loc,numel=pid
            return Storage(np.frombuffer(z.read(f'{root}/data/{key}'),dtype=DT[stype if isinstance(stype,str) else 'FloatStorage']))
    return U(z.open(f'{root}/data.pkl')).load()
def ln(x,w,b,eps=1e-5):
    m=x.mean(-1,keepdims=True); v=x.var(-1,keepdims=True); return (x-m)/np.sqrt(v+eps)*w+b
_erf=np.vectorize(erf)
def gelu(x): return 0.5*x*(1+_erf(x/np.sqrt(2)))
def forward(sd,cfg,ids):
    L=len(ids); d=cfg['d_model']; H=cfg['n_heads']; hd=d//H
    x=sd['token_embedding.weight'][ids]+sd['position_embedding.weight'][:L]
    mask=np.triu(np.ones((L,L),bool),1)
    for i in range(cfg['n_layers']):
        p=f'transformer.layers.{i}.'
        h=ln(x,sd[p+'norm1.weight'],sd[p+'norm1.bias'])
        qkv=h@sd[p+'self_attn.in_proj_weight'].T+sd[p+'self_attn.in_proj_bias']
        q,k,v=np.split(qkv,3,-1)
        q,k,v=[t.reshape(L,H,hd).transpose(1,0,2) for t in (q,k,v)]
        s=q@k.transpose(0,2,1)/math.sqrt(hd); s[:,mask]=-np.inf
        s=np.exp(s-s.max(-1,keepdims=True)); s/=s.sum(-1,keepdims=True)
        a=(s@v).transpose(1,0,2).reshape(L,d)
        x=x+a@sd[p+'self_attn.out_proj.weight'].T+sd[p+'self_attn.out_proj.bias']
        h=ln(x,sd[p+'norm2.weight'],sd[p+'norm2.bias'])
        h=gelu(h@sd[p+'linear1.weight'].T+sd[p+'linear1.bias'])@sd[p+'linear2.weight'].T+sd[p+'linear2.bias']
        x=x+h
    return ln(x,sd['final_norm.weight'],sd['final_norm.bias'])@sd['lm_head.weight'].T

def generate(ck, prompt, max_new=48):
    cfg, sd, vocab = ck["config"], ck["state_dict"], ck["vocab"]
    inv = {i: t for t, i in vocab.items()}
    plan = build_prompt_plan([{"role": "user", "content": prompt}], vocab, cfg["block_size"], max_new)
    ids, gen = list(plan.ids), []
    for _ in range(max_new):
        logits = forward(sd, cfg, ids[-cfg["block_size"]:])[-1].copy()
        logits[0] = -np.inf
        t = int(logits.argmax()); ids.append(t); gen.append(inv.get(t, UNK_TOKEN))
        b = _ends_turn(gen)
        if b:
            del gen[-b:]; break
    return finalize_text(gen, 2000), plan

if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else str(Path(__file__).resolve().parent / "victus-tiny-v0.4.pt")
    ck = load(path)
    n = sum(int(np.prod(v.shape)) for v in ck["state_dict"].values())
    print(f"parameters={n:,} vocab={len(ck['vocab'])} block_size={ck['config']['block_size']} layers={ck['config']['n_layers']} d_model={ck['config']['d_model']}")
    for prompt in ["What is gravity?", "What is an algorithm?", "Hello"]:
        text, plan = generate(ck, prompt)
        print(f"\nPROMPT: {prompt}  (prompt_tokens={plan.prompt_tokens})\nGREEDY: {text!r}")