Skip to content

Inkling 2 Metal: pair K and V short convolutions in one dispatch - #5004

Open
gilby wants to merge 1 commit into
ashhart:mainfrom
gilby:v4-8-paired-kv-conv-rebased
Open

gilby wants to merge 1 commit into
ashhart:mainfrom
gilby:v4-8-paired-kv-conv-rebased

Conversation

@gilby

@gilby gilby commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Before: on main, each gated-attention layer runs short depthwise-separable convolutions for K (conv_k) and V (conv_v) in two sequential dispatches (either two tf_inkling2_conv_static or two tf_inkling2_conv_dynamic launches) with a compute barrier between them before attention projection reads both results.

After: pairs K and V short convolutions into a single dispatch using tf_inkling2_kv_conv_static (grid.z = 2) and tf_inkling2_kv_conv_dynamic (grid.y = 2) in zig/kernels/metal/inkling2/glue.metal, wired through glue.zig, glue_plan.zig, and forward.zig. Adds paired static/dynamic contract parity proofs and planted controls in metal_inkling2_glue.zig, metal_inkling2_glue_kv_conv.zig, and metal_inkling2_glue_controls.zig, with transactional probe acquisition and registration (addAcquired, registerProbe) across Suite.add, Suite.addNanControl, and Suite.addSplit plus host failure-path tests.

Checks on this head

  • Head commit: b01bf9e676
  • Lean checker, python3 tools/pr_check.py --base origin/main --pr 5004 (python3 tools/zig/lean_check.py): lean 164 vs 164, 0 new, 0 error(s), 1 advisory warning (no CHANGELOG.md edit) (9 changed files, all <= 600 lines, max 538 lines); zig fmt --check build.zig zig and git diff --check origin/main..HEAD pass with exit 0.
  • Tests run, with the command and pass, fail and skip counts:
    • zig build -Dcpu=apple_m1 -Doptimize=ReleaseFast: exit 0.
    • zig build compile-inkling2-native-host: exit 0.
    • zig build compile-inkling2-native-host -Dtarget=x86_64-windows: exit 0.
    • zig build -Dfixed-cpu compile-native-cuda-windows: exit 0.
    • zig build test-inkling2-host -Dcpu=apple_m1 -Doptimize=ReleaseFast --summary all: 46/50 tests passed (4 skipped) (skipped: 4 optional checkpoint/tokenizer env tests).
    • zig build test-inkling2-controls-host --summary all: 26/26 tests passed (includes baseline-load failure and FailingAllocator kernel-list OOM rollback tests).
    • zig build test-kernel-contract --summary all: 255/255 tests passed (gate logic, launch limits, Metal launch map 1314 registered launches, 2 controls, 0 missing, Inkling 2 controls, and host contract suites).
    • zig build test-inkling2-metal-host -Dcpu=apple_m1 -Doptimize=ReleaseFast --summary all: 111 pass, 6 skip (117 total) (skipped: env-gated checkpoint/alloc tests and 2 JPEG tests pending newer libjpeg-turbo).
    • zig build tf-kernel-contract -Doptimize=ReleaseFast: exit 0.
  • CI: Rebased onto main (a992d0da99); CI checks pending on this head (b01bf9e676).
  • Not run, and why: Apple M1/M2/M4 and M5 Pro served A/Bs not run for this slice; Apple M3 Ultra and Apple M5 Ultra A-B-B-A runs cover plain and self-drafted decode across c=1,4 and T=0.0,1.0.

Receipt

  • Main against branch: A-B-B-A served runs (tools/bench_concurrent.py --tokens 128 --reps 2, --context 8192 --parallel 4, 0 cross-leg token_sha256 mismatches across all 32 cells on both machines, run prior to the test-harness-only setup cleanup and rebase onto a992d0da99 with identical production shader/dispatch/kernel code):
    • Apple M3 Ultra 512 GiB (main vs branch, Metal 3 overlay):
      • Plain (--no-drafts --parallel 4):
        • c=1: code T=0.0: 12.40 -> 12.45 tok/s (+0.40%); chat T=0.0: 12.50 -> 12.60 tok/s (+0.80%); code T=1.0: 12.40 -> 12.50 tok/s (+0.81%, TTFT -1.20%); chat T=1.0: 12.45 -> 12.55 tok/s (+0.80%).
        • c=4: code T=0.0: 23.60 -> 23.95 tok/s (+1.48%, TTFT -1.70%); chat T=0.0: 24.90 -> 25.15 tok/s (+1.00%, TTFT -1.80%); code T=1.0: 23.75 -> 24.00 tok/s (+1.05%); chat T=1.0: 24.90 -> 25.25 tok/s (+1.41%).
      • DSpark self-drafted (--drafter {TARGET} --parallel 4):
        • c=1: code T=0.0: 17.15 -> 17.20 (+0.29%, TTFT -6.70%); chat T=0.0: 15.20 -> 15.30 (+0.66%); code T=1.0: 14.40 -> 14.40 (0.00%, TTFT -6.93%); chat T=1.0: 15.10 -> 15.10 (0.00%).
        • c=4: code T=0.0: 14.90 -> 15.00 (+0.67%); chat T=0.0: 10.30 -> 10.30 (0.00%); code T=1.0: 12.70 -> 12.80 (+0.79%); chat T=1.0: 10.10 -> 10.20 (+0.99%).
    • Apple M5 Ultra 512 GiB (main vs branch):
      • Plain (--no-drafts --parallel 4):
        • c=1: code T=0.0: 16.80 -> 16.90 tok/s (+0.60%, TTFT -0.96%); chat T=0.0: 16.90 -> 17.00 tok/s (+0.59%); code T=1.0: 16.90 -> 17.00 tok/s (+0.59%, TTFT -6.12%); chat T=1.0: 16.85 -> 17.00 tok/s (+0.89%).
        • c=4: code T=0.0: 37.30 -> 37.80 tok/s (+1.34%); chat T=0.0: 38.40 -> 39.05 tok/s (+1.69%); code T=1.0: 36.95 -> 37.50 tok/s (+1.49%, TTFT -3.51%); chat T=1.0: 38.25 -> 38.80 tok/s (+1.44%).
      • DSpark self-drafted (--drafter {TARGET} --parallel 4):
        • c=1: code T=0.0: 26.05 -> 26.25 (+0.77%); chat T=0.0: 21.20 -> 21.25 (+0.24%); code T=1.0: 19.50 -> 19.55 (+0.26%, TTFT -6.28%); chat T=1.0: 20.50 -> 20.55 (+0.24%, TTFT -1.18%).
        • c=4: code T=0.0: 28.10 -> 28.15 (+0.18%); chat T=0.0: 19.50 -> 19.50 (0.00%, TTFT -1.49%); code T=1.0: 22.95 -> 23.10 (+0.65%); chat T=1.0: 19.80 -> 19.90 (+0.51%).
  • Boxes it reaches: glue.metal, inkling2_glue_metal_records.zig, forward.zig, glue.zig, glue_plan.zig, glue_test.zig, metal_inkling2_glue.zig, metal_inkling2_glue_controls.zig, metal_inkling2_glue_kv_conv.zig.
  • New switch? No (always active).
  • Environment, with the TensorFold commit, Zig and backend toolchain, machine and GPU, checkpoint and revision: Commit b01bf9e676 rebased onto a992d0da99 (prior M3 Ultra / M5 Ultra A-B-B-A and M5 Ultra contract receipts from 00ab195259 / d01f8f39f9), Zig 0.17.0 -Dcpu=apple_m1 -Doptimize=ReleaseFast, Apple M5 Max (applegpu_g17), Apple M3 Ultra 512 GiB, Apple M5 Ultra 512 GiB; checkpoint Inkling-2-Mini.
  • Paths and platforms the change reaches, which I ran and which I could not: Inkling 2 Metal K and V short convolutions on Apple Silicon Metal GPUs; Apple M1/M2/M4 and M5 Pro not directly run on this slice.
  • Exactness: 0 cross-leg token_sha256 mismatches across all 32 cells (plain --skip-serial and dspark --serial) on Apple M3 Ultra and Apple M5 Ultra; 0-ULP parity against sequential tf_inkling2_conv_static and tf_inkling2_conv_dynamic verified by metal_inkling2_glue.zig and metal_inkling2_glue_kv_conv.zig.
  • Decode speed before and after: See A-B-B-A tables above (up to +1.48% plain / +0.99% self-drafted on Apple M3 Ultra; up to +1.69% plain / +0.77% self-drafted on Apple M5 Ultra; 0 regressive cells out of 32).
  • Prompt speed before and after: Pairs K/V conv dispatches during prefill chunks as well; code c=1 TTFT improved up to -6.93% (M3 Ultra) and -6.28% (M5 Ultra).
  • Licence of any new weights or drafter: n/a.
Kernel contract, only when a GPU kernel is new or changed
  • Kernels registered with the contract, and the kernel each one replaces: Adds metal inkling2 glue kv_conv_static tf_inkling2_kv_conv_static (32 threads) and metal inkling2 glue kv_conv_dynamic tf_inkling2_kv_conv_dynamic (256 threads, 128 bytes TG memory), pairing two sequential tf_inkling2_conv_static or tf_inkling2_conv_dynamic dispatches for K and V in forward.zig.
  • A planted control for each new kernel, and each one fails as planted: All 69/69 controls across all metal inkling2 suites on Apple M5 Max (b01bf9e676) and 57/57 controls on Apple M5 Ultra (d01f8f39f9) fail red as planted (0 missed), including kv_conv_static and kv_conv_dynamic planted controls in metal_inkling2_glue_controls.zig.
  • Each backend's SUMMARY line and exit status:
    • Apple M5 Max (b01bf9e676, rebased on a992d0da99 which includes #5041):
      • ./zig-out/bin/tf-kernel-contract --only "metal inkling2" (all Inkling 2 suites including metal inkling2 glue and metal inkling2 dspark):
        SUMMARY 63 kernels: 63 pass gates 1-4, 0 fail, 0 known findings; 69 controls: 69 red as planted, 0 missed; 0 limit problems; gates 10955 ms, limits 657 ms (exit 0).
      • ./zig-out/bin/tf-kernel-contract --only "metal inkling2 glue":
        SUMMARY 12 kernels: 12 pass gates 1-4, 0 fail, 0 known findings; 15 controls: 15 red as planted, 0 missed; 0 limit problems; gates 586 ms, limits 58 ms (exit 0).
    • Apple M5 Ultra (d01f8f39f9): SUMMARY 50 kernels: 50 pass gates 1-4, 0 fail, 0 known findings; 57 controls: 57 red as planted, 0 missed; 0 limit problems; gates 8782 ms, limits 391 ms (exit 0).
  • Chips I could not run: Apple M1/M2/M4 not directly available.

Checklist

  • The title and description match the head commit, including the receipt and the stack.
  • New tests fail before the change, pass after it, and skip cleanly without their dependency.
  • Comments and docstrings are one line. No measurements or history in the source.
  • No personal data, machine names, internal hosts or local paths in the diff or its commits. No AI attribution lines.
  • Every token still goes through the lane rounds. No serial path, and nothing that needs drafts off.
  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo.
  • No precision traded for speed.
  • Decode and prompt processing are no slower than main at one stream and the widest admitted; with --drafter, no slower than without it, greedy and sampled.

@AIFlowML

Copy link
Copy Markdown
Contributor

I trial-merged 23870c9381 into post-release main d2b43908db on an M5 Max. The merge was clean, with 146 host tests passed and 10 skips. The Metal contract passed 63 kernels and caught all 67 planted controls, with zero problems across 73 selected launch records.

zig build test-inkling2-host test-inkling2-metal-host tf-kernel-contract -Dfixed-cpu -j2 --summary all
./zig-out/bin/tf-kernel-contract --only 'metal inkling2'

With #4981 first, the shader conflict is in glue.metal. Keeping its threadgroup bounds and adding the paired kernels' recorded bounds (static 32, dynamic 256) resolves the shader side. The load guard then fails to compile because the merged list has 13 pipelines and 11 widths. Inserting 32, 256 after the original convolution entries fixes it. That scratch pair passed 101 Metal host tests with six skips and the same 63 kernels, 67 controls and 73 launch records. #5001 has separate host and contract file conflicts when paired with this head. I did not repeat serving or throughput tests.

Igor Lessio - AIFLOW LABS

@AIFlowML

Copy link
Copy Markdown
Contributor

I also tested this head 23870c9381 after #5001 2a1fb997f6 on d2b43908db. The two changes fit together once the three textual conflicts are resolved. The scratch resolution kept the 17 pipeline slots in shader-name order, retained both shape/count rules, and preserved the separate baseline comparisons for paired K/V convolution and cached AR.

zig build test-inkling2-host test-inkling2-metal-host tf-kernel-contract -Dfixed-cpu -j2 --summary all
./zig-out/bin/tf-kernel-contract --only 'metal inkling2'

On M5 Max that pair passed 149 host tests with 10 skips and 67 Metal kernels, with all 71 planted controls caught and zero problems across 77 launch records. This was the two-PR pair. The #4981 guard and actual checkpoint serving still need coverage on the final combined tree.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks, @gilby. The paired K/V bodies retain the existing sum order and BF16 rounding, and the posted device checks are useful. One setup cleanup fix is needed: in Suite.add, the control probe is built before the fallible baseline pipeline load, but its deinit error handler is installed afterward. A failed baseline load therefore leaks the candidate pipelines. Please protect the acquired probe before that call and cover the failure path. The combined load-guard changes remain a separate integration step.

  • Synthena

@AIFlowML

Copy link
Copy Markdown
Contributor

While testing the setup cleanup Ash flagged, I found a second rollback case at 23870c9381. Both Suite.add and addSplit append the probe before the fallible kernel-list append. If that allocation fails, the probe's error handlers free it, but the probe list still holds the pointer for suite teardown.

I trial-merged into aa80cd2ae7 and injected a host allocation failure on the M5 Max after reserving a probe-list slot, with the kernel list empty. The original paired-K/V case leaves one retained probe where zero is expected. In scratch I moved the existing probe.deinit() guard before the baseline load and added a rollback pop after both probe-list appends. The fault fixture now passes for paired K/V and split router. Both fixture build tests passed, and ./zig-out/bin/tf-kernel-contract --only 'metal inkling2' passed 63 kernels, caught all 67 planted controls and found zero launch-limit problems.

The fixture injects the kernel-list allocation failure. It does not inject a baseline Metal pipeline failure.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks, @gilby. The paired arithmetic and reported combined tree checks remain useful. This head still has the setup cleanup gap: Suite.add acquires the control probe, then loads baseline pipelines before installing the probe's deinit error handler. If that load fails, the candidate pipelines leak.

Please protect the acquired probe before that call and cover the failure path. The forward.zig integration also needs to preserve indexed tree convolutions and use paired dispatch for linear segments, including the mixed-kind fallback.

  • Synthena

@AIFlowML

Copy link
Copy Markdown
Contributor

I reproduced the baseline-load failure on M5 Max at 23870c9381 after applying the glue merge resolution on a6619eb131. The fixture creates the real candidate control probe. It then loads a separate baseline shader where the dynamic convolution has a 32-thread limit instead of the required 256. The baseline returns GlueThreads. An allocation in the candidate probe's arena lets the test allocator check whether the probe is released on that path.

With the cleanup guard in its original position, the allocator reports one leak. Installing errdefer probe.deinit() before the baseline load makes that test pass with zero leaks. Reserving capacity in both registration lists before appending also passes the paired K/V and split-router allocation-failure checks.

zig build test-inkling-setup-cleanup -Dfixed-cpu -j2 --summary all

That's the local fixture target, which passes 3/3. The focused device contract on the exact PR head plus the cleanup change also passed both paired K/V kernels, caught both planted controls and reported zero launch-limit problems. The current-main glue changes are described in the #5011 integration note.

Igor Lessio - AIFLOW LABS

@gilby
gilby force-pushed the v4-8-paired-kv-conv-rebased branch from 23870c9 to ca7cb94 Compare November 25, 2026 10:32
@AIFlowML

Copy link
Copy Markdown
Contributor

I checked ca7cb9485b on M5 Max against 47a605aa12. It merges cleanly by itself. The two host targets passed 149 tests with 10 skipped. The Metal contract passed all 63 kernels, caught all 67 planted controls and reported no launch-limit problems. The paired static and dynamic paths matched the sequential reference bit for bit across 69 and 68 shapes respectively.

zig build test-inkling2-host test-inkling2-metal-host tf-kernel-contract -Dfixed-cpu -j2 --summary all
./zig-out/bin/tf-kernel-contract --only 'metal inkling2'

The rebase carries the pipeline thread limits forward. In the test harness, Suite.add still loads the baseline before installing the acquired probe's cleanup guard, so the earlier failure-path finding remains open. This exact head also conflicts with #5005's revised head in glue.zig. When combining them, carry the paired static and dynamic entries and their 32/256-thread requirements into the shared loader. I checked the merge conflict and ran the standalone contract. The combined loader and checkpoint performance remain unverified here.

Igor Lessio - AIFLOW LABS

@AIFlowML

Copy link
Copy Markdown
Contributor

I checked the landing order with #4919 912ca2449f first and this PR ca7cb9485b second, on main a3c3e5cef. The only conflicts are in inkling2_glue_metal_records.zig and metal_inkling2_glue_controls.zig. In both files, keep the two paired K/V entries from this PR and #4919's router entry. The combined registry uses the router's 1,616-byte threadgroup reservation, and the router control edits key[t] = scores[t] + bias[t];. Both NaN fallback controls still trigger separately.

zig build test-inkling2-metal-host tf-kernel-contract -Dfixed-cpu -j2 --summary all
./zig-out/bin/tf-kernel-contract --only 'metal inkling2'

On M5 Max, the resolved tree passed 104 Metal tests with six skipped. All 63 kernels passed, all 69 controls were caught, and there were zero launch-limit problems. This covers the two-PR integration and leaves the earlier test setup cleanup and checkpoint timing checks open.

Igor Lessio - AIFLOW LABS

@gilby
gilby force-pushed the v4-8-paired-kv-conv-rebased branch from ca7cb94 to 00ab195 Compare November 25, 2026 12:39
@AIFlowML

Copy link
Copy Markdown
Contributor

The revised 00ab195259 now trial-merges cleanly with #4998 3286430bfd on 9961ca492. The combined build passed 157 tests with ten skipped on M5 Max. Both paired K/V kernels passed and caught both planted controls, with no launch-limit failures. Static and dynamic outputs matched two separate launches bit for bit across 69 and 68 shapes respectively.

zig build test-inkling2-host test-inkling2-metal-host tf-kernel-contract -Dfixed-cpu -j2 --summary all
./zig-out/bin/tf-kernel-contract --only kv_conv

The earlier allocation rollback finding still applies to Suite.add: it appends the probe before the fallible kernel-list append. This integration run checks dispatch and output parity. It leaves that error path and checkpoint timing open.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks @gilby. The paired loader now carries the required thread limits, and the earlier arithmetic checks remain useful.

Two setup paths still need repair. The candidate probe's cleanup guard comes after the fallible baseline load, so that failure leaks its pipelines. Also, a failed kernel-list append leaves a freed probe in the owner list, including the split helper. Please protect the acquired probe before the baseline call and make registration transactional, with focused failure coverage.

  • Synthena

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

@gilby, about the probe-registration cleanup our review asked for: the same two-append pattern was on main in 85 places, and #5058 (now merged) fixes it there with one helper, contract.register. It reserves room in both lists before publishing, so a failed append can no longer free a probe the suite still holds:

errdefer p.deinit(); // with errdefer s.a.destroy(p) after create, as the suite's teardown frees it
try ct.register(s.a, &s.probes, &s.kernels, p, p.kernel());

Using it for this PR's new suites closes that item. zig/src/core/contract/register_test.zig shows the failure cases it covers.

  • Synthena

@gilby
gilby force-pushed the v4-8-paired-kv-conv-rebased branch from 00ab195 to b01bf9e Compare November 25, 2026 15:39
@gilby

gilby commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (a992d0da99, including #5041) at b01bf9e676 and fixed both setup cleanup paths:

  1. Candidate cleanup before baseline pipeline load: Extracted addAcquired in zig/tests/contract/metal_inkling2_glue_controls.zig and routed Suite.add, Suite.addNanControl, and Suite.addSplit in zig/tests/contract/metal_inkling2_glue.zig through it, installing errdefer probe.deinit() immediately after probe initialization and before host.Pipelines.load(device).
  2. Transactional probe/kernel registration: Added registerProbe in zig/tests/contract/metal_inkling2_glue_controls.zig, calling ensureUnusedCapacity on both probes and kernels before appendAssumeCapacity on either list so a failed kernels append rolls back cleanly instead of leaving a freed probe in Suite.probes.
  3. Host failure-path coverage: Added two unit tests in zig/tests/contract/metal_inkling2_glue_controls.zig covering (a) baseline pipeline load failure cleaning up the candidate probe once with zero leaks, and (b) std.testing.FailingAllocator failing on kernels.ensureUnusedCapacity after probes.ensureUnusedCapacity allocates, rolling back the new probe while leaving pre-existing probes intact.

Verified on b01bf9e676 (Apple M5 Max):

  • zig build test-inkling2-controls-host --summary all: 26/26 tests passed
  • zig build test-kernel-contract --summary all: 255/255 tests passed
  • ./zig-out/bin/tf-kernel-contract --only "metal inkling2": SUMMARY 63 kernels: 63 pass gates 1-4, 0 fail, 0 known findings; 69 controls: 69 red as planted, 0 missed; 0 limit problems; gates 10955 ms, limits 657 ms (exit 0, including metal inkling2 dspark and metal inkling2 glue)
  • ./zig-out/bin/tf-kernel-contract --only "metal inkling2 glue": SUMMARY 12 kernels: 12 pass gates 1-4, 0 fail, 0 known findings; 15 controls: 15 red as planted, 0 missed; 0 limit problems; gates 586 ms, limits 58 ms (exit 0)

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