okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). 2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. 3"""tools/ds4/ref.py - a whole-sequence DeepSeek-V4.1 forward in torch over an EXL3 checkpoint (the engine's oracle). 4 5python tools/ds4/ref.py --model ~/models/DSV4 --text "The capital of France is" [--dump out.npz] [--gen 8] 6 7It follows DeepSeek's inference/model.py (MIT) at start_pos 0 - the prompt path, every position at once - with each 8layer's weights decoded from EXL3 when the layer runs (tools/ds4/exl3_torch.py) and freed after it, so one GPU of 924 GB carries the 211 GB model: Hyper-Connections with the lagged pre-mix, sliding-window plus compressed sparse 10attention with the two-level indexer and its candidate blocks, the cross-layer KV / indexer sharing, Engram, the 11sqrt-softplus router, and the FP8 / FP4 activation rounding of the reference kernels (simulated, as their `inplace` 12paths do). Activations are F32 throughout (the reference keeps BF16 between ops). 13 14--dump writes every layer's residual stream ([T, hc, dim] F32 after each block), the logits and the token ids, for 15the engine's parity checks. 16""" 17from __future__import annotations 18 19import argparse 20import json 21import math 22import pathlib 23import sys 24import time 25 26import numpy as np 27import torch 28import torch .nn .functional as F 29 30HERE = pathlib .Path (__file__ ).resolve ().parent 31sys .path .insert (0 ,str (HERE )) 32import engram_hash as EH # noqa: E402 33import exl3_torch as ET # noqa: E402 34from st import SafeTensors # noqa: E402 35 36 37# ------------------------------------------------------------------ the reference kernels' roundings 38def fp8_round (x :torch .Tensor ,block :int = 32 )-> torch .Tensor : 39"""act_quant(..., scale_fmt='ue8m0', inplace=True): per `block` values a power-of-two scale, E4M3 values.""" 40sh = x .shape 41v = x .float ().reshape (* sh [:- 1 ],sh [- 1 ]// block ,block ) 42amax = v .abs ().amax (- 1 ,keepdim = True ).clamp_min (1e-4 ) 43s = torch .exp2 (torch .ceil (torch .log2 (amax / 448.0 ))) 44y = (v / s ).clamp (- 448.0 ,448.0 ).to (torch .float8_e4m3fn ).float ()* s 45return y .reshape (sh ) 46 47 48_FP4 = torch .tensor ([0.0 ,0.5 ,1.0 ,1.5 ,2.0 ,3.0 ,4.0 ,6.0 ]) 49 50 51def _e2m1 (v :torch .Tensor )-> torch .Tensor : 52"""Round to the E2M1 grid, nearest, ties to the even mantissa (values already in [-6, 6]).""" 53a = v .abs () 54g = _FP4 .to (v .device ) 55d = (a .unsqueeze (- 1 )- g ).abs () 56best = d .argmin (- 1 ) 57# ties: argmin takes the lower index; the even mantissa is the lower one at 0.25, 1.25, 2.5, 5 and the upper one 58# at 0.75, 1.75, 3.5 (grid indices: mantissa bit = index & 1 for index >= 1, 0 at index 0) 59lo = best 60hi = (best + 1 ).clamp (max = 7 ) 61tie = (d .gather (- 1 ,lo .unsqueeze (- 1 )).squeeze (- 1 )== d .gather (- 1 ,hi .unsqueeze (- 1 )).squeeze (- 1 ))& (hi != lo ) 62take_hi = tie & ((lo & 1 )== 1 ) 63idx = torch .where (take_hi ,hi ,lo ) 64return torch .copysign (g [idx ],v ) 65 66 67def fp4_round (x :torch .Tensor ,block :int ,e4m3_scale :bool )-> torch .Tensor : 68"""fp4_act_quant(..., inplace=True): E2M1 values with an E8M0 (power of two) or an E4M3 scale per block.""" 69sh = x .shape 70v = x .float ().reshape (* sh [:- 1 ],sh [- 1 ]// block ,block ) 71amax = v .abs ().amax (- 1 ,keepdim = True ) 72if e4m3_scale : 73amax = amax .clamp_min (6 * 2.0 ** - 9 ) 74s = (amax / 6.0 ).to (torch .float8_e4m3fn ).float () 75else : 76amax = amax .clamp_min (6 * 2.0 ** - 126 ) 77s = torch .exp2 (torch .ceil (torch .log2 (amax / 6.0 ))) 78y = _e2m1 ((v / s ).clamp (- 6.0 ,6.0 ))* s 79return y .reshape (sh ) 80 81 82def rms (x :torch .Tensor ,w :torch .Tensor | None ,eps :float )-> torch .Tensor : 83x = x .float () 84y = x * torch .rsqrt (x .square ().mean (- 1 ,keepdim = True )+ eps ) 85return y * w if w is not None else y 86 87 88def freqs_cis (dim ,seqlen ,original_seq_len ,base ,factor ,beta_fast ,beta_slow ,dev )-> torch .Tensor : 89freqs = 1.0 / (base ** (torch .arange (0 ,dim ,2 ,dtype = torch .float32 )/ dim )) 90if original_seq_len > 0 : 91def corr (rot ): 92return dim * math .log (original_seq_len / (rot * 2 * math .pi ))/ (2 * math .log (base )) 93low = max (math .floor (corr (beta_fast )),0 ) 94high = min (math .ceil (corr (beta_slow )),dim - 1 ) 95ramp = ((torch .arange (dim // 2 ,dtype = torch .float32 )- low )/ max (high - low ,1e-3 )).clamp (0 ,1 ) 96smooth = 1 - ramp 97freqs = freqs / factor * (1 - smooth )+ freqs * smooth 98f = torch .outer (torch .arange (seqlen ,dtype = torch .float32 ),freqs ) 99return torch .polar (torch .ones_like (f ),f ).to (dev ) 100 101 102def rope (x :torch .Tensor ,fc :torch .Tensor ,inverse :bool = False )-> torch .Tensor : 103"""Adjacent pairs as complex numbers. x [T, d] or [T, h, d]; fc [T, d/2].""" 104c = torch .view_as_complex (x .float ().reshape (* x .shape [:- 1 ],- 1 ,2 ).contiguous ()) 105if inverse : 106fc = fc .conj () 107if x .ndim == 3 : 108fc = fc [:,None , :] 109return torch .view_as_real (c * fc ).flatten (- 2 ) 110 111 112# ------------------------------------------------------------------ the model 113class Ref : 114def __init__ (self ,model :pathlib .Path ,dev :str = "cuda:0" ,max_seq :int = 8192 ): 115self .dir = model 116self .cfg = json .loads ((model / "config.json" ).read_text ()) 117self .t = t = self .cfg ["text_config" ] 118self .st = SafeTensors (model ) 119self .dev = dev 120self .dim ,self .hc = t ["hidden_size" ],t ["hc_mult" ] 121self .eps = t ["rms_norm_eps" ] 122self .nl = t ["num_hidden_layers" ] 123self .ratios = t ["compress_ratios" ] 124self .kv_src = set (t ["kv_source_layer_ids" ]) 125self .ix_src = set (t ["index_source_layer_ids" ]) 126self .cand_src = t ["candidate_source_layer_id" ] 127rs = t ["rope_scaling" ] 128rd = t ["qk_rope_head_dim" ] 129self .fc_window = freqs_cis (rd ,max_seq ,0 ,t ["rope_theta" ],rs ["factor" ],rs ["beta_fast" ],rs ["beta_slow" ],dev ) 130self .fc_comp = freqs_cis (rd ,max_seq ,rs ["original_max_position_embeddings" ],t ["compress_rope_theta" ], 131rs ["factor" ],rs ["beta_fast" ],rs ["beta_slow" ],dev ) 132self .lay = EH .Layout .from_config (t ) 133tm ,n = EH .compressed_token_map (model / "tokenizer.json" ) 134if n != t ["engram_compressed_vocab_size" ]: 135raise SystemExit ("engram: compressed vocab %d, the config says %d" % (n ,t ["engram_compressed_vocab_size" ])) 136self .hasher = EH .Hasher (self .lay ,tm ,EH .multipliers (self .lay ,n ),tm [t ["engram_pad_token_id" ]]) 137self .timing :dict [str ,float ]= {} 138 139# weights 140def W (self ,prefix :str )-> torch .Tensor : 141return ET .weight (self .st ,prefix ,self .dev ) 142 143def V (self ,name :str )-> torch .Tensor : 144return torch .from_numpy (np .array (self .st .f32 (name ))).to (self .dev ) 145 146# pieces 147def hc_mixes (self ,x ,fn ,scale ,base ): 148hc = self .hc 149xf = x .flatten (1 ).float () 150r = torch .rsqrt (xf .square ().mean (- 1 ,keepdim = True )+ self .eps ) 151mixes = (xf @fn .T )* r # [T, (2 + hc) hc] 152pre = torch .sigmoid (mixes [:, :hc ]* scale [0 ]+ base [:hc ])+ self .t ["hc_eps" ] 153post = 2 * torch .sigmoid (mixes [:,hc :2 * hc ]* scale [1 ]+ base [hc :2 * hc ]) 154comb = (mixes [:,2 * hc :]* scale [2 ]+ base [2 * hc :]).view (- 1 ,hc ,hc ) 155eps = self .t ["hc_eps" ] 156comb = comb .softmax (- 1 )+ eps 157comb = comb / (comb .sum (- 2 ,keepdim = True )+ eps ) 158for _ in range (self .t ["hc_sinkhorn_iters" ]- 1 ): 159comb = comb / (comb .sum (- 1 ,keepdim = True )+ eps ) 160comb = comb / (comb .sum (- 2 ,keepdim = True )+ eps ) 161return pre ,post ,comb 162 163@staticmethod 164def hc_pre (x ,mix ):# [T, hc, d], [T, hc] -> [T, d] 165return (mix .unsqueeze (- 1 )* x ).sum (1 ) 166 167@staticmethod 168def hc_post (y ,res ,post ,comb ):# y [T, d], res [T, hc, d] 169return post .unsqueeze (- 1 )* y .unsqueeze (1 )+ (comb .unsqueeze (- 1 )* res .unsqueeze (2 )).sum (1 ) 170 171def engram (self ,li :int ,x :torch .Tensor ,hash_ids :np .ndarray )-> torch .Tensor : 172"""x [T, hc, d]; hash_ids [T, cols] absolute rows.""" 173P = "layers.%d.engram." % li 174T ,cols = hash_ids .shape 175flat = hash_ids .reshape (- 1 ) 176wt = self .st .raw (P + "embed.weight" ).view (np .uint8 ).reshape (- 1 ,self .lay .head_dim ) 177sc = self .st .raw (P + "embed.scale" ).view (np .uint8 ).reshape (- 1 ,self .lay .head_dim // 32 ) 178order = np .argsort (flat )# sequential reads 179rows = np .empty ((flat .size ,self .lay .head_dim ),np .uint8 ) 180srow = np .empty ((flat .size ,self .lay .head_dim // 32 ),np .uint8 ) 181rows [order ]= wt [flat [order ]] 182srow [order ]= sc [flat [order ]] 183v = torch .from_numpy (rows ).to (self .dev ).view (torch .float8_e4m3fn ).float () 184s = torch .from_numpy (srow ).to (self .dev ).view (torch .float8_e8m0fnu ).float () 185e = (v .view (- 1 ,self .lay .head_dim // 32 ,32 )* s .unsqueeze (- 1 )).view (T ,cols * self .lay .head_dim ) 186e = e .to (torch .bfloat16 ).float ()# ParallelEngramEmbedding returns BF16 187kv = e @self .W (P + "wkv" ).T # [T, (hc + 1) d] 188d ,hc = self .dim ,self .hc 189key ,value = kv [:, :hc * d ].view (T ,hc ,d ),kv [:,hc * d :] 190w = self .V (P + "q_weight" )* self .V (P + "k_weight" )# [hc, d] 191h = x .float () 192rstd = torch .rsqrt (h .square ().mean (- 1 )+ self .eps )* torch .rsqrt (key .square ().mean (- 1 )+ self .eps ) 193dot = (h * w * key ).sum (- 1 )* rstd * d ** - 0.5 194gate = torch .sigmoid (torch .copysign (dot .abs ().clamp_min (1e-6 ).sqrt (),dot )) 195return h + gate .unsqueeze (- 1 )* value .unsqueeze (1 ) 196 197def sparse_attn (self ,q ,kv ,sink ,idx ,scale ): 198"""q [T, H, D], kv [N, D], sink [H], idx [T, K] int (-1 none) -> [T, H, D].""" 199T ,H ,D = q .shape 200out = torch .empty_like (q ) 201for a in range (0 ,T ,256 ): 202b = min (T ,a + 256 ) 203ii = idx [a :b ] 204valid = ii >= 0 205g = kv [ii .clamp_min (0 )]# [t, K, D] 206s = torch .einsum ("thd,tkd->thk" ,q [a :b ],g )* scale 207s = s .masked_fill (~ valid .unsqueeze (1 ),float ("-inf" )) 208m = torch .maximum (s .amax (- 1 ),sink [None , :])# [t, H] 209m = torch .maximum (m ,torch .full_like (m ,- 1e30 )) 210p = torch .exp (s - m .unsqueeze (- 1 )) 211den = p .sum (- 1 )+ torch .exp (sink [None , :]- m ) 212out [a :b ]= torch .einsum ("thk,tkd->thd" ,p ,g )/ den .unsqueeze (- 1 ) 213return out 214 215@staticmethod 216def candidates (logits ,compress_lens ,topk_blocks ,block ): 217width = logits .size (- 1 ) 218scores = F .pad (logits , (0 ,- width % block ),value = float ("-inf" )) 219scores = scores .unflatten (- 1 , (- 1 ,block )).amax (- 1 ) 220nb = scores .size (- 1 ) 221last = (compress_lens - 1 )// block 222scores = scores .masked_fill (torch .arange (nb ,device = logits .device )== last ,float ("inf" )) 223top = scores .topk (min (topk_blocks ,nb ),dim =- 1 ) 224keep = torch .zeros_like (scores ,dtype = torch .bool ).scatter_ (- 1 ,top .indices ,top .values > float ("-inf" )) 225return keep .repeat_interleave (block ,dim =- 1 )[..., :width ] 226 227def attention (self ,li :int ,x :torch .Tensor ,S :dict )-> torch .Tensor : 228t = self .t 229A = ("layers.%d.attn." % li )if li < self .nl else ("mtp.%d.attn." % (li - self .nl )) 230T = x .shape [0 ] 231H ,D ,rd = t ["num_attention_heads" ],t ["head_dim" ],t ["qk_rope_head_dim" ] 232ratio = self .ratios [li ] 233fc = (self .fc_comp if ratio else self .fc_window )[:T ] 234qr = rms (x @self .W (A + "wq_a" ).T ,self .V (A + "q_norm.weight" ),self .eps ) 235q = (qr @self .W (A + "wq_b" ).T ).view (T ,H ,D ) 236q = torch .cat ([q [..., :- rd ],rope (q [...,- rd :],fc )],- 1 ) 237kv = rms (x @self .W (A + "wkv" ).T ,self .V (A + "kv_norm.weight" ),self .eps ) 238kv = torch .cat ([kv [:, :- rd ],rope (kv [:,- rd :],fc )],- 1 ) 239kv = fp8_round (kv ) 240win = t ["sliding_window" ] 241end = torch .arange (T ,device = self .dev ).unsqueeze (1 ) 242widx = (end - win + 1 ).clamp (0 )+ torch .arange (min (T ,win ),device = self .dev ) 243widx = torch .where (widx > end ,- 1 ,widx ) 244all_kv ,all_idx = kv ,widx 245if ratio : 246is_src = li < self .nl and li in self .kv_src 247latent = None 248if is_src : 249C = A + "compressor." 250if ratio == 1 : 251latent = rms (x @self .W (C + "wkv" ).T ,self .V (C + "norm.weight" ),self .eps ) 252elif T >= ratio : 253cut = T - T % ratio 254kvc = x [:cut ] @self .W (C + "wkv" ).T 255sc = x [:cut ] @self .W (C + "wgate" ).T 256kvc ,sc = kvc .view (- 1 ,ratio ,D ),sc .view (- 1 ,ratio ,D ) 257latent = rms ((kvc * sc .softmax (1 )).sum (1 ),self .V (C + "norm.weight" ),self .eps ) 258# the indexer (index sources) before the latent is rotated 259if li < self .nl and li in self .ix_src : 260S ["topk" ]= self .indexer (li ,A ,x ,qr ,latent ,ratio ,T ,fc ,S ) 261if latent is not None : 262lat = torch .cat ([latent [:, :- rd ],rope (latent [:,- rd :],fc [:T - T % ratio :ratio ])],- 1 ) 263S ["ckv" ]= fp4_round (lat ,16 ,True ) 264ckv = S ["ckv" ][:T // ratio ]if S .get ("ckv" )is not None else kv .new_zeros (0 ,D ) 265all_kv = torch .cat ([kv ,ckv ],0 ) 266all_idx = torch .cat ([widx ,S ["topk" ]],- 1 ) 267o = self .sparse_attn (q ,all_kv ,self .V (A + "attn_sink" ),all_idx ,D ** - 0.5 ) 268o = torch .cat ([o [..., :- rd ],rope (o [...,- rd :],fc ,inverse = True )],- 1 ) 269G = t ["o_groups" ] 270o = fp8_round (o .reshape (T ,G ,- 1 )) 271parts = [o [:,g ] @self .W (A + "wo_a.slice.%d" % g ).T for g in range (G )] 272return torch .cat (parts ,- 1 ) @self .W (A + "wo_b" ).T 273 274def indexer (self ,li ,A ,x ,qr ,latent ,ratio ,T ,fc ,S ): 275t = self .t 276I = A + "indexer." 277nh ,hd ,rd = t ["index_n_heads" ],t ["index_head_dim" ],t ["qk_rope_head_dim" ] 278clen = T // ratio 279if clen == 0 : 280return torch .empty (T ,0 ,dtype = torch .long ,device = self .dev ) 281if li in self .kv_src and latent is not None :# this layer owns the index keys 282k = rms (latent @self .W (I + "wk" ).T ,self .V (I + "k_norm.weight" ),self .eps ) 283k = torch .cat ([k [:, :- rd ],rope (k [:,- rd :],fc [:T - T % ratio :ratio ])],- 1 ) 284S ["ik" ]= fp4_round (k ,32 ,False ) 285q = (qr @self .W (I + "wq_b" ).T ).view (T ,nh ,hd ) 286q = torch .cat ([q [..., :- rd ],rope (q [...,- rd :],fc )],- 1 ) 287q = fp4_round (q ,32 ,False ) 288ik = S ["ik" ][:clen ] 289w = (x @self .V (I + "weights_proj.weight" ).T )* (hd ** - 0.5 * nh ** - 0.5 )# [T, nh] 290score = torch .zeros (T ,clen ,device = self .dev ) 291for a in range (0 ,T ,512 ): 292b = min (T ,a + 512 ) 293s = torch .einsum ("thd,kd->thk" ,q [a :b ],ik ).relu_ () 294score [a :b ]= (s * w [a :b ].unsqueeze (- 1 )).sum (1 ) 295lens = (torch .arange (1 ,T + 1 ,device = self .dev )// ratio ).unsqueeze (- 1 ) 296score = score .masked_fill (torch .arange (clen ,device = self .dev )>= lens ,float ("-inf" )) 297if li == self .cand_src : 298S ["cand" ]= self .candidates (score ,lens ,t ["candidate_topk_blocks" ],t ["candidate_block_size" ]) 299elif 0 <= self .cand_src < li : 300score = score .masked_fill (~ S ["cand" ],float ("-inf" )) 301topk = min (t ["index_topk" ],clen ) 302idx = score .topk (topk ,dim =- 1 ,sorted = False ).indices .sort (- 1 ).values 303return torch .where (idx < lens ,idx + T ,- 1 ) 304 305def moe (self ,li :int ,x :torch .Tensor )-> torch .Tensor : 306t = self .t 307M = "layers.%d.ffn." % li 308T = x .shape [0 ] 309gw = self .V (M + "gate.weight" ) 310scores = F .softplus (x .float () @gw .T ).sqrt () 311idx = (scores + self .V (M + "gate.bias" )).topk (t ["num_experts_per_tok" ],dim =- 1 )[1 ] 312wts = scores .gather (1 ,idx ) 313wts = wts / (wts .sum (- 1 ,keepdim = True )+ 1e-20 )* t ["routed_scaling_factor" ] 314lim = t ["swiglu_limit" ] 315y = torch .zeros (T ,self .dim ,device = self .dev ) 316 317def expert (P ,xs ): 318g = (xs @self .W (P + "w1" ).T ).clamp (max = lim ) 319u = (xs @self .W (P + "w3" ).T ).clamp (- lim ,lim ) 320return F .silu (g )* u ,P 321 322uniq = torch .unique (idx ).tolist () 323for a in range (0 ,len (uniq ),24 ):# 24 experts decoded at once 324batch = uniq [a :a + 24 ] 325Ps = [M + "experts.%d." % e for e in batch ] 326w1 = ET .decode_many (self .st , [P + "w1" for P in Ps ],self .dev ) 327w3 = ET .decode_many (self .st , [P + "w3" for P in Ps ],self .dev ) 328w2 = ET .decode_many (self .st , [P + "w2" for P in Ps ],self .dev ) 329for i ,e in enumerate (batch ): 330rows ,slot = torch .where (idx == e ) 331xs = x [rows ] 332h = F .silu ((xs @w1 [i ].T ).clamp (max = lim ))* (xs @w3 [i ].T ).clamp (- lim ,lim ) 333y .index_add_ (0 ,rows , (h * wts [rows ,slot ,None ]) @w2 [i ].T ) 334del w1 ,w2 ,w3 335h ,_ = expert (M + "shared_experts." ,x ) 336y += h @self .W (M + "shared_experts.w2" ).T 337self .last_route = (idx ,wts ) 338return y 339 340@ torch . inference_mode () 341def forward (self ,ids :list [int ],dump :list | None = None )-> torch .Tensor : 342T = len (ids ) 343hashes = self .hasher .ids (ids )# [T, n_engram, cols] 344emb = self .st .raw ("embed.weight" ).view (np .uint16 ).reshape (- 1 ,self .dim ) 345h = torch .from_numpy (np .array (emb [np .asarray (ids )])).to (self .dev ).view (torch .bfloat16 ).float () 346h = h .unsqueeze (1 ).repeat (1 ,self .hc ,1 ) 347pre = torch .zeros (T ,self .hc ,device = self .dev ) 348pre [:,0 ]= 1.0 349S :dict = {} 350for li in range (self .nl ): 351t0 = time .time () 352B = "layers.%d." % li 353if li in self .lay .layer_ids : 354h = self .engram (li ,h ,hashes [:,self .lay .layer_ids .index (li )]) 355res = h 356a_pre ,a_post ,a_comb = self .hc_mixes (h ,self .V (B + "hc_attn_fn" ),self .V (B + "hc_attn_scale" ), 357self .V (B + "hc_attn_base" )) 358x = rms (self .hc_pre (h ,pre ),self .V (B + "attn_norm.weight" ),self .eps ) 359h = self .hc_post (self .attention (li ,x ,S ),res ,a_post ,a_comb ) 360res = h 361f_pre ,f_post ,f_comb = self .hc_mixes (h ,self .V (B + "hc_ffn_fn" ),self .V (B + "hc_ffn_scale" ), 362self .V (B + "hc_ffn_base" )) 363x = rms (self .hc_pre (h ,a_pre ),self .V (B + "ffn_norm.weight" ),self .eps ) 364h = self .hc_post (self .moe (li ,x ),res ,f_post ,f_comb ) 365pre = f_pre 366if dump is not None : 367dump .append (h .cpu ().numpy ()) 368self .timing [li ]= time .time ()- t0 369x = rms (self .hc_pre (h ,pre ),self .V ("norm.weight" ),self .eps ) 370head = self .W ("head" ) 371return x @head .T # [T, vocab] 372 373 374def main ()-> int : 375ap = argparse .ArgumentParser () 376ap .add_argument ("--model" ,default = str (pathlib .Path ("~/models/DSV4" ).expanduser ())) 377ap .add_argument ("--text" ,help = "raw text (tokenized as is, no BOS added)" ) 378ap .add_argument ("--ids" ,help = "comma-separated token ids" ) 379ap .add_argument ("--chat" ,help = "a user message, as DeepSeek-V4.1's chat (non-thinking) prompt" ) 380ap .add_argument ("--gen" ,type = int ,default = 0 ,help = "greedy tokens to append (a whole forward each)" ) 381ap .add_argument ("--dump" ,help = "write the per-layer residual streams, the logits and the ids (.npz)" ) 382ap .add_argument ("--no-hs" ,action = "store_true" ,help = "--dump without the per-layer residual streams" ) 383ap .add_argument ("--dev" ,default = "cuda:0" ) 384a = ap .parse_args () 385model = pathlib .Path (a .model ).expanduser () 386from tokenizers import Tokenizer 387tok = Tokenizer .from_file (str (model / "tokenizer.json" )) 388if a .ids : 389ids = [int (x )for x in a .ids .split ("," )] 390elif a .chat : 391ids = tok .encode ("<|begin▁of▁sentence|><|User|>" + a .chat + "<|Assistant|></think>" , 392add_special_tokens = False ).ids 393else : 394ids = tok .encode (a .text or "The capital of France is" ,add_special_tokens = False ).ids 395r = Ref (model ,a .dev ) 396"tokens:" ,len (ids ),ids [:32 ],flush = True ) 397dump = []if a .dump and not a .no_hs else None 398t0 = time .time () 399logits = r .forward (ids ,dump ) 400"forward %.1fs" % (time .time ()- t0 ),flush = True ) 401lp = torch .log_softmax (logits .float (),- 1 ) 402if len (ids )> 1 : 403tgt = torch .tensor (ids [1 :],device = lp .device ) 404nll = - lp [:- 1 ].gather (1 ,tgt [:,None ]).squeeze (1 ) 405"ppl over %d tokens: %.4f" % (len (ids )- 1 ,math .exp (nll .mean ().item ()))) 406top = lp [- 1 ].topk (8 ) 407"next:" , [(tok .decode ([i ]),round (v ,3 ))for v ,i in zip (top .values .tolist (),top .indices .tolist ())]) 408if a .dump : 409np .savez (a .dump ,ids = np .array (ids ),logits = logits .cpu ().numpy (), 410hs = np .stack (dump )if dump else np .zeros (0 )) 411out = list (ids ) 412for _ in range (a .gen ): 413nxt = int (lp [- 1 ].argmax ()) 414out .append (nxt ) 415"gen:" ,repr (tok .decode (out [len (ids ):],skip_special_tokens = False )),flush = True ) 416if nxt == 1 : 417break 418logits = r .forward (out ) 419lp = torch .log_softmax (logits .float (),- 1 ) 420return 0 421 422 423if __name__ == "__main__" : 424sys .exit (main ())