okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

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