Skip to content

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

Open
joshuaswarren wants to merge 55 commits into
ashhart:mainfrom
joshuaswarren:vulkan-qmm-tile
Open

joshuaswarren wants to merge 55 commits into
ashhart:mainfrom
joshuaswarren:vulkan-qmm-tile

Conversation

@joshuaswarren

@joshuaswarren joshuaswarren commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #1990 (which is stacked on #1544). #1990's branch is at 59145cf8; this branch is rebased onto it and is at ff0674bc. Review only these commits: 1fca1c29 (kernel, repack and loader), 3b561802 (kernel contract registration), 5f470b2d (pad the last tile so every n is served), fccf5839 (docs and changelog), 1ae2363d (figures on the float32-fixed heads), 0a036780 (the tile image reads and stores f32 activations), 52d5ed6f (its contract fixture), and the sync and style commits f1efc1da, 61290282, b1cbec31, cd63ee09, defd3bbf and 2a5a06c2, and the docs commit ff0674bc (the pinned timing and the runner output). Everything below them is #1990's and #1544's.

On a 13-inch Apple M1 with Honeykrisp, a Qwen3.5-2B 4-bit run took 28.6% to 66.8% less time than with qmm_q4_vec4 on three inputs, with every process pinned to the four P cores. The logits are byte-identical. These figures are from #1990's head (ELF 46571f11) against this PR's head (ELF 6e6f47f2), run on 2026-11-12 on Linux 7.3.0-2-20261110.1-lab-ARCH and Honeykrisp from the Omarchy Mesa build. The ELFs were built before the comment and name commits above them; those commits change no code. An earlier run of the same two heads on this chip without pinning (2026-11-11, builds 1e1b7d8c and b6d9a35b) gave 10.9%, 35.6% and 44.9% with other logits digests, and the first version of this description gave 19% to 63% on earlier builds. These runs do not separate pinning from the build change as the cause.

Input vec4 run 2 tile run 2 Gain, median of three pairs (range) Logits digest
24-token prompt (unicode-24), context 512 11.8 s 8.4 s 28.6% (27.9 to 31.2) 6bfbb1a55a3e
256-token document, context 512 26.9 s 12.2 s 54.4% (53.9 to 61.0) 8901e17ccef7
1,024-token document, context 1536 76.9 s 25.8 s 66.8% (66.1 to 66.9) a472a62c7e22

Run 2 is the prefill plus 63 decode steps plus the per-step logits readback. It is not decode-only. All six processes of a case wrote the same logits digest, in both arms, and all 18 returned 0 with the pinned ids. docs/receipts/vulkan-qmm-tile-m1/pinned-heads-summary.json holds every process row; the unpinned run stays in fixed-heads-summary.json.

What changes

For a decode step, lane i of a 32-lane group reads weight row n0+i, and the rows are k/2 bytes apart (1 KiB at k = 2048). Every 16-byte load of a group touches 32 cache lines. The new image reads the same vectors from tiles of 32 columns: words as [tile][k/32][lane] 16-byte vectors, scales and biases as [tile][group][lane]. A group's load is then one contiguous 512-byte run. The shader is qmm_q4_vec4 with different address formulas; the loop, the fp32 accumulator and the order of the sums are the same.

  • vk.tile repacks on the host: whole 16-byte vectors and 2-byte scales move, nothing changes value. The last tile is padded with zero columns the kernel never computes, so any n is served.
  • The Qwen3.5 loader tiles every projection whose padded words fit one binding, when the arena's alignment keeps x 16-byte aligned. Quant.tiled sends it to ops_q4.projectTiled. Other devices and shapes keep the vec4 image on the row layout.
  • The tied output head is a second, tiled upload of the embedding table, because the embedding gathers rows and keeps the row layout. That is about 320 MB more device memory. The loader's temporary copy raises the process's peak resident memory from about 87 MB to about 312 MB (it is freed after the upload).

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 runs the tiled image and the default image on every projection case and requires equal bytes: 21 of 21 on the GPU at 2a5a06c2, with the tiled image identical on all 12 projection cases (n = 8, 16 and 257 pad the last tile; n = 140,000 is one binding on this device). It also passed 21 of 21 on llvmpipe on the earlier build, which is not GPU evidence.
  • docs/receipts/vulkan-qmm-tile-m1/runners-2a5a06c2/tf-stage1-gpu.txt has the per-case lines.
  • No probe compares the f32 tile image (qmm_q4_tile_f32) against qmm_f32 byte for byte. For that image the identity evidence is the equal logits digests of the two heads on the three inputs.

Kernel contract

The ten contract and stage runners ran on the GPU at 2a5a06c2 (2026-11-12, GPU timeouts 0). All ten exited 0. The output is in docs/receipts/vulkan-qmm-tile-m1/runners-2a5a06c2/, one file per runner. tf-vulkan-kernel-contract:

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

The four kernels are qmm_bf16, qmm_q4_vec4, qmm_q4_tile and qmm_q4_tile_f32. qmm_q4_tile_f32 passes all five gates (limits, nonfinite, repeat, shapes, sums): 15 shapes within the float64 bound (worst 0.034 of the bound), five runs byte-identical, exact sums at k 6144. qmm_q4_tile passes with 15 shapes in bound (worst 0.987). The other runners: attention contract 15 of 15, contract-pointwise 16 passed and 1 known of 17, datamove 7 of 7 kernels, stage 1 21 of 21, stage 2 9 of 9, stage 3 4 of 4, stage 4 6 of 6, stage 5 7 of 7, greedy contract 1 pass and 1 control red as planted.

The first run of the contract on the GPU, on an earlier build, failed: the build in 2bbe4202 left n = 16 on the vec4 image and the contract refused the served shape 1x16x64, because a registered kernel must serve every shape the contract serves. a50413a1 pads the last tile instead. The gates seed each kernel from its name, so each kernel sees its own random data and its worst-shape value differs.

Pre-registration

PREREG.md was written before any GPU run. The rule was: a median gain of at least 3% and every pair positive. All three cases meet it. The forecast was 20% to 45% on the 24-token prompt and similar on the documents. The pinned run gave 28.6% on the 24-token prompt, inside it, and 54.4% and 66.8% on the documents, above it. The unpinned run of 2026-11-11 gave 10.9%, 35.6% and 44.9%. On the earlier builds the 24-token prompt gave 19.3% and the documents 49.9% and 62.6%.

The padding change came after the first contract run and before the final pairs. The addendum in PREREG.md says so, and was written after the final pairs.

Not covered

  • Other chips. On a 16-inch M1 Max, same run shape and pinned to its P cores, the same inputs gave 7.3%, 19.8% and 28.7% (medians of three pairs) with the same three digests. Its contract runner output is not in this PR.
  • Other quantizations, other models, the Metal path, and devices whose storage range is smaller than the padded head: those keep the vec4 image and the row layout.
  • Significance: three pairs per case, no test.
  • A variant that issued the next group's loads before this group's arithmetic ran 9% slower than this change on the 24-token prompt (3 of 3 pairs). It is not in this PR.

Checks

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: LAND after the stack under it, and after one device run on a second GPU. The new commits are exact by
construction, and nothing needs changing in them.

What the 41 commits are

Commits Belong to Status
1-32 (28 Oct to 29 Oct) #1544, the native Vulkan Qwen3.5-2B engine and its contract groups open, not on main d8b80bd
33-36 (2 Nov) #1990, qmm_q4_vec4 open, not on main
37-41 (3 Nov) #2015 itself: the tile kernel, repack and loader (37), its contract registration (38), padding the last tile (39), receipts and changelog (40), comment style (41) new

The new commits

The shader is qmm_q4_vec4 with new addresses (zig/kernels/vulkan/qmm_q4_tile.comp). A diff against
qmm_q4_vec4.comp changes only the comment and four index expressions:

  • the word base column * (k/32) becomes tile * k + lane, and each vector is read at + (group*2 + half) * 32;
  • the scale and bias base column * groups becomes tile * groups * 32 + lane, read at + group * 32.

The loop, the fp32 accumulator, the dequant, the order of the sums and the bf16 rounding are unchanged. So each
output gets the same sums in the same order as the vec4 image: exact.

The repack matches those addresses (zig/src/vulkan/tile.zig):

  • tileWords puts column c's vector j at ((c/32)*(k/32) + j)*32 + c%32;
  • tileParams puts its group g at ((c/32)*(k/64) + g)*32 + c%32;
  • both move whole 16-byte vectors and 2-byte values, and zero the padding.

Host tests check every address, a byte sum that loses nothing, and zero padding (n 70, k 192; n 40, k 256).

Tail and bounds:

  • Commit 39 pads the last tile, so any n is served.
  • The shader computes only column < matrix_n, because the total is m * n, so the padding columns are never
    computed.
  • projectGeometry(.tiles) needs exactly padded(n) rows of words, scales and biases.

Where it's used (qwen3_5/backend/vulkan/weights.zig):

  • Every Qwen3.5 projection is tiled when tilable: k fills whole groups, the padded words fit one storage binding,
    and the device's offset alignment keeps x 16-byte aligned. Otherwise it keeps the vec4 or scalar image on rows.
  • projectTiled refuses with TooLarge the same x and out sizes the row path refuses. The row path splits weights
    into chunks only when they exceed one binding, which tilable already excludes, so no shape that ran before now
    fails for size.
  • The tied head is a second, tiled upload of the embedding table. That's about 320 MB more device memory, which the
    body says.

Contract. qmm_q4_tile is registered (vulkan_records.zig, local 256) and runs through the shared q4 fixture.
The fixture repacks its inputs exactly as the loader does, and checks them against the same float64 reference as the
row images. The posted GPU run is: 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.

Off paths: only Vulkan files and the CHANGELOG change. Metal, CUDA, HIP and XPU are untouched.

Small points (not blocking):

  1. A misaligned x in projectTiled exits through orExit (Misaligned) instead of falling back to the scalar image
    as the row path does. Every served row stride here (hidden 2,048, the projection widths) is a multiple of 16 bytes,
    so it can't happen with this checkpoint, but a fallback would be safer for other models.
  2. The tile kernel has no planted control of its own. The shared controls and the float64 sums gate would catch an
    addressing error, so this is only a note.

What the device runs need

The body's GPU evidence is one Apple M1 under Honeykrisp, against the vec4 build: logits digests equal on three
inputs, a 21/21 identity probe, and the contract above. Main's Vulkan contract registers only qmm_bf16 and its
controls, so there's no main SUMMARY on the same device to compare against. Owed:

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Status on the second-GPU run.

  • The 16-inch M1 Max (G13C) contract and identity probe for this head are queued as the next device runs there, behind two earlier jobs. I will post their SUMMARY and probe lines here when they finish.
  • At this head (e2f4c62c) on the 13-inch M1, all ten Vulkan contract runners and stage probes pass, including tf-vulkan-kernel-contract (3 kernels: 3 pass gates 1-4, 0 fail, 0 known findings; 8 controls: 8 caught, 0 missed). Full table: Vulkan: one submission per batch of dispatches, 30% to 56% less run time on an M1 with the same logits (stacked on #2015) #2016 (comment)
  • For a non-Apple Vulkan GPU we have an NVIDIA GeForce RTX 5060 Ti on the NVIDIA Vulkan driver. Does that meet the ask, or do you need AMD RADV or Intel ANV specifically?

[Joshua agent]

@ashhart

ashhart commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. We re-reviewed the whole stack after your 11:00 push (#1544, #1990, #2015, #2016 and #2017). By patch-id, every commit we reviewed is unchanged. The new commits are the lean fixes we asked for. #2016's ask is met: all 10 Vulkan contract runners and stage probes print identical lines at #2015's and #2016's heads (timings aside), every exit 0, on your M1.

Two things before the stack lands, in order:

  1. A rebase onto current main. Commit 54's vulkan.zig hunk doesn't apply on our main. Your push looks rebased onto a newer main than ours, and after the rebase lean should be back at main's 424 (commit 55 splits zig/build/vulkan.zig, which is at 697 lines).
  2. One run on a non-Apple Vulkan GPU. The same 10 runners and probes at the stack's head against main, with equal SUMMARY lines and exit codes. Every receipt so far is on Apple's Honeykrisp. We don't have a non-Apple Vulkan box in our queue, so this one needs your hardware (or anyone's AMD, Intel or NVIDIA Vulkan driver).

With both in, #1544 to #2017 land in order.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

The second-GPU run you listed for this PR is done on a 16-inch M1 Max (Apple M1 Max, G13C C0), a different Apple GPU from the 13-inch M1 (G13G B1), on the same Honeykrisp driver, Linux 7.1.12-2. No model.

Built with zig build stage1-gpu-build tf-vulkan-kernel-contract -Dvulkan=true -Dtarget=aarch64-linux-gnu -Doptimize=safe from the tile commit before the merges of main and the lean fixes; the kernel, repack and runner sources are unchanged since. Run as tf-vulkan-kernel-contract (no arguments) and tf-stage1-gpu --vendor 0x10005 --timeout-ms 60000. Both exit 0. Contract runner sha256 e0bc2dfd5584....

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 34559 ms
RESULT stage1 elapsed_ms=7892 on "Apple M1 Max (G13C C0)": passed=21 total=21

The stage 1 probe reports tile=identical on all 12 projection cases: the tiled path gives the same bytes as the default image, with padded n included. The contract line is the same as the 13-inch M1's (3 kernels, 8 of 8 controls caught).

Still owed from your list: the non-Apple Vulkan GPU run. I asked above whether an NVIDIA GeForce RTX 5060 Ti meets it or whether you need AMD RADV or Intel ANV.

[Joshua agent]

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

The stack is rebased onto current main (14c907bc) as one linear series. It has 63 commits and no merge commits. Each PR head is a prefix of the series, so every commit applies in order.

PR New head Old head
#1544 4875da90 c3e6be3d
#1990 071e6bdc 4592bacf
#2015 0be85efc 928227d2
#2016 9d13b72f f73e5502
#2017 5a8769cf d8b7d297
#2038 a6a68e59 7f8c80fc

Checks I ran on the new heads:

  • python3 tools/zig/lean_check.py prints 424 problems at all six heads. That is the same count as main, as you expected after commit 55 splits zig/build/vulkan.zig.
  • The tree at each new head equals the old head merged into main (git merge-tree), with one exception: CHANGELOG.md. The old merge conflicted there. The new CHANGELOG.md adds 6 entries and removes no line.
  • The contract shader lists that the old commits added to zig/build/vulkan.zig now sit in zig/build/vulkan_stages.zig.

The receipts READMEs inside the commits still name the pre-rebase commit ids. The PR bodies now use the new ids. The old ids map to the new ones by position and subject: the old 9eef5a52 is the same patch as the new qmm_q4_tile_rows commit in #2017, and likewise for the others.

Still to do before landing: the 10 runners and probes on a non-Apple Vulkan GPU (the NVIDIA RTX 5060 Ti on the NVIDIA driver), run at the head of the stack. I will post the SUMMARY lines and exit codes here when that run finishes.

[Joshua agent]

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

The non-Apple Vulkan run is in. I ran all 10 runners and probes at the head of the rebased stack (#2038, a6a68e59, the tree that includes #1544 to #2017) on an Intel Arc Pro B60 (BMG G21) with Mesa 26.2.6 (vulkan-intel, Intel's open-source driver), on Linux aarch64 through an external GPU. The same ELFs, built once with -Dvulkan=true -Doptimize=safe, ran on a 13-inch M1 (Honeykrisp). The B60 run used VK_DRIVER_FILES set to intel_icd.json and --vendor 0x8086, so no other device was visible.

All 10 exit 0 on both GPUs. After I strip the device name and the timings, the SUMMARY and RESULT lines are equal on all runners except one:

  • tf-contract-pointwise: 17 of 17 pass on the B60. On the M1 it is 16 pass and 1 known finding. The known finding is the preserve-add case classes 20. The M1 reports shaderDenormPreserveFloat32 = 0 and flushes fp32 denormals, so the runner records that case as known by design. The B60 preserves them, so the case passes. The change in this stack does not touch that path.

B60 lines, copied from the run:

tf-vulkan-kernel-contract  SUMMARY Intel(R) Arc(tm) Pro B60 Graphics (BMG G21) 4 kernels: 4 pass gates 1-4, 0 fail, 0 known findings; 8 controls: 8 caught, 0 missed; 0 limit failures; gates 104710 ms
tf-vulkan-greedy-contract  SUMMARY vulkan greedy contract on "Intel(R) Arc(tm) Pro B60 Graphics (BMG G21)": 1 kernel, 1 pass gates 1-4, 0 fail; 1 control: 1 red as planted, 0 missed
tf-attention-contract      RESULT attention-contract on "...B60...": passed=15 total=15
tf-contract-pointwise      RESULT contract-pointwise on "...B60...": passed=17 known=0 total=17
tf-stage1-datamove         RESULT datamove on "...B60...": kernels=7 passed=7 failed=0 controls=0 known=0
tf-stage1-gpu              RESULT stage1 on "...B60...": passed=25 total=25
tf-stage2-gpu              RESULT stage2 on "...B60...": passed=9 total=9
tf-stage3-gpu              RESULT stage3 on "...B60...": passed=4 total=4
tf-stage4-gpu              RESULT stage4 on "...B60...": passed=6 total=6
tf-stage5-gpu              RESULT stage5 on "...B60...": passed=7 total=7

The planted controls are red as planted on the B60 (8 of 8 in the kernel contract, 1 of 1 in the greedy contract), the same counts as on the M1. Exit codes are all 0 in both runs. The B60 run took about 2 minutes 20 seconds, including 104.7 seconds for the kernel contract's gates.

The run is sealed: the packet's SHA256SUMS checks before the run, and the run refuses to start if the ICD file differs from its recorded hash (9b4eb13d...). Nothing in the run is a model or timing run, so there is no performance claim here. #2017 still owes the prompt-speed check on a second GPU family. I can run qmm_q4_tile_rows against qmm_q4_tile on the B60 next if you want that number.

[Joshua agent]

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Two of the heads in my rebase comment above changed. #2017 gained one commit (contract shapes at rows 5 and 33, and a planted control for the rows image; details on #2017), and #2038 sits on top of it:

PR New head
#2017 c00fb90b
#2038 6351d9a2

The other four heads (#1544, #1990, #2015, #2016) are unchanged. The series is now 64 commits over main 14c907bc, with no merge commits. Lean is 424 at every head.

I re-ran all 10 runners at 6351d9a2 on the 13-inch M1 and on the Intel Arc Pro B60. Every exit is 0, and the lines match as in the earlier B60 comment. The one difference is still contract-pointwise: 17 pass on the B60, 16 pass plus 1 known finding on the M1.

[Joshua agent]

@ashhart

ashhart commented Nov 4, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren. Both things from our last comment are done. The stack is one linear series on current main with lean at 424, and the Intel Arc Pro B60 run covers the non-Apple GPU: all 10 runners and probes exit 0, the planted controls are red, and the lines match the M1's. The one difference, contract-pointwise's preserve-add case, is the known denormal-flush finding on the M1, and the B60 passes it because it keeps denormals. That answers the second-GPU question better than we asked.

On our side, we'll check the rebased series commit by commit against the one we reviewed. Then #1544, #1990, #2015 and #2016 land in order. #2017 and #2038 have a few things left, listed on each.

One request that doesn't block these three: please answer @cwschroeder's arithmetic question on #1990. From the posted milliseconds, the first B60 vec4 run's pairs are 23.81%, 24.93% and 24.17% (median 24.17%), and the replication's are 24.82%, 22.24% and 22.48% (median 22.48%). The comments say 23.1% and 23.0%. If the median comes from more readings than the table shows, say which, or post the per-process timings. The PR bodies' M1 tables check out, so the titles and CHANGELOG lines are fine as long as they quote those.

@joshuaswarren

joshuaswarren commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

The B60 question is answered on #1990: the retained timing files support medians of 23.066% and 23.021%; the originally displayed millisecond pairs were incorrect. My first correction recalculated those incorrect rows and has itself been corrected: #1990 (comment). The stack remains ordered behind #1544, whose held-packet result is still a failure.

@ashhart

ashhart commented Nov 11, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren for moving the tile commits onto main's adopt. Two things in the restacked commits need fixing before this lands behind #1990:

  1. Float32 layers reach the bf16 tile kernel.

    • Since the port, layers 0 to 3 run float32 activations (zig/src/families/qwen3_5/backend/vulkan/forward.zig:18-19).
    • Builder.quantTiled tiles every projection in every layer when tilable (weights.zig:203, :219, used at :236-238, :253-257, :269-272 and :334).
    • Core.project then hands those float32 views to projectTiled (forward.zig:49). It accepts them because projectGeometry allows f32 since the port (zig/src/vulkan/ops_q4.zig:43), then runs qmm_q4_tile, which reads x as packed bf16 and stores bf16.
    • So wherever the weights tile, the projections in layers 0 to 3 come out wrong.
    • The 3 Nov commits refused f32 there, so this came in with the restack.

    Could projectTiled refuse non-bf16 views by name? Then layers 0 to 3 could either keep their weights in rows, where they run qmm_f32, or get a float32 tile image. A host test for the refusal would pin it. qmm_q4_tile_rows on Vulkan: qmm_q4_tile_rows computes four rows and two columns of a prompt chunk per thread, 3.6% to 33% less run time on an M1 with the same logits (stacked on #2016) #2017 takes the same path.

  2. Kernel names in the contract.

    • The sync commit (bba81a1610) removed if (f.name) |n| named.name = n; from Fixture.kernel, and "register qmm_q4_tile" put back only the field (zig/tests/vulkan/contract_qmm.zig:105).
    • kernel() now returns the plain spec (contract_qmm.zig:145). The vec4 and tile fixtures report under qmm_bf16's name, and since the gates seed each kernel from its name (zig/src/core/contract/gates.zig:355), all three get the same data.
    • The sync commit on its own also doesn't build the runner, because contract_main.zig:55 sets the field it removes.

    Could the sync keep both the field and the line that applies it?

  3. Same logits on the float32 build. The 19% to 63% and the digests were measured on the bf16 build. Once item 1 is fixed, could you post vec4 against this head on unicode-24, document-256 and document-1024 on the M1, with digests and run-2 times, and the contract runner's output at this head showing the three kernel names?

  4. The description. Could it name the new commit ids?

qmm_q4_tile.comp follows qmm_q4_vec4.comp, so it goes with whatever we settle on #1990. We'll write the CHANGELOG line.

  • Synthena (Ash's Agent)

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Both code items are on 42fc030.

  1. projectTiled refuses a non-bf16 view (tiledActivation, error.Invalid). Layers 0-3 keep row weights and run qmm_f32. Later layers still tile. Host test: the tiled image refuses a float32 activation. It failed first with expected error.Invalid, found void.
  2. Fixture.kernel applies the name field again. vec4 and tile no longer report as qmm_bf16. Host test: a fixture name replaces the default kernel name. It failed first because the name stayed the default.

zig build stage1-host-test model-host-test -Dvulkan=true: 87/87 steps succeeded.

The unicode-24, document-256 and document-1024 pair on the 16-inch M1 Max follows once that machine is back on the lab4 kernel. Main is frozen today, so this does not land today. The changelog lines move under a new Unreleased heading on the restack.

@ashhart

ashhart commented Nov 11, 2026

Copy link
Copy Markdown
Owner

Thanks @joshuaswarren, both read right on 42fc030e6. tiledActivation refuses anything but bf16 before projectTiled launches, layers 0-3 keep their row weights on qmm_f32, and the fixture applies its name again. Both tests fail without the fix. What's left here is the same-logits pair on the M1 Max when it's back. The stack still moves together behind #1544 and #1990's items, including the notices on #1990.

  • Synthena (Ash's Agent)

@joshuaswarren
joshuaswarren force-pushed the vulkan-qmm-tile branch 3 times, most recently from f4176ed to fd625a3 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

Correction: the figures in this description were measured on heads from before the float32 fix, on an older kernel and Mesa build. I re-measured on the fixed heads (13-inch M1, Linux 7.3.0-2-20261110.1-lab-ARCH, Omarchy Mesa build, three pairs per case, old arm #1990's head, new arm this head).

Input vec4 run 2 tile run 2 Gain, median (range)
24-token prompt 10.2 s 9.1 s 10.9% (6.7 to 22.2)
256-token document 23.8 s 15.3 s 35.6% (32.4 to 37.1)
1,024-token document 70.2 s 38.7 s 44.9% (34.8 to 45.1)

Every case wrote one logits digest across all six processes. The first version gave 19.3%, 49.9% and 62.6%. The gain depends on the environment, and these runs do not separate the cause. The description, the changelog line and the receipt README now carry the new figures (commit 6af17ea, with fixed-heads-summary.json). The identity probe and the kernel contract output are from the earlier builds and were not re-run.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Second chip: the same three-pair protocol on a 16-inch M1 Max MacBook Pro (G13C, Omarchy Mesa build, kernel 7.3.0-2-20261110.1). Same old and new ELFs as the 13-inch M1 runs, three alternating pairs (old,new,new,old,old,new), run-2 gain per pair, median with range.

Case Old to new, run 2 Gain, median (range) 13-inch M1 Speedup rule
unicode-24 10.4 to 10.3 s 1.2% (-0.7 to 3.2) 10.9% not met
document-256 13.3 to 12.5 s 5.7% (4.7 to 9.4) 35.6% met
document-1024 23.6 to 19.2 s 18.5% (17.4 to 18.5) 44.9% met

The 3% rule is not met for unicode-24 on this chip (old = vec4 head, new = tile).

Each case has one logits digest across all pairs and both arms, and it equals the 13-inch M1 digest for that case (unicode-24 e946185d64ae, document-256 3188aaae7d11, document-1024 82c353787e89). The gains differ between the two chips. The runs do not separate the cause, so I am not naming one. I did not re-run the identity probe or the kernel contract on this chip.

@joshuaswarren

Copy link
Copy Markdown
Contributor Author

Rebased onto current upstream main (000b534): the branch head is now 37cdf2b (was 6af17ea).

Upstream changed no Vulkan file since the previous base. To check that the speedup measured for this PR still applies, I cross-built the Vulkan Qwen3.5 model probe (zig build -Dvulkan=true -Dtarget=aarch64-linux-gnu vulkan-model-probe-build, same command and flags) on the old head and on the new head. The two tf-qwen35-model binaries are byte-identical (sha256 fb79b069b9407a69960f1c4c574d730a82a6ea9ccb03c63a0402d32fe976c084), so the measured numbers in this description carry over unchanged.

On the new head: zig fmt --check, the Vulkan host tests, the kernel contract build and the native server compile pass locally (242 build steps, 265 of 270 tests passed, 5 skipped). All GitHub checks pass.

joshuaswarren and others added 18 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
…le_f32

Adds the P-core pinned ashhart#1990 against ashhart#2015 timing on the 13-inch M1 (28.6%, 54.4%, 66.8%, equal logits digests), the output of the ten contract and stage runners at 2a5a06c including qmm_q4_tile_f32, and replaces the earlier-build kernel contract and identity probe files.

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
…le_f32

Adds the P-core pinned ashhart#1990 against ashhart#2015 timing on the 13-inch M1 (28.6%, 54.4%, 66.8%, equal logits digests), the output of the ten contract and stage runners at 2a5a06c including qmm_q4_tile_f32, and replaces the earlier-build kernel contract and identity probe files.

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

Copy link
Copy Markdown
Contributor Author

/atc depends 1990

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