Skip to content

Metal: experimental Inkling 2 Mini EXL3 packs - #4471

Draft
grantoverton wants to merge 35 commits into
ashhart:mainfrom
grantoverton:inkling2-exl3-metal-exl3
Draft

grantoverton wants to merge 35 commits into
ashhart:mainfrom
grantoverton:inkling2-exl3-metal-exl3

Conversation

@grantoverton

@grantoverton grantoverton commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Inkling-2-Mini weights also ship as an EXL3 4bpw safetensors pack: 24 per-layer shards of per-expert trellis tables (gate_proj/up_proj/down_proj.trellis), F16 suh/svh scales, I32 mcg codebook markers, plus dense shards and mtp.safetensors, all enumerated by model.safetensors.index.json. This teaches the Metal path to detect and serve that pack next to the official NVFP4/MXFP8 checkpoints. The official path is untouched: precision is detected per layer from the checkpoint itself, and a layer set that mixes EXL3 trellis tensors with packed w13/w2 tensors is refused.

  1. Multi-file checkpoint (metal_mapped.zig). Mapped.Set reads the safetensors index, merges every shard's tensor table into one namespace, rejects duplicate names, and adopts each file no-copy when its data start satisfies the tensor alignment; unaligned shards repack through addFileSplit. Mapped and repacked files stay alive until model teardown, and checkpointFileBytes counts the index's shard list.
  2. Format detection (plan.zig, names.zig, config.zig, metal_model.zig). plan.Precision gains .exl3; names.precisions() recognizes the trellis names before dtype detection; config accepts quant_method: "exl3" alongside ModelOpt NVFP4; the model picks an ExpertStore union member per checkpoint.
  3. EXL3 expert store (metal_experts_exl3.zig, experts_common.metal, experts_dot.metal). One descriptor per (layer, projection, expert) — 24 × 3 × 128 entries — carries the trellis GPU address, strides, width, codebook and scale layout. Decode runs the generic exl3 projection kernels through encodeIndexed with GPU route ids for expert selection, applies the capped SwiGLU in a new inkling2_exp_swiglu kernel that reuses the packed path's i2x_swiglu math, and combines down-projection outputs with the existing route-weighted combine kernel. Intermediates stay in row-compact BF16 planes; nothing dequantizes on the host.

Checks on this head

  • Head commit: 11dcd7b3fc6b2dad6ff14673aa753518701ea0c4
  • Lean checker, python3 tools/zig/lean_check.py, on the base and on this head: base 98b1e13b (the stacked parent head, isolating this delta) = 7615 files / 165 problems; head = 7617 files / 165 problems; lean_new.py reports 0 new findings.
  • Tests run, with the command and pass, fail and skip counts:
    • zig build test-inkling2-host: 31 passed, 4 environment-gated skips, 0 failed (post-merge).
    • zig build test-inkling2-metal: 7/7 on the official BF16-staged checkpoint and 7/7 with TF_INKLING2_MODEL on the EXL3 pack (post-merge; the official-path regression check).
    • zig build test-exl3: 2/2; zig build test-exl3-gpu: 21/21 (post-merge; the test binary run directly — the zig build wrapper's --listen mode flaked once, the suite itself passes).
    • tf-kernel-contract --only inkling2_exp_swiglu on the M5 Ultra: baseline passes gates 1–4 (sums N/A — elementwise), 4/4 planted controls red as planted, limits clean (details below).
    • test-metal-launch-map-host run directly: 7/7, "1272 registered launches, 2 controls, 0 missing" — the new launch maps.
    • zig fmt --check build.zig zig: clean. git diff --check: clean. Provenance scan over 98b1e13b..HEAD: 0 hits.
  • CI: pending at time of writing (fmt, zig, zig-b, zig-macos-dev-tools, zig-windows, pytest, benchmark-clients, release-paths, comfyui-moss-installer all queued on the push of 11dcd7b3f).
  • Not run, and why: CUDA/HIP/Vulkan contract or serve paths (this delta is Metal-only; no backend-neutral arithmetic changed); the vision and draft paths (text-first slice — --no-drafts is the tested configuration); tools/bench_openai.py / tools/bench_cache.py --require-cold sweeps (the shared serve instance was occupied by a running benchmark; single-shot completion telemetry is cited in the receipt instead).

Receipt

  • Main against branch: cells and numbers, or why they can't be run: n/a for the pack — main and the parent cannot detect or load an EXL3 checkpoint at all (that is the change). The meaningful comparison is engine-versus-pack-dequantized-reference, in Exactness below; official-checkpoint behaviour is covered by test-inkling2-metal 7/7 on both checkpoints and an untouched official code path.
  • Boxes it reaches: one Apple-Silicon Mac Studio (M5 Ultra, 64-core GPU, 96 GiB, macOS 27.2, Metal 4) for build, tests, contract gates and serving; a second Apple-Silicon Mac for the numpy dequantized-reference oracle.
  • New switch? Default, accepted values, profile row: none. Format is auto-detected from checkpoint tensors; TF_INKLING2_EXL3/TF_INKLING2_MODEL are test-only overrides following the existing env pattern.
  • Environment, with the TensorFold commit, Zig and backend toolchain, machine and GPU, checkpoint and revision: TensorFold 11dcd7b3f on parent 98b1e13b; Zig 0.17.0; Apple Metal 4 toolchain (note: xcrun reports no standalone metal compiler on the dev box, so offline shader checks are skipped — device compilation is exercised by every Metal test above); checkpoint inkling2-exl3-4bpw — EXL3 bits: 4.0, quant_method: exl3, 24 exl3-layer-* shards + 2 dense-* shards + mtp.safetensors indexed by model.safetensors.index.json, built from thinkingmachines/Inkling-2-Mini @ ed40e7da625f594fc9c4990f5f66be24873c22d7 (checkpoint.json records source revision 1fb4134b9a74f9681054f4ef82e4bf1f458a2337), Apache-2.0.
  • Paths and platforms the change reaches, which I ran and which I could not: Metal on Apple Silicon — ran host tests, Metal smoke (both checkpoints), the kernel contract, a real-pack serve and greedy decode; could not run CUDA/HIP/Windows/Linux (no code path added there) or the drafted/vision lanes (out of this slice).
  • Exactness, from tools/bench_concurrent.py --alone --serial or token_sha against "draft": false: the EXL3 pack is a separately quantized artifact, so token-identity with the original checkpoint is not the reference (that is what Gate proposal: Inkling 2 Mini EXL3 pack on Metal (4 bpw trellis experts, stacked on #4337) #4475 proposes to agree). Instead the reference is the pack's own dequantized weights: all 128×3 expert matrices per layer unpacked through the pack converter's own trellis path into FP32 planes, combined with the pack's dense shards, and run through a numpy op-for-op mirror of the mlx_lm Inkling-2 forward (BF16 rounding at the same boundaries). Greedy decode (sampling: greedy, --no-drafts, 33-token prompt, 45 completions): 32/45 positions token-identical; first divergence at position 32, where the oracle's top-1/top-2 logit margin is 0.0184 (relative 6.4e-4) — the narrowest margin in the window — and the engine selected the oracle's runner-up. Cross-check: the same oracle over the official checkpoint's dequantized weights diverges from the EXL3 oracle at position 31, i.e. inside the same noise band. Verdict: quantization/numerics noise at a near-tie argmax, not an implementation defect; a defect would diverge early or produce incoherent text, and 32 identical positions preceded the flip. token_sha for the run: 17709f2af654. Drafted-vs-plain, resumed-vs-fresh and concurrent-vs-solo: n/a — drafts are disabled in this configuration and no shared decode state changed.
  • Main against this branch, same machine and checkpoint, posted before asking for a run on our machines (or why you can't): n/a — main cannot serve this checkpoint; the official-checkpoint comparison is the test suite above (the union store selects the official path whenever no trellis tensors are present, and the official Metal smoke passes 7/7 post-merge).
  • Decode speed before and after, from tools/bench_openai.py: single-shot greedy completion, same machine, same 33-token prompt, drafts: false — official checkpoint 39.99 tok/s decode / 1.10 s for 45 tokens; EXL3 pack 21.18 tok/s / 2.08 s. The EXL3 path is ~1.9× slower — expected for the first functional slice: each expert tile currently issues three encodeIndexed projection calls plus the SwiGLU and combine launches with no grouped-expert batching; kernel work is the stated follow-up, not hidden here.
  • Prompt speed before and after: the cold first request's ttft_s from tools/bench_cache.py --require-cold on a long prompt, or "n/a" with the reason when the change cannot reach prompt processing: bench_cache sweep n/a — the serve instance was occupied by a running benchmark; single-shot prefill telemetry on the same prompt: official 0.133 s vs EXL3 0.501 s (33 tokens, prefill_widths: [33]).
  • Licence of any new weights or drafter, or "n/a": the EXL3 pack is Apache-2.0 (per its checkpoint metadata); no new weights or drafter are added by this change — n/a beyond that.
Kernel contract, only when a GPU kernel is new or changed
  • Kernels registered with the contract, and the kernel each one replaces: inkling2 experts inkling2_exp_swiglu — new entry point in experts_dot.metal (elementwise capped SwiGLU over BF16 gate/up planes, Inkling2ExpSwigluArgs), launched by the EXL3 store only; it replaces nothing (the packed NVFP4/MXFP8 path keeps its own kernels). Launch record added to inkling2_expert_records.zig: 256 threads, 0 threadgroup bytes, 256 reserved — matching the sibling expert launches. The generic tf_exl3_* projection kernels it drives were already registered.
  • A planted control for each new kernel, and each one fails as planted: four source-level mutations of the shared expert unit, each compiled separately and each red at its assigned gate — swaps the gate and up streams (red at shapes, 1317× bound), swaps the soft caps (red at shapes, 7.3× bound), writes one element past its output (red at shapes, guard/NaN), reads a non-finite gate as zero (red at nonfinite, class mismatch). The contract test is zig/tests/contract/metal_inkling2_exl3_swiglu.zig, wired into metal_inkling2_main.zig.
  • Each backend's SUMMARY line and exit status: tf-kernel-contract --only inkling2_exp_swiglu on Apple M5 Ultra (applegpu_g17): SUMMARY 1 kernels: 1 pass gates 1-4, 0 fail, 0 known findings; 4 controls: 4 red as planted, 0 missed; 0 limit problems — exit 0. Baseline worst case 1.000 of the float64 bound (one BF16 ulp allowance; fp32 transcendentals can land a rounding boundary a ulp off, and sub-2^-118 results can flush fp32 subnormals — both documented in the probe's bounds). CUDA/HIP: n/a — no kernel changes there.
  • Chips I could not run: contract gates ran on the M5 Ultra only; the static launch-limit audit covers M1–M5 (1 selected registered Metal launches against M1-M5, 0 problems, limits here clean: 256 threads, 0 threadgroup bytes).

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. (The EXL3 names/format tests fail on the parent — .exl3 precision and trellis names do not exist there; host skips are the pre-existing environment-gated four.)

  • 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. (The EXL3 store plugs into the same expert dispatch the packed store uses; --no-drafts is the tested configuration and drafts are untouched.)

  • Drafted output equals "draft": false, a resumed prompt equals a fresh one, and concurrent equals solo. (n/a for this slice: drafts disabled; no decode-state or scheduling changes — stated in Exactness.)

  • No precision traded for speed. If the bits change, the description says which sums change and why. (No arithmetic change to existing paths; the new SwiGLU reuses the packed path's i2x_swiglu math, contract-bounded to one BF16 ulp against a float64 oracle.)

  • 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 — knowingly not met (21.2 vs 40.0 tok/s decode, 0.50 s vs 0.13 s prefill on the same prompt): the slice is functional-first per the gate proposal, kernel batching is the agreed follow-up, and the numbers are disclosed above rather than buried.

BlivionIaG and others added 29 commits November 21, 2026 09:49
- Preserve the original release NVFP4 and MXFP8 expert weights and execute the looped text backbone on one Metal device.
- Keep the bundled DSpark head and plain prompt-cache reuse in the native lane backend.
- Refs ashhart#4274. Local M4 Pro evaluation, separate from the upstream full port.
- Keep the original vision tower, PNG/JPEG preparation, and the separate device and operator checks on the full integration branch.
- The padded-image real-weight accuracy gate remains open. This commit is not part of the text-only review branch.
- Match pinned Transformers eager QK and scaling boundaries before FP32 softmax.
- Keep the trained padded-image projector bound unchanged.
- Keep original NVFP4/MXFP8 checkpoint bytes and decode weights in registers, using BF16 activations and FP32 sums.
- Match pinned Transformers conversion and SwiGLU/route precision, with packed-weight and zero-scale controls.
- Refs ashhart#4274. Local original-weight M4 Pro qualification; not an upstream submission.
- Keep the shader and probe comments within the repository lean rules; no arithmetic changes.
- The rebase dropped the alias main uses for slide refusal, so the native server did not compile.
…-ups

- Comments are one line each again (339 runs collapsed, 40 shortened) and no `/*` text remains, so lean_check.py adds nothing to the base's 168 problems.
- TF_INKLING2_MINI_SMOKE reads through platform/environment.zig: a .metal/.path row, a docs row and a valid case in environment_test.zig.
- The load check sums every model*.safetensors shard, as core/checkpoint.zig lists them, plus mtp.safetensors when drafted.
- The state-bytes test covers Mini's looped shape: 24 physical layers as 48 visits, 8 global, visit 41 at physical 17.
- A new contract control isolates the experts' down projections; --loops and --policy refusals have a test that names them.
- The cacheBudget doc comment and the CHANGELOG state the DSpark prompt-cache limit: kept states need --no-drafts.
- The Inkling 2 contract suites move to metal_inkling2_main.zig, holding their probes for the run, which keeps metal_main.zig under 600 lines.
- The NVFP4 outer factor stays the unrounded quotient, pending the maintainer's F1 decision.
…ites

- `zig fmt --check build.zig zig` (what the Zig format workflow runs) is clean; the new suites and loaders had drifted.
- Layout and `@intFromEnum` -> `@backingInt` only: the contract, native, vision, forward and environment checks are rerun green on this tree.
…w projections

- Score GEMMs are a full fp32 dot, off the tensor-unit operand cut, so an M5 matches the product measured on earlier chips.
- One-row projections that share an input use one launch of the existing matvec lane chains. Same checkpoint token hash, about 2 ms off a 57 ms decode token.
- zig fmt on the forward layer, and the score-GEMM note is one line so lean check stays at the base count.
- Drop the blank lines zig fmt --check rejected on the projection fuse.
- f32_nt and f32_nn were filled from bf16 dyadics, so a 10-bit operand cut still matched the float64 product.
- Wide inputs now set the low fraction bits. On this M4 Pro the gates pass at 0.337 and 0.354 of the bound.
- Gate-down walked all 64 ranks in one threadgroup. Eight ranks a group, each rank's sum order unchanged.
- Decode on this M4 Pro is 23.2 tok/s, from 16.9, hash 57519a5a167f unchanged.
- Prefill chunks are 512 rows. A 1056-token prompt prefilled at 81 tok/s.
- The split moved the message-half FMA into acc[j]; the planted control still edited the old line (ControlEditMissing).
- From lucasgelfond's BlivionIaG#108.
…metal-4bit

# Conflicts:
#	docs/environment.md
#	zig/src/native/metal.zig
#	zig/src/platform/environment.zig
…ls; checkpoint size from the shard list

- controls for ik2d_alpha, embed_block, rms, add_rms, qk_prep and ik2v_embed, heads, bias_gelu, gelu_rows
- checkpointFileBytes sums core/checkpoint.zig's shardFiles (index weight map) plus mtp, with an index test
…ime expert GEMV

- each SIMDgroup owns two weight rows (one gate/up output, two down outputs) with 4-byte word loads instead of per-byte loads
- E2M1 and E4M3 decode through FP16 bit layouts (scales fold 2^14 / 2^8 exactly); accumulation order and BF16 boundaries unchanged
- contract controls re-anchored on the float2 spellings
…, one weight decode per tile

- Chunks of 64 rows or more sort the rows*topk pairs by expert on the GPU, pack the activations per K slice, then each
  tile decodes its expert's weights once into threadgroup memory for all of its pairs (same lane-strided FP32 chain, equal bytes).
- Decode and chunks under 64 rows keep the one-row kernels; the contract compares grouped batches with row-by-row dispatches
  on random, dense, one-expert and non-finite inputs and plants six controls.
…s on many threadgroups

- For up to 16 rows, attn_res, loop mix, gate down and gate mix split into 2-3 launches (statistics, mix, norm).
- Per-thread chains and simdgroup sums are unchanged, so outputs are byte-equal to the one-group kernels (bitwise-checked incl. NaN/Inf).
- The one-group kernels still serve prefill rows; contract adds multi-group controls and 17-row shapes for both paths.
- Decode 64 tok: 24.9 -> 30.0 tok/s on M4 Pro, sha 57519a5a167f unchanged.
… SwiGLU runs once per tile

- Lane 0's reduced sums are broadcast and each lane finishes one (row group, pair): same bytes, gate/up stage 26.7 -> 24.9 ms
  per 512-row layer in the microbench; the planted swapped-columns control follows the new store.
# Conflicts:
#	zig/src/families/inkling2/metal_experts.zig
…and fixed bytes

- The multi-group loop kernels' scratch buffer was missing from setResident and fixedBytes.
…ed experts kernel uses

- the decode-side rewrite dropped both from the shared sources; the grouped prefill kernel still reads them
- outputs are byte-equal to the one-row expert kernels
- the merge with main had left it inside the 1.3.3 section
Inkling-2-Mini weights also ship as an EXL3 4bpw safetensors pack:
24 per-layer shards of per-expert trellis tables, F16 scales and mcg
codebook markers plus dense shards and mtp. Detect the format from
the layer 0 gate trellis name, accept quant_method "exl3" in
config, and read the pack through a multi-file checkpoint: aligned
shards adopt no-copy, unaligned ones repack through addFileSplit,
duplicate names are rejected, and mapped files stay alive until
model teardown.

The expert store keeps the official path untouched: a per-layer,
per-projection, per-expert descriptor table feeds the generic exl3
projection kernels through encodeIndexed with GPU route ids, the
capped SwiGLU reuses the packed-path activation math, and the
route-weighted combine matches the official kernel. BF16 planes
stay row-compact; nothing dequantizes on the host.

test-inkling2-metal passes 7/7 on both the official checkpoint and
the EXL3 pack; test-inkling2-host covers the new name map and a
real-pack header check; test-exl3-gpu passes 21/21. Greedy decode
on the oracle prompt tracks the MLX reference for a 31-token prefix
before quant divergence.
Parent head 98b1e13 brings the grouped-expert and decode-attention
perf work into the same kernel files the EXL3 store shares. Resolve
experts_common.metal by keeping the branchless E4M3 decode and the
kI2xE2m1 move to experts_group.metal, with the EXL3 SwiGLU args
struct kept for inkling2_exp_swiglu; resolve native/inkling2.zig by
taking the index-driven shardFiles accounting, which already covers
the dense-*/exl3-layer-* shards through model.safetensors.index.json.
@jschmied

jschmied commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

@grantoverton a data point from the smallest Mac so far: an Apple M3 Pro (no tensor units), macOS 27.2 (26B123), Metal toolchain 32023.921, Zig 0.17.0 -Dcpu=apple_m1. This head 99006e55dd with the EXL3 pack grant-ai/Inkling-2-Mini-EXL3-4bpw at 51b284cda3, on AC with the GPU otherwise idle.

  • Pack: 41/41 files match the publisher's hashes (29 LFS sha256, 12 git blob sha1), 16.83 GB.
  • Build: zig build native rc 0.
  • Contract --only inkling2: 87 kernels pass gates 1-4, 0 fail; 111 controls red as planted, 0 missed; 0 limit problems.
  • Host tests:
    • inkling2-host 30/35 (5 skipped; your body has 31 + 4 on the M5);
    • EXL3 13/13, EXL3 GPU 21/21;
    • launch map 7/7 (1,272 launches, 0 missing);
    • inkling2-metal 7/7 on the EXL3 pack and 7/7 on the official checkpoint.
  • Served: ctx 8192, one stream, no drafts, thinking on. Loaded in 14.8 s; 15.04 GiB of weights resident, about 17.0 GiB wired by the server at peak.
same binary EXL3 4 bpw official checkpoint
decode, 128 greedy tokens (4 prompts) 10.07-10.79 tok/s 19.87-20.15 tok/s
cold 2,511-token prompt, TTFT 168.85 s (14.9 tok/s) 27.02 s (92.9 tok/s)

So decode is about 1.95x slower than the official checkpoint, the same ratio you report on the M5. The prompt pass is 6.3x slower: it runs at about decode speed. I have not profiled it, so I can't say which kernel.

--parallel 2 is admitted, but the two streams give 6.77 + 5.28 = 9.13 tok/s together, below one stream alone; both replies' hashes equal solo. Greedy hashes are equal across two rounds on all four prompts.

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