File size: 18,913 Bytes
fad02af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fad02af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
fad02af
 
 
 
 
 
 
 
ba145f2
 
 
 
 
 
 
 
 
 
fad02af
 
 
 
 
 
 
ba145f2
fad02af
ba145f2
 
fad02af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba145f2
fad02af
ba145f2
fad02af
ba145f2
 
 
 
fad02af
 
 
 
 
ba145f2
 
fad02af
 
ba145f2
fad02af
ba145f2
fad02af
 
ba145f2
fad02af
 
ba145f2
fad02af
 
ba145f2
fad02af
 
 
 
 
 
 
 
 
 
ba145f2
fad02af
 
 
 
 
 
 
 
 
ba145f2
 
 
 
 
 
 
 
 
 
 
 
 
 
fad02af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# -*- coding: utf-8 -*-
"""Capture genuine byte-by-byte inference internals from mini-beatrix-2.5s.

The craft is the full 237.1M mini-beatrix-2s core. Every capture is taken
TWICE over the SAME byte sequence — once on the bare core and once with
the library's top arm mounted — so every per-byte quantity is directly
comparable and the arm's contribution is a difference, not a guess.

Method. The reply is generated normally (greedy, the arm's own frame).
The complete sequence (prompt bytes + reply bytes) is then re-run through
ONE instrumented forward pass that walks the blocks by hand, recording
what each layer did at each byte position. The model is causal, so the
traced state at position i is the state the decode actually had there.

What is recorded, per byte, per layer:
  * the oriented address READ  (per constellation, per anchor)
  * the blackboard MASS        (per constellation, per anchor, cumulative)
  * the agreement mass (the splat denominator) per constellation
  * an exact effective attention row over all earlier bytes, derived from
    the same bilinear forms the scan sums
  * the residual stream norm in/out, the attention contribution, the bank
    trunk and dispatched-expert contributions
  * the three anchored experts' signed dispatch weights
  * the arm's patch norm and gate at that site (arm runs only)
and per byte at the head: the 256-atom signed head address, the predicted
byte distribution (top 8), its entropy, and the byte actually taken.

Usage:  python capture.py [--out DIR] [--max-bytes N]
"""
from __future__ import annotations

import json
import os
import sys

import numpy as np
import torch
import torch.nn.functional as F

REPO = r"E:/mirel/alephllm-chat/mb25/repo"
OUT = r"E:/mirel/alephllm-chat/mb25/captures"
ARM = "rules"                      # the library's top row (rank 0)
MAXB = 400
DEV = "cuda" if torch.cuda.is_available() else "cpu"

PROMPTS = [
    dict(id="rule-chain",
         title="Five rules about invented words",
         why="the arm's own domain: it reads five if-then rules about words "
             "the model never saw in pretraining and answers with the last "
             "one. The core alone does not.",
         text=("If someone is clea, then they are plyi. If someone is plyi, "
               "then they are ploym. If someone is ploym, then they are "
               "triu. If someone is triu, then they are tricu. If someone "
               "is tricu, then they are grash. Wren is clea. What follows? "
               "Reply with only the final answer."),
         gold="grash", max_new=32),
    dict(id="plain-question",
         title="An ordinary question",
         why="outside the arm's domain. The arm was trained with an "
             "abstention term, so the interesting thing here is how little "
             "it changes.",
         gold=None, text="What is a river?",
         max_new=96),
]


# ------------------------------------------------------------- quantizing
def q8(a: np.ndarray, signed: bool):
    """uint8 with one scale per array. Signed arrays centre on 128."""
    a = np.asarray(a, dtype=np.float32)
    m = float(np.abs(a).max()) if signed else float(a.max())
    m = m if m > 0 else 1.0
    if signed:
        q = np.clip(np.round(a / m * 127.0) + 128, 0, 255)
    else:
        q = np.clip(np.round(a / m * 255.0), 0, 255)
    return q.astype(np.uint8), m


def q8_dev(a: np.ndarray):
    """The fix for the anchor arrays: store the MEAN over bytes separately
    and quantize only the DEVIATION from it, with one scale per (block,
    constellation).

    Measured on the first capture: every anchor picture is dominated by a
    large constant component — the cosine similarity between neighbouring
    bytes is 1.000 — and the part that varies byte to byte is ~4% of the
    whole. Against ONE global scale that varying part lands below a single
    quantization step (0.1-0.3 of a step), so the published arrays carried
    almost no per-byte information at all. Splitting the constant off and
    giving each (block, constellation) its own scale puts the per-byte
    signal back in range, and the absolute value is still exactly
    recoverable as mean + deviation.

    The scale is the 99.5th percentile of |deviation|, NOT its maximum.
    Measured: the first two bytes of a sequence deviate ~25x more than
    every later byte (the blackboard is nearly empty there, so the
    oriented distribution is extreme), and against a max-based scale those
    two bytes crushed all 369 others into 25 of the 256 levels. The field
    is also sparse — the median |deviation| is exactly zero, a handful of
    anchors carrying everything — so a percentile scale spends the range
    where the signal is. The few cells above it clip, which is reported.

    a: (L, C, n, K) -> (uint8 dev, mean (L,C,K), scale (L,C), clipped frac)
    """
    a = np.asarray(a, dtype=np.float32)
    mean = a.mean(axis=2)                                   # (L, C, K)
    dev = a - mean[:, :, None, :]
    flat = np.abs(dev).reshape(dev.shape[0], dev.shape[1], -1)
    scale = np.percentile(flat, 99.5, axis=2)               # (L, C)
    scale = np.where(scale > 0, scale, np.abs(dev).max() or 1.0).astype(np.float32)
    clipped = float((flat > scale[:, :, None]).mean())
    q = np.clip(np.round(dev / scale[:, :, None, None] * 127.0) + 128, 0, 255)
    return q.astype(np.uint8), mean, scale, clipped


def wbin(path, arr):
    arr.tofile(path)
    return os.path.getsize(path)


# ------------------------------------------------------------------ trace
@torch.no_grad()
def trace(model, ids):
    """One instrumented forward. Returns numpy records, everything fp32."""
    from arms import BlockWithAdapter, BlockWithDispatch      # noqa: F401
    n = ids.shape[1]
    rec = {"layers": [], "n": n}
    x = model.embed(ids)
    rec["embed_norm"] = x[0].norm(dim=-1).float().cpu().numpy()

    for li, wrapped in enumerate(model.blocks):
        blk = getattr(wrapped, "block", wrapped)
        adapter = getattr(wrapped, "adapter", None)
        armed = adapter is not None and getattr(wrapped, "enabled", False)
        L = {"resid_in": x[0].norm(dim=-1).float().cpu().numpy()}

        h = blk.n1(x)
        units = blk.attn._units()
        reads, mass, dens, att = [], [], [], None
        writes, shapes, used = [], [], []
        for addr, qm, km in units:
            qp, qn = addr.oriented(qm(h))
            kp, kn = addr.oriented(km(h))
            zp, zn = qp.new_zeros(qp.shape), qp.new_zeros(qp.shape)
            torch.cumsum(kp, dim=1, out=zp)
            torch.cumsum(kn, dim=1, out=zn)
            dens.append(((qp * zp).sum(-1) + (qn * zn).sum(-1))[0])
            reads.append((qp - qn)[0])                   # signed read
            writes.append((kp - kn)[0])                  # what THIS byte writes
            m = (zp + zn)[0]                             # cumulative load
            mass.append(m)
            # The load only grows, so the raw array plots position, not
            # behaviour. The shape of the blackboard — the load divided by
            # its own total at that byte — is comparable across positions,
            # and its effective width says how many anchors are carrying it.
            p = m / m.sum(-1, keepdim=True).clamp_min(1e-12)
            shapes.append(p)
            used.append(torch.exp(-(p * p.clamp_min(1e-12).log()).sum(-1)))
            a_c = qp[0] @ kp[0].T + qn[0] @ kn[0].T      # (n, n)
            att = a_c if att is None else att + a_c
        tri = torch.tril(torch.ones(n, n, device=att.device, dtype=att.dtype))
        att = att * tri
        att = att / att.sum(-1, keepdim=True).clamp_min(1e-12)

        L["read"] = torch.stack(reads).float().cpu().numpy()      # (C, n, K)
        L["write"] = torch.stack(writes).float().cpu().numpy()    # (C, n, K)
        L["mass"] = torch.stack(mass).float().cpu().numpy()
        L["massn"] = torch.stack(shapes).float().cpu().numpy()    # (C, n, K)
        L["used"] = torch.stack(used).float().cpu().numpy()       # (C, n)
        L["den"] = torch.stack(dens).float().cpu().numpy()        # (C, n)
        L["attn"] = att.float().cpu().numpy()                     # (n, n)

        a = blk.attn(h)
        L["attn_norm"] = a[0].norm(dim=-1).float().cpu().numpy()
        x = x + a

        h2 = blk.n2(x)
        bank = blk.bank
        w = bank.addr.signed(h2)                                  # (1, n, E)
        trunk = bank.t_out(F.gelu(bank.t_in(h2)))
        out = bank(h2)
        L["experts"] = w[0].float().cpu().numpy()                 # (n, E)
        L["gates"] = torch.sigmoid(bank.gates).float().cpu().numpy()
        L["bank_trunk"] = trunk[0].norm(dim=-1).float().cpu().numpy()
        L["bank_disp"] = (out - trunk)[0].norm(dim=-1).float().cpu().numpy()
        x = x + out

        if armed:
            B, nn_, _ = x.shape
            slots = adapter.proj(x).view(B, nn_, adapter.n_slots,
                                         adapter.spec.D)
            feats = adapter.addr.m_hat(slots).reshape(B, nn_, -1)
            g = torch.sigmoid(adapter.gate)
            patch = g * adapter.consume(feats)
            L["arm_patch"] = patch[0].norm(dim=-1).float().cpu().numpy()
            L["arm_gate"] = float(g)
            # the arm's own signed per-anchor weights, written out here
            # because the packaged arm runtime exposes only m_hat:
            #     w_k = sinh(u_k) / sum_j cosh(u_j),  u = (x_hat . A_k)/tau
            A = F.normalize(adapter.addr.codebook, dim=-1)
            u = (F.normalize(slots, dim=-1) @ A.transpose(-1, -2)) \
                / adapter.addr.tau
            mu = u.abs().amax(dim=-1, keepdim=True)
            ep, en = torch.exp(u - mu), torch.exp(-u - mu)
            aw = (ep - en) / (ep + en).sum(dim=-1, keepdim=True)
            L["arm_read"] = aw.mean(dim=2)[0].float().cpu().numpy()  # (n, K)
            x = x + patch
        L["resid_out"] = x[0].norm(dim=-1).float().cpu().numpy()
        rec["layers"].append(L)

    h = model.nf(x)
    rec["head_read"] = model.head.addr.signed(
        model.head.proj(h))[0].float().cpu().numpy()              # (n, Kh)
    logits = model.head(h)[0].float()
    p = logits.softmax(-1)
    top = p.topk(8, dim=-1)
    rec["top_ids"] = top.indices.cpu().numpy().astype(np.int16)
    rec["top_p"] = top.values.cpu().numpy()
    rec["entropy"] = (-(p * p.clamp_min(1e-12).log()).sum(-1)
                      ).cpu().numpy() / np.log(2.0)
    nxt = ids[0, 1:].cpu().numpy()
    rec["p_actual"] = np.concatenate(
        [p[np.arange(n - 1), nxt].cpu().numpy(), [0.0]])
    return rec


@torch.no_grad()
def codebook_health(model):
    """Per layer, per constellation: what the frame itself looks like."""
    rows = []
    for li, wrapped in enumerate(model.blocks):
        blk = getattr(wrapped, "block", wrapped)
        for ci, (addr, _, _) in enumerate(blk.attn._units()):
            hh = addr.health(None)
            rows.append({"layer": li, "const": ci,
                         "drift_mean": round(hh["drift_mean"], 5),
                         "drift_max": round(hh["drift_max"], 5),
                         "erank": round(hh["codebook_erank"], 3),
                         "max_abs_cos": round(hh["anchor_max_abs_cos"], 4),
                         "merge_pairs": hh["anchor_merge_pairs"]})
    return rows


# ------------------------------------------------------------------ write
def emit(rec, root, cfg):
    d = os.path.join(root, cfg)
    os.makedirs(d, exist_ok=True)
    n = rec["n"]
    C, K = rec["layers"][0]["read"].shape[0], rec["layers"][0]["read"].shape[2]
    nl = len(rec["layers"])

    read = np.stack([L["read"] for L in rec["layers"]])      # (Lr, C, n, K)
    write = np.stack([L["write"] for L in rec["layers"]])
    mass = np.stack([L["mass"] for L in rec["layers"]])
    massn = np.stack([L["massn"] for L in rec["layers"]])
    attn = np.stack([L["attn"] for L in rec["layers"]])      # (Lr, n, n)
    qr, mean_r, sc_r, cl_r = q8_dev(read)
    qw, mean_w, sc_w, cl_w = q8_dev(write)
    qmn, mean_mn, sc_mn, cl_mn = q8_dev(massn)
    qm, sm = q8(mass, False)          # the raw cumulative load: dataset only
    qa = np.zeros_like(attn, dtype=np.uint8)
    rowmax = attn.max(axis=-1, keepdims=True)
    np.divide(attn, np.clip(rowmax, 1e-12, None), out=attn)
    np.clip(np.round(attn * 255.0), 0, 255, out=attn)
    qa = attn.astype(np.uint8)
    hr = rec["head_read"][None, None]                        # (1, 1, n, Kh)
    qh, mean_h, sc_h, cl_h = q8_dev(hr)

    sizes = {"read": wbin(os.path.join(d, "read.u8"), qr),
             "write": wbin(os.path.join(d, "write.u8"), qw),
             "mass": wbin(os.path.join(d, "mass.u8"), qm),
             "massn": wbin(os.path.join(d, "massn.u8"), qmn),
             "attn": wbin(os.path.join(d, "attn.u8"), qa),
             "head": wbin(os.path.join(d, "head.u8"), qh)}
    arm_shape = arm_mean = arm_scale = None
    if "arm_read" in rec["layers"][0]:
        armr = np.stack([L["arm_read"] for L in rec["layers"]])   # (Lr, n, Ka)
        qar, m_a, s_a, _ = q8_dev(armr[:, None])                  # (L,1,n,Ka)
        sizes["arm"] = wbin(os.path.join(d, "arm.u8"), qar)
        arm_shape = list(armr.shape)
        arm_mean, arm_scale = m_a[:, 0].tolist(), s_a[:, 0].tolist()

    per_layer = []
    for L in rec["layers"]:
        per_layer.append({
            "resid_in": [round(float(v), 3) for v in L["resid_in"]],
            "resid_out": [round(float(v), 3) for v in L["resid_out"]],
            "attn_norm": [round(float(v), 3) for v in L["attn_norm"]],
            "bank_trunk": [round(float(v), 3) for v in L["bank_trunk"]],
            "bank_disp": [round(float(v), 4) for v in L["bank_disp"]],
            "den": [[round(float(v), 4) for v in c] for c in L["den"]],
            "used": [[round(float(v), 2) for v in c] for c in L["used"]],
            "experts": [[round(float(v), 4) for v in row] for row in L["experts"]],
            "gates": [round(float(v), 4) for v in L["gates"]],
            "arm_patch": ([round(float(v), 4) for v in L["arm_patch"]]
                          if "arm_patch" in L else None),
            "arm_gate": L.get("arm_gate"),
        })
    summary = {
        "n": n, "layers": nl, "consts": C, "anchors": K,
        "head_atoms": int(rec["head_read"].shape[1]),
        # The anchor arrays are stored as MEAN + DEVIATION (see q8_dev):
        #   value = mean[l][c][k] + (u8 - 128)/127 * scale[l][c]
        # `mass` alone keeps the old absolute form, scale under "mass".
        "form": "mean+deviation, uint8, one scale per (block, constellation), the scale being the 99.5th percentile of |deviation| so the first two bytes of a sequence do not crush the rest; values above it clip",
        "clipped": {"read": round(cl_r, 5), "write": round(cl_w, 5),
                    "massn": round(cl_mn, 5), "head": round(cl_h, 5)},
        "mean": {"read": mean_r.tolist(), "write": mean_w.tolist(),
                 "massn": mean_mn.tolist(), "head": mean_h[0, 0].tolist(),
                 "arm": arm_mean},
        "scales": {"read": sc_r.tolist(), "write": sc_w.tolist(),
                   "massn": sc_mn.tolist(), "head": float(sc_h[0, 0]),
                   "arm": arm_scale, "mass": sm},
        "shapes": {"read": [nl, C, n, K], "write": [nl, C, n, K],
                   "mass": [nl, C, n, K], "massn": [nl, C, n, K],
                   "attn": [nl, n, n], "arm": arm_shape,
                   "head": [n, int(rec["head_read"].shape[1])]},
        "bytes_": sizes,
        "embed_norm": [round(float(v), 3) for v in rec["embed_norm"]],
        "entropy": [round(float(v), 4) for v in rec["entropy"]],
        "p_actual": [round(float(v), 5) for v in rec["p_actual"]],
        "top_ids": rec["top_ids"].tolist(),
        "top_p": [[round(float(v), 5) for v in row] for row in rec["top_p"]],
        "per_layer": per_layer,
    }
    with open(os.path.join(d, "summary.json"), "w", encoding="utf-8",
              newline="\n") as f:
        json.dump(summary, f, separators=(",", ":"))
    return sizes


def main():
    out = sys.argv[sys.argv.index("--out") + 1] if "--out" in sys.argv else OUT
    global MAXB
    if "--max-bytes" in sys.argv:
        MAXB = int(sys.argv[sys.argv.index("--max-bytes") + 1])
    sys.path.insert(0, REPO)
    from transformers import AutoModelForCausalLM
    m = AutoModelForCausalLM.from_pretrained(REPO, trust_remote_code=True)
    m = m.to(DEV).eval()
    print(f"[capture] {sum(p.numel() for p in m.parameters())/1e6:.1f}M on {DEV}")
    os.makedirs(out, exist_ok=True)
    card = m.arm_card(ARM)
    manifest = {"model": "AbstractPhil/mini-beatrix-2.5s",
                "core": "mini-beatrix-2s @ step 61,422 (237.1M, unchanged)",
                "arm": {"id": ARM, "title": card["title"],
                        "cell": card["cell"], "score": card["score"],
                        "status": card["status"],
                        "params": 8565780, "sites": 20},
                "precision": "fp32, greedy", "device": DEV,
                "captures": []}

    for spec in PROMPTS:
        root = os.path.join(out, spec["id"])
        os.makedirs(root, exist_ok=True)

        m.mount_arm(ARM)
        reply_arm = m.say(spec["text"], max_new=spec["max_new"])
        frame = m.default_frame()
        ids = m.render(spec["text"], frame=frame)
        seq = torch.cat([ids, torch.tensor(
            [list(reply_arm.encode("utf-8"))], dtype=torch.long,
            device=ids.device)], dim=1)[:, :MAXB]
        n_prompt = min(int(ids.shape[1]), int(seq.shape[1]))
        rec_arm = trace(m.model, seq)
        s_arm = emit(rec_arm, root, "arm")
        m.detach_arm(verify=True)

        reply_core = m.say(spec["text"], frame=frame, max_new=spec["max_new"])
        rec_core = trace(m.model, seq)
        s_core = emit(rec_core, root, "core")

        by = seq[0].cpu().numpy().tolist()
        manifest["captures"].append({
            "id": spec["id"], "title": spec["title"], "why": spec["why"],
            "prompt": spec["text"], "frame": frame, "gold": spec.get("gold"),
            "n": len(by), "n_prompt": n_prompt, "bytes": by,
            "reply_arm": reply_arm, "reply_core": reply_core,
            "sizes": {"arm": s_arm, "core": s_core}})
        print(f"[capture] {spec['id']}: n={len(by)} prompt={n_prompt}")
        print(f"           arm  -> {reply_arm[:90]!r}")
        print(f"           core -> {reply_core[:90]!r}")

    manifest["codebooks"] = codebook_health(m.model)
    with open(os.path.join(out, "manifest.json"), "w", encoding="utf-8",
              newline="\n") as f:
        json.dump(manifest, f, ensure_ascii=False, indent=1)
    tot = sum(os.path.getsize(os.path.join(dp, f))
              for dp, _, fs in os.walk(out) for f in fs)
    print(f"[capture] written to {out} ({tot/1e6:.1f} MB)")


if __name__ == "__main__":
    main()