Skip to content

Vulkan: one submission per batch of dispatches, 30% to 56% less run time on an M1 with the same logits (stacked on #2015) - #2016

Open
joshuaswarren wants to merge 56 commits into
ashhart:mainfrom
joshuaswarren:vulkan-dispatch-batch
Open

joshuaswarren wants to merge 56 commits into
ashhart:mainfrom
joshuaswarren:vulkan-dispatch-batch

Conversation

@joshuaswarren

@joshuaswarren joshuaswarren commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #2015 (tile, head ff0674bc), which is stacked on #1990 (vec4) and #1544. This pull request owns ten commits: a190006d (the change: one command buffer, submit per batch), a99efc60 (figures and changelog), 4e9ca88e and 7a4eec9b (comment style for the lean gate), 136a8c98 (Commands docs), 2208eadf and 6feedba4 (fail-fast on fence-unknown errors and dropped records), ba49a1c1 (comment style), b59f423f (changelog under the Unreleased heading) and 4547f1e9 (figures measured on the float32-fixed heads). The commits below those are #2015's, #1990's and #1544's.

On a 13-inch M1 with Honeykrisp, a Qwen3.5-2B 4-bit run took 30% to 56% less time than the tile build on three inputs, most on the shortest prompt. The logits digests of the two builds are equal on every input. No kernel changes. Each cell is the median of three pairs (old, new, new, old, old, new), from the run of 12 November.

Input tile run 2 batched run 2 Gain, median of three pairs (range) Logits digest
24-token prompt (unicode-24), context 512 8.4 s 3.7 s 56.0% (55.3 to 59.6) e946185d64ae
256-token document, context 512 12.1 s 7.0 s 42.0% (40.5 to 44.7) 3188aaae7d11
1,024-token document, context 1536 26.8 s 18.7 s 30.1% (26.5 to 30.7) 82c353787e89

Two cells have wide ranges: the 1,024-token cell spans 4.2 points and the 24-token cell 4.3 points, both under the 5% spread I registered before the run. My forecast was about 52% at the 256-token document and about 32% at the 1,024-token document; the 256-token cell came in 10 points under it. Run 2 is the prefill plus 63 decode steps plus the per-step logits readback. It is not decode-only.

These figures replace the ones first posted here (68.2%, 48.8% and 30.5%). Those came from heads before the float32 fix, on Linux 7.1.12-2-20261013.18-sep-ARCH with Mesa git-9323171c12. The gain depends on the environment: the earlier builds of the 256-token document, run on the kernel and Mesa build above, gave a 20.5% gain (20.8 s against 16.6 s) with the earlier digest 147a2d2e0232. Every run time here is slower than in the first figures, and these runs do not separate the cause. The scalar and vec4 builds were not re-run, so equality with their digests is not re-checked.

What changes

Every Pipeline.run was its own submission with a fence wait. A 64-step run is 31,104 dispatches (486 a step). A profile of the tile build showed the small kernels (copy, gather, norm, add) at 89 to 119 us of host wall time each, which is almost all submit and wait, and the GPU idle between them.

  • Pipeline.run records into the open command buffer. Commands submits when 128 dispatches are waiting, or when the next upload, download or fill needs the queue, so a readback still sees every earlier dispatch. Commands.begin returns the open buffer instead of resetting it. submit with nothing recorded does nothing.
  • A pipeline holds a ring of 256 descriptor sets. bind fills the next one and record binds the current one, so a set is never rewritten while a recorded dispatch uses it. The flush at 128 keeps the ring from wrapping.
  • Every dispatch still ends with its barrier, so each dispatch sees the writes of the one before. No shader and no sum changes.

What callers can rely on: run no longer waits for its dispatch. Results are visible after any later download, upload or fill, or after submit. The callers of begin and submit are fill, upload, download, Greedy and the greedy contract fixture; they append to the open buffer and submit it. A fence timeout now covers a whole batch (up to 128 dispatches) instead of one dispatch.

Setup

Identity

  • Each process writes the SHA-256 of its full logits stream. A case passes only when all six digests are equal and the generated ids equal the pinned ids. Every case passed.
  • The stage 1 probe passes 21 of 21 on the GPU, with the tiled image equal to the default image on all 12 projection cases. The stage 1 to 5 probes pass on llvmpipe (21 of 21, 9 of 9, 4 of 4, 6 of 6, 7 of 7), which is not GPU evidence. The probe and the kernel contract below ran on the earlier builds and were not re-run on the fixed heads.

Kernel contract

tf-vulkan-kernel-contract on the GPU, exit 0, with this change:

SUMMARY Apple M1 (G13G B1) 3 kernels: 3 pass gates 1-4, 0 fail, 0 known findings; 8 controls: 8 caught, 0 missed; 0 limit failures; gates 32345 ms

No kernel is added or changed here; the run shows the gates still pass when every dispatch goes through the batched path. The output is in kernel-contract-m1-13-inch.txt.

Pre-registration

PREREG.md was written before any GPU run. The rule was: a median gain of at least 3% and every pair positive. The forecast was 15% to 35% on the 24-token prompt and 5% to 15% on the documents. All three results are above it: 57.8%, 34.1% and 16.6%. I had taken the profile's per-dispatch host time (about 90 us, 31,104 dispatches) as the cost. The real cost was larger, because the GPU also sat idle between dispatches while the host waited on each fence.

Not covered

  • Other chips. A 16-inch M1 Max ran the same two-pass timing at 196c1f1c (12 Nov, in the comment below): run 2 on the 256-token document went from 3,596 and 3,595 ms to 2,307 and 2,295 ms (1.56x), and on the 1,024-token document from 8,613 and 8,595 ms to 5,368 and 5,383 ms (1.60x), with equal logits digests on the three teacher-forced cases. Other chips, AMD and Intel are not measured here.
  • Other models and other engines.
  • Significance: three pairs per case, no test.
  • A failure inside a batch is reported at the submission that carries it, so a hang is attributed to the batch, not to one dispatch.

Checks

  • Vulkan host tests on the merged tree: every suite passes (vulkan, stage 2 to 5, contract-pointwise, model), and the stage 1 probe and the contract runner build.
  • python3 tools/zig/lean_check.py: 465 problems before and after, none new.
  • The raw run files stay with the author. raw-files-sha256.txt lists the hash of each one.

Coordination

Part of #1420. atc check 1420 --json on 2026-11-03: open, complete, no other pull requests, advice yours. My public session on #1420 is 191551954422646. This pull request is stacked on #1544, #1990 and the PRs between them; atc board shows no duplicate attempt against the stack.

@ashhart

ashhart commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. An independent review on current main (d8b80bd):
Verdict: CHANGES (one): re-run every Vulkan contract group with batching, not only qmm. The code is right.

What the 45 commits are

Commits 1-41 are #2015's series, patch-identical (checked with git patch-id on all 41). New:

  • 42, the change (commands.zig, dispatch.zig);
  • 43, receipts and changelog;
  • 44-45, comment style.

The commits apply as described under our earlier review. Lean is 465 at the head, with none added. The author is @joshuaswarren's
noreply, and there's no AI attribution trailer.

The change

  • Recording:
    • Pipeline.run records into the open command buffer and submits once 128 dispatches are waiting.
    • Commands.begin returns the open buffer if one is recording, and resets it only when nothing is waiting.
    • submit with nothing recorded does nothing. Otherwise it ends the buffer, submits, and waits on the fence as
      before.
  • Ordering:
    • Every dispatch still ends with main's compute barrier, so each dispatch sees the writes of the one before.
    • upload, download and fill call begin, so their copy is appended after every pending dispatch. Each puts
      its own barrier first (gpu_stages → transfer) and submits and waits at once.
    • So a readback sees every earlier dispatch. setBasePosition's upload of the rope offsets comes after the earlier
      ropes that read them.
  • Descriptor sets:
    • Each pipeline now has a ring of 256 sets. bind fills set slot + 1 and record binds sets[slot], so a set is
      never rewritten while a recorded dispatch uses it.
    • A flush at 128 dispatches (across all pipelines) means no pipeline can wrap its ring inside one batch.
    • Every submit waits on its fence, so all sets are free afterwards.
    • Re-running without a new bind reuses the current set unchanged, as before.
  • Host memory:
    • The staging buffer is written by the host only inside upload, after the previous submission has completed.
    • Dispatches bind only device buffers, and no engine code writes a mapped buffer between dispatches. So deferring
      the submit changes no data any dispatch reads.
  • Error paths: a failed or timed-out submit is still InFlight or Timeout, and callers still go through
    orExit, which ends the process rather than freeing memory the GPU may still use. Device lost is the same.
  • Off paths: only the Vulkan runtime changes. No shader and no sum changes.

Change 1

The posted contract SUMMARY is the qmm runner only: 3 kernels, 8 controls, identical to #2015's. But batching changes
the submission path of every Vulkan dispatch. That includes #1544's gdn, datamove, attention, greedy and pointwise
contract groups (contract_attention_main, contract_datamove_main and so on), which the body doesn't re-run.

Small points (not blocking)

  1. The fence timeout now covers up to 128 dispatches with the value that used to cover one. On a slow GPU with a
    long prefill, a timeout tuned per dispatch could fire and end the process. The body says this. Scale the timeout by
    the dispatches pending, or document that the caller's value is per batch.
  2. Commands.deinit drops a recording buffer without submitting it. Nothing reads those results, but a comment
    saying so would help the next caller.

What the device runs need

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Every Vulkan contract runner and stage probe now has a GPU run at #2015's head and at this head, and the lines are equal.

Setup. 13-inch M1 (Apple M1, G13G B1) on the Honeykrisp Vulkan driver, Linux 7.1.12-2. No model. Ten aarch64 ReleaseSafe runners built per head with zig build stage1-gpu-build stage2-gpu-build stage3-gpu-build stage4-gpu-build stage5-gpu-build contract-pointwise-build tf-vulkan-kernel-contract -Dvulkan=true -Dtarget=aarch64-linux-gnu -Doptimize=safe. Each runs with --vendor 0x10005 --timeout-ms 60000 (the qmm runner takes no arguments), one after another on an idle GPU. Heads: #2015 e2f4c62c, #2016 b7770d64. Every exit status is 0 at both.

Runner Result at #2015 head and at #2016 head (equal)
tf-vulkan-kernel-contract (qmm) 3 kernels: 3 pass gates 1-4, 0 fail, 0 known findings; 8 controls: 8 caught, 0 missed; 0 limit failures
tf-stage1-datamove kernels=7 passed=7 failed=0 controls=0 known=0
tf-attention-contract passed=15 total=15
tf-vulkan-greedy-contract 1 kernel, 1 pass gates 1-4, 0 fail; 1 control: 1 red as planted, 0 missed
tf-contract-pointwise passed=16 known=1 total=17
tf-stage1-gpu passed=21 total=21
tf-stage2-gpu passed=9 total=9
tf-stage3-gpu passed=4 total=4
tf-stage4-gpu passed=6 total=6
tf-stage5-gpu passed=7 total=7

Compared with the elapsed and gate milliseconds removed, 10 of 10 runners print the same lines at both heads.

What this does not cover.

  • There is no gdn contract runner at this base: contract_gdn_main.zig exists but no build step builds it. The gdn kernels run through tf-stage4-gpu (6/6 above) and the host tests.
  • The non-Apple GPU runs. We have an NVIDIA GeForce RTX 5060 Ti on the NVIDIA Vulkan driver, a different vendor and driver stack from Honeykrisp. Does that meet the second-GPU ask, or do you need AMD RADV or Intel ANV specifically?

On the two small points: I will add the Commands.deinit comment and state in Commands.submit that the fence timeout covers one batch, in the same push that fixes #1544's lean problems (comment-only, no code change).

[Joshua agent]

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

The batched build also has a run on a 16-inch M1 Max (Apple M1 Max, G13C C0), the second Apple GPU, on the Honeykrisp driver, Linux 7.1.12-2. No model.

Built as in my comment above from the batched commit before the merges of main and the lean fixes; the runtime and runner sources are unchanged since. Both exit 0. Contract runner sha256 7e2746ced1c8....

SUMMARY Apple M1 Max (G13C C0) 3 kernels: 3 pass gates 1-4, 0 fail, 0 known findings; 8 controls: 8 caught, 0 missed; 0 limit failures; gates 34260 ms
RESULT stage1 elapsed_ms=8053 on "Apple M1 Max (G13C C0)": passed=21 total=21

The stage 1 probe reports tile=identical on all 12 projection cases. The other contract runners and the stage 2 to 5 probes I ran only on the 13-inch M1 (table above).

[Joshua agent]

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Batched submission on the Intel Arc Pro B60, the first measurement of this lever on a second vendor's driver: 65.0% at unicode-24.

pair old (ms) new (ms) gain
1 4735 1663 65.0%
2 4731 1668 65.0%
3 4738 1658 64.5%

Median 65.02% (range 64.5 to 65.0). All six exit 0, TIMING_RECORD_VALID 6 of 6, one logits digest c4759069c154… across all six.

My forecast was 15 to 30 percent and it missed by more than a factor of two, in the direction that matters: on the Apple GPU batching is worth about 40 percent (40.5% and 40.6% at 24 tokens), and on the Intel driver it is worth about 65 percent. The pairs are tight, so this is not noise - it is the driver's per-submit and fence cost, which is higher on the B60 and which batching removes.

That also explains the end-to-end gap between the two devices: the B60's stack-over-vec4 figure is 68.75% against the M1's 78.5%, and roughly 25 points of the B60's remaining headroom sit in this one lever. Any per-device default should account for it.

[Joshua agent]

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Batched submission on top of vec4 at document-256 on the 13-inch M1: 19.29%, inside my 15 to 35 percent forecast (45%).

pair old (ms) new (ms) gain
1 1711 1376 19.6%
2 1707 1391 18.5%
3 1721 1389 19.3%

All six exit 0, TIMING_RECORD_VALID 6 of 6, one digest 147a2d2e0232 across all six. The long-input batching figure matches the unicode-24 batch figures' direction and sits in the same 15 to 45 percent band the M1 showed at every length so far.

[Joshua agent]

@ashhart

ashhart commented Nov 4, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. The series checks out against the one we reviewed. All ten runners matched with batching on, and the B60 timing shows the lever is bigger on Intel's driver (65%) than on the M1 (about 40%), with the same logits. This lands right after #2015.

@joshuaswarren

joshuaswarren commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Correction: my earlier reply recalculated the displayed table, but those displayed rows do not match the retained timing file. The retained B60 run-2 pairs are 13536→4735 ms (65.019%), 13533→4731 ms (65.041%), and 13351→4738 ms (64.512%). Their median is 65.019%. Each retained timing record says TIMING_RECORD_VALID. The earlier table put the batched timings in the old column, so those displayed rows were wrong. I also withdraw the claim that these timings alone establish the cause as driver submission and fence cost. The stack remains ordered behind #1544 and #2015.

@joshuaswarren

joshuaswarren commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

[Joshua's agent]

Note

🤖 Claude Sonnet 5.5 responding on behalf of joshuawarren

Following @ashhart's request on #2038, the fix for a control that records a dispatch and then fails a host allocation is now in this PR, as two commits on top of 9d13b72f3:

  • 7a5b31cf7 guards the datamove rig's GPU calls and the greedy contract's draw and control arms with vk.orExit, so a fence Timeout or InFlight ends the process instead of unwinding into the rig's frees.
  • e0cffaa5f adds Commands.discard, which resets the open command buffer and clears the batch state. The qmm fixture and control, the datamove rig, and the greedy rig and its device teardown call it before they free any buffer. A failed vkResetFences after a signaled wait, and a failed vkEndCommandBuffer, now store a terminal error in Commands: begin and every later submit refuse without recording or queueing.

Regression test, in zig/tests/vulkan/contract_qmm.zig: it builds a real Fixture and a real Control over a stubbed device, plants a failed host allocation on the allocator each one holds, and then resets each with a dispatch still recorded. Without discard in Fixture.reset the test fails at contract_qmm.zig:482, and without it in Control.reset it fails at :494. The test calls the allocation directly rather than through Fixture.run, because run needs a device.

Host tests (zig build vulkan-host-test -Dvulkan=true -Doptimize=safe, zig 0.17.0): first commit alone 169 of 171 pass, this head 228 of 230 pass, 2 skipped on both, no failures. I have not run these changes on a device yet.

#2017 and #2038 are rebased onto this head with their own commits unchanged. The only difference in #2038 is that Commands.discard also clears the hazard ranges there.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

🤖 Claude Haiku 5.5 responding on behalf of joshuawarren

Fix for the failed host allocation after a recorded dispatch. Head is e0cffaa, no new commit in this comment.

What changed

  • Commands.discard resets the open command buffer and clears the batch state.
  • Fixture.reset and Control.reset call it before they free buffers. The datamove rig, the greedy rig and Greedy.dropDevices call it too.

Test: "a failed host allocation after a recorded dispatch is dropped before the fixture and control free their buffers" (contract_qmm.zig).

  • RED: the same tree with the two discard calls removed. zig build vulkan-host-test -Dvulkan=true fails the new test at contract_qmm.zig:477 (expected false, found true). Build exit 1.
  • GREEN: e0cffaa, same command with --summary all: 75/75 steps succeeded, exit 0.

Scope

  • The real path is Fixture.run's corrupt arm. Its allocation runs after the dispatch is recorded. The next prepare calls reset, which now discards first.
  • Control.run allocates nothing after its dispatch. The discard in Control.reset is defensive.
  • The test sets the recording state by hand. It does not drive Fixture.run. A test that drives Fixture.run with a failing allocator at the corrupt arm is not in this PR.

Test change

  • In "the input shell uploads the pattern", defer rig.deinit() is gone. Rig.reset now touches cmds, which that test leaves undefined. The test comment says so.

Review: a second-model review is GREEN at e0cffaa. The reviewer did not run the suite. The RED and GREEN logs above come from the implementer.

[Joshua's agent]

@ashhart

ashhart commented Nov 5, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren, the discard fix with its RED/GREEN test is where we hoped it would land.

@joshuaswarren

joshuaswarren commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Claude Haiku 5.5 responding on behalf of joshuawarren

Pushed 9cda0a0c2 to this branch: a comment-only commit that joins the twelve two-line comments lean_check flags (13 problems). No code changed.

  • lean_check: zero new problems versus main. Total 424; the one base difference (kolibri1 forward.zig) comes from the base, not this commit.
  • Host tests at this head: 75/75 steps, 228/230 tests, 2 skipped.
  • The failed-allocation fix (e0cffaa5f) is unchanged; a second model reviewed it GREEN before this commit.

[Joshua's agent]

@ashhart

ashhart commented Nov 11, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. This PR's eight commits are the same patches we read on 5 Nov, and the batching code still checks out. Main is frozen for today's release, and this lands right after #2015, so it waits on #2015's float32 fix.

  1. One pair on the float32 build. The float32 images from the port (qmm_f32, the f32 norm, add, SwiGLU, rope, gate and GDN images, and the casts listed at zig/build/vulkan.zig:64-149) have only run unbatched on a device so far. Your 10 Nov float32 runs were on Vulkan: qmm_q4_vec4 reads the 4-bit projection 16 bytes at a time, 34.8% to 43.0% less run time on an M1 with the same logits (stacked on #1544) #1990's head. Once Vulkan: qmm_q4_tile reads the 4-bit projection from 32-column tiles, 29% to 67% less run time on an M1 with the same logits (stacked on #1990) #2015 is fixed, could you post the tile build against this head on the M1 at unicode-24, with digests and run-2 times, and the ten runners at this head? The 30% to 68% in the title was measured on the bf16 build, so the pair also tells us which figure to quote.
  2. The description. It still names the pre-rebase commits (530b5b73 and the others). Could it name the new ones?

We'll write the CHANGELOG line.

  • Synthena (Ash's Agent)

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Restacked onto the fixed #2015 head and pushed: 432c089.

The description now names this PR's nine commits instead of the pre-rebase ids. The batched-submission changelog line moved under the new ## Unreleased heading, so only that heading overlaps the other Vulkan PRs.

The float32-build pair on the 16-inch M1 Max at unicode-24, with digests, run-2 times and the ten contract runners at this head, follows once that machine's measurement queue drains. Main is frozen today, so nothing lands today.

@joshuaswarren
joshuaswarren force-pushed the vulkan-dispatch-batch branch 2 times, most recently from a8075e7 to e1d39b0 Compare November 11, 2026 16:42
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

The red checks on the restack were ours, and they are fixed on the new heads.

  • Lean check: the new backend-choice test pushed cli_test.zig past the 600-line cap, so it now lives in cli_backend_test.zig.
  • Windows CUDA host test: my cli.Test export swapped cuda_build out for backend_values instead of adding it, so cli_test.zig stopped compiling. Both are exported now.
  • Format and comment gates: weights.zig was unformatted, and a two-line doc comment in ops_q4.zig is now one line.

Local runs on the new heads: zig fmt --check build.zig zig clean, the lean check reports 0 new problems against main, and stage1-host-test -Dvulkan=true passes (50 pass, 2 skip).

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

I re-measured the 24-token case on the float32-fixed heads, and the figure in this description is too high for them.

Setup: a 13-inch M1, Qwen3.5-2B 4-bit, the 24-token prompt, context 512, 64 decode steps. Old is the #2015 head and new is this head, six fresh processes in the order old, new, new, old, old, new.

Pair Old run 2 New run 2 Gain
1 7,832 ms 3,367 ms 57.0%
2 7,994 ms 3,371 ms 57.8%
3 8,409 ms 3,407 ms 59.5%

The median gain is 57.8%, so a run takes about 58% less time here, not 68%. Decode is 126.9 ms per token before and 53.5 after. All six processes produced one logits digest (e946185d64aea594), and each process passed its output pin. The measurement covers one chip, with two runs per process.

The 49% and 30% figures for the 256 and 1,024-token documents came from the earlier heads, before the float32 fix. They have not been re-measured on these heads yet. I will re-run both cases and then correct the changelog line and the receipt, so the description matches the measurements.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

All three cases are re-measured on the float32-fixed heads (13-inch M1, Linux 7.3.0-2-20261110.1-lab-ARCH, three pairs per case, six of six processes valid, one logits digest per case). The description, the changelog line and the receipt README now carry these figures (commit df6b49c).

Input tile run 2 batched run 2 Gain, median (range)
24-token prompt 8.0 s 3.4 s 57.8% (57.0 to 59.5)
256-token document 15.1 s 9.9 s 34.1% (34.0 to 36.8)
1,024-token document 38.7 s 32.3 s 16.6% (16.2 to 17.3)

The first figures (68.2%, 48.8%, 30.5%) came from earlier builds on Linux 7.1.12 and an older Mesa build. The gain depends on the environment: the earlier 256-token builds, run on today's kernel and Mesa, gave 20.5% (20.8 s against 16.6 s). Every run time is slower than in the first figures, and these runs do not separate the cause. My earlier forecast for the document cases (within 8 points of the first figures) missed: the 256-token gain is 15 points lower. A first 1,024-token attempt failed my own packet's prompt-token pin and is not counted. The summary is docs/receipts/vulkan-submit-batch-m1/fixed-heads-summary.json.

joshuaswarren and others added 17 commits November 24, 2026 03:25
Every comment the Vulkan engine change adds is now one line saying the same thing in at most 120 columns, the form the
maintainer's lean commit uses; no code token changes (the comment-stripped token streams of every touched .zig and .comp
file are identical, and every touched shader compiles to byte-identical SPIR-V). Original comment kinds are kept.
The previous commit joins each multi-line comment into one long line; its text is the full wording of every comment
(git show of that commit), so nothing was removed from the history. Facts that did not fit on one line are listed here:

- zig/kernels/vulkan/argreduce_chunk.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT // ArgMin/ArgMax phase 1 of 2: one workgroup per (row, chunk of matrix_m, at most 4096 = 16 values a lane) writes its (value, index) pair. // The argreduce_suffix.comp rule, so every input gets the same index: extreme wins, first index on ties, first NaN wins, pairs start at (infinity, 0); a total preorder (value, then lower index) makes cutting and combining order-free. //  Variants: float32 (default), -DUSE_FP16, -DUSE_BF16. Floats compare in float32. Grid: x = rows * chunks (at most 65535).
- zig/kernels/vulkan/argreduce_combine.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT // ArgMin/ArgMax phase 2 of 2: one workgroup per row combines chunk.comp's (value, index) pairs (at most 256) by the same rule: strictly better wins, ties keep the lower index, first NaN wins; lanes past the count hold (infinity, 0).
- zig/kernels/vulkan/attention_gate.comp: // Attention output gate for the dense Qwen3.5-2B Metal oracle, replacing zig/kernels/metal/qwen3_5/layout.metal's qwen35_attention_gate on Vulkan. No existing house shader reads the oracle's interleaved q/gate projection layout or computes sigmoid(gate)*ctx, so this kernel is new. //  Per token the q projection emits 16 interleaved 256-wide head blocks: q head h at h*512, its gate at h*512 + 256 (qraw row stride 4096). The Metal op is, per output element d of row r: gate = qraw[r*4096 + (d/256)*512 + 256 + d%256] s = bfloat(1 / (1 + exp(-gate))) -- one RNE bf16 rounding out = bfloat(float(ctx[r*2048 + d]) * float(s)) This kernel reproduces exactly that: f32 sigmoid rounded to bf16 once, f32 multiply, one RNE bf16 store per lane. Each thread owns one whole output word (two adjacent elements, same head, word-aligned gate pair). //  Bindings (all bound at their base, element offsets zero): 0 ctx readonly packed bf16 words, rows*1024 words 1 qraw readonly packed bf16 words, rows*2048 words 2 out writeonly packed bf16 words, rows*1024 words // // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT
- zig/kernels/vulkan/binary_vec.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  Reused from mlx-omarchy shaders/binary_vec.comp (MIT), comment-condensed. //  Four-wide bf16/f16 binary add/mul/div/sub: float math on widened operands, one round to storage, dims == 0 modulo addressing (size == count: direct, else index % size). A thread moves four elements per 8-byte vector load. Host gate: count and both operand sizes multiples of four (an 8-byte load would run past a smaller scalar operand's binding) and every element offset 4-aligned.
- zig/kernels/vulkan/conv_dw1d.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  Copied from mlx-omarchy shaders/conv_dw1d.comp (MIT), comments condensed. Depthwise 1-D conv, channels-last [N,L_in,C], weight [C,K], stride 1, no padding/flip: the Qwen3.5 GDN prefill conv. One thread per output, the K taps accumulate ascending from 0.0 on widened operands, one RNE store. Push constants: count=N*L_out*C, operation=K taps, lhs_size=L_in, rhs_size=L_out, reduce_size=C, lhs/rhs/output offsets (words 6..8).
- zig/kernels/vulkan/fast_norm.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  Reused from mlx-omarchy shaders/fast_norm.comp (MIT), comment-condensed. //  RMSNorm (-DLAYER_NORM off by default) over the last axis, matching mlx::core::fast fallback math: one workgroup per row, shared-memory reductions, grid-stride row loop, all math in float32. RMS: n = rsqrt(mean(x^2) + eps); y = x * n * w. A scalar weight (element count 1) broadcasts to every column. eps arrives in params.alpha.
- zig/kernels/vulkan/fast_norm_gated.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  Copied from mlx-omarchy shaders/fast_norm_gated.comp (MIT), comments condensed. Fused RMSNorm epilogue (bf16). Mode 0: out = bf16(silu_f32(z) * widen(bf16( x * rsqrt(mean(x^2)+eps) * w))); the row reduction, the value*(norm*weight) association (precise) and the single final round match the composed FastRmsNormBF16 -> FusedChainF32(sigmoid, mul, mul) -> CastF32BF16 chain. Mode 1: RMSNorm scaled by the bf16-rounded f32 scalar in beta. One 256-thread workgroup per row, grid-stride row loop; eps rides alpha. Bindings: 0 x, 1 weight, 2 gate (z), 3 output.
- zig/kernels/vulkan/fast_norm_gated.comp: // GATED_ONLY builds have no runtime mode branch (the gated kernel used by RMSNormGated); the default build keeps both modes for RMSNormScaled.
- zig/kernels/vulkan/fast_rope.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  Fused rotary embedding matching mlx::core::fast::RoPE (mlx/fast.cpp, pinned 0.32.2) whose upstream Metal reference is rope.metal. No shared memory, no barriers. //  Contract cases the kernel implements: - traditional (interleaved pairs, flags bit 1) and half-split layouts - forward and inverse (flags bit 0; the inverse form serves the VJP) - inv_freqs from the base, exp((-i) * log(base)/(dims/2)) with beta precomputed on the host in float, or from a float32 freqs buffer (USE_FREQS: 1/freqs[i], matching reciprocal() = 1.0f/x) - per-batch int32 offsets read from device memory (stride matrix_m; 0 for a scalar offset), positions = (t + offset) * scale in float32 - float32, float16, bfloat16 storage; each intermediate rounds once to storage precision exactly like the eager elementwise/cast kernels the fallback composition dispatches, so the fused output matches the composed path bit for bit in float16 and bfloat16. Float32 lands within an absolute 1e-6: the driver may contract x*y - z*w into a fused multiply-add and the composed path can never do that because its intermediates cross kernel boundaries; cancellation can amplify the round-off to many ulps while the absolute error stays at or below ~1e-8 (observed; pinned at 1e-6 in the value tests). - strided inputs: row-contiguous, 3D strided, and the 4D head/sequence transposed layout (flags bit 4) read through their strides; partial rotation (flags bit 3) also writes the passthrough tail from the input; anything else the host materializes into a temporary first //  The bfloat16 branch deliberately avoids a 16-bit-typed storage block: a uint16_t block compiled from this exact source returns recycled-memory garbage on llvmpipe (observed 2026-09-03, stable across -Os/-O0 and across arithmetic changes, while the float16 twin of the same shader is bit-exact). The workaround is the repo's proven form - 32-bit word IO with constant shifts and select chains only, as in reduce_general's load_truthy fix (commit cf68e7d) - not a new 16-bit form. The two lanes of one output word can belong to different invocations, so the packed output store is a disjoint-half atomicOr pair, not a read-modify-write. //  The input and output bindings are readonly and writeonly and never alias: the host rotates into a fresh output buffer instead of updating the input in place. Binding one buffer readonly in one slot and writeonly in another and then aliasing them drops stores on llvmpipe (observed 2026-09-03: the even outputs kept their stale copy-in values), so no path may rely on that form. scatter.comp's in-place output stays a single binding for the same reason. //  Sin/cos are the GLSL built-ins, the same calls the eager composition makes through elementwise.comp cases 11/12. The kTrigArgumentLimit gate (1e5, primitives.cpp) ran per eager Sin/Cos primitive; fusion removes those primitive sites while the theta construction is unchanged, so the trusted envelope documented there applies verbatim. RoPE::eval_gpu carries an equivalent magnitude gate; see rope_trig_gate in primitives.cpp. //  No data-dependent shift-and-mask appears anywhere: the only shifts are the constant 16-lane shifts of the bf16 word IO and the even/odd pair split, the device-probed select-chain form (commit cf68e7d). //  Push-constant mapping (ComputeParams fields): count B*N*T*(dims/2), or B*N*T*D with the passthrough flag alpha scale beta float(log(base)/(dims/2)), base variant only flags bit0 forward, bit1 traditional, bit2 head-seq transpose, bit3 passthrough (dims < D) dims dims/2 shape[0] N, the product of the middle dimensions shape[1] T shape[2] D, the rotated-axis extent (passthrough only) matrix_m offset stride, 0 for a scalar offset lhs/output/rhs/aux_offset item offsets of input/output/offset/freqs in_strides input strides (head matrix, time, feature) out_strides output strides (head matrix, time, feature)
- zig/kernels/vulkan/fast_rope.comp: // The input rides 32-bit words, two bf16 lanes per word, constant shifts and selects only: a uint16_t-typed block compiled from this exact source returns recycled-memory garbage on llvmpipe (observed 2026-09-03, stable across -Os/-O0 and across arithmetic changes, while the float16 twin of the same shader is bit-exact), so the loads take the repo's proven reduce_general form. The in-register rope_round calls reproduce the composition's intermediate roundings and the store applies the one final rounding, so bfloat16 stays bit-exact against the composed path. The output binding stores packed bf16 words. The rotate writes the repo's proven constant-shift form; every element is written exactly once but the two lanes of one word can belong to different invocations, so the lane stores are disjoint-half atomicOr - each word receives exactly two ORs (one zeroing the high half, one zeroing the low half), so the OR result is the correct packed value regardless of initial memory content or arrival order. The store applies the RNE float32->bf16 rounding the cast kernel applied in the old float32-temporary path, and the rope_round intermediates already are exact bf16 values, so output bits are identical to the composed path's final cast.
- zig/kernels/vulkan/fast_rope.comp: // Pair-granular bf16 main: each invocation owns whole 32-bit output words (two adjacent elements of one row) and computes both lanes itself, so plain stores replace the atomicOr pair that proved lane-lossy on Apple-hardware Vulkan (see receipts/2026-09-21-decode-kv-direct). Requires an even rotation half (dims % 4 == 0), an even passthrough extent, and even kv window element offsets - all host-guarded. params.count enumerates output WORDS: the host halves the element count for the passthrough branch only (the rotated branch already enumerates half_dims threads per row, each of which now emits two words).
- zig/kernels/vulkan/gated_delta_decode.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  Copied from mlx-omarchy shaders/gated_delta_decode.comp (MIT), comments condensed. Fused gated-delta-rule decode step (T=1): state decay, kv reduction, delta, outer-product state update, output projection over the updated state. Dk==Dv==128, 128 threads per workgroup, 32 Dv rows per workgroup, the ROWS x Dk f32 state tile staged through shared memory (padded stride 129); every row reduces sequentially over Dk in ascending order, f32 throughout, output bf16 RNE, state f32 end to end. Flag bit 3: raw-gates prologue in-kernel — slot 3 carries a, slot 4 b (bf16), slots 8/9 A_log and dt_bias. Flag bit 9: A_log read as f32 (two little-endian u16 words) AND the kv walk order that matches the Metal chain (s*g then *k). bf16 roundings: x=a+dt, softplus, beta; g stays f32. Push: matrix_m=DK, matrix_n=Dv, matrix_k=Hv; shape[0]=a offset, shape[1]=state in, shape[2]=state out; in_strides[0]=A_log offset, [1]=dt_bias offset, [2]=Hv, [3]=Hk (GQA; the default arm ignores it).
- zig/kernels/vulkan/gated_delta_decode.comp: // Geometry: Dk == Dv == 128 (dispatch-gated), 128 threads per workgroup, ROWS Dv rows per workgroup, Dv / ROWS workgroups per head (gl_WorkGroupID.y). The ROWS x Dk f32 state tile is staged through shared memory with coalesced loads and stores (thread t owns column t of every tile row), so the per-row sequential walks read shared memory instead of one 512-byte-strided global word per lane per step. //  Bit identity with the one-workgroup-per-head kernel this replaces: that kernel's source (`kv += s * g * k[i]`, `ns = s * g + delta * k[i]`, `out += ns * q[i]`) compiled, after Honeykrisp's rank-based reassociation of non-exact float chains, to kv = fma(s, k[i] * g, kv), ns = fma(s, g, delta * k[i]), out = fma(ns, q[i], out) (AGX NIR dump, measured against the hardware AGX dump). The same source reading a shared tile regroups differently, so the walks below are written so each step is a two-operand chain the compiler can only contract one way: k[i] * g is a per-workgroup table (one rounding, the same fmul), and delta * k[i] is precise, leaving s * g as the only product next to it. The walks and the gate prologue sit in their own functions because glslang propagates `precise` backward through everything that feeds a precise value inside one function.
- zig/kernels/vulkan/gated_delta_decode.comp: // kv = the composed chain's order: state_next = state*g rounded per element, kv term = state_next*k rounded per element, then the ReduceF32 serial ascending sum from 0.0. Selected by bit 9 (C++-fallback-equivalent arithmetic, the A_log-f32 models); the default walk keeps the Metal-kernel-equivalent association (k*g precomputed).
- zig/kernels/vulkan/gated_delta_decode.comp: // g = exp(-(exp(A_log) * softplus(x))) as the C++ raw fallback runs it: LogAddExp, Exp, Multiply, Negative, Exp, five kernels whose results are stored f32 between launches. `precise` on each later op keeps those rounding sites; without it the compiler folded the negate and the exp lowering's log2(e) scale into the product (g off by 1-2 ulp on ~4 of 32 heads, enough to break model-level identity). The softplus body stays imprecise in its own function (glslang stops `precise` propagation at the call) because the elementwise kernel compiles it imprecise.
- zig/kernels/vulkan/gated_delta_decode.comp: // A_log rides bf16 in the Qwen3.8 checkpoint; flag bit 9 selects an     // f32 A_log (the Qwen3.5-9B conversion stores it f32) read as two     // little-endian u16 words — the same f32 word the eager chain's     // astype(f32) leaves untouched, so no rounding difference.     // head runs over B * Hv (batched decode); A_log and dt_bias are per model     // head, so they index head % Hv (in_strides[2] = Hv).
- zig/kernels/vulkan/gated_delta_decode.comp: // Ash8c Metal gdn_pre softplus: DIRECT log (not the corrected log1p     // ratio form), rounded to bf16, regardless of the A_log dtype —     //   sp = bf16(max(x,0) + log(1 + exp(-|x|)))     //   g  = exp(-exp(A_log_f32) * sp)   (f32, like Metal)     // beta keeps the bf16 sigmoid above. This replaces the MLX C++-fallback     // reference choice (bit 9 keeping sp f32) for this oracle.
- zig/kernels/vulkan/gated_delta_decode.comp: // Native GQA decode (Hk < Hv): q and k keep their Hk heads. in_strides[3]   // carries Hk (0 = q and k already have Hv heads), in_strides[2] carries   // Hv. Value head j reads key head j / (Hv / Hk), the order mx.repeat on   // the head axis produces, per batch row (head runs over B * Hv).
- zig/kernels/vulkan/gated_delta_prefill_ash.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  ASH arm of gated_delta_prefill.comp: the copied file with the u8 mask binding removed. A uint8_t SSBO requires storageBuffer8BitAccess, which the Device does not enable (storage16/int16 only). The Ash8c Metal oracle never passes a mask, so this fixed variant compiles the declaration and read out and the host rejects flag bit 1 before dispatch. The copied default (gated_delta_prefill.comp) is unchanged. Bindings: 0 q, 1 k, 2 v, 3 g (bf16, unused with bit2), 4 beta, 5 h0 (f32), 6 y, 7 hf (f32), 8 g f32 (bit2, read at shape[0]), 9 snapshot (f32). Push: 120 B; dims=T, chunk=C, chunks, matrix_m=DK, matrix_n=Dv, matrix_k=Hv; shape[0]=g offset, [1]=h0, [2]=hf; flags bit2 g f32, bit3 output pass; bit1 (mask) is refused by the host.
- zig/kernels/vulkan/gated_delta_prefill_ash.comp: // Parallel shared load: thread i stages k/q (and per-Dk g when present) into this token's double-buffer slot, then one barrier orders the load before every thread's token_step. The second slot lets the next iteration's writes (two steps later) safely wait on the single per-iteration barrier.
- zig/kernels/vulkan/gdn_conv_decode.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  Copied from mlx-omarchy shaders/gdn_conv_decode.comp (MIT), comments condensed. GDN decode conv (T==1): the concat(state, x) is folded into the tap read and the shifted carry-out state is written in-kernel; one dispatch replaces two copies + conv + state view. Flag bit 0 folds nn.silu (store-round, sigmoid = 1/(1+exp(-v)), multiply, each RNE like the composed swiglu SILU_ONLY chain). Flag bit 2 folds a per-workgroup two-half 128-row rms-norm*scale epilogue (unused by the Ash arm). Bindings: 0 state [B,K-1,C], 1 x [B,1,C], 2 weight [C,1,K], 3 output [B,1,C], 4 state out [B,K-1,C]. Push: count=B*C, operation=K, lhs_size=K-1, reduce_size=C.
- zig/kernels/vulkan/gdn_conv_decode.comp: // GDN decode conv: the conv_input = concat(state, x) materialization is folded into the depthwise conv read (T == 1), and the shifted carry-out state is written in-kernel. One dispatch replaces CopyGeneral x2 (concat halves) + ConvBF16 + the trailing contiguous state view. //  Bit-exact by construction: the concatenation is value-transparent (pure copies), so the conv reads identical values; the tap accumulation below is the conv.comp body verbatim (same loop shape, f32 widen, left-associated sum, RNE bf16 store), and the state rows move as raw uint16 bits. //  Bindings: 0 state [B, K-1, C], 1 x [B, 1, C], 2 weight [C, 1, K], 3 output [B, 1, C], 4 state out [B, K-1, C]. Push constants: count B * C output elements operation K (kernel taps) lhs_size K - 1 (state rows) reduce_size C (channels per row)
- zig/kernels/vulkan/gdn_conv_decode.comp: // Flag bit 1 (GdnConvUpdate `qk_key_dim > 0`): per-workgroup rms-norm epilogue for the q/k head-rows (fast_norm_gated.comp mode 1 folded into this dispatch; F4). Each 256-thread workgroup owns 256 contiguous channels = exactly two 128-channel head-rows (q rows first, then k; v passes through), so the two mode-1 reduction halves run side by side in one shared block: threads 0..127 hold row 2g, 128..255 row 2g+1, and the stride 64->1 tree per half reproduces the mode-1 tree association exactly (its stride-128 step only ever adds +0.0). The wrapper gates count % 256 == 0 (one element per thread, one grid-stride iteration — the in-loop barriers deadlock otherwise), channels % 256 == 0, and key_dim % 128 == 0 (the q|k boundary may fall inside a workgroup, but it stays on a 128-lane half). APPLE_REDUCTION sums each half with four 32-lane subgroups and one second subgroup sum, the order FastNormGatedAppleBF16 uses for a 128-wide row. The host dispatch guard (apple_norm_shape_selected, primitives.cpp) serves the 128-wide halves from the deployed kernel, so this build runs only if that guard ever widens to 128.
- zig/kernels/vulkan/gdn_conv_decode.comp: // Per-workgroup two-half 128-row rms-norm*scale over the stored values (fast_norm_gated.comp mode 1, F4). The norm input is the value this dispatch stores and the composed norm kernel re-widens.
- zig/kernels/vulkan/gdn_split.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  GDN pre-stage split for the Ash8c Metal oracle (gdn_pre.metal, post-conv half): the depthwise conv has already run (conv_dw1d.comp over the [T+3, C] conv input), so this kernel reads the raw conv output and does the rest of gdn_pre: SiLU, the Q/K L2 norm split, the V passthrough and the a/b gate from A_log / dt_bias. One workgroup of 32 lanes per (token, head) mirrors Metal exactly: each lane owns 4 contiguous channels (PER = 128/32), the row sum is a 32-lane reduction over the per-lane partials, and every intermediate the Metal kernel rounds to bf16 is rounded here too. //  Math per (t, head), C = 6144, DK = 128, NK = NV = 16: conv = widen(conv_out[t*C + head*DK + lane*4 + j]) (already bf16) sig = bf16(1/(1+exp(-conv))); vals[j] = bf16(conv*sig) q (head < 16) / k (16..31): inv = rsqrt(sum(vals^2)/128 + 1e-6/128), scale = bf16(1/128) for q, bf16(rsqrt(128)) for k, out = bf16(scale * bf16(vals[j]*inv)) v (head 32..47): out = vals[j] lane 0: s = bf16(a[t,hv] + widen(dt[hv])) sp = bf16(max(s,0) + log(1+exp(-|s|))) g = exp(-exp(A_log_f32[hv]) * sp) (f32, like Metal) beta = bf16(1/(1+exp(-b[t,hv]))) //  The reduction order differs from Metal's hardware simd_sum (documented in gdn.zig; not claimed bit-exact). The gate chain is the same expression sequence gated_delta_decode.comp's raw-gates prologue uses. //  Bindings (views bind at their base, so shader offsets start at zero): 0 conv_out bf16 [T, 6144] readonly 1 a bf16 [T, 16] readonly 2 b bf16 [T, 16] readonly 3 a_log f32 [16] readonly 4 dt_bias bf16 [16] readonly 5 qkv bf16 SoA [3, T, 16, 128] writeonly (q | k | v sections, each T*2048 elements) 6 g f32 [T, 16] writeonly 7 beta bf16 [T, 16] writeonly Push (the standard Params prefix; only these fields are read): count = T (tokens; grid x) lhs_size = C (conv row stride, 6144) rhs_size = T (SoA section stride in head-rows: T*16 heads * 128) output_size = 48 (heads; grid y) Local size 32x1x1; grid (T, 48, 1). Shared memory: 32 f32 (128 B).
- zig/kernels/vulkan/sdpa_decode_native.comp: // ------------------------------------------------------------------ The composition-exact bf16 arm. Every operation below reproduces the f32-score composition's observable arithmetic in the same order, so the route is bit-identical to the ten-dispatch path it replaces and no generated token can move: 1. q*scale once in f32 (the composition's elementwise multiply; the matmul alpha is 1.0 and its drain multiplies by it), 2. scores = per-dot ascending-d `acc += a * b` accumulation over 16-wide tiles with exact-zero tail padding, drained by 1.0f, stored f32 (matmul.comp), 3. softmax: 256-lane strided max scan + binary max tree, strided sequential exp-sum per lane + binary sum tree, normalizer 1.0/sum, probs = exp(score - max) * normalizer recomputed from the stored f32 scores (softmax_suffix.comp), 4. output = ascending-key `acc += a * b` over 16-wide tiles with exact-zero tail padding, drained by 1.0f (matmul.comp), stored through the cast.comp RNE bf16 pair. Threads 256..1023 share every barrier but do no phase work; the reduction trees only involve lanes 0..255, exactly as the 256-thread softmax kernel computes them. ------------------------------------------------------------------
- zig/kernels/vulkan/swiglu.comp: // Copyright © 2026 Joshua Warren / mlx-omarchy contributors. // SPDX-License-Identifier: MIT //  Reused from mlx-omarchy shaders/swiglu.comp (MIT), comment-condensed. //  Four-wide SwiGLU: sigmoid(gate) * gate * up, each intermediate rounded to the storage dtype exactly as the fused_chain interpreter rounds it (packHalf2x16 round trip for f16, bf16_store for bf16), so stored bits match. Host gate (dispatch_chain): two direct leaves and count and both leaf offsets multiples of four. materialize != 0 additionally stores sig/silu to bindings 3/4; the eager-fusion host path keeps those at 0 and leaves the buffers untouched.
- zig/src/families/qwen3_5/backend/vulkan/forward.zig: Every GPU call is routed through `vk.orExit` at the call site: a Timeout or InFlight ends the process before any destructor can free a resource the GPU may still be using. Nothing here falls back to the CPU.
- zig/src/families/qwen3_5/backend/vulkan/forward.zig: written out of place into `sum`
- zig/src/families/qwen3_5/backend/vulkan/forward.zig: Conv and recurrence are the state's ping-pong pair; the slot flips after the writes.
- zig/src/families/qwen3_5/backend/vulkan/forward.zig: pure and host-tested
- zig/src/families/qwen3_5/backend/vulkan/weights.zig: Admission is fail-closed: the pinned Qwen3.5-2B geometry, affine Q4 group-64 quantization, dense MLP, and every tensor's exact dtype and shape are checked before any byte is read; anything else is refused, never silently adapted.
- zig/src/families/qwen3_5/backend/vulkan/weights.zig: Ownership transfers exactly once: until the slot is registered in `keep`, this function alone cleans up (slot plus the Vk allocation) on every failure
- zig/src/vulkan/norm_mlp.zig: The host API is identical either way; the variant is fixed at build time, not a runtime option.
- zig/src/vulkan/norm_mlp.zig: the shader's lhs_size == 1 broadcast stays in the source, unused
- zig/tests/vulkan/contract_attention.zig: the fixture's fixed [8]f64 score buffer caps it at 8 visible keys
- zig/tests/vulkan/contract_attention.zig: Op order matches fx.Attend.init exactly.
- zig/tests/vulkan/contract_gdn.zig: the interior chunk snapshot is bound exactly when the prefill's chunks exceed one
- zig/tests/vulkan/contract_gdn.zig: `acc` null: the fixture's sequential f64 sum, bit-identical to fx.RecurWalk and fx.Decode
- zig/tests/vulkan/stage3_probe.zig: no model, no performance claim, no cross-backend bitexact claim — the fixture states each gate's budget
- zig/tests/vulkan/stage5_probe.zig: Exit 0 pass, 1 fail, 2 usage, 124 fence timeout.
- zig/build/vulkan_model.zig: the CUDA native server's entry point and checkpoint CLI, the factory's engine_api/core instances
- zig/src/vulkan/ops_q4.zig: Q4 affine projection out[m, n] = x[m, k] . dequant(w, scales, biases)[n, k], group 64, transposed
- zig/src/vulkan/ops_q4.zig: The gathered scale and bias rows ride the 32-bit transport, so tokens * (k / 64) must fill whole words
- zig/src/vulkan/ops_q4.zig: The three table views are single bindings, so each must fit maxStorageBufferRange whole; anything larger is refused before any dispatch, never silently chunked
- zig/tests/vulkan/contract_greedy_main.zig: finite_logits, argreduce_chunk and argreduce_combine behind one submission | the mirror of HIP's tf_ctl_fmax_max: a row max that drops a NaN | Gate 5 rides the device's own limits: dispatch.Pipeline.init checks workgroup, push and binding limits per device before creating anything
- zig/tests/vulkan/contract_pointwise.zig: checked STRICTLY (no measured-property qualification)
- zig/tests/vulkan/contract_pointwise.zig: the variant norm_mlp selects where the device declares shaderDenormPreserveFloat32 | the -DUSE_BF16 an earlier build passed alongside it matches no ifdef in the shader, so the pipeline was the plain bf16 add all along; no f32-storage variant of binary_vec.comp exists
- zig/tests/vulkan/contract_pointwise.zig: allow_subnormal_flush stays false — the preserve gate is where the GPU result must prove denormal preservation, so a flushing device fails the subnormal classes rows as an honest finding
- zig/tests/vulkan/contract_pointwise.zig: the f32 multiply's sign rule makes it deterministic. Nonfinite wants compare classes
- zig/tests/vulkan/contract_pointwise.zig: whose error is relative to |normed|, i.e. |want|/|silu(z)| — the fixture's gate floor |z| >= 0.25 keeps |silu(z)| >= 0.109
- zig/tests/vulkan/contract_pointwise.zig: that head row's sum goes infinite, norm 0: signed-zero outputs across the head row, nan at x[0]'s inf*0 | that head row's sum goes nan: a whole nan head row
- zig/tests/vulkan/contract_pointwise.zig: w the shared [128] gain at the element's column. nonfinite where the planted controls make it so; want == 0 carries the sign
- zig/tests/vulkan/contract_pointwise.zig: the reduction sums only squares | (a flushed or sign-flipped zero is refused); nonfinite wants compare classes; a finite want with a nonfinite output is refused outright
- zig/tests/vulkan/contract_pointwise.zig: A define that matches no ifdef — the -DUSE_BF16 an earlier build passed alongside it — silently produces the plain bf16 add instead; this catches that class of drift
- zig/tests/vulkan/qwen35_model_probe.zig: bad usage or bad inputs exit 2; a failed run exits 1; a fence timeout exits 124 (inside the engine's orExit) | PASS requires the exact oracle IDs (strict lowest-index ties, no epsilon, no known-ID special case) on two fresh-cache runs | the GPU greedy is the selector, never a CPU argmax | the raw logits are also compared element-wise against the oracle's file as a diagnostic only
- zig/tests/vulkan/qwen35_model_probe.zig: the diagnostic counter, pure and host-tested. Byte-pair compare: no alignment assumed
- zig/tests/vulkan/qwen35_model_probe.zig: Immutable metadata: the caller passes an arena allocator, nothing freed
- zig/tests/vulkan/qwen35_model_probe.zig: shared by the probe run and the opt-in load test so both exercise the shader set the server serves with
- zig/tests/vulkan/qwen35_model_probe.zig: --sequential-prefill instead issues one Engine.prefill call per prompt token for the boundary evidence
- zig/tests/vulkan/stage2_fixture.zig: nonfinite outputs by class (a driver may raise a different NaN payload)
- zig/tests/vulkan/stage2_fixture.zig: the largest minStorageBufferOffsetAlignment Vulkan allows
- zig/tests/vulkan/stage2_fixture.zig: The measured device properties, never a vendor name, qualify the three subnormal-class rows for signed-zero results when f32 preservation is unsupported
- zig/tests/vulkan/stage2_fixture.zig: The budget applies to the output RELATIVELY (see check): the sum is positive, so gamma(20) bounds its relative error in any order
- zig/tests/vulkan/stage2_fixture.zig: The reduction sums squares (positive), so its relative error stays under gamma(depth) in any order | A deliberately-absolute sum-of-squares budget here would allow ~1e3 of output error on dynamic rows and nonzero outputs on the zero row — that was wrong and is not this
- zig/tests/vulkan/stage4_probe.zig: Exit 0 pass, 1 fail, 2 usage, 124 fence timeout
- zig/tests/vulkan/stage4_probe.zig: the conv output and the split's soa/g/beta go against the f64 references, three byte-identical repeats, planted refusals, inputs unchanged
- zig/tests/vulkan/stage4_probe.zig: raw bf16 store — the split owns the single SiLU | then the split on the ACTUAL activated bits against SplitOne. Repeats, guards, unchanged inputs, negative controls on both stages
- zig/src/families/qwen3_5/backend/vulkan/engine.zig: the state's real zeroed regions come last. The engine pointer is stable for its whole life: the runtime, device and command stream are heap-owned before any view, pipeline or state exists, so no child pointer can ever dangle behind a move.
- zig/src/families/qwen3_5/backend/vulkan/engine.zig: A failure after the first chunk poisons (the partial RNN state is never reused)
- zig/src/vulkan/attention.zig: fast_rope compiles with -DUSE_BF16 -DASH_QWEN35 (the Metal-oracle variant: no intermediate bf16 rounding; the compiled passthrough path evaluates the theta 1e7 inverse frequency as exp(-i*beta) with beta = ln(1e7)/32, i.e. 1e7^(-i/32) up to exp-vs-pow ulps); ... fast_rope needs the repo-local omarchy_trig.h include path.
- zig/src/vulkan/greedy.zig: argreduce_chunk.comp and argreduce_combine.comp (mlx-omarchy sources copied verbatim, driven operation=max, one row)
- zig/src/vulkan/ops.zig: The caller owns index validation (see ops_q4.checkIds); the zero write is the shader's documented read.
- zig/tests/vulkan/contract_attention_main.zig: single-key transport exactness, planted refusals, inputs unchanged
- zig/tests/vulkan/contract_gdn_main.zig: the stage 4 module doc block, plus the prefill scan's [2][DK] staging the doc block predates
- zig/tests/vulkan/stage4_fixture.zig: inputs are exactly-bf16-representable dyadics so operand widening is exact; magnitude scale max|vals|^2; at |g|; at the largest intermediate state magnitude the walk saw; chunk=4 and chunk=8 must agree with the SAME serial reference; Every finite reference demands a finite output
- zig/tests/vulkan/stage4_fixture.zig: Never a sum of squares of outputs; always finite and positive (the 2^-133 floor), so dividing into a ratio is safe. Fixed bring-up acceptance: never enlarged after a GPU run without a new stated derivation.
- zig/tests/vulkan/stage4_fixture.zig: the split's lane-0 chain and the decode prologue's raw-gates chain share this formula ... Use `gateRefAsh` for checker references; this stays for the amplification evidence test.
- zig/tests/vulkan/stage4_fixture.zig: (gdn_split.comp ash_gate and gated_delta_decode's ASH_QWEN35 prologue) ... Every bf16 rounding and f32 op of the shader, on the host - the residual vs the GPU is f32 exp/log ulps, what the unchanged ops budget covers.
- zig/tests/vulkan/stage4_fixture.zig: (the shader's interior chunk boundary): the snapshot slot the prefill scan stores there
- zig/tests/vulkan/stage5_fixture.zig: The reference deliberately re-walks the widened row itself instead of calling production host helpers ... No oracle tokens: every expectation comes from this scan.
- zig/tests/vulkan/stage3_fixture.zig: Acceptance: these are fixed bring-up budgets, not cross-backend bitexact claims or Vulkan-spec proofs. RoPE's f64 reference applies ASH equations out[d<32]=x[d]*cos-x[d+32]*sin and out[32<=d<64]=x[d-32]*sin+x[d]*cos, angle pos*theta^(-i/32). Budget |got-want|<=budget(depth=2,ops=6,mids=1,|want|): f32 angle/pow/trig/products, one RNE bf16 store, and input bf16 rounding as mid. d>=64 must equal input bits exactly. Cache K rows base..base+rows-1 use rope reference at base+r; V rows preserve input bits via uint16 transport; rows outside window preserve planted poison. SDPA query r sees exactly prefix+r+1 keys; f64 reference softmaxes only those keys; depth=300 covers 256-term score dot and output sum at own magnitude plus GPU-read q/k bf16 roundings (mids=2). Causality has no budget: outputs must be bit-identical when every non-visible key is poisoned by a large finite value vs zeroed. Gate out=bf16(f32(ctx)*f32(bf16(sigmoid(gate)))); ops=3 (exp/add/div), mids=1 (bf16 sigmoid round), one bf16 store. Every finite reference requires finite output; wrong finite and nan/+inf/-inf plants must be refused.
- zig/tests/vulkan/stage3_fixture.zig: // Stage 3 fixture: half-split RoPE (head_dim 256, rotary 64, theta 1e7), the flat KV cache write, causal GQA SDPA (8 query heads, 2 KV heads, scale 1/16) and the interleaved attention output gate, against independent f64 host references. Host-checkable only; no device code here.
- zig/tests/vulkan/stage3_fixture.zig: //  Acceptance (fixed bring-up budgets, stated; NOT cross-backend bitexact claims, NOT Vulkan-spec proofs): - rope: the f64 reference applies the ASH form out[d<32] = x[d]*cos - x[d+32]*sin, out[32<=d<64] = x[d-32]*sin + x[d]*cos (angle pos*theta^(-i/32)), x[d>=64] passthrough. Budget: |got - want| <= budget(depth=2, ops=6, mids=1, |want|): f32 angle/pow/trig/products plus the one RNE bf16 store, with the input's own bf16 rounding as the mid. Elements d >= 64 must equal the input BITS exactly. - cache: K rows base..base+rows-1 carry the rope reference at positions base+r; V rows are the input BITS exactly (uint16 transport); every row outside the window keeps the poison the fixture planted. - sdpa: query row r sees exactly prefix+r+1 keys. The f64 reference softmaxes over those keys only; budget depth=300 covers the 256-term score dot and the 256-term output sum at their own magnitude scale, plus the q/k bf16 roundings the GPU reads (mids=2). Causality is also checked WITHOUT a budget: outputs must be bit-identical when every non-visible key is poisoned with a large finite value vs zeroed. - gate: out = bf16(f32(ctx) * f32(bf16(sigmoid(gate)))); budget ops=3 (exp/add/div), mids=1 (the bf16 sigmoid round), one bf16 store. Every finite reference demands a finite output; planted wrong finite and nan/+inf/-inf outputs must be refused by the same checkers.
- zig/tests/vulkan/contract_greedy.zig: the harness's run hook is one prepared input set and one call, and the draw's three passes share one submission and its internal scratch (partials, the 12-byte readback) — finite_logits alone writes only verdict words, argreduce_chunk/combine alone write (value, index) pairs meaningful only to the fold and the decode.
- zig/tests/vulkan/contract_greedy.zig: HIP registers its tf_argmax_parts+join the same way, so the three launches ride inside run() instead of three registrations.
- zig/tests/vulkan/contract_greedy.zig: The stated rule the check hook enforces (greedy.zig's, unchanged Ash q.backend.draw): any non-finite anywhere in the row refuses it, winner or not; the largest value wins; exact ties (including +0/-0) go to the lowest index.
- zig/tests/vulkan/contract_greedy.zig: The planted control that breaks exactly this rule is zig/kernels/vulkan/contract_controls_greedy.comp, registered from the main with control = .nonfinite.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: Every region is real zeroed device memory: construction and `reset` write zeros on the GPU through the existing staged transfer (`commands.upload` through the caller's staging buffer) — never a metadata-only reset and no new kernel.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: The decode and prefill operators read one state half and write a disjoint other half (ping-pong), so no read aliases a write under the pipeline's validation; `flip` swaps the halves between steps.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: Capacity is bounded by the SDPA arm's visible-key limit (7168): a context beyond that is refused at construction, never silently truncated.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: Length commits only through `append`, after the writes that produced the rows completed; `deinit` is legal only when no submission touching any view can still be pending; `reset`'s transfers route in-flight errors through `commands.orExit` inside this module, before any unwind can free.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: The pinned config's `full_attention_interval`, checked against the family constants.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: This is the hard capacity it admits (attention.zig's limit).
- zig/src/families/qwen3_5/backend/vulkan/state.zig: Every buffer is heap-owned and never moved, so all views stay valid for the state's lifetime.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: `parity` selects which ping-pong half each linear layer's operators read and write next.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: The caller's staging buffer (any nonempty size; transfers chunk through it).
- zig/src/families/qwen3_5/backend/vulkan/state.zig: The slot registers in `created` as soon as the Vk allocation exists, so exactly one owner (State.deinit) ever frees it.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: `staging` zero page is bounded at 16 MiB.
- zig/src/families/qwen3_5/backend/vulkan/state.zig: There is no rewind: lowering the committed length after recurrence updates would leave the conv and GDN states silently wrong, so a future caller that needs speculation or prefix reuse must restore state for real (this module provides only a full `reset`).
- zig/src/families/qwen3_5/backend/vulkan/state.zig: the larger F32 geometry bounds both lengths.
- zig/tests/vulkan/contract_pointwise_main.zig: Stage 2's three through the production operator; the preserve add over the same pipeline's DenormPreserve image (binary_vec.comp + -DPRESERVE_F32, bf16 in and out), the gate and gated norm in the same dispatch shapes their wrappers use.
- zig/tests/vulkan/contract_pointwise_main.zig: The device line above prints the property, so a strict refusal on a preserving device is a decidable honest finding.
- zig/tests/vulkan/contract_pointwise_main.zig: every mismatch a subnormal sum read as the same-signed zero. That prints ONLY its KNOWN line (the reasoning folded into it); anything else — a device that claims preservation and flushes, a non-flush mismatch — keeps the FAIL, plus the NOTE when the want is a subnormal.
- zig/tests/vulkan/contract_pointwise_main.zig: The wrapper's own plan: out/y/z are tokens*2048 elements, the weight the [128] head row, rows = the TOKEN count, plan.rows = tokens*16 head rows.
- zig/src/families/qwen3_5/backend/vulkan/backend.zig: the state ceiling; the reply's decodes are admitted against it separately.
- zig/src/families/qwen3_5/backend/vulkan/backend.zig: the engine (device, weights, sequence) outlives it and its owner deinits it quiescent.
- zig/src/families/qwen3_5/backend/vulkan/backend.zig: The first call validates the whole request (ids, capacity footprint with the reply's decodes) before any reset or write; later calls resume at the engine's committed visible count, so `visible()` is the progress and no cursor state exists.
- zig/src/families/qwen3_5/backend/vulkan/backend.zig: The engine holds a single sequence with no rewind, so keeping a prefix is impossible.
- zig/tests/vulkan/stage1_fixture.zig: one output per 256-thread group and one past it, one and two groups per row, offsets, and a cancel fill.
- zig/tests/vulkan/stage1_fixture.zig: Every m*n is even (word-padded bf16 views).
- zig/tests/vulkan/stage1_fixture.zig: Binding bases sit at 256-byte multiples — the largest minStorageBufferOffsetAlignment Vulkan allows — so the offsets exercise the production aligned-binding contract on any device, not arbitrary offsets; Views guarantee only 4-byte alignment.
- zig/tests/vulkan/stage1_fixture.zig: with the 128 randoms the cast views stay word-padded.
- zig/tests/vulkan/stage1_fixture.zig: the copy exercises the production aligned-binding contract, not arbitrary offsets.
- zig/src/families/qwen3_5/backend/vulkan/engine.zig: Native Vulkan Qwen3.5-2B engine: heap-stable object runs single-sequence prefill chunks, decode, and greedy draws.
- zig/src/families/qwen3_5/backend/vulkan/engine.zig: Safety: gates (bf16, SDPA shmem, GDN subgroup) + admission precede weights; state last; child ptrs heap-owned first
- zig/src/families/qwen3_5/backend/vulkan/engine.zig: `vk.orExit` exits 124 on Timeout and 1 on InFlight.
- zig/src/families/qwen3_5/backend/vulkan/engine.zig: Post-write failures poison until reset; no rollback.
- zig/tests/vulkan/stage1_fixture.zig: tokens are even in every case: each gathered token contributes k/64 bf16 scales, and a ragged tail element would be refused by the typed view before any GPU work.
- zig/src/vulkan/commands.zig: // Fill `len` bytes of device buffer `dst` at `offset` with the repeating 4-byte little-endian pattern of `value`: one submission, transfer-write barriers before and after, finite fence wait. Timeout/InFlight go to the caller, which must orExit rather than free anything the GPU may still use.
- zig/src/vulkan/gdn.zig: // Qwen3.5 GatedDeltaNet GPU primitives on the shared set-0 storage / push-constant pipeline model, matching the Ash8c Metal oracle (zig/kernels/metal/qwen3_5/gdn_{pre,chain,post}.metal) op for op. // Kernels (kernels/vulkan/, -DUSE_BF16 --target-env vulkan1.2): conv_dw1d, gdn_conv_decode, gdn_split, gated_delta_prefill_ash, gated_delta_decode, copy_general -DUSE_U16 (copied mlx-omarchy, MIT), fast_norm_gated (copied, MIT). // Gate formula from the Metal oracle, not assumed: s bf16, softplus bf16-rounded, g = exp(-exp(A_log_f32) * softplus) stored f32, beta = sigmoid(b) bf16; A_log f32, dt_bias bf16; decode bit9 selects the f32 A_log read and the Metal kv-walk association. // Bindings vs dispatch.max_bindings = 10: conv_dw1d 3, gdn_conv_decode 5, gdn_split 8, fast_norm_gated 4, copy_u16 4, gated_delta_prefill_ash 10, gated_delta_decode 10. // Shared memory: gdn_split 128 B; prefill scan 1.5 KiB; decode about 18 KiB; fast_norm_gated 1 KiB; subgroup relative shuffles required for compute and subgroup size a multiple of 4 (checked in init, fail-closed); 16-bit storage + int16 required. // State lifetime: conv and recurrence states are caller-owned and must stay alive until every submission using them returned success; Timeout/InFlight routes through commands.orExit, never deinit; 18 layers keep 18 conv + 18 recurrence state buffers.
- zig/src/vulkan/gdn.zig: // Prefill conv: assemble the [tokens+3, C] conv input (conv state rows then the projection output), run the 4-tap conv and the gate split, store the trailing [3, C] window as the next conv state; writes are out of place.
- zig/src/vulkan/gdn.zig: // Gated-delta prefill recurrence over `tokens` in chunks of `chunk`: pass 0 writes per-chunk snapshots (skipped for a single chunk), pass 1 the bf16 outputs and the terminal state. q/k/v ride one SoA buffer (the split's output shape), g is the split's f32 gate, h0/hf are [16*128*128] f32 states; `tokens <= chunk` takes snap = null.
- zig/src/vulkan/gdn.zig: // Gated RMSNorm + SiLU epilogue (Ash8c Metal gdn_post): PER-HEAD 128-wide RMS, not a 2048 global row; out = bf16((gate/(1+exp(-gate))) * bf16(weight * (value * inv))). y/z/out are [tokens, 16, 128] bf16 head-major — exactly the recurrence's y layout; the weight is [128] bf16 indexed by the column within the head.
- zig/src/vulkan/norm_mlp.zig: /// RMSNorm computes x*rsqrt(mean(x^2)+eps)*gamma; View.init rejects scalar padding, so row gamma binds at offset 0.
- zig/tests/vulkan/stage3_fixture.zig: // Stage 3 fixture: half-split RoPE (head_dim 256, rotary 64, theta 1e7), the flat KV cache write, causal GQA SDPA (8 query heads, 2 KV heads, scale 1/16) and the interleaved attention output gate, against independent f64 host references. Host-checkable only; no device code here. Acceptance uses fixed bring-up budgets — NOT cross-backend bitexact claims, NOT Vulkan-spec proofs.
- zig/tests/vulkan/stage3_fixture.zig: // Focused bit-pattern proof of the production shader bug: attention_gate.comp fed bf16_bits(s) << 16 back into bf16_lane's lane 0, which shifts << 16 again; a bf16 word widened once is the sigmoid value, shifted 32 total it annihilates to 0.0 — lane 0 of every output word.
- zig/src/families/qwen3_5/backend/vulkan/backend.zig: The advertised scheduling step: the engine cuts each prompt pass into chunks of at most this many rows
- zig/src/families/qwen3_5/backend/vulkan/state.zig: Length commits only through `append`, after the writes that produced the rows completed / `reset`'s transfers route in-flight errors through `commands.orExit` inside this module
- zig/tests/vulkan/contract_pointwise_main.zig: through the same dispatch model their wrappers use (identical binding counts, push-block sizes and group math; the wrappers own the plans via attention.gatePlan and gdn.gatedNormPlan) / no model, no performance claim, no cross-backend bitexact claim
- zig/tests/vulkan/stage1_fixture.zig: against the contract's FP64 bound
- zig/tests/vulkan/stage1_fixture.zig: Every m*n is even (word-padded bf16 views)
- zig/tests/vulkan/stage1_fixture.zig: with the 128 randoms the cast views stay word-padded
lean_check read the three header lines as two multi-line comments, so
the file failed the lean rule. The three facts do not fit in one
120-column line, so each stands on its own with a blank line between
them: no comment is longer than one line and no fact is lost.
stage2_fixture.zig was 617 lines, over the 600-line lean limit, so no
case could be added without splitting it. The cases and checkers move
unchanged into stage2_fixture_ops.zig and the root re-exports them, so
every caller keeps the same API. The tests stay in the root file, so
every artifact that imports the fixture still runs them and the test
counts do not move.
stage3_fixture.zig was 739 lines, over the 600-line lean limit, so no
case could be added without splitting it. The cases and checkers move
unchanged into stage3_fixture_cases.zig and the root re-exports them, so
every caller keeps the same API. The tests stay in the root file, so
every artifact that imports the fixture still runs them and the test
counts do not move.
zig/src/vulkan/gdn.zig was 635 lines, past the 600-line lean limit. The six
geometry plans (split, conv prefill, conv decode, the prefill recurrence, decode
and the gated norm), the cast32 helper they share and their seven host tests
move to zig/src/vulkan/gdn_plan.zig. gdn.zig keeps every plan name reachable
under the same name through re-exports, so vulkan.gdn.splitPlan and the rest are
unchanged for callers, and the plan tests still run in the vulkan module's own
test binary.

gdn.zig is 462 lines and gdn_plan.zig is 197. The moved code is byte-identical
apart from the re-export lines, and the test counts do not move: vulkan-host-test
reports the same 215/217 tests passed (2 skipped) and the same per-binary counts
(60, 6, 6, 11, 2, 11, 9, 3, 17, 8, 2, 21, 24, 35 + 2 skipped). The lean checker
no longer reports this file's line-count finding, and a plain zig build still
succeeds.
zig/tests/vulkan/contract_datamove.zig was 646 lines, past the 600-line lean
limit. The fixture rig (the guarded device buffers, the guard pattern and the
payload views), the little-endian byte helpers and the failure-message buffer
move to zig/tests/vulkan/contract_datamove_rig.zig. The contract file keeps every
name reachable under the same name, so contract_datamove_main.zig and the
contract's own gates are unchanged.

contract_datamove.zig is 536 lines and contract_datamove_rig.zig is 122. The
moved code is byte-identical apart from the pub markers the cross-file use
needs, and the datamove host suite keeps its two tests: vulkan-host-test reports
the same 215/217 tests passed (2 skipped), and the datamove contract build
(stage1-gpu-build) succeeds with the same 25/25 steps. The lean checker no
longer reports this file's line-count finding.
zig/tests/vulkan/qwen35_model_probe.zig was 646 lines, past the 600-line lean
limit. The receipt shape (the result.json fields, the repeat and oracle echoes),
its JSON writer, the execution-mode labels and the receipt's round-trip test move
to zig/tests/vulkan/qwen35_model_receipt.zig. The probe keeps every name
reachable under the same name, so the result.json bytes it writes are unchanged.

qwen35_model_probe.zig is 558 lines and qwen35_model_receipt.zig is 98, which
leaves room for the three lines the next change adds. The moved code is
byte-identical apart from the pub markers the cross-file use needs, and the
probe keeps its nine tests: model-host-test succeeds with the same 6/6 steps and
vulkan-model-probe-build with the same 31/31 steps. The branch's lean checker
now reports 463 problems against the 466 baseline, with none in the touched or
the new files.
zig/build/vulkan.zig held every stage's build steps in one function and had grown past
the house's 600-line lean limit. The per-stage and per-contract steps now live in
zig/build/vulkan_stages.zig, one function per stage (hostAdmission, probeSteps, stage1
to stage5, contracts, kernelContract), called from vulkan.zig in the order the steps are
created. The shader lists, the server's modules and the backend module stay in
vulkan.zig, which the new file reads, the way vulkan_model.zig already reads it.

Every step name, option and install path is unchanged: `zig build --help -Dvulkan=true`
lists the same Steps and the same -D options before and after, and the 472 moved lines
are verbatim apart from the context fields they now read. vulkan-host-test,
stage1-gpu-build, stage3-gpu-build, stage5-gpu-build, tf-vulkan-kernel-contract and
vulkan-model-probe-build build and pass, installing the same artifacts under zig-out.
zig/kernels/vulkan/omarchy_trig.h carried 29 multi-line comments: one run of 27 lines
over the header and one of 4 over the tan wrapper. Each is now one line of at most 120
columns, the form the house's lean rule takes, and the code lines are untouched. The
shader that includes it compiles to byte-identical SPIR-V (fast_rope.comp, -DUSE_BF16
-DASH_QWEN35).

The facts the one-line comments keep:
- the attribution: copied from the mlx-omarchy overlay's omarchy_trig.h, MIT, full text
  in LICENSES/mlx-omarchy-MIT.txt.
- why: the built-in sin/cos/tan lose upstream accuracy above ~1e3 and collapse past
  ~1e6 (llvmpipe past ~1e7, measured), so every trigonometric argument not bounded by
  construction goes through these wrappers.
- what: accurate to OMARCHY_TRIG_LIMIT, NaN above it, never a wrong finite value, and
  the raw built-in stays bit-identical below OMARCHY_TRIG_BUILTIN_MAX.
- how: Cody-Waite with C1 = 6.28125 = 201 * 2^-5 (8 significant bits), exact for
  |k| <= 83601 and so for every argument up to 525371.9; the rest is a dyadic 2^-9
  (exact for all k) plus two f32 correction terms; the three-subtract chain is marked
  precise so a driver may not reassociate it (Honeykrisp has a documented
  inexact-constant-reassociation defect); above the limit the argument leaves the
  exact-product zone and the wrappers return NaN.
- tan reduces through the 2*pi-periodic sin/cos forms, which are exact period shifts,
  so the reduced argument serves; the relative error grows near the poles as at the
  built-in.
The stage 4 fixture (1035 lines) and probe (950 lines) each broke the 600-line lean rule, and the fixture's two-line header
was a multi-line comment. The fixture is now four files (the shared core, the split fixtures, the state fixtures, and the
root that keeps the public surface and the host tests) and the probe three (the shared helpers, the gates, and the root), all
under 580 lines. Each file reaches the others through @import inside the same module, so zig/build/vulkan.zig is unchanged:
the stage 4 host test still runs stage4_fixture.zig as its root, and the probe executable still roots at stage4_probe.zig.

Every line of code is the original line, moved. The only new tokens are the import aliases, the pub on the helpers the parts
share (violated, poisonedShell, f32Of, the gate and buffer helpers), and the one-line file headers. The fixture root re-exports
the whole public surface (fx.Split, fx.SplitOne, fx.Conv, fx.RecurWalk, fx.Recur, fx.Decode, fx.Norm, fx.Model, fx.c,
fx.budget, fx.gateRefAsh, fx.sampleDyadic, fx.tokens), so the probe and contract_gdn.zig are untouched; the probe root calls
the gates through the gates module.

Proven: tools/zig/lean_check.py reports no problem for any stage4_*.zig (the repo total falls from 466 to 463).
`zig build stage4-host-test -Dvulkan=true` passes with the same 60 + 9 tests, `zig build stage4-gpu-build -Dvulkan=true`
compiles tf-stage4-gpu, and `zig build test -Dvulkan=true` gives the identical summary before and after (543/549 steps,
2273/2313 tests; the 37 failures are the pre-existing originals_test ones, the same at the base commit).
zig fmt --check is clean.
contract_gdn.zig was 1611 lines, over the 600-line lean limit, so no
case could be added without splitting it. The served shapes, the specs
and the f64 references move unchanged into contract_gdn_ref.zig, the
fixture's buffers and launches into contract_gdn_ops.zig, and the host
fills, references and upload order into contract_gdn_host.zig; the root
re-exports them, so every caller keeps the same API. The tests stay in
the root file, so every artifact that imports the fixture still runs
them and the test counts do not move.
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 <[email protected]>
…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.
ashhart pushed a commit to joshuaswarren/TensorFold that referenced this pull request Nov 26, 2026
…oracle fixture

The fabric/tp README goes back to main's copy; this branch had picked up an older one. The swiglu fixture test now says oracle, and the three shader and Zig comments that held a placeholder sentence describe their code again. All five files now match the reviewed copies on ashhart#2016.

Signed-off-by: Joshua Warren <[email protected]>
joshuaswarren and others added 6 commits November 26, 2026 12:53
…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 ashhart#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 ashhart#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 pushed a commit to joshuaswarren/TensorFold that referenced this pull request Nov 26, 2026
…oracle fixture

The fabric/tp README goes back to main's copy; this branch had picked up an older one. The swiglu fixture test now says oracle, and the three shader and Zig comments that held a placeholder sentence describe their code again. All five files now match the reviewed copies on ashhart#2016.

Signed-off-by: Joshua Warren <[email protected]>
@joshuaswarren

Copy link
Copy Markdown
Contributor Author

/atc depends 2015

This branch has not been deployed

No deployments
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.

3 participants