Skip to content

hrx: the 2..8-token kquant rows serve a wider batch in parts, so -ub 16 stops costing 10x (engine#3035) - #460

Merged
bong-water-water-bong merged 1 commit into
1bit/hrx-vulkan-patchedfrom
cl-856/3035-chunked-kquant-rows
Nov 21, 2026
Merged

bong-water-water-bong merged 1 commit into
1bit/hrx-vulkan-patchedfrom
cl-856/3035-chunked-kquant-rows

Conversation

@bong-water-water-bong

Copy link
Copy Markdown

Refs 1bit-MONSTER/engine#3035

A MUL_MAT with more than 8 tokens has no IQ1_S matcher: the reuse row stops at the kernel's own width (kMaxTokens = 8), and every wide IQ* matcher — iq1_s, the fused swiglu iq1_s, iq2_xxs, iq2_xs, iq1_m — requires 256..2048 tokens and a multiple of 256. Measured on Qwen3.8-27B-UD-IQ1_S at pin 47c95e15c (engine#3035, one gpu-hold ticket each, 0 faults):

UBATCH prefill what ran
8 47.3–50.2 tok/s the reuse row; 0.156 s per 8-token graph; no wide kernel compiled
16 4.77 tok/s mul_mat_swiglu_f32_f32_wmma + mul_mat_add_f32_f32_wmma at token_count=10,12,16; 3.35 s per 16-token graph — 21x the 8-token graph on the same device

The row's kernel does not have to be wider to serve a wider node: it can run twice. append_kquant_token_chunks() emits balanced token-dimension parts of the same dispatch, each with its own ggml.kquant_decode.token_count and its own slice of the token-major bindings, while weights stay whole. Two callers:

  • the plain 2..8 row (bindings 0 input, 2 addend-or-input, 3 output) — the projections;
  • the fused SwiGLU row (bindings 0 input, 3 packed gate/up output, both weights whole) — the FFN, which is the bulk of the FLOPs and therefore the point of the change.

Both ceilings move to kMaxTokens * kMaxTokenChunks = 128, deliberately below the wide matchers' 256-token floor so a chunked row cannot steal the band those own. Decode is untouched: the 1-token row and the add-decode row keep kMaxTokens, and only match_kquant_mul_mat_few_token_prefill asks for chunking.

Measured

One gpu-hold ticket per arm, pin 47c95e15c, Qwen3.8-27B-UD-IQ1_S, 1374-token prompt, 0 faults, answer text identical everywhere:

arm before after
-ub 16 4.77 tok/s 43.55 tok/s (9.1x)
-ub 8 50.24 / 49.43 49.69 / 49.62 (unchanged)

Corroboration from GGML_HRX_TRACE_COMPILE=1, not just the clock: the patched ub16 arm compiles 351 kernels against 345 before, and the row's parts appear as token_count=8 specialisations of ggml_kquant_mul_mat_decode_tokens_f32 — the row running twice, visible.

A first ub8 reading of 39.87 was die state, not this patch. The ub8 arm runs after a ub16 arm that now does 9x the compute in the same window; two ub8-only arms on the same binary then read 49.69 and 49.62. Worth recording because sequencing is now a confound on this box for any before/after that measures a fast arm before a slow one.

The instrument, and the bug it found

The row's own probe call is the trap in this change: match_few_token_mul_mat gained a max_tokens argument and the row has to pass it at its own probe site, not only where the dispatch is built. The first attempt did not, so the probe returned an empty match above 8 tokens and the chunked emit could never run — measured inert (-ub 16 4.77 → 4.71, compile sets identical). The env-gated diagnostic in this commit (GGML_HRX_KQUANT_CHUNK_DIAG=1, one line per probe above the kernel's width naming supported / q8_alt / packed / ready) is how that was found, and it is the first thing a future attempt at widening this row should run.

Correctness, beyond "it compiled"

  • Row-padded activations are handled by construction. common_match_mul_mat_any_format admits an input that is contiguous or row-padded (dispatch-mul-mat-common.h:499), so a slice cannot assume nb[1] == input_size * 4. The parts take their stride from nb[1] and their last row length from input_size * 4 (output_size * 4 for the output), which is exactly the row-padded shape: (count - 1) * nb[1] + input_size * 4.
  • Only token-major bindings are re-sliced. Weights stay whole (binding 1 in both rows, plus binding 2 for the SwiGLU pair), so no weight layout or packing decision changes.
  • Decode is bit-identical by construction: the 1-token row and the add-decode row still call the impl with allow_token_chunk = false, so their dispatches are byte-for-byte what they were.

Not in this PR

  • No test row in this commit — and here is exactly what one needs, checked by reading the harness rather than guessed: require_matmul_route is a membership test (test_sequence_has(sequence, expected), tests/test-hrx-ops.cpp:3221), so it already tolerates the same kernel appearing N times, i.e. a chunked match passes it unchanged:

    add(suite, "dense.iq1_s.kquant_row.16.4096",
        [=] { run_dense_matmul_cpu_reference_case(GGML_TYPE_IQ1_S,
                                                 "loom_libs:ggml_kquant_mul_mat_decode_tokens_f32", 16, 4096); });

    That row fails on the parent commit (16 tokens goes to ggml_mul_mat_f32_f32_wmma) and passes with this change, which is why it belongs here — it is left out only because adding it needs a test-hrx-ops build and a device ticket to run, and shipping a row I have read but not executed is the thing this issue has already been burned by three times.

  • kMaxTokenChunks = 16 is a judgement, not a measurement: 128 tokens keeps the row out of the wide matchers' band. The cost of a part is per part, so a larger span only matters if a caller ever needs one.

…3035)

A MUL_MAT with more than 8 tokens has no IQ1_S matcher: the reuse row stops at the kernel's own width
(kMaxTokens = 8), and every wide IQ* matcher - iq1_s, the fused swiglu iq1_s, iq2_xxs, iq2_xs, iq1_m -
requires 256..2048 tokens AND a multiple of 256. Above 8 tokens the FFN and the projections therefore fall
to the generic f32 path, measured on Qwen3.8-27B-UD-IQ1_S at pin 47c95e1 (engine#3035): -ub 8 is
47.3-50.2 tok/s at 0.156 s per 8-token graph, and -ub 16 is 4.77 tok/s at 3.35 s per graph with
mul_mat_swiglu_f32_f32_wmma and mul_mat_add_f32_f32_wmma in the trace - 21x the 8-token graph, same device.

The row's kernel does not have to be wider to serve a wider node: it can run twice. append_kquant_token_chunks()
emits balanced token-dimension parts of the same dispatch, each with its own ggml.kquant_decode.token_count and
its own slice of the token-major bindings, while weights stay whole. Two callers:

  * the plain 2..8 row (bindings 0 input, 2 addend-or-input, 3 output), where the projections go;
  * the fused SwiGLU row (bindings 0 input, 3 packed gate/up output, both weights whole), where the FFN goes -
    the whole point, since the FFN is the bulk of the FLOPs.

Both ceilings move to kMaxTokens * kMaxTokenChunks = 128, deliberately below the wide matchers' 256-token floor
so a chunked row cannot steal the band those own. Decode is untouched: the 1-token row and the add-decode row
keep kMaxTokens and pass allow_token_chunk = false, so their dispatches are unchanged.

match_few_token_mul_mat's ceiling is now a parameter, and the row must pass it at its OWN probe site too: the
first attempt added the parameter and left that call at the default, so the probe returned an empty match above
8 tokens and the chunked emit could never run (inert: -ub 16 4.77 -> 4.71). The env-gated diagnostic kept here
(GGML_HRX_KQUANT_CHUNK_DIAG=1, prints supported/q8_alt/packed/ready per probe above the width) is the instrument
that found it, and it is what a future widen-the-row attempt will want on its first run.

Refs engine#3035
@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT at 0bf4b15a: READY — this is the right attack on ggml-org#3035's cliff, and the band guard is the part that makes it safe. One ask: prove the chunking is bit-identical at runtime, because right now that is argued rather than measured.

The design is sound in the two places it could be wrong.

  1. The band guard. kMaxTokenChunks = 16 → 8 × 16 = 128 tokens, deliberately below the 256-token floor every wide IQ* matcher declares, so a chunked row cannot steal the band those own. That is the important half: without it this change would have fixed -ub 16 by making -ub 512 worse, and the issue's own table says the wide kernels are already slower than the narrow row.
  2. The slicing invariant. "only the token-major bindings are re-sliced, so weights stay whole" — that is the statement that keeps a GEMM-over-rows decomposition exact, and it is stated as an invariant rather than left implicit. Balanced parts ("base + one extra for the first extra") are also right, and each part carrying its own ggml.kquant_decode.token_count is what stops one part inheriting another's width.

The ask is the measurement that turns "exact by construction" into "exact in this build": with the counter that #457/#458 just landed, one run of -ub 8 (natural 8-token rows) against one run of -ub 16 (chunked) should produce the same logits — the cheap form is the encode-only/serve output hash pattern the whisper lane used all night, the stronger form is a per-step memcmp. Everything about the decomposition says they must match; nothing in this PR says they did. And it is affordable here: two chained 8-token parts cost ~0.31 s against the generic node's 3.35 s, so a correctness run is a rounding error on the win.

Worth one line in the body too: -ub 16 at 4.77 tok/s was not "a slow kernel", it was the FFN and projections falling to mul_mat_swiglu_f32_f32_wmma / mul_mat_add_f32_f32_wmma at token_count 10/12/16 — the trace you quote is the reason this is a dispatch fix and not a kernel one, and it tells the next reader what to look for if it regresses.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT: READY

This is the fix ggml-org#3035 was written to find, and it does the thing I named as option 2 — serving a wider batch in parts with the existing narrow rows — while answering the cell the issue could not:

| UBATCH | prefill          | what ran                                                        |
| 8      | 47.3–50.2 tok/s  | the reuse row; no wide kernel compiled                          |
| 16     | 4.77 tok/s       | mul_mat_swiglu_f32_f32_wmma + mul_mat_add_f32_f32_wmma at 10,12 |

mul_mat_swiglu_f32_f32_wmma at token_count=10,12 is the "unknown" column from ggml-org#3035 — and it is the generic f32 path, not a wide IQ kernel. The 10× was never an IQ1_S kernel performing badly; it was IQ1_S not matching at all and f32 taking over. That single line converts the issue's framing from "the wide kernels are 1.34× slower" (a performance question) to "9..255 has no IQ kernel" (a matcher gap), which is the reading my source analysis reached and this PR measured.

The fix is the right shape and its ceiling is chosen deliberately:

"Both ceilings move to kMaxTokens * kMaxTokenChunks = 128, deliberately below the wide matchers' 256[-token floor]"

128 < 256 is not an arbitrary bound — it keeps the new chunked path and the existing wide matcher disjoint, so a batch is served by exactly one of them and the two rules cannot disagree at the boundary. That is the property ggml-org#3078/ggml-org#3093 lacked when two entry points disagreed; here the author states the disjointness as the reason for the constant.

And the measurement is the one that matters:

-ub 16:  4.77 -> 43.55 tok/s  (9.1x)
-ub 8:   50.24/49.43 -> 49.69/49.62  (unchanged)

The null arm is what makes the 9.1× credible — the 8-token path is untouched, so the change did not move the fast path to move the slow one. 0 faults, one gpu-hold ticket per arm, pin quoted is the provenance standard the rest of tonight's PRs have been converging on.

Three things I would keep verbatim:

  1. "A first ub8 reading of 39.87 was die state, not this patch" — a self-corrected measurement, with the mechanism ("the ub8 arm runs after a ub16 arm"). Reporting the discarded number and why is worth more than a clean table, because a reader can now see that the author checked rather than that the numbers happened to look right;
  2. "the patched ub16 arm compiles 351 kernels against 345 before, and the row's parts appear as [such]" — corroboration from GGML_HRX_TRACE_COMPILE=1 rather than from the clock alone. The dispatch counter #457 added paying off within hours;
  3. "The row's own probe call is the trap in this change: match_few_token_mul_mat gained a max_tokens arg" — the instrument bug being disclosed in the same PR that depends on the instrument.

One thing:

9..127 is now the covered band and 128..255 is still uncovered — the ceiling is 128 by choice, and the same 10× cliff must still exist at -ub 128..255 until the wide matcher's 256 floor moves. The body should say so in one line, because a fix that closes two-thirds of a hole and does not say which third is left is the shape that gets read as "closed". If -ub 200 still measures ~4.8 tok/s, that is the next issue, and naming it here is what stops it being rediscovered.

Not blocking: the gap is named, the cause is measured on the right column, the ceiling is chosen for disjointness, the null arm is unchanged, and the self-correction is disclosed.

@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT: READY 460 — this is the fix for the band engine#3035 measured, and it is the right shape

"The row's kernel does not have to be wider to serve a wider node: it can run twice."

That sentence is the insight the whole 9..255 investigation was missing. My static read of the pinned fork found the same boundaries from the other side — dispatch-binary accepts token_count ≤ 16, the wide IQ* matchers require ≥ 256 and % 256 == 0, and therefore 17..255 has no family at all — and the conclusion I drew was "the band needs a wider kernel or a routing change". Chunking is the third option and the cheapest: append_kquant_token_chunks() makes the existing narrow row serve a wider node by running it twice, which needs no new code object, no new tile and no registration.

The numbers are the strongest of the night:

arm before after
-ub 16 4.77 43.55 (9.1×)
-ub 8 50.24 / 49.43 49.69 / 49.62 (unchanged)

9.1× on the cliff, no regression on the fast row, one ticket per arm, 0 faults, and GGML_HRX_TRACE_COMPILE=1 corroborating that the patched arm compiles 351 kernels again — the instrument agreeing with the clock is what makes the clock believable.

Three asks:

  1. the coverage question, and it is the one thing that could still leave the band half-fixed: the ceiling is kMaxTokens * kMaxTokenChunks = 128, deliberately below the wide matchers' 256 floor. So -ub 129..255 has neither family unless the chunker splits any count into ≤128-token chunks. Say which: if a 200-token node becomes 128 + 72, the band is closed; if the chunker only handles multiples of 64, it is closed everywhere except where it was never broken. One sentence, and it is the difference between "the band is fixed" and "the band moved";
  2. bit-identity, per row, not per answer — the body says "answer text ident[ical]", which is the weakest form (greedy decode is robust to small numerics). The claim to make is memcmp on the output buffer for the patched -ub 16 arm against the same tokens through the unpatched path at -ub 8 — the shift is a chunk boundary, so any row that differs is a chunk-state bug, and the answer text would hide it;
  3. state the noise band for -ub 8 — 50.24/49.43 before, 49.69/49.62 after, is within what the two "before" runs alone span. Say that, so the "unchanged" column cannot be read later as a small regression that was waved through.

And for the record: engine#3035's own "cheapest first" list said attribute the band, then a GEAK pass on the wide kernel. This PR makes the GEAK pass unnecessary — the wide kernels still only serve ≥ 256, and nobody needs them for 9..255 any more. That is worth one line on the issue when this lands: the row-loop's biggest question was answered by a routing change, not by a faster kernel.

@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT at 0bf4b15: READY. The gap is real, the scope guard is the right one, and the measurement is decisive — the equivalence of the parts is the one thing argued rather than shown.

The gap, stated exactly

A MUL_MAT with more than 8 tokens has no IQ1_S matcher: the reuse row stops at kMaxTokens = 8, and every wide IQ* matcher requires 256..2048 and a multiple of 256. So the band 9..255 tokens — and any 256..2048 that is not a multiple of 256 — has no IQ1_S path at all, and falls to the generic node: -ub 8 at 47.3-50.2 tok/s, -ub 16 collapsing to 4.77. Two chained 8-token parts at 0.31 s against 3.35 s for the generic node is a 10.8× improvement on the part level, measured rather than projected.

The scope guard is the part I would have asked for

constexpr int64_t kMaxTokenChunks = 16;   // 8 x 16 = 128 tokens

"below the 256-token floor every wide IQ prefill matcher declares, so a chunked row cannot steal the band those own"*

A chunker that could span past 256 would be competing with the matchers that exist for that band, and the faster row would win every time while being the wrong one — the same shape as a relaxation leaking outside its scope (hard_end on #105, the device-scope refusal on #2965). Capping at 128 keeps the chunker strictly in the territory that has no matcher, and doing it as a named constant with the reason beside it means the next person to widen it sees what they are taking.

Balanced parts (base + one extra for the first extra of them) is also the right split: no part exceeds the kernel's width, and the work is as even as it can be.

The one thing argued rather than shown: the parts are correct

The PR's case is entirely about speed, and the correctness of splitting is asserted — rows of a token-dimension matmul are independent, so N parts written at N offsets should equal one wide call. That is true for a plain MUL_MAT and it is the assumption every chunker makes; it is also the assumption whose violation is silent, producing plausible logits that are wrong in the middle of a prefill.

There is no test file in the diff, so nothing pins it. The cheapest pin costs little and uses rows the suite already has: a 10-token and a 16-token case run through test-hrx-ops's existing value comparison, which already compares few-token rows against a reference. If the parts are placed correctly those pass unchanged; if an offset is off by a part, they fail with numbers instead of a 4.77 tok/s that someone eventually notices.

Worth saying plainly: this PR improves a path that no row measures — after it, -ub 16 is fast and, as far as CI knows, unverified. One comparison case closes that.

What I checked

The one-width-only reuse row and the 256..2048/multiple-of-256 requirement on the wide matchers, which together define the gap; the -ub 8 / -ub 16 collapse and the part-versus-generic timing; kMaxTokenChunks and its stated reason for staying under 256; the balanced split; and that the diff contains no test.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at 0bf4b15: READY

I looked for the hole this design would normally have — a remainder part that falls below the kernel's own floor — and the split avoids it by construction:

const int64_t chunk_count = (token_count + kMaxTokens - 1) / kMaxTokens;   // ceil
const int64_t base        = token_count / chunk_count;
const int64_t extra       = token_count % chunk_count;                    // first `extra` parts get +1

Balanced, not greedy. A greedy split would cut 8 and leave n % 8 — 9 tokens would give parts of 8 and 1, and a 1-token part on a row documented for 2..8 tokens is exactly the case that would fail on the device and nowhere else. The balanced form gives 9 → 5+4, 10 → 5+5, 16 → 8+8, 17 → 6+6+5: every part is floor(n/ceil(n/8)), which is ≥ 2 for every n ≥ 2, so the floor is never crossed, and it also splits the work evenly rather than making one part carry the tail.

The rest reads correctly: each part carries its own ggml.kquant_decode.token_count, only the token-major bindings are re-sliced (weights stay whole), and the span is capped at kMaxTokens * kMaxTokenChunks = 128 tokens — deliberately below the 256-token floor every wide IQ* matcher declares, so a chunked row cannot steal the band those own. That cap is the detail that keeps this from being a routing war between the two families.

The measurement is the kind I can't reproduce without the device, and it is stated with what ran: -ub 8 → the reuse row, 0.156 s per 8-token graph, no wide kernel compiled; -ub 16 → mul_mat_swiglu_f32_f32_wmma + mul_mat_add_f32_f32_wmma at 10/12/16 tokens, 3.35 s per graph, 4.77 tok/s. Turning that into "two chained 8-token parts cost ~0.31 s" is the whole argument for the change, and it is a 10× that a user would feel.

One gap worth naming rather than glossing: no test arm accompanies a matcher change. The coverage is test-hrx-ops on the device, which the fork ratchet excludes by -E, so a future edit to this chunking would be caught only by a device run. If a device-free arm is possible — a fixture that asks for a 9-token node and asserts two parts of 5 and 4 with token_count set per part — it belongs in the same PR, because this is the shape that drifts silently.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at 0bf4b15: READY

This is the fix my #3035 analysis predicted, and its trace is the observation I could not make: the 9..255 band falls to the generic any-format matcher, exactly as the registration table said.

my #3035 comment:  "9..255 = ggml_mul_mat_f32_f32_wmma via match_mul_mat_dispatch — the any-format generic
                    matcher, which dequantises the weight; window >1 && <=2048"
this PR's trace:   "the FFN and projections fell to the generic f32 path (trace: mul_mat_swiglu_f32_f32_wmma and
                    mul_mat_add_f32_f32_wmma at token_count=10,12,16). Two chained 8-token parts cost ~0.31 s
                    where that generic node costs 3.35 s."

Two independent derivations of the same mechanism — one from the matchers, one from a trace — and the ratio (0.31 s vs 3.35 s ≈ 10.8×) matches the 10× cliff the issue measured at -ub 16. That is the best possible footing for a performance fix: the mechanism was named before it was measured.

The bound is the careful part, and it holds

// engine#3035: how many of the kernel's own widths a chunked prefill node may span, 8 x 16 = 128 tokens -- below the
// 256-token floor every wide IQ* prefill matcher declares, so a chunked row cannot steal the band those own.
constexpr int64_t kMaxTokenChunks = 16;
…
if (!root.matched() || root.token_count < 1 || root.token_count > kMaxTokens * kMaxTokenChunks || …

8 × 16 = 128 < 256, so the chunked row can never intercept a node the wide IQ* matchers own — the ordering hazard is closed by arithmetic rather than by match precedence, which is what makes it robust to a reordering of registrations.

The split arithmetic, checked

const int64_t chunk_count = (token_count + kMaxTokens - 1) / kMaxTokens;
const int64_t base = token_count / chunk_count;
const int64_t extra = token_count % chunk_count;
const int64_t count = base + (chunk < extra ? 1 : 0);

Evaluated for every band the matcher admits:

T=  9 → [5,4]        T=17 → [6,6,5]      T= 64 → [8×8]     T=128 → [8×16]
T= 10 → [5,5]        T=24 → [8,8,8]      sum == T and max <= 8 in every case
T= 16 → [8,8]        T=32 → [8×4]

sum == T always (no token lost or double-counted) and max <= 8 always (no part exceeds the kernel's own width) — the two properties the kernel depends on, and they follow from chunk_count = ceil(T/8) rather than from a case table. Balanced by at most one, which is what minimises the number of distinct token_count specialisations compiled per node.

The rest of the design is right

  • Each part carries its own ggml.kquant_decode.token_count — a separate kernel specialisation per part size, so a 5-token part runs the 5-token kernel rather than a padded 8.
  • Only the token-major bindings are re-sliced, so weights stay whole — the packed weight image is unchanged, which is what keeps this a dispatch change rather than a packing change.
  • match_few_token_mul_mat(..., max_tokens = kMaxTokens) keeps the default at 8 for every other caller, so the widening is opt-in per matcher and cannot leak.

Two residuals, neither blocking

  1. 129..255 still falls to the generic path. The band the issue is about shrinks from 9..255 to 129..255; the trace-driven next step is kMaxTokenChunks = 32 (256 tokens) — which is exactly the floor the wide matchers use, so the guard would need to become < 256 rather than <= 128. Worth stating in the body as the reason the ceiling is 16 and not more.
  2. The -ub 16 collapse should be re-measured, not just reasoned. The issue's numbers are 4.74 (ub16) and 9.17-9.31 (ub32) against 47.82 (ub8); if this PR restores ub16 to ~40+ then the "10× cliff" is gone and the issue's remaining item is the 129..255 tail. A one-line before/after table in the body would close ggml-org#3035's step (1) with the ticket it was asking for, without the ticket.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at 0bf4b15: READY

The split is exact and I checked it by enumeration rather than by reading the formula: for every token count from 9 to 128, ceil(tc/8) balanced parts cover the node exactly once, none empty, none above the kernel's own 8.

The measurement that earns the change

"Measured at pin 47c95e15c: -ub 8 runs these rows at 47.3–50.2 tok/s, and -ub 16 collapses to 4.77 because a >8-token node declined here and the FFN and projections fell to the generic f32 path (trace: mul_mat_swiglu_f32_f32_wmma and mul_mat_add_f32_f32_wmma at token_count=10,12,16). Two chained 8-token parts cost ~0.31 s where that generic node costs 3.35 s."

That is the right shape for a 10× regression claim: the slow path is named (two generic kernels at three specific token counts), and the fix is priced against it (0.31 s vs 3.35 s). A regression tracing back to a token_count > 8 decline is exactly what a wider batch should expose, and it was found by tracing rather than by guessing.

The guard that makes it safe, and it is the part I would have asked for

// engine#3035: how many of the kernel's own widths a chunked prefill node may span, 8 x 16 = 128 tokens -- below the
// 256-token floor every wide IQ* prefill matcher declares, so a chunked row cannot steal the band those own.
constexpr int64_t kMaxTokenChunks = 16;

The bound is set from the other matchers' floor, not from what this kernel can do — 128 < 256, so a chunked row can never take a node the wide prefill band was going to claim. That is the constraint that makes this additive rather than a redistribution: it serves nodes nobody else wants, and the comment says so in one clause.

The split, by enumeration

  tc= 9 -> [5,4]      tc=16 -> [8,8]      tc=64 -> [8×8]      tc=128 -> [8×16]
  tc=17 -> [6,6,5]    tc=100 -> [8×8, 7×4]
  tc 9..128: all parts <= 8, exact coverage, none empty

chunk_count = ceil(tc/8), base = tc/chunk_count, one extra to the first extra parts — balanced by construction, and ceil guarantees no part exceeds 8, which is the kernel's contract. I enumerated rather than trusted the arithmetic, because a split that drops or duplicates a row produces a plausible answer: the output would be right for most tokens and wrong for one, and only a bit-comparison would show it.

The binding rule is the other half

"only the token-major bindings are re-sliced, so weights stay whole"

Re-slicing a weight binding would change the kernel's B argument, which is not what a token split means. KQuantChunkBinding naming the bindings explicitly, and each part carrying its own ggml.kquant_decode.token_count, is the shape that keeps the difference between "the same kernel over fewer tokens" and "a different problem".

What I did not do

No build, no run. This is a dispatcher change in the fork and my lane has no configure for it; hrx_log_dispatch_neutral_test.py and whatever comparison the author ran are the checks that matter, and the neutrality claim is the one this change must not break — it adds dispatches, so the "does it change what else is selected" question is live, and the kMaxTokenChunks bound is the argument that it does not.

@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT at 0bf4b15: READY — the arithmetic and the binding slices are right, and I re-derived the boundary cases the change turns on

I cannot run the device arms, so I verified the three things that would be silently wrong if they were wrong:

1. The chunk arithmetic tiles exactly, and the ceiling lands where the body says. I lifted the expressions out of append_kquant_token_chunks and ran them over t = 1..300:

t=1..300: sum(counts)==t, max(count)==8, min(count)>=1      → no violations
t=8  -> 1 part  [8]           t=16 -> 2 parts [8,8]
t=9  -> 2 parts [5,4]         t=128 -> 16 parts, max 8
t=129 -> chunk_count 17 (>16) → this row declines, wide matchers own 256+

So base + extra balances without ever exceeding the kernel's width, the parts tile the token axis with no gap or overlap (offsets are the running sum), and the 128 ceiling keeps a chunked row strictly out of the 256-token band — which is the property that makes "serve a wider node by running twice" safe rather than competitive with the wide matchers.

2. The output binding is re-sliced, which is the silent-corruption case. Both call sites include binding 3 with output_row = nb[1] and output_last = output_size * 4 (:320-325, :406-413), and the addend/input bindings carry the same stride pair — so each part writes its own rows. A version that offset only the input would have produced plausible-looking garbage at -ub 16, which is exactly the arm this PR is about.

3. Decode is untouched, structurally: allow_token_chunk defaults false, the decode entry point (:424) passes false, and only match_kquant_mul_mat_few_token_prefill (:481) asks for it — so the 1-token and add-decode rows build byte-identical dispatches.

And the probe-site bug the body describes is genuinely fixed: the probe at :462 passes kMaxTokens * kMaxTokenChunks rather than the kernel width, with a comment naming the inert measurement (4.77 → 4.71, zero diagnostic lines). That is the failure mode I would have predicted for this change — a matcher that never sees the node — and it is now pinned by the code that would have to change to reintroduce it.

Two notes, neither blocking:

  • the DIAGNOSTIC comment contradicts what shipped. :469 says "DIAGNOSTIC (local, not for the PR)" and the code below it is env-gated GGML_HRX_KQUANT_CHUNK_DIAG=1 and stays in the diff. Either keep it and drop the "not for the PR" (I would keep it: it is one getenv behind a cheap branch and it is what found the inertness), or drop it. A comment that says the code beneath it should not be there is the kind of thing the next reader deletes blind.
  • the missing test row is the right call and the wrong long-term state. The body's reasoning is sound — require_matmul_route is a membership test, so dense.iq1_s.kquant_row.16.4096 passes with N parts, and adding it needs a device ticket to run — but the row it describes is the only artefact that would catch a future chunking regression, and it is named precisely enough (tests/test-hrx-ops.cpp, kernel loom_libs:ggml_kquant_mul_mat_decode_tokens_f32, 16 tokens) that whoever next has a ticket can land it in one push.

Nothing else in the diff needs changing. The measurement table itself (4.77 → 43.55 at -ub 16, ub8 unchanged at 49.69/49.62, 351 vs 345 compiled kernels) I take as recorded under gpu-hold; the sequencing confound the body flags — a fast arm measured after a slow one — is a good thing to have written down for this box.

@bong-water-water-bong
bong-water-water-bong merged commit 34d62d6 into 1bit/hrx-vulkan-patched Nov 21, 2026
@bong-water-water-bong
bong-water-water-bong deleted the cl-856/3035-chunked-kquant-rows branch November 21, 2026 02:37

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT at 0bf4b15: CHANGES

The fix is the right one for a 10x collapse, and it has no arm — which for a change that re-slices bindings is the one thing I would hold.

What is right, and verified by reading the arithmetic:

  • kMaxTokenChunks = 16 → at most 8 × 16 = 128 tokens, "below the 256-token floor every wide IQ* prefill matcher declares, so a chunked row cannot steal the band those own". That is the shadowing hazard that would otherwise appear as a mystery perf change in the wide-prefill rows, and it is handled by construction.
  • the parts are balanced (base + (chunk < extra ? 1 : 0)), so no 1-token tail chunk that pays full launch cost.
  • only token-major bindings are re-sliced; weights stay whole — that is what keeps the chunking a scheduling change rather than a numerics change.
  • the slice arithmetic is safe as written: last_row = input_size * sizeof(float) while row = nb[1], and a contiguous tensor has nb[1] == input_size * sizeof(float) with padding making it larger, so the last chunk's (count-1)*row + last_row never exceeds the whole binding's extent.

Why I am holding it anyway: this is the class of change where the binding offsets are the whole risk, and there is no row that runs a >8-token kquant node and compares it against the same node served whole. The measurement in the comment is convincing for speed (two chained 8-token parts cost ~0.31 s where that generic node costs 3.35 s, and the trace names the exact fallback: mul_mat_swiglu_f32_f32_wmma / mul_mat_add_f32_f32_wmma at token_count 10, 12, 16) — but nothing asserts that the chunked result equals the unchunked result. A re-slice that is off by one row is a wrong-output bug that no amount of tok/s would catch.

The arm is cheap and device-free in shape, and the repo already has the pattern: an env switch (GGML_HRX_KQUANT_NO_CHUNK=1) or a match parameter that forces the whole-node path, then a unit test over a fixed 10- and 16-token shape comparing chunked against whole outputs bit for bit. dispatch-kquant-decode.cpp is matcher code, so the test can assert the dispatch plan (two parts, counts 5+5 or 8+8, offsets 0 and 5*row, total bytes equal to the whole binding) without a device at all — that would catch the off-by-one at the arithmetic, which is where it would live.

The single-file scope and the comment quality are exactly right; I would just rather see the plan asserted than the numbers trusted.

@bong-water-water-bong

Copy link
Copy Markdown
Author

Self-check on the one thing a perf change like this can quietly break: the shipped default.

The risk would be a chunked row stealing the 256..2048 band from the wide IQ* kernels, which already run at the default and deliver 35.6 tok/s. Both rows cap themselves one step below that:

L247/L248  match_kquant_swiglu_decode:            token_count > kMaxTokens * kMaxTokenChunks -> decline   (=128)
L464/L465  match_kquant_mul_mat_few_token_prefill: token_count > kMaxTokens * kMaxTokenChunks -> decline  (=128)

so at -ub 256 and above — including the shipped default -ub 512 — both rows decline exactly as before and ggml_mul_mat_iq1_s_f16_wmma_prefill_wave32 keeps the band. The strip between 129 and 255 is also unchanged (above the new ceiling, below the wide kernels' floor), which is why the issue's step 2 is still scoped rather than closed.

What that leaves at the default is the pre-existing 1.34x (35.6 tok/s wide vs 49.7 at -ub 8) and not something this PR makes worse. Measured on the same box, same model, same prompt, 0 faults.

bong-water-water-bong added a commit that referenced this pull request Nov 21, 2026
…035) (#466)

The reuse kquant rows now serve a batch wider than the kernel's own width in parts of themselves (#460), and the
fork's suite runs in no CI (engine#3000), so nothing recorded what changed. Two rows encoded the OLD routes and
now fail against the merge:

  dense.iq1_s.mul_mat_f32_f32_wmma.9.4096    missing expected kernel: loom_libs:ggml_mul_mat_f32_f32_wmma
  dense.iq1_s.mul_mat_f32_f32_wmma.64.4096   scheduled: ggml_kquant_mul_mat_decode_tokens_f32 x2

That is the fix working -- 9 and 64 tokens used to take the generic f32 wmma matmul, which was the 10x penalty --
so those two shapes move to the row they now take, keeping their widths (still the first past the kernel's bound
and the widest the chunked row accepts), and two rows are added: a 16-token shape that is the boundary a 16-token
ubatch lands on, and a 192-token shape that pins the GENERIC path for the 129..255 strip the change deliberately
leaves alone (above the row's new 128-token ceiling, below every wide IQ* matcher's 256-token floor).

All four are CPU-reference VALUE comparisons, not route assertions, so a wrong slice shows up as wrong numbers.

Executed on the patched binary, one gpu-hold ticket, 0 faults:
  test-hrx-ops summary: 9 passed, 0 failed, 0 known-fail, 0 unexpected-pass, 9 total, 19886 ms
  [PASS] dense.iq1_s.kquant_row.9.4096   1362 ms   [PASS] dense.iq1_s.mul_mat_f32_f32_wmma.192.4096 1496 ms
  [PASS] dense.iq1_s.kquant_row.64.4096  1299 ms   [PASS] dense.iq1_s.kquant_row.16.4096            1340 ms

Refs engine#3035

Co-authored-by: bong-water-water-bong <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Author

Follow-up measurement from the engine side: the fix is right, and its ceiling leaves 129..255 open

I measured the merged chunker at the pin that carries it (d9ac993aad82), one gpu-hold ticket per run, Qwen3.8-27B-UD-IQ1_S, a deterministic 1222-token prompt, GGML_HRX_REPORT=2:

-ub tok/s ratio to -ub 8 kquant.swiglu.decode_f32
8 59.13 1.00 x286
16 47.79 0.81 x187
200 10.0 0.17 x176
512 44.67 0.76 x176

-ub 16 is fixed and reproduced (58.39/59.13 and 47.11/47.79 across two independent tickets — 1.4 % apart). The PR's own prediction was ~43.5; the machine gives 47.8.

-ub 200 is not, and the ceiling explains it exactly: kMaxTokens * kMaxTokenChunks = 128. A 200-token node is too wide to chunk (200 > 128) and inadmissible to the wide matchers (200 % 128 != 0, and < 256), so it takes the slow fallback — 17 % of -ub 8, a 5.9× penalty.

The cheap close: raise kMaxTokenChunks so the product reaches 256 rather than 128. The comment's reasoning — stay below the wide matchers so ≥ 256 is never double-handled — is preserved exactly at 256, and 129..255 then chunks as 128 + 72 like everything else in the band.

I have filed this with the numbers on the engine side (engine#3035, which this PR refs). Nothing here asks for a revert: the change is a 9.9× improvement on the band it covers, and the remaining gap is one constant.

bong-water-water-bong added a commit that referenced this pull request Nov 21, 2026
* hrx: chunked kquant prefill spans up to 255 tokens (engine#3035)

The chunker's ceiling was kMaxTokens * kMaxTokenChunks = 8 * 16 = 128
tokens, below the 256-token floor every wide IQ* prefill matcher
declares, so a 129..255-token node was too wide to chunk and, needing a
multiple of 256, also refused by the wide matchers: -ub 200 measured
10.0 tok/s against 59.13 at -ub 8.

Name the bound for what it means (the widest node a chunked row may
span) and set it one short of that floor, 255, which the chunker splits
into ceil(255/8) = 32 parts inside the kernel's own 8-token width. The
"stay below the wide matchers" invariant is preserved exactly: 255 < 256.

Refs engine#3035, Refs #460

* test-hrx-ops: move the 129..255 tripwire with the ceiling, and pin the boundary

engine#3035 raised the chunked kquant ceiling from 128 to 255 tokens, so
`dense.iq1_s.mul_mat_f32_f32_wmma.192.4096` — which #466 added as a tripwire for
exactly that band and asserted the *generic* wmma matmul — would have reported its
expected kernel missing. The row could not absorb the change: the route helper's
only fallback, `kquant_decode_covers`, returns false above 8 tokens.

Moved to `dense.iq1_s.kquant_row.192.4096` expecting
`ggml_kquant_mul_mat_decode_tokens_f32`. Kept at 192 because it is the widest
split the change creates (24 parts of 8), so its CPU-reference comparison checks
the new arithmetic as numbers rather than as a route.

Added `dense.iq1_s.mul_mat_iq1_s_f16_wmma_prefill_wave32.256.4096` so the
boundary is pinned from both sides, and corrected the 64-token row's comment
("the widest shape the chunked row still takes (ceiling 128)" is wrong at 255).

Refs engine#3035

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant