Repository navigation
Vulkan batching: record one decode token in one command buffer (stacked on #1544) - #1561
Closed
joshuaswarren wants to merge 35 commits into
Closed
joshuaswarren wants to merge 35 commits into
joshuaswarren wants to merge 35 commits into
Conversation
The Vulkan backend comes in on the same terms as HIP: every kernel registers with the kernel contract. This registers the one kernel the base PR holds, the affine Q4 group-64 projection (qmm_bf16: bf16 in and out, fp32 sums). contract_qmm.zig fills the shared contract.spec for it and gives the shared gates a Vulkan fixture (real dispatch through the runtime, staged upload and readback, poisoned guard words). Served shapes are the ones the Qwen3.5-2B engine calls it at: K 2048 and 6144, N from 16 up to the 248320-row head, one row for decode and 32 for a prefill chunk, plus small fixture shapes. Gate 4 keeps the harness default (fp16 and bf16 sums must miss by 100x). contract_controls.comp holds the planted controls, one per gate, each a kernel built to break its gate: a projection that drops NaN, an order-dependent atomic sum, a sum that writes into its input, a projection that loses its K tail, and one that sums in fp16. A run where a control passes is a failed run. Gate 5 needs per-chip limits: vulkan_records.zig declares each launch's workgroup size and shared bytes, limits.zig adds the Vulkan launch and limit types, and a host test refuses any chip whose limits are not measured, so no value is assumed. The runner prints every limit it reads from the live device (LIMITS lines) and checks the declared launches against them. tf-vulkan-kernel-contract builds the runner and the controls without running them; vulkan-kernel-contract runs them on the device. Both exist only with -Dvulkan=true. Checked: the host tests and the aarch64 build of the runner pass. Not yet run: the runner on a device (gates 1 to 4 and the live limits check), so no SUMMARY line exists yet, and the per-chip limit table is still unmeasured.
…wo input-write controls Review found gate 2 (repeat, aliasing, guards) vacuous for qmm_bf16: Fixture.run read back only the output buffer and the rig's inputs stayed the host snapshot taken before upload, so 'inputs untouched' could not fail for the real kernel. (The scribble control was caught only because Control.run downloads its x buffer.) Fixture.run now downloads all four input buffers (x, w, scales, biases) into the snapshot after each run, so the before/after comparison sees what the device holds. Two planted controls prove it: the same fixture with a write to its weights and to its biases (the last input, so a readback that stops one short misses it) after the dispatch must fail gate 2 and are counted as controls (8 controls now). The records comment no longer cites runner stderr hashes (they were from older runs, and a file cannot carry the hash of a run of itself); the description carries the hashes of the runs on this head. Proved by: vulkan-host-test 26 of 26 (18, 6 and 2 in three binaries) and the aarch64 ReleaseSafe runner build; not device-run yet.
…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.
…ion shapes contract_pointwise.zig states and checks the six pointwise closures of stages 2-4 on the host: the stage 2 trio reuses stage2_fixture, the f32-preserving residual add claims the exact f32 sum bit for bit (a flush-to-zero device fails HONESTLY), the attention output gate uses boundExact with ops 4 mids 1 and demands signed-exact zeros, and the gated RMSNorm uses the rows family bound plus ops 10 mids 12 with nan/inf/±0/zero-row/nan-row controls class-checked. Every checker also refuses a corrupted output, a sign-flipped zero and a planted nonfinite. contract_pointwise_main.zig drives all six on a real GPU through the wrappers' exact dispatch shapes (NormMlp for stage 2; the preserve add, gate and gated norm at attention.gatePlan's and gdn.gatedNormPlan's geometry), three byte-identical repeats per case. Ported from w7p/native-vulkan-stage2 (c0ee7bf + eb72415) onto the engine-pr2 tree. One source adaptation: this tree's NormMlp.Shaders gained the add_preserve_bf16 field, so the runner now serves it (the image this tree's stage 2 closure already compiles); the shader sources themselves landed with this tree's stage 3/4 closures. Proven: zig build -Dvulkan=true contract-pointwise-build, vulkan-host-test pass on this box, and zig-out/stage{2,3,4} carries the six images; tf-contract-pointwise --help exits 0 and the runner fails closed (exit 1) with only the software llvmpipe present.
… cross target The datamove test module was built for -Dtarget, so a cross build (aarch64 on the x86 build host) failed with 'unable to spawn foreign binary' in vulkan-host-test. It now gets its own host-target module like every other host suite. Proved by: vulkan-host-test and all stage and runner build steps pass with -Dtarget=aarch64-linux-gnu (224/224 steps).
… and u16 copy On a real device (Apple M2 Max, Honeykrisp) the shapes gate failed three kernels with the Zig error Misaligned: the gate's edge shapes include odd element counts, and a 16-bit range of an odd count is not bindable (dispatch.bind needs whole 32-bit words; View.init refuses the same ragged tail), so the fixture's view call raised an error that the gate scored as FAIL. The kernel refuses that edge, so prepare now returns false for it (an edge refused by the kernel, as the gates count them); served shapes (146x1, 3x700, 300x1, 2x520) are all even. Proved by: vulkan-host-test and stage1-gpu-build pass for aarch64 (81/81 steps, 210/212 tests, 2 skipped). Not proved: no device rerun yet.
…hat prepare sized The M2 Max's run of the gdn group died in gate 1 of the prefill_y kernel: "index out of bounds: index 524288, len 10248" at contract_gdn.zig's uploadBuffers, called from the nonfinite gate's prepare. 524288 is 2 * state_elems and 10248 is 5 * linear_dim + the guard words, so the sliced region belonged to a different kernel: the prefill arm uploaded the same buffers for prefill_y and prefill_state, and the state's region (prefill_y's out holds y only) was sliced out of a much shorter out. The upload path now lives in one place, uploadWords, which hands each device buffer the words it takes: a checked output its own region of out, an output no fetch reads fresh poison scratch, and every region bounded by what prepare sized, so a mismatch is an error the gate reports instead of a panic that kills the runner. The prefill_y and decode_state outputs that no fetch downloads take scratch, the checked ones keep out's region, and every other arm keeps the bytes it had. Proof: a new host test drives the gates' own shape sequence (gate 1 and 2's small() shape, gate 3's served and edge shapes, gate 4's stress shape) through prepare and the upload path with no device, and holds every upload inside the region prepare sized and the buffer count at what run() binds. It fails on the old sourcing with the same out-of-range region the device hit (outWords: OutputRegionOutOfRange) and passes on the fix; the whole host suite is 21/21 and the arm64 runner builds clean (100/100 steps). The split g gate's class finding (1 of 128 outputs: nan where float64 gives finite) is untouched: it is a device finding for the maintainer to decide on, not a fixture bug.
…assuming it Why: the repeat gate failed on the PR-B device run with 'a run wrote outside its outputs' (gates.zig intact check). The rig's input() uploaded only the data window at offset guard, so the shell's guard bytes never held the 0xa5 pattern intact() demands — fresh device memory reads as zeros, and the gate was false on every run of every shape. The draw itself never writes the shell (its outputs are the internal partials and results buffers, the same shape HIP's argmax contract declares via rig.scratch/rig.output), so the guard finding was a runner bug, not an overrun. What: Rig.input builds the full shell through a new shellFor (pattern, data, pattern) and uploads it at offset 0, the way the datamove rig's slot() already did. New host test pins the layout: guards patterned on both sides, data between, exact length — the invariant the old code never stated anywhere. Proof: zig build vulkan-host-test stage5-gpu-build contract-pointwise-build contract-pointwise-host-test (shared cache) green: 103/103 steps, 22/22 tests, including the new shell test. The gate's strictness is unchanged; a real overrun still fails intact(). The gate line's device-side pass still needs its device run, which is out of scope for this offline fix. Build log: scratch/atc-vulkan-native-20261026/prb-fix-gp-build.log
…ally built Why: the PR-B device run failed all three preserve-add cases and the plain add's classes case. The preserve fixture modeled a pipeline nobody builds: it filled f32 buffers and demanded exact f32 sums, but add_preserve_bf16 is binary_vec.comp with -DPRESERVE_F32 over the default bf16 storage — the -DUSE_BF16 the build passed alongside it matches no ifdef in the shader (storage variant is USE_FP16/default), so the device ran the bf16 add reading u16 halves of f32 bits. Every reported got matches that model bit for bit: cancel element 0 is widen(0x293a)+widen(0x293a) stored bf16 0x29ba (read back as u32 0x000029ba), random element 0 is 0xbed4fbc2, classes element 6 is the j=12 NaN 0x7fc0 beside the j=13 overflow +inf 0x7f80 = 0x7f807fc0. The plain add's classes failure was a runner gap: stage2's measured-property policy (allow_subnormal_flush from shaderDenormPreserveFloat32, as stage2_probe wires it) was never applied, so the subnormal rows were checked strictly regardless of the device's reported float controls. What: PreserveAdd and PreserveCase become aliases of stage2.Add/AddCase — one model of the pipeline (f32 add, one RNE bf16 store), two pipelines — and the preserve gate checks strictly (no flush qualification ever): a device that flushes fp32 denormals fails the subnormal classes rows as an honest finding, printed by a NOTE, never fitted away. addGate now wires the stage 2 policy from the device property and the device line prints preserve32/flush32 so the next run is decidable. The inert -DUSE_BF16 is dropped from both binary_vec build entries and the stale 'compiled without -DUSE_BF16 stores exact f32' comments are gone. A host test scans the embedded SPIR-V: add_preserve_bf16 declares OpCapability DenormPreserve (4464), add_bf16 does not — a define that matches no ifdef can never silently produce the plain add again. Proof: shared-cache build green, 103/103 steps, 22/22 tests, including the rewritten preserve tests (subnormal want 0x0002 must stay refused when a device flushes) and the capability scan; the generated images were verified directly (4464 present only in add_preserve_bf16). Build log: scratch/atc-vulkan-native-20261026/prb-fix-gp-build.log
gated_delta_decode, gated_delta_prefill_ash and gdn_split quieted every value whose exponent is all ones and whose top mantissa bits are zero: (bits & 0x7fff0000) == 0x7f800000. That test is true for +-inf (0x7f800000), so the helper returned 0x7fc0 (NaN) for an infinity; only a NaN with a payload in the low 16 bits was meant. In the gate chain s = bf16(a + dt) an infinite a became NaN, then softplus and g were NaN where float64 gives exp(-inf) = 0. Found by the kernel contract's nonfinite gate on Apple M1 and M2 Max (3 FAILs: split g 1 of 128, decode y 896 of 16384, decode state 16384 of 262144 outputs differ in class). The first diagnosis blamed exp(-inf) in the driver; a bit-level emulation of the helper shows 0x7fc0/0xffc0 for +-inf, so it was our helper. Every other shader here already uses isnan(value); these three now do too. Finite values are untouched (same bits), NaN stays a quiet NaN. Proved by: bit emulation, vulkan-host-test and every stage and runner build for aarch64 pass; not yet re-run on a device.
…device finding On Apple M1 and M2 Max under Honeykrisp the device reports shaderDenormPreserveFloat32 = false and flushes fp32 denormals, so the preserve-add classes case reads the bf16 subnormal sum 0x0002 as 0x0000. The runner now prints KNOWN (not FAIL) and counts it apart from passes when every mismatch is a subnormal sum read as a same-signed zero and the device reports no denormal preservation; a device that claims preservation and flushes, or any other mismatch, stays a FAIL. The RESULT line carries known=N. Proved by: host tests and the aarch64 build (224/224 steps); not device-run yet.
…etry, a run that always answers Why: the device run died with a bare 'error: Invalid' in the first gated-norm case and never printed RESULT. gatedNormGate called gdn.gatedNormPlan with the fixture's 2048-element weight, but the production gated norm is PER HEAD (gdn.Model: 16 head rows of 128 a token, the [128] gain indexed by the column within the head and shared by every head) and the plan refuses any other weight width — the gate had never reached a device. The fixture modeled a 2048-wide global row; nothing in the kernel computes that. What: - The fixture is the production geometry: tokens x 16 head rows of 128, head-major, the [128] gain at the column; the f64 reference computes the norm per head row and the poison cases prove head isolation (an inf/nan input poisons only its own head row). Served shapes are the tokens the engine serves: one decode row and a whole prefill chunk of 32 (qwen3_5 vulkan forward, max_prefill_rows), plus the controls on three. - The bound is re-derived for the 128-wide reduction, honestly: 256 threads over 128 columns = at most one square per thread (1 rounding) + 8 tree levels (zeros exact) + the mean divide = 10, depth stated 12; gamma(12, 2^-24) ~ 7.2e-6 against the old 2048-row figure gamma(20) ~ 1.2e-5 — the bound is TIGHTER, not loosened. ops 10 and the mids argument are unchanged (per-element, depth-independent). - No gate can kill the run: every case goes through a guard that prints 'FAIL <gate> case=...: <error name>' and the loop continues; the RESULT line (passed, known, total) always prints and the exit is nonzero exactly when passed + known falls short of total. - The preserve-add KNOWN case now prints only its KNOWN line (the reasoning folded into it); the FAIL and NOTE lines are kept for genuine mismatches. - Host tests: the plan accepts every fixture case's dimensions and refuses the old 2048-gain shape (the exact call that died on device), the fixture's element counts, the per-head reference (finite off controls, signed zeros, head-isolated poison), and the checker refusals. Proof: shared-cache build green — 106/106 steps, 178/180 tests passed with the 2 pre-existing skips (device/env-gated); a fully cached rerun shows zero failed steps. Build log: scratch/atc-vulkan-native-20261026/prb-fix-gn-build.log
The probe gave no per-token timing, so a decode speed change on the Vulkan backend could not be measured the same way before and after. steadyToken stamps CLOCK_MONOTONIC (std.Io.Clock.awake) before the first host action of a token and again once the chosen id and the full 496,640-byte logits row are in host memory, and the probe writes every sample to steady_samples.jsonl after both runs. An engine without a combined decode runs its separate decode, GPU draw and logits readback inside the same timed span, so the span is the same work for any engine. Behaviour, generated ids and the logits receipt are unchanged. Checked: the probe and the server cross-build for aarch64 with the Vulkan option and the host suites pass (101/101 steps, no failures).
A decode token took about 496 separate submits, each with its own fence wait. Engine.decodeDraw records the fed token's upload, the embed, all 24 layers, the head, the GPU greedy draw, the 12-byte chosen-id copy and the optional full logits copy into one command buffer with one submit and one fence wait. The backend's decode seams (queue and verify) call it. Shaders, arithmetic, dispatch order and barriers are unchanged, so output is byte-identical. Making one command buffer safe needed two things the per-submit path hid: - Descriptor sets are not captured when a set is bound, so each dispatch in a batch gets its own set from a bounded per-pipeline bank (512 sets), written once and reused only after the previous batch's fence. - The staging buffer was overwritten from offset 0 on every upload; a batch now gives each upload and readback its own slice, so nothing is overwritten before the GPU reads it. A synchronous download inside an open batch is refused, and a read is allowed only for a slice the batch recorded. Failure handling is unchanged: a failure before the submit aborts the batch, poisons the engine until reset, and a timeout or in-flight failure still ends the process before anything is freed. The visible position advances only after the fence. Measured on the instrumented build of this change (private profiler, not in this commit), unicode-24, 64 tokens, ReleaseSafe, three interleaved pairs, the median over 63 steady tokens per process, old and new generated ids and all 64 logits rows byte-identical to the unbatched build in every process: M1 Max (G13C) 160 ms to 94 ms per token (median pair gain 40.75 percent), M1 (G13G) 30.0 percent, M2 Max (G14C) 61.7 percent. This commit is re-measured without the profiler separately. Checked: host suites pass, the probe and server cross-build for aarch64.
Contributor
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this changes
Stacked on #1544 (the engine and kernel-contract registration), which stacks on #1526 (the runtime and the Q4 projection); part of #1420. GitHub cannot base this on #1544's fork branch, so the diff here also contains #1544's and #1526's commits — they are already up for review in those PRs; review the last 2 commits here. One decode token on the Vulkan backend took about 496 separate submits, each with its own fence wait.
Engine.decodeDrawnow records the whole token in one command buffer with one submit and one fence wait: the fed token's upload, the embed, all 24 layers, the head, the GPU greedy draw, the 12-byte chosen-id copy and, when asked, the full 496,640-byte logits row. The backend's decode seams (queue and verify) call it. No shader, dispatch order, barrier or arithmetic changes, so output is byte-identical. Five source files change (commands.zig,dispatch.zig,greedy.zig,engine.zig,backend.zig), plus a per-token timer in the model probe (separate first commit).Making one command buffer safe needed two things the per-submit path hid:
Failure handling is unchanged: a failure before the submit aborts the batch and poisons the engine until reset; a timeout or an in-flight failure still ends the process before anything is freed; the visible position advances only after the fence.
Receipt
zig build test -Dvulkan=trueon the build host (Debug): 2177 of 2217 tests passed, 3 skipped, 37 failed. Every failure is theoriginals_testmodule insidetest-lane-api-host(host snapshot/rollback file tests); the same step on the unmodified Native Vulkan backend for Qwen3.5-2B (opt-in): engine and kernel-contract registration (stacked on #1526) #1544 head f280f25 fails with the same test names and the same 376/388 count on this host, so they are pre-existing environment failures, not from this change. The three Vulkan host test groups pass; one earlier run of those groups had a single transient test-binary failure that did not reproduce on any later fresh run, including the full-matrix run. The branch cross-builds for aarch64-linux-gnu in ReleaseSafe: 25/25 default steps plus the probe step; the model probe ELF tf-qwen35-model is 5801656 bytes, sha256 11fd507f47120e5e41f437dc30eb356337fc4f57d307f84b32521e931e9b9ca1.Notes