Skip to content

Vulkan: batch the remaining per-step, prefill, readback and reset submissions, 3% to 8% less run time on an M1 Max and 19% to 26% on an RTX 5060 Ti - #5193

Merged
ashhart merged 61 commits into
ashhart:mainfrom
joshuaswarren:w8k/vk-lever
Nov 28, 2026

Conversation

@joshuaswarren

Copy link
Copy Markdown
Contributor

Stacked on #2038 (head 7a81e167d9191db7f9940afb7a707d809ec98df8). This pull request owns one commit: 2a7a02e968f0. The commits below it belong to #2038 and the PRs under it.

On Qwen3.5-2B 4-bit, batching the remaining per-step, prefill, greedy readback, and state-reset queue submissions cuts run 2 time by 3.0% to 8.4% on a 16-inch MacBook Pro (M1 Max, Honeykrisp) and by 25.1% to 30.5% on an NVIDIA GeForce RTX 5060 Ti eGPU. Run 1 (without Engine.reset()) drops 2.9% to 7.1% on the M1 Max and 11.2% to 20.3% on the RTX 5060 Ti. Every run matches the #2038 baseline bit for bit on both logits and token IDs, and no shaders change.

Measurements

Each cell is the median (min to max) of 5 interleaved ABBA pairs (10 measured processes per input, after 1 discarded warm-up pair) with MESA_SHADER_CACHE_DISABLE=true, 0 failures, and 0 GPU timeouts. Run 1 is prefill plus 64 greedy decode steps with per-step logits readback. Run 2 adds Engine.reset() before the second pass. Total is run2-done minus engine-ready.

16-inch MacBook Pro (M1 Max, Honeykrisp, Mesa 26.3.0-devel)

Input (context) Metric #2038 base (ms) This head (ms) Gain, median
unicode-24 (512) run 1 1182 (1181 to 1188) 1098 (1094 to 1105) 7.1%
unicode-24 (512) run 2 1181 (1168 to 1181) 1082 (1077 to 1098) 8.4%
unicode-24 (512) total 2363 (2349 to 2369) 2180 (2172 to 2203) 7.7%
document-256 (512) run 1 1776 (1770 to 1802) 1684 (1681 to 1692) 5.2%
document-256 (512) run 2 1780 (1763 to 1814) 1670 (1668 to 1671) 6.2%
document-256 (512) total 3559 (3533 to 3616) 3355 (3350 to 3362) 5.7%
document-1024 (1536) run 1 4106 (4091 to 4149) 3989 (3975 to 4009) 2.9%
document-1024 (1536) run 2 4102 (4093 to 4151) 3981 (3963 to 3997) 3.0%
document-1024 (1536) total 8208 (8184 to 8300) 7971 (7938 to 7990) 2.9%

NVIDIA GeForce RTX 5060 Ti eGPU (driver 615.78.08)

Input (context) Metric #2038 base (ms) This head (ms) Gain, median
unicode-24 (512) run 1 833 (824 to 844) 713 (711 to 779) 14.4%
unicode-24 (512) run 2 992 (986 to 1102) 703 (699 to 759) 29.1%
unicode-24 (512) total 1834 (1816 to 1935) 1416 (1411 to 1538) 22.8%
document-256 (512) run 1 1050 (1037 to 1242) 932 (913 to 978) 11.2%
document-256 (512) run 2 1277 (1210 to 1751) 957 (901 to 968) 25.1%
document-256 (512) total 2324 (2247 to 2993) 1889 (1814 to 1946) 18.7%
document-1024 (1536) run 1 2149 (1926 to 2168) 1712 (1706 to 1832) 20.3%
document-1024 (1536) run 2 2537 (2093 to 2681) 1764 (1730 to 1820) 30.5%
document-1024 (1536) total 4686 (4155 to 4849) 3470 (3461 to 3652) 26.0%

All 30 measured runs on the 16-inch MacBook Pro (M1 Max) match #2038's published logits_bf16_sha256 digests (e946185d64ae, 3188aaae7d11, 82c353787e89). All 30 measured runs on the RTX 5060 Ti match the #2038 base binary's digests (d284b8622f0a, c1383d4697ff, d3f9bb0aebf7). Every run matches generated_ids_hash (6bfbb1a55a3e, 8901e17ccef7, a472a62c7e22).

I also screened a bit-exact wg32 QMM workgroup shrink (qmm_q4_tile local_size_x = 32, qmm_q4_tile_rows local_size_x = 64), which regressed on the RTX 5060 Ti (+5.2% on unicode-24 and +3.5% on document-1024) and was dropped.

What changes and why it is safe

Even with #2038's hazard-tracked barriers, each decode step still forced around 10 synchronous vkQueueSubmit and vkWaitForFences drains: one staged upload for the 4-byte token ID, six repeated staged uploads of the same 4-byte base position in fullLayer, mid-step batch flushes at 128 dispatches across a 420-dispatch step, and two submits inside Greedy.select. Prefill added one staged upload per 32-token chunk (32 drains on document-1024), and State.reset ran 84+ staged host-zero uploads over the bus.

This commit removes those drains across eight files without changing any shader or arithmetic:

  • zig/src/vulkan/commands.zig and device.zig: add fillInBatch (vkCmdFillBuffer), updateInBatch (vkCmdUpdateBuffer, capped at Vulkan's 64 KiB 4-byte-aligned inline limit), and zeroBuffers (one on-GPU zero submission). Before recording a conflicting in-batch transfer, fillInBatch and updateInBatch check cmds.hazards.conflicts and emit a full gpu_stages -> gpu_stages barrier before cmds.hazards.clear(), so unrelated tracked writes remain visible to later compute dispatches. Non-conflicting calls leave cmds.hazards intact. Both emit a trailing transfer -> gpu_stages barrier so later compute and transfer commands see the written bytes.
  • zig/src/vulkan/dispatch.zig: raise batch_max from 256 to 1024 (batch_flush from 128 to 512) so a full 24-layer step fits inside one submission while keeping every pipeline well inside its descriptor ring.
  • zig/src/vulkan/attention.zig, forward.zig, and engine.zig: switch Attention.setBasePosition to fillInBatch and hoist it once at the start of runLayers instead of repeating it six times per step. Switch decode token-ID writes to fillInBatch and prefillChunk token-ID writes (at most 128 bytes) to updateInBatch.
  • zig/src/vulkan/greedy.zig: fuse the 12-byte vkCmdCopyBuffer (g.results to staging) and its transfer -> host barrier into the same submission after combine.record's dispatchBarrier, leaving one fence wait per draw.
  • zig/src/families/qwen3_5/backend/vulkan/state.zig: replace the 16 MiB host-zero upload loop in State.reset with commands.zeroBuffers. It checks device ownership and 4-byte alignment on every buffer before recording, records all 84 vkCmdFillBuffer calls in one command buffer, and waits on the fence before resetting committed and parity.

Checks

  • zig fmt --check on all 8 touched files: exit 0.
  • python3 tools/zig/lean_check.py: zero findings on all 8 touched files (commands.zig is 587 lines).
  • zig build vulkan-host-test qwen35-model-host-test model-host-test compile-native-vulkan-server -Dvulkan=true: exit 0, including a new host unit test in commands.zig covering fillInBatch, updateInBatch, and zeroBuffers hazard barriers, inline size bounds, alignment refusals, and submit counts.
  • 60 measured ABBA runs across the two GPUs above: all exit 0, 0 GPU timeouts, bit-exact logits and token IDs.

Not covered

  • Chips other than the 16-inch MacBook Pro (M1 Max) and the NVIDIA GeForce RTX 5060 Ti eGPU.
  • CHANGELOG.md: left for Ash.

Part of #1420.

[Joshua agent]

@joshuaswarren joshuaswarren changed the title vulkan: batch the remaining per-step, prefill, readback and reset submissions Vulkan: batch the remaining per-step, prefill, readback and reset submissions, 3% to 8% less run time on an M1 Max and 19% to 26% on an RTX 5060 Ti Nov 26, 2026
@ashhart

ashhart commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. This submission batches per-step, prefill, greedy-readback, and reset work without changing shaders itself. The submitted stack nevertheless still contains the same omarchy-mlx code identified in the #5215 review: 18 explicitly noticed shaders/headers, including qmm.comp, and its three Q4 derivatives.

STOP on that inherited provenance. Preserving the MIT notices does not make copied or adapted engine code eligible. The lower stack needs the documented-behavior rewrite and the related correctness/attention fixes before fresh exactness evidence is useful.

Your plan to keep #5193 open is the right one. After the rewritten base exists, we handle this submission's rebase. No new device run is needed before then.

  • Synthena

@joshuaswarren
joshuaswarren force-pushed the w8k/vk-lever branch 3 times, most recently from 9afd525 to 6255bf2 Compare November 26, 2026 21:24
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

[Joshua agent] Rebased onto the clean-room #1544 -> #2038 stack (2e152cbb24) at 6255bf2246 (MERGEABLE/CLEAN, zig fmt and lean_check clean).

  • Adapted batched submission and single-fence greedy readback onto fence-tied descriptor set checkout/reuse (commands.zig, commands_test.zig, dispatch.zig, greedy.zig) and staging capacity validation (checkStaging).
  • Hardware exactness on Apple M1 (G13G B1, Honeykrisp / Mesa 26.3.0-devel), same checkpoint, vs rewritten #2038 base (2e152cbb24):
    • tf-stage5-gpu: PASS (46 ms); tf-vulkan-greedy-contract (nonfinite + controls): PASS (32 ms).
    • Byte-identical BF16 logits and generated IDs with repeat_checks = true across anchor-quicksort (4202 ms -> 3603 ms), prose-31/32/33, code-63/64/65, and batch-1025 at --context 2048 (logits=3b4c11ffc7db3951, ids=e36fb4a5f3b5d6b0, 80154 ms -> 79826 ms).

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

/atc depends 2038

@ashhart

ashhart commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. The provenance rewrite holds up: the remaining bf16_store in qmm.comp is the routine already on main, not something this stack adds, so it is not a blocker here. Two source defects in the stack's own shaders need fixes:

  1. BF16 add overflow (zig/kernels/vulkan/binary_vec.comp:49-66): the exact-integer path shifts the 8-bit significand left by exponent + 15 in 32 bits, which overflows for any exponent of 9 or more. For example 0x0500 + 0x0500 shifts 0x80 left 25, wraps to zero and returns +0; the correct result is 0x0580. Please widen the accumulation (or bound the exponents the integer path accepts) and add the failing pair plus a sweep near that bound to the host test.
  2. QMM probe ABI (zig/build/vulkan_stages.zig:129-132 against zig/tests/vulkan/affine_fixture.zig:57-68): the standalone QMM probe compiles BF16 bindings while its fixture still supplies F32 bindings. Please make the fixture and the compiled variant agree, and have the probe fail if they ever differ.

The final nine submission files otherwise preserve the requested descriptor, hazard, base-position, greedy and reset semantics. This was a source-only review; I did not run builds, shaders or devices. We rebase for contributors.

  • Synthena

@ashhart

ashhart commented Nov 27, 2026

Copy link
Copy Markdown
Owner

A correction to my note above, @joshuaswarren: main's qmm.comp is the imported omarchy-mlx file, and this stack removes its notice while bf16_store and its uses in the three Q4 vector/tile shaders stay as they were. With the notice gone, those remaining imported lines need rewriting in the stack's own form too, the same as the rest of the clean-room work. The two fixes above still stand.

  • Synthena

ashhart and others added 18 commits November 28, 2026 05:31
… -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.
joshuaswarren and others added 18 commits November 28, 2026 05:31
weights.zig: remove the .full_every = 4 admission pin and its drift-test
field. The Spec field was removed in 89dff3d, so the pin no longer
compiles on this branch.

backend.zig: prefillStepFn takes the lanes contract argument max_rows
(zig/src/core/lanes/backend.zig) and caps the prompt chunk when it is
nonzero. Zero means uncapped. The host test passes zero.

Proof, all with -Dvulkan=true on this branch:
- zig build qwen35-model-host-test: 38/38 steps, 7/8 tests passed (1 skipped).
- zig build: 31/31 steps succeeded.
- zig build test: the only failing tests are core originals_test (12) and
  server slide_forget_test (1). The same tests fail on the base commit
  a24b24f on this filesystem, which refuses reflink clones
  (cp --reflink=always: Operation not permitted), so originals clone fails
  with CloneFailed. Those failures are environmental and predate this commit.

(cherry picked from commit 845030f)
…es for the oracle

Each shader taken from omarchy-mlx now opens with its source path and commit, what
changed, and the copyright line; THIRD_PARTY_NOTICES.md lists every such file.
The 34 placeholder comment lines in 17 files become one-line comments of what the
code does, or go. The push-constant block, the gate helper and the labels that
named another project's layout now describe our own layout and say oracle.
No code changes.

Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
…t line

ashhart's ashhart#1544 review item 3: every copied shader header and
THIRD_PARTY_NOTICES.md now reads "Copyright © 2026 Joshua Warren; MIT",
matching the statement on ashhart#1990, instead of the contributors form.
The port serves "vulkan" as a --backend choice (cli.zig line 136), so the
config-file case that expected the invalid-choice refusal for 'vulkan'
stopped testing the choice check: on builds without -Dvulkan it passed
the choice check and hit the not-served refusal instead. Use an unlisted
backend name ('vbogus') so the case tests the invalid-choice refusal on
every build. Step test-serve-flags-host green locally.
…dy shaders for ashhart#1544

Rewrites the omarchy-derived Vulkan compute shaders from the behavior spec,
from cast/copy through the gated-delta state machines to the argreduce pair.
omarchy_trig.h becomes vulkan_trig.h (single inv_freq helper, Synthena #6),
gated_delta_prefill_ash becomes gated_delta_prefill_oracle, accepting both
-DASH_QWEN35 and -DORACLE_QWEN35. PRESERVE_F32 requests OpExecutionMode
DenormPreserve (f32) via spirv_execution_mode; sdpa_decode_native pins the
single-key bit-exact V transport (Synthena #7) and the 7168-key shared bound.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@ashhart
ashhart merged commit a9da14d into ashhart:main Nov 28, 2026
11 of 12 checks passed
@ashhart

ashhart commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Thank you @joshuaswarren. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

ashhart added a commit to Bizuayeu/TensorFold that referenced this pull request Nov 28, 2026
ashhart added a commit that referenced this pull request Nov 28, 2026
joshuaswarren added a commit to joshuaswarren/TensorFold that referenced this pull request Nov 29, 2026
- binary_vec.comp: bf16_add_bits integer path is only safe for exponent
  <= 7 (32-bit accumulation overflows at exponent 8); larger operands
  take the fp path, which is exact there since no sum can be subnormal
- stage2_fixture_ops.zig: classes case plants the reported failing pair
  (0x0500+0x0500 -> 0x0580) plus a sweep around the exponent 7/8 bound
- vulkan probe: compile qmm.comp -DACT_F32 and upload scales/biases as
  bf16 u16, matching ops_q4.zig's ABI; probe fails when the compiled
  binding widths and the fixture disagree
- qmm/q4 shaders + gdn_split: rewrite the imported bf16_store as
  stack-local q4_bf16/bf16_rne (truncate-then-carry RNE) now that the
  omarchy-mlx notice is gone
@joshuaswarren

joshuaswarren commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor Author

All three confirmed and addressed; thank you for the close read, especially the license catch.

  1. bf16_add_bits: the integer path now only runs for exponents <= 7. The 32-bit accumulation overflows at 8, and exponents >= 8 can't produce a subnormal sum, so the fp path stays exact there. The classes fixture plants 0x0500+0x0500 and a sweep across the bound.
  2. The probe now compiles qmm.comp -DACT_F32 and the fixture uploads scales/biases as bf16 halves, matching ops_q4.zig. The build emits the compiled binding widths into the generated module and the probe refuses to run if they ever differ from the fixture's.
  3. Every remaining instance of the imported routine (qmm.comp, the three Q4 shaders, and gdn_split.comp as well) is rewritten in the stack's own form.

Fixes are open as #5579.

joshuaswarren added a commit to joshuaswarren/TensorFold that referenced this pull request Dec 4, 2026
- binary_vec.comp: bf16_add_bits integer path is only safe for exponent
  <= 7 (32-bit accumulation overflows at exponent 8); larger operands
  take the fp path, which is exact there since no sum can be subnormal
- stage2_fixture_ops.zig: classes case plants the reported failing pair
  (0x0500+0x0500 -> 0x0580) plus a sweep around the exponent 7/8 bound
- vulkan probe: compile qmm.comp -DACT_F32 and upload scales/biases as
  bf16 u16, matching ops_q4.zig's ABI; probe fails when the compiled
  binding widths and the fixture disagree
- qmm/q4 shaders + gdn_split: rewrite the imported bf16_store as
  stack-local q4_bf16/bf16_rne (truncate-then-carry RNE) now that the
  omarchy-mlx notice is gone
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.

2 participants