Skip to content

mtp: block the head's matvec over n so a code byte shares its cache line (2.7x on the host head, bit-identical) - #968

Merged
bong-water-water-bong merged 8 commits into
mainfrom
npu/mtp-head-matvec
Nov 4, 2026
Merged

bong-water-water-bong merged 8 commits into
mainfrom
npu/mtp-head-matvec

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Root cause

Matrix::matvec (npu/mtp/mtp_head.cpp) walked the code image one column at a time. The image is laid out
[k][n], so one column's 5120 codes are read with a stride of N bytes — one 64-byte cache line per 1-byte
code
. One MTP head step is those eight matvecs (424 M MACs, fc q k v o gate up down), i.e. ~27 GB of traffic
per step, and it measured 1-7 GF/s per matrix. The live draft loop runs 6 + accepted head steps per
iteration (both commit_rows calls plus every chained draft), so this was the loop's largest single cost on the
host — bigger than the drafter's logits calls, which is not what SERVE-RECIPE.md assumed.

Fix

Block n (NB=64) instead of walking single columns: for a fixed k a block's codes are 64 contiguous bytes, so
every line fetched is fully used. Each column keeps its exact accumulation order (g ascending, k ascending,
then the additive-min pass over g), so not one float moves.

  • npu/mtp/mtp_head.cpp: the blocked loop (with the reason written next to it).
  • tests/mtp_draft_test.cpp [10]: the unblocked form is kept in the test as the reference and every column
    is compared with memcmp — 692 columns over 5 shapes, including N = 200 = 3*64 + 8 so a wrong block tail bound
    fails it. Deleting the defect's statement is the only way to pass it.
  • tools/mtp_head_bench.cpp (new, +1 CMake target, host only, no device): loads the real head, prints per-matrix
    and per-step milliseconds, and hashes every output hidden. That is how the numbers below are stated, and how the
    next change to the head's maths gets a before/after instead of an argument.

Measured (this box, interleaved A/B, three alternating reps, same window, real weights)

  matvec sum, the eight matrices   135-155 ms  ->  50-68 ms
  head step, no lm head (median)   152-162 ms  ->  57-71 ms
  output hash                      e817b44a834a7eef == e817b44a834a7eef

Per matrix, one rep (--steps 5 --matvec 15): fc 14.4→11.5, q 27.2→8.6, k 9.2→5.6, v 8.1→9.5,
o 11.2→6.2, gate 24.8→9.0, up 24.1→8.7, down 36.4→9.2 ms. Absolute milliseconds move with box load
(other lanes' builds); the ratio and the hash are what the claim rests on.

ctest -R mtp_draft 1/1, tools/copyright.py --check rc 0, ninja mtp_head_bench mtp_draft_test mtp_acceptance
rc 0.

What this does and does not change

  • No number can move: the head's output is bit-identical, so every acceptance figure this lane has published
    (44/80, chain 3.20, per-depth 90/65/35/30 on prompt 0) stands. The device re-measurement of the live
    loop's wall clock lands separately (one npu-hold ticket, prompt 0, the same numbers expected).
  • The draft route was measured at 0.35-0.70x of plain decode (§TMTPLOOP-STATE 2026-11-02). Removing ~0.7-0.9 s
    from a ~4 s iteration is the first lever that moves that ratio in the route's favour; it is not claimed until the
    ticket reports it.

Refs #805 (P6: acceptance, hit rate, passes/token for this drafter). No device number is claimed in this PR.

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 07d9a80)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

805 - Partially compliant

Compliant requirements:

  • The PR implements the blocked matvec computation for the MTP head, which improves cache locality and performance
  • The PR includes a benchmark tool (mtp_head_bench) to measure and verify the performance of the head computation
  • The PR includes tests to ensure bit-identical results between the blocked and unblocked versions of the matvec computation

Non-compliant requirements:

  • The PR does not implement the full tau-gated chain logic, verify rows, spare rows, or deferred GDN commits as described in the ticket
  • The PR does not include the full draft loop implementation with the specified acceptance criteria and lane behavior

Requires further human verification:

  • The full draft loop implementation and acceptance criteria need to be verified against the hardware performance metrics
  • The lane behavior (pi-bonsai then pi-hexagon) needs to be confirmed in the actual hardware setup
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Cache Access Pattern

The change introduces a blocked access pattern for the n dimension in Matrix::matvec, which improves cache locality. However, the performance improvement is highly dependent on the hardware's cache characteristics and memory bandwidth. The PR should include measured performance improvements on the target hardware (AMD Strix Halo's XDNA 2 NPU) to validate the claimed 2.7x improvement.

void Matrix::matvec(const float* a, float* y) const {
    const int G = K / kG;
    // Codes are laid out [k][n], so ONE row of a's products walks n with a stride of 1 byte and the columns a
    // thread touches are scattered N bytes apart.  Doing one n at a time (the first form of this function) is
    // therefore a 64-byte cache line per 1-byte code: 424 M codes ~ 27 GB of traffic per head step, measured
    // 331 ms for the eight matrices of a step (0.7-4.8 GF/s, TMTPLOOP-STATE 2026-11-04 02:4x).
    //
    // Blocking n fixes the access pattern without touching the arithmetic: for a block of NB columns the k loop
    // reads NB CONTIGUOUS code bytes per row, and each column's accumulation keeps its exact order (g ascending,
    // k ascending, then the additive-min pass), so the result is bit-identical to the unblocked form -- asserted
    // in tests/mtp_draft_test.cpp [10] against the old code kept there as the reference.
    constexpr int NB = 64;
    const int nblocks = (N + NB - 1) / NB;
#pragma omp parallel for schedule(static)
    for (int nb = 0; nb < nblocks; nb++) {
        const int n0 = nb * NB, w = std::min(N - n0, NB);
        double acc[NB], P[NB], ex[NB];
        for (int i = 0; i < w; i++) {
            acc[i] = 0.0;
            ex[i] = std::ldexp(1.0, (int)eref[(size_t)n0 + i]);
        }
        for (int g = 0; g < G; g++) {
            for (int i = 0; i < w; i++) P[i] = 0.0;
            for (int k = 0; k < kG; k++) {
                const double av = (double)a[g * kG + k];
                const int8_t* ck = &codes[(size_t)(g * kG + k) * N + n0];
                for (int i = 0; i < w; i++) P[i] += av * (double)ck[i];
            }
            const int16_t* mg = &ms[(size_t)g * N + n0];
            for (int i = 0; i < w; i++) acc[i] += P[i] * ((double)mg[i] * ex[i]);
        }
        // the source's additive min, second pass over g exactly as before
        for (int g = 0; g < G; g++) {
            double s = 0.0;
            for (int k = 0; k < kG; k++) s += a[g * kG + k];
            const float* ad = &add[(size_t)g * N + n0];
            for (int i = 0; i < w; i++) acc[i] += s * (double)ad[i];
        }
        for (int i = 0; i < w; i++) y[n0 + i] = (float)acc[i];
    }
}
Bit-Identical Verification

The test verifies bit-identical results between the blocked and unblocked forms of matvec. However, the test only covers a limited set of matrix shapes and does not cover the full range of possible inputs that could be encountered in the draft loop. The test should be expanded to cover more edge cases and ensure that the blocked version maintains bit-identical results across all possible inputs.

// [10] the head's matvec is n-blocked (npu/mtp/mtp_head.cpp): one column at a time walks the [k][n] code image
// with a 64-byte cache line per 1-byte code, which measured 135-331 ms for the eight matrices of one head step
// depending on box load (0.7-7 GF/s; tools/mtp_head_bench.cpp).  Blocking n fixes the access pattern and must NOT move a single float: the accumulation order
// per column (g ascending, k ascending, then the additive-min pass) is identical, so this is a bit-identity
// check, not a tolerance check.  The unblocked form is kept here as the reference, so a future rewrite has to
// delete the statement of the defect to pass.
{
    auto matvec_unblocked = [](const onebit::npu::mtp::Matrix& m, const float* a, float* y) {
        const int G = m.K / onebit::npu::mtp::kG;
        for (int n = 0; n < m.N; n++) {
            double acc_n = 0.0;
            for (int g = 0; g < G; g++) {
                const int8_t* cg = &m.codes[(size_t)(g * onebit::npu::mtp::kG) * m.N + n];
                double P = 0.0;
                for (int k = 0; k < onebit::npu::mtp::kG; k++)
                    P += (double)a[g * onebit::npu::mtp::kG + k] * (double)cg[(size_t)k * m.N];
                acc_n += P * ((double)m.ms[(size_t)g * m.N + n] * std::ldexp(1.0, (int)m.eref[(size_t)n]));
            }
            for (int g = 0; g < G; g++) {
                double s = 0.0;
                for (int k = 0; k < onebit::npu::mtp::kG; k++) s += a[g * onebit::npu::mtp::kG + k];
                acc_n += s * (double)m.add[(size_t)g * m.N + n];
            }
            y[n] = (float)acc_n;
        }
    };
    // N covers the block tail (200 = 3 x 64 + 8), an exact block (64), one column, and a wide matrix; a
    // wrong tail bound or an off-by-one in the block loop shows up as a disagreeing column.
    const int shapes[][2] = {{64, 200}, {128, 64}, {32, 1}, {256, 127}, {96, 300}};
    int bad_cols = 0, cols = 0;
    for (const auto& sh : shapes) {
        const int K = sh[0], N = sh[1], G = K / onebit::npu::mtp::kG;
        onebit::npu::mtp::Matrix m;
        m.K = K;
        m.N = N;
        m.codes.assign((size_t)K * N, 0);
        m.ms.assign((size_t)G * N, 0);
        m.eref.resize((size_t)N);
        m.add.resize((size_t)G * N);
        uint32_t st = 12345u + (uint32_t)(K * 131 + N);
        for (auto& c : m.codes) { st = st * 1664525u + 1013904223u; c = (int8_t)((int)((st >> 16) % 16) - 8); }
        for (auto& v : m.ms) { st = st * 1664525u + 1013904223u; v = (int16_t)(1000 + (int)((st >> 16) % 30000)); }
        for (auto& e : m.eref) { st = st * 1664525u + 1013904223u; e = (int16_t)((int)((st >> 16) % 9) - 4); }
        for (auto& v : m.add) { st = st * 1664525u + 1013904223u; v = (float)((int)((st >> 16) % 2001) - 1000) * 0.5f; }
        std::vector<float> a((size_t)K), got((size_t)N), want((size_t)N);
        for (auto& x : a) { st = st * 1664525u + 1013904223u; x = (float)((int)((st >> 16) % 2001) - 1000) * 0.001f; }
        matvec_unblocked(m, a.data(), want.data());
        m.matvec(a.data(), got.data());
        for (int n = 0; n < N; n++) {
            cols++;
            if (std::memcmp(&got[(size_t)n], &want[(size_t)n], sizeof(float)) != 0) bad_cols++;
        }
    }
    check(bad_cols == 0, "matvec: the blocked form is BIT-identical to the unblocked form on every column");
    std::printf("INFO matvec: %d columns over 5 shapes, %d differ (K x N incl. a 200 = 3x64+8 block tail)\n", cols,
                bad_cols);
}

@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 822b24b4c. Bit-identity confirmed end to end, and the speedup is larger than claimed here (the box is loaded, so treat the absolute numbers as soft and the direction as solid).

Built and ran both halves, at this head with gcc-16 / Release:

$ ./build/mtp_draft_test
PASS  matvec: the blocked form is BIT-identical to the unblocked form on every column
INFO matvec: 692 columns over 5 shapes, 0 differ (K x N incl. a 200 = 3x64+8 block tail)
rc 0

The block tail is covered (N = 200 = 3*64 + 8), which is the case a NB=64 blocking gets wrong if the last block is mishandled.

The end-to-end A/B, same bench binary, only npu/mtp/mtp_head.cpp swapped for origin/main's:

median ms/step (8 steps) min max output hash
main's unblocked matvec 2656.27 1180.14 3445.04 91688767b0eba370
this head, blocked 432.09 292.14 455.90 91688767b0eba370

6.15x median here against the 2.7x in the body — the same bytes out (FNV-1a over 8 x 5120 floats, identical across every run I did, including a third run of each that landed at 40.45 and 3490.77 ms) and the spread between my runs of the same build was large, so I would not quote any of these as a headline; the claim is conservative, and what matters is that the hash never moved.

Why the arithmetic is safe, read not just measured: for each column the accumulation order is unchanged — P over k ascending, acc over g ascending, then the additive-min pass over g — and ex[i] = ldexp(1.0, eref[...]) is hoisted but pure, so nothing is reassociated. The bounds are safe too: ck[i] with i < w = min(N - n0, NB) cannot pass N - 1, and nblocks rounds up so the tail is handled. ag_sum was dead in the old form and is gone.

tools/mtp_head_bench.cpp is a new file with the notice, and the --matvec / --steps flags make the A/B reproducible, which is what let me run this at all.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit b540bae

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Second commit at 721cf902 (rebased onto the main merge): the two costs SERVE-RECIPE.md had fitted are now measured by the tool that uses them.

One array lm_head call, measured (--probe-lm 10, prompt 0, one npu-hold ticket, 151 s, amdxdna errors 0):

lm head probe: 10 calls over vocab 248320, median 29.3 ms, min 28.2, max 30.4

So the drafter's four logits calls per iteration cost ~117 ms, not the ~1.8 s the 2026-11-02 12:44 entry fitted by subtracting base passes out of a draft-phase wall clock. That fit was the basis for "the per-draft logits call is the cost, P3 is the only lever" — it was wrong, and this PR is the correction: the cost was the host head's matvec (previous commit, 2.6x, bit-identical), which is where the drafter's time actually went.

Same ticket, end-to-end proof of the previous commit on the real model:

prompt text accepted chain per-depth stream / mismatches
0 TEXT IDENTICAL 44/80 3.20 90 / 65 / 35 / 30 % 72 rows, 0
3 TEXT IDENTICAL 50/64 4.12 87.5 / 75 / 75 / 75 % 72 rows, 0

Both are the counts this lane measured before the matvec change (2026-11-02 12:11/12:38) — bit-identical is not a claim about the bench hash only. Wall clock on those tickets: prompt 0 plain 0.588 s/tok vs draft 0.904 s/tok (0.65x), prompt 3 0.484 vs 0.771 (0.63x). The draft route is still slower than plain decode on these two prompts, so the serve switch stays off; what changed is the reason and the remaining lever.

Also added, and deliberately carries no number: --batchcheck now prints a verify batch's cost at M = 1, 2, k+1, max_batch_rows on the same stream. The loop's "two passes per iteration" is only true if an M-row batch costs one row; the kernels are sealed at M=16, so either the pad rows are idle (#805's leaf fill is the lever) or the work is per row. The ticket that would have measured it was refused by my device-flock guard and then removed when the array went into the owner's amdxdna maintenance window — it is instrumented, unmeasured, and will be run when the array is announced back. Until then the loop still has ~1.4 s/iteration unaccounted for between "two base passes + head steps + logits calls" and the measured iteration wall clock, and this mode is how that gets closed.

bong-water-water-bong added 2 commits November 4, 2026 02:47
…ine (2.7x on the host head, bit-identical)

The MTP head runs on the host (npu/mtp/mtp_head.cpp, the pb16i-exact form) and one head step is its eight
matvecs: 424 M MACs.  The code image is laid out [k][n], so the per-column loop read its 5120 codes with a
stride of N bytes -- one 64-byte cache line per 1-byte code, ~27 GB of traffic per head step -- and measured
1-7 GF/s per matrix.

Walk a block of NB=64 columns at once instead.  For a fixed k the block's codes are 64 contiguous bytes, so
each line fetched is fully used.  Each column keeps its exact accumulation order (g ascending, k ascending,
then the additive-min pass over g), so the result does not move: the bench's output hash is identical between
the two builds, and tests/mtp_draft_test.cpp [10] keeps the unblocked form as the reference and compares every
column bit for bit (692 columns over 5 shapes, including a 200 = 3*64+8 block tail).

Measured on this box, interleaved A/B (three alternating reps, same window, same weights, --steps 5
--matvec 15):

  matvec sum, the eight matrices   135-155 ms   ->   50-68 ms
  head step, no lm head (median)   152-162 ms   ->   57-71 ms
  output hash                      e817b44a834a7eef  ==  e817b44a834a7eef

Per matrix (one rep): fc 14.4->11.5, q 27.2->8.6, k 9.2->5.6, v 8.1->9.5, o 11.2->6.2, gate 24.8->9.0,
up 24.1->8.7, down 36.4->9.2 ms (absolute milliseconds move with box load; the ratio and the hash are what
the claim rests on).

tools/mtp_head_bench.cpp is new and is how the above is stated: it loads the real head, prints per-matrix and
per-step milliseconds, and hashes every output hidden, so the next change to the head's maths has a before/after
and a bit-exactness check instead of an argument.  The live loop runs 6 + accepted head steps per iteration
(both commit_rows calls and every chained draft), so this is ~0.7-0.9 s off a ~4 s iteration; the device
re-measurement of that lands separately.  No acceptance number can move, because the head's output is
bit-identical.

Refs #805 (P6's gate: acceptance, hit rate and passes/token for this drafter).
… call, and a verify batch's row scaling

SERVE-RECIPE and TMTPLOOP-STATE carried two numbers that were fits, not measurements: "~0.4 s per full-vocab
logits call" (from subtracting base passes out of a draft-phase wall clock, 2026-11-02 12:44) and "two passes
per iteration" (from counting the loop's calls).  Neither survives a direct measurement, and the draft route's
break-even is computed from both.

--probe-lm N times N real lm_head calls on the probe step's own hidden and prints median/min/max.  Measured on
this box, prompt 0, one npu-hold ticket (151 s, amdxdna errors 0):

  lm head probe: 10 calls over vocab 248320, median 29.3 ms, min 28.2, max 30.4

i.e. the drafter's four logits calls per iteration are ~117 ms, not ~1.8 s: the array's vocabulary projection is
NOT what makes the draft route slower, and the host head (tools/mtp_head_bench.cpp, 2.6x in the previous
commit) was the dominant term.

--batchcheck now also prints the verify batch's cost at M = 1, 2, k+1 and max_batch_rows on the same stream.
The loop's "two passes per iteration" is only true if an M-row batch costs one row; the kernels are sealed at
M=16, so either the pad rows are idle (batch harder, #805's leaf fill) or the work is per row (fix the batch).
Instrumented and not yet run -- the array went into the owner's amdxdna maintenance window before it could be,
so it carries no number here.  The same run also re-proves the previous commit end to end: prompt 0 gave
TEXT IDENTICAL, 44/80, chain 3.20, stream 72 rows, 0 mismatch, per-depth 90/65/35/30 and prompt 3 gave 50/64,
chain 4.12 -- the same counts as before the matvec change, which is what bit-identical means on the real model
at speed: plain 0.588 s/tok vs draft 0.904 s/tok (0.65x) on prompt 0, 0.484 vs 0.771 (0.63x) on prompt 3.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The unmeasured item in this PR is now measured, and it closes the cost model. One npu-hold ticket (HOLD=4, 127 s, exit 0, amdxdna errors 0), same stream as the argmax/hidden check in the same run:

M  1 rows: 16 batches,  643.99 ms/batch, 643.99 ms/row,  1.6 rows/s
M  2 rows:  8 batches,  911.61 ms/batch, 455.81 ms/row,  2.2 rows/s
M  5 rows:  3 batches, 1851.82 ms/batch, 370.36 ms/row,  2.7 rows/s
M 16 rows:  1 batches, 4130.82 ms/batch, 258.18 ms/row,  3.9 rows/s

So a verify batch is near-linear in rows, and the loop's passes/token = 2/(1+accept-len) (which counts a batch as one pass) understates it: prompt 3's measured 3.08 s iteration = 0.64 s step + 1.85 s for the M=5 batch + ~0.55 s host head steps + 0.12 s logits calls = 3.16 s. Every term is now measured, and the ~1.4 s/iteration that was unexplained at the previous comment was the batch.

Filed as #972 with the arithmetic and the break-even conclusion (no (k, tau) makes the route beat plain decode while a batch row costs 258-644 ms and plain decode costs 484-588 ms/token; the engine's batch path is the binding term, not the drafter). This PR is still the two changes it started as — the n-blocked matvec (2.6x, bit-identical) and the measurement modes that name each term — and it claims no device speedup for the route itself.

Also rebased onto main ebb29050 (#916 merged) — the conflict was tests/mtp_draft_test.cpp, where #916's rewritten [9] and this PR's [10] are adjacent; main's [9] is kept verbatim, [10] follows it, ctest -R mtp_draft 1/1, tools/copyright.py --check rc 0, mtp_acceptance rebuilt at the new head. Branch is at e229e0fc.

@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 e229e0fc4 (re-verdict; my READY was at 822b24b4c).

The certified code is untouched. The Matrix::matvec I verified bit-identical is the same bytes at both heads:

822b24b4c  matvec: a71c9a5cf61a646f
e229e0fc4  matvec: a71c9a5cf61a646f

so the A/B I ran (2656.27 → 432.09 ms/step, output hash 91688767b0eba370 identical both ways) and the mtp_draft_test arm (692 columns, 5 shapes, 0 differ, block tail N=200) carry to this head unchanged. The other changes that appear in the diff since my verdict — depth_verdict() in mtp_head.cpp, the reached_at/LiveDepths additions, the +98 in tests/mtp_draft_test.cpp — are #916 arriving through a main merge, not part of this PR.

The one new own commit is measurement tooling, and it is honest about itself. e229e0f adds --probe-lm N (+55 lines in tools/mtp_acceptance.cpp) to replace two numbers that were fits:

lm head probe: 10 calls over vocab 248320, median 29.3 ms, min 28.2, max 30.4

i.e. the drafter's four logits calls are ~117 ms an iteration, not the ~1.8 s the recipe carried, which is a useful correction to the draft route's break-even arithmetic — and it points at the same conclusion my A/B reached from the other side: the host head was the dominant term, not the vocabulary projection.

It also re-proves the previous commit end to end on the real model at speed — TEXT IDENTICAL, per-depth 90/65/35/30 and 50/64, chain 3.20/4.12, 0 mismatch, "the same counts as before the matvec change, which is what bit-identical means" — and it says plainly that the --batchcheck M-row row is instrumented and not yet run, so it carries no number. That is exactly the right way to land a probe: no row claimed that was not measured.

Not run by me: the new --probe-lm and the --batchcheck extension (both need an npu-hold ticket, a real base model and the sealed head ELFs; the lane's 151 s run had 0 amdxdma errors). Nothing here changes what I verified with the host bench, and tools/mtp_acceptance.cpp is not in the shipped binary.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit c13882b

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 1b90867

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 7bdb7d8

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit f0e3018

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 5b741c4

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 07d9a80

@bong-water-water-bong
bong-water-water-bong merged commit 1120bc0 into main Nov 4, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant