Repository navigation
gpu: make the tiled and single-dispatch decode paths byte-identical in f32 (stacked on #3431) - #3640
joshuaswarren wants to merge 473 commits into
Conversation
… -Dcontract-root option The contract runner built only the Q4 projection's shaders. Each later operator registers in the same runner, so it now imports the stage 1 to 5 shader modules (norm, rope, attention, GDN, greedy and the data-movement kernels) that the operator probes already build, and the stage modules are hoisted out of their probe blocks so both can share them. -Dcontract-root points the runner at another root file, so one operator group can be built and run on its own.
…nel contract The stage 4 GatedDeltaNet images (conv_dw1d, gdn_conv_decode, gdn_split, gated_delta_prefill_ash and gated_delta_decode in its ASH_QWEN35 raw-gates mode) register as eight kernels through the production Gdn wrapper, so the wrapper's binding tables — the read-only g slot and the single-chunk snapshot dummy among them — are the ones under test. f32 state flows in and out of place, the interior chunk snapshot is bound exactly when chunks exceed one, and the decode loop chains the carried state. References are the stage 4 fixture's f64 walkers made parametric in tokens; every depth a spec states is a function of the token count (one ~130-deep state update per token, the fixture's stated derivation). The f32 state parts prove fp32 sums with an engineered stress fill whose kv partials overflow fp16; the bf16 parts declare bf16=0 with the reason the output's own rounding hides the sum error, as HIP's mamba and CUDA's gdn_prep do. The host suite cross-checks the walker against the fixture's bit for bit and proves the generated fills against the references without a GPU. contract_gdn_main.zig runs the group alone via -Dcontract-root and prints the same LIMITS lines, records audit and runAll tally as contract_main, plus live local-size and shared-memory evidence for all seven pipelines. Proven: zig build vulkan-host-test (20 gdn contract tests, walker parity with fx.RecurWalk/fx.Decode, stress fp16 margins >= 100x); both contract runners build; the runner refuses the software Vulkan device fail-closed. GPU gates 1-4 pending on the M1/M2 devices (none reachable from this host: llvmpipe only).
…e run Three fixture bugs the M1 Max's first run surfaced, none of them shader bugs: the split parts uploaded one combined output buffer where the wrapper binds soa, g and beta separately (OutOfRange on every gate); the decode conv's unchanged-check listed the host chain scratch as an input while indexing one device buffer fewer, so input_now's tail was never filled (a false 'a run changed its inputs'); and the prefill recurrence's random fill used the stage 4 fixture's ranges, which only ever ran at 8 tokens - at 130 the walk outgrew f32. The random fill now decays (g, beta and the whole soa at 2^-3 scale or less), so any token count stays bounded. Also the sums replay the gates ran: every dot re-summed in the requested accumulator and order, the conv chains replayed from the uploaded initial state, exactly as computeWant walks them. Proven: vulkan-host-test green; runAll on Apple M1 Max (G13C C0) Honeykrisp - prefill conv, decode conv and decode state pass gates 1-4 fully; prefill y, hf+snap and split classes settle with the fill fix pending the next device run.
…the soa sums proof The M1 Max run showed the split g shapes gate failing where a random a_log above ~2.4 drove g into f32 subnormals the device flushes - the exact case the stage 4 fixture's census deferred to Main. The served random fill now draws a_log in [-6, 0] (g >= e^-4.5, normal), with the census case named in the fill; the subnormal-flush decision stays with Main. The split soa sums gate moves to f16=0 with the measured reason: the fixture budget's magnitude term at the output's scale is wider than any fp16 miss the stress can engineer, and gate 3's shapes already bound the norm's sum to f32 quality (a bf16-summed ss misses ~2^-8 relative against an observed worst of 0.037 of bound). Proven: vulkan-host-test green.
…tes 1-4 cast_f32_bf16, cast_bf16_f32, copy_u32, copy_u16, gather_u32, gather_u16 and dequant_bf16 register with the kernel contract, bit for bit (a NaN keeps its class; a non-finite dequant scale or bias is checked by class; every gather run includes an out-of-range id whose stated rule is the documented zero row). tf-stage1-datamove runs the group on a real GPU (zig build stage1-datamove) and refuses CPU devices; the stage 1 imports hoist so the probe and this runner share them. Ported from w7p/native-vulkan's a3f040c onto the engine-pr2 tree: the files needed no source change; the wiring reuses this tree's hoisted stage1_shaders module. Proven: zig build -Dvulkan=true stage1-gpu-build and vulkan-host-test pass on this box (llvmpipe only); tf-stage1-datamove --help exits 0 and the runner fails closed (exit 1) with only the software device present.
rope_bf16 and sdpa_rows_bf16 against stage3_fixture's f64 references generalized past the fixture's 8-key score buffer to the served shapes (decode rows 1, prefill rows <= 32, visible keys 1..7168 on the 16-key tile, 256-lane scan and 1024-thread stride edges and the kStreamKeys bound). The sdpa bound is derived from the shader text -- denominator depth ceil(n/256)+8, the 256-lane strided chains plus the 8-level tree, NOT the plain n-term sum -- and pinned to the source by a host test. Single-key rows carry the V bits exactly; multi-row prefill rows decode alone bit-identical. Ported from w7p/native-vulkan-model's 60a22e7 onto the engine-pr2 tree: the files needed no source change; the wiring reuses this tree's hoisted stage1/stage3 shader modules. Proven: zig build -Dvulkan=true stage3-gpu-build, stage3-host-test and vulkan-host-test pass on this box; tf-attention-contract --help exits 0 and honestly refuses this box's software llvmpipe (exit 1). Real-GPU run needs the Apple Vulkan rig.
The greedy draw — finite_logits, argreduce_chunk and argreduce_combine behind one submission, three launches inside the run hook — registers through gates 1-4, plus the planted control contract_controls_greedy.comp (the mirror of HIP's tf_ctl_fmax_max: a row max that drops a NaN), registered with control = .nonfinite and required to go red. The acceptance is exact: the token equals the host greedyRef (max wins, ties to the lowest index, +0/-0 equal), a planted non-finite row refuses naming its first offender, repeats are byte-identical, inputs and guards untouched. Ported from the greedy agent's files on w7p/native-vulkan-model onto the engine-pr2 tree: the files needed no source change; the wiring compiles the control beside the stage 5 variants and reuses this tree's hoisted stage5_shaders module. Proven: zig build -Dvulkan=true stage5-gpu-build, stage5-host-test and vulkan-host-test pass on this box; tf-vulkan-greedy-contract --help exits 0 and the runner fails closed (exit 1) with only the software llvmpipe present.
…ion shapes contract_pointwise.zig states and checks the six pointwise closures of stages 2-4 on the host: the stage 2 trio reuses stage2_fixture, the f32-preserving residual add claims the exact f32 sum bit for bit (a flush-to-zero device fails HONESTLY), the attention output gate uses boundExact with ops 4 mids 1 and demands signed-exact zeros, and the gated RMSNorm uses the rows family bound plus ops 10 mids 12 with nan/inf/±0/zero-row/nan-row controls class-checked. Every checker also refuses a corrupted output, a sign-flipped zero and a planted nonfinite. contract_pointwise_main.zig drives all six on a real GPU through the wrappers' exact dispatch shapes (NormMlp for stage 2; the preserve add, gate and gated norm at attention.gatePlan's and gdn.gatedNormPlan's geometry), three byte-identical repeats per case. Ported from w7p/native-vulkan-stage2 (c0ee7bf + eb72415) onto the engine-pr2 tree. One source adaptation: this tree's NormMlp.Shaders gained the add_preserve_bf16 field, so the runner now serves it (the image this tree's stage 2 closure already compiles); the shader sources themselves landed with this tree's stage 3/4 closures. Proven: zig build -Dvulkan=true contract-pointwise-build, vulkan-host-test pass on this box, and zig-out/stage{2,3,4} carries the six images; tf-contract-pointwise --help exits 0 and the runner fails closed (exit 1) with only the software llvmpipe present.
… cross target The datamove test module was built for -Dtarget, so a cross build (aarch64 on the x86 build host) failed with 'unable to spawn foreign binary' in vulkan-host-test. It now gets its own host-target module like every other host suite. Proved by: vulkan-host-test and all stage and runner build steps pass with -Dtarget=aarch64-linux-gnu (224/224 steps).
… and u16 copy On a real device (Apple M2 Max, Honeykrisp) the shapes gate failed three kernels with the Zig error Misaligned: the gate's edge shapes include odd element counts, and a 16-bit range of an odd count is not bindable (dispatch.bind needs whole 32-bit words; View.init refuses the same ragged tail), so the fixture's view call raised an error that the gate scored as FAIL. The kernel refuses that edge, so prepare now returns false for it (an edge refused by the kernel, as the gates count them); served shapes (146x1, 3x700, 300x1, 2x520) are all even. Proved by: vulkan-host-test and stage1-gpu-build pass for aarch64 (81/81 steps, 210/212 tests, 2 skipped). Not proved: no device rerun yet.
…hat prepare sized The M2 Max's run of the gdn group died in gate 1 of the prefill_y kernel: "index out of bounds: index 524288, len 10248" at contract_gdn.zig's uploadBuffers, called from the nonfinite gate's prepare. 524288 is 2 * state_elems and 10248 is 5 * linear_dim + the guard words, so the sliced region belonged to a different kernel: the prefill arm uploaded the same buffers for prefill_y and prefill_state, and the state's region (prefill_y's out holds y only) was sliced out of a much shorter out. The upload path now lives in one place, uploadWords, which hands each device buffer the words it takes: a checked output its own region of out, an output no fetch reads fresh poison scratch, and every region bounded by what prepare sized, so a mismatch is an error the gate reports instead of a panic that kills the runner. The prefill_y and decode_state outputs that no fetch downloads take scratch, the checked ones keep out's region, and every other arm keeps the bytes it had. Proof: a new host test drives the gates' own shape sequence (gate 1 and 2's small() shape, gate 3's served and edge shapes, gate 4's stress shape) through prepare and the upload path with no device, and holds every upload inside the region prepare sized and the buffer count at what run() binds. It fails on the old sourcing with the same out-of-range region the device hit (outWords: OutputRegionOutOfRange) and passes on the fix; the whole host suite is 21/21 and the arm64 runner builds clean (100/100 steps). The split g gate's class finding (1 of 128 outputs: nan where float64 gives finite) is untouched: it is a device finding for the maintainer to decide on, not a fixture bug.
…assuming it Why: the repeat gate failed on the PR-B device run with 'a run wrote outside its outputs' (gates.zig intact check). The rig's input() uploaded only the data window at offset guard, so the shell's guard bytes never held the 0xa5 pattern intact() demands — fresh device memory reads as zeros, and the gate was false on every run of every shape. The draw itself never writes the shell (its outputs are the internal partials and results buffers, the same shape HIP's argmax contract declares via rig.scratch/rig.output), so the guard finding was a runner bug, not an overrun. What: Rig.input builds the full shell through a new shellFor (pattern, data, pattern) and uploads it at offset 0, the way the datamove rig's slot() already did. New host test pins the layout: guards patterned on both sides, data between, exact length — the invariant the old code never stated anywhere. Proof: zig build vulkan-host-test stage5-gpu-build contract-pointwise-build contract-pointwise-host-test (shared cache) green: 103/103 steps, 22/22 tests, including the new shell test. The gate's strictness is unchanged; a real overrun still fails intact(). The gate line's device-side pass still needs its device run, which is out of scope for this offline fix. Build log: scratch/atc-vulkan-native-20261026/prb-fix-gp-build.log
…ally built Why: the PR-B device run failed all three preserve-add cases and the plain add's classes case. The preserve fixture modeled a pipeline nobody builds: it filled f32 buffers and demanded exact f32 sums, but add_preserve_bf16 is binary_vec.comp with -DPRESERVE_F32 over the default bf16 storage — the -DUSE_BF16 the build passed alongside it matches no ifdef in the shader (storage variant is USE_FP16/default), so the device ran the bf16 add reading u16 halves of f32 bits. Every reported got matches that model bit for bit: cancel element 0 is widen(0x293a)+widen(0x293a) stored bf16 0x29ba (read back as u32 0x000029ba), random element 0 is 0xbed4fbc2, classes element 6 is the j=12 NaN 0x7fc0 beside the j=13 overflow +inf 0x7f80 = 0x7f807fc0. The plain add's classes failure was a runner gap: stage2's measured-property policy (allow_subnormal_flush from shaderDenormPreserveFloat32, as stage2_probe wires it) was never applied, so the subnormal rows were checked strictly regardless of the device's reported float controls. What: PreserveAdd and PreserveCase become aliases of stage2.Add/AddCase — one model of the pipeline (f32 add, one RNE bf16 store), two pipelines — and the preserve gate checks strictly (no flush qualification ever): a device that flushes fp32 denormals fails the subnormal classes rows as an honest finding, printed by a NOTE, never fitted away. addGate now wires the stage 2 policy from the device property and the device line prints preserve32/flush32 so the next run is decidable. The inert -DUSE_BF16 is dropped from both binary_vec build entries and the stale 'compiled without -DUSE_BF16 stores exact f32' comments are gone. A host test scans the embedded SPIR-V: add_preserve_bf16 declares OpCapability DenormPreserve (4464), add_bf16 does not — a define that matches no ifdef can never silently produce the plain add again. Proof: shared-cache build green, 103/103 steps, 22/22 tests, including the rewritten preserve tests (subnormal want 0x0002 must stay refused when a device flushes) and the capability scan; the generated images were verified directly (4464 present only in add_preserve_bf16). Build log: scratch/atc-vulkan-native-20261026/prb-fix-gp-build.log
gated_delta_decode, gated_delta_prefill_ash and gdn_split quieted every value whose exponent is all ones and whose top mantissa bits are zero: (bits & 0x7fff0000) == 0x7f800000. That test is true for +-inf (0x7f800000), so the helper returned 0x7fc0 (NaN) for an infinity; only a NaN with a payload in the low 16 bits was meant. In the gate chain s = bf16(a + dt) an infinite a became NaN, then softplus and g were NaN where float64 gives exp(-inf) = 0. Found by the kernel contract's nonfinite gate on Apple M1 and M2 Max (3 FAILs: split g 1 of 128, decode y 896 of 16384, decode state 16384 of 262144 outputs differ in class). The first diagnosis blamed exp(-inf) in the driver; a bit-level emulation of the helper shows 0x7fc0/0xffc0 for +-inf, so it was our helper. Every other shader here already uses isnan(value); these three now do too. Finite values are untouched (same bits), NaN stays a quiet NaN. Proved by: bit emulation, vulkan-host-test and every stage and runner build for aarch64 pass; not yet re-run on a device.
…device finding On Apple M1 and M2 Max under Honeykrisp the device reports shaderDenormPreserveFloat32 = false and flushes fp32 denormals, so the preserve-add classes case reads the bf16 subnormal sum 0x0002 as 0x0000. The runner now prints KNOWN (not FAIL) and counts it apart from passes when every mismatch is a subnormal sum read as a same-signed zero and the device reports no denormal preservation; a device that claims preservation and flushes, or any other mismatch, stays a FAIL. The RESULT line carries known=N. Proved by: host tests and the aarch64 build (224/224 steps); not device-run yet.
…etry, a run that always answers Why: the device run died with a bare 'error: Invalid' in the first gated-norm case and never printed RESULT. gatedNormGate called gdn.gatedNormPlan with the fixture's 2048-element weight, but the production gated norm is PER HEAD (gdn.Model: 16 head rows of 128 a token, the [128] gain indexed by the column within the head and shared by every head) and the plan refuses any other weight width — the gate had never reached a device. The fixture modeled a 2048-wide global row; nothing in the kernel computes that. What: - The fixture is the production geometry: tokens x 16 head rows of 128, head-major, the [128] gain at the column; the f64 reference computes the norm per head row and the poison cases prove head isolation (an inf/nan input poisons only its own head row). Served shapes are the tokens the engine serves: one decode row and a whole prefill chunk of 32 (qwen3_5 vulkan forward, max_prefill_rows), plus the controls on three. - The bound is re-derived for the 128-wide reduction, honestly: 256 threads over 128 columns = at most one square per thread (1 rounding) + 8 tree levels (zeros exact) + the mean divide = 10, depth stated 12; gamma(12, 2^-24) ~ 7.2e-6 against the old 2048-row figure gamma(20) ~ 1.2e-5 — the bound is TIGHTER, not loosened. ops 10 and the mids argument are unchanged (per-element, depth-independent). - No gate can kill the run: every case goes through a guard that prints 'FAIL <gate> case=...: <error name>' and the loop continues; the RESULT line (passed, known, total) always prints and the exit is nonzero exactly when passed + known falls short of total. - The preserve-add KNOWN case now prints only its KNOWN line (the reasoning folded into it); the FAIL and NOTE lines are kept for genuine mismatches. - Host tests: the plan accepts every fixture case's dimensions and refuses the old 2048-gain shape (the exact call that died on device), the fixture's element counts, the per-head reference (finite off controls, signed zeros, head-isolated poison), and the checker refusals. Proof: shared-cache build green — 106/106 steps, 178/180 tests passed with the 2 pre-existing skips (device/env-gated); a fully cached rerun shows zero failed steps. Build log: scratch/atc-vulkan-native-20261026/prb-fix-gn-build.log
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.
…tiled prefill Three tiled cases (rows 2, 17, 64) plant NaN, +inf and -inf over keys past row 0's bound but inside the loaded chunk, and past the served keys into spare capacity. The rows 2 case is the review's repro: zero Q/K, V0 = 1, V1 = NaN, so row 0 must come out exactly 1.0. Each case runs the tiled path and the replaced per-row decode kernel and requires byte-identical complete outputs, finite outputs for the rows whose windows hold only finite values, and non-finite outputs where the plants are genuinely visible, on the bf16 and f32 paths. On the pre-fix shader all three cases fail at element 0 on a 16-inch M1 Max; with the causal-bound guard all six case runs pass and the whole gate reads passed=21 total=21. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
CI fmt job flagged contract_attention_main.zig. Whitespace only.
… plant the cancel fill only for the cancel cases Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> # Conflicts: # CHANGELOG.md
Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
The decode SDPA kernel runs one workgroup per head, 8 in all, and each walks every visible key. The tiled scores, softmax and PV dispatches spread the keys over many workgroups and keep the same accumulation order. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> (cherry picked from commit b8b6341)
…ow over 511 to 2048 keys The attention gate compared tiled output against attend() at one row as the old path, but attend() now routes one row over 512 or more keys through the tiled path, so that reference is the tiled path itself there. The decode cases check against an f64 reference inside a bound, not byte for byte, and the tile cases use dyadic data whose f32 sums are exact, so a different summation order never shows. attendOn(path, ...) forces the single or the tiled dispatch; attend() is attendOn(.auto, ...) with the same routing. routeGate decodes one row both ways for 511, 512, 513, 1024, 1025 and 2048 keys, bf16 and f32 queries, dyadic and uniform data, and prints the mismatch count and max abs difference. Built for aarch64 with stage3-gpu-build; not yet run on a device. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
The single-dispatch decode arm computes every product with explicit fma; the tile kernels used plain mul-add and left contraction to the driver. Apple contracts both the same way, so the gate was byte-identical there; the NVIDIA driver does not contract the plain adds, and the f32 tile path then diverges from the f32 decode path by one to two ulp whenever a product is not exact: the attention gate failed 3 of 24 route cases (f32, uniform data, visible keys 511, 513, 1025) and the f32 poison tile cases on the RTX 5060 Ti while the 13-inch M1 passed 33 of 33. Dyadic data hides it because every product is exact. Explicit fma pins the same rounding on both paths. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
496 and 512 are 16-aligned controls; 508, 510, 511, 513, 514, 1025 are partial-tile cases. On the RTX 5060 Ti the f32 tile path mismatched only at partial key tiles (511, 513, 1025); the sweep tests whether the boundary is exactly keys mod 16. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
…stream probsGate runs the single dispatch through the long (stream) image and the tiled path at 7200/7201/7205 keys, then byte-compares the probability arrays themselves: the single probs from the f32 stream, the tiled probs from the score scratch (probsScratch accessor, Attention.tile_rows exposes the head stride). A prob mismatch convicts scores/softmax; equal probs with differing outputs convict PV. The RTX 5060 Ti sweep pinned the f32 divergence to partial key tiles; this splits which stage rounds differently. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
…udget The first probe fetched the whole 4M-word score scratch through the gate's 1 MiB staging buffer and corrupted the heap (glibc double-free abort on the M1 before any probe line). Fetch each head strip with a source offset instead: 256 KiB per head, well inside staging. The unused probsScratch accessor goes with the fix. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
attendPlan refuses any total past shared_stream_keys without a stream view, path-blind: the probe's tiled call at 7200 keys passed null and got error Invalid before any probability line. The tiled path never reads the stream, so pass the view unconditionally. Also init the probe's deferred slices empty: the ReleaseSafe run showed the error path freeing undefined slices (segfault at 0xaa fill), which masked the real Invalid. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
Both machines agreed: head 0's probabilities matched and heads 1 through 7 mismatched from key 0 with the assumed tile_rows*max_visible_keys head stride, while the outputs stayed byte-equal on the M1 - the assumed layout is wrong, not the GPU. Fetch the whole score scratch (the download API already chunks through staging) and locate each head's qrow-0 strip by search, then compare at the found offsets and print them. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
The probability-array probe on the RTX 5060 Ti convicts PV alone: at 7200, 7201 and 7205 keys the single dispatch and the tiled path produce byte-identical probability arrays (located head strips, 0 of about 57600 words differing) while the f32 outputs differ by one to two ulp in up to 1791 of 2048 elements. The tile PV multiplies with explicit fma; the decode kernel's PV loop still used plain mul-add, and the NVIDIA driver leaves those uncontracted while Apple contracts them, so the two paths rounded differently. Pin the 16-wide loop and the tail to fma; Apple's bits cannot change (its driver already contracted), NVIDIA's single path joins the tile path. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
|
[Joshua's agent] Cross-model review pass at head 00f8467 (reviewer model moonshotai/kimi-k3.1-pro, independent of the implementing model):
Reviewer summary: "numerically sound and appropriately scoped ... aligns the single-dispatch decode path with the tiled kernels on the one rounding site that actually mattered." Supporting measurements in the PR description: attention-contract passed=47 total=47 on both the RTX 5060 Ti (gpu-timeouts delta 0) and the 13-inch M1, probability arrays byte-identical at 7200, 7201 and 7205 keys. |
The chase commits left comment paragraphs past the house lean rules (past 120 columns, consecutive comment lines, a 669-line test file). Merge each pair into a single line under the cap, move the tiled prefill gate into contract_attention_tile.zig, and zig fmt the qmm gate file. tf-attention-contract cross-compiles clean after the split. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com>
3f95be3 to
0727e05
Compare
0727e05 to
3f95be3
Compare
|
[Joshua's agent] A note on the two force-pushes above from this morning (11:20 and 11:24 UTC). A rebase attempt on our side went wrong, and for four minutes this branch pointed at a commit that would have undone unrelated files on main. I have put the branch back to |
|
Thanks @joshuaswarren for isolating the f32 divergence to P·V accumulation and running the 47/47 attention contract on both the RTX 5060 Ti and the 13-inch M1. The explicit-fma changes are narrowly scoped, and the probability-array comparison separates scores from PV as intended. Two exactness issues remain before this stacked branch can land. First, the unresolved #3431 ask still stands: its default 256-key token parity has not been closed by this separate f32 fix. Second, this PR deliberately changes NVIDIA f32 accumulator bits by one to two ulp; please add served greedy token IDs from the same rebased parent and head for the tiled and single-dispatch routes, including the 511/513/1025-key boundary cases. Kernel output parity alone does not show whether served tokens stay unchanged. The supplied diff also conflicts with current main in
|
|
Verified on a different card than the author's runs: jw16 (16-inch), NVIDIA GeForce RTX 5060 Ti (0x2d04), driver 615.78.08, head
The f32 divergence this branch fixes (plain multiply-add in the P·V accumulators vs the decode path's explicit FMA) is resolved on Blackwell sm_120 as well as the author's card. +1 from a third-party repro. — lane w7S |
|
@joshuaswarren Thanks for pinning both P·V accumulation sites to explicit FMA and for the independent 47/47 contract results. Three small items remain:
|
…erved tokens asserted per path ashhart's three ashhart#3640 review items: - sdpa_decode_native.comp's adaptation count covers the two FMA pins (3 lines adapted); - the opening comments of sdpa_scores_tile.comp and sdpa_softmax_rows.comp wrap below 120 columns; - probe_keys gains the default 256-key decode and the 511/513/1025 routing boundaries, and probsGate derives each path's served greedy token from its output row (largest wins, ties to the lowest index, non-finite refuses) and fails unless tiled and single-dispatch serve the same token; the MILESTONE line prints tokens single=<id> tiled=<id>.
|
All three items are in at
The contract binary compiles clean on the Linux host ( |
… omarchy-mlx imports
|
Both landing requirements are met. Commit 9e5b3db on w7p/sdpa-fma-consistency:
Head: 9e5b3db |
[Joshua's agent]
The route gate caught the tiled decode path diverging from the single-dispatch path in f32 on NVIDIA: 3 of 24 route cases failed on the RTX 5060 Ti (visible keys 511, 513, 1025, and the f32 tile poison cases) while the 13-inch M1 passed 33 of 33. Dyadic data hid it because every product is exact.
Chase: a probability-array probe that byte-compares both paths' probability outputs past the shared scratch shows the probability arrays byte-identical on both vendors at 7200, 7201 and 7205 keys (0 of about 57600 words differing, located head strips) while only the f32 attention outputs differ, by one to two ulp in up to 1791 of 2048 elements. That convicts the P·V accumulation alone: the tile PV multiplied with plain mul-add while the decode kernel accumulated with explicit fma; Apple's driver contracts the plain adds, NVIDIA's does not.
Fixes, one per side:
Gate after both: attention-contract passed=47 total=47 on the RTX 5060 Ti (gpu-timeouts delta 0) and passed=47 total=47 on the 13-inch M1. The probability probe stays byte-identical everywhere, and on Apple the bits cannot change since its driver already contracted the plain adds into fma.
The intermediate commits are the gate and probe tooling this chase ran on: the f32 route sweep around the 512 decode routing bound, the shared-probs byte-compare past the stride boundary, per-head-strip tiled probability fetch in the gate staging, the stream requirement on the tiled probe path, and the empirical head-strip layout search (located=8 strips, 12 of 12 datasets, on the 13-inch M1).
Closes #3846.