Skip to content

npu: load a converted MTP head and run it (--head) -- the oracle on real weights - #789

Merged
bong-water-water-bong merged 2 commits into
mainfrom
npu/mtp-head-oracle
Nov 1, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
npu/mtp-head-oracle

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Follow-up to #784 (merged as c86138d4): the reference now loads a converted head and runs it, which is what makes
it the oracle on real weights rather than only on synthetic ones. (The branch for #784 was deleted on merge, so this is
a fresh PR rather than another commit on it.)

~/models/npu/bonsai2-27b-mtp-head/q4_k/ holds the source's own cells, so they are decoded with
decode_mode0_tile() — no requantisation anywhere — and assembled into the eight matrices and seven norms:

$ python3 tools/mtp_head_ref.py --head ~/models/npu/bonsai2-27b-mtp-head/q4_k
[1] shapes: 8/8 matrices match the descriptor
[2] loaded 424.7 M weights in float32 (1.58 GiB) + 7 norm vectors; finite=True
[3] one step on real weights: hidden rms=1.7817 finite=True deterministic=True
[4] second step with the kv cache: hidden rms=1.9020 finite=True  (cache (4, 1, 256))
[5] per-tensor |w| mean: fc=0.0083, q=0.0115, o=0.0149, gate=0.0099, down=0.0095

Checked separately on the same artifact: 15/15 tensors byte-identical to the source container
(qwen38-flm-mtp/model.mtp.q4nx), so the q4_k form is a faithful copy and the oracle above is running on the source's
own weights. Head step: 50 ms in numpy on the CPU (that number sets the speculation break-even: at k=4 the head
costs 4x50 ms against two 0.44 s base passes, so a mean accept length above ~1.45 already wins).

The pb16i images as delivered are the lossy twin, by ~100x — the actionable part for the converter:

tensor manifest rel-L1 exact host-group-sum plan, same cells
fc 0.1815 9.8e-04
down 0.1267 1.5e-03
gate / up 0.1132 / 0.1129 6.8e-04 / 8.0e-04
k / v 0.1296 / 0.1193 1.4e-03 / 1.5e-03
o 0.1313 9.1e-04
q 0.1164 2.2e-03

The source blocks are w = q4*S + M with an additive per-(32-K group, column) min; a bias-free tile cannot hold it,
so dropping it costs 11-18 % of the weight L1. It is recoverable exactly on the host from eight activation group
sums per GEMV (the decomposition in this file), which lands at the int16-mantissa limit instead. So the fix is to carry
M_g(n) + 8*S_g(n) as a side table per image and keep the source codes — not a better requantiser.

No device, no GPU, nothing in the decode path changes.

@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 99d531f)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

784 - Partially compliant

Compliant requirements:

  • Create a new file tools/mtp_head_ref.py with the CPU reference implementation
  • Implement loading of converted head weights in q4_k format
  • Implement the head step function with proper tensor shapes and operations
  • Add self-test functionality to verify correctness
  • Add functionality to run the head on real weights
  • Ensure the implementation matches the shipped container's geometry and tensor shapes
  • Verify that the conversion maintains bit-exactness with the source container

Non-compliant requirements:

  • None

Requires further human verification:

  • Verification that the head runs correctly on actual hardware
  • Confirmation that the performance metrics (50ms head step) match expectations on the target NPU
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Memory Access Issue

The code reads raw binary data from a file and directly accesses it without proper bounds checking for the entire file. If the file is corrupted or truncated, it could lead to memory access violations or undefined behavior when trying to read beyond the file boundaries. The code should verify that the file size matches the expected structure before attempting to read.

blob = open(os.path.join(head_dir, "model.q4nx"), "rb").read()
hlen = struct.unpack("<Q", blob[:8])[0]
tensors = {t["name"]: t for t in cfg["tensors"]}
W = {}
name_of = {
    "model.mtp.fc.weight": "fc",
    "model.mtp.layers.0.self_attn.q_proj.weight": "q",
    "model.mtp.layers.0.self_attn.k_proj.weight": "k",
    "model.mtp.layers.0.self_attn.v_proj.weight": "v",
    "model.mtp.layers.0.self_attn.o_proj.weight": "o",
    "model.mtp.layers.0.mlp.gate_proj.weight": "gate",
    "model.mtp.layers.0.mlp.up_proj.weight": "up",
    "model.mtp.layers.0.mlp.down_proj.weight": "down",
}
norm_of = {
    "model.mtp.pre_fc_norm_embedding.weight": "pre_fc_emb",
    "model.mtp.pre_fc_norm_hidden.weight": "pre_fc_hid",
    "model.mtp.layers.0.input_layernorm.weight": "ln_in",
    "model.mtp.layers.0.post_attention_layernorm.weight": "ln_post",
    "model.mtp.norm.weight": "norm",
    "model.mtp.layers.0.self_attn.q_norm.weight": "q_norm",
    "model.mtp.layers.0.self_attn.k_norm.weight": "k_norm",
}
off = 8 + hlen
for t in cfg["tensors"]:
    n = t["bytes"]
    raw = blob[off:off + n]
    if len(raw) != n:
        raise SystemExit(f"{head_dir}: short read for {t['name']}")
    off += n
Possible Performance Bottleneck

The nested loops for decoding tiles (lines 245-248) iterate over all row blocks and column blocks, which could be a performance bottleneck for large tensors. While this approach works for correctness, it may not be optimal for performance-critical paths. Consider vectorizing or using more efficient memory access patterns for better performance on the CPU.

for rb in range(grid[0]):
    for cb in range(grid[1]):
        m[rb * 32:(rb + 1) * 32, cb * 256:(cb + 1) * 256] = \
            decode_mode0_tile(cells[rb, cb].tobytes())

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 767f3d8

…eal weights

The converter landed ~/models/npu/bonsai2-27b-mtp-head/q4_k, which keeps the source's own cells, so the head
is decoded cell by cell with decode_mode0_tile() and no requantisation is involved.  Verified on the real
artifact: 15/15 tensors byte-identical to the source container, 8/8 shapes match the descriptor, 424.7 M
weights (1.58 GiB float32), one step and a second step against the KV cache both finite and deterministic,
head step 50 ms in numpy on the CPU.

The delivered pb16i images are the lossy twin: on the same cells they lose 0.113-0.182 rel-L1 per tensor,
because the source blocks carry an ADDITIVE per-group min that a bias-free tile cannot hold, while the host
group-sum decomposition of this reference lands at 6.8e-4-2.2e-3 (tensor 0 of each, two probe vectors).
Carrying that per-(group, column) table is the converter fix; requantising is not.
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 3af6f2a

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

First review, and this one I could run end to end rather than read.

Ran the new path at 3af6f2a5 on the real converted head:

$ python3 tools/mtp_head_ref.py --head ~/models/npu/bonsai2-27b-mtp-head/q4_k
[1] shapes: 8/8 matrices match the descriptor
[2] loaded 424.7 M weights in float32 (1.58 GiB) + 7 norm vectors; finite=True
[3] one step on real weights: hidden rms=1.7817 finite=True deterministic=True
[4] second step with the kv cache: hidden rms=1.9020 finite=True  (cache (4, 1, 256))
[5] per-tensor |w| mean: fc=0.0083, q=0.0115, o=0.0149, gate=0.0099, down=0.0095
real 0m1.5s

Every line of the body reproduces, including the determinism claim and the cache shape, and the load is 1.58 GiB of float32
for 424.7 M weights — i.e. it really is the whole head decoded from the container's own mode-0 cells
(decode_mode0_tile()), with no requantisation anywhere in the path.

The break-even arithmetic in the body is right, and it is the number that matters for #785's loop: 4 drafts × 50 ms of
head + 2 × 440 ms of base passes = 1080 ms per iteration, and 1080 ms / (a+1) tokens = 440 ms/token gives
a ≈ 1.45 mean accepted drafts. That is a low bar for a real head on real prompts — which is exactly why the loop is
worth wiring — and it is stated with its inputs rather than as a bare claim.

The pb16i finding is the actionable part and it is consistent with everything I have measured separately: the
delivered images are off by 11-18 % rel-L1 because the source blocks carry an additive per-(32-K group, column) min
(w = q4*S + M) that a bias-free tile cannot hold; the exact host-group-sum plan lands at 6.8e-4 – 2.2e-3 instead. That
matches the manifest I checked on disk (rel_l1_residual 0.1129-0.1815 over the eight tensors) and #784's selftest
(exact plan … rel max err 5.350e-04). The conclusion — carry M_g(n) + 8*S_g(n) as a side table and keep the source
codes rather than build a better requantiser — is the right one, and it is a converter change, not a kernel one.

CodeQL and build are green on this head; nothing here touches the device or the hot path. tprs-ready applied.

@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 1, 2026
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 99d531f

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 99d531f5, the head its waiter rebuilt after #778 merged; build green, and tools/mtp_head_ref.py is byte-identical to
the head I reviewed (git diff --stat 3af6f2a5 <head> -- tools/mtp_head_ref.py → empty), so the run stands:

$ python3 tools/mtp_head_ref.py --head ~/models/npu/bonsai2-27b-mtp-head/q4_k
[1] shapes: 8/8 matrices match the descriptor
[2] loaded 424.7 M weights in float32 (1.58 GiB) + 7 norm vectors; finite=True
[3] one step on real weights: hidden rms=1.7817 finite=True deterministic=True
[4] second step with the kv cache: hidden rms=1.9020 finite=True  (cache (4, 1, 256))
[5] per-tensor |w| mean: fc=0.0083, q=0.0115, o=0.0149, gate=0.0099, down=0.0095

The two things that make this worth merging: it is the oracle on real weights (the container's own mode-0 cells, no
requantisation in the path), and its break-even arithmetic is checkable — 4×50 ms of head + 2×440 ms of base passes =
1080 ms, so 1080/(a+1) = 440 → a ≈ 1.45 mean accepted drafts, which is the bar #785's loop has to clear. The pb16i
table agrees with what I measured independently (manifest rel_l1 0.1129-0.1815 on disk; #784's exact-plan selftest
5.35e-4), and its conclusion — carry M_g(n) + 8*S_g(n) as a side table and keep the source codes — is a converter change,
not a kernel one.

tprs-ready stays.

@bong-water-water-bong
bong-water-water-bong merged commit f5f19ad into main Nov 1, 2026
8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the npu/mtp-head-oracle branch November 1, 2026 22:25
bong-water-water-bong pushed a commit that referenced this pull request Nov 1, 2026
…act, not 11-18 % lossy)

The source head's cells are w = q4*S + M with an ADDITIVE per-(32-K group, column) min.  A pb16i tile has no
bias, so the plain conversion drops M and the images report 0.113-0.182 rel-L1 per tensor.  The min is
constant per (group, column), so it does not have to be dropped: keep the source codes (q4-8, exactly
representable in int4), carry the per-column exponent and int16 magnitudes, and ship M + 8*S as a host table
that the GEMV recovers from eight activation group sums.

Emitted for all eight head matrices into ~/models/npu/bonsai2-27b-mtp-head/pb16i-exact/ in the sealed tile
order (layout_w4.py pack-pb16i: [c][ki][nt][r], 4,608 B per tile), with .add (float32 [K/32][N]), .eref
(int16 [N]) and a manifest.  Self-checks on the real artifact: image round-trip 0 mismatches on every tensor;
full-matrix GEMV against the exact float weights rel-L1 1.6e-5 .. 1.6e-4 (against 0.113-0.182 for the lossy
form); and the whole head step, source cells vs emitted images, agrees with hidden cosine 1.00000000 and
rel-L1 1.8e-4.

Stacks on the open #789, which adds mtp_head_ref.load_q4k_head() -- this tool uses it to read the q4_k cells
rather than duplicating the container logic.
bong-water-water-bong added a commit that referenced this pull request Nov 2, 2026
…act, not 11-18 % lossy) (#791)

The source head's cells are w = q4*S + M with an ADDITIVE per-(32-K group, column) min.  A pb16i tile has no
bias, so the plain conversion drops M and the images report 0.113-0.182 rel-L1 per tensor.  The min is
constant per (group, column), so it does not have to be dropped: keep the source codes (q4-8, exactly
representable in int4), carry the per-column exponent and int16 magnitudes, and ship M + 8*S as a host table
that the GEMV recovers from eight activation group sums.

Emitted for all eight head matrices into ~/models/npu/bonsai2-27b-mtp-head/pb16i-exact/ in the sealed tile
order (layout_w4.py pack-pb16i: [c][ki][nt][r], 4,608 B per tile), with .add (float32 [K/32][N]), .eref
(int16 [N]) and a manifest.  Self-checks on the real artifact: image round-trip 0 mismatches on every tensor;
full-matrix GEMV against the exact float weights rel-L1 1.6e-5 .. 1.6e-4 (against 0.113-0.182 for the lossy
form); and the whole head step, source cells vs emitted images, agrees with hidden cosine 1.00000000 and
rel-L1 1.8e-4.

Stacks on the open #789, which adds mtp_head_ref.load_q4k_head() -- this tool uses it to read the q4_k cells
rather than duplicating the container logic.

Co-authored-by: bong-water-water-bong <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 3/5 tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant