Repository navigation
Metal: experimental Inkling 2 Mini EXL3 packs - #4471
Draft
grantoverton wants to merge 35 commits into
Draft
grantoverton wants to merge 35 commits into
grantoverton wants to merge 35 commits into
Conversation
- 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
…metal-4bit # Conflicts: # CHANGELOG.md
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.
Open
1 task done
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.
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
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.
|
8 tasks done
4 tasks done
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
work/inkling2-mini-metal-4bitat98b1e13b). The reviewable delta isgit diff 98b1e13b..11dcd7b3f:dae95c591(the EXL3 pack path), merge82df5cc20(the parent's moved head, no force-push),75402062f(kernel contract for the new SwiGLU) and11dcd7b3f(lean comment style). Everything below the parent tip is theirs.atc overlap --json: focused run on the current head11dcd7b3f(ATC reports 1322 changed files in its working-tree view; the unrestricted whole-tree scan exceeds its pull-request limits, so the relevant set was checked directly). Metal loader: a checkpoint span of 16 GiB or more loads (each pread capped at 1 GiB) #4435 and lanes/depth: price full fixed_draft_block head cost in lone roundCost #4457 clean; Inkling 2 Mini on Metal: #4387's native build compiles, its norms write their output, and concurrent streams equal solo #4446/Inkling 2 Mini DSpark on Metal: attention scale 1/sqrt(128), and the recurrent step reads kappa as FP32 #4447/Inkling 2 Mini on Metal: experts, gates, router, depth mix, combine, row batching, attention chunks and a concurrent forward (1,159 to 14 ms a row on M5 Ultra) #4448 conflict on the parallellead/inkling2-miniline (1–2 shared files each, none in this delta); inkling2 metal: grouped NAX MoE, NAX/multi-TG attention, vectorized mv_fuse, and fused decode kernels #4458 shares 113 files / 5 conflict files and inkling2 metal: enable DSpark prompt cache, widen prefill chunks to 1024, and warm verify window costs #4459 shares 114 / 6 — verified bygit merge-treeto be sibling-PR overlap on the shared Inkling-2 kernel and contract-record files (experts_dot.metal,experts_sources.zig,inkling2_expert_records.zig,metal_experts.zig,inkling2_metal_ops_records.zig,lanes/depth.zig), including this delta's appendedinkling2_exp_swiglulaunch and record — line-adjacent, resolvable at merge time, and disclosed here rather than silently.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), F16suh/svhscales, I32mcgcodebook markers, plus dense shards andmtp.safetensors, all enumerated bymodel.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 packedw13/w2tensors is refused.metal_mapped.zig).Mapped.Setreads 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 throughaddFileSplit. Mapped and repacked files stay alive until model teardown, andcheckpointFileBytescounts the index's shard list.plan.zig,names.zig,config.zig,metal_model.zig).plan.Precisiongains.exl3;names.precisions()recognizes the trellis names before dtype detection;configacceptsquant_method: "exl3"alongside ModelOpt NVFP4; the model picks anExpertStoreunion member per checkpoint.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 genericexl3projection kernels throughencodeIndexedwith GPU route ids for expert selection, applies the capped SwiGLU in a newinkling2_exp_swiglukernel that reuses the packed path'si2x_swiglumath, 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
11dcd7b3fc6b2dad6ff14673aa753518701ea0c4python3 tools/zig/lean_check.py, on the base and on this head: base98b1e13b(the stacked parent head, isolating this delta) = 7615 files / 165 problems; head = 7617 files / 165 problems;lean_new.pyreports 0 new findings.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 withTF_INKLING2_MODELon 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 — thezig buildwrapper's--listenmode flaked once, the suite itself passes).tf-kernel-contract --only inkling2_exp_swigluon 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-hostrun 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 over98b1e13b..HEAD: 0 hits.11dcd7b3f).--no-draftsis the tested configuration);tools/bench_openai.py/tools/bench_cache.py --require-coldsweeps (the shared serve instance was occupied by a running benchmark; single-shot completion telemetry is cited in the receipt instead).Receipt
mainand 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 bytest-inkling2-metal7/7 on both checkpoints and an untouched official code path.TF_INKLING2_EXL3/TF_INKLING2_MODELare test-only overrides following the existing env pattern.11dcd7b3fon parent98b1e13b; Zig 0.17.0; Apple Metal 4 toolchain (note:xcrunreports no standalonemetalcompiler on the dev box, so offline shader checks are skipped — device compilation is exercised by every Metal test above); checkpointinkling2-exl3-4bpw— EXL3bits: 4.0,quant_method: exl3, 24exl3-layer-*shards + 2dense-*shards +mtp.safetensorsindexed bymodel.safetensors.index.json, built fromthinkingmachines/Inkling-2-Mini@ed40e7da625f594fc9c4990f5f66be24873c22d7(checkpoint.json records source revision1fb4134b9a74f9681054f4ef82e4bf1f458a2337), Apache-2.0.tools/bench_concurrent.py --alone --serialortoken_shaagainst"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 themlx_lmInkling-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_shafor 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.maincannot 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).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 threeencodeIndexedprojection calls plus the SwiGLU and combine launches with no grouped-expert batching; kernel work is the stated follow-up, not hidden here.ttft_sfromtools/bench_cache.py --require-coldon 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]).Kernel contract, only when a GPU kernel is new or changed
inkling2 experts inkling2_exp_swiglu— new entry point inexperts_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 toinkling2_expert_records.zig: 256 threads, 0 threadgroup bytes, 256 reserved — matching the sibling expert launches. The generictf_exl3_*projection kernels it drives were already registered.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 iszig/tests/contract/metal_inkling2_exl3_swiglu.zig, wired intometal_inkling2_main.zig.SUMMARYline and exit status:tf-kernel-contract --only inkling2_exp_swigluon 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'sbounds). CUDA/HIP: n/a — no kernel changes there.1 selected registered Metal launches against M1-M5, 0 problems,limits hereclean: 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 —
.exl3precision 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-draftsis 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_swiglumath, 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.