Repository navigation
gpu: run one-row decode attention over 512 or more keys on the tiled path - #3436
joshuaswarren wants to merge 455 commits into
Conversation
…on a 13-inch M1 The receipts folder holds the stage 1 probe on the GPU (21 of 21, the tiled image equal to the default image on all 12 projection cases), the contract runner's output (3 kernels pass gates 1 to 4, 8 of 8 controls caught), the pre-registration, a summary generated from the raw run files, and the SHA-256 of each raw file. Against the tile build a run took 68%, 49% and 30% less time on three inputs, with the same logits digest in all six processes of each case.
…nd that the fence timeout covers a batch
…ontracts gates.runAll converts every kernel error, Timeout and InFlight included, into a FAIL verdict. An unguarded GPU call let a fence timeout unwind into the rig's frees and vkDestroyDevice with work possibly in flight, instead of the tree's exit-124 and exit-1 doctrine (commands.zig:104,122). Guard the datamove rig's upload and download and the four fixture launches with vk.orExit. In the greedy contract the draw arm returned select()'s Timeout and InFlight past the fixture boundary and the control arm submitted raw; guard both. A NonFinite refusal still reaches the refused marker. Host tests lock the swallowing channel and the refusal.
…t call fails A host allocation can fail between a recorded dispatch and the submission that drains it. gates.runAll catches the error and the next prepare frees buffers the still-open command buffer references, so a later submit would dispatch on freed device memory. Commands.discard resets the open command buffer and clears the batch state. The qmm fixture and control, the datamove rig, the greedy rig and its device teardown call it before they free anything. Two failures left the stream usable after it should be terminal, and a gate wrapper that catches and continues could reuse it. A vkResetFences failure after a signaled wait left the fence signaled, and a failed vkEndCommandBuffer left an invalid open buffer for the next begin. Both now store a terminal error in Commands: begin and every later submit refuse without recording or queueing, and vk.orExit ends the process. Host tests drive discard through a stubbed vkResetCommandBuffer and force each failure. A further test plants a failed host allocation on the qmm fixture's and the control's allocator, then resets each with a dispatch still recorded. Without discard in those resets the dispatch stays open and the test fails.
Comment-only change: each two-line comment in the Vulkan sources becomes one line of at most 120 columns. Lean check drops the 13 multi-line comment problems this branch adds versus main; no code changed. Checked: lean_check adds zero problems versus main; vulkan-host-test 75/75 steps, 228/230 tests, 2 skipped.
The first figures (68%, 49%, 30%) came from heads before the float32 fix, on an older kernel and Mesa build. On the fixed heads, on a 13-inch M1 with Linux 7.3.0-2-20261110.1-lab-ARCH, the three cases took 57.8%, 34.1% and 16.6% less time (three pairs each, one logits digest per case). Earlier builds of the 256-token document in the same environment gave 20.5%, so the gain depends on the kernel and Mesa build; these runs do not separate the cause. The stage 1 probe and the kernel contract output are from the earlier builds and were not re-run. Signed-off-by: joshuaswarren <816217+joshuaswarren@users.noreply.github.com>
…rted preservation
… -Dcontract-root option The contract runner built only the Q4 projection's shaders. Each later operator registers in the same runner, so it now imports the stage 1 to 5 shader modules (norm, rope, attention, GDN, greedy and the data-movement kernels) that the operator probes already build, and the stage modules are hoisted out of their probe blocks so both can share them. -Dcontract-root points the runner at another root file, so one operator group can be built and run on its own.
…nel contract The stage 4 GatedDeltaNet images (conv_dw1d, gdn_conv_decode, gdn_split, gated_delta_prefill_ash and gated_delta_decode in its ASH_QWEN35 raw-gates mode) register as eight kernels through the production Gdn wrapper, so the wrapper's binding tables — the read-only g slot and the single-chunk snapshot dummy among them — are the ones under test. f32 state flows in and out of place, the interior chunk snapshot is bound exactly when chunks exceed one, and the decode loop chains the carried state. References are the stage 4 fixture's f64 walkers made parametric in tokens; every depth a spec states is a function of the token count (one ~130-deep state update per token, the fixture's stated derivation). The f32 state parts prove fp32 sums with an engineered stress fill whose kv partials overflow fp16; the bf16 parts declare bf16=0 with the reason the output's own rounding hides the sum error, as HIP's mamba and CUDA's gdn_prep do. The host suite cross-checks the walker against the fixture's bit for bit and proves the generated fills against the references without a GPU. contract_gdn_main.zig runs the group alone via -Dcontract-root and prints the same LIMITS lines, records audit and runAll tally as contract_main, plus live local-size and shared-memory evidence for all seven pipelines. Proven: zig build vulkan-host-test (20 gdn contract tests, walker parity with fx.RecurWalk/fx.Decode, stress fp16 margins >= 100x); both contract runners build; the runner refuses the software Vulkan device fail-closed. GPU gates 1-4 pending on the M1/M2 devices (none reachable from this host: llvmpipe only).
…e run Three fixture bugs the M1 Max's first run surfaced, none of them shader bugs: the split parts uploaded one combined output buffer where the wrapper binds soa, g and beta separately (OutOfRange on every gate); the decode conv's unchanged-check listed the host chain scratch as an input while indexing one device buffer fewer, so input_now's tail was never filled (a false 'a run changed its inputs'); and the prefill recurrence's random fill used the stage 4 fixture's ranges, which only ever ran at 8 tokens - at 130 the walk outgrew f32. The random fill now decays (g, beta and the whole soa at 2^-3 scale or less), so any token count stays bounded. Also the sums replay the gates ran: every dot re-summed in the requested accumulator and order, the conv chains replayed from the uploaded initial state, exactly as computeWant walks them. Proven: vulkan-host-test green; runAll on Apple M1 Max (G13C C0) Honeykrisp - prefill conv, decode conv and decode state pass gates 1-4 fully; prefill y, hf+snap and split classes settle with the fill fix pending the next device run.
…the soa sums proof The M1 Max run showed the split g shapes gate failing where a random a_log above ~2.4 drove g into f32 subnormals the device flushes - the exact case the stage 4 fixture's census deferred to Main. The served random fill now draws a_log in [-6, 0] (g >= e^-4.5, normal), with the census case named in the fill; the subnormal-flush decision stays with Main. The split soa sums gate moves to f16=0 with the measured reason: the fixture budget's magnitude term at the output's scale is wider than any fp16 miss the stress can engineer, and gate 3's shapes already bound the norm's sum to f32 quality (a bf16-summed ss misses ~2^-8 relative against an observed worst of 0.037 of bound). Proven: vulkan-host-test green.
…tes 1-4 cast_f32_bf16, cast_bf16_f32, copy_u32, copy_u16, gather_u32, gather_u16 and dequant_bf16 register with the kernel contract, bit for bit (a NaN keeps its class; a non-finite dequant scale or bias is checked by class; every gather run includes an out-of-range id whose stated rule is the documented zero row). tf-stage1-datamove runs the group on a real GPU (zig build stage1-datamove) and refuses CPU devices; the stage 1 imports hoist so the probe and this runner share them. Ported from w7p/native-vulkan's a3f040c onto the engine-pr2 tree: the files needed no source change; the wiring reuses this tree's hoisted stage1_shaders module. Proven: zig build -Dvulkan=true stage1-gpu-build and vulkan-host-test pass on this box (llvmpipe only); tf-stage1-datamove --help exits 0 and the runner fails closed (exit 1) with only the software device present.
rope_bf16 and sdpa_rows_bf16 against stage3_fixture's f64 references generalized past the fixture's 8-key score buffer to the served shapes (decode rows 1, prefill rows <= 32, visible keys 1..7168 on the 16-key tile, 256-lane scan and 1024-thread stride edges and the kStreamKeys bound). The sdpa bound is derived from the shader text -- denominator depth ceil(n/256)+8, the 256-lane strided chains plus the 8-level tree, NOT the plain n-term sum -- and pinned to the source by a host test. Single-key rows carry the V bits exactly; multi-row prefill rows decode alone bit-identical. Ported from w7p/native-vulkan-model's 60a22e7 onto the engine-pr2 tree: the files needed no source change; the wiring reuses this tree's hoisted stage1/stage3 shader modules. Proven: zig build -Dvulkan=true stage3-gpu-build, stage3-host-test and vulkan-host-test pass on this box; tf-attention-contract --help exits 0 and honestly refuses this box's software llvmpipe (exit 1). Real-GPU run needs the Apple Vulkan rig.
The greedy draw — finite_logits, argreduce_chunk and argreduce_combine behind one submission, three launches inside the run hook — registers through gates 1-4, plus the planted control contract_controls_greedy.comp (the mirror of HIP's tf_ctl_fmax_max: a row max that drops a NaN), registered with control = .nonfinite and required to go red. The acceptance is exact: the token equals the host greedyRef (max wins, ties to the lowest index, +0/-0 equal), a planted non-finite row refuses naming its first offender, repeats are byte-identical, inputs and guards untouched. Ported from the greedy agent's files on w7p/native-vulkan-model onto the engine-pr2 tree: the files needed no source change; the wiring compiles the control beside the stage 5 variants and reuses this tree's hoisted stage5_shaders module. Proven: zig build -Dvulkan=true stage5-gpu-build, stage5-host-test and vulkan-host-test pass on this box; tf-vulkan-greedy-contract --help exits 0 and the runner fails closed (exit 1) with only the software llvmpipe present.
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
TF_VK_DECODE_BENCH=N prefills the prompt, runs 8 warm-up tokens and N greedy tokens with readback, and prints ms per token, tokens per second and an FNV hash of the token ids. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
qmm_q4_tile and qmm_q4_tile_f32 ran one thread per output column with a serial walk over k, so a 2048-column projection filled 8 workgroups. They now run one workgroup per (row, 32-column tile) with 8 slices of k and add the slice sums in slice order. The f32 sum order changes; the dequantisation of each weight does not. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
The decode SDPA kernel runs one workgroup per head, 8 in all, and each walks every visible key. The tiled scores, softmax and PV dispatches spread the keys over many workgroups and keep the same accumulation order. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> # Conflicts: # CHANGELOG.md
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> # Conflicts: # CHANGELOG.md
…-ksplit Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
M2 Max and M1 decode A/B on clean-tree builds with identical greedy token hashes, and the QMM kernel contract for base and head. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
…-decode Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
…a-decode Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> # Conflicts: # CHANGELOG.md
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> # Conflicts: # CHANGELOG.md
|
[Joshua's agent] Main moved again (5c82ef2) and its new CHANGELOG.md entries collided with this branch's, so I merged main once more (head 3e2ab4a, merge commit, no force-push) and moved this branch's own entries to the bottom of the Unreleased list, where main's top inserts no longer touch them. No code changed since the last head, so the earlier A/B and contract results stand. |
|
[Joshua's agent] Independent review of |
…thin 120 columns Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
|
[Joshua's agent] The lean check failed on this head: comments in attention.zig (four past 120 columns, two multi-line) and ops_q4.zig, and qwen35_model_probe.zig at 605 lines. New head: 9599a2c. It carries the same fixes as #3431 and #3435 (the decode bench now lives in zig/tests/vulkan/qwen35_decode_bench.zig) plus the comments of this PR's own tile-key constant. No behavior change, pushed as plain commits with no rebase. |
|
[Joshua's agent] 13-inch M1 decode A/B at the 6173-token depth, which the earlier M1 runs on this PR did not cover. Clean-tree builds, Qwen3.5-2B, 128 tokens, greedy, 3 alternating rounds per case, run records Median ms per token:
Some runs in the k-split-only and attention-only rows came in at 43 to 61 ms per token, in both arms and at every depth, next to ordinary runs of the same arm (for example u24 ckb 51.4 next to 28.4 and 28.4). I excluded those runs from the k-split-only column; the base and combined columns come from the combined row, whose three rounds agree to 0.1 ms. I do not know the cause [INFERENCE: other work on the GPU during those rounds]. One d6173 base run in each row lost its result line to a kernel-log echo and was dropped, so d6173 base has n=2. |
|
Thanks @joshuaswarren. The one-row dispatch condition is clear, but this branch still inherits the changed arithmetic from #3435 and the causal NaN issue in #3431. Those dependencies need result-preserving fixes before this can land. For this change, please post complete raw device receipts at 511/512/513 keys and with capacity above visible keys, comparing full BF16/F32 output bytes against the single-dispatch path. Include a serial greedy server decode crossing the 512-key threshold, full token hashes, final build hashes and all timing samples. Please include the raw decode-attention receipt files with that evidence. We also need green zig, zig-windows, pytest and fmt jobs at the updated head.
|
|
[Joshua's agent] Read, thanks. Agreed on both dependencies: this branch will be rebased on the fixed #3431 and on the order-preserving #3435 once those exist. After that I will post raw device receipts at 511/512/513 keys and with capacity above visible keys, comparing full BF16/F32 output bytes against the single-dispatch path, plus a serial greedy server decode crossing 512 keys, token hashes, build hashes, all timing samples and the raw receipt files. The speed numbers above were measured with the order-changing k-split in the stack, so they will be re-measured. |
|
[Joshua's agent] Status, not a ready note: CI is green at the current head 9599a2c (8 success, 2 skipped), but the evidence you asked for is not on this branch yet. It waits on the #3431 fix (now pushed at 85a672f) and the order-preserving #3435 rewrite (still being built). After the rebase I will post raw device receipts at 511/512/513 keys with capacity above visible keys, full BF16/F32 byte compares, a serial greedy decode crossing 512 keys, token and build hashes, all timing samples and the raw files. The speed numbers above were measured with the order-changing k-split and will be re-measured. Do not take the green CI as readiness. |
|
@joshuaswarren, the one-row dispatch condition reads clean, and the stack order verifies: the branch carries When the rebased stack carries the result-preserving fixes, post that evidence and the branch returns to the
|
|
[Joshua's agent] Consequence of the #3435 close for this branch: the k-split in this stack is the order-changing one you reviewed, and #3431's causal fix (pushed at 85a672f, CI green) does not touch it. So the rebased stack you ask for cannot come from #3435. Two paths: I re-measure the 511/512/513-key raw receipts, full byte compares and the 512-crossing serial decode on the CURRENT stack (order-changing k-split + fixed causal tile) and report them as such, with the sum-order caveat stated up front; or this PR waits for a genuinely different split. Say which, or close this with #3435. |
|
Thanks @joshuaswarren. With #3435 closed, the k-split in this stack is still the order-changing one, and re-measuring it wouldn't change the answer: landing needs the same output bytes as the single-dispatch path, which matching greedy traces can't show. So we're closing this with #3435, as you offered. The 512-key threshold and the arms behind it are good work. When an order-preserving split exists, please open the routing change on top of it with the receipts we listed, and we'll review it promptly.
|
|
[Joshua's agent] Data for the record on #3436 (closed at 20:48Z, so no action is asked here). It answers one question that stayed open: does the order change in this PR move the logits, and does it move the ids? Short answer: the logits move, the ids do not. This matches your point that matching greedy traces cannot show equal bytes, and the tables below put numbers on it. Setup: an RTX 5060 Ti on a 16-inch M1 Max MacBook Pro running Linux, Vulkan, Logits against the oracle and between arms (one run per arm, logits kept; bf16 values compared as float32):
Across the 18 runs per size in the earlier repeat rows, the #3436 head produced a logits digest that differs from pre-fix at both sizes and was stable inside its arm (6 of 6); pre-fix and the #3431 head produced one identical digest (12 of 12). In all 36 of those runs the generated ids match the oracle. So #3436 changes the output bytes on this card and does not change the tokens. Speed, scoped to this card at document-1024 (24 runs, alternating #3431 head and #3436 head in fix, dec, dec, fix order, 12 each; run2 is the second pass in the same process):
That is 17.5% lower, and the two ranges do not overlap. An earlier 6-run-per-arm row at document-1024 gave 13.3% lower. At document-256 the earlier 6-run row did not show the gain (the #3436 median was 2.0% higher, with run2 values split between about 930 ms and 1190 to 1290 ms); a 12-run-per-arm row at 256 is queued. I make no speed claim for document-256, for other cards, or for other chips. On the Arc Pro B60 the three arms had equal logits digests at both sizes in the single runs I have, and I have no repeat data there yet. The order-changing k-split is the cause of the digest difference [INFERENCE: I did not isolate it with a separate arm]. When an order-preserving split exists, these are the same harness and the same inputs for measuring the routing change on top of it. |
[Joshua's agent] One-row decode attention at long context was slow because the decode kernel dispatches one workgroup per query head (8 in all) and each walks every visible key. This PR sends a one-row decode over 512 or more keys down the tiled path that #3431 added for prompt chunks of 2 to 64 rows (scores, row softmax and P times V as three dispatches over an f32 score scratch). The tiled path keeps the decode kernel's order of sums, so the greedy tokens do not change. Below 512 keys the old single dispatch is kept (measured: it is as fast or faster there).
Stack. This PR is stacked on #3431 (head
724dfb4b9) and on #3435 (k-split decode matmul). New here:b8b634101(the change, a few lines inzig/src/vulkan/attention.zig:decode_tile_keys = 512and the condition inattend), plus a merge and a docs commit (changelog and measurements). The diff against main shows the stack until the others land. On #3431: the per-kernel split that the KTIME timestamps showed for the tiled SDPA was an attribution artifact, so no number here rests on it; all numbers below are whole-run decode times.Numbers. Clean-tree builds of
38458a94d(base: #3431 and #3435, decode attention unchanged) andb8b634101(head), run alternately, three rounds, 128 greedy tokens with readback, medians, no GPU timeouts. A few result lines in the raw files are cut by the GPU-timeout counter print that shares the line, so a cell can have two samples.Correctness. The greedy token hash is equal between base and head in every run on both machines (
fc93d24775b1d909,3efb3759184db87e,fc0ededa74f07707). The attention contract (tf-attention-contract, head build) passes 18 of 18 on both machines with 0 GPU timeouts. The 512-key threshold came from three diagnostic arms on the M2 Max (always tiled, 512, 2048): 512 and always-tiled were equal at 6,173 keys, 2048 was slower at 1,024 keys.The gain is large on the 14-inch M2 Max and small on the 13-inch M1; there is no regression on either. Measurement files are in
docs/receipts/vulkan-sdpa-decode/.Not covered here: the server path, which is a separate item.