diff --git a/NOTICE b/NOTICE index eb7e0adea8..2165294d4f 100644 --- a/NOTICE +++ b/NOTICE @@ -532,7 +532,9 @@ Used in mlx-serve: * `src/plugins/inkling2/kernels/relattn.metal` ports the `relative_attention` kernel of the Inkling 2 model (`mlx_lm/models/inkling2/kernels.py`, https://github.com/ml-explore/mlx-lm/pull/2086); `relsplit.metal` and - `relslots.metal` split that kernel's read over the keys and over slots. + `relslots.metal` split that kernel's read over the keys and over slots; + `relative_attention_nax.metal` (Stéphane Busso's, from his inkling2-final + branch of PR 1261) runs MLX's NAX attention loop with that kernel's score. Modifications by mlx-serve: reimplemented in Zig against mlx-c, and the GDN kernel is extended by a sequence variant (`GDN_KERNEL_SEQ_SOURCE`) that records diff --git a/docs/gotchas/engine-mlx.md b/docs/gotchas/engine-mlx.md index 117d895625..6eeb4d2245 100644 --- a/docs/gotchas/engine-mlx.md +++ b/docs/gotchas/engine-mlx.md @@ -1706,9 +1706,13 @@ before the drafter's state carried over), and a seeded sampled one never repeate finished one adopted its drafter state (context rows, calibration) and copied its answer as drafts, so its rounds lined up differently; a verify row's logits differ from another alignment's in the low bits (bf16), and a near-tie token flips. Fix: a greedy or seeded request (`SamplingParams.repeats`) adopts nothing and copies no earlier answer; -an unseeded sampled one keeps both. Rule: state carried between requests may speed a request up, never change what -a request that asks to repeat reads. Beside other requests a group still follows arrival order. Guard: `plugin native -drafter: only an unseeded sampled request continues an earlier one`. +an unseeded sampled one keeps both. Beside other requests the group rounds then made its text follow arrivals: a +group's forward carries every slot's rows, and the kernels (MLX's matmul by row count, the router and expert paths past +32 and 63 rows, the split-K by the launch's longest lane, the draft head and tree width by lanes) follow the group. Fix: +such a request can round alone (`native_group.roundsAlone`, opt-in `MLX_SERVE_GREEDY_SOLO_ROUNDS=1`: on by default it held +multi-user greedy decode flat). Rule: a request that must repeat under load reads nothing another request chose. Guards: `plugin native drafter: only an unseeded sampled request continues an earlier +one`, `roundsAlone: with the switch on, a request that must answer the same twice never shares a forward`, `inkling2 release: a greedy lane's +rounds beside a sampled group are its rounds alone`. ### A kernel template argument that carried a launch's rows filled the proof table, and every launch then paid an evaluation Defect: Inkling 2's decode ran 10 ms a round slower for the life of a process, from the first boot of a build (its warm @@ -1747,3 +1751,11 @@ media model held the room until something unloaded it. Fix: a prefill whose cach first unloads the least recently used idle media model, one per cut, then re-clamps grow-only (`reclaimSqueezedCache`, `squeezed_from`); a media job that grew active memory re-checks the budgets, since the weights land at the first job. Guard: `a squeezed hot cache takes its room back from an idle media model, never a held one or a chat model`. + +### Inkling 2's prompt paths also ran in grouped verifies and batched decode +Defect: paths built for prompt chunks (the strided prep past 8 rows, the row norm past 32, the tiled gates, the experts' +row map and its gate_up epilogue past 64) keyed on the forward's rows, so batched decode at 9-32 slots and grouped +verifies of 2+ lanes (past 64 rows at 11 DFlash2 lanes on NAX) took arms never tested or timed there; the row map's +prompt call also dropped the condition that keeps MLX's verify bits. Fix: each asks `kernels.Load` (a prompt chunk or +not, from the forward's mode). Rule: a path built for a load asks the load. Guards: `inkling2 proof: batched slots and a +grouped verify take main's path`, `inkling2 kernels: a verify's rows past 64 keep MLX's gather`. diff --git a/docs/known-issues.md b/docs/known-issues.md index c275aec572..4e53cf571e 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -43,6 +43,13 @@ Declared today: - **Concurrent**: archs that batch decode (B > 1) are not row-exact across batch widths; serial archs (`qwen3_next`, `laguna`, `kolibri1`, `bailing_hybrid`, `hy_v3`, `inkling`, `gpt_oss`, `nemotron_h`, `lfm2`) and the single-flight `deepseek_v4`/`deepseek_v41` are equal to solo by construction but no guard checks it. +- **Concurrent, a served drafter's groups** (`inkling2`): a greedy or seeded request groups with the others by default, so + a near-tie token can follow who else is served and in what order. With `MLX_SERVE_GREEDY_SOLO_ROUNDS=1` it rounds + alone (`native_group.roundsAlone`, at a multi-user throughput cost), so its text is the one it gets alone, except: past 16 + requests drafting on the model its drafter ring can be parked out and restart (`max_open`); a prompt prefilled while + others decode runs 2048-row chunks (1024 under a decode share; `companyPrefillChunk`); with speculation off it decodes + in the batched group; and a prompt restored from another request's prefix-cache entry is outside `exact_resumed` + (above). An unseeded sampled request groups, and its tokens follow who else is served and in what order. - **Embedded engines** (`ds4`, `llama`, `ane`): every contract unverified. The adapters ignore `Request.no_drafts` and `CacheHint.cold`, and ds4 reports `Stats.drafted = 0`, so a drafted check could not see a draft. - Embedding, decision and media plugins have no token decode loop; their bar is seeded outputs identical. diff --git a/docs/plugin-abi.md b/docs/plugin-abi.md index fabdcedbab..6225c3f504 100644 --- a/docs/plugin-abi.md +++ b/docs/plugin-abi.md @@ -154,10 +154,11 @@ Model facts the host keeps once at load. Defaults are the generic model's. | `merged_state` | `bool` | `false` | A batch's recurrent state is read and written only through `CacheOps.state_rows` / `set_state_rows`, so the engine may keep it merged across batched ticks instead of re-stacking every layer each tick. | | `slot_state` | `bool` | `false` | Module-owned state (`owns_decode_state`) kept per slot (`Forward.slots`, `release_slot`, `activate_slot`): requests interleave and batch instead of running single-flight. | | `ablation` | `bool` | `false` | The forward honours `Forward.ablation` on every pass that writes the residual stream (a native drafter's rounds included). A plugin that resumes its own state across requests (`CacheHooks.resume_prompt`) resumes only under the same `Ablation.keys` entry. | -| `prompt_last_row` | `bool` | `false` | A prompt forward asked for `Logits.last_row` returns its last row's logits alone, bit-identical to that row of its `.all_rows` result, and still every hidden and captured row it is asked for. The host asks for it on the prefill's prompt forwards unless the request echoes prompt logprobs. | +| `prompt_last_row` | `bool` | `false` | A prompt forward asked for `Logits.last_row` returns its last row's logits alone, bit-identical to that row of its `.all_rows` result, and still every hidden and captured row it is asked for. The host asks for it on the prefill's prompt forwards unless the request echoes prompt logprobs. The SDK's bases slice the head's call over every row of the forward, so the bytes do not depend on the mode; a plugin that runs its own head owns the same contract. | | `experts_stream` | `bool` | `false` | The load streams an MLX pack's routed experts on the `stream_experts` setting (`sdk/weights/streamed.zig`): the preflight bills their slot rows, not the experts. Without it the setting is refused by name. | | `served_context` | `bool` | `false` | The load reports the context it serves (`LoadCtx.reportGrant`), and the host holds it to that. A model that streams its weights should: one that does not serves the context it was asked for, and the host warns. | -| `_` | `u30` | `0` | | +| `repeatable_prefill` | `bool` | `false` | A repeatable (greedy or seeded) request's bytes depend on nothing a boot measures: the prompt chunk is pinned from the machine and the pack, never live memory, and a prompt that does not fit waits for room, then is refused by name, instead of running at another width. | +| `_` | `u29` | `0` | | ### `ThinkingDefault` (enum(u8)) @@ -1054,6 +1055,7 @@ A model plugin's table, exported as `exportName(name, version)`. `claims` and `p | `weights` | `*const WeightHooks` | | | | `meters` | `?*const fn (m: *anyopaque, slot: u32, out: *Str) callconv(.c) void` | `null` | `slot`'s arm counters for its request's summary lines (each a full log line), in memory the plugin owns until the next call on `m`; the counters reset. | | `speech` | `?*const SpeechHooks` | `null` | | +| `ready` | `?*const fn (m: *anyopaque) callconv(.c) void` | `null` | The load's own warm-up has run and the model serves requests from now on: work the plugin does only while it warms stops here. Once per load, on the inference thread. Read it through `readyOf`. | ### `declaresMode(caps: Caps, mode: Mode) bool` diff --git a/src/abi/dylib.zig b/src/abi/dylib.zig index 67c890d8bc..5e18d375ee 100644 --- a/src/abi/dylib.zig +++ b/src/abi/dylib.zig @@ -158,7 +158,7 @@ pub fn negotiate(m: *const Manifest, host_mlx: []const u8) Verdict { switch (m.kind) { .model => { if (head.version == 0 or head.version > model_abi.version) return Verdict.refuse(.unsupported, "model table is newer than this host's: a newer mlx-serve serves it"); - if (head.size < @sizeOf(model_abi.ModelTable)) return Verdict.refuse(.unsupported, "model table is older than this host's"); + if (head.size < model_abi.ModelTable.min_size) return Verdict.refuse(.unsupported, "model table is older than this host's"); const t: *const model_abi.ModelTable = @ptrCast(@alignCast(m.table)); if (nullWord(t, "cache") or nullWord(t, "weights")) return Verdict.refuse(.failed, "model table has no cache or weight hook table: both are required, even empty"); @@ -318,6 +318,13 @@ test "abi dylib: a model table with a hook table older than the host's is refuse // never writes a grown `Parsed` or `Bill` past this host's. t.version = model_abi.version - 1; try testing.expect(negotiate(&m, pin).isOk()); + // A table built before `ready` loads, the hook read as absent; one shorter still is refused. + t.size = model_abi.ModelTable.min_size; + try testing.expect(negotiate(&m, pin).isOk()); + try testing.expect(t.readyOf() == null); + t.size = model_abi.ModelTable.min_size - 8; + try testing.expectEqualStrings("model table is older than this host's", negotiate(&m, pin).why.slice()); + t.size = @sizeOf(model_abi.ModelTable); t.version = model_abi.version + 1; try testing.expectEqualStrings("model table is newer than this host's: a newer mlx-serve serves it", negotiate(&m, pin).why.slice()); t.version = model_abi.version; diff --git a/src/abi/plugin.zig b/src/abi/plugin.zig index fa4a917d00..10c31b9721 100644 --- a/src/abi/plugin.zig +++ b/src/abi/plugin.zig @@ -138,7 +138,9 @@ pub const Caps = packed struct(u64) { ablation: bool = false, /// A prompt forward asked for `Logits.last_row` returns its last row's logits alone, bit-identical to that row of /// its `.all_rows` result, and still every hidden and captured row it is asked for. The host asks for it on the - /// prefill's prompt forwards unless the request echoes prompt logprobs. + /// prefill's prompt forwards unless the request echoes prompt logprobs. The SDK's bases slice the head's call over + /// every row of the forward, so the bytes do not depend on the mode; a plugin that runs its own head owns the same + /// contract. prompt_last_row: bool = false, /// The load streams an MLX pack's routed experts on the `stream_experts` setting (`sdk/weights/streamed.zig`): /// the preflight bills their slot rows, not the experts. Without it the setting is refused by name. @@ -146,7 +148,11 @@ pub const Caps = packed struct(u64) { /// The load reports the context it serves (`LoadCtx.reportGrant`), and the host holds it to that. A model that /// streams its weights should: one that does not serves the context it was asked for, and the host warns. served_context: bool = false, - _: u30 = 0, + /// A repeatable (greedy or seeded) request's bytes depend on nothing a boot measures: the prompt chunk is pinned + /// from the machine and the pack, never live memory, and a prompt that does not fit waits for room, then is + /// refused by name, instead of running at another width. + repeatable_prefill: bool = false, + _: u29 = 0, }; pub const ThinkingDefault = enum(u8) { unset, off, on, on_with_tools }; @@ -1200,6 +1206,18 @@ pub const ModelTable = extern struct { /// the next call on `m`; the counters reset. meters: ?*const fn (m: *anyopaque, slot: u32, out: *Str) callconv(.c) void = null, speech: ?*const SpeechHooks = null, + /// The load's own warm-up has run and the model serves requests from now on: work the plugin does only while it + /// warms stops here. Once per load, on the inference thread. Read it through `readyOf`. + ready: ?*const fn (m: *anyopaque) callconv(.c) void = null, + + /// `ready`, null on a table whose `size` ends before it. + pub fn readyOf(t: *const ModelTable) ?*const fn (m: *anyopaque) callconv(.c) void { + if (t.size < @offsetOf(ModelTable, "ready") + @sizeOf(@FieldType(ModelTable, "ready"))) return null; + return t.ready; + } + + /// The smallest table the loader admits: one built before `ready`, which reads as absent. + pub const min_size: u32 = @offsetOf(ModelTable, "ready"); }; /// The modes a model serves: prefill, decode and verify always; the rest as its caps declare. An encoder (`embed`) @@ -1266,6 +1284,16 @@ test "abi plugin: auxiliary callbacks are required function pointers" { } } +test "abi plugin: a model table built before `ready` reads it as absent" { + // Bar: a table whose size ends at `min_size` has no ready hook; a full one has the hook it set. + var t: ModelTable = .{ .name = .of("toy"), .claims = undefined, .parse = undefined, .free_parsed = undefined, .bill = undefined, .load = undefined, .unload = undefined, .forward = undefined, .cache = undefined, .weights = undefined, .ready = &struct { + fn f(_: *anyopaque) callconv(.c) void {} + }.f }; + try testing.expect(t.readyOf() != null); + t.size = ModelTable.min_size; + try testing.expect(t.readyOf() == null); +} + test "abi plugin: unset generation defaults read as unset" { const g: GenDefaults = .{}; try testing.expect(std.math.isNan(g.temperature) and std.math.isNan(g.top_p) and g.top_k == -1); diff --git a/src/engines/mlx/AGENTS.md b/src/engines/mlx/AGENTS.md index 6246e91571..7dc9632973 100644 --- a/src/engines/mlx/AGENTS.md +++ b/src/engines/mlx/AGENTS.md @@ -10,6 +10,9 @@ Loading + residency: else it arrives as `EngineFailed`: DSV4.1's benign `MissingVisionWeights` opt-out failed whole loads under `-Dunits`. - **The first time a build loads a model on a Mac it serves its own warm requests** (`warm_requests.zig`, marker beside Metal's shader cache): a kernel compiles at first use, one variant per row count, prompt size class, cache state and spec mode. Ready first, then `MINIMAL` while idle, each request admitted alone; `--warmup-full` serves `FULL` (adds the prompt-size ladder) before ready: benchmark with it. A new variant axis needs a request that selects it. Guard: `tests/test_first_request_compiles.sh`. +- **A load that read a stored round ladder serves one prompt before ready** (`warm_requests.warmPrompt`, `PROMPT_WARM`): + the rounds' timing request was every other boot's first prefill, so without it a user's first prompt made the prompt + path's pipelines and buffers. Guard: `tests/test_inkling2_first_prompt_warm.sh`. - **The load preflight's "available" is capped by Metal's working-set limit** (`effectiveAvailableBytes(…, memory_ceiling.deviceWorkingSet())`, a forced ceiling never above Metal's working set): a lowered `iogpu.wired_limit_mb` binds below free RAM and weights past it OOM in warmup, leaving a server that refuses every request. - **The load preflight counts the RAM outside wired + compressor, less the OS reserve** (`computeLoadAvailableBytes`): macOS moves any app's pages for a wiring, so only another wired model binds. The eviction planner (`loadRamRoom`) and the GPU ceiling (`currentGpuMemoryCeiling`: admission, auto-context) read the same room (`getLoadRoomBytes`); the hot-cache clamp, held while idle, keeps free + file-backed + purgeable (`idleCacheGpuMemoryCeiling`). - **`modelDiskBytes` bills the shards the INDEX names** (#274); an index naming NO shard on disk is STALE, not a filter (`indexShardSet` → null). @@ -41,12 +44,18 @@ Memory bills + admission: - **A generation's growth is billed to the KV reserve's HEADROOM, never the auto budget** (`glm5PrefillMemoryNeeded`): an omitted `max_tokens` is the rest of a 1M window, and pricing that answer refused a 431-token prompt at 43 GB beside 36 GB free. - **Siblings are billed against un-allocated promises and the plan leaves the OS an eighth of RAM** (`PromiseLedger`, 2 GB `SIBLING_MARGIN_BYTES`; `osReserveBytes` 2..8 GB, `--os-reserve-gib 0` / app toggle). - **A long prefill EVICTS the hot cache to be admitted, on the inference thread** (#353, `evictLruToAdmit`); refusals by NAME (`PrefillDoesNotFit` → 400); warm prompts bill via `WarmPrefix`; ONE `[admission]` line. +- **A `repeatable_prefill` model's chunk is pinned from R, never live memory** (`pinFromMachine`: `contextCeiling`, + `ModelConfig.resident_bytes`, the flags), and a greedy or seeded prompt that does not fit waits for room + (`waitForRoom`, `REPEATABLE_WAIT_MS`), then is refused (`PrefillDoesNotFit`): another width moved a request's bytes. - **A prompt that does not fit UNLOADS idle resident models before it is refused** (`fitAfterUnloadingIdle`, LRU, never its own model): an image model idle beside GLM-5.3 held the memory an agent turn needed, and the 400 ended the agent's session. A load refused for memory does the same and retries (`loadAfterUnloadingIdle`): a plugin sizes its own caches from what is free, past the gate. - **A hot cache a revise cut by over a quarter unloads ONE idle media model before its model's next prefill** (`reclaimSqueezedCache`, `squeezed_from`); a media job that grew active memory re-checks the budgets, since a media model's weights land at its first job, after its load's re-check. Idle ACE-Step held DeepSeek-V4.1's budget at 0. - **A multi-chunk prompt RESERVES its KV up front** (`reservedPrefillTokens`: a grow copies the cache); qwen4_exp past 32k pre-buys generation headroom (`KVCache.reservedTokens`); `max_tokens` clamped FIRST. A decode-billed bill that sets `reserves_request` (streamed Ling) reserves its whole request to the context, and its decode bill prices that KV once. - **Long-context mechanisms of #363 gate on ONE predicate** (`ModelConfig.longCtxGated()`, qwen4_exp). +- **A plugin's optional accelerators ride its `resident_bytes` and are declined, never the load** (`declineAccel`): a bill + that does not fit (live memory at load, the resident cap at the gate) is re-billed under `"accel":false` and the load + serves without them, logged by name; a plugin that bills no less keeps its bill. - **Gates, preflight and COMMIT read ONE estimator** (#126, `estimatePeakResidentBytes` → `gateEstimateBytes`); a refusal quotes the number it COMPARED (`loadRequirementBytes`); staged bills are per-STAGE and a residency bill is a PLAN (`stagedPeakBytes`, `ltxPeakBytes`). - **An H3 request is billed on its OWN sequence** (`h3ActivationBytes`: `h3RequestRows` x `H3_ROW_BYTES` + the fast recipe's per-block attention cache; it prices the resident plan too, and `handleVideoH3` refuses the staged one by NAME before any stage loads, #764): the per-model peak bills one canvas, and a 1536x672 x 124f run died in an uncatchable Metal OOM on its first step. - **A video response is ONE JSON body**: the transport cap bills DELIVERED frames incl. chain windows (#283, `videoRgbTransportReason`, 768 MB). @@ -118,6 +127,9 @@ Attention + KV: - **A fallible re-init BEHIND a `deinit` leaves a freed object** — build first, then swap (`KVCache.reinit`). A handle freed before a fallible op is reset AT the free (`updateDense`). Guard: `KVCache dense update` fault sweep. - **KV growth is PROPORTIONAL** (`nextCapacity` +25%, floor one chunk, cap 8192) and stops at the context plus the widest verify (`limitGrowth`, set per request). `active` flat while phys climbs = the POOL (`/props` `memory.cache_bytes`). - **Allocator cache**: `mlx_clear_cache()` per CHUNK and per emitted block, un-skippable (#110): `applyMlxCacheLimit` once in `main()`; cadence interval-based; `Generator.advanceStep` is the one step mover; `finishSlot` clears the tail. +- **Every prompt logs one `[repro]` line** (`repro.zig`: `inputs=` the build, OS build, machine, pack and `MLX_` set; `plan=` + the pinned width, KV, sampling key, spec mode, solo rounds; `company=` where another request narrowed the width): equal + digests with different bytes are a kernel's defect (an unwritten read or a race), never a decision. - **Hybrid-SSM prefix cache retains ~3.4× what it reports** (lever = ENTRY COUNT, `ramCappedPrefixCacheEntries`). SSM-checkpoint stride never sub-divides the chunk; dense hd-256 chunk cap 8192, MoE 4096. - **Hybrid prefix candidates rank by RESTORABLE SSM position** (`findBestRestorableMatch`). The always-on SSM snapshot sits `SSM_SNAPSHOT_BACKOFF` (30) tokens BEFORE prompt end. - **A re-rendered answer re-tokenizes, and a sampled answer need not be canonical** (`" ----" "--------"` against @@ -146,12 +158,12 @@ Spec decode: - **A native drafter's copy is looked up where a round may not run** (`copyAhead` over the committed tail): checked only in drafted rounds, a sampled request whose policy had stopped drafting never copied a repeated file. A repeated prompt also copies from the earlier answer (`adoptFor`'s tail, indexed before the prompt). -- **A greedy or seeded request takes nothing an earlier request left** (`SamplingParams.repeats`: no adopted drafter - state, no earlier answer to copy): with either its rounds line up otherwise, a verify row's logits part in the low - bits, and the same request answered differently twice. Alone it repeats; beside others its group follows arrivals. -- **A native drafter's rounds are priced on a ladder its load times once, never on a clock inside a request** - (`sdk/spec/rounds.zig`: `Timing` through `warm_requests.timeRounds`, a `Controller` per request over its own - acceptance counts): wall-clock samples sent a seed to plain decode or wide rounds by boot. Untimed = plain steps. +- **A greedy or seeded request reads nothing another request chose** (`SamplingParams.repeats`): no adopted drafter + state, no earlier answer to copy, and no shared forward (`native_group.slotAlone`: no group round, no yield to the + batched decode). Each lines its rounds up otherwise: a verify row's logits part in the low bits, a near-tie flips. +- **A native drafter's rounds are priced on a ladder timed once per release, never on a clock inside a request** + (`rounds.Timing` via `warm_requests.timeRounds`, stored per build/machine/model/`MLX_` set by `spec/ladder_store.zig`; + a `Controller` per request): wall-clock samples, or a ladder re-timed each boot, moved the rounds by boot. - **A pipelined step is timed as the mean of a run of ticks, a round as its least** (`rounds.Timing`): pipelined ticks trade time with each other, and the least tick read the step a quarter short, which prices every round as a loss. - **A block decoder checks its ENTRY token first** (`generate.tokenStops`, all five); only an ALL-pad generation declines commit (`commitDeclinesPadOnly`); a cancel mid batched tick still RECORDS the row (`batchedTickAction`). @@ -263,6 +275,6 @@ Kernels + numerics: - **Tokenizer**: special-token splitting only in `Tokenizer.encode` (first-byte buckets); any per-position loop over a vocab-derived collection needs an index. - **Upgrades**: mlx-c → diff `lib/mlxc-src/mlx/c/*.h` vs `src/mlx/ffi.zig`; ds4 → re-sync `engines/ds4/ffi.zig` EngineOptions + CORE_OBJS; NAX presence asserted, never assumed. - **ANE prefill (opt-in, M4-and-below, LOSSY)**: rules in `docs/reference.md` "ANE prefill rules"; parity = per-program cos/rms + perceived-content equivalence; `ready: N/M` under-count = silent partial coverage. Guard: `tests/test_ane_prefill.sh`. -- **Slots of a served drafter verify as ONE group round, sampled or greedy** (`spec/native_group.zig`, `dspark.nativeGroupRound`): the plugin opens every slot's block as one forward (`NativeDrafter.verify_group`), the accepts start together (sampled: `acceptStartProbs`, one filter block when the slots filter alike; greedy: `greedyPicks`, one argmax block), each slot accepts under its own sampling. A slot the controller sends plain rides it on its one row; `specYieldTick` keeps group-capable slots from yielding to plain decode up to `NativeDrafter.group_width`. `MLX_SERVE_NATIVE_GROUPS=0` = a slot's round after another. +- **Slots of a served drafter verify as ONE group round** (`spec/native_group.zig`, `dspark.nativeGroupRound`): the plugin opens every slot's block as one forward (`NativeDrafter.verify_group`), the accepts start together (sampled: `acceptStartProbs`, one filter block when the slots filter alike; greedy: `greedyPicks`, one argmax block), each slot accepts under its own sampling. A slot the controller sends plain rides it on its one row; `specYieldTick` keeps group-capable slots from yielding to plain decode up to `NativeDrafter.group_width`. A greedy or seeded slot groups too; with `MLX_SERVE_GREEDY_SOLO_ROUNDS=1` it rounds alone (`roundsAlone`), so it repeats under load. `MLX_SERVE_NATIVE_GROUPS=0` = a slot's round after another. - **A drafter that serves `NativeDrafter.step_group` runs the whole round itself** (draft, verify, accept, commit; `nativeStepGroup`): the engine hands each slot its sampling filters and seed, takes the committed tokens back, and falls to verify_group/finish_group when the plugin answers `unsupported`; a keyed-serial sampler and the load's ladder timing never take it. - **A default-on kill switch is read with `env.notOff`**: `env.on` is false when the variable is unset (the group rounds ran in no server that did not set it). diff --git a/src/engines/mlx/admission/pending.zig b/src/engines/mlx/admission/pending.zig index fd2bf5ff07..fae0201e5d 100644 --- a/src/engines/mlx/admission/pending.zig +++ b/src/engines/mlx/admission/pending.zig @@ -40,6 +40,23 @@ pub fn slotHoldsForMemory(sch: *Scheduler, slot: *Slot) bool { return true; } +/// How long a repeatable prompt on a `repeatable_prefill` model waits for room at its pinned width before it is +/// refused, and how often it looks: memory macOS has not yet shown free, or another process lets go of. +pub const REPEATABLE_WAIT_MS: u32 = 10_000; +pub const REPEATABLE_POLL_MS: u32 = 100; + +/// Asks `fits` every `poll_ms` until it says yes or `wait_ms` have passed, giving MLX's pool back before each +/// look. True when it fit. The width stays as planned: a repeatable request's bytes never depend on room. +pub fn waitForRoom(io: std.Io, ctx: ?*anyopaque, fits: *const fn (?*anyopaque) bool, wait_ms: u32, poll_ms: u32) bool { + var waited: u32 = 0; + while (waited < wait_ms) : (waited += poll_ms) { + std.Io.sleep(io, .fromMilliseconds(poll_ms), .real) catch {}; + _ = mlx.mlx_clear_cache(); + if (fits(ctx)) return true; + } + return false; +} + pub fn releasePromise(sch: *Scheduler, slot: *Slot) void { sch.promise_ledger.release(slot.memory_promised); slot.memory_promised = 0; @@ -179,3 +196,22 @@ test "admitPendingTick: non-exclusive concurrency and queue order preserved" { try testing.expectEqual(@as(usize, 1), small[1]); } } + +// Bar: a wait ends at the first look that fits, and a prompt that never fits is let go after the bound. +test "waitForRoom: returns at the first fit, gives up at the bound" { + const Probe = struct { + looks: u32 = 0, + fits_at: u32, + fn call(ctx: ?*anyopaque) bool { + const self: *@This() = @ptrCast(@alignCast(ctx.?)); + self.looks += 1; + return self.looks >= self.fits_at; + } + }; + var soon = Probe{ .fits_at = 3 }; + try testing.expect(waitForRoom(testing.io, &soon, Probe.call, 50, 1)); + try testing.expectEqual(@as(u32, 3), soon.looks); + var never = Probe{ .fits_at = std.math.maxInt(u32) }; + try testing.expect(!waitForRoom(testing.io, &never, Probe.call, 5, 1)); + try testing.expectEqual(@as(u32, 5), never.looks); +} diff --git a/src/engines/mlx/admission/prefill_chunk.zig b/src/engines/mlx/admission/prefill_chunk.zig index 6406e01d21..15e96a42d9 100644 --- a/src/engines/mlx/admission/prefill_chunk.zig +++ b/src/engines/mlx/admission/prefill_chunk.zig @@ -188,9 +188,11 @@ pub fn sizerCtxKvBytes(config: *const model_mod.ModelConfig, kv_bits: u64) u64 { } /// The chunk this model is billed at, from static inputs only: the context ceiling and the model's own resident -/// bill (`ModelConfig.resident_bill`), so a reload under other memory pins the same width. +/// bill (`ModelConfig.resident_bill`), so a reload under other memory pins the same width. A `repeatable_prefill` +/// model's is `pinFromMachine` under the same ceiling (`contextCeiling`): one definition for the pin and every reader. pub fn staticPrefillChunk(config: *const model_mod.ModelConfig) u32 { if (config.pinned_prefill_chunk != 0) return config.pinned_prefill_chunk; + if (config.repeatablePrefill()) return pinFromMachine(config, contextCeiling()); const kv_bits: u64 = defaultKvBits(config); // Which ask: the gated arch reads the resolved budget; every other arch reads the raw ask as before. const hot_cache_ask = if (config.longCtxGated()) resolvedPrefixCacheMem() else legacyPrefixCacheAsk(); @@ -204,6 +206,10 @@ pub fn staticPrefillChunk(config: *const model_mod.ModelConfig) u32 { /// decided: the memory limit bills this chunk's transient reserve, and `checkAttentionMemory` and /// `generate.effectivePrefillChunk` then read the same frozen value, so the bill and the forward cannot drift. pub fn pinPrefillChunk(config: *model_mod.ModelConfig) u32 { + if (config.pinned_prefill_chunk == 0 and config.repeatablePrefill()) { + config.pinned_prefill_chunk = staticPrefillChunk(config); + return config.pinned_prefill_chunk; + } if (config.pinned_prefill_chunk == 0) { config.pinned_prefill_chunk = staticPrefillChunk(config); // Say when the ctx bar is the binding one. @@ -226,6 +232,17 @@ pub fn pinPrefillChunk(config: *model_mod.ModelConfig) u32 { return config.pinned_prefill_chunk; } +/// A `repeatable_prefill` model's pin: the ladder against `ceiling` (`contextCeiling`: the working set, lowered by +/// `--gpu-ceiling-gib` / `--memory-preset`, less the OS reserve) less the pack's committed weights, the configured +/// hot-cache ask and an explicit `--ctx-size`'s KV. Nothing a boot measures enters it, so every boot of the same +/// build, pack, flags and machine runs a prompt at the same width. +pub fn pinFromMachine(config: *const model_mod.ModelConfig, ceiling: u64) u32 { + const kv_bits: u64 = defaultKvBits(config); + const ask = legacyPrefixCacheAsk(); + const width = billedPrefillChunk(config, kv_bits, ceiling, config.resident_bytes, sizerCtxKvBytes(config, kv_bits), ask, explicitPrefillChunk()); + return @intCast(config.cappedPrefillChunk(width)); +} + /// The width a ladder rung actually forwards at for this prompt. fn widthForRung(cfg: *const model_mod.ModelConfig, seq: u64, rung: u32) u32 { return @intCast(rungWidth(cfg, seq, rung, cfg.longCtxGated())); @@ -1783,3 +1800,47 @@ test "the live 364k session's admission numbers reproduce, to the megabyte" { prefillNeededAtChunk(&cfg, 368_208, 418_224, kv_bits, 512, .{}) / mb, ); } + +// Bar: a `repeatable_prefill` model pins one chunk whatever the machine's free memory reads at load, and that chunk +// follows the forced GPU ceiling (`--gpu-ceiling-gib` through `contextCeiling`): a smaller ceiling pins narrower (the +// test's power). The pin and `staticPrefillChunk` give one number. +test "pinPrefillChunk: a repeatable_prefill model pins from the machine and its weights, never live memory" { + const t = std.testing; + const GB: u64 = 1 << 30; + var cfg = model_mod.ModelConfig{}; + cfg.num_hidden_layers = 28; + cfg.num_attention_heads = 24; + cfg.num_key_value_heads = 8; + cfg.head_dim = 128; + cfg.hidden_size = 3072; + cfg.intermediate_size = 8192; + cfg.max_position_embeddings = 131072; + cfg.resident_bytes = 4 * GB; + cfg.legacy.caps.repeatable_prefill = true; + const saved = memory_ceiling.overrides().*; + defer memory_ceiling.overrides().* = saved; + const capacity = http_server.launch().prefix_cache_capacity; + defer http_server.launch().prefix_cache_capacity = capacity; + http_server.launch().prefix_cache_capacity = 0; + const os_reserve = @import("../../../sdk/util/system.zig").osReserveOverride(); + const saved_reserve = os_reserve.*; + defer os_reserve.* = saved_reserve; + os_reserve.* = 0; + memory_ceiling.overrides().device_working_set = 128 * GB; // a 128 GB Mac, whatever runs the test + memory_ceiling.overrides().wired_limit_mb = 0; + + var pins: [2][2]u32 = undefined; + for ([_]u64{ 5 * GB, 30 * GB }, &pins) |forced, *row| for ([_]u64{ 2 * GB, 24 * GB }, row) |free, *pin| { + memory_ceiling.overrides().static_ceiling = forced; + memory_ceiling.overrides().machine_free = .{ .idle = free, .request = free }; + cfg.pinned_prefill_chunk = 0; + try t.expectEqual(forced, memory_ceiling.contextCeiling()); + const unpinned = staticPrefillChunk(&cfg); + pin.* = pinPrefillChunk(&cfg); + try t.expectEqual(unpinned, pin.*); + }; + try t.expectEqual(pins[0][0], pins[0][1]); + try t.expectEqual(pins[1][0], pins[1][1]); + try t.expect(pins[0][0] < pins[1][0]); + try t.expectEqual(pinFromMachine(&cfg, 30 * GB), pins[1][0]); +} diff --git a/src/engines/mlx/load.zig b/src/engines/mlx/load.zig index c184d37a8f..e796729b01 100644 --- a/src/engines/mlx/load.zig +++ b/src/engines/mlx/load.zig @@ -30,6 +30,7 @@ const plugin_media = @import("plugin/media.zig"); const DrafterModel = drafter_mod.DrafterModel; const dflash_mod = @import("spec/dflash/dflash.zig"); const round_cost_mod = @import("spec/round_cost.zig"); +const ladder_store = @import("spec/ladder_store.zig"); const DflashModel = dflash_mod.DflashModel; const VisionEncoder = vision_mod.VisionEncoder; const Weights = model_mod.Weights; @@ -50,6 +51,8 @@ const residentModelDiskBytes = @import("runtime/preflight.zig").residentModelDis const residentGateBytes = @import("runtime/preflight.zig").residentGateBytes; const committedTextBytes = @import("runtime/preflight.zig").committedTextBytes; const availForLoad = @import("runtime/preflight.zig").availForLoad; +const memInsufficientForLoad = @import("runtime/preflight.zig").memInsufficientForLoad; +const declineAccel = @import("runtime/preflight.zig").declineAccel; const mtpSidecarDiskBytes = @import("runtime/preflight.zig").mtpSidecarDiskBytes; const mtpCoarseBytes = @import("runtime/preflight.zig").mtpCoarseBytes; const drafterResidentBytes = @import("runtime/preflight.zig").drafterResidentBytes; @@ -95,10 +98,14 @@ pub fn doLoadOnInferenceThread(sch: *Scheduler, params: anytype) !void { try doLoadGenOnInferenceThread(sch, params, modality); return; } - const model_bytes = params.resident_model_bytes orelse blk: { + const model_bytes = try fitAccel(sch, params, params.resident_model_bytes orelse blk: { const scanned = try residentModelDiskBytes(sch.allocator, sch.io, params.model_dir, params.config); break :blk residentGateBytes(scanned, params.entry.bytes_on_disk, true).?; - }; + }); + // The pack's term in a `repeatable_prefill` model's chunk pin, set before anything pins it: `decideServedContext` + // pins the chunk (`staticMemoryLimit`). + params.config.resident_bytes = committedTextBytes(model_bytes, params.config) + pleTableBill(sch.io, params.config); + params.config.repro_inputs = @import("repro.zig").inputsDigest(sch.io, sch.allocator, params.model_dir); try decideServedContext(params, model_bytes, ane_declined or (params.gguf == null and engines_served.aneWanted(params.config, params.ane))); // GPU-memory pre-flight (MLX path). A Metal OOM during weight load / warmup @@ -125,9 +132,7 @@ pub fn doLoadOnInferenceThread(sch: *Scheduler, params: anytype) !void { const gb = 1024.0 * 1024.0 * 1024.0; const sidecar: []const u8 = chosen_drafter orelse in_dir_drafter orelse ""; const drafter_bytes: u64 = if (sidecar.len == 0) 0 else drafterResidentBytes(modelDiskBytes(sch.io, sidecar), dflash_mod.sidecarQuantBits(sch.io, sch.allocator, sidecar)); - const mtp_on = params.config.mtp_override orelse params.mtp_enabled; - const mtp_bytes = mtpSidecarDiskBytes(sch.io, sch.allocator, params.model_dir, mtp_on); - const coarse_bytes = if (mtp_on) mtpCoarseBytes(params.config, mtp_mod.hasMtpHead(sch.io, sch.allocator, params.model_dir)) else 0; + const mtp_bytes, const coarse_bytes = mtpBill(sch, params); const weights_bytes = model_bytes + drafter_bytes + mtp_bytes + coarse_bytes; const avail_bytes = availForLoad(sch.io, weights_bytes); log.info("[preflight] weights ~{d:.2} GB, available {d:.2} GB\n", .{ @@ -963,6 +968,16 @@ pub fn doLoadOnInferenceThread(sch: *Scheduler, params: anytype) !void { // `--warmup-full`: ready only once it has served its own first requests, so whoever asks next measures the model, // not its compiles. Otherwise it is ready now and owes a short warm-up for when the server is idle. const chat = ModelRegistry.chatCapable(entry); + // A served drafter's ladder stored by an earlier boot of this build, machine and composition: nothing times it. + if (entry.transformer) |xfm| if (plugin_driver.nativeStages(xfm) > 0) ladder_store.restore(sch.io, xfm.plugin.?, .{ + .build = round_cost_mod.engineBuildId(), + .chip = ane_mod.chipBrand(), + .mem_bytes = ane_mod.totalMemBytes(), + .model_dir = params.model_dir, + .levers = ladder_store.levers(), + }); + // A stored ladder leaves no request to time the rounds, the prompt every other boot serves first: one, before ready. + if (warm_requests.promptWarmOwed(entry, params.warmup_full, chat)) warm_requests.warmPrompt(sch, entry); if (params.warmup_full) { if (warm_marker) |marker| { if (!chat or warm_requests.run(sch, entry)) warm_requests.remember(marker); @@ -970,6 +985,8 @@ pub fn doLoadOnInferenceThread(sch: *Scheduler, params: anytype) !void { } warm_requests.timeRounds(sch, entry); } + // Everything the load serves itself has run: what follows is served to whoever asks. + if (entry.transformer) |xfm| plugin_driver.ready(xfm); sch.registry.mutex.lockUncancelable(sch.io); entry.bytes_live = bytes_live; @@ -979,6 +996,27 @@ pub fn doLoadOnInferenceThread(sch: *Scheduler, params: anytype) !void { publishHotCacheResidency(sch); } +/// `billed` where it fits, with the MTP terms, what the load can use once idle models make room for it, else the bill +/// without the plugin's accelerators (`declineAccel`); before anything reads the bill. An optional drafter is the +/// preflight's to drop. +fn fitAccel(sch: *Scheduler, params: anytype, billed: u64) !u64 { + const b = params.config.plugin orelse return billed; + if (scheduler_mod.skip_mem_preflight or params.config.accel_declined or b.table.weights.resident_bytes == null) return billed; + makeRoomInRam(sch, params.entry.id, billed); + const mtp_bytes, const coarse_bytes = mtpBill(sch, params); + const with = billed + mtp_bytes + coarse_bytes; + if (!memInsufficientForLoad(with, availForLoad(sch.io, with))) return billed; + return (try declineAccel(sch.allocator, sch.io, params.model_dir, params.config, billed)) orelse billed; +} + +/// The preflight's MTP terms beside the weights: the head's sidecar and its coarse shortlist head. +fn mtpBill(sch: *Scheduler, params: anytype) struct { u64, u64 } { + const mtp_on = params.config.mtp_override orelse params.mtp_enabled; + const mtp_bytes = mtpSidecarDiskBytes(sch.io, sch.allocator, params.model_dir, mtp_on); + const coarse_bytes = if (mtp_on) mtpCoarseBytes(params.config, mtp_mod.hasMtpHead(sch.io, sch.allocator, params.model_dir)) else 0; + return .{ mtp_bytes, coarse_bytes }; +} + /// The served context of an MLX load, before the plugin opens: from static inputs (the model's own resident bill /// under the context ceiling), the remembered record when the key holds. A streamed bank's is its grant at load. /// `declined`: the Neural Engine was wanted and the GPU serves it instead. diff --git a/src/engines/mlx/plugin/driver.zig b/src/engines/mlx/plugin/driver.zig index dc4e7f02dd..da23690e33 100644 --- a/src/engines/mlx/plugin/driver.zig +++ b/src/engines/mlx/plugin/driver.zig @@ -71,6 +71,9 @@ pub const Bound = struct { /// for good where the timing request (`ladder_asked`) could not time them: the drafter stays off. ladder: ?rounds.Ladder = null, ladder_asked: bool = false, + /// Where this load's ladder is stored once timed (`spec/ladder_store.zig`); empty = nowhere. + ladder_file: [600]u8 = undefined, + ladder_file_len: usize = 0, /// Each layer's kind (`CacheHooks.layout`), `.full` past the layout or without one. kinds: [128]abi.LayerKind = @splat(.full), @@ -133,13 +136,14 @@ fn headMxfp8Setting(config: *const ModelConfig) ?bool { } /// `LoadCtx.settings_json`: the load settings stated for this model (a plugin that serves them reads them): the lossy -/// `lm_head_mxfp8`, the `mtp` head, the lossy `int8_prefill`, `stream_experts` and the model's `ctx_size`. `buf` holds 128 bytes. +/// `lm_head_mxfp8`, the `mtp` head, the lossy `int8_prefill`, `stream_experts`, the model's `ctx_size` and a declined accelerator. `buf` holds 256 bytes. pub fn loadSettings(buf: []u8, config: *const ModelConfig) []const u8 { var w: std.Io.Writer = .fixed(buf); w.writeByte('{') catch unreachable; if (headMxfp8Setting(config)) |on| w.print("\"lm_head_mxfp8\":{s}", .{if (on) "true" else "false"}) catch unreachable; if (config.mtp_override) |on| w.print("{s}\"mtp\":{s}", .{ if (w.end > 1) "," else "", if (on) "true" else "false" }) catch unreachable; if (config.int8_prefill_override) |on| w.print("{s}\"int8_prefill\":{s}", .{ if (w.end > 1) "," else "", if (on) "true" else "false" }) catch unreachable; + if (config.accel_declined) w.print("{s}\"accel\":false", .{if (w.end > 1) "," else ""}) catch unreachable; if (config.stream_experts_override) |st| { if (w.end > 1) w.writeByte(',') catch unreachable; switch (st) { @@ -1094,7 +1098,7 @@ fn loadTensors(io: std.Io, a: std.mem.Allocator, config: *ModelConfig, model_dir var why: abi.Verdict = .{}; // A placeholder only the tokenizer names (RADIO's ``) comes from the engine config, which read it. if (b.parsed.caps.images and b.parsed.placeholder_ids.image == 0) b.parsed.placeholder_ids.image = config.image_token_id; - var settings_buf: [128]u8 = undefined; + var settings_buf: [256]u8 = undefined; const ceiling = @import("../../../host/registry/memory_ceiling.zig").staticGpuMemoryCeiling(); // A streamed bank's calibration applies only under this server's key; a key that cannot be read is none. const fit_key: ?[]u8 = if (b.parsed.caps.streamed_weights) @import("fit_key.zig").hostKey(a, io, fs.root, config, &dir) catch null else null; @@ -1500,6 +1504,12 @@ pub fn nativeDrafter(xfm: *const Transformer) ?*const abi.NativeDrafter { return spec.native_drafter; } +/// Tells the served model its load is ready (`ModelTable.ready`): after the load's own requests, before it serves. +pub fn ready(xfm: *const Transformer) void { + const b = xfm.plugin orelse return; + if (b.table.readyOf()) |f| f(b.model); +} + /// The draft stages of the served model's native drafter (`SpecFacts.native_stages`); 0 without one. pub fn nativeStages(xfm: *const Transformer) u32 { const nd = nativeDrafter(xfm) orelse return 0; @@ -2249,6 +2259,17 @@ test "plugin driver: the load settings carry the model's lm_head_mxfp8 and mtp" try std.testing.expectEqualStrings("{\"lm_head_mxfp8\":false,\"mtp\":false,\"ctx_size\":262144}", loadSettings(&buf, &c)); } +test "plugin driver: the load settings decline a plugin's accelerators only where the load declined them" { + var buf: [256]u8 = undefined; + var c: ModelConfig = .{}; + try std.testing.expectEqualStrings("{}", loadSettings(&buf, &c)); + c.accel_declined = true; + try std.testing.expectEqualStrings("{\"accel\":false}", loadSettings(&buf, &c)); + // Every setting at once fits the buffers the load and the preflight hand it. + c = .{ .lm_head_mxfp8_override = false, .mtp_override = false, .int8_prefill_override = false, .stream_experts_override = .{ .rows = std.math.maxInt(u32) }, .ctx_override = std.math.maxInt(u32), .accel_declined = true }; + try std.testing.expect(std.mem.indexOf(u8, loadSettings(&buf, &c), "\"accel\":false") != null); +} + test "driver: a DeepSeek-V4.1 pack's vision, aligner and image rows move to the tower; its trunk stays" { var c: ModelConfig = .{ .model_type = "deepseek_v41" }; for ([_][]const u8{ "vision.patch_embed.proj.weight", "aligner.w1.weight", "image_newline" }) |k| try std.testing.expect(towerKey(&c, k)); diff --git a/src/engines/mlx/prefill.zig b/src/engines/mlx/prefill.zig index bfbcd86ebf..1b9d91dd9d 100644 --- a/src/engines/mlx/prefill.zig +++ b/src/engines/mlx/prefill.zig @@ -5,6 +5,8 @@ const mlx = @import("../../mlx/ffi.zig"); const transformer_mod = @import("transformer.zig"); const generate_mod = @import("generate.zig"); const gen_mod = @import("../../host/media_jobs/gen.zig"); +const pending_mod = @import("admission/pending.zig"); +const repro = @import("repro.zig"); const model_mod = @import("../../sdk/config/model.zig"); const prefix_cache_mod = @import("cache/prefix_cache.zig"); const restore_dump = @import("cache/restore_dump.zig"); @@ -512,6 +514,11 @@ pub fn runPrefill(sch: *Scheduler, slot: *Slot) !void { fits = cold_report.admitted; publishHotCacheResidency(sch); }; + // A repeatable prompt keeps the width its model pinned: it waits for room, then is refused. + if (!fits and cfg.repeatablePrefill() and slot.sampling.repeats()) { + log.info("[prefill] repeatable: {d} tokens wait up to {d} ms for room at width {d}\n", .{ slot.full_prompt.len, pending_mod.REPEATABLE_WAIT_MS, cfg.pinned_prefill_chunk }); + fits = pending_mod.waitForRoom(sch.io, &probe, Probe.call, pending_mod.REPEATABLE_WAIT_MS, pending_mod.REPEATABLE_POLL_MS); + } if (!fits) { log.warn("[scheduler] prefill refused: {d} tokens do not fit even with an empty hot cache\n", .{slot.full_prompt.len}); if (scheduler_mod.prefill_admission_refused_log) |report_fn| { @@ -554,6 +561,16 @@ pub fn runPrefill(sch: *Scheduler, slot: *Slot) !void { // out of prefill_ns below (the decoding slots got the time). var interleave_ctx = InterleaveCtx{ .sch = sch, .slot = slot, .chunk_sw = io_util.Stopwatch.init(sch.io) }; var write_through_ctx = WriteThroughCtx{ .slot = slot }; + // What this request's numerics read, and where another request moved them. + if (slot.model.config) |cfg| repro.logLine(cfg.repro_inputs, .{ + .planned = req_prefill_chunk, + .width = companyPrefillChunk(req_prefill_chunk, scheduler_mod.decodingCount(sch)), + .kv_bits = if (slot.cache.config.scheme == .off) 16 else slot.cache.config.bits, + .repeats = slot.sampling.repeats(), + .seed = slot.sampling.seed, + .spec = if (use_dflash) .dflash else if (use_mtp) .mtp else if (use_drafter) .drafter else if (use_pld) .pld else .off, + .solo_rounds = @import("spec/native_group.zig").roundsAlone(slot.sampling), + }); // Per-chunk prefill width context. Stack-scoped like `interleave_ctx`. var width_ctx = ChunkWidthCtx{ .sch = sch, diff --git a/src/engines/mlx/prefill_interleave.zig b/src/engines/mlx/prefill_interleave.zig index 9ab9678afe..9c6822da8d 100644 --- a/src/engines/mlx/prefill_interleave.zig +++ b/src/engines/mlx/prefill_interleave.zig @@ -65,11 +65,12 @@ pub fn yieldsToCompany(mode: SpecTickMode, cuda: bool, sparse_target: bool, othe const Company = struct { others: usize = 0, dspark: bool = false }; /// Who else decodes on `s`'s model: how many, and whether one of them can join its DSpark group round -/// (`groupable`). Plain company would wait on a solo DSpark round every token. -fn modelCompany(active: anytype, s: anytype, groupable: anytype) Company { +/// (`groupable`). Plain company would wait on a solo DSpark round every token. A slot that rounds `alone` batches +/// with nobody, so it is no one's company. +fn modelCompany(active: anytype, s: anytype, groupable: anytype, alone: anytype) Company { var c: Company = .{}; for (active) |o| { - if (o == s or o.model != s.model) continue; + if (o == s or o.model != s.model or alone(o)) continue; c.others += 1; c.dspark = c.dspark or groupable(o); } @@ -93,7 +94,12 @@ pub fn specYieldTick(active: []const *Slot) void { s.company_ticks = 0; continue; }; - var company = modelCompany(active, s, groupRoundSlot); + // A request that must answer the same twice keeps its own rounds at any load (`native_group.slotAlone`). + if (native_group.slotAlone(s)) { + s.company_ticks = 0; + continue; + } + var company = modelCompany(active, s, groupRoundSlot, native_group.slotAlone); // More slots than a served drafter's group carries to each one's benefit decode plain in the batched group. if (s.model.transformer) |t| if (native_group.slotGroupable(s) and company.others + 1 > plugin_driver.nativeGroupWidth(t)) { company.dspark = false; @@ -1039,18 +1045,27 @@ test "yieldsToCompany: a DSpark slot keeps drafting beside a slot it can group w } test "modelCompany: only another slot on the same model that can join its group round is DSpark company" { - const F = struct { model: u8, ds: bool }; - const fs = [_]F{ .{ .model = 1, .ds = true }, .{ .model = 1, .ds = false }, .{ .model = 2, .ds = true }, .{ .model = 1, .ds = true } }; - const p = [_]*const F{ &fs[0], &fs[1], &fs[2], &fs[3] }; + const F = struct { model: u8, ds: bool, alone: bool = false }; + const fs = [_]F{ .{ .model = 1, .ds = true }, .{ .model = 1, .ds = false }, .{ .model = 2, .ds = true }, .{ .model = 1, .ds = true }, .{ .model = 1, .ds = false, .alone = true } }; + const p = [_]*const F{ &fs[0], &fs[1], &fs[2], &fs[3], &fs[4] }; const groupable = struct { fn f(x: *const F) bool { return x.ds; } }.f; + const alone = struct { + fn f(x: *const F) bool { + return x.alone; + } + }.f; // Plain company on its model and a DSpark slot on another model: nothing to group with. - try testing.expectEqual(Company{ .others = 1, .dspark = false }, modelCompany(p[0..3], p[0], groupable)); - try testing.expectEqual(Company{ .others = 2, .dspark = true }, modelCompany(p[0..4], p[0], groupable)); - try testing.expectEqual(Company{ .others = 0, .dspark = false }, modelCompany(p[0..4], p[2], groupable)); + try testing.expectEqual(Company{ .others = 1, .dspark = false }, modelCompany(p[0..3], p[0], groupable, alone)); + try testing.expectEqual(Company{ .others = 2, .dspark = true }, modelCompany(p[0..4], p[0], groupable, alone)); + try testing.expectEqual(Company{ .others = 0, .dspark = false }, modelCompany(p[0..4], p[2], groupable, alone)); + // A slot that rounds alone (a greedy request on a grouping drafter) is nobody's company. + try testing.expectEqual(Company{ .others = 2, .dspark = true }, modelCompany(p[0..5], p[0], groupable, alone)); + const pair = [_]*const F{ p[1], p[4] }; + try testing.expectEqual(Company{ .others = 0, .dspark = false }, modelCompany(pair[0..], p[1], groupable, alone)); } test "companyPrefillChunk: a prefill narrows only while someone decodes" { diff --git a/src/engines/mlx/repro.zig b/src/engines/mlx/repro.zig new file mode 100644 index 0000000000..7ff20f9980 --- /dev/null +++ b/src/engines/mlx/repro.zig @@ -0,0 +1,138 @@ +//! A request's bytes are a function of R: the build, the OS build, the pack, the settings, the machine class and the +//! request. `inputsDigest` hashes R's boot terms once a load (`ModelConfig.repro_inputs`); a `Plan` holds what this +//! request's numerics read; the `[repro]` line prints both per request, plus the company events (other requests +//! narrowing the width). Two runs with equal digests and no company event that give different bytes name a kernel +//! that reads unwritten bytes or races (rule B), never a decision. + +const std = @import("std"); +const builtin = @import("builtin"); +const round_cost = @import("spec/round_cost.zig"); +const ladder_store = @import("spec/ladder_store.zig"); +const system = @import("../../sdk/util/system.zig"); +const log = @import("../../sdk/util/log.zig"); + +/// R's boot terms: the build (executable digest), the OS build (the Metal compiler ships with it), the machine (chip +/// and RAM in GB), the pack (its folder and its index file's bytes) and the settings (every `MLX_` variable). +pub fn inputsDigest(io: std.Io, allocator: std.mem.Allocator, pack_dir: []const u8) u64 { + var h = std.hash.Fnv1a_64.init(); + h.update(round_cost.engineBuildId()); + h.update("\x00"); + h.update(osBuild()); + h.update("\x00"); + h.update(chip()); + const ram_gb: u64 = system.getTotalMemBytes() >> 30; + h.update(std.mem.asBytes(&ram_gb)); + h.update(pack_dir); + h.update("\x00"); + mixIndex(io, allocator, &h, pack_dir); + h.update(&ladder_store.levers()); + return h.final(); +} + +fn osBuild() []const u8 { + if (comptime builtin.os.tag != .macos) return @tagName(builtin.os.tag); + const S = struct { + var buf: [64]u8 = undefined; + var len: usize = 0; + }; + if (S.len == 0) { + var n: usize = S.buf.len; + if (std.c.sysctlbyname("kern.osversion", &S.buf, &n, null, 0) == 0) S.len = n; + } + return S.buf[0..S.len]; +} + +fn chip() []const u8 { + if (comptime builtin.os.tag != .macos) return ""; + const S = struct { + var buf: [128]u8 = undefined; + var len: usize = 0; + }; + if (S.len == 0) { + var n: usize = S.buf.len; + if (std.c.sysctlbyname("machdep.cpu.brand_string", &S.buf, &n, null, 0) == 0) S.len = n; + } + return S.buf[0..S.len]; +} + +/// The pack's index and config: what names the loader's tensors and the model's shape, not every file in the folder. +fn mixIndex(io: std.Io, allocator: std.mem.Allocator, h: *std.hash.Fnv1a_64, pack_dir: []const u8) void { + var dir = std.Io.Dir.openDirAbsolute(io, pack_dir, .{}) catch return; + defer dir.close(io); + for ([_][]const u8{ "model.safetensors.index.json", "config.json" }) |name| { + const bytes = dir.readFileAlloc(io, name, allocator, .limited(64 << 20)) catch continue; + defer allocator.free(bytes); + h.update(name); + h.update(bytes); + } +} + +/// What this request's numerics read: the width its model pinned (`planned`) and the width it runs at (`width`, which +/// company narrows), the KV scheme, the sampling that keys its draws, the spec mode and whether its rounds run alone. +pub const Plan = struct { + planned: u32, + width: u32, + kv_bits: u8, + repeats: bool, + seed: ?u64, + spec: Spec, + solo_rounds: bool, + + pub const Spec = enum(u8) { off, pld, drafter, mtp, dflash }; + + /// The plan with its company event undone: the part that must equal across fresh servers. + pub fn digest(p: Plan) u64 { + var h = std.hash.Fnv1a_64.init(); + h.update(std.mem.asBytes(&p.planned)); + h.update(std.mem.asBytes(&p.kv_bits)); + h.update(std.mem.asBytes(&p.repeats)); + const seed: u64 = p.seed orelse 0; + const seeded: u8 = @intFromBool(p.seed != null); + const spec: u8 = @intFromEnum(p.spec); + h.update(std.mem.asBytes(&seed)); + h.update(std.mem.asBytes(&seeded)); + h.update(std.mem.asBytes(&spec)); + h.update(std.mem.asBytes(&p.solo_rounds)); + return h.final(); + } +}; + +/// The `[repro]` line: `inputs= plan=`, then a company event where another request moved +/// the width. +pub fn line(buf: []u8, inputs: u64, plan: Plan) []const u8 { + var w = std.Io.Writer.fixed(buf); + w.print("[repro] inputs={x:0>16} plan={x:0>16} width={d}", .{ inputs, plan.digest(), plan.planned }) catch return w.buffered(); + if (plan.width != plan.planned) w.print(" company=width:{d}", .{plan.width}) catch {}; + return w.buffered(); +} + +pub fn logLine(inputs: u64, plan: Plan) void { + var buf: [160]u8 = undefined; + log.info("{s}\n", .{line(&buf, inputs, plan)}); +} + +// ── tests ── + +const testing = std.testing; + +// Bar: equal plans print equal digests; a decision that changes numerics (width, KV, seed, spec, rounds) changes the +// digest, and another request narrowing the width is a company event that leaves it. +test "repro: the plan digest follows the request's numerics, never its company" { + const base = Plan{ .planned = 8192, .width = 8192, .kv_bits = 16, .repeats = true, .seed = 7, .spec = .off, .solo_rounds = false }; + try testing.expectEqual(base.digest(), (Plan{ .planned = 8192, .width = 8192, .kv_bits = 16, .repeats = true, .seed = 7, .spec = .off, .solo_rounds = false }).digest()); + var narrowed = base; + narrowed.width = 2048; + try testing.expectEqual(base.digest(), narrowed.digest()); + for ([_]Plan{ + .{ .planned = 4096, .width = 4096, .kv_bits = 16, .repeats = true, .seed = 7, .spec = .off, .solo_rounds = false }, + .{ .planned = 8192, .width = 8192, .kv_bits = 8, .repeats = true, .seed = 7, .spec = .off, .solo_rounds = false }, + .{ .planned = 8192, .width = 8192, .kv_bits = 16, .repeats = true, .seed = 8, .spec = .off, .solo_rounds = false }, + .{ .planned = 8192, .width = 8192, .kv_bits = 16, .repeats = true, .seed = null, .spec = .off, .solo_rounds = false }, + .{ .planned = 8192, .width = 8192, .kv_bits = 16, .repeats = true, .seed = 7, .spec = .dflash, .solo_rounds = false }, + .{ .planned = 8192, .width = 8192, .kv_bits = 16, .repeats = true, .seed = 7, .spec = .off, .solo_rounds = true }, + }) |other| try testing.expect(other.digest() != base.digest()); + + var buf: [160]u8 = undefined; + try testing.expect(std.mem.indexOf(u8, line(&buf, 0xab, base), "company") == null); + try testing.expect(std.mem.endsWith(u8, line(&buf, 0xab, narrowed), " width=8192 company=width:2048")); +} diff --git a/src/engines/mlx/runtime/preflight.zig b/src/engines/mlx/runtime/preflight.zig index 4c7849f082..ad4cb93a24 100644 --- a/src/engines/mlx/runtime/preflight.zig +++ b/src/engines/mlx/runtime/preflight.zig @@ -148,7 +148,7 @@ fn shardResidentBytes(allocator: std.mem.Allocator, io: std.Io, model_dir: []con } const b = config.plugin orelse return shards; const f = b.table.weights.resident_bytes orelse return shards; - var settings: [128]u8 = undefined; + var settings: [256]u8 = undefined; var out = shards; const v = f(&b.parsed, .of(model_dir), .of(plugin_driver.loadSettings(&settings, config)), shards, &out); if (!v.isOk()) { @@ -158,6 +158,30 @@ fn shardResidentBytes(allocator: std.mem.Allocator, io: std.Io, model_dir: []con return out; } +/// The weight bill of a load that declines its plugin's accelerators, which `billed` holds and which do not fit: its +/// `resident_bytes` under `"accel":false` (`config.accel_declined`), logged by name. Null, nothing declined, where +/// the plugin bills no less without them: the caller keeps `billed`. +pub fn declineAccel(allocator: std.mem.Allocator, io: std.Io, model_dir: []const u8, config: *model_mod.ModelConfig, billed: u64) !?u64 { + const b = config.plugin orelse return null; + if (config.accel_declined or b.table.weights.resident_bytes == null) return null; + config.accel_declined = true; + const lean = residentModelDiskBytes(allocator, io, model_dir, config) catch |e| { + config.accel_declined = false; + return e; + }; + if (lean >= billed) { + config.accel_declined = false; + return null; + } + const gb = 1024.0 * 1024.0 * 1024.0; + log.warn("[preflight] {s}: its accelerators (~{d:.1} GB beside {d:.1} GB of weights) do not fit; declined, the load serves without them\n", .{ + b.table.name.slice(), + @as(f64, @floatFromInt(billed - lean)) / gb, + @as(f64, @floatFromInt(lean)) / gb, + }); + return lean; +} + pub fn ggufGateBytes(discovered: ?u64, disk_only: u64) ?u64 { return if (discovered) |bytes| bytes -| disk_only else null; } @@ -420,6 +444,64 @@ test "residentModelDiskBytes: a served pack is billed by its plugin's resident_b try std.testing.expectError(error.ResidentBytesRefused, residentModelDiskBytes(std.testing.allocator, io, dir, &config)); } +test "declineAccel: a plugin's resident_bytes bills its accelerators, and a load that declines them bills it without, logged by name" { + const T = struct { + fn accel(_: *const abi.Parsed, _: abi.Str, settings_json: abi.Str, shards: u64, out: *u64) callconv(.c) abi.Verdict { + out.* = if (std.mem.indexOf(u8, settings_json.slice(), "\"accel\":false") != null) shards else shards + 5; + return .ok; + } + fn none(_: *const abi.Parsed, _: abi.Str, _: abi.Str, shards: u64, out: *u64) callconv(.c) abi.Verdict { + out.* = shards; + return .ok; + } + }; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = "0123456789" }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(io, &buf)]; + const a = std.testing.allocator; + const hooks = [_]abi.WeightHooks{ .{ .resident_bytes = &T.accel }, .{ .resident_bytes = &T.none } }; + var tables: [2]abi.ModelTable = undefined; + for (&tables, &hooks) |*t, *h| + t.* = .{ .name = .of("fake_accel"), .claims = undefined, .parse = undefined, .free_parsed = undefined, .bill = undefined, .load = undefined, .unload = undefined, .forward = undefined, .cache = undefined, .weights = h }; + // The log beside, not in, the pack the bill scans. + var log_tmp = std.testing.tmpDir(.{}); + defer log_tmp.cleanup(); + var log_root: [std.fs.max_path_bytes]u8 = undefined; + var path_buf: [std.fs.max_path_bytes + 16]u8 = undefined; + try log.openFile(try std.fmt.bufPrint(&path_buf, "{s}/decline.log", .{log_root[0..try log_tmp.dir.realPath(io, &log_root)]}), 0); + defer log.closeFile(); + // Declared: billed with the pack (a load where it fits serves this bill), and without them once declined, the + // decline in the load settings. + var binding: @import("../plugin/config.zig").Binding = .{ .table = &tables[0] }; + var config: model_mod.ModelConfig = .{ .num_hidden_layers = 2, .hidden_size = 64, .plugin = &binding }; + const billed = try residentModelDiskBytes(a, io, dir, &config); + try std.testing.expectEqual(@as(u64, 15), billed); + try std.testing.expectEqual(@as(?u64, 10), try declineAccel(a, io, dir, &config, billed)); + try std.testing.expect(config.accel_declined); + try std.testing.expectEqual(@as(u64, 10), try residentModelDiskBytes(a, io, dir, &config)); + try std.testing.expectEqual(@as(?u64, null), try declineAccel(a, io, dir, &config, billed)); + // None declared, or no hook: the bill is the pack's, and nothing is declined. + var plain: @import("../plugin/config.zig").Binding = .{ .table = &tables[1] }; + config = .{ .num_hidden_layers = 2, .hidden_size = 64, .plugin = &plain }; + try std.testing.expectEqual(@as(u64, 10), try residentModelDiskBytes(a, io, dir, &config)); + try std.testing.expectEqual(@as(?u64, null), try declineAccel(a, io, dir, &config, 10)); + try std.testing.expect(!config.accel_declined); + const bare: abi.ModelTable = .{ .name = .of("t"), .claims = undefined, .parse = undefined, .free_parsed = undefined, .bill = undefined, .load = undefined, .unload = undefined, .forward = undefined, .cache = undefined, .weights = &.{} }; + var hookless: @import("../plugin/config.zig").Binding = .{ .table = &bare }; + config = .{ .num_hidden_layers = 2, .hidden_size = 64, .plugin = &hookless }; + try std.testing.expectEqual(@as(?u64, null), try declineAccel(a, io, dir, &config, 10)); + try std.testing.expect(!config.accel_declined); + // One decline line, naming the plugin; the loads that declined nothing logged none. + log.closeFile(); + const text = try log_tmp.dir.readFileAlloc(io, "decline.log", a, .limited(4096)); + defer a.free(text); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "do not fit; declined, the load serves without them")); + try std.testing.expect(std.mem.indexOf(u8, text, "[preflight] fake_accel: its accelerators") != null); +} + test "modelDiskBytes follows HF-cache symlinks (a snapshot dir measured ZERO)" { // A model served straight out of the HuggingFace hub cache is a snapshot // dir of SYMLINKS into ../../blobs. Skipping .sym_link entries measured a diff --git a/src/engines/mlx/scheduler.zig b/src/engines/mlx/scheduler.zig index 231e440736..f54422ef39 100644 --- a/src/engines/mlx/scheduler.zig +++ b/src/engines/mlx/scheduler.zig @@ -139,6 +139,7 @@ const mlxActiveBytes = @import("runtime/preflight.zig").mlxActiveBytes; const pleTableBill = @import("runtime/preflight.zig").pleTableBill; const residentModelDiskBytes = @import("runtime/preflight.zig").residentModelDiskBytes; const residentGateBytes = @import("runtime/preflight.zig").residentGateBytes; +const declineAccel = @import("runtime/preflight.zig").declineAccel; const ggufGateBytes = @import("runtime/preflight.zig").ggufGateBytes; pub const loadRequirementBytes = @import("runtime/preflight.zig").loadRequirementBytes; @@ -159,6 +160,7 @@ test { _ = @import("slot.zig"); _ = @import("spec/dflash_gate.zig"); _ = @import("spec/mtp_groups.zig"); + _ = @import("spec/native_group.zig"); _ = @import("spec/wiring.zig"); _ = @import("step.zig"); _ = @import("loop_stop.zig"); @@ -879,7 +881,11 @@ fn ensureLoadedOnce(self: *Scheduler, id_or_empty: []const u8) !*LoadedModel { else null; const discovered_bytes = if (owned.gguf) |g| ggufGateBytes(entry.bytes_on_disk, g.disk_only_bytes) else entry.bytes_on_disk; - const resident_model_bytes = residentGateBytes(validated_model_bytes, discovered_bytes, mlx_text); + var resident_model_bytes = residentGateBytes(validated_model_bytes, discovered_bytes, mlx_text); + // A plugin's accelerators that alone break the resident cap are declined, not the load (`declineAccel`). + if (validated_model_bytes) |billed| if (loadExceedsMemCap(gateEstimateBytes(0, billed, owned.config.num_hidden_layers, owned.config.hidden_size) + pleTableBill(self.io, owned.config), self.registry.max_resident_mem)) { + if (declineAccel(self.allocator, self.io, entry.path, owned.config, billed) catch null) |lean| resident_model_bytes = lean; + }; // A Neural Engine load holds int8 copies of the pack's 4- to 8-bit weights, and its KV. const ane_bytes: ?u64 = if (mlx_text and engines_served.aneWanted(owned.config, self.ane)) engines_load.aneBytes(self.allocator, entry.path, self.ane_slots) diff --git a/src/engines/mlx/spec/dspark.zig b/src/engines/mlx/spec/dspark.zig index cbfd177cdd..90a8c2ff11 100644 --- a/src/engines/mlx/spec/dspark.zig +++ b/src/engines/mlx/spec/dspark.zig @@ -148,6 +148,7 @@ pub fn keepLadder(self: *Generator) void { const t = if (self.dspark_pol) |*pol| (if (pol.timing) |*x| x else return) else return; const l = t.ladder() orelse return log.warn("[rounds] the round timing did not finish; the drafter stays off\n", .{}); self.xfm.plugin.?.ladder = l; + @import("ladder_store.zig").keep(self.timer.io, self.xfm.plugin.?, &l); var copies: [160]u8 = undefined; var drafts: [160]u8 = undefined; log.info("[rounds] plain step {d:.1} ms; a round by its drafts: copied {s}; drafted {s}\n", .{ l.plain, joinMs(&copies, &l.copies), joinMs(&drafts, l.drafts[0 .. l.block + 1]) }); diff --git a/src/engines/mlx/spec/ladder_store.zig b/src/engines/mlx/spec/ladder_store.zig new file mode 100644 index 0000000000..5b4e1ac0ba --- /dev/null +++ b/src/engines/mlx/spec/ladder_store.zig @@ -0,0 +1,203 @@ +//! A served drafter's round ladder (`rounds.Ladder`), stored once per release: the first boot times it and stores it, +//! later boots read it, so every boot of one build verifies the same draft counts. The key is the build (its id covers +//! the executable or release and the MLX build), the chip, the RAM, the model and the server's `MLX_` settings, bar the +//! diagnostics and `MLX_SERVE_ROUNDS_LADDER` itself. `MLX_SERVE_ROUNDS_LADDER` names the folder; `=0` stores nothing. + +const std = @import("std"); +const builtin = @import("builtin"); +const env = @import("../../../env.zig"); +const log = @import("../../../sdk/util/log.zig"); +const rounds = @import("../../../sdk/spec/rounds.zig"); + +const Ladder = rounds.Ladder; +const MAX_ROWS = rounds.MAX_ROWS; + +/// What a ladder depends on. +pub const Parts = struct { build: []const u8, chip: []const u8, mem_bytes: u64, model_dir: []const u8, levers: [32]u8 }; + +/// The server's `MLX_` settings as one digest, in any order, bar the diagnostics and the folder variable. +pub fn levers() [32]u8 { + var acc: [32]u8 = @splat(0); + if (comptime builtin.os.tag == .windows) return acc; // no C `environ` to walk; drafters serve on Metal + var i: usize = 0; + while (std.c.environ[i]) |e| : (i += 1) { + const entry = std.mem.span(e); + if (!std.mem.startsWith(u8, entry, "MLX_")) continue; + if (std.mem.indexOf(u8, entry, "DIAG") != null or std.mem.startsWith(u8, entry, "MLX_SERVE_ROUNDS_LADDER=")) continue; + var d: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(entry, &d, .{}); + for (&acc, d) |*x, y| x.* ^= y; + } + return acc; +} + +/// The key's id: 24 hex digits of the sha256 of its parts. +pub fn keyId(p: Parts) [24]u8 { + var h = std.crypto.hash.sha2.Sha256.init(.{}); + for ([_][]const u8{ p.build, p.chip, p.model_dir }) |part| { + h.update(part); + h.update("\x00"); + } + h.update(std.mem.asBytes(&((p.mem_bytes + (1 << 29)) >> 30))); + h.update(&p.levers); + var d: [32]u8 = undefined; + h.final(&d); + return std.fmt.bytesToHex(d[0..12].*, .lower); +} + +/// `ladder1`, then `plain`, `block`, and the `copies` and `drafts` rows, ms with 4 decimals. +pub fn encode(buf: []u8, l: *const Ladder) ![]const u8 { + var w = std.Io.Writer.fixed(buf); + try w.print("ladder1\nplain {d:.4}\nblock {d}\n", .{ l.plain, l.block }); + for ([_][]const u8{ "copies", "drafts" }, [_]*const [MAX_ROWS]f32{ &l.copies, &l.drafts }) |name, row| { + try w.writeAll(name); + for (row) |ms| try w.print(" {d:.4}", .{ms}); + try w.writeByte('\n'); + } + return w.buffered(); +} + +/// Null on any other version or shape, and on a cost a timed ladder cannot hold. +pub fn decode(text: []const u8) ?Ladder { + var lines = std.mem.splitScalar(u8, text, '\n'); + if (!std.mem.eql(u8, lines.next() orelse return null, "ladder1")) return null; + var l: Ladder = .{ .plain = 0, .copies = undefined, .drafts = undefined, .block = 0 }; + const plain = lines.next() orelse return null; + if (!std.mem.startsWith(u8, plain, "plain ")) return null; + l.plain = std.fmt.parseFloat(f32, plain[6..]) catch return null; + const block = lines.next() orelse return null; + if (!std.mem.startsWith(u8, block, "block ")) return null; + l.block = std.fmt.parseInt(u32, block[6..], 10) catch return null; + if (l.block == 0 or l.block > rounds.MAX_DRAFTS) return null; + for ([_][]const u8{ "copies", "drafts" }, [_]*[MAX_ROWS]f32{ &l.copies, &l.drafts }) |name, row| { + var f = std.mem.splitScalar(u8, lines.next() orelse return null, ' '); + if (!std.mem.eql(u8, f.next() orelse return null, name)) return null; + for (row) |*ms| ms.* = std.fmt.parseFloat(f32, f.next() orelse return null) catch return null; + if (f.next() != null) return null; + } + if (!std.math.isFinite(l.plain) or l.plain <= 0) return null; + for ([_]f32{l.drafts[0]} ++ l.copies) |ms| if (!std.math.isFinite(ms) or ms <= 0) return null; + for (l.drafts[1 .. l.block + 1]) |ms| if (!std.math.isFinite(ms) or ms <= 0) return null; + return l; +} + +/// The folder: the variable's value, else `~/.mlx-serve/rounds` (made when missing; none in a test build, which stays +/// hermetic); null at `0`. +pub fn dir(io: std.Io, buf: []u8) ?[]const u8 { + if (env.span(.MLX_SERVE_ROUNDS_LADDER)) |v| return if (v.len == 0 or v[0] == '0') null else v; + if (builtin.is_test) return null; + const home = std.mem.span(env.get(.HOME) orelse return null); + const d = std.fmt.bufPrint(buf, "{s}/.mlx-serve/rounds", .{home}) catch return null; + std.Io.Dir.cwd().createDirPath(io, d) catch return null; + return d; +} + +/// `/rounds-ladder-.txt`. +pub fn path(buf: []u8, folder: []const u8, id: []const u8) ?[]const u8 { + return std.fmt.bufPrint(buf, "{s}/rounds-ladder-{s}.txt", .{ folder, id }) catch null; +} + +/// The ladder stored at `p`; null when there is none or it does not parse. +pub fn read(io: std.Io, p: []const u8) ?Ladder { + const f = std.Io.Dir.openFileAbsolute(io, p, .{}) catch return null; + defer f.close(io); + var rb: [1024]u8 = undefined; + var rs = f.reader(io, &rb); + var text: [2048]u8 = undefined; + const n = rs.interface.readSliceShort(&text) catch return null; + return decode(std.mem.trimEnd(u8, text[0..n], "\n")); +} + +/// Writes `l` to `p` through a temporary file, so a reader never sees half of one. +pub fn store(io: std.Io, p: []const u8, l: *const Ladder) !void { + var body: [2048]u8 = undefined; + const text = try encode(&body, l); + var tmp_buf: [600]u8 = undefined; + const tmp = try std.fmt.bufPrint(&tmp_buf, "{s}.tmp", .{p}); + { + const f = try std.Io.Dir.createFileAbsolute(io, tmp, .{}); + defer f.close(io); + var wb: [2048]u8 = undefined; + var fw = f.writer(io, &wb); + try fw.interface.writeAll(text); + try fw.interface.flush(); + } + try std.Io.Dir.renameAbsolute(tmp, p, io); +} + +/// At load: the stored ladder of `parts` into `b.ladder` (then nothing times it), else its path kept in `b` for +/// `keep`. Logs `[rounds] ladder read` or `[rounds] ladder: none stored`. +pub fn restore(io: std.Io, b: anytype, parts: Parts) void { + var dir_buf: [512]u8 = undefined; + const folder = dir(io, &dir_buf) orelse return; + const id = keyId(parts); + const p = path(&b.ladder_file, folder, &id) orelse return; + b.ladder_file_len = p.len; + if (read(io, p)) |l| { + b.ladder = l; + b.ladder_asked = true; + log.info("[rounds] ladder read: {s} (plain step {d:.1} ms, {d} drafts)\n", .{ p, l.plain, l.block }); + } else log.info("[rounds] ladder: none stored at {s}; the load times it\n", .{p}); +} + +/// After the timing request: `l` stored where `restore` named, for every later boot of this key. +pub fn keep(io: std.Io, b: anytype, l: *const Ladder) void { + if (b.ladder_file_len == 0) return; + const p = b.ladder_file[0..b.ladder_file_len]; + store(io, p, l) catch |e| return log.warn("[rounds] ladder not stored ({s}) at {s}\n", .{ @errorName(e), p }); + log.info("[rounds] ladder stored: {s}\n", .{p}); +} + +const testing = std.testing; + +fn testLadder() Ladder { + var l: Ladder = .{ .plain = 12.5, .copies = undefined, .drafts = undefined, .block = 6 }; + for (&l.copies, &l.drafts, 0..) |*c, *d, k| { + c.* = 13.0 + 1.25 * @as(f32, @floatFromInt(k)); + d.* = 14.0 + 1.5 * @as(f32, @floatFromInt(k)); + } + return l; +} + +// Bar: a ladder is stored once and read back to the stored values; another key (a lever, the build, the model) is a +// miss, and a later store under the first key leaves the other key's file absent. +test "ladder store: a timed ladder is stored once, read back, and a key change misses" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var root_buf: [512]u8 = undefined; + const root = root_buf[0..try tmp.dir.realPath(testing.io, &root_buf)]; + const base: Parts = .{ .build = "dev 0123456789abcdef", .chip = "Apple M5 Max", .mem_bytes = 128 << 30, .model_dir = "/models/inkling2", .levers = @splat(0) }; + const l = testLadder(); + var p_buf: [600]u8 = undefined; + const id = keyId(base); + const p = path(&p_buf, root, &id).?; + try testing.expect(read(testing.io, p) == null); + try store(testing.io, p, &l); + const got = read(testing.io, p).?; + try testing.expectEqual(l.plain, got.plain); + try testing.expectEqual(l.block, got.block); + for (l.copies, got.copies) |x, y| try testing.expectApproxEqAbs(x, y, 1e-4); + for (l.drafts, got.drafts) |x, y| try testing.expectApproxEqAbs(x, y, 1e-4); + var lever = base; + lever.levers[0] = 1; + var build = base; + build.build = "dev fedcba9876543210"; + var model = base; + model.model_dir = "/models/other"; + for ([_]Parts{ lever, build, model }) |other| { + const oid = keyId(other); + try testing.expect(!std.mem.eql(u8, &oid, &id)); + var o_buf: [600]u8 = undefined; + try testing.expect(read(testing.io, path(&o_buf, root, &oid).?) == null); + } +} + +test "ladder store: a malformed or untimed file is a miss" { + var buf: [2048]u8 = undefined; + var l = testLadder(); + const text = try encode(&buf, &l); + try testing.expect(decode(text[0 .. text.len - 1]) != null); + try testing.expect(decode("ladder0\nplain 1\n") == null); + l.drafts[2] = std.math.inf(f32); + try testing.expect(decode(try encode(&buf, &l)) == null); +} diff --git a/src/engines/mlx/spec/native_group.zig b/src/engines/mlx/spec/native_group.zig index 9bb99d856a..706c98811c 100644 --- a/src/engines/mlx/spec/native_group.zig +++ b/src/engines/mlx/spec/native_group.zig @@ -1,6 +1,7 @@ //! Rounds of a served drafter (a plugin's `NativeDrafter`) for several slots of one model at once: each slot drafts and //! opens its verify, every accept starts on the GPU together, and each slot then keeps its accepted prefix (a sampled slot -//! accepts under its own sampling, a greedy one against the trunk's picks). A slot alone, or one whose next round is not a group's, ticks solo. +//! accepts under its own sampling, a greedy one against the trunk's picks). A slot alone, or one whose next round is not a +//! group's, ticks solo; so does a request that must answer the same twice (`roundsAlone`), at any load. const std = @import("std"); const env = @import("../../../env.zig"); @@ -17,18 +18,41 @@ const runSingleDecodeTick = @import("../decode.zig").runSingleDecodeTick; const loopGuardTick = @import("../loop_stop.zig").loopGuardTick; const publishSpeculativeBlock = @import("wiring.zig").publishSpeculativeBlock; const slotSpecMode = @import("wiring.zig").slotSpecMode; +const SamplingParams = @import("../sampling/params.zig").SamplingParams; /// Slots one group round carries: the plugin keeps a verify open for each. pub const MAX_SLOTS: usize = plugin_driver.max_native_group; -/// Whether `slot` ticks rounds of a served drafter that keeps a verify open a slot. -pub fn slotGroupable(slot: *const Slot) bool { +/// Whether a request rounds alone beside any company (`MLX_SERVE_GREEDY_SOLO_ROUNDS`): one that must answer the same +/// twice (`SamplingParams.repeats`). A group's forward carries every slot's rows, and its kernels, tiles, splits and +/// tree widths follow the group, so a near-tie token would follow who else was served and in what order. +pub fn roundsAlone(sampling: SamplingParams) bool { + // Read once a process (every decode tick asks it a slot); a test build reads it at every call, so a test can flip it. + const solo = if (@import("builtin").is_test) env.on(.MLX_SERVE_GREEDY_SOLO_ROUNDS) else env.onCached(&solo_rounds_env_cached, .MLX_SERVE_GREEDY_SOLO_ROUNDS); + return solo and sampling.repeats(); +} + +var solo_rounds_env_cached: ?bool = null; + +/// Whether `slot` ticks rounds of a served drafter whose slots group (`MLX_SERVE_NATIVE_GROUPS`). +fn groupedRounds(slot: *const Slot) bool { if (!env.notOff(.MLX_SERVE_NATIVE_GROUPS)) return false; const gen = if (slot.legacy_gen) |*g| g else return false; if (gen.spec_disabled_runtime or slotSpecMode(slot, gen) != .dspark) return false; return plugin_driver.nativeGroups(slot.model.transformer orelse return false); } +/// Whether `slot` joins its model's group rounds. +pub fn slotGroupable(slot: *const Slot) bool { + return groupedRounds(slot) and !roundsAlone(slot.legacy_gen.?.sampling); +} + +/// Whether `slot`'s every forward carries its own rows only, whatever its company (`roundsAlone`): it joins no group +/// round, never yields its rounds to the batched decode, and is no other slot's company. +pub fn slotAlone(slot: *const Slot) bool { + return groupedRounds(slot) and roundsAlone(slot.legacy_gen.?.sampling); +} + /// The decode tick's grouped slots: one group round per model, `MAX_SLOTS` slots at a time; a slot alone ticks solo. pub fn runNativeGroups(sch: *Scheduler, slots: []*Slot) !void { std.sort.pdq(*Slot, slots, {}, struct { @@ -93,3 +117,21 @@ fn runGroupTickInner(sch: *Scheduler, group: []*Slot) !void { publishSpeculativeBlock(sch, slot, gen, r.tokens); } } + +// Bar: by default every request groups; with MLX_SERVE_GREEDY_SOLO_ROUNDS=1 a greedy or seeded request rounds alone +// beside any company and an unseeded sampled one still groups. +test "roundsAlone: with the switch on, a request that must answer the same twice never shares a forward" { + const greedy: SamplingParams = .{ .temperature = 0.0 }; + const top1: SamplingParams = .{ .temperature = 0.8, .top_k = 1 }; + const seeded: SamplingParams = .{ .temperature = 0.8, .seed = 7 }; + const sampled: SamplingParams = .{ .temperature = 0.8 }; + { + const unset = env.override(.MLX_SERVE_GREEDY_SOLO_ROUNDS, null); + defer unset.restore(); + for ([_]SamplingParams{ greedy, top1, seeded, sampled }) |sp| try std.testing.expect(!roundsAlone(sp)); + } + const on = env.override(.MLX_SERVE_GREEDY_SOLO_ROUNDS, "1"); + defer on.restore(); + for ([_]SamplingParams{ greedy, top1, seeded }) |sp| try std.testing.expect(roundsAlone(sp)); + try std.testing.expect(!roundsAlone(sampled)); +} diff --git a/src/engines/mlx/warm_requests.zig b/src/engines/mlx/warm_requests.zig index 22aaba29f0..6a82fd4b27 100644 --- a/src/engines/mlx/warm_requests.zig +++ b/src/engines/mlx/warm_requests.zig @@ -229,6 +229,35 @@ pub fn timeRounds(sch: *Scheduler, entry: *LoadedModel) void { log.warn("Timing the drafter's rounds failed ({s}); it stays off.\n", .{@errorName(err)}); } +/// The prompt a load serves when a stored ladder means nothing times its drafter's rounds (`ladder_store.restore`): +/// `ROUNDS`' context, ragged against the prompt kernels' 64-row and 32-key tiles, and one token. Served before ready, +/// so the first request finds the prompt path's pipelines and buffers made, and no request waits behind it. +const PROMPT_WARM: Request = .{ .base = 3, .len = ROUNDS.len + 3, .gen = 1 }; + +/// Whether the load serves `PROMPT_WARM`: a native drafter whose ladder was read (nothing times its rounds after +/// ready), a model that chats, and no `--warmup-full` (which serves its own prompts first). +pub fn promptWarmOwed(entry: *const LoadedModel, warmup_full: bool, chat: bool) bool { + const xfm = entry.transformer orelse return false; + return promptWarmFor(plugin_driver.nativeStages(xfm), if (xfm.plugin) |b| b.ladder_asked else false, warmup_full, chat); +} + +fn promptWarmFor(native_stages: u32, ladder_read: bool, warmup_full: bool, chat: bool) bool { + return native_stages > 0 and ladder_read and !warmup_full and chat; +} + +/// `PROMPT_WARM`, inside the load. +pub fn warmPrompt(sch: *Scheduler, entry: *LoadedModel) void { + const cfg = entry.config orelse return; + if (!holds(cfg, PROMPT_WARM)) return; + var twin = twinOf(entry); + defer if (twin) |*t| t.deinit(); + var buf: [PROMPT_WARM.len]u32 = undefined; + const sw = io_util.Stopwatch.init(sch.io); + serve(sch, entry, if (twin) |*t| t else null, fill(&buf, cfg.vocab_size, PROMPT_WARM), PROMPT_WARM) catch |err| + return log.warn("[warm] the load's prompt failed ({s}); the first request makes its pipelines\n", .{@errorName(err)}); + log.info("[warm] the load served one {d}-token prompt (a stored ladder: nothing times the rounds) in {d} ms\n", .{ PROMPT_WARM.len, sw.read() / std.time.ns_per_ms }); +} + /// An empty cache with the retention rules of the model's own, for its warm requests. fn twinOf(entry: *const LoadedModel) ?prefix_cache_mod.HotPrefixCache { var twin = (entry.prefix_cache orelse return null).ramTwin(); @@ -714,3 +743,13 @@ test "stop: a warm-up still owed at shutdown is dropped unmarked" { f.sch.warm_queue = .empty; try testing.expect(!served(f.marker)); } + +// Bar: the load serves its prompt warm only where a read ladder leaves nothing to time the rounds after ready. +test "warm requests: the load's prompt warm is owed only to a drafter whose ladder was read" { + try std.testing.expect(promptWarmFor(1, true, false, true)); + try std.testing.expect(!promptWarmFor(1, false, false, true)); + try std.testing.expect(!promptWarmFor(0, true, false, true)); + try std.testing.expect(!promptWarmFor(1, true, true, true)); + try std.testing.expect(!promptWarmFor(1, true, false, false)); + try std.testing.expect(PROMPT_WARM.len % 64 != 0 and PROMPT_WARM.len % 32 != 0 and PROMPT_WARM.len > ROUNDS.len); +} diff --git a/src/env.zig b/src/env.zig index 36c8ef0879..52397949d3 100644 --- a/src/env.zig +++ b/src/env.zig @@ -341,6 +341,9 @@ pub const vars = struct { pub const MLX_SERVE_MING_FUSED: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "plugins/ming_tts", .since = "26.11.3", .doc = "Ming-3.0-tts fused DiT and LM kernels (=0: the op chain)" }; pub const MLX_SERVE_MING_SYSTEM: Var = .{ .kind = .public, .type = .text, .default = "你是一个友好的AI助手。", .owner = "plugins/ming_image", .since = "unreleased", .doc = "Ming-Image's system-turn content in its chat template (unset: the release's line); empty drops the system turn, so the caption conditioning is steered by the prompt alone" }; pub const MLX_SERVE_INKLING2_FUSED: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "plugins/inkling2", .since = "26.11.4", .doc = "Inkling 2 one-row step kernels (=0: the op chain)" }; + pub const MLX_SERVE_INKLING2_MARKOV_Q8: Var = .{ .kind = .kill, .type = .flag, .default = "off", .owner = "plugins/inkling2", .since = "26.12.1", .doc = "Inkling 2 bundled drafter, opt-in for an A/B: the Markov chain\'s fold held as int8 a vocab row and its RNN\'s context made once a block (off: main\'s group-64 8-bit fold)" }; + pub const MLX_SERVE_INKLING2_PIPELINES_AT_LOAD: Var = .{ .kind = .kill, .type = .text, .default = "~/.mlx-serve/inkling2", .owner = "plugins/inkling2", .since = "26.12.1", .doc = "Inkling 2: a folder for this build, machine and composition's record of first kernel launches, replayed at load so their pipelines are built before ready; it takes first launches until the load is ready, and a launch then does no work for it (=0: none)" }; + pub const MLX_SERVE_INKLING2_TRUNK_Q8: Var = .{ .kind = .kill, .type = .flag, .default = "off", .owner = "plugins/inkling2", .since = "26.12.1", .doc = "Inkling 2 on Metal, opt-in (inexact): a dense trunk (attention and dynamic-conv projections, embedding, head) quantized at load to 8-bit affine, group 64, as tests/convert_inkling2.py --bits 8 stores it (off: the checkpoint's dense trunk)" }; pub const MLX_SERVE_INKLING2_TREE: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "plugins/inkling2", .since = "26.11.4", .doc = "Inkling 2 DFlash2 GPU draft tree and fused accept (=0: chain verify)" }; pub const MLX_SERVE_CUDA_QMV_TC: Var = .{ .kind = .kill, .type = .flag, .default = "on where measured (sm_120)", .owner = "sdk/blocks/qmm", .since = "26.10.3", .doc = "CUDA tensor-core 4-bit GEMV for 2..8 rows" }; pub const MLX_SERVE_DSV41_ATTN_F16: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "plugins/deepseek_v41", .since = "26.10.3", .doc = "DeepSeek-V4.1 f16 attention (=0: f32)" }; @@ -353,7 +356,9 @@ pub const vars = struct { pub const MLX_SERVE_GDN_STATE_F32: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "engines/mlx", .since = "26.10.2", .doc = "f32 GDN recurrent state (=0: bf16)" }; pub const MLX_SERVE_H3_RESIDENT: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "plugins/minimax_h3", .since = "26.10.2", .doc = "H3 DiT resident between requests" }; pub const MLX_SERVE_KV_ATTN_MMA: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "sdk/blocks/attention", .since = "26.11.3", .doc = "packed-KV decode attention on the simdgroup-matrix kernel (=0: the block kernel, or matmul2d on M4/M5 past 16K keys)" }; - pub const MLX_SERVE_NATIVE_GROUPS: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "engines/mlx/spec", .since = "26.11.4", .doc = "a served drafter's slots, sampled or greedy, run their rounds as one group tick (=0: they decode plain in the batched group)" }; + pub const MLX_SERVE_NATIVE_GROUPS: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "engines/mlx/spec", .since = "26.11.4", .doc = "a served drafter's slots run their rounds as one group tick (=0: they decode plain in the batched group)" }; + pub const MLX_SERVE_ROUNDS_LADDER: Var = .{ .kind = .kill, .type = .text, .default = "~/.mlx-serve/rounds", .owner = "engines/mlx/spec", .since = "26.12.1", .doc = "a served drafter's round ladder: a folder where the first boot of a build, machine, model and MLX_ composition stores the ladder it timed and later boots read it (=0: timed at every load)" }; + pub const MLX_SERVE_GREEDY_SOLO_ROUNDS: Var = .{ .kind = .kill, .type = .flag, .default = "off", .owner = "engines/mlx/spec", .since = "26.12.1", .doc = "a greedy or seeded request on a served drafter whose slots group runs its own rounds at any load: it joins no group round and never yields to the batched decode, so its text is the one it gets alone (=1; off: it groups with the others, and a near-tie token follows who else is served)" }; pub const MLX_SERVE_KEYED_SAMPLING: Var = .{ .kind = .kill, .type = .flag, .default = "off (keyed only where the decode is row-exact)", .owner = "engines/mlx/sampling", .since = "26.11.2", .doc = "every clean sampled request draws through the keyed sampler (Gumbel-max keyed by seed, position and id; an unseeded request gets a seed), and DSpark's stochastic arm keeps a draft only while it equals the keyed draw at its position (the serial verdict): a drafted request emits what serial decoding draws from the same rows' logits, at the same acceptance law" }; pub const MLX_SERVE_PREFIX_CACHE_PRESSURE: Var = .{ .kind = .kill, .type = .flag, .default = "on", .owner = "engines/mlx", .since = "unreleased", .doc = "a change in the macOS memory-pressure level re-clamps every hot-cache budget against free memory (=0: only a model load or unload does)" }; @@ -566,6 +571,7 @@ pub const vars = struct { pub const HY3_MODEL_DIR: Var = .{ .kind = .fixture, .type = .text, .default = "unset: the test skips", .owner = "host/chat", .since = "26.7.8", .doc = "renderChatTemplate: REAL Hy3 chat_template.jinja renders without fallback (HY3_MODEL_DIR)" }; pub const INKLING2_PACK: Var = .{ .kind = .fixture, .type = .text, .default = "unset: the test skips", .owner = "plugins/inkling2", .since = "26.11.3", .doc = "an Inkling 2 pack dir whose lm_head the last-row test reads" }; pub const INKLING2_RELEASE: Var = .{ .kind = .fixture, .type = .text, .default = "unset: the test skips", .owner = "plugins/inkling2", .since = "26.11.4", .doc = "the Inkling 2 Mini release's directory, for the tests that load it" }; + pub const INKLING2_Q8_REF: Var = .{ .kind = .fixture, .type = .text, .default = "unset: the test skips", .owner = "plugins/inkling2", .since = "26.12.1", .doc = "q8ref_conv.py's json: tests/convert_inkling2.py --bits 8's sha256 of every tensor it quantizes" }; pub const INKLING2_DFLASH2_PACK: Var = .{ .kind = .fixture, .type = .text, .default = "unset: the test skips", .owner = "plugins/inkling2", .since = "26.11.4", .doc = "the Inkling 2 Mini release's files with its DFlash2 draft as `drafter/`, for the tests that run them together" }; pub const INKLING2_DFLASH2_DIR: Var = .{ .kind = .fixture, .type = .text, .default = "unset: the test skips", .owner = "plugins/inkling2", .since = "26.11.4", .doc = "incoai/Inkling-2-Mini-DFlash2's directory, for the DFlash2 parity test" }; pub const INKLING2_DFLASH2_FIXTURES: Var = .{ .kind = .fixture, .type = .text, .default = "unset: the test skips", .owner = "plugins/inkling2", .since = "26.11.4", .doc = "tests/dump_inkling2_dflash2_fixtures.py's output (the reference's block rows and selector path)" }; diff --git a/src/kernels/digests.txt b/src/kernels/digests.txt index d64a3a4dcb..24afac211e 100644 --- a/src/kernels/digests.txt +++ b/src/kernels/digests.txt @@ -83,8 +83,8 @@ f8bc2a6506e2654ca1babb98d0662de5ef2ed0e2767a205c1442b8a438234a92 kernels/mlp/ta c8364e8f0196b1735c19c00a052bf7c9ece2e65eb170d5f56314f79ef11f9c09 kernels/moe/down_reduce_rows.fmt.metal a2c91f316bb90334cdbf12c47dbd5499386b93f34b9d533bc56ea2444a29af10 kernels/moe/down_reduce.fmt.metal ee9ae0bb2fb65c455de32c6294284a856f972d4c620ced31067e4763a052a9ef kernels/moe/gather_qmm_nax_header.metal -3772ecbbfa865184ade0cd973c4708a0c13f5d5b72ef913aaf0719cd1e6f2e93 kernels/moe/gather_qmm_nax_mapped_header.metal -55e616af0c22eb6b41e6598615f0ed3e5dd16f70a5330a3dd0359c921683722c kernels/moe/gather_qmm_nax_mapped.metal +989217c20fb700631f7c4e4332846226fbd3616463c768eb1c5b5d48ecdf9970 kernels/moe/gather_qmm_nax_mapped_header.metal +2e7b2d4cd69cf670f8f178112ec1bd9886ed46490270a37e58e784cb19fe8d9d kernels/moe/gather_qmm_nax_mapped.metal d95f226a1115256c06713fd3138bb5f85501cc4e44d9b19f6717c065e125e6f8 kernels/moe/gather_qmm_nax_scan.metal 1787cf197d9465f12b4b56a17bdac56455595396701e867f1cca520d810d6bc8 kernels/moe/gather_qmm_nax.metal 722581bad6bd1d9239060acf85a5cb4fc2ba39b70418b13126e74c74fa987171 kernels/moe/gather_qmv_gateup_rows.fmt.metal @@ -446,23 +446,29 @@ d340bf595d35b819c07c5f827c3e03e5847e1fa1d45adb6aa347be63465ead42 plugins/inklin 8e964d450df1991360373e86752c52d0f88989be10ab5b795dce99ccb5a4eadd plugins/inkling2/kernels/downs_grp.metal 099369804260287debb2415b64105c0b85dac5452200943dc0ab0d4deee00a16 plugins/inkling2/kernels/few_tail.metal f6a0ce8979d48492fd89c32e1b78a54db7d1f65995f747013341fbe573880f1f plugins/inkling2/kernels/gate.metal +7f8bc7649b40ab6f91fcd11fccf2acd4743210c609b5eb53c88b945f8e7e6fd3 plugins/inkling2/kernels/gate_mm.metal b813e4997878fb911c9784ef85ff4a6a4270570727acb4ff82ad0592319bb94f plugins/inkling2/kernels/gated.metal 1507d55c12cbc401e7b4c64442d6515b1fb4d0b44a58f0d1c9a42a133709b45f plugins/inkling2/kernels/group.metal eb52fb42c7564389f231e45fec92398b407041e7434681028b54d9da4df2aca3 plugins/inkling2/kernels/markov_fold.metal d267cf57ab8e41fe7d7c70ad91e5b9d9d3e1e812061feb00bdb50ffd188c0da9 plugins/inkling2/kernels/markov_fold_batch.metal 004d8e907919152f91a9d860d032a1a76675b7c095654f65449a606ab06fa5f6 plugins/inkling2/kernels/markov_fold_q8.metal +9bfb7d9e0997b6555829cf32529d3ecc37ec7b659b71822180de89aeff664b37 plugins/inkling2/kernels/markov_fold_q8_row.metal a9ffc63259e4b0f74872b0a4437e4dcb574dfddd0356e478b5e95327973cb21c plugins/inkling2/kernels/markov_header.metal 78db75ade5a823d01205f9780330016acf2629dad9f661329568d68cde25a20d plugins/inkling2/kernels/markov_pick.metal 4cc89a12b1d762bdc8a470f5670d925e983b2360e13a76636b2494d523e0e312 plugins/inkling2/kernels/markov_pick_batch.metal 55fa72ecd9d992e3630f81376436ac3dd87b06ddfb07db198f8b80d44efee508 plugins/inkling2/kernels/markov_pick_rnn.metal e06283a27a4a035a7fc24241a356145fec64093d563c0ea44e7bc9d6665176a9 plugins/inkling2/kernels/markov_pick_sample.metal 9dd8321add7c4eafd99fe9452a2fa4d70c3fcc9cf5ff31d5221e401555b23305 plugins/inkling2/kernels/markov_rnn.metal +ba67b3a7a703d7946bc63bf71d897ada95e0f4070983215e3ee5620e8ed3fac3 plugins/inkling2/kernels/markov_step_rnn.metal b4477a5e1a1912d0ef185510727f8a26ad3bb2ec2532078f0e8d579266452b13 plugins/inkling2/kernels/mid.metal 89076659ed7250332b24c5193684b3d114c416ed023de500559ca6cc2622e9cf plugins/inkling2/kernels/moe_wide.metal 6ed771a281a25bb68a473df5be39604b2c49fd1fb1bd18d4bda3b498086a7ee3 plugins/inkling2/kernels/oproj.metal -f30720dc9d360357d41ad8a231ff997e1b38b00ef69abd2009879354e48c64ab plugins/inkling2/kernels/norm.metal +671b9fe3a8dbe7d9fbfe1f7f347acda25a8702b3362f94f359809bf290b6ce3b plugins/inkling2/kernels/norm.metal +f30720dc9d360357d41ad8a231ff997e1b38b00ef69abd2009879354e48c64ab plugins/inkling2/kernels/norm_step.metal 996c0eb43fc24f851cbe5c1bd08dc853a6791024d9ec15efc8a753a916e8a237 plugins/inkling2/kernels/pre.metal -daf24737c9afd550e108119e946cd15df7182adfa7d858cd267eace4cd510624 plugins/inkling2/kernels/prep.metal +d047e45552223eb5f924818258cf43a4de30308a5aee31170da890d9fbd06602 plugins/inkling2/kernels/prep.metal +daf24737c9afd550e108119e946cd15df7182adfa7d858cd267eace4cd510624 plugins/inkling2/kernels/prep_step.metal +a1d2f9ed16400e7da0736a63b1519da64775194973f283d9b39904e2289d60db plugins/inkling2/kernels/relative_attention_nax.metal 020c05082442ad134a0d7e58d137eb63a709c3d1d95a5be2c16fdf21d62b48d9 plugins/inkling2/kernels/relattn.metal 392e291b02a3abd9a85d9bee531d702c980662c1317ff0650b997d644f96026d plugins/inkling2/kernels/relattn_nax.metal f799adf545df1485716284efaf87eb8380843cb5a8a7912096d7f979f9f0d2ca plugins/inkling2/kernels/relcomb.metal diff --git a/src/kernels/moe/gather_qmm_nax_mapped.metal b/src/kernels/moe/gather_qmm_nax_mapped.metal index f21e1f5b80..5633170622 100644 --- a/src/kernels/moe/gather_qmm_nax_mapped.metal +++ b/src/kernels/moe/gather_qmm_nax_mapped.metal @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // Ported from oMLX (jundot/omlx) omlx/patches/m5_gather_qmm_nax.py @ d6b2b92. +// sigtab: the paired epilogue's bf16 sigmoid table, or EPI < 0's f32 caps and scales (store_il reads it as f32). using Q = metal::conditional_t, omlx_gqmm::AffineQ>; using G = omlx_gqmm::Geo; using WT = typename Q::WT; @@ -13,10 +14,10 @@ Q uq{up_scales, up_biases}; if constexpr (SCHED == 1) { omlx_gqmm::gather_mapped_db(x, rmap, (const device uint8_t*)w, (const device uint8_t*)up_w, q, uq, desc, y_col, y, params[0], params[1], - Ws, simdgroup_index_in_threadgroup, thread_index_in_simdgroup, sigtab, row_wt, params[2]); + Ws, simdgroup_index_in_threadgroup, thread_index_in_simdgroup, (const device T*)sigtab, row_wt, params[2]); } else { omlx_gqmm::gather_mapped_seg(x, rmap, (const device uint8_t*)w, (const device uint8_t*)up_w, q, uq, desc, y_col, y, params[0], params[1], Ws, simdgroup_index_in_threadgroup, - thread_index_in_simdgroup, sigtab, row_wt, params[2]); + thread_index_in_simdgroup, (const device T*)sigtab, row_wt, params[2]); } diff --git a/src/kernels/moe/gather_qmm_nax_mapped_header.metal b/src/kernels/moe/gather_qmm_nax_mapped_header.metal index a5238de95c..81e5483712 100644 --- a/src/kernels/moe/gather_qmm_nax_mapped_header.metal +++ b/src/kernels/moe/gather_qmm_nax_mapped_header.metal @@ -110,6 +110,10 @@ METAL_FUNC void store_act(thread DTile& D, device T* y, const int ld, const int rows, const device T* sigtab, const device float* row_wt); +template +METAL_FUNC void store_il(thread DTile& D, device T* y, const int ld, + const int rows, const device T* aux, const uint expert); + template < typename T, typename Q, @@ -138,8 +142,10 @@ METAL_FUNC void gather_mapped_seg( const device float* row_wt = nullptr, const int up_off = 0) { using WT = typename Q::WT; - constexpr bool kPair = EPI != 0; - static_assert(!kPair || ALIGN_N, "paired gate/up tiles are full"); + constexpr bool kPair = EPI > 0; + // EPI < 0: one bank's gate (even) and up (odd) rows, tiled as one product; the epilogue pairs adjacent columns. + constexpr bool kIL = EPI < 0; + static_assert(!(kPair || kIL) || ALIGN_N, "paired gate/up tiles are full"); constexpr int BKP = G::kBK + 16 / sizeof(WT); const int row_start = int(desc.x); const uint32_t expert = desc.y; @@ -152,7 +158,7 @@ METAL_FUNC void gather_mapped_seg( const int k_remain = K - K_it * G::kBK; const int half_n = N / 2; const int w_col = kPair ? y_col / 2 : y_col; - const int ldy = kPair ? half_n : N; + const int ldy = kPair || kIL ? half_n : N; // `up_off`: a gate/up bank fused along its rows (gate rows then up rows an expert) passes the up rows' offset. const size_t w_row = size_t(expert) * (kPair ? half_n + up_off : N) + w_col; @@ -166,7 +172,7 @@ METAL_FUNC void gather_mapped_seg( if constexpr (!MAP) { x += size_t(row_start) * K; } - y += size_t(row_start) * ldy + w_col; + y += size_t(row_start) * ldy + (kIL ? y_col / 2 : w_col); const short tm = kSM * short(sgid / kWN); const short tn = kSN * short(sgid % kWN); @@ -238,7 +244,11 @@ METAL_FUNC void gather_mapped_seg( } } - if constexpr (kPair) { + if constexpr (kIL) { + if (sg_active) { + store_il(Dtile, y + tm * ldy + tn / 2, ldy, int(sgp_sm), sigtab, expert); + } + } else if constexpr (kPair) { if (sg_active) { store_act( Dtile, y + tm * ldy + tn / 2, ldy, int(sgp_sm), sigtab, @@ -273,7 +283,8 @@ METAL_FUNC void gather_mapped_db( const int up_off = 0) { using WT = typename Q::WT; static_assert(G::kBK == 64, "db runs 64-deep K steps"); - constexpr bool kPair = EPI != 0; + constexpr bool kPair = EPI > 0; + constexpr bool kIL = EPI < 0; constexpr int BKP = G::kBK + 16 / sizeof(WT); constexpr int kTile = kBN * BKP; const int row_start = int(desc.x); @@ -375,7 +386,17 @@ METAL_FUNC void gather_mapped_db( threadgroup_barrier(mem_flags::mem_threadgroup); } - if constexpr (kPair) { + if constexpr (kIL) { + if (rows > 0) { + store_il( + D, + y + size_t(row_start + m0) * half_n + y_col / 2 + (kSN / 2) * (sgid % kWN), + half_n, + rows, + sigtab, + expert); + } + } else if constexpr (kPair) { if (rows > 0) { store_act( D, @@ -434,4 +455,36 @@ METAL_FUNC void store_act( } } } +// EPI < 0: Inkling 2's soft-capped SwiGLU over one bank's interleaved gate (even) and up (odd) columns, as its +// act.metal computes it on the rounded products: g, u = T(product) * the expert's scale; out = T(cap_g tanh(g / cap_g) +// * cap_u tanh(u / cap_u) / (1 + exp(-g))). `aux` is f32 { 1 / cap_g, cap_g, 1 / cap_u, cap_u, scale[E] }. +template +METAL_FUNC void store_il( + thread DTile& D, device T* y, const int ld, const int rows, + const device T* aux_t, const uint expert) { + const device float* aux = (const device float*)aux_t; + const float sc = aux[4 + expert]; + const short2 xy = BaseNAXFrag::get_coord(); + STEEL_PRAGMA_UNROLL + for (short i = 0; i < DTile::kTileRows; i++) { + STEEL_PRAGMA_UNROLL + for (short h = 0; h < 2; h++) { + const int r = i * 16 + h * 8 + xy.y; + if (r < rows) { + STEEL_PRAGMA_UNROLL + for (short f = 0; f < DTile::kTileCols; f++) { + vec v; + STEEL_PRAGMA_UNROLL + for (short p = 0; p < 2; p++) { + const float g = float(T(D.frag_at(i, f)[h * 4 + 2 * p])) * sc; + const float u = float(T(D.frag_at(i, f)[h * 4 + 2 * p + 1])) * sc; + const float capped = (metal::precise::tanh(g * aux[0]) * aux[1]) * (metal::precise::tanh(u * aux[2]) * aux[3]); + v[p] = T(capped / (1.0f + metal::precise::exp(-g))); + } + *(device vec*)(y + size_t(r) * ld + (f * 16 + xy.x) / 2) = v; + } + } + } + } +} } // namespace omlx_gqmm diff --git a/src/plugins/bailing_hybrid/AGENTS.md b/src/plugins/bailing_hybrid/AGENTS.md index 1b825998e4..12a8e36cdb 100644 --- a/src/plugins/bailing_hybrid/AGENTS.md +++ b/src/plugins/bailing_hybrid/AGENTS.md @@ -24,7 +24,7 @@ with the KDA-hybrid family's readers (`sdk/bases/kda_hybrid/config.zig`) and loa - Ling-3.1 streaming pack (the EXL3 repack beside `experts.bin`): it keeps the release's config, so its EXL3 `quantization_config` (not `expert_streaming`) sets `streamed_bank`; glm5_next's streaming rules then apply. Its prompt bill is `prefill_bytes`: the engine's unstreamed arithmetic over `sdk/bill/prefill.zig`, pinned by `bill_test.zig` - (the closure stays in sdk/); `prompt_last_row` reads the head's last 32 rows only. + (the closure stays in sdk/); `prompt_last_row` slices the head's call over every row of the forward. - Exact verify (streaming packs, `serialVerify`, ≤ 16 rows): every verify row carries serial decode's bytes (projections at `QuantTable.exact_rows`, KDA and MLA per row, `moe.mlpRows`), so greedy MTP text equals MTP off; not `exact_drafted` (sampled MTP is not position-keyed). Bar: `served_test.zig`. diff --git a/src/plugins/bailing_hybrid/config.zig b/src/plugins/bailing_hybrid/config.zig index ed33b97b65..5152ed7e0c 100644 --- a/src/plugins/bailing_hybrid/config.zig +++ b/src/plugins/bailing_hybrid/config.zig @@ -122,8 +122,7 @@ fn lingFacts(c: *const Config, p: *abi.Parsed) void { p.caps = .{ .moe = c.num_experts > 0, .dflash_capture = true, .experts_stream = c.num_experts > 0 }; if (c.streamed_bank) { family.bankFacts(p); - // The outside plugin's head computes a prompt row as the whole prompt's call does - // (sdk/bases/kda_hybrid/host.zig `finish`). + // A last-row prompt is the slice of the head's call over every row (sdk/bases/kda_hybrid/host.zig `finish`). p.caps.prompt_last_row = true; } p.chat.thinking_default = .on; diff --git a/src/plugins/inkling2/AGENTS.md b/src/plugins/inkling2/AGENTS.md index c565517ab1..1703e1380c 100644 --- a/src/plugins/inkling2/AGENTS.md +++ b/src/plugins/inkling2/AGENTS.md @@ -51,9 +51,14 @@ a `dspark-*.gguf` beside it is the bundled drafter, its weights in the set's own projections are held `[4, rank, 2 D]` for the same reason. - **Every step kernel takes rows on grid y**, so `kernels.visit` serves one row, a prompt's rows and batched slots; the conv kernels read one state the rows chain behind (`SEQ` 1) or a state per row (`SEQ` 0, batched slots). -- **A prompt's rows (past `small_rows`) read on the NAX tensor unit** (`relattn_nax.metal`: `matmul2d` for Q K^T and - P V, no mask built); `relattn.metal` (8x8 SIMD matrices, 4x the time a key) serves a GPU without NAX. A masked key's - value still enters P V at weight 0 in its 32-key tile: a NaN there reaches the row. +- **A prompt's rows (past `small_rows`) read on the NAX tensor unit** (`relative_attention_nax.metal`, the bias made + in f32 inside the read, where `kernels.relnaxTakes` takes the dtypes and widths: bf16, head dim 128, 16 relative + dims; a prompt it does not take reads main's `relattn_nax.metal`: `matmul2d` for Q K^T and P V, no mask built); + `relattn.metal` (8x8 SIMD matrices, 4x the time a key) serves a GPU without NAX. A masked key's value still enters P V at weight 0 in its + 32-key tile: a NaN there reaches the row. +- **A tile one SIMD group's lanes exchange through threadgroup memory is ordered by the threadgroup's barriers** + (`relative_attention_nax.metal`'s bias rows, every group passing them where group 0 stages): with SIMD-group barriers + alone, a sliding read behind an earlier chunk's keys moved 8 of a group's rows between repeats. Guard: `repeats bit for bit`. - **Reads of at most `small_rows` rows build a mask (`relmask.metal`) and use MLX's attention**, which beats the flash kernel (`relattn.metal`, mlx-lm's, MIT: 16 keys at a time on one threadgroup) at a few rows' latency. - **2 to `packed_rows` rows (64) read the packed expert banks in place, their picks GROUPED by expert** (`group`: tiles @@ -141,6 +146,39 @@ a `dspark-*.gguf` beside it is the bundled drafter, its weights in the set's own - **The draft head's 3 layers and Markov chain**: `draft_bits = 8` joins `q|k|v`, `k_ctx|v_ctx`, `gate|up` and quantizes the layers to affine 8-bit g64; `fold` is group-64 uint8+f16 (`markov_fold_q8.metal`, `~55 MB < 96 MB` SLC) and `markov_pick_rnn.metal` fuses pick + next-step RNN (`LAW=0` greedy, `LAW=1` Gumbel-max + parallel law probs). `draft.markov`'s op chain is the proof reference. +- **`MARKOV_Q8` (opt-in for an A/B; off: the group-64 fold above) folds the chain's head into int8 a vocab row** + (`Drafter.quantizeFoldRows`, `markov_fold_q8_row`, `markov_step_rnn` over a block's precomputed context `kappa`); + drafts are proposals, so the trunk's picks stand. It acts only on a pack without a DFlash2 `drafter/`. +- **A speed path has no env switch: its code gate decides** (the load, a device check such as `verifyQmmNaxAvailable`, + a shape, dtype or layout check). An env variable exists only for two arms worth comparing: an inexact or trade-off + arm is opt-in (`config.optIn`, default off; `TRUNK_Q8`, `MARKOV_Q8`) until the standard A/B picks one, and an arm + that loses is removed with the code only it reaches. A proof test compares a path against the code it replaced by + calling both: a load (`.step` takes main's gate, norm and prep at any width), an entry point (`relativeNax`), or, + for a whole forward, `kernels.test_main` (a test build only). +- **A path built for a prompt's rows asks the forward's load** (`kernels.Load`, from `abi.Mode`; `visit` and `sequence` + own it), never its row count: a grouped verify passes 64 rows at 11 DFlash2 lanes and batched decode 8 at 9 slots, and + those loads keep main's path (the strided prep past 8 rows, the row norm past 32, the tiled gates, the experts' row + map and its gate_up epilogue past 64, the async eval points). +- **The prompt paths run only on NAX (M5)**: the strided prep, the row norm, the tiled gates (`gate_mm`) and the async + eval points (`prefill_async`) ask `verifyQmmNaxAvailable`, as the row map and the tensor-unit read do: no M1-M4 run + measures them. Every GPU without NAX (M1-M4) serves a prompt on main's path, byte for byte; the proof `off NAX a + prompt takes main's path, byte for byte` holds it under the forced GPU-family fallback (`vqmm_nax_probe_override = + false`), and a test that asserts one of these paths engages skips off NAX. A path opens to M1-M4 only after a + non-NAX Mac measures it. +- **Main's path is main's kernel text, not the same values**: a step's norm and prep launch `norm_step.metal` and + `prep_step.metal` (main's bytes); a prompt's row norm and strided prep launch their own (`norm_row_kernel`, + `prep_strided_kernel`). One source serving both, its row mode and stride reads cost every one-row step CPU and GPU time. +- **The experts' row map and its gate_up epilogue take the banks the SDK kernel's own check decodes** + (`gather_qmm_nax.bankLayoutOk`: NVFP4, MXFP4, affine 2/3/4/8 at g32-128, bf16 scales) on NAX; MXFP8 and affine 5/6 + bits keep MLX's gather, logged `gather_rowmap declined`. +- **The 8-bit trunk is opt-in, inexact** (`TRUNK_Q8=1`; the release serves its dense trunk): made at load on Metal (attention, + conv projections, embedding, head; affine 8, group 64) as `convert_inkling2.py --bits 8` stores it (`INKLING2_Q8_REF`). +- CUDA keeps the dense trunk, synchronous eval points (`plugin.prefillAsync` asks for Metal) and no pipeline record: + none is measured there. +- **The first-launch pipelines are kept per build, machine and composition** (`fit_key.zig`, `~/.mlx-serve/inkling2`): + the file name carries the key, so a new build or MLX setting records again. The record is written before ready only + (the replay, warm-up and the load's own requests) and closes at the engine's `ModelTable.ready`: an open record cost + every decode launch a signature hash. A load that adds nothing marks it `#closed`, never appended again. - **Batched decode**: slots are rows with their own cache and conv state (`attendSlots`, `state.get`/`put`); their reads run as one `relslots` launch per 8 slots (each slot's K, V and K's strides a buffer: a kernel takes 31) into `relcomb`. A CPU stream or several rows a slot run a slot at a time. @@ -185,11 +223,13 @@ a `dspark-*.gguf` beside it is the bundled drafter, its weights in the set's own mlx-lm's bit for bit (dense and quantized), planted state mutations, the media splice, a verified block's commit, batched slots against each slot alone (CPU) or reordered and re-neighboured (GPU), and each kernel against its chain. -- `contract.zig`: `gated`, `state`, `relmask`, `act`, `sum`, `topk`, `gate` (its one-row arm), `relsplit`, `relattn_nax`, - `relsplit_nax`, `relsplit_lanes`, `relcomb`, `relslots`, `markov_rnn`, `markov_fold`, `markov_pick`, `markov_fold_batch`, - `markov_pick_batch`, `markov_pick_sample`, `oproj`, `router`, `norm`, `dflash_attn`. +- `contract.zig`: `gated`, `state`, `relmask`, `act`, `sum`, `topk`, `gate` (its one-row arm), `gate_mm`, `prep` (its + strided reads), `relsplit`, `relnax`, `relattn_nax`, `relsplit_nax`, `relsplit_lanes` (bf16, dense and affine 4/8-bit), + `relcomb`, `relslots`, `markov_rnn`, `markov_fold`, `markov_pick`, `markov_fold_batch`, `markov_pick_batch`, + `markov_pick_sample`, `markov_step_rnn`, `markov_fold_q8_row`, `oproj`, `router`, `norm`, `dflash_attn`; its + `rounds_contract.zig`: `accept_tree`, `sample_tree_mass`/`_search`/`_draw`, `dflash_conv`/`_top16_shard`/`_top16_merge`/ + `_edges`/`_tree`; its `trunk_contract.zig`: `gate` (its prompt arm); its `vision_contract.zig`: the tower's kernels. - Contract entries owed (GPU proofs in `proof_test.zig` cover each): `pre`, `prep`, `mid`, `ups`, `downs`, `relattn`, - `gate`'s prompt arm, `group`, `ups_grp`, `downs_grp`, `few_tail`, `topk_group`, `tile_scan`, `moe_wide`, - `markov_fold_q8`, `markov_pick_rnn`, - `accept_tree`, `sample_tree_draw`/`_mass`/`_search`, `dflash_conv`/`_edges`/`_top16_shard`/`_top16_merge`/`_tree`. + `group`, `ups_grp`, `downs_grp`, `few_tail`, `topk_group`, `tile_scan`, `moe_wide`, `markov_fold_q8`, + `markov_pick_rnn`, and `relsplit_nax`/`relsplit_lanes` at f16, f32 and the tree arm. - Not verified: an image against mlx-lm's tower, the drafter's tokens against oMLX's. diff --git a/src/plugins/inkling2/config.zig b/src/plugins/inkling2/config.zig index 02f573351b..c5db632ac8 100644 --- a/src/plugins/inkling2/config.zig +++ b/src/plugins/inkling2/config.zig @@ -243,6 +243,28 @@ pub fn fusedOn() bool { return kernelsServe(@import("builtin").os.tag.isDarwin(), @import("../../env.zig").span(.MLX_SERVE_INKLING2_FUSED)); } +/// `MLX_SERVE_INKLING2_TRUNK_Q8` (opt-in, inexact): the dense trunk at 8 bits from load, on a Metal build only; unset, +/// and on another backend, the checkpoint's dense trunk serves (main's path). +pub fn trunkQ8() bool { + return @import("builtin").os.tag.isDarwin() and optIn(.MLX_SERVE_INKLING2_TRUNK_Q8); +} + +/// An opt-in arm (`.kill`, default "off" in `src/env.zig`): off unless set on. Its off arm is main's path, which an A/B +/// compares it against. Read once a process, as the forward asks it every visit; a test build reads it at every call, +/// so a test can flip it. +pub fn optIn(comptime name: @EnumLiteral()) bool { + const env = @import("../../env.zig"); + if (@import("builtin").is_test) return env.on(name); + const latch = struct { + const which = name; + var value_env_cached: ?bool = null; + }; + if (latch.value_env_cached) |got| return got; + const v = env.on(name); + latch.value_env_cached = v; + return v; +} + fn kernelsServe(metal: bool, raw: ?[]const u8) bool { const r = raw orelse return metal; return metal and !(r.len > 0 and r[0] == '0'); @@ -551,7 +573,7 @@ pub fn parse(dir: *const abi.PackDir, config_json: abi.Str, settings_json: abi.S }; // A batched tick reads each slot's own cache (`attendSlots`): no slot pads KV to its neighbours'. - var p: abi.Parsed = .{ .caps = .{ .moe = true, .images = c.vision != null, .batches_decode = fusedOn(), .batch_pads_kv = false, .prompt_last_row = true } }; + var p: abi.Parsed = .{ .caps = .{ .moe = true, .images = c.vision != null, .batches_decode = fusedOn(), .batch_pads_kv = false, .prompt_last_row = true, .repeatable_prefill = true } }; // A DFlash2 draft in `drafter/` serves in place of the bundled head, when the port runs it. if (!stub and dir.exists(dir.ctx, abi.Str.of(dflash2_dir ++ "/model.safetensors"))) c.dflash2 = readDflash2File(dir, c.hidden_size, c.visits()); if (c.dflash2) |d| { @@ -827,6 +849,29 @@ test "inkling2 config: a batched tick pads no KV" { try testing.expect(!p.caps.batch_pads_kv); } +// Bar: a repeatable request's prompt width is pinned from the machine and the pack, never from live memory. +test "inkling2 config: a repeatable prompt reads no live memory for its width" { + var p: abi.Parsed = .{}; + try testing.expect(parseJson(fixture_config, &p).isOk()); + defer freeParsed(&p); + try testing.expect(p.caps.repeatable_prefill); +} + +// Bar: TRUNK_Q8 is opt-in: unset or 0 keeps the dense trunk, and =1 quantizes on a Metal build only. +test "inkling2 config: the 8-bit trunk is opt-in and made on a Metal build only" { + const env = @import("../../env.zig"); + { + const ov = env.override(.MLX_SERVE_INKLING2_TRUNK_Q8, "1"); + defer ov.restore(); + try testing.expectEqual(@import("builtin").os.tag.isDarwin(), trunkQ8()); + } + for ([_]?[*:0]const u8{ null, "0" }) |v| { + const ov = env.override(.MLX_SERVE_INKLING2_TRUNK_Q8, v); + defer ov.restore(); + try testing.expect(!trunkQ8()); + } +} + // Bar: the step kernels serve only a Metal build, and there only while the kill switch is not 0. test "inkling2 config: the step kernels serve a Metal build unless switched off" { try testing.expect(kernelsServe(true, null) and kernelsServe(true, "1")); diff --git a/src/plugins/inkling2/contract.zig b/src/plugins/inkling2/contract.zig index ac89f0dde0..e8603c0301 100644 --- a/src/plugins/inkling2/contract.zig +++ b/src/plugins/inkling2/contract.zig @@ -19,6 +19,8 @@ const layers = @import("layers.zig"); const config = @import("config.zig"); const abi = @import("../../abi/plugin.zig"); const attn = @import("../../sdk/blocks/attention/contract.zig"); +const rounds_contract = @import("rounds_contract.zig"); +const trunk_contract = @import("trunk_contract.zig"); const spec = kc.spec; const metal = kc.metal; @@ -991,6 +993,170 @@ const Gate = struct { } }; +const gate_mm_launch = metal.Launch{ .name = "msv_inkling2_gate_mm", .inputs = &.{ "A", "MS", "ST", "F", "G" }, .outputs = &.{"Y"}, .source = source("plugins/inkling2/kernels/gate_mm.metal"), .header = "#include \n", .tg_bytes = 4 * (2 * 64 * 32 + 32 * 32), .m1 = 1024, .m2 = 1024 }; + +/// `kernels.gateAt`'s tiled gates: a prompt chunk's loop message gates on the matrix units: rows = gates, n = the +/// chunk's rows, k = D. +/// `bt`: the tile's rows (`kernels.gate_mm_rows`, 64). +fn GateMmOf(comptime bt: c_int) type { + return struct { + const Self = @This(); + rig: metal.Rig, + launch: *const metal.Launch = &gate_mm_launch, + arena: std.heap.ArenaAllocator, + shape: Shape = undefined, + /// `[J, S, D]` each; `st` `[J, S, RANK]`; `f`, `g` `[J, D, RANK]`. + a: []f64 = &.{}, + ms: []f64 = &.{}, + st: []f64 = &.{}, + f: []f64 = &.{}, + g: []f64 = &.{}, + args: [5]mlx.mlx_array = undefined, + wt: mlx.mlx_dtype, + + fn init(al: std.mem.Allocator, wt: mlx.mlx_dtype) Self { + return .{ .rig = metal.Rig.init(al), .arena = .init(al), .wt = wt }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(_: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.n <= kernels.small_rows or shape.k == 0 or shape.k % 32 != 0) return null; + const d: c_int = @intCast(shape.k); + const nt: c_int = @divExact(bt, 16) * 2 * 32; + var geo = metal.Geometry{ .grid = .{ nt * @divExact(d, 32), @divFloor(@as(c_int, @intCast(shape.n)) + bt - 1, bt), @intCast(shape.rows) }, .tg = .{ nt, 1, 1 } }; + geo.int("BM", @as(c_int, bt)); + geo.out(&.{ @intCast(shape.rows), @intCast(shape.n), d }, .float32); + geo.int("D", d); + geo.int("RANK", @as(c_int, RANK)); + return geo; + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const al = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const j = shape.rows; + const s = shape.n; + const d = shape.k; + self.a = try spread(al, rng, j * s * d, .f32); + self.ms = try spread(al, rng, j * s * d, .f32); + self.st = try al.alloc(f64, j * s * RANK); + for (self.st) |*v| v.* = spec.roundTo(.bf16, rng.float(f64) * 2 - 1); + self.f = try al.alloc(f64, j * d * RANK); + self.g = try al.alloc(f64, j * d * RANK); + for ([_][]f64{ self.f, self.g }) |w| for (w) |*v| { + v.* = spec.roundTo(elemOf(self.wt), 0.2 * (rng.float(f64) * 2 - 1)); + }; + switch (fill) { + .random => {}, + .nonfinite => { + plant(self.a, d); + // An infinite state saturates its gate's row: the stream leaves, the message stays whole. + if (s > 1) self.st[RANK + 3] = std.math.inf(f64); + }, + // Gate 4, as Gate's: states of one, projections 1, then 62 of 2^-12, then -1. + .stress => { + @memset(self.a, 2); + @memset(self.ms, 1); + @memset(self.st, 1); + for ([_][]f64{ self.f, self.g }) |w| for (w, 0..) |*v, i| { + v.* = switch (i % RANK) { + 0 => 1, + RANK - 1 => -1, + else => 0x1p-12, + }; + }; + }, + } + self.rig.reset(); + const jj: c_int = @intCast(j); + const ss: c_int = @intCast(s); + const dd: c_int = @intCast(d); + self.args = .{ + try self.rig.input(.float32, &.{ jj, ss, dd }, self.a), + try self.rig.input(.float32, &.{ jj, ss, dd }, self.ms), + try self.rig.input(.bfloat16, &.{ jj, ss, RANK }, self.st), + try self.rig.input(self.wt, &.{ jj, dd, RANK }, self.f), + try self.rig.input(self.wt, &.{ jj, dd, RANK }, self.g), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return self.shape.rows * self.shape.n * self.shape.k; + } + + /// Element `e`'s forget and message terms. + fn terms(self: *const Self, e: usize, tf: *[RANK]f64, tg: *[RANK]f64) void { + const d = self.shape.k; + const s = self.shape.n; + const j = e / (s * d); + const row = (e / d) % s; + const i = e % d; + for (tf, tg, 0..) |*x, *y, r| { + const st = self.st[(j * s + row) * RANK + r]; + x.* = self.f[(j * d + i) * RANK + r] * st; + y.* = self.g[(j * d + i) * RANK + r] * st; + } + } + + fn mix(self: *const Self, e: usize, f: f64, g: f64) f64 { + return (1 - std.math.tanh(f)) * self.a[e] + std.math.tanh(g) * self.ms[e]; + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + var tf: [RANK]f64 = undefined; + var tg: [RANK]f64 = undefined; + for (want, mag, 0..) |*w, *m, e| { + self.terms(e, &tf, &tg); + var f: f64 = 0; + var g: f64 = 0; + var af: f64 = 0; + var ag: f64 = 0; + for (tf, tg) |x, y| { + f += x; + g += y; + af += @abs(x); + ag += @abs(y); + } + w.* = self.mix(e, f, g); + m.* = af * @abs(self.a[e]) + ag * @abs(self.ms[e]) + @abs((1 - std.math.tanh(f)) * self.a[e]) + @abs(std.math.tanh(g) * self.ms[e]); + if (!std.math.isFinite(m.*)) m.* = 0; + } + } + + pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { + var tf: [RANK]f64 = undefined; + var tg: [RANK]f64 = undefined; + for (out, 0..) |*o, e| { + self.terms(e, &tf, &tg); + o.* = self.mix(e, spec.sumIn(acc, order, &tf), spec.sumIn(acc, order, &tg)); + } + } + + fn wrapper(self: *Self) ![]const u8 { + var g = ops.Graph.init(self.rig.a, self.rig.stream()); + defer g.deinit(); + const x = self.args; + const gates: layers.Gates = .{ .down = x[2], .forget = x[3], .message = x[4] }; + return self.rig.bytesOf(&.{try kernels.gate(&g, &gates, x[0], x[1], x[2], 0, @intCast(self.shape.rows))}); + } + + }; +} +const GateMm = GateMmOf(kernels.gate_mm_rows); + fn rankDepth(_: Shape) usize { return RANK; } @@ -1198,6 +1364,256 @@ const TopK = struct { } }; +/// Mini's attention for `prep.metal`: query and KV heads, relative state width; the head width is `SD`, the conv's taps +/// `KT`, the relative extent `R`. The joined projection a row: q, gate, relative, k, v. +const PH = 24; +const PHKV = 8; +const PDREL = 16; +const PC = PHKV * SD; +const PQD = PH * SD; +const PJW = 2 * PQD + PH * PDREL + 2 * PC; +/// Where each part starts in a joined row, then the row's end. +const prep_starts = [_]usize{ 0, PQD, 2 * PQD, 2 * PQD + PH * PDREL, 2 * PQD + PH * PDREL + PC, PJW }; + +const prep_ins_c = &[_][*:0]const u8{ "QP", "GP", "RP", "KP", "VP", "KDY", "VDY", "ST", "KW", "VW", "QS", "RS", "RJ", "PR", "PARENT" }; +const prep_outs_c = &[_][*:0]const u8{ "Q", "GATE", "K", "V", "BIAS", "REL" }; +const prep_launch = metal.Launch{ .name = "msv_inkling2_prep", .inputs = prep_ins_c, .outputs = prep_outs_c, .source = source("plugins/inkling2/kernels/prep_step.metal"), .tg_bytes = 4 * SD, .m1 = 1024, .m2 = 1024 }; +const prep_strided_launch = metal.Launch{ .name = "msv_inkling2_prep_strided", .inputs = prep_ins_c, .outputs = prep_outs_c, .source = source("plugins/inkling2/kernels/prep.metal"), .contiguous = false, .tg_bytes = 4 * SD, .m1 = 928, .m2 = 928 }; + +/// The strided prep (a prompt chunk's): `prep.metal` reading q, gate, relative, k and v as views of one joined +/// projection (their row strides), bit-equal to the kernel on contiguous copies. rows = S, n = a one-row read's keys +/// (0 for more), k = R. +const PrepStrided = PrepCase(true); + +fn prepHeads(shape: Shape) usize { + return shape.rows * PQD; +} + +/// Q, GATE and K's element types and counts. +const prep_outs: []const spec.Part = &.{ .{ .elem = .bf16, .count = prepHeads }, .{ .elem = .f32, .count = prepHeads }, .{ .elem = .bf16, .count = prepHeads } }; + +fn PrepCase(comptime strided: bool) type { + return struct { + rig: metal.Rig, + launch: *const metal.Launch = if (strided) &prep_strided_launch else &prep_launch, + arena: std.heap.ArenaAllocator, + shape: Shape = undefined, + /// `[S, PJW]`: the rows' joined projection. + joined: []f64 = &.{}, + args: [15]mlx.mlx_array = undefined, + /// `strided`: the five parts' views of the joined input, freed at the next prepare. + views: [5]mlx.mlx_array = @splat(.{ .ctx = null }), + note: [200]u8 = undefined, + + const Self = @This(); + + fn init(a: std.mem.Allocator) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a) }; + } + + fn dropViews(self: *Self) void { + for (&self.views) |*v| { + if (v.ctx != null) _ = mlx.mlx_array_free(v.*); + v.* = .{ .ctx = null }; + } + } + + pub fn deinit(self: *Self) void { + self.dropViews(); + self.rig.deinit(); + self.arena.deinit(); + } + + fn wide(shape: Shape) bool { + return shape.rows > 1; + } + + /// The tail's one-row bias or more rows' states, elements. + fn tail(shape: Shape) usize { + return if (wide(shape)) shape.rows * PH * PDREL else PH * shape.n; + } + + pub fn geometry(_: *const Self, shape: Shape) ?metal.Geometry { + const s = shape.rows; + if (s == 0 or shape.k != R or (!wide(shape) and shape.n == 0)) return null; + const ci = struct { + fn f(x: usize) c_int { + return @intCast(x); + } + }.f; + const x = PQD + 2 * PC + PH * (if (wide(shape)) PDREL else shape.n); + var g = metal.Geometry{ .grid = .{ ci(x), ci(s), 1 }, .tg = .{ SD, 1, 1 } }; + const unused1: []const c_int = &.{1}; + if (wide(shape)) g.out(&.{ 1, ci(s), PH, SD }, .bfloat16) else g.out(&.{ 1, PH, 1, SD }, .bfloat16); + g.out(&.{ci(s * PQD)}, .float32); + g.out(&.{ 1, PHKV, ci(s), SD }, .bfloat16); + g.out(&.{ 1, PHKV, ci(s), SD }, .bfloat16); + if (wide(shape)) g.out(unused1, .float32) else g.out(&.{ 1, PH, 1, ci(shape.n) }, .bfloat16); + if (wide(shape)) g.out(&.{ 1, ci(s), PH, PDREL }, .bfloat16) else g.out(unused1, .float32); + g.unread = if (wide(shape)) @as(u8, 1 << 4) else 1 << 5; + g.dtype("T", .bfloat16); + g.dtype("WT", .bfloat16); + g.dtype("S", .bfloat16); + g.int("H", @as(c_int, PH)); + g.int("HD", @as(c_int, SD)); + g.int("HKV", @as(c_int, PHKV)); + g.int("DREL", @as(c_int, PDREL)); + g.int("KT", @as(c_int, KT)); + g.int("DYN", @as(c_int, 0)); + g.int("WIDE", @as(c_int, @intFromBool(wide(shape)))); + g.int("TREE", @as(c_int, 0)); + return g; + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + self.dropViews(); + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const s = shape.rows; + self.joined = try host.uniform(a, rng, s * PJW, -2, 2, .bfloat16); + const st = try host.uniform(a, rng, (KT - 1) * 2 * PC, -1, 1, .float32); + const kw = try host.uniform(a, rng, PC * KT, -0.5, 0.5, .bfloat16); + const vw = try host.uniform(a, rng, PC * KT, -0.5, 0.5, .bfloat16); + const qs = try host.uniform(a, rng, PH * SD, 0.5, 1.5, .bfloat16); + const rs = try host.uniform(a, rng, PH * PDREL, 0.5, 1.5, .bfloat16); + const rj = try host.uniform(a, rng, PDREL * R, -1, 1, .float32); + // qk clip, relative clip, eps, tau (one row's log scale), the static conv's scale, a one-row read's keys. + var pr = [6]f64{ @as(f32, 22.627416997969522), 8, @as(f32, 1e-6), if (wide(shape)) 1 else 1.25, @as(f32, 1.0 / @sqrt(@as(f32, KT + 1))), @floatFromInt(shape.n) }; + switch (fill) { + .random => {}, + // In every part of the rows' projections (a NaN in row 0, infinities in rows 1 to 3). + .nonfinite => for (0..5) |part| { + const at = prep_starts[part]; + const w = prep_starts[part + 1] - at; + const puts = [_]f64{ std.math.nan(f64), std.math.inf(f64), -std.math.inf(f64), std.math.inf(f64) }; + for (0..@min(s, 4)) |r| { + const row = self.joined[r * PJW + at ..][0..w]; + row[(part * 37 + r * 11) % w] = puts[r]; + if (r == 3) row[w - 1] = -std.math.inf(f64); + } + }, + // States of one, unclipped (a relative clip no norm reaches). + .stress => { + for (0..s) |r| @memset(self.joined[r * PJW + 2 * PQD ..][0 .. PH * PDREL], 1); + @memset(rs, 1); + pr[1] = 1e30; + }, + } + self.rig.reset(); + const ci = struct { + fn f(x: usize) c_int { + return @intCast(x); + } + }.f; + const starts = prep_starts; + var parts: [5]mlx.mlx_array = undefined; + if (strided) { + const whole = try self.rig.input(.bfloat16, &.{ 1, ci(s), PJW }, self.joined); + for (&self.views, 0..) |*v, i| { + v.* = mlx.mlx_array_new(); + try mlx.check(mlx.mlx_slice(v, whole, &[_]c_int{ 0, 0, ci(starts[i]) }, 3, &[_]c_int{ 1, ci(s), ci(starts[i + 1]) }, 3, &[_]c_int{ 1, 1, 1 }, 3, self.rig.stream())); + try mlx.check(mlx.mlx_array_eval(v.*)); + } + parts = self.views; + } else for (&parts, 0..) |*x, i| { + const w = starts[i + 1] - starts[i]; + const vals = try a.alloc(f64, s * w); + for (0..s) |r| @memcpy(vals[r * w ..][0..w], self.joined[r * PJW + starts[i] ..][0..w]); + x.* = try self.rig.input(.bfloat16, &.{ 1, ci(s), ci(w) }, vals); + } + self.args = .{ + parts[0], parts[1], parts[2], parts[3], parts[4], + // A static conv's KDY, VDY slots hold k and v, which it never reads. + parts[3], parts[4], try self.rig.input(.float32, &.{ 1, KT - 1, 2 * PC }, st), try self.rig.input(.bfloat16, &.{ PC, KT, 1 }, kw), try self.rig.input(.bfloat16, &.{ PC, KT, 1 }, vw), + try self.rig.input(.bfloat16, &.{ PH, SD }, qs), try self.rig.input(.bfloat16, &.{ PH, PDREL }, rs), try self.rig.input(.float32, &.{ PDREL, R }, rj), try self.rig.input(.float32, &.{6}, &pr), + try self.rig.input(.int32, &.{1}, &.{0}), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + const s = self.shape.rows; + return 2 * s * PQD + 2 * s * PC + tail(self.shape); + } + + fn dims(self: *const Self) kernels.PrepDims { + return .{ .heads = PH, .kv_heads = PHKV, .hd = SD, .d_rel = PDREL, .kt = KT, .keys = @intCast(self.shape.n), .dynamic = false }; + } + + fn bytesOf(self: *Self, o: [6]mlx.mlx_array) ![]const u8 { + return self.rig.bytesOf(&.{ o[0], o[1], o[2], o[3], if (wide(self.shape)) o[5] else o[4] }); + } + + /// The kernel on contiguous inputs in the plain order (the engine's path with both switches off): its bytes. + fn plain(self: *Self) ![]const u8 { + var g = ops.Graph.init(self.rig.a, self.rig.stream()); + defer g.deinit(); + return self.bytesOf(try kernels.prepLaunch(&g, &self.args, self.dims(), false)); + } + + /// `strided`: the contiguous kernel on the same views (MLX copies them first). + pub const replaced = if (strided) plain else notReplacing; + + fn notReplacing(_: *Self) ![]const u8 { + return error.NotAReplacement; + } + + /// The plain kernel's values (its bytes read back) with their magnitude. + fn values(self: *Self, out: []f64, mag: ?[]f64) !void { + const s = self.shape.rows; + const nq = s * PQD; + const nk = s * PC; + const nt = tail(self.shape); + const b = try self.plain(); + var at: usize = 0; + var off: usize = 0; + for ([_]spec.Elem{ .bf16, .f32, .bf16, .bf16, .bf16 }, [_]usize{ nq, nq, nk, nk, nt }) |e, n| { + for (0..n) |i| out[at + i] = spec.read(e, b[off..], i); + at += n; + off += n * spec.size(e); + } + if (mag) |m| for (m[0..at], out[0..at]) |*x, w| { + x.* = @abs(w); + }; + } + + pub fn reference(self: *Self, want: []f64, mag: []f64) !void { + try self.values(want, mag); + } + + pub fn simulate(self: *Self, _: spec.Accum, _: spec.Order, out: []f64) !void { + try self.values(out, null); + } + + /// Gates 1 and 3: every output bit-equal to the plain kernel's. + pub fn check(self: *Self, _: spec.Gate) !?[]const u8 { + const al = self.rig.a; + const got = try al.dupe(u8, self.rig.outputBytes()); + defer al.free(got); + const want = try self.plain(); + const head = want.len; + if (got.len < head or !std.mem.eql(u8, got[0..head], want)) + return std.fmt.bufPrint(&self.note, "its bytes differ from the contiguous kernel's from byte {d}", .{std.mem.indexOfDiff(u8, got, want) orelse head}) catch "its bytes differ from the plain kernel's"; + if (got.len == head) return null; + return "it writes more than the plain kernel"; + } + + fn wrapper(self: *Self) ![]const u8 { + var g = ops.Graph.init(self.rig.a, self.rig.stream()); + defer g.deinit(); + return self.bytesOf(try kernels.prepLaunch(&g, &self.args, self.dims(), strided)); + } + }; +} + /// The model's head width and query heads a KV head; the split read's keys a threadgroup and a tile. const SD = 128; const SG = 3; @@ -1211,7 +1627,7 @@ const split_soft = attn.Soft{ .base2 = true, .p_unit = 0x1p-11, .p_abs = 0x1p-25 const HALF_SUB = 0x1p-25; const half_sub_row: [SD]f64 = @splat(HALF_SUB); -const split_launch = metal.Launch{ .name = "msv_inkling2_relsplit", .inputs = &.{ "q", "k", "v", "kb", "vb", "rel", "sinks", "sizes", "scale" }, .outputs = &.{ "PART", "ML" }, .source = source("plugins/inkling2/kernels/relsplit.metal"), .contiguous = false, .tg_bytes = 2 * (SD * (SBK + 8) + SBK * (SD + 8)), .m1 = 1024, .m2 = 1024 }; +const split_launch = metal.Launch{ .name = "msv_inkling2_relsplit", .inputs = &.{ "q", "k", "v", "kb", "vb", "rel", "sinks", "sizes", "scale" }, .outputs = &.{ "PART", "ML" }, .source = source("plugins/inkling2/kernels/relsplit.metal"), .contiguous = false, .tg_bytes = 2 * (SD * (SBK + 8) + SBK * (SD + 8)), .m1 = 576, .m2 = 576 }; /// The split read's splits of a few rows behind a cache: rows = KV heads, n = rows read, k = keys; `window` 0 on a /// global layer. `own`: the rows' keys and values are a second source behind the cache's (a verify's open read). @@ -1608,7 +2024,7 @@ const NAX_BK = 32; /// A prompt's rows on the tensor unit: rows = query rows, n = KV heads (3 query heads each), k = keys, the rows at the last /// `rows` of them; `window` 0 on a global layer. Each SIMD group's 16 rows walk 32-key tiles from their first row's window /// to their last row, the keys a row may not see entering P V at weight 0. -const RelNax = struct { +const RelattnNax = struct { rig: metal.Rig, launch: *const metal.Launch = &nax_launch, arena: std.heap.ArenaAllocator, @@ -1800,74 +2216,49 @@ const RelNax = struct { } }; -const relsplit_nax_launch = metal.Launch{ - .name = "msv_inkling2_relsplit_nax", - .inputs = &.{ "q", "k0", "k1", "k2", "k3", "v0", "v1", "v2", "v3", "q0", "q1", "q2", "q3", "kb", "vb", "rel", "sinks", "GATE", "TMETA", "sizes", "params" }, - .outputs = &.{ "PART", "ML", "OUT" }, - .source = source("plugins/inkling2/kernels/relsplit_nax.metal"), - .header = source("kernels/common/mpp_tensor_ops.metal"), + +/// The tensor-unit read's rows a threadgroup and keys a block, and `relPad`'s projection width. +const NBQ = 64; +const NBK = 32; +const NRP = kernels.relp_before + R + 64; +/// Gate 4's q: the largest 8-bit integer, exact in bf16. +const NAX_STRESS_Q = 251; + +const relnax_launch = metal.Launch{ + .name = "msv_inkling2_relnax", + .inputs = &.{ "q", "k", "v", "rel", "sinks", "key_start", "sizes", "scale", "relp" }, + .outputs = &.{"out"}, + .source = source("plugins/inkling2/kernels/relative_attention_nax.metal"), + .header = source("kernels/attention/nax_tiles.metal") ++ source("kernels/attention/nax_attention.metal"), .contiguous = false, - // Dual BK x D bf16 staging tiles (Ks_v + Vs_v) when BITS > 0; eliminated when BITS == 0. - .tg_bytes = 2 * NAX_BK * SD * 2, - .m1 = 1024, - .m2 = 1024, + // Mtg: four simdgroups' 16 x 49 f32 bias rows. + .tg_bytes = 4 * 16 * 49 * 4, .offline = false, .min_gen = 17, }; -const relsplit_lanes_launch = metal.Launch{ - .name = "msv_inkling2_relsplit_lanes", - .inputs = relsplit_nax_launch.inputs, - .outputs = relsplit_nax_launch.outputs, - .source = source("plugins/inkling2/kernels/relsplit_lanes.metal"), - .header = kernels.lanes_header, - .contiguous = false, - // Ks [D x 24] and Vs [16 x (D + 8)] at the float element. - .tg_bytes = (SD * 24 + 16 * (SD + 8)) * 4, - .m1 = 1024, - .m2 = 1024, -}; - -/// `RelSplitNax`'s read on a GPU without NAX (`relsplit_lanes.metal`, 16-key tiles): same shapes, same reference. -/// Single-split (`DIRECT=1`) NAX verify read over dense (`bits == 0`, up to 4 lanes) or affine-quantized (`bits == 4|8`, -/// up to 2 lanes) cached KV and dense own keys: rows = verify rows L (2..16), n = lanes, k = cached keys per lane. -const RelSplitNax = struct { +/// The tensor-unit prompt read: `relative_attention_nax.metal` over a prompt chunk's rows with the relative bias made +/// inside the read, rows = KV heads, n = L query rows, k = S keys. +const RelNax = struct { rig: metal.Rig, - launch: *const metal.Launch = &relsplit_nax_launch, + launch: *const metal.Launch = &relnax_launch, arena: std.heap.ArenaAllocator, - bits: u32, - gs: usize, window: usize, - lanes: bool = false, shape: Shape = undefined, + /// `[HQ, L, SD]`, `[HKV, S, SD]` twice, `[L, HQ, 16]`, `[16, R]`, `[L, HQ]`. q: []f64 = &.{}, - kb: []f64 = &.{}, - vb: []f64 = &.{}, - rel: []f64 = &.{}, + k: []f64 = &.{}, + v: []f64 = &.{}, + st: []f64 = &.{}, + proj: []f64 = &.{}, sinks: []f64 = &.{}, - gate: []f64 = &.{}, - kd: [kernels.nax_lanes][]f64 = undefined, - vd: [kernels.nax_lanes][]f64 = undefined, - kq: [kernels.nax_quant_lanes]host.Quant = undefined, - vq: [kernels.nax_quant_lanes]host.Quant = undefined, scale: f64 = @as(f32, 1.0 / @sqrt(@as(f32, SD))), - log_alpha: f64 = 0.2, - log_n_floor: usize = 16, - args: [21]mlx.mlx_array = undefined, - msg: [256]u8 = undefined, + args: [9]mlx.mlx_array = undefined, const Self = @This(); - const HQS = SHKV * SG; - fn init(a: std.mem.Allocator, bits: u32, gs: usize, window: usize) Self { - return .{ .rig = metal.Rig.init(a), .arena = .init(a), .bits = bits, .gs = gs, .window = window }; - } - - fn initLanes(a: std.mem.Allocator, bits: u32, gs: usize, window: usize) Self { - var s = init(a, bits, gs, window); - s.lanes = true; - s.launch = &relsplit_lanes_launch; - return s; + fn init(a: std.mem.Allocator, window: usize) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a), .window = window }; } pub fn deinit(self: *Self) void { @@ -1875,31 +2266,279 @@ const RelSplitNax = struct { self.arena.deinit(); } - fn tile(self: *const Self) usize { - return if (self.lanes) 16 else NAX_BK; - } - pub fn geometry(self: *const Self, shape: Shape) ?metal.Geometry { - const max_l: usize = if (self.bits == 0) kernels.nax_lanes else kernels.nax_quant_lanes; - if (shape.rows < 2 or shape.rows > kernels.open_rows or shape.n == 0 or shape.n > max_l or shape.k == 0) return null; - if (self.bits == 0) { - if (shape.k * SHKV * SD * 2 < 4096 or shape.rows * SHKV * SD * 2 < 4096) return null; - } else { - if (shape.k * SHKV * (SD / self.gs) < 8 or shape.n * shape.rows * SHKV * SD * 2 < 4096) return null; - } - const total = shape.k + shape.rows; - const first: usize = if (self.window > 0 and total + 1 > shape.rows + self.window) total + 1 - shape.rows - self.window else 0; - const span = total - first; - const kps: usize = @intCast(kernels.splitKps(@intCast(span), shape.n)); - if ((span + kps - 1) / kps != 1) return null; - const rows: c_int = @intCast(shape.n * shape.rows); - var g = metal.Geometry{ .grid = .{ 32 * SG, SHKV, @intCast(shape.n) }, .tg = .{ 32 * SG, 1, 1 } }; - g.out(&.{1}, .float32); - g.out(&.{1}, .float32); - g.out(&.{ 1, rows, HQS * SD }, .bfloat16); - g.unread = 0b011; + if (shape.rows == 0 or shape.n < 2 or shape.k < shape.n) return null; + const hq: c_int = @intCast(shape.rows * SG); + const l: c_int = @intCast(shape.n); + var g = metal.Geometry{ .grid = .{ @divTrunc(l + NBQ - 1, NBQ) * 128, hq, 1 }, .tg = .{ 128, 1, 1 } }; + g.out(&.{ 1, l, hq, SD }, .bfloat16); g.dtype("T", .bfloat16); - g.dtype("ST", .bfloat16); + g.int("D", @as(c_int, SD)); + g.int("HQ", hq); + g.int("HKV", @as(c_int, @intCast(shape.rows))); + g.int("R", @as(c_int, R)); + g.int("WINDOW", @as(c_int, @intCast(self.window))); + g.flag("ALIGN_Q", shape.n % NBQ == 0); + g.flag("ALIGN_K", shape.k % NBK == 0); + g.int("RP", @as(c_int, NRP)); + g.int("PADL", @as(c_int, kernels.relp_before)); + return g; + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const hq = shape.rows * SG; + const l = shape.n; + if (fill == .stress) { + // Integer q and k whose dots are exact in f32 in any order while their partial sums leave fp16's range + // and bf16's precision (the SDK's NAX case's rows); integer states and projection, exact anywhere. + self.q = try a.alloc(f64, hq * l * SD); + for (self.q, 0..) |*x, i| x.* = if (i % SD < SD / 2) NAX_STRESS_Q else -NAX_STRESS_Q; + self.k = try host.ints(a, rng, shape.rows * shape.k * SD, 0, 127); + var r: usize = 0; + while (r < self.k.len) : (r += SD) for (0..SD / 2) |i| { + self.k[r + SD / 2 + i] = self.k[r + (i + 1) % (SD / 2)] + @as(f64, if (i < 2) @floatFromInt(rng.uintLessThan(u32, 2)) else 0); + }; + self.st = try host.ints(a, rng, l * hq * 16, -1, 1); + self.proj = try host.ints(a, rng, 16 * R, -1, 1); + } else { + self.q = try host.uniform(a, rng, hq * l * SD, -1, 1, .bfloat16); + self.k = try host.uniform(a, rng, shape.rows * shape.k * SD, -1, 1, .bfloat16); + self.st = try host.uniform(a, rng, l * hq * 16, -1, 1, .bfloat16); + self.proj = try host.uniform(a, rng, 16 * R, -1, 1, .bfloat16); + } + self.v = try host.uniform(a, rng, shape.rows * shape.k * SD, -2, 2, .bfloat16); + self.sinks = try host.uniform(a, rng, l * hq, -1, 3, .float32); + if (fill == .nonfinite) { + host.plant(self.q, hq * l, SD); + host.plant(self.v, shape.rows * shape.k, SD); + } + const relp = try a.alloc(f64, 16 * NRP); + @memset(relp, 0); + for (0..16) |i| @memcpy(relp[i * NRP + kernels.relp_before ..][0..R], self.proj[i * R ..][0..R]); + self.rig.reset(); + const ci = struct { + fn f(x: usize) c_int { + return @intCast(x); + } + }.f; + self.args = .{ + try self.rig.input(.bfloat16, &.{ 1, ci(hq), ci(l), SD }, self.q), + try self.rig.input(.bfloat16, &.{ 1, ci(shape.rows), ci(shape.k), SD }, self.k), + try self.rig.input(.bfloat16, &.{ 1, ci(shape.rows), ci(shape.k), SD }, self.v), + try self.rig.input(.bfloat16, &.{ 1, ci(l), ci(hq), 16 }, self.st), + try self.rig.input(.float32, &.{ 1, ci(l), ci(hq) }, self.sinks), + try self.rig.input(.int32, &.{1}, &.{0}), + try self.rig.input(.int32, &.{2}, &.{ @floatFromInt(l), @floatFromInt(shape.k) }), + try self.rig.scalar(@floatCast(self.scale)), + try self.rig.input(.bfloat16, &.{ 16, NRP }, relp), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return self.shape.n * self.shape.rows * SG * SD; + } + + /// Whether the simdgroup of rows [lo, hi] (its rows below L) sees no key of block kb: all its scores are -inf. + fn dead(self: *const Self, off: usize, lo: usize, hi: usize, kb: usize) bool { + const c_lo = kb * NBK; + return c_lo > off + hi or (self.window > 0 and off + lo >= c_lo + NBK - 1 + self.window); + } + + fn emit(self: *const Self, want: []f64, mag: ?[]f64, sim: attn.Sim) !void { + const a = self.rig.a; + const l = self.shape.n; + const s = self.shape.k; + const hq = self.shape.rows * SG; + const off = s - l; + const nk = (s + NBK - 1) / NBK; + const keys = try a.alloc(attn.Key, (nk + 1) * NBK); + defer a.free(keys); + const ends = try a.alloc(usize, nk + 1); + defer a.free(ends); + const terms = try a.alloc(f64, SD); + defer a.free(terms); + const o = try a.alloc(f64, SD); + defer a.free(o); + const eo = try a.alloc(f64, SD); + defer a.free(eo); + const zero: [SD]f64 = @splat(0); + var pc: [16]f64 = undefined; + const scale2: f64 = @as(f32, @floatCast(self.scale * LOG2E)); + for (0..hq) |h| for (0..l) |r| { + const kv = h / SG; + const q0 = r / NBQ * NBQ; + const lo = q0 + (r - q0) / 16 * 16; + const hi = @min(lo + 16, l) -| 1; + const first_diag = off + q0; + const last_diag = off + @min(q0 + NBQ, l) - 1; + const first_key = if (self.window > 0) (first_diag + 1) -| self.window else 0; + const kb_hi = @min(nk, last_diag / NBK + 1); + const at = off + r; + const qrow = self.q[(h * l + r) * SD ..][0..SD]; + const srow = self.st[(r * hq + h) * 16 ..][0..16]; + var n: usize = 0; + var nb: usize = 0; + for (first_key / NBK..kb_hi) |kb| { + if (self.dead(off, lo, hi, kb)) continue; + for (kb * NBK..kb * NBK + NBK) |c| { + const vrow: []const f64 = if (c < s) self.v[(kv * s + c) * SD ..][0..SD] else &zero; + if (c >= s or c > at or (self.window > 0 and at - c >= self.window)) { + keys[n] = .{ .s = -std.math.inf(f64), .on = false, .v = vrow }; + n += 1; + continue; + } + const d = attn.dot(qrow, self.k[(kv * s + c) * SD ..][0..SD], scale2, SD + 1, 3, sim, terms); + var b: host.Val = .{ .v = 0 }; + if (at - c < R) { + for (&pc, 0..) |*x, i| x.* = self.proj[i * R + at - c]; + b = attn.dot(srow, &pc, LOG2E, 17, 0, sim, terms); + } + const sv = d.v + b.v; + keys[n] = .{ .s = sv, .e = d.e + b.e + host.U * @abs(sv), .v = vrow }; + n += 1; + } + ends[nb] = n; + nb += 1; + } + const m0: f64 = @as(f32, @floatCast(self.sinks[r * hq + h] * LOG2E)); + const row = attn.online(.{ .base2 = true, .p_unit = 0.5 * host.ulpOf(.bfloat16) }, .{ .m = m0, .e = host.U * @abs(m0), .l = 1 }, keys[0..n], ends[0..nb], o, eo); + attn.normalize(row, o, eo); + const out_at = (r * hq + h) * SD; + @memcpy(want[out_at..][0..SD], o); + if (mag) |m| for (m[out_at..][0..SD], eo) |*x, e| { + x.* = host.allowance(e); + }; + }; + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + try self.emit(want, mag, null); + } + + pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { + try self.emit(out, null, .{ .acc = acc, .order = order }); + } + + fn wrapper(self: *Self) ![]const u8 { + var g = ops.Graph.init(self.rig.a, self.rig.stream()); + defer g.deinit(); + const x = self.args; + const o = (try kernels.relativeNaxStates(&g, @intCast(self.shape.rows * SG), @intCast(self.shape.rows), x[0], x[1], x[2], x[3], x[8], x[4], @intCast(self.window), @intCast(self.shape.n), @intCast(self.shape.k), R, @floatCast(self.scale))) orelse return error.Declined; + return self.rig.bytesOf(&.{o}); + } +}; + +const relsplit_nax_launch = metal.Launch{ + .name = "msv_inkling2_relsplit_nax", + .inputs = &.{ "q", "k0", "k1", "k2", "k3", "v0", "v1", "v2", "v3", "q0", "q1", "q2", "q3", "kb", "vb", "rel", "sinks", "GATE", "TMETA", "sizes", "params" }, + .outputs = &.{ "PART", "ML", "OUT" }, + .source = source("plugins/inkling2/kernels/relsplit_nax.metal"), + .header = source("kernels/common/mpp_tensor_ops.metal"), + .contiguous = false, + // Dual BK x D bf16 staging tiles (Ks_v + Vs_v) when BITS > 0; eliminated when BITS == 0. + .tg_bytes = 2 * NAX_BK * SD * 2, + .m1 = 1024, + .m2 = 1024, + .offline = false, + .min_gen = 17, +}; + +const relsplit_lanes_launch = metal.Launch{ + .name = "msv_inkling2_relsplit_lanes", + .inputs = relsplit_nax_launch.inputs, + .outputs = relsplit_nax_launch.outputs, + .source = source("plugins/inkling2/kernels/relsplit_lanes.metal"), + .header = kernels.lanes_header, + .contiguous = false, + // Ks [D x 24] and Vs [16 x (D + 8)] at the float element. + .tg_bytes = (SD * 24 + 16 * (SD + 8)) * 4, + .m1 = 1024, + .m2 = 1024, +}; + +/// `RelSplitNax`'s read on a GPU without NAX (`relsplit_lanes.metal`, 16-key tiles): same shapes, same reference. +/// Single-split (`DIRECT=1`) NAX verify read over dense (`bits == 0`, up to 4 lanes) or affine-quantized (`bits == 4|8`, +/// up to 2 lanes) cached KV and dense own keys: rows = verify rows L (2..16), n = lanes, k = cached keys per lane. +const RelSplitNax = struct { + rig: metal.Rig, + launch: *const metal.Launch = &relsplit_nax_launch, + arena: std.heap.ArenaAllocator, + bits: u32, + gs: usize, + window: usize, + lanes: bool = false, + shape: Shape = undefined, + q: []f64 = &.{}, + kb: []f64 = &.{}, + vb: []f64 = &.{}, + rel: []f64 = &.{}, + sinks: []f64 = &.{}, + gate: []f64 = &.{}, + kd: [kernels.nax_lanes][]f64 = undefined, + vd: [kernels.nax_lanes][]f64 = undefined, + kq: [kernels.nax_quant_lanes]host.Quant = undefined, + vq: [kernels.nax_quant_lanes]host.Quant = undefined, + scale: f64 = @as(f32, 1.0 / @sqrt(@as(f32, SD))), + log_alpha: f64 = 0.2, + log_n_floor: usize = 16, + args: [21]mlx.mlx_array = undefined, + msg: [256]u8 = undefined, + + const Self = @This(); + const HQS = SHKV * SG; + + fn init(a: std.mem.Allocator, bits: u32, gs: usize, window: usize) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a), .bits = bits, .gs = gs, .window = window }; + } + + fn initLanes(a: std.mem.Allocator, bits: u32, gs: usize, window: usize) Self { + var s = init(a, bits, gs, window); + s.lanes = true; + s.launch = &relsplit_lanes_launch; + return s; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + fn tile(self: *const Self) usize { + return if (self.lanes) 16 else NAX_BK; + } + + pub fn geometry(self: *const Self, shape: Shape) ?metal.Geometry { + const max_l: usize = if (self.bits == 0) kernels.nax_lanes else kernels.nax_quant_lanes; + if (shape.rows < 2 or shape.rows > kernels.open_rows or shape.n == 0 or shape.n > max_l or shape.k == 0) return null; + if (self.bits == 0) { + if (shape.k * SHKV * SD * 2 < 4096 or shape.rows * SHKV * SD * 2 < 4096) return null; + } else { + if (shape.k * SHKV * (SD / self.gs) < 8 or shape.n * shape.rows * SHKV * SD * 2 < 4096) return null; + } + const total = shape.k + shape.rows; + const first: usize = if (self.window > 0 and total + 1 > shape.rows + self.window) total + 1 - shape.rows - self.window else 0; + const span = total - first; + const kps: usize = @intCast(kernels.splitKps(@intCast(span), shape.n)); + if ((span + kps - 1) / kps != 1) return null; + const rows: c_int = @intCast(shape.n * shape.rows); + var g = metal.Geometry{ .grid = .{ 32 * SG, SHKV, @intCast(shape.n) }, .tg = .{ 32 * SG, 1, 1 } }; + g.out(&.{1}, .float32); + g.out(&.{1}, .float32); + g.out(&.{ 1, rows, HQS * SD }, .bfloat16); + g.unread = 0b011; + g.dtype("T", .bfloat16); + g.dtype("ST", .bfloat16); g.int("D", @as(c_int, SD)); g.int("HQ", @as(c_int, HQS)); g.int("HKV", @as(c_int, SHKV)); @@ -2189,6 +2828,7 @@ const RelSplitNax = struct { } }; + const slots_launch = metal.Launch{ .name = "msv_inkling2_relslots", .inputs = &.{ "q", "k0", "k1", "k2", "k3", "k4", "k5", "k6", "k7", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "rel", "sinks", "KEYS", "scale" }, @@ -2197,8 +2837,8 @@ const slots_launch = metal.Launch{ .contiguous = false, // sm, sl [NSG][G] and so [NSG][G][D] f32 at 8 groups of 3 heads. .tg_bytes = 4 * (2 * 8 * SG + 8 * SG * SD), - .m1 = 1024, - .m2 = 1024, + .m1 = 832, + .m2 = 832, }; /// The KV heads, the kernel's keys a threadgroup and SIMD groups. const SHKV = 8; @@ -2458,7 +3098,305 @@ const RelComb = struct { var g = metal.Geometry{ .grid = .{ 32, @intCast(lh(shape)), 1 }, .tg = .{ 32, 1, 1 } }; g.out(&.{ 1, @intCast(shape.rows), @intCast(HQ * shape.k) }, .bfloat16); g.dtype("T", .bfloat16); - g.int("D", @as(c_int, @intCast(shape.k))); + g.int("D", @as(c_int, @intCast(shape.k))); + return g; + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const rows = lh(shape); + const ns = shape.n; + const d = shape.k; + self.m = try host.uniform(a, rng, ns * rows, -3, 3, .float32); + self.l = try host.uniform(a, rng, ns * rows, 1, 20, .float32); + self.o = try host.uniform(a, rng, ns * rows * d, -20, 20, .float32); + self.gate = try host.uniform(a, rng, rows * d, 0, 1, .float32); + switch (fill) { + .random => {}, + .nonfinite => host.plant(self.o, ns * rows, d), + // Gate 4: maxes 0, sums 1, gate 1; the outputs' first half cancels the second but for small integers, so + // the true sum is small while its partial sums leave fp16's range. + .stress => { + @memset(self.m, 0); + @memset(self.l, 1); + @memset(self.gate, 1); + for (0..ns) |s| for (0..rows * d) |i| { + const at = s * rows * d + i; + self.o[at] = if (s < ns / 2) @floatFromInt(rng.intRangeAtMost(i32, 20000, 40000)) else if (s < 2 * (ns / 2)) -self.o[at - (ns / 2) * rows * d] + @as(f64, @floatFromInt(rng.intRangeAtMost(i32, 0, 3))) else 1; + }; + }, + } + if (fill != .stress) for (0..rows) |r| if (r % 3 == 1 and ns > 1) { + // A split past a row's visible keys: max at the kernel's floor, sum and output zero. + self.m[(ns - 1) * rows + r] = @as(f32, -1e30); + self.l[(ns - 1) * rows + r] = 0; + @memset(self.o[((ns - 1) * rows + r) * d ..][0..d], 0); + }; + const ml = try a.alloc(f64, 2 * ns * rows); + for (0..ns * rows) |i| { + ml[2 * i] = self.m[i]; + ml[2 * i + 1] = self.l[i]; + } + self.rig.reset(); + const n: c_int = @intCast(ns); + const lr: c_int = @intCast(rows); + self.args = .{ + try self.rig.input(.float32, &.{ n, lr, @intCast(d) }, self.o), + try self.rig.input(.float32, &.{ n, lr, 2 }, ml), + try self.rig.input(.float32, &.{@intCast(rows * d)}, self.gate), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return lh(self.shape) * self.shape.k; + } + + fn emit(self: *const Self, want: []f64, mag: ?[]f64, sim: attn.Sim) !void { + const rows = lh(self.shape); + const ns = self.shape.n; + const d = self.shape.k; + const t = try self.rig.a.alloc(f64, 2 * ns); + defer self.rig.a.free(t); + // A precise exp2 (one f32 ulp) a weight, the f32 sums, the divide. + const sums = spec.gamma(@floatFromInt(ns + 1), host.U); + for (0..rows) |r| { + var mx = -std.math.inf(f64); + for (0..ns) |s| mx = @max(mx, self.m[s * rows + r]); + for (0..d) |i| { + var num: f64 = 0; + var den: f64 = 0; + var en: f64 = 0; + var ed: f64 = 0; + for (0..ns) |s| { + const w = @exp2(self.m[s * rows + r] - mx); + const x = self.o[(s * rows + r) * d + i]; + t[s] = w * x; + t[ns + s] = w * self.l[s * rows + r]; + num += t[s]; + den += t[ns + s]; + en += @abs(t[s]) * (0x1p-23 + sums); + ed += @abs(t[ns + s]) * (0x1p-23 + sums); + } + if (sim) |x| { + num = spec.sumIn(x.acc, x.order, t[0..ns]); + den = spec.sumIn(x.acc, x.order, t[ns..]); + } + const read = num / den; + const g = self.gate[r * d + i]; + want[r * d + i] = read * g; + if (mag) |m| { + const err = (en + @abs(read) * ed) / den + host.U * @abs(read); + m[r * d + i] = if (std.math.isFinite(err)) host.allowance(err * g) else 0; + } + } + } + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + try self.emit(want, mag, null); + } + + pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { + try self.emit(out, null, .{ .acc = acc, .order = order }); + } + + fn wrapper(self: *Self) ![]const u8 { + var g = ops.Graph.init(self.rig.a, self.rig.stream()); + defer g.deinit(); + const x = self.args; + return self.rig.bytesOf(&.{try kernels.splitJoin(&g, .{ x[0], x[1] }, x[2], @intCast(self.shape.rows), .bfloat16)}); + } +}; + +// ── the drafter's Markov step ── + +/// The block's steps, the previous-token table's rows a test binds (one is read), f32 unit roundoff of a precise +/// tanh / exp (a few ulps). +const MSTEPS = 7; +const MPREV = 64; +const PRECISE = 4 * 0x1p-24; +const NONE_IDX: f64 = 0xffffffff; +/// The release's logit soft cap. +const MCAP = 30.0; + +/// `x` under the soft cap, as the kernels' precise tanh gives it. +fn capped(x: f64) f64 { + return MCAP * std.math.tanh(x / MCAP); +} + +fn markovLaunch(comptime file: [:0]const u8, comptime ins: []const [*:0]const u8, comptime outs: []const [*:0]const u8, comptime header: bool, comptime tg_bytes: u32) metal.Launch { + return .{ .name = "msv_inkling2_" ++ file, .inputs = ins, .outputs = outs, .source = source("plugins/inkling2/kernels/" ++ file ++ ".metal"), .header = if (header) source("plugins/inkling2/kernels/markov_header.metal") else "", .tg_bytes = tg_bytes, .m1 = 1024, .m2 = 1024 }; +} + +const mk_rnn_launch = markovLaunch("markov_rnn", &.{ "W", "B", "ST", "PREV", "ROWS", "NEW", "TOK", "AT" }, &.{"P"}, false, 0); +const mk_fold_launch = markovLaunch("markov_fold", &.{ "P", "FOLD", "FB", "BASE", "AT", "CAP" }, &.{ "PM", "PI", "PS" }, true, 4 * (256 + 3 * 8)); +const mk_pick_launch = markovLaunch("markov_pick", &.{ "PM", "PI", "PS", "P", "ST", "CAP" }, &.{ "TOKN", "CONF", "NST" }, true, 4 * 3 * 8); +const mk_fold_batch_launch = markovLaunch("markov_fold_batch", &.{ "P", "FOLD", "FB", "BASE", "AT", "CAP" }, &.{ "PM", "PI", "PS" }, true, 4 * (8 * 256 + 3 * 8)); +const mk_pick_batch_launch = markovLaunch("markov_pick_batch", &.{ "PM", "PI", "PS", "P", "ST", "CAP" }, &.{ "TOKN", "CONF", "NST" }, true, 4 * 3 * 8); +const mk_pick_sample_launch = markovLaunch("markov_pick_sample", &.{ "PM", "PI", "P", "ST", "CAP", "LPARAMS", "SEEDS", "AT" }, &.{ "TOKN", "CANDS", "PROBS", "DRAW", "NST" }, true, 4 * (2 * 8 + 2 * 16 + 2)); + +fn cint(x: usize) c_int { + return @intCast(x); +} + +const mk_step_rnn_launch = markovLaunch("markov_step_rnn", &.{ "W", "KAPPA", "ST", "PREV", "TOK", "AT" }, &.{"P"}, false, 0); +const mk_fold_q8_launch = markovLaunch("markov_fold_q8_row", &.{ "P", "FQ", "FSC", "BASE", "AT", "CAP" }, &.{ "PM", "PI", "PS" }, true, 4 * (256 + 64 + 8 + 8 + 2)); + +/// Precomputed-kappa Markov RNN step (`markov_step_rnn.metal`): n = rank. +const MarkovStepRnn = struct { + rig: metal.Rig, + launch: *const metal.Launch = &mk_step_rnn_launch, + arena: std.heap.ArenaAllocator, + shape: Shape = undefined, + w: []f64 = &.{}, + kappa: []f64 = &.{}, + st: []f64 = &.{}, + prev: []f64 = &.{}, + tok: usize = 0, + at: usize = 0, + args: [6]mlx.mlx_array = undefined, + + const Self = @This(); + + fn init(a: std.mem.Allocator) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a) }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(_: *const Self, shape: Shape) ?metal.Geometry { + if (shape.n == 0 or 3 * shape.n * 32 % 256 != 0) return null; + var g = metal.Geometry{ .grid = .{ cint(32 * 3 * shape.n), 1, 1 }, .tg = .{ 256, 1, 1 } }; + g.out(&.{cint(3 * shape.n)}, .float32); + g.dtype("T", .bfloat16); + g.int("R", cint(shape.n)); + return g; + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const r = shape.n; + self.w = try host.uniform(a, rng, 3 * r * (2 * r), -0.05, 0.05, .bfloat16); + self.kappa = try host.uniform(a, rng, MSTEPS * 3 * r, -0.5, 0.5, .float32); + self.st = try host.uniform(a, rng, r, -1, 1, .bfloat16); + self.prev = try host.uniform(a, rng, MPREV * r, -0.5, 0.5, .bfloat16); + self.tok = rng.uintLessThan(usize, MPREV); + self.at = rng.uintLessThan(usize, MSTEPS); + if (fill == .nonfinite) host.plant(self.w, 3 * r, 2 * r); + self.rig.reset(); + self.args = .{ + try self.rig.input(.bfloat16, &.{ cint(3 * r), cint(2 * r) }, self.w), + try self.rig.input(.float32, &.{ MSTEPS, cint(3 * r) }, self.kappa), + try self.rig.input(.bfloat16, &.{ 1, 1, cint(r) }, self.st), + try self.rig.input(.bfloat16, &.{ MPREV, cint(r) }, self.prev), + try self.rig.input(.int32, &.{1}, &.{@floatFromInt(self.tok)}), + try self.rig.input(.int32, &.{1}, &.{@floatFromInt(self.at)}), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return 3 * self.shape.n; + } + + fn emit(self: *const Self, want: []f64, mag: ?[]f64, sim: attn.Sim) !void { + const r = self.shape.n; + const n = 2 * r; + const t = try self.rig.a.alloc(f64, n); + defer self.rig.a.free(t); + for (want, 0..) |*w, row| { + var abs: f64 = 0; + for (t, 0..) |*x, c| { + const fv = if (c < r) self.st[c] else self.prev[self.tok * r + (c - r)]; + x.* = self.w[row * n + c] * fv; + abs += @abs(x.*); + } + const s = if (sim) |x| spec.sumIn(x.acc, x.order, t) else host.sum(t); + const k = self.kappa[self.at * 3 * r + row]; + const res = bf(.{ .v = s + k, .e = spec.gamma(@floatFromInt(n + 1), host.U) * (abs + @abs(k)) }); + w.* = res.v; + if (mag) |m| m[row] = if (std.math.isFinite(res.e)) host.allowance(res.e) else 0; + } + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + try self.emit(want, mag, null); + } + + pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { + try self.emit(out, null, .{ .acc = acc, .order = order }); + } + + fn wrapper(self: *Self) ![]const u8 { + var g = ops.Graph.init(self.rig.a, self.rig.stream()); + defer g.deinit(); + const x = self.args; + return self.rig.bytesOf(&.{try kernels.markovStepRnn(&g, x[0], x[1], x[2], x[3], x[4], x[5])}); + } +}; + +fn foldQ8Groups(shape: Shape) usize { + return (shape.k + 63) / 64; +} + +/// Coalesced per-vocab-row Q8 Markov fold (`markov_fold_q8_row.metal`, MARKOV_Q8): rows = rank, n = padded V, k = real vocab. +const MarkovFoldQ8 = struct { + rig: metal.Rig, + launch: *const metal.Launch = &mk_fold_q8_launch, + arena: std.heap.ArenaAllocator, + shape: Shape = undefined, + p: []f64 = &.{}, + fq: []f64 = &.{}, + fsc: []f64 = &.{}, + base: []f64 = &.{}, + at: usize = 0, + logit: []host.Val = &.{}, + note: [200]u8 = undefined, + args: [6]mlx.mlx_array = undefined, + + const Self = @This(); + + fn init(a: std.mem.Allocator) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a) }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(_: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.rows % 4 != 0 or shape.k == 0 or shape.k > shape.n) return null; + const ng = cint(foldQ8Groups(shape)); + var g = metal.Geometry{ .grid = .{ ng * 256, 1, 1 }, .tg = .{ 256, 1, 1 } }; + g.out(&.{ng}, .float32); + g.out(&.{ng}, .uint32); + g.out(&.{ng}, .float32); + g.dtype("T", .bfloat16); + g.int("R", cint(shape.rows)); + g.int("VOCAB", cint(shape.k)); return g; } @@ -2469,46 +3407,33 @@ const RelComb = struct { const a = self.arena.allocator(); var prng = std.Random.DefaultPrng.init(seed); const rng = prng.random(); - const rows = lh(shape); - const ns = shape.n; - const d = shape.k; - self.m = try host.uniform(a, rng, ns * rows, -3, 3, .float32); - self.l = try host.uniform(a, rng, ns * rows, 1, 20, .float32); - self.o = try host.uniform(a, rng, ns * rows * d, -20, 20, .float32); - self.gate = try host.uniform(a, rng, rows * d, 0, 1, .float32); + const r = shape.rows; + const v = shape.n; + self.p = try host.uniform(a, rng, 3 * r, -2, 2, .float32); + self.fq = try a.alloc(f64, v * r); + for (self.fq) |*x| x.* = @floatFromInt(rng.intRangeAtMost(i8, -127, 127)); + self.fsc = try host.uniform(a, rng, v, 0.0005, 0.003, .float32); + self.base = try host.uniform(a, rng, MSTEPS * v, -8, 8, .float32); + self.at = rng.uintLessThan(usize, MSTEPS); + const row = self.base[self.at * v ..][0..v]; switch (fill) { .random => {}, - .nonfinite => host.plant(self.o, ns * rows, d), - // Gate 4: maxes 0, sums 1, gate 1; the outputs' first half cancels the second but for small integers, so - // the true sum is small while its partial sums leave fp16's range. - .stress => { - @memset(self.m, 0); - @memset(self.l, 1); - @memset(self.gate, 1); - for (0..ns) |s| for (0..rows * d) |i| { - const at = s * rows * d + i; - self.o[at] = if (s < ns / 2) @floatFromInt(rng.intRangeAtMost(i32, 20000, 40000)) else if (s < 2 * (ns / 2)) -self.o[at - (ns / 2) * rows * d] + @as(f64, @floatFromInt(rng.intRangeAtMost(i32, 0, 3))) else 1; - }; + .nonfinite => for ([_]usize{ 5, 64 + 9, 128 + 1 }, [_]f64{ std.math.nan(f64), std.math.inf(f64), -std.math.inf(f64) }) |c, x| { + if (c < shape.k) row[c] = x; + }, + .stress => for (0..foldQ8Groups(shape)) |g| { + row[@min(shape.k - 1, g * 64 + rng.uintLessThan(usize, 64))] = 48; }, } - if (fill != .stress) for (0..rows) |r| if (r % 3 == 1 and ns > 1) { - // A split past a row's visible keys: max at the kernel's floor, sum and output zero. - self.m[(ns - 1) * rows + r] = @as(f32, -1e30); - self.l[(ns - 1) * rows + r] = 0; - @memset(self.o[((ns - 1) * rows + r) * d ..][0..d], 0); - }; - const ml = try a.alloc(f64, 2 * ns * rows); - for (0..ns * rows) |i| { - ml[2 * i] = self.m[i]; - ml[2 * i + 1] = self.l[i]; - } + self.logit = try a.alloc(host.Val, shape.k); self.rig.reset(); - const n: c_int = @intCast(ns); - const lr: c_int = @intCast(rows); self.args = .{ - try self.rig.input(.float32, &.{ n, lr, @intCast(d) }, self.o), - try self.rig.input(.float32, &.{ n, lr, 2 }, ml), - try self.rig.input(.float32, &.{@intCast(rows * d)}, self.gate), + try self.rig.input(.float32, &.{cint(3 * r)}, self.p), + try self.rig.input(.int8, &.{ cint(v), cint(r) }, self.fq), + try self.rig.input(.float32, &.{cint(v)}, self.fsc), + try self.rig.input(.float32, &.{ 1, MSTEPS, cint(v) }, self.base), + try self.rig.input(.int32, &.{1}, &.{@floatFromInt(self.at)}), + try self.rig.input(.float32, &.{1}, &.{MCAP}), }; return true; } @@ -2518,96 +3443,114 @@ const RelComb = struct { } pub fn count(self: *const Self) usize { - return lh(self.shape) * self.shape.k; + return 3 * foldQ8Groups(self.shape); } - fn emit(self: *const Self, want: []f64, mag: ?[]f64, sim: attn.Sim) !void { - const rows = lh(self.shape); - const ns = self.shape.n; - const d = self.shape.k; - const t = try self.rig.a.alloc(f64, 2 * ns); - defer self.rig.a.free(t); - // A precise exp2 (one f32 ulp) a weight, the f32 sums, the divide. - const sums = spec.gamma(@floatFromInt(ns + 1), host.U); - for (0..rows) |r| { - var mx = -std.math.inf(f64); - for (0..ns) |s| mx = @max(mx, self.m[s * rows + r]); - for (0..d) |i| { - var num: f64 = 0; - var den: f64 = 0; - var en: f64 = 0; - var ed: f64 = 0; - for (0..ns) |s| { - const w = @exp2(self.m[s * rows + r] - mx); - const x = self.o[(s * rows + r) * d + i]; - t[s] = w * x; - t[ns + s] = w * self.l[s * rows + r]; - num += t[s]; - den += t[ns + s]; - en += @abs(t[s]) * (0x1p-23 + sums); - ed += @abs(t[ns + s]) * (0x1p-23 + sums); - } - if (sim) |x| { - num = spec.sumIn(x.acc, x.order, t[0..ns]); - den = spec.sumIn(x.acc, x.order, t[ns..]); - } - const read = num / den; - const g = self.gate[r * d + i]; - want[r * d + i] = read * g; - if (mag) |m| { - const err = (en + @abs(read) * ed) / den + host.U * @abs(read); - m[r * d + i] = if (std.math.isFinite(err)) host.allowance(err * g) else 0; - } + fn logits(self: *Self, sim: attn.Sim) !void { + const r = self.shape.rows; + const v = self.shape.n; + const a = self.rig.a; + const lat = try a.alloc(host.Val, r); + defer a.free(lat); + for (lat, 0..) |*l, i| { + const t = std.math.tanh(self.p[2 * r + i]); + l.* = bf(.{ .v = t, .e = PRECISE * @abs(t) }); + } + const t = try a.alloc(f64, r); + defer a.free(t); + for (self.logit, 0..) |*o, c| { + var abs: f64 = 0; + var flips: f64 = 0; + for (t, lat, 0..) |*x, l, i| { + x.* = l.v * self.fq[c * r + i]; + abs += @abs(x.*); + flips += l.e * @abs(self.fq[c * r + i]); + } + const s = if (sim) |x| spec.sumIn(x.acc, x.order, t) else host.sum(t); + const scaled = s * self.fsc[c]; + const se = (spec.gamma(@floatFromInt(r), host.U) * abs + flips) * @abs(self.fsc[c]) + host.U * @abs(scaled); + const x = self.base[self.at * v + c] + scaled; + o.* = .{ .v = x, .e = se + host.U * @abs(x) }; + } + } + + fn group(self: *const Self, g: usize) struct { at: usize, e: f64, sum: f64 } { + const lo = g * 64; + const hi = @min(self.shape.k, lo + 64); + var best = lo; + var e: f64 = 0; + for (lo..hi) |c| { + if (better(self.logit[c].v, c, self.logit[best].v, best)) best = c; + if (std.math.isFinite(self.logit[c].e)) e = @max(e, self.logit[c].e); + } + var sum: f64 = 0; + for (lo..hi) |c| sum += @exp(capped(self.logit[c].v) - capped(self.logit[best].v)); + return .{ .at = best, .e = e, .sum = sum }; + } + + fn emit(self: *Self, want: []f64, mag: ?[]f64, sim: attn.Sim) !void { + try self.logits(sim); + const ng = foldQ8Groups(self.shape); + for (0..ng) |g| { + const x = self.group(g); + want[g] = self.logit[x.at].v; + want[ng + g] = @floatFromInt(x.at); + want[2 * ng + g] = x.sum; + if (mag) |m| { + m[g] = host.allowance(x.e); + m[ng + g] = 0; + m[2 * ng + g] = host.allowance(x.sum * (2 * x.e + PRECISE + spec.gamma(64, host.U))); } } } pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { - try self.emit(want, mag, null); + try @constCast(self).emit(want, mag, null); } pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { - try self.emit(out, null, .{ .acc = acc, .order = order }); + try @constCast(self).emit(out, null, .{ .acc = acc, .order = order }); + } + + fn fail(self: *Self, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.bufPrint(&self.note, fmt, args) catch "a group breaks the rule"; + } + + pub fn check(self: *Self, _: spec.Gate) !?[]const u8 { + try self.logits(null); + const bytes = self.rig.outputBytes(); + const ng = foldQ8Groups(self.shape); + for (0..ng) |g| { + const x = self.group(g); + const pm = spec.read(.f32, bytes, g); + const pi: usize = @intFromFloat(spec.read(.u32, bytes[4 * ng ..], g)); + const ps = spec.read(.f32, bytes[8 * ng ..], g); + const top = self.logit[x.at]; + if (!std.math.isFinite(top.v)) { + if (pi != x.at) return self.fail("group {d}: column {d} where {d} leads", .{ g, pi, x.at }); + if (std.math.isNan(top.v) != std.math.isNan(pm) or (!std.math.isNan(top.v) and pm != top.v)) return self.fail("group {d}: max {d} where float64 gives {d}", .{ g, pm, top.v }); + if (std.math.isNan(x.sum) != std.math.isNan(ps)) return self.fail("group {d}: sum {d} where float64 gives {d}", .{ g, ps, x.sum }); + continue; + } + if (pi < g * 64 or pi >= @min(self.shape.k, (g + 1) * 64)) return self.fail("group {d}: column {d} outside it", .{ g, pi }); + const mine = self.logit[pi]; + if (!(mine.v + mine.e + x.e >= top.v)) return self.fail("group {d}: column {d} ({d}) where {d} leads ({d})", .{ g, pi, mine.v, x.at, top.v }); + if (!(@abs(pm - mine.v) <= mine.e + 0x1p-24 * @abs(mine.v))) return self.fail("group {d}: max {d} where its column's logit is {d}", .{ g, pm, mine.v }); + var sum: f64 = 0; + for (g * 64..@min(self.shape.k, (g + 1) * 64)) |c| sum += @exp(capped(self.logit[c].v) - capped(mine.v)); + if (!(@abs(ps - sum) <= sum * (2 * x.e + PRECISE + spec.gamma(64, host.U)))) return self.fail("group {d}: sum {d} where float64 gives {d}", .{ g, ps, sum }); + } + return null; } fn wrapper(self: *Self) ![]const u8 { var g = ops.Graph.init(self.rig.a, self.rig.stream()); defer g.deinit(); const x = self.args; - return self.rig.bytesOf(&.{try kernels.splitJoin(&g, .{ x[0], x[1] }, x[2], @intCast(self.shape.rows), .bfloat16)}); + return self.rig.bytesOf(&(try kernels.markovFoldQ8Row(&g, x[0], x[1], x[2], x[3], x[4], @intCast(self.shape.k), x[5], .bfloat16))); } }; -// ── the drafter's Markov step ── - -/// The block's steps, the previous-token table's rows a test binds (one is read), f32 unit roundoff of a precise -/// tanh / exp (a few ulps). -const MSTEPS = 7; -const MPREV = 64; -const PRECISE = 4 * 0x1p-24; -const NONE_IDX: f64 = 0xffffffff; -/// The release's logit soft cap. -const MCAP = 30.0; - -/// `x` under the soft cap, as the kernels' precise tanh gives it. -fn capped(x: f64) f64 { - return MCAP * std.math.tanh(x / MCAP); -} - -fn markovLaunch(comptime file: [:0]const u8, comptime ins: []const [*:0]const u8, comptime outs: []const [*:0]const u8, comptime header: bool, comptime tg_bytes: u32) metal.Launch { - return .{ .name = "msv_inkling2_" ++ file, .inputs = ins, .outputs = outs, .source = source("plugins/inkling2/kernels/" ++ file ++ ".metal"), .header = if (header) source("plugins/inkling2/kernels/markov_header.metal") else "", .tg_bytes = tg_bytes, .m1 = 1024, .m2 = 1024 }; -} - -const mk_rnn_launch = markovLaunch("markov_rnn", &.{ "W", "B", "ST", "PREV", "ROWS", "NEW", "TOK", "AT" }, &.{"P"}, false, 0); -const mk_fold_launch = markovLaunch("markov_fold", &.{ "P", "FOLD", "FB", "BASE", "AT", "CAP" }, &.{ "PM", "PI", "PS" }, true, 4 * (256 + 3 * 8)); -const mk_pick_launch = markovLaunch("markov_pick", &.{ "PM", "PI", "PS", "P", "ST", "CAP" }, &.{ "TOKN", "CONF", "NST" }, true, 4 * 3 * 8); -const mk_fold_batch_launch = markovLaunch("markov_fold_batch", &.{ "P", "FOLD", "FB", "BASE", "AT", "CAP" }, &.{ "PM", "PI", "PS" }, true, 4 * (8 * 256 + 3 * 8)); -const mk_pick_batch_launch = markovLaunch("markov_pick_batch", &.{ "PM", "PI", "PS", "P", "ST", "CAP" }, &.{ "TOKN", "CONF", "NST" }, true, 4 * 3 * 8); -const mk_pick_sample_launch = markovLaunch("markov_pick_sample", &.{ "PM", "PI", "P", "ST", "CAP", "LPARAMS", "SEEDS", "AT" }, &.{ "TOKN", "CANDS", "PROBS", "DRAW", "NST" }, true, 4 * (2 * 8 + 2 * 16 + 2)); - -fn cint(x: usize) c_int { - return @intCast(x); -} /// `x` rounded to bf16 where the device holds it within `e` of it. fn bf(x: host.Val) host.Val { @@ -3878,7 +4821,8 @@ fn routerDepth(shape: Shape) usize { return shape.k; } -const norm_launch = metal.Launch{ .name = "msv_inkling2_norm", .inputs = &.{ "Y", "NW0", "NW1", "NW2", "RT", "PR" }, .outputs = &.{ "X", "SCORES" }, .source = source("plugins/inkling2/kernels/norm.metal"), .tg_bytes = 4 * (768 / 32) * 3, .m1 = 1024, .m2 = 1024, .adapts = true }; +const norm_launch = metal.Launch{ .name = "msv_inkling2_norm", .inputs = &.{ "Y", "NW0", "NW1", "NW2", "RT", "PR" }, .outputs = &.{ "X", "SCORES" }, .source = source("plugins/inkling2/kernels/norm_step.metal"), .tg_bytes = 4 * (768 / 32) * 3, .m1 = 1024, .m2 = 1024, .adapts = true }; +const norm_row_launch = metal.Launch{ .name = "msv_inkling2_norm_row", .inputs = &.{ "Y", "NW0", "NW1", "NW2", "RT", "PR" }, .outputs = &.{ "X", "SCORES" }, .source = source("plugins/inkling2/kernels/norm.metal"), .tg_bytes = 4 * (768 / 32) * 3, .m1 = 1024, .m2 = 1024, .adapts = true }; /// The model's norm epsilon, as the kernel reads it. const NORM_EPS: f32 = 1e-6; @@ -3891,13 +4835,15 @@ fn sum64(x: []const f64) f64 { /// The visit's weighted RMS norms (`kernels.norm`): a later pass's three attention inputs, or the MLP input with the /// router's scores over it; rows x streams x hidden. -fn Norm(comptime dt: mlx.mlx_dtype, comptime routed: bool) type { +/// `one_tg`: the row norm's grid, one threadgroup a row (`kernels.streamRow`, a prompt's rows); else a step's grid, +/// D / TG threadgroups a row, at any width. +fn Norm(comptime dt: mlx.mlx_dtype, comptime routed: bool, comptime one_tg: bool) type { return struct { const Self = @This(); const J: usize = if (routed) 1 else 3; const E: usize = if (routed) EXPERTS else 0; rig: metal.Rig, - launch: *const metal.Launch = &norm_launch, + launch: *const metal.Launch = if (one_tg) &norm_row_launch else &norm_launch, arena: std.heap.ArenaAllocator, shape: Shape = undefined, /// `y` `[J, S, D]`, `nw` `[D]` each, `rt` `[E, D]`. @@ -3920,7 +4866,7 @@ fn Norm(comptime dt: mlx.mlx_dtype, comptime routed: bool) type { const tg = kernels.streamGroup(@intCast(shape.k)) orelse return null; const d: c_int = @intCast(shape.k); const extra: c_int = if (routed) @divTrunc(@as(c_int, E) * 32 + tg - 1, tg) * tg else 0; - var geo = metal.Geometry{ .grid = .{ d + extra, @intCast(shape.rows), 1 }, .tg = .{ tg, 1, 1 } }; + var geo = metal.Geometry{ .grid = .{ (if (one_tg) tg else d) + extra, @intCast(shape.rows), 1 }, .tg = .{ tg, 1, 1 } }; geo.out(&.{ @intCast(J), @intCast(shape.rows), d }, dt); if (routed) geo.out(&.{ @intCast(shape.rows), @intCast(E) }, .float32) else { geo.out(&.{1}, .float32); @@ -3931,6 +4877,7 @@ fn Norm(comptime dt: mlx.mlx_dtype, comptime routed: bool) type { geo.int("D", d); geo.int("J", @as(c_int, J)); geo.int("E", @as(c_int, E)); + if (one_tg) geo.int("ROW", 1); return geo; } @@ -3990,6 +4937,8 @@ fn Norm(comptime dt: mlx.mlx_dtype, comptime routed: bool) type { defer a.free(normed); const terms = try a.alloc(f64, d); defer a.free(terms); + const flips = try a.alloc(f64, d); + defer a.free(flips); for (0..J) |j| for (0..s) |r| { const row = self.y[(j * s + r) * d ..][0..d]; for (sq, row) |*q, v| q.* = v * v; @@ -3999,13 +4948,27 @@ fn Norm(comptime dt: mlx.mlx_dtype, comptime routed: bool) type { if (!routed or j != 0) continue; // The router reads the normed row as the stream holds it. for (normed, row, self.nw[0]) |*n, v, w| n.* = spec.roundTo(elemOf(dt), v * inv * w); + // The kernel rounds its own normed row: y times its f32 rsqrt of an f32 sum, times the weight. An + // element within that path's relative error `eps` of a rounding midpoint can round to the other + // neighbour; `flips` holds each such element's step (0 elsewhere), and every score's bound takes + // those steps times the router's weights on top of its sum's. + const g24 = spec.gamma(@floatFromInt(d), 0x1p-24); + const eps = g24 + 4 * 0x1p-24; + for (flips, row, self.nw[0], normed) |*f, v, w, n| { + const x = v * inv * w; + const lo = spec.roundTo(elemOf(dt), x * (1 - eps)); + const hi = spec.roundTo(elemOf(dt), x * (1 + eps)); + f.* = @max(@abs(lo - n), @abs(hi - n)); + } for (0..E) |ex| { for (terms, normed, self.rt[ex * d ..][0..d]) |*t, n, q| t.* = n * q; want[nx + r * E + ex] = if (acc) |ac| spec.sumIn(ac, order, terms) else sum64(terms); if (mag) |m| { var abs: f64 = 0; for (terms) |t| abs += @abs(t); - m[nx + r * E + ex] = if (std.math.isFinite(abs)) abs else 0; + var step: f64 = 0; + for (flips, self.rt[ex * d ..][0..d]) |f, q| step += f * @abs(q); + m[nx + r * E + ex] = if (std.math.isFinite(abs) and std.math.isFinite(step)) abs + step / g24 else 0; } } }; @@ -4030,7 +4993,7 @@ fn Norm(comptime dt: mlx.mlx_dtype, comptime routed: bool) type { cfg.num_experts = @intCast(EXPERTS); cfg.rms_norm_eps = NORM_EPS; const x = self.args; - const o = try kernels.norm(&g, &cfg, x[0], .{ x[1], x[2], x[3] }, @intCast(J), dt, if (routed) x[4] else null); + const o = try kernels.normAt(&g, if (one_tg) .prompt else .step, &cfg, x[0], .{ x[1], x[2], x[3] }, @intCast(J), dt, if (routed) x[4] else null); return self.rig.bytesOf(if (routed) &.{ o[0], o[1] } else &.{o[0]}); } }; @@ -4054,6 +5017,12 @@ fn name(comptime what: []const u8, comptime dt: mlx.mlx_dtype) []const u8 { return what ++ (if (dt == .bfloat16) " bf16" else " f32"); } +/// The Markov kernels' gate-4 sums. +const markov_sums: spec.Sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "the outputs round to bf16 or pass an exp: the stress inputs check the fp32 sums within the float64 bound" }; + +/// The split reads' gate-4 sums: the softmax's exp leaves no sum exact. +const split_sums: spec.Sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "the softmax's exp leaves no sum exact: the stress inputs check the fp32 sums within the float64 bound" }; + pub fn register(set: *kc.Set) !void { try set.add(Act, .init(set.a), .{ .name = "inkling2 act bf16", @@ -4135,7 +5104,6 @@ pub fn register(set: *kc.Set) !void { .served = &.{ .{ .rows = 8, .n = 1031, .k = 1024 }, .{ .rows = 8, .n = 4104, .k = 0 }, .{ .rows = kernels.small_rows, .n = 1055, .k = 1024 }, .{ .rows = 2, .n = 2, .k = 1024 } }, }, null); } - const split_sums: spec.Sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "the softmax's exp leaves no sum exact: the stress inputs check the fp32 sums within the float64 bound" }; // 4 and 8 rows behind a sliding layer's window and a global layer's keys; 8 KV heads of 3 query heads. try set.add(RelSplit, .init(set.a, 1024, false), .{ .name = "inkling2 relsplit bf16 (sliding 1024)", @@ -4187,7 +5155,7 @@ pub fn register(set: *kc.Set) !void { }, null); // A prompt's rows on the tensor unit: a sliding window's tiles and a global layer's, both dtypes the kernel serves. inline for (.{ .{ mlx.mlx_dtype.bfloat16, "bf16" }, .{ mlx.mlx_dtype.float16, "f16" } }) |d| inline for (.{ .{ 1024, "sliding 1024" }, .{ 0, "global" } }) |w| { - try set.add(RelNax, .init(set.a, d[0], w[0]), .{ + try set.add(RelattnNax, .init(set.a, d[0], w[0]), .{ .name = "inkling2 relattn_nax " ++ d[1] ++ " (" ++ w[1] ++ ")", .accum = .none, .depth = host.depthOne, @@ -4219,7 +5187,6 @@ pub fn register(set: *kc.Set) !void { .served = &.{ .{ .rows = 8, .n = 1031, .k = 1024 }, .{ .rows = 8, .n = 4104, .k = 0 }, .{ .rows = 2, .n = 300, .k = 0 } }, .sums = split_sums, }, null); - const markov_sums: spec.Sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "the outputs round to bf16 or pass an exp: the stress inputs check the fp32 sums within the float64 bound" }; // The release's drafter: rank 256, hidden 2304, 201024 head rows (the fold's real vocab 200058, 98 groups). try set.add(MarkovRnn, .init(set.a), .{ .name = "inkling2 markov_rnn bf16", @@ -4323,7 +5290,7 @@ pub fn register(set: *kc.Set) !void { .served = &.{ .{ .rows = 8, .n = EXPERTS, .k = 2304 }, .{ .rows = 2, .n = EXPERTS, .k = 2304 }, .{ .rows = kernels.small_rows, .n = EXPERTS, .k = 2304 } }, }, null); inline for (dtypes) |dt| { - try set.add(Norm(dt, false), .init(set.a), .{ + try set.add(Norm(dt, false, false), .init(set.a), .{ .name = name("inkling2 norm (three streams)", dt), .accum = .f32, .depth = rowLength, @@ -4334,7 +5301,7 @@ pub fn register(set: *kc.Set) !void { .served = &.{ .{ .rows = 1, .n = 3, .k = 2304 }, .{ .rows = 8, .n = 3, .k = 2304 }, .{ .rows = 512, .n = 3, .k = 2304 } }, .sums = .{ .f16 = 32, .bf16 = 0, .why = "positive squares: a pairwise bf16 sum stays near the output's rounding" }, }, null); - try set.add(Norm(dt, true), .init(set.a), .{ + try set.add(Norm(dt, true, false), .init(set.a), .{ .name = name("inkling2 norm (MLP input + router)", dt), .accum = .f32, .depth = rowLength, @@ -4346,11 +5313,87 @@ pub fn register(set: *kc.Set) !void { .sums = .{ .f16 = 32, .bf16 = 0, .why = "positive squares: a pairwise bf16 sum stays near the output's rounding" }, }, null); } + try set.add(PrepStrided, .init(set.a), .{ + .name = "inkling2 prep bf16 (a joined projection's parts in place)", + .accum = .none, + .depth = none, + .out = .bf16, + .outs = prep_outs, + .replaces = "prep on contiguous copies", + .nan = .{ .stated = "the contiguous kernel's bytes" }, + // A draft verify's 8 rows, a sliding and a global one-row read, a short prompt chunk. + .served = &.{ .{ .rows = 8, .n = 0, .k = R }, .{ .rows = 1, .n = 1024, .k = R }, .{ .rows = 1, .n = 4104, .k = R }, .{ .rows = 64, .n = 0, .k = R } }, + }, null); + // The tiled gates: a prompt chunk's three attention-input gates at 64-row tiles, 128 rows and a ragged 100. + inline for (.{ .float32, .bfloat16 }) |wt| try set.add(GateMm, .init(set.a, wt), .{ + .name = if (wt == .float32) "inkling2 gate_mm (a prompt chunk, f32 projections)" else "inkling2 gate_mm (a prompt chunk, bf16 projections)", + .accum = .f32, + .depth = rankDepth, + .ops = 6, + .out = .f32, + .served = &.{ .{ .rows = 3, .n = 128, .k = 2304 }, .{ .rows = 3, .n = 100, .k = 2304 } }, + .sums = .{ .f16 = 16, .exact = false, .why = "a half sum drops only the few small terms it meets beside the one" }, + }, null); // Every affine width a pack's attention may carry at g64, 4-bit at g32 and g128, and the release's dense bf16. + // The row norm: a prompt chunk's three attention-input norms and its MLP input with the router, one threadgroup + // a row. + try set.add(Norm(.bfloat16, false, true), .init(set.a), .{ + .name = "inkling2 norm bf16 (three streams, one threadgroup a row)", + .accum = .f32, + .depth = rowLength, + .ops = 6, + .out = .bf16, + .served = &.{ .{ .rows = 64, .n = 3, .k = 2304 }, .{ .rows = 512, .n = 3, .k = 2304 } }, + .sums = .{ .f16 = 32, .bf16 = 0, .why = "positive squares: a pairwise bf16 sum stays near the output's rounding" }, + }, null); + try set.add(Norm(.bfloat16, true, true), .init(set.a), .{ + .name = "inkling2 norm bf16 (MLP input + router, one threadgroup a row)", + .accum = .f32, + .depth = rowLength, + .ops = 6, + .out = .bf16, + .outs = &.{ .{ .elem = .bf16, .count = normsOf }, .{ .elem = .f32, .count = scoresOf } }, + .served = &.{ .{ .rows = 64, .n = 1, .k = 2304 }, .{ .rows = 512, .n = 1, .k = 2304 } }, + .sums = .{ .f16 = 32, .bf16 = 0, .why = "positive squares: a pairwise bf16 sum stays near the output's rounding" }, + }, null); + // The tensor-unit prompt read, a sliding (1024) and a global layer: 9 ragged rows behind 1,291 keys (one simdgroup + // of four holds rows), 100 rows (a remainder of 64) and 256 (whole threadgroups), ragged keys; a global layer's 9 + // rows at 16,384 keys (a long prompt's chunk, past the bias's 1,024 distances). + inline for (.{ 1024, 0 }) |window| try set.add(RelNax, .init(set.a, window), .{ + .name = if (window > 0) "inkling2 relnax bf16 (in-read bias, sliding 1024)" else "inkling2 relnax bf16 (in-read bias, global)", + .nax = true, + .accum = .f32, + .depth = host.depthOne, + .out = .bf16, + .tiles = .{ .{}, .{ .size = NBQ, .min = 2 }, .{} }, + .served = if (window > 0) &.{ .{ .rows = 8, .n = 9, .k = 1300 }, .{ .rows = 8, .n = 100, .k = 1123 }, .{ .rows = 8, .n = 256, .k = 1279 } } else &.{ .{ .rows = 8, .n = 9, .k = 1300 }, .{ .rows = 8, .n = 100, .k = 1200 }, .{ .rows = 8, .n = 256, .k = 1290 }, .{ .rows = 8, .n = 9, .k = 16384 } }, + .sums = .{ .exact = false }, + }, null); inline for (.{ 2, 3, 4, 5, 6, 8 }) |bits| try set.add(OProj, .init(set.a, bits, 64), oprojSpec(std.fmt.comptimePrint("inkling2 oproj bf16 ({d}-bit g64)", .{bits}), 64, .{}), null); try set.add(OProj, .init(set.a, 4, 32), oprojSpec("inkling2 oproj bf16 (4-bit g32)", 32, .{ .f16 = 40, .why = "stress codes under 16 in groups of 32: an fp16 sum misses by ~45x, short of 100x but far past fp32's exact sums" }), null); try set.add(OProj, .init(set.a, 4, 128), oprojSpec("inkling2 oproj bf16 (4-bit g128)", 128, .{}), null); try set.add(OProj, .init(set.a, 0, 16), oprojSpec("inkling2 oproj bf16 (dense)", 16, .{}), null); + // MARKOV_Q8's two kernels (the step's RNN over the precomputed context, the 8-bit fold). + try set.add(MarkovStepRnn, .init(set.a), .{ + .name = "inkling2 markov_step_rnn bf16", + .accum = .f32, + .depth = host.depthOne, + .out = .f32, + .served = &.{.{ .rows = 1, .n = 256, .k = 1 }}, + .sums = markov_sums, + }, null); + try set.add(MarkovFoldQ8, .init(set.a), .{ + .name = "inkling2 markov_fold_q8_row bf16", + .accum = .f32, + .depth = host.depthOne, + .out = .f32, + .outs = &.{ .{ .elem = .f32, .count = foldQ8Groups }, .{ .elem = .u32, .count = foldQ8Groups }, .{ .elem = .f32, .count = foldQ8Groups } }, + .nan = .{ .stated = "MLX's argmax order: a NaN logit is a group's pick, its max and sum NaN" }, + .served = &.{ .{ .rows = 256, .n = 4096, .k = 4000 }, .{ .rows = 256, .n = 512, .k = 512 } }, + .sums = markov_sums, + }, null); + try rounds_contract.register(set); + try trunk_contract.register(set); // NAX verify reads: dense (BITS=0, up to 4 lanes) and affine 4/8-bit across g32/g64/g128 (up to 2 lanes), sliding and global. const dense_served = [_]Shape{ .{ .rows = 8, .n = 1, .k = 40 }, .{ .rows = 4, .n = 4, .k = 32 } }; const qkv_served = [_]Shape{ .{ .rows = 8, .n = 1, .k = 40 }, .{ .rows = 4, .n = 2, .k = 32 } }; @@ -4435,24 +5478,41 @@ test "kernel contract inkling2: each declared launch is the shipped wrapper's, b try std.testing.expectEqualSlices(u8, try p.wrapper(), ours); } }; - inline for (.{ RelSplit, RelSplit, RelSplit, RelSplit, DflashAttn, RelNax, RelNax, RelNax, RelNax, RelComb, RelSlots, MarkovRnn, MarkovFold, MarkovPick, MarkovFoldBatch(2), MarkovFoldBatch(4), MarkovFoldBatch(9), MarkovPickBatch(4), MarkovPickSample(4), Gate, Router, Norm(.bfloat16, false), Norm(.bfloat16, true), Norm(.float32, false), Norm(.float32, true) }) |T| { + inline for (.{ RelSplit, RelSplit, RelSplit, RelSplit, DflashAttn, RelattnNax, RelattnNax, RelattnNax, RelattnNax, RelComb, RelSlots, MarkovRnn, MarkovFold, MarkovPick, MarkovFoldBatch(2), MarkovFoldBatch(4), MarkovFoldBatch(9), MarkovPickBatch(4), MarkovPickSample(4), Gate, Router, Norm(.bfloat16, false, false), Norm(.bfloat16, true, false), Norm(.float32, false, false), Norm(.float32, true, false), PrepStrided, GateMm, GateMm, Norm(.bfloat16, false, true), Norm(.bfloat16, true, true), RelNax, RelNax }) |T| { const k = set.kernels.items[at]; at += 1; - // Off NAX the tensor-unit read is not dispatched. - const served = T != RelNax or @import("../../mlx/device.zig").naxAvailable(); - const p: *T = @ptrCast(@alignCast(k.ctx)); - if (served) for (k.spec.served) |shape| { + // The tensor-unit read runs where the engine calls it; so do the prompt paths gated to NAX (the tiled gates and + // the row norm: off NAX their wrappers dispatch main's kernels). + const prompt_path = T == GateMm or T == Norm(.bfloat16, false, true) or T == Norm(.bfloat16, true, true); + if ((!k.spec.nax or @import("../../mlx/device.zig").naxAvailable()) and (!prompt_path or @import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable())) { + const p: *T = @ptrCast(@alignCast(k.ctx)); + for (k.spec.served) |shape| { + try std.testing.expect(try p.prepare(shape, .random, 7)); + try p.run(); + const ours = try a.dupe(u8, p.rig.outputBytes()); + defer a.free(ours); + try std.testing.expectEqualSlices(u8, try p.wrapper(), ours); + } + } + } + // After the output projections (bounded by name): MARKOV_Q8's two cases, the speculative rounds' kernels, the vision tower's. + var end = at; + while (end < set.kernels.items.len and std.mem.startsWith(u8, set.kernels.items[end].spec.name, "inkling2 oproj")) end += 1; + for (set.kernels.items[at..end]) |k| { + const p: *OProj = @ptrCast(@alignCast(k.ctx)); + for (k.spec.served) |shape| { try std.testing.expect(try p.prepare(shape, .random, 7)); try p.run(); const ours = try a.dupe(u8, p.rig.outputBytes()); defer a.free(ours); try std.testing.expectEqualSlices(u8, try p.wrapper(), ours); - }; + } } - var end = at; - while (end < set.kernels.items.len and std.mem.startsWith(u8, set.kernels.items[end].spec.name, "inkling2 oproj")) end += 1; - for (set.kernels.items[at..end]) |k| { - const p: *OProj = @ptrCast(@alignCast(k.ctx)); + at = end; + inline for (.{ MarkovStepRnn, MarkovFoldQ8 }) |T| { + const k = set.kernels.items[at]; + at += 1; + const p: *T = @ptrCast(@alignCast(k.ctx)); for (k.spec.served) |shape| { try std.testing.expect(try p.prepare(shape, .random, 7)); try p.run(); @@ -4461,12 +5521,22 @@ test "kernel contract inkling2: each declared launch is the shipped wrapper's, b try std.testing.expectEqualSlices(u8, try p.wrapper(), ours); } } - var qend = end; + var rset = kc.Set.init(a); + defer rset.deinit(); + try rounds_contract.register(&rset); + try rounds_contract.checkWrappers(a, set.kernels.items[at..][0..rset.kernels.items.len]); + at += rset.kernels.items.len; + var tset = kc.Set.init(a); + defer tset.deinit(); + try trunk_contract.register(&tset); + try trunk_contract.checkWrappers(set.kernels.items[at..][0..tset.kernels.items.len]); + at += tset.kernels.items.len; + var qend = at; while (qend < set.kernels.items.len and std.mem.startsWith(u8, set.kernels.items[qend].spec.name, "inkling2 relsplit_nax")) qend += 1; var lend = qend; while (lend < set.kernels.items.len and std.mem.startsWith(u8, set.kernels.items[lend].spec.name, "inkling2 relsplit_lanes")) lend += 1; // Each family's wrapper dispatches only on its own GPU: the tensor-unit reads on NAX, the lanes reads off it. - const read_here = if (@import("../../mlx/device.zig").naxAvailable()) set.kernels.items[end..qend] else set.kernels.items[qend..lend]; + const read_here = if (@import("../../mlx/device.zig").naxAvailable()) set.kernels.items[at..qend] else set.kernels.items[qend..lend]; for (read_here) |k| { const p: *RelSplitNax = @ptrCast(@alignCast(k.ctx)); for (k.spec.served) |shape| { @@ -4490,6 +5560,29 @@ test "kernel contract inkling2: gates 1-4 pass" { var t: kc.gates.Tally = .{}; try kc.gates.runAll(a, set.kernels.items, 0xc0de, &t); try std.testing.expectEqual(@as(usize, 0), t.problems()); - // Off NAX the tensor-unit reads skip. - try std.testing.expectEqual(set.kernels.items.len, t.passed + t.skipped); + // Off NAX the tensor-unit reads skip; every planted control must be caught. + try std.testing.expectEqual(set.kernels.items.len, t.passed + t.skipped + t.caught); +} + +// Bar: the norm at one threadgroup a row (a prompt's) writes the bytes the norm at D / TG threadgroups a row writes, on +// the same inputs: a prompt chunk's three streams and its MLP input with the router, 512 rows, random and stress fills. +test "kernel contract inkling2: the norm at one threadgroup a row is the three-threadgroup norm's bytes" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = std.testing.allocator; + inline for (.{ false, true }) |routed| { + var three = Norm(.bfloat16, routed, false).init(a); + defer three.deinit(); + var row1 = Norm(.bfloat16, routed, true).init(a); + defer row1.deinit(); + const shape: Shape = .{ .rows = 512, .n = if (routed) 1 else 3, .k = 2304 }; + for ([_]spec.Fill{ .random, .stress }) |fill| for ([_]u64{ 7, 0xc0de }) |seed| { + try std.testing.expect(try three.prepare(shape, fill, seed)); + try three.run(); + const want = try a.dupe(u8, three.rig.outputBytes()); + defer a.free(want); + try std.testing.expect(try row1.prepare(shape, fill, seed)); + try row1.run(); + try std.testing.expectEqualSlices(u8, want, row1.rig.outputBytes()); + }; + } } diff --git a/src/plugins/inkling2/dflash2.zig b/src/plugins/inkling2/dflash2.zig index 0f211c3b5d..13f15da9af 100644 --- a/src/plugins/inkling2/dflash2.zig +++ b/src/plugins/inkling2/dflash2.zig @@ -275,7 +275,7 @@ pub const Drafter = struct { }; } - fn prepare(d: *const Drafter, g: *Graph, c: *const Conv, x: Array) !Prepared { + pub fn prepare(d: *const Drafter, g: *Graph, c: *const Conv, x: Array) !Prepared { const dyn_raw = try project(g, &c.proj, x); const lanes = ops.shape(x)[0]; const len = ops.shape(x)[1]; @@ -304,7 +304,7 @@ pub const Drafter = struct { }; } - fn finishAdd(d: *const Drafter, g: *Graph, c: *const Conv, x: Array, dyn: Array, res: Array) !Array { + pub fn finishAdd(d: *const Drafter, g: *Graph, c: *const Conv, x: Array, dyn: Array, res: Array) !Array { const lanes = ops.shape(x)[0]; const len = ops.shape(x)[1]; const dt = ops.dtype(x); diff --git a/src/plugins/inkling2/draft.zig b/src/plugins/inkling2/draft.zig index 36358b99d9..c9c6ef4778 100644 --- a/src/plugins/inkling2/draft.zig +++ b/src/plugins/inkling2/draft.zig @@ -123,6 +123,12 @@ pub const Drafter = struct { fold_q: Array = .{}, fold_s: Array = .{}, fold_qb: Array = .{}, + /// `MLX_SERVE_INKLING2_MARKOV_Q8` (opt-in): the RNN's step columns `[3R, 2R]` and context columns `[3R, 2H]`, and + /// the fold as int8 `[V, R]` with a scale a vocab row `[V]` f32 (each row's absolute max over 127). + rnn_step: Array = .{}, + rnn_ctx: Array = .{}, + fold_q8: Array = .{}, + fold_q8_sc: Array = .{}, /// An 8-bit copy of a dense trunk head, which the block rows are read through (`draftHead`); null = the trunk's. head: ?Linear = null, @@ -195,10 +201,33 @@ pub const Drafter = struct { d.fold_s = try at.keep(qf[1]); d.fold_qb = try at.keep(qf[2]); } + const rdt = ops.dtype(d.rnn.w); + if (config.optIn(.MLX_SERVE_INKLING2_MARKOV_Q8) and mlx.streamIsGpu(s) and (rdt == .bfloat16 or rdt == .float16) and @rem(rank, 4) == 0) { + const h_int: c_int = @intCast(hidden); + d.rnn_step = try at.keep(try g.contiguous(try g.sliceAxis(d.rnn.w, 1, 0, 2 * rank))); + d.rnn_ctx = try at.keep(try g.contiguous(try g.sliceAxis(d.rnn.w, 1, 2 * rank, 2 * rank + 2 * h_int))); + const qf = try quantizeFoldRows(&g, d.fold); + d.fold_q8 = try at.keep(qf[0]); + d.fold_q8_sc = try at.keep(qf[1]); + } d.head = try at.draftHead(head); return d; } + /// `fold_src` `[R, V]` as int8 `[V, R]`, a vocab row at a time, and its scales `[V]` f32 (`MARKOV_Q8`). + pub fn quantizeFoldRows(g: *Graph, fold_src: Array) ![2]Array { + const ft = try g.astype(try g.transpose(fold_src, &.{ 1, 0 }), .float32); + const mx = try g.max(try g.abs(ft), 1, true); + const zero = try g.scalar(0.0, .float32); + const pos = try g.greater(mx, zero); + const sc = try g.where(pos, try g.mulScalar(mx, 1.0 / 127.0), try g.scalar(1.0, .float32)); + const inv = try g.where(pos, try g.div(try g.scalar(127.0, .float32), mx), zero); + const clamped = try g.minimum(try g.maximum(try g.mul(ft, inv), try g.scalar(-127.0, .float32)), try g.scalar(127.0, .float32)); + const fq = try g.contiguous(try g.astype(try g.call(mlx.mlx_round, .{ clamped, @as(c_int, 0) }), .int8)); + const fsc = try g.contiguous(try g.reshape(sc, &.{ops.shape(ft)[0]})); + return .{ fq, fsc }; + } + fn release(d: *Drafter) void { for (d.owned.items) |a| _ = mlx.mlx_array_free(a); d.owned.deinit(gpa); @@ -694,6 +723,28 @@ pub const Drafter = struct { var sure: [abi.max_round_tokens]Array = undefined; var probs: [abi.max_round_tokens]Array = undefined; const dense_rows = try g.contiguous(rows); + // `MLX_SERVE_INKLING2_MARKOV_Q8` (opt-in; off: the fold path below): the block rows' and newest mix's share of + // each step's RNN input made once for the block, then one RNN step and one int8 fold a step. + if (fused and law == null and d.fold_q8.ctx != null and kernels.markovQ8Runs(g, d.rnn_step, d.fold_q8, rank)) { + kernels.engaged(.MLX_SERVE_INKLING2_MARKOV_Q8); + const st_c: c_int = @intCast(steps); + const ctx_in = try g.concat(&.{ dense_rows, try g.broadcast(newest, &.{ 1, st_c, @intCast(d.hidden) }) }, 2); + const k3 = try g.add(try g.matmul(ctx_in, try g.transpose(d.rnn_ctx, &.{ 1, 0 })), d.rnn_bias); + const kappa = try g.contiguous(try g.reshape(try g.astype(k3, .float32), &.{ st_c, 3 * rank })); + const base_b = try g.contiguous(try g.add(base, try g.astype(d.fold_bias, .float32))); + for (0..steps) |i| { + const st = try kernels.markovStepQ8(g, d.rnn_step, kappa, state, d.prev_rows, prev, d.fold_q8, d.fold_q8_sc, base_b, @intCast(i), vocab, softcap); + state = st.state; + prev = st.token; + drafted[i] = st.token; + sure[i] = st.confidence; + } + return .{ + .tokens = try g.concat(drafted[0..steps], 0), + .confidence = try g.concat(sure[0..steps], 0), + .probs = .{}, + }; + } if (fused and steps > 0) { const cap = try g.fromSlice(f32, &.{softcap}, &.{1}); const q8 = d.fold_q.ctx != null; diff --git a/src/plugins/inkling2/fit_key.zig b/src/plugins/inkling2/fit_key.zig new file mode 100644 index 0000000000..351ff40a0c --- /dev/null +++ b/src/plugins/inkling2/fit_key.zig @@ -0,0 +1,59 @@ +//! The plugin's own key for `MLX_SERVE_INKLING2_PIPELINES_AT_LOAD`'s record, from what it can read itself: the +//! server executable's bytes (an in-tree plugin builds into it, so this stands for the +//! plugin and the server build), the MLX version, the machine (chip and RAM), and the +//! server's `MLX_` settings (bar the diagnostics). Never the prompt: a record is machine tuning. +const std = @import("std"); +const builtin = @import("builtin"); +const mlx = @import("../../mlx/ffi.zig"); +const offload = @import("../../sdk/ane/offload.zig"); + +/// ` mlx GB`, in `buf`. +pub fn own(buf: []u8) ![]const u8 { + var exe: [16]u8 = @splat('0'); + if (exeDigest()) |d| exe = std.fmt.bytesToHex(d[0..8].*, .lower); + var ver = mlx.mlx_string_new(); + defer _ = mlx.mlx_string_free(ver); + const version: []const u8 = if (mlx.mlx_version(&ver) == 0) std.mem.span(mlx.mlx_string_data(ver)) else "unknown"; + return std.fmt.bufPrint(buf, "{s} mlx {s} {s} {d}GB", .{ &exe, version, machine(offload.chipBrand()), (offload.totalMemBytes() + (1 << 29)) >> 30 }); +} + +fn machine(chip: []const u8) []const u8 { + return if (chip.len > 0) chip else "unknown"; +} + +/// The server executable's sha256; null where it cannot be read. +fn exeDigest() ?[32]u8 { + var path_buf: [4096]u8 = undefined; + const path = exePath(&path_buf) orelse return null; + const fh = std.c.fopen(path, "rb") orelse return null; + defer _ = std.c.fclose(fh); + var h = std.crypto.hash.sha2.Sha256.init(.{}); + var buf: [1 << 16]u8 = undefined; + while (true) { + const n = std.c.fread(&buf, 1, buf.len, fh); + if (n == 0) break; + h.update(buf[0..n]); + } + var d: [32]u8 = undefined; + h.final(&d); + return d; +} + +fn exePath(buf: []u8) ?[:0]const u8 { + if (!builtin.os.tag.isDarwin()) return null; + var n: u32 = @intCast(buf.len); + if (std.c._NSGetExecutablePath(buf.ptr, &n) != 0) return null; + return std.mem.sliceTo(@as([*:0]const u8, @ptrCast(buf.ptr)), 0); +} + +test "inkling2 draft: the plugin's own fit key names this build and machine and is stable" { + var a: [512]u8 = undefined; + var b: [512]u8 = undefined; + const k1 = try own(&a); + const k2 = try own(&b); + try std.testing.expectEqualStrings(k1, k2); + try std.testing.expect(std.mem.indexOf(u8, k1, " mlx ") != null); + try std.testing.expect(std.mem.endsWith(u8, k1, "GB")); + // The executable's digest on macOS; elsewhere the zero placeholder (`exePath` reads none). + try std.testing.expectEqual(builtin.os.tag.isDarwin(), !std.mem.startsWith(u8, k1, "0000000000000000")); +} diff --git a/src/plugins/inkling2/kernels.zig b/src/plugins/inkling2/kernels.zig index e4c6c3115d..5cfb782347 100644 --- a/src/plugins/inkling2/kernels.zig +++ b/src/plugins/inkling2/kernels.zig @@ -19,6 +19,11 @@ const mxfp8 = @import("../../sdk/blocks/qmm/mxfp8_qmv.zig"); const log = @import("../../sdk/util/log.zig"); const rel = @import("../inkling/attention.zig"); const layers = @import("layers.zig"); +const MoeBank = @import("../../sdk/bases/blocks/moe.zig").Bank; + +const optIn = @import("config.zig").optIn; +const verifyQmmNaxAvailable = @import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable; +const gnax = @import("../../sdk/blocks/moe/gather_qmm_nax.zig"); const Config = @import("config.zig").Config; const Graph = ops.Graph; @@ -38,6 +43,10 @@ pub const Kernel = struct { built: ?mlx.mlx_fast_metal_kernel = null, host_built: ?*anyopaque = null, host_src: ?*const sdk_host.abi.Host = null, + /// Launches of this kernel an open pipeline record has seen since it opened (`Pipes.saw`), for `seen_epoch`. + seen_sigs: [8]u64 = @splat(0), + seen_at: u8 = 0, + seen_epoch: u32 = 0, }; /// Active host table for cached Metal kernel launches (`Host.kernel` + `HostGpu.launch`), bound at load. @@ -91,12 +100,23 @@ const bank_rows: c_int = 1; const bank_groups: c_int = 8; pub var pre_kernel: Kernel = .{ .name = "msv_inkling2_pre", .ins = &.{ "HIN", "BLK", "QY", "NW0", "NW1", "NW2", "BANK", "BPART", "MQ", "PR" }, .outs = &.{ "X", "NORMED", "A", "MSGO", "BOTH" }, .source = kernelSource("plugins/inkling2/kernels/pre.metal") }; -pub var prep_kernel: Kernel = .{ .name = "msv_inkling2_prep", .ins = &.{ "QP", "GP", "RP", "KP", "VP", "KDY", "VDY", "ST", "KW", "VW", "QS", "RS", "RJ", "PR", "PARENT" }, .outs = &.{ "Q", "GATE", "K", "V", "BIAS", "REL" }, .source = kernelSource("plugins/inkling2/kernels/prep.metal") }; +pub const prep_ins = &[_][*:0]const u8{ "QP", "GP", "RP", "KP", "VP", "KDY", "VDY", "ST", "KW", "VW", "QS", "RS", "RJ", "PR", "PARENT" }; +pub const prep_outs = &[_][*:0]const u8{ "Q", "GATE", "K", "V", "BIAS", "REL" }; +pub var prep_kernel: Kernel = .{ .name = "msv_inkling2_prep", .ins = prep_ins, .outs = prep_outs, .source = kernelSource("plugins/inkling2/kernels/prep_step.metal") }; +/// `prep_kernel` taking its inputs as they are (a prompt chunk past `split_rows`): a joined projection's parts read +/// by their strides, not copied first. +pub var prep_strided_kernel: Kernel = .{ .name = "msv_inkling2_prep_strided", .ins = prep_ins, .outs = prep_outs, .source = kernelSource("plugins/inkling2/kernels/prep.metal"), .contiguous = false }; pub var oproj_kernel: Kernel = .{ .name = "msv_inkling2_oproj", .ins = &.{ "ATT", "GATE", "WQ", "WS", "WB" }, .outs = &.{"Y"}, .source = kernelSource("plugins/inkling2/kernels/oproj.metal"), .header = bank_header }; pub var gated_kernel: Kernel = .{ .name = "msv_inkling2_gated", .ins = &.{ "ATT", "GATE" }, .outs = &.{"OUT"}, .source = kernelSource("plugins/inkling2/kernels/gated.metal") }; pub var mid_kernel: Kernel = .{ .name = "msv_inkling2_mid", .ins = &.{ "OP", "ST", "AW", "HIN", "NORMED", "BLK", "QY", "PN", "MSG3", "PR", "PARENT" }, .outs = &.{ "RES", "X", "X32", "M", "BOTH" }, .source = kernelSource("plugins/inkling2/kernels/mid.metal") }; pub var gate_kernel: Kernel = .{ .name = "msv_inkling2_gate", .ins = &.{ "A", "MS", "ST", "F", "G" }, .outs = &.{"Y"}, .source = kernelSource("plugins/inkling2/kernels/gate.metal") }; -pub var norm_kernel: Kernel = .{ .name = "msv_inkling2_norm", .ins = &.{ "Y", "NW0", "NW1", "NW2", "RT", "PR" }, .outs = &.{ "X", "SCORES" }, .source = kernelSource("plugins/inkling2/kernels/norm.metal") }; +/// A prompt chunk's message gates on the matrix units (`gateAt` past `packed_rows`). +pub var gate_mm_kernel: Kernel = .{ .name = "msv_inkling2_gate_mm", .ins = &.{ "A", "MS", "ST", "F", "G" }, .outs = &.{"Y"}, .source = kernelSource("plugins/inkling2/kernels/gate_mm.metal"), .header = "#include \n" }; +pub var norm_kernel: Kernel = .{ .name = "msv_inkling2_norm", .ins = norm_ins, .outs = norm_outs, .source = kernelSource("plugins/inkling2/kernels/norm_step.metal") }; +/// `norm_kernel` over a prompt's rows one threadgroup a row (`streamRow`). +pub var norm_row_kernel: Kernel = .{ .name = "msv_inkling2_norm_row", .ins = norm_ins, .outs = norm_outs, .source = kernelSource("plugins/inkling2/kernels/norm.metal") }; +const norm_ins = &[_][*:0]const u8{ "Y", "NW0", "NW1", "NW2", "RT", "PR" }; +const norm_outs = &[_][*:0]const u8{ "X", "SCORES" }; pub var topk_kernel: Kernel = .{ .name = "msv_inkling2_topk", .ins = &.{ "SC", "RB", "PR" }, .outs = &.{ "IDX", "WTS" }, .source = kernelSource("plugins/inkling2/kernels/topk.metal") }; pub var topk_group_kernel: Kernel = .{ .name = "msv_inkling2_topk_group", .ins = &.{ "SC", "RB", "PR" }, .outs = &.{ "IDX", "WTS", "TEXP", "TCNT", "TPICK" }, .source = kernelSource("plugins/inkling2/kernels/topk_group.metal") }; pub var act_kernel: Kernel = .{ .name = "msv_inkling2_act", .ins = &.{ "GU", "IDX", "SC", "PR" }, .outs = &.{"ACT"}, .source = kernelSource("plugins/inkling2/kernels/act.metal") }; @@ -119,6 +139,9 @@ const markov_header = kernelSource("plugins/inkling2/kernels/markov_header.metal pub var markov_rnn_kernel: Kernel = .{ .name = "msv_inkling2_markov_rnn", .ins = &.{ "W", "B", "ST", "PREV", "ROWS", "NEW", "TOK", "AT" }, .outs = &.{"P"}, .source = kernelSource("plugins/inkling2/kernels/markov_rnn.metal") }; pub var markov_fold_kernel: Kernel = .{ .name = "msv_inkling2_markov_fold", .ins = &.{ "P", "FOLD", "FB", "BASE", "AT", "CAP" }, .outs = &.{ "PM", "PI", "PS" }, .source = kernelSource("plugins/inkling2/kernels/markov_fold.metal"), .header = markov_header }; pub var markov_fold_q8_kernel: Kernel = .{ .name = "msv_inkling2_markov_fold_q8", .ins = &.{ "P", "FQ", "FS", "FQB", "FB", "BASE", "AT", "CAP", "LPARAMS" }, .outs = &.{ "PM", "PI", "PS", "GM", "SCALED" }, .source = kernelSource("plugins/inkling2/kernels/markov_fold_q8.metal"), .header = markov_header }; +/// `MLX_SERVE_INKLING2_MARKOV_Q8` (opt-in): one RNN step over a block's precomputed context, and the int8 fold a vocab row. +pub var markov_step_rnn_kernel: Kernel = .{ .name = "msv_inkling2_markov_step_rnn", .ins = &.{ "W", "KAPPA", "ST", "PREV", "TOK", "AT" }, .outs = &.{"P"}, .source = kernelSource("plugins/inkling2/kernels/markov_step_rnn.metal") }; +pub var markov_fold_q8_row_kernel: Kernel = .{ .name = "msv_inkling2_markov_fold_q8_row", .ins = &.{ "P", "FQ", "FSC", "BASE", "AT", "CAP" }, .outs = &.{ "PM", "PI", "PS" }, .source = kernelSource("plugins/inkling2/kernels/markov_fold_q8_row.metal"), .header = markov_header }; pub var markov_pick_kernel: Kernel = .{ .name = "msv_inkling2_markov_pick", .ins = &.{ "PM", "PI", "PS", "P", "ST", "CAP" }, .outs = &.{ "TOKN", "CONF", "NST" }, .source = kernelSource("plugins/inkling2/kernels/markov_pick.metal"), .header = markov_header }; pub var markov_fold_batch_kernel: Kernel = .{ .name = "msv_inkling2_markov_fold_batch", .ins = &.{ "P", "FOLD", "FB", "BASE", "AT", "CAP" }, .outs = &.{ "PM", "PI", "PS" }, .source = kernelSource("plugins/inkling2/kernels/markov_fold_batch.metal"), .header = markov_header }; pub var markov_pick_batch_kernel: Kernel = .{ .name = "msv_inkling2_markov_pick_batch", .ins = &.{ "PM", "PI", "PS", "P", "ST", "CAP" }, .outs = &.{ "TOKN", "CONF", "NST" }, .source = kernelSource("plugins/inkling2/kernels/markov_pick_batch.metal"), .header = markov_header }; @@ -135,7 +158,7 @@ pub var sample_draw_kernel: Kernel = .{ .name = "msv_inkling2_sample_draw", .ins pub var accept_tree_kernel: Kernel = .{ .name = "msv_inkling2_accept_tree", .ins = &.{ "TOKENS", "PARENT", "SELECTED", "ACCEPT_CAP", "STOPS", "N_STOPS" }, .outs = &.{"RESULT"}, .source = kernelSource("plugins/inkling2/kernels/accept_tree.metal") }; pub const enabled = @import("config.zig").fusedOn; -pub const TArg = union(enum) { dtype: Dtype, int: c_int }; +pub const TArg = union(enum) { dtype: Dtype, int: c_int, flag: bool }; pub const Out = struct { shape: []const c_int, dtype: Dtype }; /// An output a kernel variant never writes. pub const unused: Out = .{ .shape = &.{1}, .dtype = .float32 }; @@ -156,6 +179,7 @@ pub fn launchGrid(g: *Graph, k: *Kernel, inputs: []const Array, comptime n: usiz for (targs) |t| switch (t[1]) { .dtype => |d| try mlx.check(mlx.mlx_fast_metal_kernel_config_add_template_arg_dtype(cfg, t[0], d)), .int => |v| try mlx.check(mlx.mlx_fast_metal_kernel_config_add_template_arg_int(cfg, t[0], v)), + .flag => |v| try mlx.check(mlx.mlx_fast_metal_kernel_config_add_template_arg_bool(cfg, t[0], v)), }; const iv = mlx.mlx_vector_array_new_data(inputs.ptr, inputs.len); defer _ = mlx.mlx_vector_array_free(iv); @@ -216,6 +240,7 @@ pub fn launchGrid(g: *Graph, k: *Kernel, inputs: []const Array, comptime n: usiz }; try mlx.check(mlx.mlx_fast_metal_kernel_apply(&ov, kernel, iv, cfg, g.s)); } + if (pipes.watching) pipes.saw(k, inputs, &outs, grid, tg, targs); if (unproven(k, tg, targs)) |key| if (!mlx.errorPending()) { _ = mlx.mlx_eval(ov); if (mlx.takeErrorIf("maximum allowed threads per threadgroup")) return error.ThreadLimit; @@ -234,6 +259,309 @@ pub fn launchGrid(g: *Graph, k: *Kernel, inputs: []const Array, comptime n: usiz return res; } +/// Every plugin kernel, by name, for a pipeline record's replay. +const all_kernels = [_]*Kernel{ &pre_kernel, &prep_kernel, &prep_strided_kernel, &oproj_kernel, &gated_kernel, &mid_kernel, &gate_kernel, &gate_mm_kernel, &norm_kernel, &norm_row_kernel, &topk_kernel, &topk_group_kernel, &act_kernel, &ups_kernel, &downs_kernel, &group_kernel, &ups_grp_kernel, &downs_grp_kernel, &relattn_kernel, &tile_scan_kernel, &moe_wide_kernel, &router_kernel, &relattn_nax_kernel, &relsplit_nax_kernel, &relsplit_lanes_kernel, &relsplit_kernel, &relcomb_kernel, &markov_rnn_kernel, &markov_fold_kernel, &markov_fold_q8_kernel, &markov_step_rnn_kernel, &markov_fold_q8_row_kernel, &markov_pick_kernel, &markov_fold_batch_kernel, &markov_pick_batch_kernel, &markov_pick_sample_kernel, &markov_pick_rnn_kernel, &relslots_kernel, &relmask_kernel, &sum_kernel, &few_tail_kernel, &state_kernel, &sample_mass_kernel, &sample_search_kernel, &sample_draw_kernel, &accept_tree_kernel, &@import("dflash2.zig").dflash_attn_kernel }; + +/// The plugin's kernel pipelines (`MLX_SERVE_INKLING2_PIPELINES_AT_LOAD`): MLX builds one for each kernel, template +/// arguments and input and output dtypes at its first launch. At load the build's record is replayed on zero inputs of +/// its launches' shapes, and until the load is ready (`ready`: its replay, warm-up and own requests) each first launch +/// is appended to it. From ready on, and in a process that replays a closed record or runs with the switch off, a +/// launch does no work for it: the one `watching` test in `launchGrid`. +pub const Pipes = struct { + seen: [1024]u64 = undefined, + n: usize = 0, + /// Launches the record held at this load, and first launches the load added to it before ready. + held: u64 = 0, + added: u64 = 0, + record: [512]u8 = undefined, + record_len: usize = 0, + replaying: bool = false, + /// Each launch is looked up, and a first one appended unless `replaying`: from `pipelinesAtLoad` to `ready`. + watching: bool = false, + + /// The line that ends a complete record: a load whose warm-up launched nothing it lacked. + pub const closed_mark = "#closed"; + + /// The load is ready: no later launch looks anything up. A record this load replayed and added nothing to is + /// complete for the load's warm-up and is closed, so the next load replays it and watches nothing; one that grew + /// (or is still empty) stays open for the next load's warm-up, which may take another path (a stored ladder's warm + /// prompt in place of the rounds' timing). + pub fn ready(p: *Pipes) void { + if (!p.watching) return; + p.watching = false; + if (p.record_len == 0) return; + const complete = p.added == 0 and p.held > 0; + if (complete) if (std.c.fopen(@ptrCast(&p.record), "ab")) |fh| { + _ = std.c.fwrite(closed_mark ++ "\n", 1, closed_mark.len + 1, fh); + _ = std.c.fclose(fh); + }; + log.info("[inkling2] pipelines at load: record closed at ready, {d} first launches added ({d} kept){s}\n", .{ p.added, p.n, if (complete) ", record complete" else "" }); + } + + /// One launch of a kernel within this process: its template arguments' names (by address) and values, its inputs' + /// and outputs' dtypes. Never 0. + fn sigOf(inputs: []const Array, outs: []const Out, targs: TArgs) u64 { + const m: u64 = 0x100000001b3; + var h: u64 = 0x9e3779b97f4a7c15; + for (targs) |t| { + const v: u64 = switch (t[1]) { + .dtype => |d| @as(u64, @intCast(@intFromEnum(d))), + .int => |x| @as(u64, @as(u32, @bitCast(x))), + .flag => |f| @as(u64, @intFromBool(f)), + }; + const at: u64 = @intCast(@intFromPtr(t[0])); + h = (h ^ at ^ (v << 32)) *% m; + } + for (inputs) |x| { + const d: u64 = @intCast(@intFromEnum(ops.dtype(x))); + h = (h ^ d) *% m; + } + for (outs) |o| { + const d: u64 = @intCast(@intFromEnum(o.dtype)); + h = (h ^ (d << 8)) *% m; + } + return h | 1; + } + + fn keyOf(k: *const Kernel, inputs: []const Array, outs: []const Out, targs: TArgs) u64 { + var h = std.hash.Wyhash.init(0x51ce); + h.update(std.mem.span(k.name)); + for (targs) |t| { + h.update(std.mem.span(t[0])); + switch (t[1]) { + .dtype => |d| h.update(std.mem.asBytes(&d)), + .int => |v| h.update(std.mem.asBytes(&v)), + .flag => |v| h.update(std.mem.asBytes(&v)), + } + } + for (inputs) |x| { + const d = ops.dtype(x); + h.update(std.mem.asBytes(&d)); + } + for (outs) |o| h.update(std.mem.asBytes(&o.dtype)); + return h.final(); + } + + /// `keyOf` for a record line: the same kernel, template arguments and dtypes give the same key. + fn keyOfLine(r: *const RecordLine) u64 { + var h = std.hash.Wyhash.init(0x51ce); + h.update(std.mem.span(r.kernel.name)); + for (r.targs) |t| { + h.update(std.mem.span(t[0])); + switch (t[1]) { + .dtype => |d| h.update(std.mem.asBytes(&d)), + .int => |v| h.update(std.mem.asBytes(&v)), + .flag => |v| h.update(std.mem.asBytes(&v)), + } + } + for (r.ins) |x| h.update(std.mem.asBytes(&x.dtype)); + for (r.outs) |o| h.update(std.mem.asBytes(&o.dtype)); + return h.final(); + } + + fn saw(p: *Pipes, k: *Kernel, inputs: []const Array, outs: []const Out, grid: [3]c_int, tg: [3]c_int, targs: TArgs) void { + // A launch this kernel already made since the record opened (every decode step repeats its launches): no key + // over the names, no scan of the seen keys. + if (k.seen_epoch != pipes_epoch) { + k.seen_sigs = @splat(0); + k.seen_at = 0; + k.seen_epoch = pipes_epoch; + } + const sig = sigOf(inputs, outs, targs); + if (std.mem.indexOfScalar(u64, &k.seen_sigs, sig) != null) return; + k.seen_sigs[k.seen_at] = sig; + k.seen_at = (k.seen_at + 1) & 7; + const key = keyOf(k, inputs, outs, targs); + if (std.mem.indexOfScalar(u64, p.seen[0..p.n], key) != null) return; + if (p.n < p.seen.len) { + p.seen[p.n] = key; + p.n += 1; + } + if (p.replaying) return; + p.added += 1; + log.debug("[inkling2] pipeline built before ready: {s} ({d} so far)\n", .{ k.name, p.added }); + if (p.record_len > 0) p.append(k, inputs, outs, grid, tg, targs) catch {}; + } + + /// One launch as a record line: name, grid, threadgroup, template arguments, inputs, outputs. + fn append(p: *Pipes, k: *const Kernel, inputs: []const Array, outs: []const Out, grid: [3]c_int, tg: [3]c_int, targs: TArgs) !void { + var buf: [8192]u8 = undefined; + var at: usize = 0; + const put = struct { + fn f(b: []u8, n: *usize, comptime fmt: []const u8, args: anytype) !void { + const w = try std.fmt.bufPrint(b[n.*..], fmt, args); + n.* += w.len; + } + }.f; + try put(&buf, &at, "{s}\t{d},{d},{d}\t{d},{d},{d}\t", .{ k.name, grid[0], grid[1], grid[2], tg[0], tg[1], tg[2] }); + for (targs) |t| switch (t[1]) { + .dtype => |d| try put(&buf, &at, "{s}=d{d};", .{ t[0], @intFromEnum(d) }), + .int => |v| try put(&buf, &at, "{s}=i{d};", .{ t[0], v }), + .flag => |v| try put(&buf, &at, "{s}=f{d};", .{ t[0], @intFromBool(v) }), + }; + try put(&buf, &at, "\t", .{}); + for (inputs) |x| { + try put(&buf, &at, "{d}:", .{@intFromEnum(ops.dtype(x))}); + for (ops.shape(x), 0..) |d, i| try put(&buf, &at, "{s}{d}", .{ if (i == 0) "" else "x", d }); + try put(&buf, &at, ";", .{}); + } + try put(&buf, &at, "\t", .{}); + for (outs) |o| { + try put(&buf, &at, "{d}:", .{@intFromEnum(o.dtype)}); + for (o.shape, 0..) |d, i| try put(&buf, &at, "{s}{d}", .{ if (i == 0) "" else "x", d }); + try put(&buf, &at, ";", .{}); + } + try put(&buf, &at, "\n", .{}); + const fh = std.c.fopen(@ptrCast(&p.record), "ab") orelse return error.PipelineRecordOpen; + _ = std.c.fwrite(&buf, 1, at, fh); + _ = std.c.fclose(fh); + } +}; +pub var pipes: Pipes = .{}; +/// Moves at each `pipelinesAtLoad`: a kernel's seen launches (`Kernel.seen_sigs`) hold for one record. +var pipes_epoch: u32 = 0; + +/// A shape as a record writes it, `2x3`; empty for a scalar. +fn parseShape(a: std.mem.Allocator, txt: []const u8) ![]c_int { + var out: std.ArrayList(c_int) = .empty; + if (txt.len == 0) return out.toOwnedSlice(a); + var it = std.mem.splitScalar(u8, txt, 'x'); + while (it.next()) |d| try out.append(a, try std.fmt.parseInt(c_int, d, 10)); + return out.toOwnedSlice(a); +} + +/// One record line: a kernel's launch, its inputs as dtypes and shapes. +const RecordLine = struct { + kernel: *Kernel, + grid: [3]c_int, + tg: [3]c_int, + targs: TArgs, + ins: []const Out, + outs: []const Out, +}; + +fn parseOuts(a: std.mem.Allocator, txt: []const u8) ![]const Out { + var outs: std.ArrayList(Out) = .empty; + var it = std.mem.splitScalar(u8, txt, ';'); + while (it.next()) |x| { + if (x.len == 0) continue; + const c = std.mem.indexOfScalar(u8, x, ':') orelse return error.PipelineRecordLine; + try outs.append(a, .{ .shape = try parseShape(a, x[c + 1 ..]), .dtype = @enumFromInt(try std.fmt.parseInt(std.meta.Tag(Dtype), x[0..c], 10)) }); + } + return outs.toOwnedSlice(a); +} + +/// A record line parsed; null for a kernel this build does not have. +fn parseRecordLine(a: std.mem.Allocator, line: []const u8) !?RecordLine { + var f = std.mem.splitScalar(u8, line, '\t'); + const name = f.next() orelse return error.PipelineRecordLine; + const kp = for (all_kernels) |k| { + if (std.mem.eql(u8, std.mem.span(k.name), name)) break k; + } else return null; + var r: RecordLine = .{ .kernel = kp, .grid = undefined, .tg = undefined, .targs = &.{}, .ins = &.{}, .outs = &.{} }; + for ([_]*[3]c_int{ &r.grid, &r.tg }) |dst| { + var it = std.mem.splitScalar(u8, f.next() orelse return error.PipelineRecordLine, ','); + for (dst) |*v| v.* = try std.fmt.parseInt(c_int, it.next() orelse return error.PipelineRecordLine, 10); + } + var targs: std.ArrayList(std.meta.Child(TArgs)) = .empty; + var ti = std.mem.splitScalar(u8, f.next() orelse return error.PipelineRecordLine, ';'); + while (ti.next()) |t| { + if (t.len == 0) continue; + const eq = std.mem.indexOfScalar(u8, t, '=') orelse return error.PipelineRecordLine; + if (eq + 2 > t.len) return error.PipelineRecordLine; + const nm = try a.dupeSentinel(u8, t[0..eq], 0); + const v = t[eq + 2 ..]; + const arg: TArg = switch (t[eq + 1]) { + 'd' => .{ .dtype = @enumFromInt(try std.fmt.parseInt(std.meta.Tag(Dtype), v, 10)) }, + 'i' => .{ .int = try std.fmt.parseInt(c_int, v, 10) }, + 'f' => .{ .flag = (try std.fmt.parseInt(c_int, v, 10)) != 0 }, + else => return error.PipelineRecordLine, + }; + try targs.append(a, .{ nm.ptr, arg }); + } + r.targs = targs.items; + r.ins = try parseOuts(a, f.next() orelse return error.PipelineRecordLine); + r.outs = try parseOuts(a, f.next() orelse return error.PipelineRecordLine); + return r; +} + +/// `MLX_SERVE_INKLING2_PIPELINES_AT_LOAD`: the record at `path` (this build, machine and composition) replayed on `s`, +/// each launch on zero inputs of its shapes, all evaluated: its pipelines built before ready. Returns (pipelines +/// built, launches replayed, lines unreadable); keeps `path` as the record first launches before ready append to, +/// unless it is closed. An unreadable line is skipped, never the record. +pub fn pipelinesAtLoad(s: mlx.mlx_stream, path: []const u8) ![3]usize { + if (path.len + 1 >= pipes.record.len) return error.PipelineRecordPath; + @memcpy(pipes.record[0..path.len], path); + pipes.record[path.len] = 0; + pipes.record_len = path.len; + var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); + defer arena.deinit(); + const a = arena.allocator(); + pipes.held = 0; + pipes.added = 0; + pipes.watching = true; + pipes_epoch +%= 1; + const fh = std.c.fopen(@ptrCast(&pipes.record), "rb") orelse return .{ 0, 0, 0 }; + var text_list: std.ArrayList(u8) = .empty; + var chunk: [65536]u8 = undefined; + while (true) { + const got = std.c.fread(&chunk, 1, chunk.len, fh); + if (got == 0) break; + try text_list.appendSlice(a, chunk[0..got]); + } + _ = std.c.fclose(fh); + // The replay looks every launch up (a closed record's too), so its keys are seen; it appends none. + var closed = false; + pipes.replaying = true; + defer { + pipes.replaying = false; + pipes.watching = !closed; + } + const before = pipes.n; + var done: usize = 0; + var bad: usize = 0; + var lines = std.mem.splitScalar(u8, text_list.items, '\n'); + while (lines.next()) |line| { + if (line.len == 0) continue; + if (std.mem.eql(u8, line, Pipes.closed_mark)) { + closed = true; + continue; + } + const r = (parseRecordLine(a, line) catch { + bad += 1; + continue; + }) orelse continue; + pipes.held += 1; + // One launch a pipeline, each evaluated and freed before the next: the record repeats keys at other shapes. + if (std.mem.indexOfScalar(u64, pipes.seen[0..pipes.n], Pipes.keyOfLine(&r)) != null) continue; + var g = Graph.init(std.heap.c_allocator, s); + defer g.deinit(); + var ins: std.ArrayList(Array) = .empty; + for (r.ins) |x| try ins.append(a, try g.zeros(x.shape, x.dtype)); + const made = replayOne(&g, r.kernel, ins.items, r.outs, r.grid, r.tg, r.targs) catch continue; + try ops.evalMany(made); + done += 1; + } + return .{ pipes.n - before, done, bad }; +} + +/// A record line's launch, its output count at run time (the record's), each output's array. +fn replayOne(g: *Graph, k: *Kernel, inputs: []const Array, outs: []const Out, grid: [3]c_int, tg: [3]c_int, targs: TArgs) ![]const Array { + const res = struct { + var buf: [8]Array = undefined; + }; + switch (outs.len) { + inline 1...8 => |n| { + var o: [n]Out = undefined; + for (&o, outs[0..n]) |*d, x| d.* = x; + const r = try launchGrid(g, k, inputs, n, o, grid, tg, targs); + for (res.buf[0..n], r) |*d, x| d.* = x; + return res.buf[0..n]; + }, + else => return error.PipelineRecordOutputs, + } +} + fn floating(dt: Dtype) bool { return dt == .bfloat16 or dt == .float16 or dt == .float32; } @@ -250,6 +578,18 @@ pub fn streamGroup(hidden: u32) ?c_int { return null; } +/// Whether the norm kernel over `s` rows of `d` at threadgroup `tg` runs one threadgroup a row: a prompt's rows +/// (`load`) on NAX (`verifyQmmNaxAvailable`), each thread keeping at most `row_elems` of a row's elements in registers. +/// A decode, a verify, batched slots, a few rows and every GPU without NAX (M1-M4) keep main's D / TG threadgroups a +/// row, which spread their latency over more cores, as does a threadgroup narrowed past `row_elems`. `pre` and `mid` +/// take one threadgroup a row by their own rule (`ONE_TG`), at the same bound. +pub fn streamRow(load: Load, s: c_int, d: c_int, tg: c_int) bool { + return load == .prompt and s > small_rows and @divTrunc(d, tg) <= row_elems and verifyQmmNaxAvailable() and !mainFor(.stream_row); +} + +/// The most elements of a row a stream kernel's thread keeps at one threadgroup a row. +pub const row_elems = 4; + /// After a refused stream launch: whether a narrower threadgroup is left to try. fn narrow(hidden: u32) bool { const now = streamGroup(hidden) orelse return false; @@ -280,6 +620,7 @@ fn unproven(k: *const Kernel, tg: [3]c_int, targs: TArgs) ?u64 { for (targs) |t| switch (t[1]) { .dtype => |d| h.update(std.mem.asBytes(&d)), .int => |v| h.update(std.mem.asBytes(&v)), + .flag => |v| h.update(std.mem.asBytes(&v)), }; const key = h.final() | 1; return if (std.mem.indexOfScalar(u64, probed[0..probed_n], key) == null) key else null; @@ -336,11 +677,33 @@ fn streams(g: *Graph, cfg: *const Config, consts: ?*const layers.Consts, h: Arra /// streams), from each gate's state `st` `[n, S, rank]`: `[n, S, D]` f32. A few rows' threads take the forget and /// message projections themselves (MLX's f32 matmul at two rows is several launches' latency); a prompt's rows take /// them from two matmuls. +/// `gate_mm_kernel`'s rows a threadgroup. +pub const gate_mm_rows: c_int = 64; + pub fn gate(g: *Graph, gates: *const layers.Gates, a: Array, ms: Array, st: Array, from: c_int, n: c_int) !Array { + return gateAt(g, .prompt, gates, a, ms, st, from, n); +} + +/// `gate` for a forward of `load`. +pub fn gateAt(g: *Graph, load: Load, gates: *const layers.Gates, a: Array, ms: Array, st: Array, from: c_int, n: c_int) !Array { const sh = ops.shape(gates.forget); const s = ops.shape(st)[1]; var forget = try g.sliceAxis(gates.forget, 0, from, from + n); var message = try g.sliceAxis(gates.message, 0, from, from + n); + // Past `packed_rows`, a prompt's rows on NAX (`verifyQmmNaxAvailable`) through one tiled kernel, F st and G st on + // the matrix units in f32 and the mix in its epilogue: no [n, S, D] product written and read back, no TF32 + // (precision-up against the TF32 matmuls). 64-row tiles (eight SIMD groups), each projection slice staged once. A + // step's rows, widths the tiles do not divide and every GPU without NAX (M1-M4) take main's gate kernel below (past + // `packed_rows`, on two matmuls' products). + if (load == .prompt and s > packed_rows and @rem(sh[1], 32) == 0 and @rem(sh[2], 32) == 0 and verifyQmmNaxAvailable() and !mainFor(.gate_mm)) { + engaged(.gate_mm); + const bm: c_int = gate_mm_rows; + const nt = @divExact(bm, 16) * 2 * 32; + const o = try launchGrid(g, &gate_mm_kernel, &.{ a, ms, st, forget, message }, 1, .{.{ .shape = &.{ n, s, sh[1] }, .dtype = .float32 }}, .{ nt * @divExact(sh[1], 32), @divTrunc(s + bm - 1, bm), n }, .{ nt, 1, 1 }, &.{ + .{ "D", .{ .int = sh[1] } }, .{ "RANK", .{ .int = sh[2] } }, .{ "BM", .{ .int = bm } }, + }); + return o[0]; + } const projected = s > packed_rows; if (projected) { const st32 = try g.astype(st, .float32); @@ -361,25 +724,47 @@ fn routerThreads(cfg: *const Config, tg: c_int) c_int { /// The `n` streams `y` `[n, S, D]` f32 under their weighted RMS norms, `[n, S, D]` in `dt`; with a `router`, its /// scores `[S, E]` f32 over the first. pub fn norm(g: *Graph, cfg: *const Config, y: Array, nw: [3]Array, n: c_int, dt: Dtype, router: ?Array) ![2]Array { - return normWithConsts(g, cfg, null, y, nw, n, dt, router); + return normWithConsts(g, .prompt, cfg, null, y, nw, n, dt, router); +} + +/// `norm` for a forward of `load`. +pub fn normAt(g: *Graph, load: Load, cfg: *const Config, y: Array, nw: [3]Array, n: c_int, dt: Dtype, router: ?Array) ![2]Array { + return normWithConsts(g, load, cfg, null, y, nw, n, dt, router); } -fn normWithConsts(g: *Graph, cfg: *const Config, consts: ?*const layers.Consts, y: Array, nw: [3]Array, n: c_int, dt: Dtype, router: ?Array) ![2]Array { +fn normWithConsts(g: *Graph, load: Load, cfg: *const Config, consts: ?*const layers.Consts, y: Array, nw: [3]Array, n: c_int, dt: Dtype, router: ?Array) ![2]Array { const d: c_int = @intCast(cfg.hidden_size); const s = ops.shape(y)[1]; const experts_n: c_int = if (router != null) @intCast(cfg.num_experts) else 0; const eps = if (consts != null and consts.?.eps.ctx != null) consts.?.eps else try g.fromSlice(f32, &.{cfg.rms_norm_eps}, &.{1}); while (true) { const tg = streamGroup(cfg.hidden_size) orelse return error.ThreadLimit; - return launchGrid(g, &norm_kernel, &.{ y, nw[0], nw[1], nw[2], router orelse y, eps }, 2, .{ + const row = streamRow(load, s, d, tg); + const rt: c_int = if (router != null) routerThreads(cfg, tg) else 0; + const ins = [_]Array{ y, nw[0], nw[1], nw[2], router orelse y, eps }; + // A prompt's rows a threadgroup a row on their own kernel; every other load main's, a thread an element. + const o = (if (row) normRows(g, &ins, n, s, d, dt, experts_n, tg, rt) else launchGrid(g, &norm_kernel, &ins, 2, .{ .{ .shape = &.{ n, s, d }, .dtype = dt }, if (router != null) .{ .shape = &.{ s, experts_n }, .dtype = .float32 } else unused, - }, .{ d + if (router != null) routerThreads(cfg, tg) else 0, s, 1 }, .{ tg, 1, 1 }, &.{ + }, .{ d + rt, s, 1 }, .{ tg, 1, 1 }, &.{ .{ "T", .{ .dtype = dt } }, .{ "TG", .{ .int = tg } }, .{ "D", .{ .int = d } }, .{ "J", .{ .int = n } }, .{ "E", .{ .int = experts_n } }, - }) catch |e| if (e == error.ThreadLimit and narrow(cfg.hidden_size)) continue else return e; + })) catch |e| if (e == error.ThreadLimit and narrow(cfg.hidden_size)) continue else return e; + if (row) engaged(.stream_row); + return o; } } +/// `norm` over a prompt's rows (`norm_row_kernel`, `norm.metal`'s row mode): `tg` threads a row, then `rt` router threads. +fn normRows(g: *Graph, ins: []const Array, n: c_int, s: c_int, d: c_int, dt: Dtype, experts_n: c_int, tg: c_int, rt: c_int) ![2]Array { + return launchGrid(g, &norm_row_kernel, ins, 2, .{ + .{ .shape = &.{ n, s, d }, .dtype = dt }, + if (experts_n > 0) .{ .shape = &.{ s, experts_n }, .dtype = .float32 } else unused, + }, .{ tg + rt, s, 1 }, .{ tg, 1, 1 }, &.{ + .{ "T", .{ .dtype = dt } }, .{ "TG", .{ .int = tg } }, .{ "D", .{ .int = d } }, .{ "J", .{ .int = n } }, .{ "E", .{ .int = experts_n } }, + .{ "ROW", .{ .int = 1 } }, + }); +} + /// A visit's projections with what its second half reads: the stream's unweighted norm `[1, S, D]`, and on a later /// loop pass the visit's messages `[4, S, D]` f32. pub const Fore = struct { proj: [6]Array, dyn: ?[2]Array, normed: Array, messages: ?Array }; @@ -402,6 +787,11 @@ fn gateDowns(g: *Graph, x: Array, gates: *const layers.Gates, from: c_int, n: c_ /// `layers.project`. `bank` is the last pass's bank and normed output on a later loop pass. pub fn pre(g: *Graph, L: *const Layer, w: *const Body, h: Array, blocks: ?Array, bank: ?[2]Array) !Fore { + return preAt(g, .prompt, L, w, h, blocks, bank); +} + +/// `pre` for a forward of `load`. +pub fn preAt(g: *Graph, load: Load, L: *const Layer, w: *const Body, h: Array, blocks: ?Array, bank: ?[2]Array) !Fore { const cfg = &w.cfg; const dt = ops.dtype(h); var x: Array = undefined; @@ -411,7 +801,7 @@ pub fn pre(g: *Graph, L: *const Layer, w: *const Body, h: Array, blocks: ?Array, const gates = &(L.gates orelse return error.Inkling2NoMessageGate); const o = try streams(g, cfg, &w.consts, h, blocks, L.attn_query, L.in_norm, 3, .{ .bank = bk[0], .partial = bk[1], .query = L.message_query, .gt = ops.dtype(gates.down) }); const st = try gateDowns(g, o[4], gates, 0, 3); - x = (try normWithConsts(g, cfg, &w.consts, try gate(g, gates, o[2], o[3], st, 0, 3), L.in_norm, 3, dt, null))[0]; + x = (try normWithConsts(g, load, cfg, &w.consts, try gateAt(g, load, gates, o[2], o[3], st, 0, 3), L.in_norm, 3, dt, null))[0]; normed = o[1]; messages = o[3]; } else { @@ -446,15 +836,26 @@ pub fn keysSeen(L: *const Layer, cfg: *const Config, total: c_int) c_int { /// `layers.prepare` as one launch. One row takes its log-scaling factor `tau` and the count of `keys` it will read, /// for its bias row; more rows leave both to the read. Null where the projections are not one float dtype. +/// Whether `x`'s last axis is unit-strided (a joined projection's part is). +fn unitLast(x: Array) bool { + const n = mlx.mlx_array_ndim(x); + return n > 0 and mlx.mlx_array_strides(x)[n - 1] == 1; +} + pub fn prep(g: *Graph, L: *const Layer, cfg: *const Config, proj: *const [6]Array, taps: ?[2]Array, st: Array, tau: f32, keys: c_int) !?Prep { return prepWith(g, L, cfg, proj, taps, st, tau, keys, null); } pub fn prepWith(g: *Graph, L: *const Layer, cfg: *const Config, proj: *const [6]Array, taps: ?[2]Array, st: Array, tau: f32, keys: c_int, parent: ?Array) !?Prep { - return prepWithConsts(g, L, cfg, null, proj, taps, st, tau, keys, parent); + return prepWithConsts(g, .prompt, L, cfg, null, proj, taps, st, tau, keys, parent); } -fn prepWithConsts(g: *Graph, L: *const Layer, cfg: *const Config, consts: ?*const layers.Consts, proj: *const [6]Array, taps: ?[2]Array, st: Array, tau: f32, keys: c_int, parent: ?Array) !?Prep { +/// `prepWith` for a forward of `load`. +pub fn prepAt(g: *Graph, load: Load, L: *const Layer, cfg: *const Config, proj: *const [6]Array, taps: ?[2]Array, st: Array, tau: f32, keys: c_int, parent: ?Array) !?Prep { + return prepWithConsts(g, load, L, cfg, null, proj, taps, st, tau, keys, parent); +} + +fn prepWithConsts(g: *Graph, load: Load, L: *const Layer, cfg: *const Config, consts: ?*const layers.Consts, proj: *const [6]Array, taps: ?[2]Array, st: Array, tau: f32, keys: c_int, parent: ?Array) !?Prep { const dt = ops.dtype(proj[0]); for (proj) |x| if (ops.dtype(x) != dt) return null; // A head is one threadgroup. @@ -472,7 +873,6 @@ fn prepWithConsts(g: *Graph, L: *const Layer, cfg: *const Config, consts: ?*cons const hd: c_int = @intCast(cfg.head_dim); const d_rel: c_int = @intCast(cfg.d_rel); const kt: c_int = @intCast(cfg.sconv_kernel); - const kv_dim = kv_heads * hd; const conv_scale: f32 = 1.0 / @sqrt(@as(f32, @floatFromInt(if (dynamic) 2 * kt + 1 else kt + 1))); const cached_pr = if (wide and tau == 1.0 and keys == 0 and consts != null) (if (dynamic) consts.?.prep_pr_dyn else consts.?.prep_pr_static) @@ -480,22 +880,53 @@ fn prepWithConsts(g: *Graph, L: *const Layer, cfg: *const Config, consts: ?*cons Array{}; const pr = if (cached_pr.ctx != null) cached_pr else try g.fromSlice(f32, &.{ cfg.qk_clip, cfg.rel_clip, cfg.rms_norm_eps, tau, conv_scale, @floatFromInt(keys) }, &.{6}); const par = parent orelse (if (consts != null and consts.?.zero_i32.ctx != null) consts.?.zero_i32 else try g.zeros(&.{1}, .int32)); - const o = try launchGrid(g, &prep_kernel, &.{ proj[0], proj[1], proj[2], proj[4], proj[5], dyn[0], dyn[1], st, kw, vw, L.q_scale, L.rel_scale, L.rel_proj_rev, pr, par }, 6, .{ - .{ .shape = if (wide) &.{ 1, s, heads, hd } else &.{ 1, heads, 1, hd }, .dtype = dt }, - .{ .shape = &.{s * heads * hd}, .dtype = .float32 }, - .{ .shape = &.{ 1, kv_heads, s, hd }, .dtype = dt }, - .{ .shape = &.{ 1, kv_heads, s, hd }, .dtype = dt }, - if (wide) unused else .{ .shape = &.{ 1, heads, 1, keys }, .dtype = dt }, - if (wide) .{ .shape = &.{ 1, s, heads, d_rel }, .dtype = dt } else unused, - }, .{ heads * hd + 2 * kv_dim + heads * (if (wide) d_rel else keys), s, 1 }, .{ hd, 1, 1 }, &.{ - .{ "T", .{ .dtype = dt } }, .{ "WT", .{ .dtype = ops.dtype(kw) } }, .{ "S", .{ .dtype = ops.dtype(L.q_scale) } }, - .{ "H", .{ .int = heads } }, .{ "HD", .{ .int = hd } }, .{ "HKV", .{ .int = kv_heads } }, - .{ "DREL", .{ .int = d_rel } }, .{ "KT", .{ .int = kt } }, .{ "DYN", .{ .int = @intFromBool(dynamic) } }, - .{ "WIDE", .{ .int = @intFromBool(wide) } }, .{ "TREE", .{ .int = @intFromBool(parent != null) } }, - }); + var ins = [_]Array{ proj[0], proj[1], proj[2], proj[4], proj[5], dyn[0], dyn[1], st, kw, vw, L.q_scale, L.rel_scale, L.rel_proj_rev, pr, par }; + // A prompt chunk past `split_rows` on NAX (`verifyQmmNaxAvailable`): the projections' parts as they are (views with + // a unit last stride), the rest made contiguous here (a no-op where they are). A step's rows, parts with another + // last stride and every GPU without NAX (M1-M4) are copied, main's prep. + const strided = load == .prompt and s > split_rows and verifyQmmNaxAvailable() and !mainFor(.prep_strided) and for (proj) |x| { + if (unitLast(x) == false) break false; + } else true; + if (strided) engaged(.prep_strided); + // A static conv's KDY, VDY slots hold k and v, which it never reads. + if (strided) for (ins[if (dynamic) 5 else 7..13]) |*x| { + x.* = try g.contiguous(x.*); + }; + if (strided) ins[14] = try g.contiguous(ins[14]); + const o = try prepLaunch(g, &ins, .{ .heads = heads, .kv_heads = kv_heads, .hd = hd, .d_rel = d_rel, .kt = kt, .keys = keys, .dynamic = dynamic, .tree = parent != null }, strided); return .{ .q = o[0], .gate = o[1], .k = o[2], .v = o[3], .bias = o[4], .rel = o[5] }; } +/// What `prepLaunch` takes besides its inputs: the attention's widths, the conv's taps, a one-row read's `keys`, the +/// conv's kind and whether the rows are a verify tree's. +pub const PrepDims = struct { heads: c_int, kv_heads: c_int, hd: c_int, d_rel: c_int, kt: c_int, keys: c_int, dynamic: bool, tree: bool = false }; + +/// `prep.metal` over `ins` (`prep_ins`' order) at the rows of `ins[0]`: `prep_strided_kernel` with `strided` (the +/// projections read as they are), else `prep_kernel`. Q, GATE, K, V, then BIAS (one row) or REL (more). +pub fn prepLaunch(g: *Graph, ins: []const Array, d: PrepDims, strided: bool) ![6]Array { + return prepLaunchOn(g, if (strided) &prep_strided_kernel else &prep_kernel, ins, d); +} + +/// `prepLaunch` on the kernel `k` (a source of `prep.metal`'s interface). +pub fn prepLaunchOn(g: *Graph, k: *Kernel, ins: []const Array, d: PrepDims) ![6]Array { + const dt = ops.dtype(ins[0]); + const s = ops.shape(ins[0])[1]; + const wide = s > 1; + return launchGrid(g, k, ins, 6, .{ + .{ .shape = if (wide) &.{ 1, s, d.heads, d.hd } else &.{ 1, d.heads, 1, d.hd }, .dtype = dt }, + .{ .shape = &.{s * d.heads * d.hd}, .dtype = .float32 }, + .{ .shape = &.{ 1, d.kv_heads, s, d.hd }, .dtype = dt }, + .{ .shape = &.{ 1, d.kv_heads, s, d.hd }, .dtype = dt }, + if (wide) unused else .{ .shape = &.{ 1, d.heads, 1, d.keys }, .dtype = dt }, + if (wide) .{ .shape = &.{ 1, s, d.heads, d.d_rel }, .dtype = dt } else unused, + }, .{ d.heads * d.hd + 2 * d.kv_heads * d.hd + d.heads * (if (wide) d.d_rel else d.keys), s, 1 }, .{ d.hd, 1, 1 }, &.{ + .{ "T", .{ .dtype = dt } }, .{ "WT", .{ .dtype = ops.dtype(ins[8]) } }, .{ "S", .{ .dtype = ops.dtype(ins[10]) } }, + .{ "H", .{ .int = d.heads } }, .{ "HD", .{ .int = d.hd } }, .{ "HKV", .{ .int = d.kv_heads } }, + .{ "DREL", .{ .int = d.d_rel } }, .{ "KT", .{ .int = d.kt } }, .{ "DYN", .{ .int = @intFromBool(d.dynamic) } }, + .{ "WIDE", .{ .int = @intFromBool(wide) } }, .{ "TREE", .{ .int = @intFromBool(d.tree) } }, + }); +} + /// `x` (any shape) times the output gate's sigmoid element by element, `[1, S, H * hd]` in its dtype. /// How `oproj` reads an output projection: an affine weight at a width the bank reader takes (FMT 3) or a dense one in /// the activation's dtype (FMT 4); null for any other (an outside or rotated weight, a bias), which keeps `gated` and @@ -548,6 +979,95 @@ pub fn relMask(g: *Graph, bias: Array, sinks: Array, keys: c_int, window: c_int, return mask[0]; } +/// The prompt paths a test sends a whole forward down main's kernels for, so it compares the logits each serves. Set +/// only in a test build: `mainFor` is false at compile time in any other, so a served forward takes every path its +/// code gate allows. +pub const TestMain = struct { + relnax: bool = false, + gather_rowmap: bool = false, + gu_act: bool = false, + prefill_async: bool = false, + gate_mm: bool = false, + prep_strided: bool = false, + stream_row: bool = false, +}; + +/// A test build's choice of paths that take main's kernels (`TestMain`); all false unless a test sets them. +pub var test_main: TestMain = .{}; + +/// Whether a test sent `path` (a `TestMain` field) down main's kernels; false outside a test build. +pub fn mainFor(comptime path: @EnumLiteral()) bool { + return @import("builtin").is_test and @field(test_main, @tagName(path)); +} + +/// Logs `[inkling2] engaged` the first time a path serves a launch: a log shows which way the path's gate +/// went (a device, a layout, a load), and an opt-in arm shows in its own A/B's log. +pub fn engaged(comptime name: @EnumLiteral()) void { + const told = engagedFlag(name); + if (told.*) return; + told.* = true; + log.info("[inkling2] {s} engaged\n", .{@tagName(name)}); +} + +/// Whether `name` has served a launch since the process started or `resetEngaged(name)`. +pub fn wasEngaged(comptime name: @EnumLiteral()) bool { + return engagedFlag(name).*; +} + +/// Forgets that `name` served (a test that asks which path a load takes). +pub fn resetEngaged(comptime name: @EnumLiteral()) void { + engagedFlag(name).* = false; +} + +fn engagedFlag(comptime name: @EnumLiteral()) *bool { + // The struct names `name`, so each path has its own flag (a type that captures nothing is one type for all). + const once = struct { + const which = name; + var told = false; + }; + return &once.told; +} + +/// The reasons `declined` has logged, by hash. +var declines: [32]u64 = @splat(0); +var declines_n: usize = 0; + +fn declineKey(comptime name: @EnumLiteral(), why: []const u8) u64 { + return (std.hash.Wyhash.hash(0x1e7e, @tagName(name)) ^ std.hash.Wyhash.hash(0xdec1, why)) | 1; +} + +/// Logs `[inkling2] declined: ` once for each reason: a layout a path leaves out is named in the log, +/// never silently slower. +pub fn declined(comptime name: @EnumLiteral(), why: []const u8) void { + const key = declineKey(name, why); + if (std.mem.indexOfScalar(u64, declines[0..declines_n], key) != null) return; + if (declines_n < declines.len) { + declines[declines_n] = key; + declines_n += 1; + } + log.info("[inkling2] {s} declined: {s}\n", .{ @tagName(name), why }); +} + +/// Whether `declined(name, why)` has logged. +pub fn wasDeclined(comptime name: @EnumLiteral(), why: []const u8) bool { + return std.mem.indexOfScalar(u64, declines[0..declines_n], declineKey(name, why)) != null; +} + +/// The load a forward serves, as the paths built for a prompt's rows read it (`prepWithConsts`'s strided read, +/// `streamRow`, `gateAt`'s tiled gates, `rowMapped`, `plugin.prefillAsync`): `.prompt` a prompt chunk, `.step` a +/// decode, a verify, a grouped verify or batched slots, which take main's path at any width. One owner: `visit` and +/// `sequence` read it from the forward's mode (`of`); every such path asks it, never the row count alone (a grouped +/// verify of 11 DFlash2 lanes is past 64 rows, batched decode past 8). Each such path also asks +/// `verifyQmmNaxAvailable`: a prompt on a GPU without NAX (M1-M4) takes main's path, as a step does. +pub const Load = enum { + prompt, + step, + + pub fn of(mode: abi.Mode) Load { + return if (mode == .prefill) .prompt else .step; + } +}; + /// The rows a read hands MLX's attention under a built mask: the flash kernel walks the keys 16 at a time on one /// threadgroup, which is a prompt's throughput and a draft verify's latency. pub const small_rows = 32; @@ -564,14 +1084,22 @@ pub fn relative(g: *Graph, L: *const Layer, cfg: *const Config, q_rows: Array, r /// `[1, S, H * hd]` directly (fused into `relattn.metal` on non-NAX GPUs, or via `gated` on NAX / small-row paths). pub fn relativeWith(g: *Graph, L: *const Layer, cfg: *const Config, q_rows: Array, rel_states: Array, sinks: Array, k: Array, v: Array, offset: c_int, flash: bool, out_gate: ?Array) !Array { const s = ops.shape(q_rows)[1]; - if (s > small_rows) if (try relativeNax(g, L, cfg, q_rows, rel_states, sinks, k, v, offset)) |o| { - return if (out_gate) |gt| gated(g, o, gt, s) else o; - }; const dt = ops.dtype(q_rows); const hd: c_int = @intCast(cfg.head_dim); if (ops.dtype(k) != dt or ops.dtype(v) != dt or @rem(hd, 8) != 0) return error.Inkling2StepDtype; const heads: c_int = @intCast(cfg.num_attention_heads); const keys = ops.shape(k)[2]; + // `relative_attention_nax.metal`'s read, its bias made in f32 inside it. A prompt it does not take (`relnaxTakes`: + // no tensor units, another dtype or width) reads main's `relattn_nax.metal` below: the one fallback. + if ((s > small_rows or flash) and relnaxTakes(dt, ops.dtype(k), ops.dtype(v), ops.dtype(rel_states), hd, @intCast(cfg.d_rel))) { + const st = try readStates(g, L, cfg, q_rows, rel_states, sinks, offset); + const win: c_int = if (L.global) 0 else @intCast(cfg.sliding_window); + const sc = 1.0 / @sqrt(@as(f32, @floatFromInt(hd))); + if (try relativeNaxStates(g, heads, @intCast(cfg.num_key_value_heads), st.q, k, v, st.states, try relPad(g, L, dt), st.sinks, win, s, keys, ops.shape(L.rel_proj)[1], sc)) |o| return if (out_gate) |gt| gated(g, o, gt, s) else o; + } + if (s > small_rows) if (try relativeNax(g, L, cfg, q_rows, rel_states, sinks, k, v, offset)) |o| { + return if (out_gate) |gt| gated(g, o, gt, s) else o; + }; const in = try readInputs(g, L, cfg, q_rows, rel_states, sinks, offset); const q = in.q; const bias = in.bias; @@ -601,6 +1129,47 @@ pub fn relativeWith(g: *Graph, L: *const Layer, cfg: *const Config, q_rows: Arra return o[0]; } +/// `relative_attention_nax.metal` (Stéphane Busso's): the flash read's loop on the tensor units, 64 rows a threadgroup +/// of 4 SIMD groups, keys 32 at a time. +pub var relnax_kernel: Kernel = .{ .name = "msv_inkling2_relnax", .ins = &.{ "q", "k", "v", "rel", "sinks", "key_start", "sizes", "scale", "relp" }, .outs = &.{"out"}, .source = kernelSource("plugins/inkling2/kernels/relative_attention_nax.metal"), .header = kernelSource("kernels/attention/nax_tiles.metal") ++ kernelSource("kernels/attention/nax_attention.metal"), .contiguous = false }; + +/// Whether `relative_attention_nax.metal` reads a prompt of these dtypes and widths: tensor units, bf16 q, k, v and +/// relative states at head dim 128 with 16 relative dims. The read asks it too; every prompt it does not take reads +/// main's `relattn_nax.metal`. +pub fn relnaxTakes(q: Dtype, k: Dtype, v: Dtype, states: Dtype, hd: c_int, d_rel: c_int) bool { + return !mainFor(.relnax) and verifyQmmNaxAvailable() and + q == .bfloat16 and k == .bfloat16 and v == .bfloat16 and states == .bfloat16 and hd == 128 and d_rel == 16; +} + +/// A prompt's flash read (`relative`'s arguments) on the tensor units, its bias made inside the read in f32: `states` +/// the rows' clipped relative states `[1, S, H, 16]`, `relp` the projection padded by `relPad`. Null where `relnaxTakes` +/// does not take it. +pub fn relativeNaxStates(g: *Graph, heads: c_int, kv_heads: c_int, q: Array, k: Array, v: Array, states: Array, relp: Array, sinks: Array, window: c_int, s: c_int, keys: c_int, r: c_int, scale: f32) !?Array { + if (!relnaxTakes(ops.dtype(q), ops.dtype(k), ops.dtype(v), ops.dtype(states), ops.shape(q)[3], ops.shape(states)[3]) or ops.dtype(relp) != .bfloat16 or s < 2) return null; + engaged(.relnax); + const o = try launchGrid(g, &relnax_kernel, &.{ + q, k, v, try g.contiguous(states), try g.contiguous(sinks), try g.zeros(&.{1}, .int32), try g.fromSlice(i32, &.{ s, keys }, &.{2}), try g.scalar(scale, .float32), relp, + }, 1, .{.{ .shape = &.{ 1, s, heads, 128 }, .dtype = .bfloat16 }}, .{ @divTrunc(s + 63, 64) * 128, heads, 1 }, .{ 128, 1, 1 }, &.{ + .{ "T", .{ .dtype = .bfloat16 } }, .{ "D", .{ .int = 128 } }, + .{ "HQ", .{ .int = heads } }, .{ "HKV", .{ .int = kv_heads } }, + .{ "R", .{ .int = r } }, .{ "WINDOW", .{ .int = window } }, + .{ "ALIGN_Q", .{ .flag = @rem(s, 64) == 0 } }, .{ "ALIGN_K", .{ .flag = @rem(keys, 32) == 0 } }, + .{ "RP", .{ .int = ops.shape(relp)[1] } }, .{ "PADL", .{ .int = relp_before } }, + }); + return o[0]; +} + +/// Zero columns `relPad` puts before a projection's distance 0 and after its last (the read's blocks reach 94 before +/// and 63 after). +pub const relp_before = 128; +const relp_after = 64; + +/// The layer's bias projection `[16, R]` in `dt`, `relp_before` zero columns before it and `relp_after` after. +pub fn relPad(g: *Graph, L: *const Layer, dt: Dtype) !Array { + const sh = ops.shape(L.rel_proj); + return g.contiguous(try g.concat(&.{ try g.zeros(&.{ sh[0], relp_before }, dt), try g.astype(L.rel_proj, dt), try g.zeros(&.{ sh[0], relp_after }, dt) }, 1)); +} + fn relProjT(g: *Graph, L: *const Layer, dt: Dtype) !Array { if (L.rel_proj_t.ctx != null and ops.dtype(L.rel_proj_t) == dt) return L.rel_proj_t; return g.contiguous(try g.astype(try g.transpose(L.rel_proj, &.{ 1, 0 }), dt)); @@ -672,6 +1241,44 @@ pub fn markovStep(g: *Graph, rnn: Array, rnn_bias: Array, state: Array, prev_row return .{ .token = o[0], .confidence = o[1], .state = o[2] }; } +/// Whether `markovStepQ8` serves a drafter with the RNN's step columns `rnn_step` `[3R, 2R]` and the 8-bit fold +/// `fold_q` `[V, R]` (`MLX_SERVE_INKLING2_MARKOV_Q8`, opt-in). +pub fn markovQ8Runs(g: *const Graph, rnn_step: Array, fold_q: Array, rank: c_int) bool { + const dt = ops.dtype(rnn_step); + if (!mlx.streamIsGpu(g.s) or !enabled() or (dt != .bfloat16 and dt != .float16) or ops.dtype(fold_q) != .int8) return false; + return @rem(rank, 4) == 0 and @rem(3 * rank, 8) == 0; +} + +/// `markovStep` over the 8-bit fold: the step's RNN reads its block-row and newest-mix share from `kappa` +/// `[steps, 3R]` f32 (made once a block), and the fold `fold_q` `[V, R]` int8 with a scale a vocab row `fold_sc` `[V]` +/// f32; `base_b` `[1, steps, V]` f32 is the rows' head logits with the fold's bias in. +pub fn markovStepQ8(g: *Graph, rnn_step: Array, kappa: Array, state: Array, prev_rows: Array, token: Array, fold_q: Array, fold_sc: Array, base_b: Array, at: c_int, vocab: c_int, softcap: f32) !MarkovStep { + const step = try g.fromSlice(i32, &.{at}, &.{1}); + const cap = try g.fromSlice(f32, &.{softcap}, &.{1}); + const p = try markovStepRnn(g, rnn_step, kappa, state, prev_rows, token, step); + const o = try markovPick(g, try markovFoldQ8Row(g, p, fold_q, fold_sc, base_b, step, vocab, cap, ops.dtype(rnn_step)), p, state, cap); + return .{ .token = o[0], .confidence = o[1], .state = o[2] }; +} + +/// `markov_step_rnn.metal`: the step's RNN projection `[3 R]` f32 over `rnn_step` `[3 R, 2 R]` plus `kappa`'s row. +pub fn markovStepRnn(g: *Graph, rnn_step: Array, kappa: Array, state: Array, prev_rows: Array, token: Array, step: Array) !Array { + const rank = @divExact(ops.shape(rnn_step)[0], 3); + const o = try launch(g, &markov_step_rnn_kernel, &.{ rnn_step, kappa, state, prev_rows, token, step }, 1, .{.{ .shape = &.{3 * rank}, .dtype = .float32 }}, 32 * 3 * rank, 256, &.{ + .{ "T", .{ .dtype = ops.dtype(rnn_step) } }, .{ "R", .{ .int = rank } }, + }); + return o[0]; +} + +/// `markov_fold_q8_row.metal`: each threadgroup's (max, argmax, sum of exp) over 64 vocab rows of the 8-bit fold. +pub fn markovFoldQ8Row(g: *Graph, p: Array, fold_q: Array, fold_sc: Array, base_b: Array, step: Array, vocab: c_int, cap: Array, dt: Dtype) ![3]Array { + const groups = @divTrunc(vocab + 63, 64); + return launch(g, &markov_fold_q8_row_kernel, &.{ p, fold_q, fold_sc, base_b, step, cap }, 3, .{ + .{ .shape = &.{groups}, .dtype = .float32 }, .{ .shape = &.{groups}, .dtype = .uint32 }, .{ .shape = &.{groups}, .dtype = .float32 }, + }, groups * 256, 256, &.{ + .{ "T", .{ .dtype = dt } }, .{ "R", .{ .int = ops.shape(fold_q)[1] } }, .{ "VOCAB", .{ .int = vocab } }, + }); +} + /// `markov_rnn.metal`: the step's RNN projection `[3 R]` f32. pub fn markovRnn(g: *Graph, rnn: Array, rnn_bias: Array, state: Array, prev_rows: Array, rows: Array, newest: Array, token: Array, step: Array) !Array { const rank = @divExact(ops.shape(rnn)[0], 3); @@ -873,7 +1480,11 @@ pub fn markovPickRnnLaw(g: *Graph, part: [4]Array, p: Array, state: Array, cap: /// `[1, S, H, R]` and the sinks `[1, S, H]` f32. const ReadInputs = struct { q: Array, bias: Array, sinks: Array }; -fn readInputs(g: *Graph, L: *const Layer, cfg: *const Config, q_rows: Array, rel_states: Array, sinks: Array, offset: c_int) !ReadInputs { +/// `readInputs` before the bias projection: q, the relative states as the projection reads them (log-scaled on a +/// global layer past the floor) and the sinks. +const ReadStates = struct { q: Array, states: Array, sinks: Array }; + +fn readStates(g: *Graph, L: *const Layer, cfg: *const Config, q_rows: Array, rel_states: Array, sinks: Array, offset: c_int) !ReadStates { const dt = ops.dtype(q_rows); const s = ops.shape(q_rows)[1]; var q = try g.transpose(q_rows, &.{ 0, 2, 1, 3 }); @@ -884,9 +1495,15 @@ fn readInputs(g: *Graph, L: *const Layer, cfg: *const Config, q_rows: Array, rel q = try g.astype(try g.mul(try g.astype(q, .float32), tau), dt); states = try g.astype(try g.mul(try g.astype(states, .float32), try g.reshape(tau, &.{ 1, s, 1, 1 })), dt); } - return .{ .q = q, .bias = try g.matmul(states, try g.astype(L.rel_proj, dt)), .sinks = try g.contiguous(try g.astype(sinks, .float32)) }; + return .{ .q = q, .states = states, .sinks = try g.contiguous(try g.astype(sinks, .float32)) }; +} + +fn readInputs(g: *Graph, L: *const Layer, cfg: *const Config, q_rows: Array, rel_states: Array, sinks: Array, offset: c_int) !ReadInputs { + const r = try readStates(g, L, cfg, q_rows, rel_states, sinks, offset); + return .{ .q = r.q, .bias = try g.matmul(r.states, try g.astype(L.rel_proj, ops.dtype(q_rows))), .sinks = r.sinks }; } + /// Rows from which a read behind a cache splits over the keys (`splitRead`): below it MLX's attention under a mask is /// as fast; up to `split_rows`, the kernel's one 8-row fragment. pub const split_from = 4; @@ -1606,6 +2223,11 @@ pub fn mid(g: *Graph, L: *const Layer, w: *const Body, attn: Array, out_gate: ?A } pub fn midWith(g: *Graph, L: *const Layer, w: *const Body, attn: Array, out_gate: ?Array, h: Array, normed: Array, blocks: ?Array, st: Array, messages: ?Array, parent: ?Array) !Middle { + return midAt(g, .prompt, L, w, attn, out_gate, h, normed, blocks, st, messages, parent); +} + +/// `midWith` for a forward of `load`. +pub fn midAt(g: *Graph, load: Load, L: *const Layer, w: *const Body, attn: Array, out_gate: ?Array, h: Array, normed: Array, blocks: ?Array, st: Array, messages: ?Array, parent: ?Array) !Middle { const cfg = &w.cfg; const d: c_int = @intCast(cfg.hidden_size); const s = ops.shape(h)[1]; @@ -1644,7 +2266,7 @@ pub fn midWith(g: *Graph, L: *const Layer, w: *const Body, attn: Array, out_gate if (gates) |gs| { const state = try gateDowns(g, o[4], gs, 3, 1); const wide_router = s > packed_rows; - const xs = try normWithConsts(g, cfg, &w.consts, try gate(g, gs, o[3], msg3, state, 3, 1), @splat(L.post_norm), 1, dt, if (wide_router) null else L.router); + const xs = try normWithConsts(g, load, cfg, &w.consts, try gateAt(g, load, gs, o[3], msg3, state, 3, 1), @splat(L.post_norm), 1, dt, if (wide_router) null else L.router); x = xs[0]; scores = if (wide_router) try g.matmul(try g.astype(x, .float32), try g.transpose(L.router, &.{ 1, 0 })) else xs[1]; } else scores = if (s > 1 and s <= packed_rows) try routerRows(g, o[2], L.router) else try g.matmul(o[2], try g.transpose(L.router, &.{ 1, 0 })); @@ -1721,6 +2343,56 @@ fn biasesOf(bank: anytype) Array { return if (bank.b.ctx != null) bank.b else bank.s; } +/// The row map's gate, and so the gate_up epilogue's: a prompt chunk's rows on NAX, over a bank the mapped kernels' +/// own layout check takes (`rowMapTakes`). A bank it does not take is declined by name and keeps MLX's gather. +fn rowMapped(load: Load, s: c_int, bank: *const MoeBank) bool { + if (load != .prompt or s <= 1 or mainFor(.gather_rowmap) or !verifyQmmNaxAvailable()) return false; + if (rowMapTakes(bank)) return true; + var buf: [96]u8 = undefined; + declined(.gather_rowmap, rowMapLayout(&buf, bank)); + return false; +} + +/// Whether the row-mapped kernels decode `bank` (`gather_qmm_nax.bankLayoutOk`: NVFP4, MXFP4, affine 2, 3, 4, 8 bits). +pub fn rowMapTakes(bank: *const MoeBank) bool { + if (bank.s.ctx == null or ops.dtype(bank.w) != .uint32) return false; + return gnax.bankLayoutOk(bank.qp.bits, bank.qp.group_size, bank.qp.mode != .affine, ops.dtype(bank.s), if (bank.b.ctx != null) ops.dtype(bank.b) else null); +} + +/// A bank's layout as a decline names it: `mxfp8 8-bit g32 experts`, `dense experts`. +pub fn rowMapLayout(buf: []u8, bank: *const MoeBank) []const u8 { + if (bank.s.ctx == null) return "dense experts"; + return std.fmt.bufPrint(buf, "{s} {d}-bit g{d} experts, {s} scales", .{ @tagName(bank.qp.mode), bank.qp.bits, bank.qp.group_size, @tagName(ops.dtype(bank.s)) }) catch "an expert layout"; +} + +/// The sorted pairs' gate_up over the prompt rows `x` `[1, S, D]` read through `token` (each pair's row): the NAX +/// gather's mapped kernel, `[N, 1, out]`; null where it does not serve (no NAX, another format). +fn gatherMapped(g: *Graph, x: Array, token: Array, bank: *const MoeBank, sel: Array) !?Array { + const sh = ops.shape(x); + const rows = try g.reshape(x, &.{ sh[1], 1, sh[2] }); + const map = try g.contiguous(try g.astype(token, .uint32)); + const ids = try g.contiguous(try g.astype(sel, .uint32)); + const y = (try gnax.sortedGatherMappedPrompt(rows, map, bank.w, bank.s, bank.b, ids, bank.qp.bits, bank.qp.group_size, bank.qp.mode != .affine, verifyQmmNaxAvailable(), g.s)) orelse return null; + return try g.adopt(y); +} + +/// `gatherMapped` then `activation` as one launch: the NAX gather's interleaved epilogue takes the rounded gate (even) +/// and up (odd) products, times the expert's `scale` (null = none), through act.metal's soft-capped SwiGLU under +/// `caps`: `[N, 1, I]`, the same values. Null where it does not serve (a gate_up of rows not a multiple of 64), which +/// keeps `gatherMapped` and its own activation launch. +fn gatherMappedAct(g: *Graph, x: Array, token: Array, bank: *const MoeBank, sel: Array, scale: ?Array, caps: Array) !?Array { + if (mainFor(.gu_act)) return null; + const sh = ops.shape(x); + const banks = ops.shape(bank.w)[0]; + const per = if (scale) |sc| try g.reshape(try g.astype(sc, .float32), &.{banks}) else try g.ones(&.{banks}, .float32); + const aux = try g.contiguous(try g.concat(&.{ try g.astype(caps, .float32), per }, 0)); + const rows = try g.reshape(x, &.{ sh[1], 1, sh[2] }); + const map = try g.contiguous(try g.astype(token, .uint32)); + const ids = try g.contiguous(try g.astype(sel, .uint32)); + const y = (try gnax.sortedGateUpInterleaved(rows, map, bank.w, bank.s, bank.b, ids, aux, bank.qp.bits, bank.qp.group_size, bank.qp.mode != .affine, verifyQmmNaxAvailable(), g.s)) orelse return null; + return try g.adopt(y); +} + /// Tile width for grouped expert picks: 4 up to 128 picks (low register footprint for solo/2-slot verifies), 8 past that. pub fn groupTileWidth(n: c_int) c_int { return if (n <= 128) 4 else 8; @@ -1861,10 +2533,15 @@ pub fn topKGroup(g: *Graph, scores: Array, bias: Array, scale: Array, k: c_int, /// window. Another bank, or more rows (their pairs sorted by expert), go through `topK` and MLX's gather, with the /// SwiGLU and the sum, conv and add as launches of their own. pub fn experts(g: *Graph, L: *const Layer, cfg: *const Config, m: *const Middle, kp: Array, vp: Array, st: Array, open: ?*Open) !Tail { - return expertsWithConsts(g, L, cfg, null, m, kp, vp, st, open); + return expertsWithConsts(g, .prompt, L, cfg, null, m, kp, vp, st, open); } -fn expertsWithConsts(g: *Graph, L: *const Layer, cfg: *const Config, consts: ?*const layers.Consts, m: *const Middle, kp: Array, vp: Array, st: Array, open: ?*Open) !Tail { +/// `experts` for a forward of `load`. +pub fn expertsAt(g: *Graph, load: Load, L: *const Layer, cfg: *const Config, m: *const Middle, kp: Array, vp: Array, st: Array, open: ?*Open) !Tail { + return expertsWithConsts(g, load, L, cfg, null, m, kp, vp, st, open); +} + +fn expertsWithConsts(g: *Graph, load: Load, L: *const Layer, cfg: *const Config, consts: ?*const layers.Consts, m: *const Middle, kp: Array, vp: Array, st: Array, open: ?*Open) !Tail { const dt = ops.dtype(m.x); const s = ops.shape(m.x)[1]; const top_k: c_int = @intCast(cfg.top_k); @@ -1965,9 +2642,20 @@ fn expertsWithConsts(g: *Graph, L: *const Layer, cfg: *const Config, consts: ?*c const pairs = try layers.pairs(g, cfg, m.x, picks[0]); const sel = pairs.sel; const sorted = pairs.inverse != null; + // A prompt chunk's gate_up reads each sorted pair's row through its row map (the NAX gather's mapped kernel, the + // same tile and bytes), so the pairs' rows are never written out. A verify or batched slots keep MLX's gather and + // its bits. + const mapped: ?Array = if (rowMapped(load, s, &L.gate_up)) pairs.token else null; const act: [1]Array = if (up) |u| .{u[0]} else blk: { - const gu = try layers.gather(g, pairs.rows, &L.gate_up, sel, sorted); + if (mapped) |t| if (try gatherMappedAct(g, m.x, t, &L.gate_up, sel, if (L.gate_up_scale.ctx != null) L.gate_up_scale else null, caps)) |act_rows| { + engaged(.gather_rowmap); + engaged(.gu_act); + break :blk .{act_rows}; + }; + const by_map: ?Array = if (mapped) |t| try gatherMapped(g, m.x, t, &L.gate_up, sel) else null; + if (by_map != null) engaged(.gather_rowmap); + const gu = by_map orelse try layers.gather(g, pairs.rows, &L.gate_up, sel, sorted); if (!floating(ops.dtype(gu))) return error.Inkling2StepDtype; break :blk .{try activation(g, gu, sel, if (L.gate_up_scale.ctx != null) L.gate_up_scale else caps, caps, L.gate_up_scale.ctx != null)}; }; @@ -2022,15 +2710,16 @@ pub fn visit(c: *block.Ctx, L: *const Layer, w: *const Body, h: Array, blocks: ? const batch = c.slots > 1 and c.rows == 1; const held = if (c.slots > 1) try slot_state.get(c, .conv) else try kv.state(c, .conv); const st = held orelse try g.zeros(&.{ c.slots, @intCast(cfg.sconv_kernel - 1), @intCast(2 * cfg.kvDim() + 2 * cfg.hidden_size) }, .float32); - const f = try pre(g, L, w, h, blocks, bank); + const load = Load.of(c.mode); + const f = try preAt(g, load, L, w, h, blocks, bank); const total = @as(c_int, @intCast(c.offset())) + 1; const one = c.rows == 1 and !batch; const tree_parent: ?Array = if (open) |o| (if (o.tree) |t| t.parent else null) else null; - const p = (try prepWithConsts(g, L, cfg, &w.consts, &f.proj, f.dyn, st, if (one and L.global) layers.stepTau(cfg, total) else 1.0, if (one) keysSeen(L, cfg, total) else 0, tree_parent)) orelse return null; + const p = (try prepWithConsts(g, load, L, cfg, &w.consts, &f.proj, f.dyn, st, if (one and L.global) layers.stepTau(cfg, total) else 1.0, if (one) keysSeen(L, cfg, total) else 0, tree_parent)) orelse return null; const fuse = one and open == null and oFormat(&L.o, ops.dtype(h)) != null; const read = if (batch) try attendSlots(c, L, cfg, &w.consts, &p, f.proj[3]) else try attend(c, L, cfg, &w.consts, &p, f.proj[3], open, fuse); - const m = try midWith(g, L, w, read, if (fuse) p.gate else null, h, f.normed, blocks, st, f.messages, tree_parent); - const t = try expertsWithConsts(g, L, cfg, &w.consts, &m, f.proj[4], f.proj[5], st, open); + const m = try midAt(g, load, L, w, read, if (fuse) p.gate else null, h, f.normed, blocks, st, f.messages, tree_parent); + const t = try expertsWithConsts(g, load, L, cfg, &w.consts, &m, f.proj[4], f.proj[5], st, open); if (open == null) { if (batch) try slot_state.put(c, .conv, t.state) else try kv.setState(c, .conv, t.state); } @@ -2180,3 +2869,37 @@ test "inkling2 kernels: a threadgroup past the pipeline's limit is refused by na stream_threads = 64; try std.testing.expect(streamGroup(64).? == 64 and narrow(64) and streamGroup(64).? == 32 and !narrow(64)); } + +test "inkling2 pipeline record: a scalar input parses to no dimensions; a malformed line is an error, not a record's end" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const r = (try parseRecordLine(a, "msv_inkling2_relsplit\t96,8,1\t96,1,1\tT=d12;D=i128;F=f1;\t12:1x24x8x128;10:;\t10:1x192x2;")).?; + try std.testing.expectEqual(@as(usize, 2), r.ins.len); + try std.testing.expectEqual(@as(usize, 0), r.ins[1].shape.len); + try std.testing.expectEqual(@as(usize, 4), r.ins[0].shape.len); + try std.testing.expectEqual(@as(usize, 3), r.targs.len); + try std.testing.expectError(error.PipelineRecordLine, parseRecordLine(a, "msv_inkling2_relsplit\t96,8")); + try std.testing.expect((try parseRecordLine(a, "msv_not_a_kernel\t1,1,1")) == null); +} + +test "inkling2 kernels: only a prompt chunk is a prompt's load; the row norm takes a prompt's rows at a threadgroup wide enough" { + try std.testing.expectEqual(Load.prompt, Load.of(.prefill)); + for ([_]abi.Mode{ .decode, .verify, .batched_rows }) |m| try std.testing.expectEqual(Load.step, Load.of(m)); + try std.testing.expect(!streamRow(.step, 512, 2304, 768)); + try std.testing.expect(!streamRow(.prompt, small_rows, 2304, 768)); + // Narrowed to 288 threads a thread would keep 8 elements of a row: the D / TG grid serves it. + try std.testing.expect(!streamRow(.prompt, 512, 2304, 288)); + // The row norm runs on NAX only. + if (!verifyQmmNaxAvailable()) return error.SkipZigTest; + try std.testing.expect(streamRow(.prompt, 512, 2304, 768)); +} + +test "inkling2 kernels: an engagement flag is its own path's" { + resetEngaged(.gate_mm); + resetEngaged(.stream_row); + engaged(.gate_mm); + try std.testing.expect(wasEngaged(.gate_mm)); + try std.testing.expect(!wasEngaged(.stream_row)); + resetEngaged(.gate_mm); +} diff --git a/src/plugins/inkling2/kernels/gate_mm.metal b/src/plugins/inkling2/kernels/gate_mm.metal new file mode 100644 index 0000000000..eda868b267 --- /dev/null +++ b/src/plugins/inkling2/kernels/gate_mm.metal @@ -0,0 +1,69 @@ +// Inkling 2: a prompt chunk's J loop message gates as one tiled kernel (`kernels.gateAt` past 64 rows). A, MS [J, S, D] +// f32 the gated streams and their messages, ST [J, S, RANK] each gate's state, F and G [J, D, RANK] the forget and +// message projections (their stored float dtype). A threadgroup of NT threads (BM / 16 x 2 SIMD groups) takes a BM-row +// by 32-column tile of one gate: the states' and both projections' slices staged as exact f32 in threadgroup +// memory, F st and G st on the matrix units (simdgroup_float8x8, f32 accumulate over RANK in 8-wide steps), then +// Y [J, S, D] f32 = (1 - tanh(F st)) A + tanh(G st) MS from the staged sums; no [J, S, D] product is written out. +// grid (NT * D / 32, ceil(S / BM), J), threadgroup (NT, 1, 1). D and RANK multiples of 32. +// BM: the tile's rows (64 served: eight SIMD groups, 256 threads). Each output's sum over RANK runs the same 8-wide +// steps in the same order at any BM, so the same bits; a taller tile stages each projection slice for more rows. +constexpr uint NT = (BM / 16) * 2 * 32; +const uint t = thread_position_in_threadgroup.x; +const uint S = ST_shape[1]; +const uint c0 = threadgroup_position_in_grid.x * 32; +const uint r0 = threadgroup_position_in_grid.y * BM; +const uint j = threadgroup_position_in_grid.z; +const uint sg = t / 32; +const uint sr = (sg / 2) * 16; +const uint sc = (sg % 2) * 16; +threadgroup float ts[BM * 32]; +threadgroup float tf[32 * 32]; +threadgroup float tq[BM * 32]; +simdgroup_float8x8 af[2][2]; +simdgroup_float8x8 aq[2][2]; +for (uint m = 0; m < 2; m++) for (uint n = 0; n < 2; n++) { + af[m][n] = make_filled_simdgroup_matrix(0.0f); + aq[m][n] = make_filled_simdgroup_matrix(0.0f); +} +for (uint k0 = 0; k0 < RANK; k0 += 32) { + for (uint e = t; e < BM * 32; e += NT) { + const uint a = e / 32, k = e % 32; + const uint row = r0 + a; + ts[e] = row < S ? float(ST[(j * S + row) * RANK + k0 + k]) : 0.0f; + } + for (uint e = t; e < 1024; e += NT) { + const uint a = e / 32, k = e % 32; + tf[e] = float(F[(j * D + c0 + a) * RANK + k0 + k]); + tq[e] = float(G[(j * D + c0 + a) * RANK + k0 + k]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint kk = 0; kk < 32; kk += 8) { + simdgroup_float8x8 x[2]; + simdgroup_float8x8 bf[2]; + simdgroup_float8x8 bq[2]; + for (uint m = 0; m < 2; m++) simdgroup_load(x[m], ts + (sr + m * 8) * 32 + kk, 32); + // A projection's rows are output columns: loaded transposed, B[k][c] = F[c][k]. + for (uint n = 0; n < 2; n++) { + simdgroup_load(bf[n], tf + (sc + n * 8) * 32 + kk, 32, ulong2(0, 0), true); + simdgroup_load(bq[n], tq + (sc + n * 8) * 32 + kk, 32, ulong2(0, 0), true); + } + for (uint m = 0; m < 2; m++) for (uint n = 0; n < 2; n++) { + simdgroup_multiply_accumulate(af[m][n], x[m], bf[n], af[m][n]); + simdgroup_multiply_accumulate(aq[m][n], x[m], bq[n], aq[m][n]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} +for (uint m = 0; m < 2; m++) for (uint n = 0; n < 2; n++) { + simdgroup_store(af[m][n], ts + (sr + m * 8) * 32 + sc + n * 8, 32); + simdgroup_store(aq[m][n], tq + (sr + m * 8) * 32 + sc + n * 8, 32); +} +threadgroup_barrier(mem_flags::mem_threadgroup); +for (uint e = t; e < BM * 32; e += NT) { + const uint a = e / 32, c = e % 32; + const uint row = r0 + a; + if (row >= S) continue; + const uint at = (j * S + row) * D + c0 + c; + // The precise tanh, as gate.metal. + Y[at] = (1.0f - precise::tanh(ts[e])) * A[at] + precise::tanh(tq[e]) * MS[at]; +} diff --git a/src/plugins/inkling2/kernels/markov_fold_q8_row.metal b/src/plugins/inkling2/kernels/markov_fold_q8_row.metal new file mode 100644 index 0000000000..873a08168f --- /dev/null +++ b/src/plugins/inkling2/kernels/markov_fold_q8_row.metal @@ -0,0 +1,104 @@ +// Inkling 2's drafter, one Markov step over coalesced per-vocab-row Q8 fold (64 vocab rows per threadgroup): +// FQ [V, R] int8, FSC [V] f32, BASE [1, steps, V] f32 (fold_bias pre-added), P [3 R] f32, AT [1] i32, CAP [1] f32. +// grid (ceil(VOCAB / 64) * 256, 1, 1), threadgroup (256, 1, 1): 8 SIMD groups x 8 contiguous vocab rows = 64 rows/TG. +threadgroup float sh_lat[R]; +threadgroup float sh_lg[64]; +threadgroup float rm[8]; +threadgroup uint ri[8]; +threadgroup float rs[2]; +constexpr uint NONE = 0xffffffffu; +const uint t = thread_position_in_threadgroup.x; +const uint tg = threadgroup_position_in_grid.x; +const uint lane = thread_index_in_simdgroup; +const uint sg = t >> 5; +const uint V = FQ_shape[0]; +const size_t at = size_t(AT[0]); + +for (uint r = t; r < R; r += 256) sh_lat[r] = float(T(metal::precise::tanh(P[2 * R + r]))); +threadgroup_barrier(mem_flags::mem_threadgroup); + +const device float* brow = BASE + at * V; +float m = -INFINITY; +uint mi = NONE; + +for (uint pass = 0u; pass < 2u; ++pass) { + const uint v0 = tg * 64u + pass * 32u + sg * 4u; + const bool full4 = (v0 + 3u) < VOCAB; + float a0 = 0.0f, a1 = 0.0f, a2 = 0.0f, a3 = 0.0f; + if (full4) { + const device char4* q0 = (const device char4*)(FQ + size_t(v0 + 0u) * R); + const device char4* q1 = (const device char4*)(FQ + size_t(v0 + 1u) * R); + const device char4* q2 = (const device char4*)(FQ + size_t(v0 + 2u) * R); + const device char4* q3 = (const device char4*)(FQ + size_t(v0 + 3u) * R); + for (uint k = lane; k < R / 4u; k += 32u) { + const float4 xv = ((const threadgroup float4*)sh_lat)[k]; + a0 += dot(float4(q0[k]), xv); + a1 += dot(float4(q1[k]), xv); + a2 += dot(float4(q2[k]), xv); + a3 += dot(float4(q3[k]), xv); + } + } else if (v0 < VOCAB) { + for (uint k = lane; k < R / 4u; k += 32u) { + const float4 xv = ((const threadgroup float4*)sh_lat)[k]; + a0 += dot(float4(((const device char4*)(FQ + size_t(v0) * R))[k]), xv); + if (v0 + 1u < VOCAB) a1 += dot(float4(((const device char4*)(FQ + size_t(v0 + 1u) * R))[k]), xv); + if (v0 + 2u < VOCAB) a2 += dot(float4(((const device char4*)(FQ + size_t(v0 + 2u) * R))[k]), xv); + } + } + const float ds[4] = { simd_sum(a0), simd_sum(a1), simd_sum(a2), simd_sum(a3) }; + if (lane == 0u) { + for (uint j = 0u; j < 4u; ++j) { + const uint v = v0 + j; + float lg = -INFINITY; + if (v < VOCAB) { + lg = brow[v] + ds[j] * FSC[v]; + if (mi == NONE || msv_ink2_better(lg, v, m, mi)) { + m = lg; + mi = v; + } + } + sh_lg[pass * 32u + sg * 4u + j] = lg; + } + } +} + +if (lane == 0u) { + rm[sg] = m; + ri[sg] = mi; +} +threadgroup_barrier(mem_flags::mem_threadgroup); + +if (t < 64u) { + float top = rm[0]; + uint at_top = ri[0]; + for (uint g = 1u; g < 8u; ++g) { + if (ri[g] != NONE && (at_top == NONE || msv_ink2_better(rm[g], ri[g], top, at_top))) { + top = rm[g]; + at_top = ri[g]; + } + } + const float cap = CAP[0]; + const float ctop = cap > 0 ? cap * metal::precise::tanh(top / cap) : top; + const uint v = tg * 64u + t; + float ex = 0.0f; + if (v < VOCAB) { + const float lv = sh_lg[t]; + ex = metal::precise::exp((cap > 0 ? cap * metal::precise::tanh(lv / cap) : lv) - ctop); + } + const float s = simd_sum(ex); + if (lane == 0u) rs[sg] = s; +} +threadgroup_barrier(mem_flags::mem_threadgroup); +if (t == 0u) { + float top = rm[0]; + uint at_top = ri[0]; + for (uint g = 1u; g < 8u; ++g) { + if (ri[g] != NONE && (at_top == NONE || msv_ink2_better(rm[g], ri[g], top, at_top))) { + top = rm[g]; + at_top = ri[g]; + } + } + PM[tg] = top; + PI[tg] = at_top; + PS[tg] = rs[0] + rs[1]; +} diff --git a/src/plugins/inkling2/kernels/markov_step_rnn.metal b/src/plugins/inkling2/kernels/markov_step_rnn.metal new file mode 100644 index 0000000000..c625d8172c --- /dev/null +++ b/src/plugins/inkling2/kernels/markov_step_rnn.metal @@ -0,0 +1,16 @@ +// Inkling 2's drafter, one Markov RNN step with precomputed static context KAPPA [steps, 3 R] f32: +// P [3 R] f32 = T(W_step . [ST | PREV[TOK]] + KAPPA[AT]), where W_step is [3 R, 2 R] (T), ST [R] (T), PREV [V, R] (T), +// TOK [1] and AT [1] int32. One SIMD group per row of W_step. +const uint row = thread_position_in_grid.x / 32; +const uint lane = thread_index_in_simdgroup; +constexpr uint IN = 2 * R; +const size_t tok = size_t(TOK[0]); +const uint at = uint(AT[0]); +const device T* w = W + size_t(row) * IN; +float acc = 0.0f; +for (uint c = lane; c < IN; c += 32) { + const float x = c < R ? float(ST[c]) : float(PREV[tok * R + (c - R)]); + acc += float(w[c]) * x; +} +acc = simd_sum(acc); +if (lane == 0) P[row] = float(T(acc + KAPPA[size_t(at) * (3 * R) + row])); diff --git a/src/plugins/inkling2/kernels/norm.metal b/src/plugins/inkling2/kernels/norm.metal index ec3111d795..2f952caeab 100644 --- a/src/plugins/inkling2/kernels/norm.metal +++ b/src/plugins/inkling2/kernels/norm.metal @@ -2,6 +2,9 @@ // grid (D, S), threadgroup (TG, 1): one thread per stream element of a row; sums as pre.metal's. X [J, S, D] T. With // E > 0 also SCORES [S, E] f32 = the router's rows RT [E, D] f32 over X's first stream: a row's last E * 32 threads, // a SIMD group per expert, redo the sums as their threadgroup. +// ROW 1 (a prompt's rows): grid (TG + the router's threads, S), one threadgroup a row's stream, each thread writing its +// D / TG elements (at most 4: `kernels.row_elems`), kept in registers; ROW 0: grid (D + the router's threads, S), each +// thread keeping the one element it writes. The same sums either way. const uint t = thread_position_in_threadgroup.x; const uint e = thread_position_in_grid.x; const uint row = thread_position_in_grid.y; @@ -12,12 +15,15 @@ constexpr uint NSG = TG / 32; threadgroup float red[NSG * J]; // The streams' folds of the SIMD groups' partial sums, each by one thread in the order every thread used to run it. threadgroup float fold[J]; -float ss[J], mine[J]; +constexpr uint KEEP = ROW ? D / TG : 1; +float ss[J], mine[J][KEEP]; for (uint j = 0; j < J; j++) ss[j] = 0.0f; -for (uint i = t; i < D; i += TG) for (uint j = 0; j < J; j++) { +for (uint k = 0; k < D / TG; k++) for (uint j = 0; j < J; j++) { + const uint i = t + k * TG; const float y = Y[(j * S + row) * D + i]; ss[j] += y * y; - if (i == e) mine[j] = y; + if (ROW) mine[j][k] = y; + else if (i == e) mine[j][0] = y; } for (uint j = 0; j < J; j++) { ss[j] = simd_sum(ss[j]); @@ -31,15 +37,20 @@ for (uint j = t; j < J; j += TG) { } threadgroup_barrier(mem_flags::mem_threadgroup); for (uint j = 0; j < J; j++) ss[j] = metal::precise::rsqrt(fold[j] / float(D) + PR[0]); -if (e >= D) { - const uint ex = (e - D) / 32; +constexpr uint W = ROW ? TG : D; +if (e >= W) { + const uint ex = (e - W) / 32; float dot = 0.0f; if (ex < E) for (uint i = lane; i < D; i += 32) dot += float(T(Y[row * D + i] * ss[0] * float(NW0[i]))) * float(RT[ex * D + i]); dot = simd_sum(dot); if (lane == 0 && ex < E) SCORES[row * E + ex] = dot; return; } -for (uint j = 0; j < J; j++) { - const float nw = float(j == 0 ? NW0[e] : (j == 1 ? NW1[e] : NW2[e])); - X[(j * S + row) * D + e] = T(mine[j] * ss[j] * nw); +for (uint q = 0; q < (ROW ? D / TG : 1); q++) { + const uint k = ROW ? q : 0; + const uint c = ROW ? t + q * TG : e; + for (uint j = 0; j < J; j++) { + const float nw = float(j == 0 ? NW0[c] : (j == 1 ? NW1[c] : NW2[c])); + X[(j * S + row) * D + c] = T(mine[j][k] * ss[j] * nw); + } } diff --git a/src/plugins/inkling2/kernels/norm_step.metal b/src/plugins/inkling2/kernels/norm_step.metal new file mode 100644 index 0000000000..ec3111d795 --- /dev/null +++ b/src/plugins/inkling2/kernels/norm_step.metal @@ -0,0 +1,45 @@ +// Inkling 2: J streams of S rows, Y [J, S, D] f32, under their weighted RMS norms (weights NW0..NW2 [D], eps PR[0]). +// grid (D, S), threadgroup (TG, 1): one thread per stream element of a row; sums as pre.metal's. X [J, S, D] T. With +// E > 0 also SCORES [S, E] f32 = the router's rows RT [E, D] f32 over X's first stream: a row's last E * 32 threads, +// a SIMD group per expert, redo the sums as their threadgroup. +const uint t = thread_position_in_threadgroup.x; +const uint e = thread_position_in_grid.x; +const uint row = thread_position_in_grid.y; +const uint S = Y_shape[1]; +const uint lane = thread_index_in_simdgroup; +const uint sg = t / 32; +constexpr uint NSG = TG / 32; +threadgroup float red[NSG * J]; +// The streams' folds of the SIMD groups' partial sums, each by one thread in the order every thread used to run it. +threadgroup float fold[J]; +float ss[J], mine[J]; +for (uint j = 0; j < J; j++) ss[j] = 0.0f; +for (uint i = t; i < D; i += TG) for (uint j = 0; j < J; j++) { + const float y = Y[(j * S + row) * D + i]; + ss[j] += y * y; + if (i == e) mine[j] = y; +} +for (uint j = 0; j < J; j++) { + ss[j] = simd_sum(ss[j]); + if (lane == 0) red[sg * J + j] = ss[j]; +} +threadgroup_barrier(mem_flags::mem_threadgroup); +for (uint j = t; j < J; j += TG) { + float s = 0.0f; + for (uint g = 0; g < NSG; g++) s += red[g * J + j]; + fold[j] = s; +} +threadgroup_barrier(mem_flags::mem_threadgroup); +for (uint j = 0; j < J; j++) ss[j] = metal::precise::rsqrt(fold[j] / float(D) + PR[0]); +if (e >= D) { + const uint ex = (e - D) / 32; + float dot = 0.0f; + if (ex < E) for (uint i = lane; i < D; i += 32) dot += float(T(Y[row * D + i] * ss[0] * float(NW0[i]))) * float(RT[ex * D + i]); + dot = simd_sum(dot); + if (lane == 0 && ex < E) SCORES[row * E + ex] = dot; + return; +} +for (uint j = 0; j < J; j++) { + const float nw = float(j == 0 ? NW0[e] : (j == 1 ? NW1[e] : NW2[e])); + X[(j * S + row) * D + e] = T(mine[j] * ss[j] * nw); +} diff --git a/src/plugins/inkling2/kernels/prep.metal b/src/plugins/inkling2/kernels/prep.metal index 46bbd9c6ea..bca7bc5d35 100644 --- a/src/plugins/inkling2/kernels/prep.metal +++ b/src/plugins/inkling2/kernels/prep.metal @@ -7,7 +7,8 @@ // its own). Static convs take KW, VW [C, KT, 1] (WT) and round their sum to WT as the conv op does; dynamic ones (DYN) // take KW, VW [KT, C] (WT) plus each head's projected taps KDY, VDY [1, S, HKV * KT] (T), tap `lag` on the input // `lag` rows back. QS [H, HD] and RS [H, DREL] (S) scale q and the relative states before their L2 clips. -// PR = { qk clip, rel clip, eps, tau, conv scale, KV }. +// PR = { qk clip, rel clip, eps, tau, conv scale, KV }. QP, GP, RP, KP and VP are read by their row strides (unit +// last stride): a joined projection's parts arrive as views. // Q [1, S, H, HD] T (clipped, times tau), GATE [S * H * HD] f32 (sigmoid), K, V [1, HKV, S, HD] T (conv, then the L2 // clip or the unweighted RMS norm). The tail is, WIDE: REL [1, S, H, DREL] T, the clipped relative states; else (one // row): BIAS [1, H, 1, KV] T, the row's additive bias over its KV keys, the newest last (the clipped states through @@ -23,11 +24,12 @@ const uint C = HKV * HD; const uint R = RJ_shape[1]; const uint SW = ST_shape[2]; const float qk_thr = PR[0], rel_thr = PR[1], eps = PR[2], tau = PR[3], cs = PR[4]; +const uint QRS = QP_strides[1], GRS = GP_strides[1], RRS = RP_strides[1], KRS = KP_strides[1], VRS = VP_strides[1]; threadgroup float buf[HD]; threadgroup float n2_sh; if (i < QD) { const uint at = row * QD + i; - const float mine = float(QP[at]) * float(QS[i]); + const float mine = float(QP[row * QRS + i]) * float(QS[i]); buf[t] = mine * mine; threadgroup_barrier(mem_flags::mem_threadgroup); if (t == 0) { @@ -41,7 +43,7 @@ if (i < QD) { T q = T(mine * f); if (tau != 1.0f) q = T(float(q) * tau); Q[at] = q; - GATE[at] = 1.0f / (1.0f + exp(-float(GP[at]))); + GATE[at] = 1.0f / (1.0f + exp(-float(GP[row * GRS + i]))); return; } uint r = i - QD; @@ -50,7 +52,7 @@ if (r < 2 * C) { const uint c = is_v ? r - C : r; const uint h = c / HD; const uint off = is_v ? C : 0u; - const float x = float(is_v ? VP[row * C + c] : KP[row * C + c]); + const float x = float(is_v ? VP[row * VRS + c] : KP[row * KRS + c]); const uint slot = row / RPS; float y = 0.0f; for (uint j = 0; j < KT; j++) { @@ -64,7 +66,7 @@ if (r < 2 * C) { } float wv = x; if (p < 0) wv = ST[(slot * (KT - 1) + uint(int(KT - 1) + p)) * SW + off + c]; - else if (j + 1 < KT) wv = float(is_v ? VP[(slot * RPS + uint(p)) * C + c] : KP[(slot * RPS + uint(p)) * C + c]); + else if (j + 1 < KT) wv = float(is_v ? VP[(slot * RPS + uint(p)) * VRS + c] : KP[(slot * RPS + uint(p)) * KRS + c]); float wt; if (DYN) { const uint lag = KT - 1 - j; @@ -104,19 +106,20 @@ if (!WIDE) { } } const uint rp = row * H * DREL + h * DREL; +const uint rin = row * RRS + h * DREL; float n2 = 0.0f; for (uint j = 0; j < DREL; j++) { - const float v = float(RP[rp + j]) * float(RS[h * DREL + j]); + const float v = float(RP[rin + j]) * float(RS[h * DREL + j]); n2 += v * v; } const float f = min(rel_thr / (sqrt(n2) + 1e-6f), 1.0f); if (WIDE) { const uint j = r % DREL; - REL[rp + j] = T(float(RP[rp + j]) * float(RS[h * DREL + j]) * f); + REL[rp + j] = T(float(RP[rin + j]) * float(RS[h * DREL + j]) * f); return; } const uint col = r % KV; const uint d = col + R - KV; float acc = 0.0f; -for (uint j = 0; j < DREL; j++) acc += float(T(float(RP[rp + j]) * float(RS[h * DREL + j]) * f)) * RJ[j * R + d]; +for (uint j = 0; j < DREL; j++) acc += float(T(float(RP[rin + j]) * float(RS[h * DREL + j]) * f)) * RJ[j * R + d]; BIAS[r] = T(acc * tau); diff --git a/src/plugins/inkling2/kernels/prep_step.metal b/src/plugins/inkling2/kernels/prep_step.metal new file mode 100644 index 0000000000..46bbd9c6ea --- /dev/null +++ b/src/plugins/inkling2/kernels/prep_step.metal @@ -0,0 +1,122 @@ +// Inkling 2: what the attention read needs from a visit's projections for S rows. grid (H * HD + 2 * HKV * HD + the +// tail, S), threadgroup (HD, 1): one thread per output element of a row, a head of q, k or v one threadgroup whose +// threads each square their own element into BUF for the group to sum, so no thread loops over a head's inputs. +// QP, GP [1, S, H * HD], RP [1, S, H * DREL], KP, VP [1, S, HKV * HD] are the q, gate, relative, k and v projections +// (T); the k and v convs run over the rows behind the windows before them (ST [NSLOT, KT - 1, >= 2 * HKV * HD] f32, k +// then v): RPS rows of ROWS make a slot, each slot behind its own window (RPS == ROWS: one sequence; 1: every row a sequence of +// its own). Static convs take KW, VW [C, KT, 1] (WT) and round their sum to WT as the conv op does; dynamic ones (DYN) +// take KW, VW [KT, C] (WT) plus each head's projected taps KDY, VDY [1, S, HKV * KT] (T), tap `lag` on the input +// `lag` rows back. QS [H, HD] and RS [H, DREL] (S) scale q and the relative states before their L2 clips. +// PR = { qk clip, rel clip, eps, tau, conv scale, KV }. +// Q [1, S, H, HD] T (clipped, times tau), GATE [S * H * HD] f32 (sigmoid), K, V [1, HKV, S, HD] T (conv, then the L2 +// clip or the unweighted RMS norm). The tail is, WIDE: REL [1, S, H, DREL] T, the clipped relative states; else (one +// row): BIAS [1, H, 1, KV] T, the row's additive bias over its KV keys, the newest last (the clipped states through +// RJ [DREL, R] f32, distance 0 last, times tau; zero for a key past the extent R). +const uint i = thread_position_in_grid.x; +const uint row = thread_position_in_grid.y; +const uint ROWS = QP_shape[1]; +const uint RPS = ROWS / ST_shape[0]; +const uint pos = row % RPS; +const uint t = thread_position_in_threadgroup.x; +const uint QD = H * HD; +const uint C = HKV * HD; +const uint R = RJ_shape[1]; +const uint SW = ST_shape[2]; +const float qk_thr = PR[0], rel_thr = PR[1], eps = PR[2], tau = PR[3], cs = PR[4]; +threadgroup float buf[HD]; +threadgroup float n2_sh; +if (i < QD) { + const uint at = row * QD + i; + const float mine = float(QP[at]) * float(QS[i]); + buf[t] = mine * mine; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float s = 0.0f; + for (uint j = 0; j < HD; j++) s += buf[j]; + n2_sh = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float n2 = n2_sh; + const float f = min(qk_thr / (sqrt(n2) + 1e-6f), 1.0f); + T q = T(mine * f); + if (tau != 1.0f) q = T(float(q) * tau); + Q[at] = q; + GATE[at] = 1.0f / (1.0f + exp(-float(GP[at]))); + return; +} +uint r = i - QD; +if (r < 2 * C) { + const bool is_v = r >= C; + const uint c = is_v ? r - C : r; + const uint h = c / HD; + const uint off = is_v ? C : 0u; + const float x = float(is_v ? VP[row * C + c] : KP[row * C + c]); + const uint slot = row / RPS; + float y = 0.0f; + for (uint j = 0; j < KT; j++) { + // Tap j reads row `pos + j` of [the slot's ST | its rows], or walks PARENT on a tree. + int p; + if constexpr (TREE) { + p = int(pos); + for (uint stp = 0; stp < KT - 1 - j; ++stp) p = (p >= 0) ? PARENT[slot * RPS + uint(p)] : (p - 1); + } else { + p = int(pos) + int(j) - int(KT - 1); + } + float wv = x; + if (p < 0) wv = ST[(slot * (KT - 1) + uint(int(KT - 1) + p)) * SW + off + c]; + else if (j + 1 < KT) wv = float(is_v ? VP[(slot * RPS + uint(p)) * C + c] : KP[(slot * RPS + uint(p)) * C + c]); + float wt; + if (DYN) { + const uint lag = KT - 1 - j; + const uint tap = (row * HKV + h) * KT + lag; + wt = float(is_v ? VW[lag * C + c] : KW[lag * C + c]) + float(is_v ? VDY[tap] : KDY[tap]); + } else { + wt = float(is_v ? VW[c * KT + j] : KW[c * KT + j]); + } + y += wv * wt; + } + if (!DYN) y = float(WT(y)); + const float mine = float(T((y + x) * cs)); + buf[t] = mine * mine; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float s = 0.0f; + for (uint j = 0; j < HD; j++) s += buf[j]; + n2_sh = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float n2 = n2_sh; + const uint at = (h * ROWS + row) * HD + c % HD; + if (is_v) V[at] = T(mine * rsqrt(n2 / float(HD) + eps)); + else K[at] = T(mine * min(qk_thr / (sqrt(n2) + 1e-6f), 1.0f)); + return; +} +r -= 2 * C; +// A head's relative states, clipped. +const uint KV = WIDE ? 0u : uint(PR[5]); +const uint h = WIDE ? r / DREL : r / KV; +if (!WIDE) { + const uint col = r % KV; + // Key `col` sits R - KV + col columns into the logits; keys past R are zero. + if (col + R < KV) { + BIAS[r] = T(0.0f); + return; + } +} +const uint rp = row * H * DREL + h * DREL; +float n2 = 0.0f; +for (uint j = 0; j < DREL; j++) { + const float v = float(RP[rp + j]) * float(RS[h * DREL + j]); + n2 += v * v; +} +const float f = min(rel_thr / (sqrt(n2) + 1e-6f), 1.0f); +if (WIDE) { + const uint j = r % DREL; + REL[rp + j] = T(float(RP[rp + j]) * float(RS[h * DREL + j]) * f); + return; +} +const uint col = r % KV; +const uint d = col + R - KV; +float acc = 0.0f; +for (uint j = 0; j < DREL; j++) acc += float(T(float(RP[rp + j]) * float(RS[h * DREL + j]) * f)) * RJ[j * R + d]; +BIAS[r] = T(acc * tau); diff --git a/src/plugins/inkling2/kernels/relative_attention_nax.metal b/src/plugins/inkling2/kernels/relative_attention_nax.metal new file mode 100644 index 0000000000..2678aab2ea --- /dev/null +++ b/src/plugins/inkling2/kernels/relative_attention_nax.metal @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: Apache-2.0 +// relative_attention on the NAX tiles: MLX's attention_nax loop (Copyright (c) 2024-25 Apple Inc., MIT, via oMLX's +// port in kernels/attention/nax_attention.metal) with relative_attention's score: the relative bias by distance, a +// sink logit per query, the band and key_start. Header: nax_tiles.metal + nax_attention.metal. D is 128. +static_assert(D == 128, "the P x V barrier and the pair MMAs assume head dim 128"); +constexpr short kU = 16; +constexpr int BQ = 64; +constexpr int BK = 32; +constexpr int TD = D / kU; +constexpr short TK = BK / kU; +constexpr float LOG2E = 1.44269504089f; +using otile_t = omlx_nax::NAXTile; +using stile_t = omlx_nax::NAXTile; +constexpr short kRowsPT = otile_t::kRowsPerThread; + +const int L = sizes[0]; +const int S = sizes[1]; +const int start = key_start[0]; +const uint3 tid = threadgroup_position_in_grid; +const int head = tid.y; +const int kv_head = head / (HQ / HKV); +const int q0 = tid.x * BQ; +const short tm = kU * simdgroup_index_in_threadgroup; +const int qld = int(q_strides[2]); +const int kld = int(k_strides[2]); +const int vld = int(v_strides[2]); +const device T* Q = q + head * q_strides[1] + int64_t(q0 + tm) * qld; +const device T* K = k + kv_head * k_strides[1]; +const device T* V = v + kv_head * v_strides[1]; + +otile_t Otile; +Otile.clear(); +const short2 coord = otile_t::NAXFrag_t::get_coord(); +const short sm = coord.y; +const short sn = coord.x; + +// This thread's two rows: each online softmax starts from its sink logit (rows past L from 0). +int rows[kRowsPT]; +metal::vec max_score; +metal::vec sum_score; +OMLX_NAX_UNROLL +for (short i = 0; i < kRowsPT; ++i) { + rows[i] = q0 + tm + sm + i * otile_t::kFragRowsJump; + const bool ok = rows[i] < L; + max_score[i] = ok ? sinks[rows[i] * HQ + head] * LOG2E : 0.0f; + sum_score[i] = 1.0f; +} + +const int off = S - L; +const int first_diag = off + q0; +const int last_diag = off + min(q0 + BQ, L) - 1; +int first_key = WINDOW > 0 ? max(0, first_diag - WINDOW + 1) : 0; +first_key = max(first_key, start); +const int NK = (S + BK - 1) / BK; +const int NK_aligned = S / BK; +const int kb_lo = first_key / BK; +const int kb_hi = min(NK, last_diag / BK + 1); +const int lim_rows_q = min(L - (q0 + tm), int(kU)); +const int lim_rows_k = S - NK_aligned * BK; +const int srow_lo = q0 + tm; +const int srow_hi = min(q0 + tm + kU, L) - 1; +const float scale2 = scale * LOG2E; +K += int64_t(kb_lo) * BK * kld; +V += int64_t(kb_lo) * BK * vld; + +// `rel` is the rows' clipped relative states [S, HQ, 16] (T) and `relp` the bias projection +// [16, RP] (T) with PADL zero columns before distance 0 and zeros past R. For each 16-row, 32-key block the bias at +// the block's 47 distances is one product on the tensor units, states [16 x 16] times relp's 64 columns from the +// block's least distance, in f32 (no bf16 rounding of the bias), staged in threadgroup memory for the scores. +constexpr int MLD = 49; +constexpr short kFR = stile_t::kFragThrRows; +threadgroup float Mtg[4 * kU * MLD]; +threadgroup float* msg = Mtg + int(simdgroup_index_in_threadgroup) * kU * MLD; +omlx_nax::NAXTile Rtile; +{ + const device T* rs = rel + (int64_t(q0 + tm) * HQ + head) * 16; + if (!ALIGN_Q && lim_rows_q < kU) { + Rtile.load_rows(rs, HQ * 16, short(max(lim_rows_q, 0))); + } else { + Rtile.load(rs, HQ * 16); + } +} + +for (int kb = kb_lo; kb < kb_hi; kb++) { + const bool last_k = !ALIGN_K && kb == NK_aligned; + stile_t Stile; + Stile.clear(); + + // S = Q K^T, the query fragments re-read for every block (held in registers they cost occupancy). + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik += 2) { +#pragma clang loop unroll_count(4) + for (short id = 0; id < TD; id++) { + omlx_nax::NAXTile Qtile; + omlx_nax::NAXTile Ktile; + if (!ALIGN_Q && lim_rows_q < kU) { + Qtile.load_rows(Q + id * kU, qld, lim_rows_q); + } else { + Qtile.load(Q + id * kU, qld); + } + const int off_k = ik * kU * kld + id * kU; + if (last_k) { + Ktile.load_rows(K + off_k, kld, lim_rows_k - ik * kU); + } else { + Ktile.load(K + off_k, kld); + } + stile_t::NAXFrag_t::mma( + Stile.frag_at(0, ik), Stile.frag_at(0, ik + 1), Qtile.frag_at(0, 0), metal::false_type{}, + Ktile.frag_at(0, 0), Ktile.frag_at(1, 0), metal::true_type{}); + } + } + + // Scores in log2 units, plus the bias at distance d = diag - key below R; -inf outside the band. A block every row + // of this simdgroup sees whole and at distances of R or more needs only the scale. + const int c_lo = kb * BK; + const int c_hi = c_lo + BK - 1; + const bool plain = off + srow_lo - c_hi >= R && (WINDOW == 0 || off + srow_hi - c_lo < WINDOW) && c_lo >= start + && c_hi < S && srow_lo + kU - 1 < L; + // A group's bias tile crosses its lanes through threadgroup memory, so the threadgroup's barriers order it: the first + // the last staged block's reads before this block's writes, the second those writes before their reads. Every group + // passes both wherever group 0 stages (its rows are the threadgroup's nearest to the block); a far block passes none. + if (off + q0 - c_lo - (BK - 1) < R) { + threadgroup_barrier(mem_flags::mem_threadgroup); + const int dbase = off + srow_lo - c_lo - (BK - 1); + if (!plain && dbase < R) { + omlx_nax::NAXTile M0, M1; + M0.clear(); + M1.clear(); + omlx_nax::NAXTile P0, P1; + P0.load(relp + PADL + dbase, RP); + P1.load(relp + PADL + dbase + 32, RP); + stile_t::NAXFrag_t::mma(M0.frag_at(0, 0), M0.frag_at(0, 1), Rtile.frag_at(0, 0), metal::false_type{}, + P0.frag_at(0, 0), P0.frag_at(0, 1), metal::false_type{}); + stile_t::NAXFrag_t::mma(M1.frag_at(0, 0), M1.frag_at(0, 1), Rtile.frag_at(0, 0), metal::false_type{}, + P1.frag_at(0, 0), P1.frag_at(0, 1), metal::false_type{}); + OMLX_NAX_UNROLL + for (short f = 0; f < 4; f++) { + thread auto& mf = f < 2 ? M0.frag_at(0, f) : M1.frag_at(0, f - 2); + OMLX_NAX_UNROLL + for (short ii = 0; ii < kFR; ii++) { + OMLX_NAX_UNROLL + for (short jj = 0; jj < 4; jj++) { + const int col = f * kU + sn + jj; + if (col < MLD - 1) msg[(sm + ii * 8) * MLD + col] = mf[ii * 4 + jj]; + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (plain) { + OMLX_NAX_UNROLL + for (short i = 0; i < stile_t::kElemsPerTile; i++) { + Stile.elems()[i] *= scale2; + } + } else { + // The block's least distance for this group's rows; past R every bias is zero (a last block's ragged keys or rows). + const int dbase = off + srow_lo - c_lo - (BK - 1); + const bool near = dbase < R; + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik++) { + thread auto& fg = Stile.frag_at(0, ik); + OMLX_NAX_UNROLL + for (short ii = 0; ii < stile_t::kFragThrRows; ii++) { + const int r = rows[ii]; + const int c0 = c_lo + ik * kU + sn; + // The 4 columns' distances d0 - jj: their bias from the block's staged rows (zero past R). + const int d0 = off + r - c0; + float b[4]; + OMLX_NAX_UNROLL + for (short jj = 0; jj < 4; jj++) { + b[jj] = near ? msg[(sm + ii * 8) * MLD + (sm + ii * 8) - (ik * kU + sn + jj) + (BK - 1)] : 0.0f; + } + OMLX_NAX_UNROLL + for (short jj = 0; jj < stile_t::kFragThrCols; jj++) { + const int c = c0 + jj; + const int d = d0 - jj; + const bool visible = r < L && c < S && d >= 0 && c >= start && (WINDOW == 0 || d < WINDOW); + const short at = ii * stile_t::kFragThrCols + jj; + fg[at] = visible ? fma(b[jj], LOG2E, fg[at] * scale2) : -INFINITY; + } + } + } + } + + metal::vec new_max; + metal::vec factor; + OMLX_NAX_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + new_max[i] = max_score[i]; + } + Stile.template row_reduce(new_max); + Stile.template row_bin_op(new_max); + OMLX_NAX_UNROLL + for (short i = 0; i < kRowsPT; ++i) { + factor[i] = fast::exp2(max_score[i] - new_max[i]); + max_score[i] = new_max[i]; + sum_score[i] = sum_score[i] * factor[i]; + } + Stile.template row_reduce(sum_score); + Otile.template row_bin_op(factor); + + simdgroup_barrier(mem_flags::mem_none); + + // O += P V + OMLX_NAX_UNROLL + for (short id = 0; id < TD; id += 2) { + if (id == 4) { + threadgroup_barrier(mem_flags::mem_none); + } + OMLX_NAX_UNROLL + for (short ik = 0; ik < TK; ik++) { + omlx_nax::NAXTile Vtile; + const int off_v = ik * kU * vld + id * kU; + if (last_k) { + Vtile.load_rows(V + off_v, vld, lim_rows_k - ik * kU); + } else { + Vtile.load(V + off_v, vld); + } + otile_t::NAXFrag_t::mma( + Otile.frag_at(0, id), Otile.frag_at(0, id + 1), Stile.frag_at(0, ik), metal::false_type{}, + Vtile.frag_at(0, 0), Vtile.frag_at(0, 1), metal::false_type{}); + } + } + K += BK * kld; + V += BK * vld; +} + +threadgroup_barrier(mem_flags::mem_none); +metal::vec rcp; +OMLX_NAX_UNROLL +for (short i = 0; i < kRowsPT; ++i) { + rcp[i] = 1.0f / sum_score[i]; +} +Otile.template row_bin_op(rcp); +device T* O = out + (int64_t(q0 + tm) * HQ + head) * D; +if (!ALIGN_Q && lim_rows_q < kU) { + if (lim_rows_q > 0) { + Otile.store_rows(O, HQ * D, lim_rows_q); + } +} else { + Otile.store(O, HQ * D); +} diff --git a/src/plugins/inkling2/layers.zig b/src/plugins/inkling2/layers.zig index 80717c7435..f9685b4d9e 100644 --- a/src/plugins/inkling2/layers.zig +++ b/src/plugins/inkling2/layers.zig @@ -502,7 +502,8 @@ pub fn route(g: *Graph, L: *const Layer, cfg: *const Config, x: Array) !Route { /// A call's (row, pick) pairs as the banks read them: `rows` `[N, 1, D]` (or one row broadcast over its picks) and /// their experts `sel` `[N]`. From `sort_from` pairs on they are sorted by expert, so a wide call reads one bank at /// a time (mlx-lm's `_gather_sort`), with `inverse` the place of pair (row, pick) in that order. -pub const Pairs = struct { rows: Array, sel: Array, inverse: ?Array }; +/// `token`: a sorted pair's row (the gather's row map), set where they are sorted. +pub const Pairs = struct { rows: Array, sel: Array, inverse: ?Array, token: ?Array = null }; pub fn pairs(g: *Graph, cfg: *const Config, x: Array, idx: Array) !Pairs { const sh = ops.shape(x); @@ -522,6 +523,7 @@ pub fn pairs(g: *Graph, cfg: *const Config, x: Array, idx: Array) !Pairs { .sel = try g.take(flat, order, 0), .rows = try g.reshape(try g.take(try g.reshape(x, &.{ s, d }), token, 0), &.{ n, 1, d }), .inverse = try g.argsort(order, 0), + .token = token, }; } diff --git a/src/plugins/inkling2/plugin.zig b/src/plugins/inkling2/plugin.zig index e98ba8b1ef..e104345d37 100644 --- a/src/plugins/inkling2/plugin.zig +++ b/src/plugins/inkling2/plugin.zig @@ -24,6 +24,7 @@ const dflash2 = @import("dflash2.zig"); const kv = @import("../../sdk/bases/kv.zig"); const rounds = @import("../../sdk/spec/rounds.zig"); const sdk_host = @import("../../sdk/host.zig"); +const verifyQmmNaxAvailable = @import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable; pub const config = @import("config.zig"); pub const plugin = config.plugin; @@ -35,6 +36,33 @@ const gpa = std.heap.c_allocator; /// MLX's nvfp4 global scale is the block's amax; the codes times their block scales carry it over 6 x 448. const nvfp4_global_unit: f32 = 6.0 * 448.0; +/// `At.affine8`'s group, `tests/convert_inkling2.py`'s GROUP_SIZE. +const q8_group = 64; +/// Tensors the load's `At.affine8` quantized, for its engagement line. +var q8_tensors: u32 = 0; + +/// What the last load's `TRUNK_Q8` quantized. +pub fn trunkQ8Tensors() u32 { + return q8_tensors; +} + +/// The dense `[out, in]` `l` (unowned) as MLX's 8-bit affine at `q8_group`, evaluated; its dense handle released. +fn quant8(l: Linear, s: mlx.mlx_stream) !Linear { + var v = mlx.mlx_vector_array_new(); + defer _ = mlx.mlx_vector_array_free(v); + try mlx.check(mlx.mlx_quantize(&v, l.w, mlx.mlx_optional_int.some(q8_group), mlx.mlx_optional_int.some(8), "affine", .{ .ctx = null }, s)); + var parts: [3]Array = @splat(.{ .ctx = null }); + errdefer for (parts) |p| if (p.ctx != null) { + _ = mlx.mlx_array_free(p); + }; + for (&parts, 0..) |*p, k| { + p.* = mlx.mlx_array_new(); + try mlx.check(mlx.mlx_vector_array_get(p, v, k)); + } + try ops.evalMany(&parts); + _ = mlx.mlx_array_free(l.w); + return .{ .w = parts[0], .s = parts[1], .b = parts[2], .bits = 8, .group_size = q8_group, .mode = .affine }; +} /// The slots whose rounds one verify carries, and whose rings the Spec keeps (the current one and `max_open - 1` parked). const max_open = 16; @@ -228,7 +256,6 @@ pub const Spec = struct { pub const Model = struct { pub const batches_decode = true; - pub const prompt_last_row = true; pub const Weights = struct { embed: b.embed.TableEmbed.Weights, @@ -300,6 +327,10 @@ pub const Model = struct { var ref_h: ops.Array = .{}; var ref_bank: ops.Array = .{}; var ref_blocks: ?ops.Array = null; + // A prompt chunk's eval points hand the graph to the GPU and go on building (a verify, batched slots and a + // backend other than Metal keep main's synchronous eval points). + const prompt_async = prefillAsync(kernels.Load.of(run.mode), run.rows, run.eval_every, mlx.metalKernelsAvailable()); + if (prompt_async) kernels.engaged(.prefill_async); for (0..visits) |v| { const at = cfg.visit(@intCast(v)); if (cfg.core() > 0 and at.layer == cfg.core_start) { @@ -360,7 +391,7 @@ pub const Model = struct { } } } - try run.cadence(v, cfg.cacheEntries(), h); + if (prompt_async) try cadenceAsync(&run, v, cfg.cacheEntries(), h) else try run.cadence(v, cfg.cacheEntries(), h); } const stepped: ?ops.Array = try kernels.finalStream(g, &w.body, h, blocks, w.final_norm); var final = stepped orelse try g.astype(try g.rmsNorm(try layers.finalInput(g, &w.body, h, blocks), w.final_norm, cfg.rms_norm_eps), ops.dtype(h)); @@ -472,8 +503,14 @@ pub const table = abi.ModelTable{ .weights = &.{}, .media = &.{ .tower = &media.tower, .prepare = &media.prepare }, .spec = &.{ .native_drafter = &.{ .step = &draftStep, .verify = &draftVerify, .finish = &draftFinish, .active = &draftActive, .verify_group = &draftVerifyGroup, .finish_group = &draftFinishGroup, .group_width = &draftGroupWidth, .step_group = &draftStepGroup } }, + .ready = &loadReady, }; +/// The load is ready: the pipeline record closes, so no launch from here on does work for it. +fn loadReady(_: *anyopaque) callconv(.c) void { + kernels.pipes.ready(); +} + fn draftStep(mp: *anyopaque, f: *const abi.Forward, out: *abi.ForwardOut) callconv(.c) abi.Verdict { const m: *Loaded = @ptrCast(@alignCast(mp)); round(m, f, out) catch |e| return .{ .code = .failed, .why = abi.Str.of(@errorName(e)) }; @@ -556,6 +593,29 @@ const Lane = struct { want: ?Want = null, }; +/// The server's lever settings as one digest, in any order: every `MLX_` variable but the diagnostics (a lever moves +/// which kernels a launch builds, so each composition keeps its own record). +fn composition() [32]u8 { + var acc: [32]u8 = @splat(0); + if (comptime @import("builtin").os.tag == .windows) return acc; // no C `environ` to walk; the plugin serves on Metal + var i: usize = 0; + while (std.c.environ[i]) |e| : (i += 1) { + const entry = std.mem.span(e); + if (!std.mem.startsWith(u8, entry, "MLX_")) continue; + if (std.mem.indexOf(u8, entry, "DIAG") != null) continue; + var d: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(entry, &d, .{}); + for (&acc, d) |*x, y| x.* ^= y; + } + return acc; +} + +fn printZ(buf: []u8, comptime fmt: []const u8, args: anytype) ![:0]u8 { + const n = (try std.fmt.bufPrint(buf[0 .. buf.len - 1], fmt, args)).len; + buf[n] = 0; + return buf[0..n :0]; +} + /// A lane's call on the drafter: `t1`'s normed embedding, the drafts it may make, the law to draw them from. const Want = struct { anchor: ops.Array, cap: u32, law: ?draft.Drafter.Law, round_ms: []const f32, stops: []const u32 }; @@ -1455,6 +1515,14 @@ fn stepGroup(m: *Loaded, fs: []const abi.Forward, outs: []abi.ForwardOut) !abi.V return .ok; } +fn nowUs() i64 { + return @import("../../sdk/util/io_util.zig").nowUsMonotonic(std.Io.Threaded.global_single_threaded.io()); +} + +fn msSince(t0: i64) f32 { + return @as(f32, @floatFromInt(nowUs() - t0)) / 1000; +} + /// The engine's default arithmetic over the shell and the layout, plus the drafter's context (`draftStatePerToken`). fn bill(p: *const abi.Parsed, _: *const abi.Shape, out: *abi.Bill) callconv(.c) void { out.* = .{ .state_per_token = config.draftStatePerToken(p) }; @@ -1486,6 +1554,16 @@ pub const Loaded = struct { return 0; } + /// The slots' drafter state as the load left it (no open verify; every ring, context and calibration dropped), the + /// weights and the load's settings kept: a test that takes a load another test used starts where a fresh load does. + pub fn freshSlots(m: *Loaded) void { + if (m.opened) |o| closeOpen(o); + m.opened = null; + const fresh: Spec = .{ .visits = m.spec.visits, .keep = m.spec.keep, .full = m.spec.full }; + m.spec.deinit(); + m.spec = fresh; + } + fn release(m: *Loaded) void { if (m.tower) |*t| t.deinit(); if (m.opened) |o| closeOpen(o); @@ -1518,6 +1596,25 @@ fn forward(mp: *anyopaque, f: *const abi.Forward, out: *abi.ForwardOut) callconv return run_mod.tableForward(Model, &m.base, f, out); } +/// Whether a forward's eval points run as async evals: a prompt chunk's rows with eval points, on `metal` with NAX +/// (`verifyQmmNaxAvailable`). Every GPU without NAX (M1-M4) keeps main's synchronous eval points. +pub fn prefillAsync(kind: kernels.Load, rows: c_int, eval_every: u32, metal: bool) bool { + return metal and kind == .prompt and rows > 1 and eval_every > 0 and verifyQmmNaxAvailable() and !kernels.mainFor(.prefill_async); +} + +/// `Run.cadence`'s eval points as async evals of the same arrays (the stream and the conv states): the CPU builds the +/// next visits while the GPU runs these. The same graph, so the same values. +fn cadenceAsync(r: *const run_mod.Run, layer: usize, n: usize, h: ops.Array) !void { + if ((layer + 1) % r.eval_every != 0 and layer + 1 != n) return; + const vec = mlx.mlx_vector_array_new_value(h); + defer _ = mlx.mlx_vector_array_free(vec); + if (r.cache_ops) |co| for (r.caches) |cache| for (0..n) |l| { + const st = co.state(cache, @intCast(l), .conv); + if (st.ctx != null) _ = mlx.mlx_vector_array_append_value(vec, .{ .ctx = st.ctx }); + }; + try mlx.check(mlx.mlx_async_eval(vec)); +} + fn load(ctx: *const abi.LoadCtx, out: *abi.Verdict) callconv(.c) ?*anyopaque { return loadModel(ctx) catch |e| { out.* = .{ .code = .failed, .why = abi.Str.of(@errorName(e)) }; @@ -1536,6 +1633,17 @@ const At = struct { /// oMLX's oQ layout: mlx-lm's tensors under `oqLeaf`'s names, the projections off one input stored joined along /// their rows, a looped layer's gates and message queries stacked under the layer. oq: bool = false, + /// The dense attention projections, dynamic-conv projections, embedding and head as 8-bit affine at load + /// (`MLX_SERVE_INKLING2_TRUNK_Q8=1`, opt-in; unset keeps them dense): MLX's quantize at group 64, the values + /// `tests/convert_inkling2.py --bits 8` stores. + q8: bool = false, + + /// `l` (unowned) as 8-bit affine when `q8` and it is dense, its dense handle released; else `l`. + fn affine8(a: At, l: Linear) !Linear { + if (!a.q8 or l.s.ctx != null or l.w.ctx == null) return l; + q8_tensors += 1; + return quant8(l, a.r.s); + } fn name(a: At, buf: []u8, comptime leaf: []const u8, comptime rel: []const u8) ![]const u8 { if (a.release) return if (a.layer) |i| a.r.name(buf, "layers.{d}." ++ rel, .{i}) else a.r.name(buf, rel, .{}); @@ -1665,7 +1773,7 @@ const At = struct { /// A projection the caller owns once it has tried a join. fn projRaw(a: At, comptime leaf: []const u8, comptime rel: []const u8, in_dim: u32) !Linear { var buf: [256]u8 = undefined; - return a.r.tableAt(try a.name(&buf, leaf, rel), in_dim); + return a.affine8(try a.r.tableAt(try a.name(&buf, leaf, rel), in_dim)); } /// Dense projections off one input joined along their rows: the parts become row views of the joined weight, as @@ -1799,7 +1907,12 @@ const At = struct { .dynamic = .{ .static = try a.need(leaf ++ ".static_weight", rel ++ ".static_w"), // The release's is a bare `[out, in]` tensor, with no `.weight` leaf for the format to find. - .proj = if (cut) |l| l else if (a.release) .{ .w = try a.need("", rel ++ ".weight_proj") } else try a.proj(leaf ++ ".weight_proj", "", hidden), + .proj = if (cut) |l| l else if (a.release) blk: { + var buf: [256]u8 = undefined; + const l = try a.affine8(.{ .w = try a.r.need(try a.name(&buf, "", rel ++ ".weight_proj")) }); + try a.o.linear(l); + break :blk l; + } else try a.proj(leaf ++ ".weight_proj", "", hidden), }, }; } @@ -1968,15 +2081,19 @@ fn loadModel(ctx: *const abi.LoadCtx) !*Loaded { m.* = .{ .base = .{ .weights = undefined, .shared = bases.Shared.init(c.rms_norm_eps, c.rms_norm_eps), .a = gpa, .s = r.s, .placeholders = ctx.parsed.placeholder_ids } }; errdefer m.release(); m.layers = try gpa.alloc(layers.Layer, c.num_hidden_layers); - for (m.layers, 0..) |*L, i| L.* = try loadLayer(.{ .r = &r, .o = &m.owned, .layer = @intCast(i), .release = release, .oq = oq }, c, @intCast(i)); + const q8 = config.trunkQ8(); + var dir_buf: [512]u8 = undefined; + q8_tensors = 0; + for (m.layers, 0..) |*L, i| L.* = try loadLayer(.{ .r = &r, .o = &m.owned, .layer = @intCast(i), .release = release, .oq = oq, .q8 = q8 }, c, @intCast(i)); - const at: At = .{ .r = &r, .o = &m.owned, .release = release, .oq = oq }; + const at: At = .{ .r = &r, .o = &m.owned, .release = release, .oq = oq, .q8 = q8 }; const hidden: c_int = @intCast(c.hidden_size); var nb: [256]u8 = undefined; - const embed = try r.tableAt(try at.name(&nb, "embed_tokens", "embed"), c.hidden_size); + const embed = try at.affine8(try r.tableAt(try at.name(&nb, "embed_tokens", "embed"), c.hidden_size)); try m.owned.linear(embed); - const head = try r.tableAt(if (release) try at.name(&nb, "", "unembed") else "lm_head", c.hidden_size); + const head = try at.affine8(try r.tableAt(if (release) try at.name(&nb, "", "unembed") else "lm_head", c.hidden_size)); try m.owned.linear(head); + if (q8) log.info("[inkling2] trunk_q8 engaged: {d} dense tensors at 8-bit affine, group {d}\n", .{ q8_tensors, q8_group }); var ones: [2]Array = undefined; for (&ones, [_]c_int{ hidden, @intCast(c.head_dim) }) |*x, n| { x.* = mlx.mlx_array_new(); @@ -2023,6 +2140,7 @@ fn loadModel(ctx: *const abi.LoadCtx) !*Loaded { var dir: [std.fs.max_path_bytes]u8 = undefined; const d = try dflash2.Drafter.load(try std.fmt.bufPrint(&dir, "{s}/{s}", .{ ctx.model_dir.slice(), config.dflash2_dir }), dc, c.hidden_size, &head, r.s, draft_bits); m.drafter2 = d; + log.info("[inkling2] drafter: dflash2 ({s})\n", .{config.dflash2_dir}); // The mask token's row as the anchor's: through the table, then its norm. var g = ops.Graph.init(gpa, r.s); defer g.deinit(); @@ -2036,6 +2154,7 @@ fn loadModel(ctx: *const abi.LoadCtx) !*Loaded { m.base.weights.spec = &m.spec; } else if (drafts_on) if (c.draft) |dc| if (try draft.Drafter.load(ctx, dc, c.hidden_size, &head, r.s, draft_bits)) |d| { m.drafter = d; + log.info("[inkling2] drafter: the bundled mtp head\n", .{}); m.tap_visits = dc.taps; m.spec = .{ .visits = m.tap_visits[0 .. dc.tap_count - 1], .keep = @intCast(dc.window - 1) }; if (dc.fullBytesPerToken() > 0) m.spec.full = d; @@ -2053,9 +2172,42 @@ fn loadModel(ctx: *const abi.LoadCtx) !*Loaded { }); } + // `MLX_SERVE_INKLING2_PIPELINES_AT_LOAD`: this build, machine and composition's recorded launches replayed, their + // pipelines built before ready; first launches until ready (`loadReady`) append to the record. Only where the + // kernels run (Metal). + if (if (kernels.enabled()) leverDir(.MLX_SERVE_INKLING2_PIPELINES_AT_LOAD, &dir_buf) else null) |dir| { + var own_buf: [512]u8 = undefined; + const key = @import("fit_key.zig").own(&own_buf) catch "unkeyed"; + var h = std.crypto.hash.sha2.Sha256.init(.{}); + h.update(key); + h.update(&composition()); + var digest: [32]u8 = undefined; + h.final(&digest); + const hex = std.fmt.bytesToHex(digest[0..12].*, .lower); + var path_buf: [600]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/inkling2-pipelines-{s}.txt", .{ dir, &hex }); + const t0 = nowUs(); + const got = kernels.pipelinesAtLoad(m.base.s, path) catch |e| blk: { + log.warn("[inkling2] pipelines at load: {s}\n", .{@errorName(e)}); + break :blk [3]usize{ 0, 0, 0 }; + }; + log.info("[inkling2] pipelines at load: {d} built from {d} recorded launches ({d} lines unreadable) in {d:.1} ms ({s})\n", .{ got[0], got[1], got[2], msSince(t0), path }); + } return m; } +/// The folder a lever keeps its stored files in (`MLX_SERVE_INKLING2_PIPELINES_AT_LOAD`): the +/// variable's value, else `~/.mlx-serve/inkling2` (made when missing; none in a test build, which stays hermetic); +/// null at `0`. +fn leverDir(comptime name: @EnumLiteral(), buf: []u8) ?[]const u8 { + if (@import("../../env.zig").span(name)) |v| return if (v.len == 0 or v[0] == '0') null else v; + if (@import("builtin").is_test) return null; + const home = std.mem.span(std.c.getenv("HOME") orelse return null); + _ = std.c.mkdir(printZ(buf, "{s}/.mlx-serve", .{home}) catch return null, 0o755); + const dir = printZ(buf, "{s}/.mlx-serve/inkling2", .{home}) catch return null; + _ = std.c.mkdir(dir, 0o755); + return dir; +} /// The width the DFlash2 draft's projections are held at: its weights are read every round, and drafts are only proposals. const draft_bits = 8; @@ -2294,6 +2446,7 @@ test { _ = vision; _ = media; _ = draft; + _ = @import("fit_key.zig"); _ = dflash2; } @@ -2513,3 +2666,13 @@ test "inkling2 loopcd: fixed and adaptive logit guidance formulas" { } } } + +test "inkling2: a prompt's eval points run async on Metal only, and never for a step" { + try std.testing.expect(!prefillAsync(.prompt, 64, 2, false)); + try std.testing.expect(!prefillAsync(.step, 64, 2, true)); + try std.testing.expect(!prefillAsync(.prompt, 1, 2, true)); + try std.testing.expect(!prefillAsync(.prompt, 64, 0, true)); + // Async eval points run on NAX only. + if (!verifyQmmNaxAvailable()) return error.SkipZigTest; + try std.testing.expect(prefillAsync(.prompt, 64, 2, true)); +} diff --git a/src/plugins/inkling2/proof_test.zig b/src/plugins/inkling2/proof_test.zig index f606481fcf..a351532c80 100644 --- a/src/plugins/inkling2/proof_test.zig +++ b/src/plugins/inkling2/proof_test.zig @@ -17,7 +17,7 @@ const fixture = @import("../../sdk/testing/fixture.zig"); const Tensors = @import("../../sdk/testing/tensors.zig").Tensors; const parity = @import("../../sdk/testing/parity.zig"); const run = @import("../../sdk/bases/run.zig"); -const head_block = @import("../../sdk/bases/blocks/head.zig"); +const test_loads = @import("test_loads.zig"); const testing = std.testing; const VOCAB = 60; @@ -47,18 +47,26 @@ fn expectRows(ours: []const f32, ref: []const f32) !void { try testing.expect(cmp.min_cos > 0.999 and misses == 0); } +/// `MLX_SERVE_INKLING2_TRUNK_Q8` for a load: the proofs hold the dense trunk: on the random fixture +/// an 8-bit rounding flips expert picks, so only TRUNK_Q8's own tests load it at 8 bits. +fn trunkQ8(on: bool) @import("../../env.zig").Override(.MLX_SERVE_INKLING2_TRUNK_Q8) { + return @import("../../env.zig").override(.MLX_SERVE_INKLING2_TRUNK_Q8, if (on) "1" else "0"); +} + const Setup = struct { arena: std.heap.ArenaAllocator, pack: conformance.Loaded, whole: []f32, - /// The pack, on the CPU's stream or the GPU's, and the whole prompt's rows from one forward. + /// The pack with its dense trunk, on the CPU's stream or the GPU's, and the whole prompt's rows from one forward. fn init(a: std.mem.Allocator, gpu: bool) !Setup { - return initWith(a, gpu, ""); + return initWith(a, gpu, false, ""); } - /// `init` under the model settings `settings` (the parse's and the load's). - fn initWith(a: std.mem.Allocator, gpu: bool, settings: []const u8) !Setup { + /// `init` with the trunk at 8 bits when `q8`, under the model settings `settings` (the parse's and the load's). + fn initWith(a: std.mem.Allocator, gpu: bool, q8: bool, settings: []const u8) !Setup { + const ov = trunkQ8(q8); + defer ov.restore(); var arena = std.heap.ArenaAllocator.init(a); errdefer arena.deinit(); var pack = try conformance.Loaded.openWith(testing.io, arena.allocator(), plugin.plugin.name, &plugin.table, try plugin.conformanceFixture(arena.allocator()), .{ .gpu = gpu, .settings = settings }); @@ -80,8 +88,8 @@ fn streams() []const bool { return if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) &.{false} else &.{ false, true }; } -// Bar: a last-row prompt forward (`Caps.prompt_last_row`, its head over the last rows) serves the bytes of that row of -// the all-rows forward, under the head's tail rows and past them, on the GPU's stream, where the model is served. +// Bar: a last-row prompt forward (`Caps.prompt_last_row`) serves the bytes of that row of the all-rows forward, at 1, +// 31, 33 and 300 rows (the 8-bit fixture head takes another MLX kernel at 32 rows than at 33), on the GPU's stream. test "inkling2 proof: a last-row prompt serves the last row of the all-rows forward, bit for bit" { if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; const a = testing.allocator; @@ -106,9 +114,9 @@ test "inkling2 proof: a last-row prompt serves the last row of the all-rows forw } } -// Bar: on the GPU, the pack's own lm_head over a prompt's last `head_tail_rows` rows gives that row the all-rows bits, -// through the head's own matmul and this build's kernels. -test "inkling2 pack: the lm_head over the last head_tail_rows rows serves the last row of all of them, bit for bit (INKLING2_PACK)" { +// Bar: on the GPU, through the pack's own lm_head and this build's kernels, a last-row ask (`Run.finish`) serves the +// bytes of the all-rows ask's last row at 33 to 4100 rows. +test "inkling2 pack: a last-row head serves the all-rows head's last row, bit for bit (INKLING2_PACK)" { if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; const dir = std.mem.span(@import("../../env.zig").named("INKLING2_PACK") orelse return error.SkipZigTest); const a = testing.allocator; @@ -148,12 +156,17 @@ test "inkling2 pack: the lm_head over the last head_tail_rows rows serves the la defer a.free(buf); for (buf) |*x| x.* = prng.random().floatNorm(f32); const rows = try g.astype(try g.adopt(mlx.mlx_array_new_data(buf.ptr, &[_]c_int{ 1, most, hidden }, 3, .float32)), .bfloat16); + const head: layers.Head.Weights = .{ .lin = lin, .vocab = ops.shape(lin.w)[0], .softcap = 30.0 }; + var c: @import("../../sdk/bases/block.zig").Ctx = undefined; + c.g = &g; for ([_]c_int{ 33, 300, 1536, most }) |n| { const x = try g.sliceAxis(rows, 1, 0, n); - const all = try g.contiguous(try g.astype(try g.sliceAxis(try head_block.project(&g, &lin, x), 1, n - 1, n), .float32)); - const tail = try g.contiguous(try g.astype(try g.sliceAxis(try head_block.project(&g, &lin, try g.sliceAxis(x, 1, n - run.head_tail_rows, n)), 1, run.head_tail_rows - 1, run.head_tail_rows), .float32)); + const all_run: run.Run = .{ .mode = .prefill, .rows = n, .slots = 1, .positions = &.{0}, .logits = .all_rows }; + const last_run: run.Run = .{ .mode = .prefill, .rows = n, .slots = 1, .positions = &.{0}, .logits = .last_row }; + const all = try g.contiguous(try g.sliceAxis((try all_run.finish(&g, &c, x, layers.Head, &head)).logits, 0, n - 1, n)); + const tail = try g.contiguous((try last_run.finish(&g, &c, x, layers.Head, &head)).logits); try ops.evalMany(&.{ all, tail }); - const vocab: usize = @intCast(ops.shape(all)[2]); + const vocab: usize = @intCast(ops.shape(all)[1]); const want = mlx.mlx_array_data_float32(all).?[0..vocab]; const got = mlx.mlx_array_data_float32(tail).?[0..vocab]; if (!std.mem.eql(u8, std.mem.sliceAsBytes(want), std.mem.sliceAsBytes(got))) std.debug.print("[inkling2 pack] last row differs at {d} rows\n", .{n}); @@ -191,8 +204,7 @@ test "inkling2 pack: a quantized joined projection is whole tiles and serves eac var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const a = arena.allocator(); - var rel = try Release.open(a, dir); - defer rel.close(); + const rel = try Release.shared(dir); fx_stream = rel.m.base.s; var g = ops.Graph.init(a, rel.m.base.s); defer g.deinit(); @@ -503,7 +515,36 @@ const Release = struct { m: *plugin.Loaded, s: mlx.mlx_stream, + /// The release with its dense trunk. fn open(a: std.mem.Allocator, pack_dir: []const u8) !Release { + return openWith(a, pack_dir, false); + } + + /// `open`'s load, held for every test that asks for it (`test_loads.hold`), its slots as a fresh load's. + fn shared(pack_dir: []const u8) !*Release { + return sharedWith(pack_dir, false); + } + + /// `openWith`'s load, held for every test that asks for it (`test_loads.hold`), its slots as a fresh load's. + fn sharedWith(pack_dir: []const u8, q8: bool) !*Release { + const ov = trunkQ8(q8); + defer ov.restore(); + const Opener = struct { + dir: []const u8, + q8: bool, + pub fn open(o: @This(), r: *Release, a: std.mem.Allocator) !void { + r.* = try openWith(a, o.dir, o.q8); + } + }; + const r = try test_loads.hold(Release, &.{ pack_dir, if (q8) "q8" else "dense" }, Opener{ .dir = pack_dir, .q8 = q8 }); + r.m.freshSlots(); + return r; + } + + /// The release, its trunk at 8 bits when `q8`. + fn openWith(a: std.mem.Allocator, pack_dir: []const u8, q8: bool) !Release { + const ov = trunkQ8(q8); + defer ov.restore(); const FsPackDir = @import("../../sdk/util/pack_dir.zig").FsPackDir; const io = std.Io.Threaded.global_single_threaded.io(); var fs = try FsPackDir.open(io, pack_dir); @@ -522,7 +563,7 @@ const Release = struct { return r; } - fn close(r: *Release) void { + pub fn close(r: *Release) void { _ = mlx.mlx_synchronize(r.s); plugin.table.unload(r.m); plugin.table.free_parsed(&r.parsed); @@ -556,6 +597,7 @@ test "inkling2 release: the drafter's full layer reads the prompt past its windo var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const a = arena.allocator(); + test_loads.drop(); var rel = try Release.open(a, pack_dir); defer rel.close(); // Apple9+ only (`draftsOn`). @@ -571,20 +613,12 @@ test "inkling2 release: the drafter's full layer reads the prompt past its windo while (ids.items.len < quokka_def.len + d.cfg.window) try ids.appendSlice(a, &quokka_filler); try ids.appendSlice(a, &quokka_again); const n: u32 = @intCast(ids.items.len); - const prefill = struct { - fn run(m: *plugin.Loaded, al: std.mem.Allocator, cache: *test_cache.TestCache, tokens: []const u32, slot: u32) !u32 { - var h = [_]abi.Handle{cache.handle()}; - var out: abi.ForwardOut = .{}; - try testing.expect(plugin.table.forward(m, &.{ .mode = .prefill, .logits = .last_row, .rows = @intCast(tokens.len), .tokens = .of(tokens), .slots = .of(&[_]u32{slot}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); - return argmaxOf(try conformance.consumeF32(al, out.logits)); - } - }; // Slot 0 the plain decode, slots 1 and 2 the rounds with and without the full read, each its own drafter context. var plain = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); defer plain.deinit(); var want: [64]u32 = undefined; var step_logits: [want.len][]f32 = undefined; - want[0] = try prefill.run(rel.m, a, &plain, ids.items, 0); + want[0] = try releasePrefill(rel.m, a, &plain, ids.items, 0); for (1..want.len) |i| { var h = [_]abi.Handle{plain.handle()}; var out: abi.ForwardOut = .{}; @@ -600,7 +634,7 @@ test "inkling2 release: the drafter's full layer reads the prompt past its windo const slot: u32 = @intCast(1 + arm); var cache = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); defer cache.deinit(); - var t1 = try prefill.run(rel.m, a, &cache, ids.items, slot); + var t1 = try releasePrefill(rel.m, a, &cache, ids.items, slot); var got: std.ArrayList(u32) = .empty; var pos: u32 = n; var verified: [abi.max_round_tokens]u32 = @splat(0); @@ -643,7 +677,7 @@ test "inkling2 release: the drafter's full layer reads the prompt past its windo { var cache = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); defer cache.deinit(); - const t1 = try prefill.run(rel.m, a, &cache, ids.items, 3); + const t1 = try releasePrefill(rel.m, a, &cache, ids.items, 3); try testing.expectEqual(want[0], t1); var h = [_]abi.Handle{cache.handle()}; var out: abi.ForwardOut = .{}; @@ -661,7 +695,7 @@ test "inkling2 release: the drafter's full layer reads the prompt past its windo { var cache = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); defer cache.deinit(); - const t1 = try prefill.run(rel.m, a, &cache, ids.items, 4); + const t1 = try releasePrefill(rel.m, a, &cache, ids.items, 4); var h = [_]abi.Handle{cache.handle()}; var out: abi.ForwardOut = .{}; try testing.expect(nd.verify.?(rel.m, &.{ .mode = .decode, .rows = 1, .tokens = .of(&[_]u32{t1}), .slots = .of(&[_]u32{4}), .positions = .of(&[_]u32{n}), .caches = .of(&h), .cache_ops = &test_cache.ops, .accept_cap = 7, .draft_temperature = 1.0, .draft_seed = 11 }, &out).isOk()); @@ -694,8 +728,7 @@ test "inkling2 release: a DFlash2 draft's greedy rounds commit the plain decode var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const a = arena.allocator(); - var rel = try Release.open(a, pack_dir); - defer rel.close(); + const rel = try Release.shared(pack_dir); // Apple9+ only (`draftsOn`). const d = rel.m.drafter2 orelse return error.SkipZigTest; const t = &plugin.table; @@ -706,19 +739,11 @@ test "inkling2 release: a DFlash2 draft's greedy rounds commit the plain decode try ids.appendSlice(a, &quokka_filler); try ids.appendSlice(a, &quokka_again); const n: u32 = @intCast(ids.items.len); - const prefill = struct { - fn run(m: *plugin.Loaded, al: std.mem.Allocator, cache: *test_cache.TestCache, tokens: []const u32, slot: u32) !u32 { - var h = [_]abi.Handle{cache.handle()}; - var out: abi.ForwardOut = .{}; - try testing.expect(plugin.table.forward(m, &.{ .mode = .prefill, .logits = .last_row, .rows = @intCast(tokens.len), .tokens = .of(tokens), .slots = .of(&[_]u32{slot}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); - return argmaxOf(try conformance.consumeF32(al, out.logits)); - } - }; var plain = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); defer plain.deinit(); var want: [48]u32 = undefined; var step_logits: [want.len][]f32 = undefined; - want[0] = try prefill.run(rel.m, a, &plain, ids.items, 0); + want[0] = try releasePrefill(rel.m, a, &plain, ids.items, 0); for (1..want.len) |i| { var h = [_]abi.Handle{plain.handle()}; var out: abi.ForwardOut = .{}; @@ -728,7 +753,7 @@ test "inkling2 release: a DFlash2 draft's greedy rounds commit the plain decode } var cache = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); defer cache.deinit(); - var t1 = try prefill.run(rel.m, a, &cache, ids.items, 1); + var t1 = try releasePrefill(rel.m, a, &cache, ids.items, 1); var got: std.ArrayList(u32) = .empty; var pos: u32 = n; var verified: [abi.max_round_tokens]u32 = @splat(0); @@ -768,7 +793,7 @@ test "inkling2 release: a DFlash2 draft's greedy rounds commit the plain decode // A sampled round's verify draws its drafts from the selector's law and hands that law back, a row a draft. var sampled = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); defer sampled.deinit(); - const s1 = try prefill.run(rel.m, a, &sampled, ids.items, 2); + const s1 = try releasePrefill(rel.m, a, &sampled, ids.items, 2); var h = [_]abi.Handle{sampled.handle()}; var out: abi.ForwardOut = .{}; try testing.expect(nd.verify.?(rel.m, &.{ .mode = .decode, .rows = 1, .tokens = .of(&[_]u32{s1}), .slots = .of(&[_]u32{2}), .positions = .of(&[_]u32{n}), .caches = .of(&h), .cache_ops = &test_cache.ops, .accept_cap = 7, .draft_temperature = 1.0, .draft_seed = 7 }, &out).isOk()); @@ -845,8 +870,7 @@ test "inkling2 release: DFlash2 group rounds commit each slot's plain decode to var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const a = arena.allocator(); - var rel = try Release.open(a, pack_dir); - defer rel.close(); + const rel = try Release.shared(pack_dir); if (rel.m.drafter2 == null) return error.SkipZigTest; const step_group = plugin.table.spec.?.native_drafter.?.step_group.?; const n_layers = rel.parsed.shell.num_hidden_layers; @@ -930,6 +954,102 @@ test "inkling2 release: DFlash2 group rounds commit each slot's plain decode to } } +/// A prompt's prefill on the release through slot `slot`'s cache: the argmax after it. +fn releasePrefill(m: *plugin.Loaded, a: std.mem.Allocator, cache: *test_cache.TestCache, tokens: []const u32, slot: u32) !u32 { + var h = [_]abi.Handle{cache.handle()}; + var out: abi.ForwardOut = .{}; + try testing.expect(plugin.table.forward(m, &.{ .mode = .prefill, .logits = .last_row, .rows = @intCast(tokens.len), .tokens = .of(tokens), .slots = .of(&[_]u32{slot}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); + return argmaxOf(try conformance.consumeF32(a, out.logits)); +} + +/// A request's lane on the release: its cache, its next round's `t1` and position, its sampling, what it committed. +const RoundLane = struct { + cache: test_cache.TestCache = undefined, + slot: u32, + t1: u32 = 0, + pos: u32 = 0, + temperature: f32 = 0, + seed: u64 = 0, + got: std.ArrayList(u32) = .empty, + + fn open(l: *RoundLane, m: *plugin.Loaded, a: std.mem.Allocator, n_layers: usize, tokens: []const u32) !void { + l.cache = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); + l.t1 = try releasePrefill(m, a, &l.cache, tokens, l.slot); + l.pos = @intCast(tokens.len); + } +}; + +/// One DFlash2 round of `lanes` as one forward (`NativeDrafter.step_group`), asked as the engine asks it; a sampled lane +/// draws under a new seed each round. +fn stepLanes(m: *plugin.Loaded, a: std.mem.Allocator, lanes: []const *RoundLane) !void { + const max = 4; + var tokens: [max][1]u32 = undefined; + var slots: [max][1]u32 = undefined; + var positions: [max][1]u32 = undefined; + var handles: [max][1]abi.Handle = undefined; + var fs: [max]abi.Forward = undefined; + var outs: [max]abi.ForwardOut = @splat(.{}); + for (lanes, 0..) |l, k| { + tokens[k] = .{l.t1}; + slots[k] = .{l.slot}; + positions[k] = .{l.pos}; + handles[k] = .{l.cache.handle()}; + l.seed +%= 1; + fs[k] = .{ .mode = .verify, .rows = 1, .tokens = .of(&tokens[k]), .slots = .of(&slots[k]), .positions = .of(&positions[k]), .caches = .of(&handles[k]), .cache_ops = &test_cache.ops, .accept_cap = abi.max_round_tokens - 1, .draft_temperature = l.temperature, .draft_seed = l.seed }; + } + try testing.expect(plugin.table.spec.?.native_drafter.?.step_group.?(m, &fs, &outs, @intCast(lanes.len)).isOk()); + for (lanes, outs[0..lanes.len]) |l, o| { + try l.got.appendSlice(a, o.round.tokens[0..o.round.n]); + l.t1 = o.round.next_token; + l.pos = @intCast(o.round.position); + } +} + +// Bar: on the DFlash2 release (`INKLING2_DFLASH2_PACK`), a greedy lane's rounds, one lane a forward as the engine runs a +// request that rounds alone (`native_group.roundsAlone`), commit the same tokens alone and between the rounds of a +// sampled group of two, arrived after it or before it. +test "inkling2 release: a greedy lane's rounds beside a sampled group are its rounds alone" { + const env = @import("../../env.zig"); + const pack_dir = std.mem.span(env.get(.INKLING2_DFLASH2_PACK) orelse return error.SkipZigTest); + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const rel = try Release.shared(pack_dir); + // Apple9+ only (`draftsOn`). + _ = rel.m.drafter2 orelse return error.SkipZigTest; + const n_layers = rel.parsed.shell.num_hidden_layers; + const greedy_prompt = quokka_def ++ quokka_filler ++ quokka_again; + const first_other = quokka_filler ++ quokka_def; + const second_other = quokka_again ++ quokka_filler; + const rounds_n = 12; + + var alone: RoundLane = .{ .slot = 40 }; + try alone.open(rel.m, a, n_layers, &greedy_prompt); + defer alone.cache.deinit(); + for (0..rounds_n) |_| try stepLanes(rel.m, a, &.{&alone}); + try testing.expect(alone.got.items.len > rounds_n); + + for ([_]bool{ true, false }) |greedy_first| { + const base: u32 = if (greedy_first) 50 else 60; + var g: RoundLane = .{ .slot = base }; + var s1: RoundLane = .{ .slot = base + 1, .temperature = 0.8, .seed = 0x5eed }; + var s2: RoundLane = .{ .slot = base + 2, .temperature = 1.0, .seed = 0xface }; + if (greedy_first) try g.open(rel.m, a, n_layers, &greedy_prompt); + try s1.open(rel.m, a, n_layers, &first_other); + try s2.open(rel.m, a, n_layers, &second_other); + if (!greedy_first) try g.open(rel.m, a, n_layers, &greedy_prompt); + defer for ([_]*RoundLane{ &g, &s1, &s2 }) |l| l.cache.deinit(); + for (0..rounds_n) |_| { + if (greedy_first) try stepLanes(rel.m, a, &.{&g}); + try stepLanes(rel.m, a, if (greedy_first) &.{ &s1, &s2 } else &.{ &s2, &s1 }); + if (!greedy_first) try stepLanes(rel.m, a, &.{&g}); + } + try testing.expect(s1.got.items.len >= rounds_n and s2.got.items.len >= rounds_n); + try testing.expectEqualSlices(u32, alone.got.items, g.got.items); + } +} + test "inkling2 proof: a step reads every visit's conv windows and each loop pass's own KV" { for (streams()) |gpu| try stateMutations(gpu); } @@ -976,6 +1096,8 @@ test "inkling2 proof: media rows splice at the image placeholder" { const files = try arena.allocator().dupe(@TypeOf(fx.files[0]), fx.files); files[0].bytes = "{\"model_type\":\"inkling2_loop\",\"eos_token_id\":2,\"image_token_id\":59,\"vision_config\":{\"hidden_size\":32,\"num_hidden_layers\":1,\"num_attention_heads\":2}," ++ config.fixture_text ++ "}"; fx.files = files; + const ov = trunkQ8(false); + defer ov.restore(); var pack = try conformance.Loaded.openWith(testing.io, arena.allocator(), plugin.plugin.name, &plugin.table, fx, .{ .gpu = false }); defer pack.close(); try testing.expect(pack.parsed.caps.images and pack.parsed.placeholder_ids.image == 59); @@ -1396,6 +1518,8 @@ const Stage = struct { body: *const layers.Body, fn init(a: std.mem.Allocator) !Stage { + const ov = trunkQ8(false); + defer ov.restore(); var arena = std.heap.ArenaAllocator.init(a); errdefer arena.deinit(); const pack = try conformance.Loaded.openWith(testing.io, arena.allocator(), plugin.plugin.name, &plugin.table, try plugin.conformanceFixture(arena.allocator()), .{ .gpu = true }); @@ -2701,8 +2825,7 @@ test "inkling2 dflash2: a batched draft drafts what each lane drafts alone" { var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const a = arena.allocator(); - var rel = try Release.open(a, pack_dir); - defer rel.close(); + const rel = try Release.shared(pack_dir); const d = rel.m.drafter2 orelse return error.SkipZigTest; const w = &rel.m.base.weights; const taps: c_int = @intCast(d.cfg.tap_count); @@ -3553,8 +3676,7 @@ test "inkling2 draft: stepGroupBundled matches plain decode on the release pack" var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); const a = arena.allocator(); - var rel = try Release.open(a, pack_dir); - defer rel.close(); + const rel = try Release.shared(pack_dir); if (rel.m.drafter == null or rel.m.drafter2 != null) return error.SkipZigTest; const nd = plugin.table.spec.?.native_drafter.?; const step_group = nd.step_group.?; @@ -4152,7 +4274,7 @@ test "inkling2 kernels: sampled Q8 fold keeps Gumbel scores finite" { /// The tiny looped fixture's whole-prompt logits under the model settings `settings`. fn runLoopCdWhole(a: std.mem.Allocator, settings: []const u8, gpu: bool) ![]f32 { - var s = try Setup.initWith(a, gpu, settings); + var s = try Setup.initWith(a, gpu, false, settings); defer s.deinit(a); return a.dupe(f32, s.whole); } @@ -4255,7 +4377,7 @@ test "inkling2 loopcd: logits and adaptive match the exact reference-pass oracle "{\"loopcd\":{\"mode\":\"logits\",\"omega\":0.4,\"ref_pass\":1}}", "{\"loopcd\":{\"mode\":\"adaptive\",\"omega\":0.6,\"ref_pass\":2}}", }) |spec| { - var s = try Setup.initWith(a, false, spec); + var s = try Setup.initWith(a, false, false, spec); defer s.deinit(a); var cache = try test_cache.TestCache.init(a, s.pack.parsed.shell.num_hidden_layers); defer cache.deinit(); @@ -4345,7 +4467,7 @@ test "inkling2 loopcd: verified block commit preserves main and reference coda c "{\"loopcd\":{\"mode\":\"hidden\",\"omega\":0.4,\"ref_pass\":1}}", "{\"loopcd\":{\"mode\":\"logits\",\"omega\":0.4,\"ref_pass\":1}}", }) |spec| { - var s = try Setup.initWith(a, true, spec); + var s = try Setup.initWith(a, true, false, spec); defer s.deinit(a); const m: *plugin.Loaded = @ptrCast(@alignCast(s.pack.model)); const n_entries = s.pack.parsed.shell.num_hidden_layers; @@ -4548,3 +4670,1450 @@ test "inkling2 kernels: quantized split read matches dense over strided 4-bit an } } } + +/// `a`'s bytes (a view made contiguous) as a lowercase sha256. +fn sha256Hex(a: mlx.mlx_array, out: *[64]u8) !void { + var c = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(c); + try mlx.check(mlx.mlx_contiguous(&c, a, false, mlx.gpuStream())); + try mlx.check(mlx.mlx_array_eval(c)); + const n = mlx.mlx_array_size(c) * mlx.mlx_array_itemsize(c); + const p = mlx.mlx_array_data_uint8(c) orelse return error.NoData; + var d: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(p[0..n], &d, .{}); + out.* = std.fmt.bytesToHex(d, .lower); +} + +/// On the release (`INKLING2_RELEASE`), a 3,300-token prompt's last-row logits with `path` (a `kernels.TestMain` +/// field) on main's kernels, then as served (each on its own slot and cache), and the count of words that differ. +fn releaseMainDiffers(comptime path: @EnumLiteral()) !usize { + const env = @import("../../env.zig"); + const pack_dir = std.mem.span(env.get(.INKLING2_RELEASE) orelse return error.SkipZigTest); + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const rel = try Release.shared(pack_dir); + const t = &plugin.table; + const n_layers = rel.parsed.shell.num_hidden_layers; + const snippet = [_]u32{ 1719, 220, 46389, 7, 77, 8, 25, 198, 149862, 150003, 149934, 196982, 220, 17, 25, 198, 149860, 149862, 150583, 149934, 198, 149862, 150583, 220, 46389, 7, 77, 196973, 220, 16, 8, 196986, 220, 46389, 7, 77, 196973, 220, 17, 8, 68019, 1719, 150935, 888, 7, 77, 8, 25, 198 }; + const n: u32 = 3300; + const ids = try a.alloc(u32, n); + for (ids, 0..) |*x, i| x.* = snippet[i % snippet.len]; + var got: [2][]f32 = undefined; + const saved = kernels.test_main; + defer kernels.test_main = saved; + for (0..2) |k| { + @field(kernels.test_main, @tagName(path)) = k == 0; + const slot: u32 = @intCast(40 + k); + var cache = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); + defer cache.deinit(); + var h = [_]abi.Handle{cache.handle()}; + var out: abi.ForwardOut = .{}; + try testing.expect(t.forward(rel.m, &.{ .mode = .prefill, .logits = .last_row, .rows = n, .tokens = .of(ids), .slots = .of(&[_]u32{slot}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); + got[k] = try conformance.consumeF32(a, out.logits); + } + var differ: usize = 0; + for (got[0], got[1]) |x, y| { + if (@as(u32, @bitCast(x)) != @as(u32, @bitCast(y))) differ += 1; + } + std.debug.print("inkling2 release: a prompt's logits with {s} as served differ at {d} of {d} (top token {d} / {d})\n", .{ @tagName(path), differ, got[0].len, argmaxOf(got[0]), argmaxOf(got[1]) }); + if (differ > 0 and argmaxOf(got[0]) != argmaxOf(got[1])) return error.TopTokenMoved; + return differ; +} + +/// Distances of a read's outputs `got` from the float64 read `want`: l2 and max. +fn distances(got: []const f32, want: []const f64) [2]f64 { + var l2: f64 = 0; + var most: f64 = 0; + for (got, want) |x, y| { + const d = @abs(@as(f64, x) - y); + l2 += d * d; + most = @max(most, d); + } + return .{ @sqrt(l2), most }; +} + +/// The float64 relative read: q `[S, H, 128]`, k, v `[HKV, keys, 128]`, the states `[S, H, 16]` times the projection +/// `[16, R]` as the bias below R, the sinks `[S, H]`, the rows the last S of the keys under `window` (0: none). +fn readF64(a: std.mem.Allocator, q: []const f32, k: []const f32, v: []const f32, st: []const f32, p: []const f32, sinks: []const f32, rows: usize, heads: usize, kvh: usize, keys: usize, r: usize, window: usize, scale: f64) ![]f64 { + return readF64Rows(a, q, k, v, st, p, sinks, rows, heads, kvh, keys, r, window, scale, 0, rows); +} + +/// `readF64` of rows `from .. to` only: `[to - from, H, 128]`. +fn readF64Rows(a: std.mem.Allocator, q: []const f32, k: []const f32, v: []const f32, st: []const f32, p: []const f32, sinks: []const f32, rows: usize, heads: usize, kvh: usize, keys: usize, r: usize, window: usize, scale: f64, from: usize, to: usize) ![]f64 { + const out = try a.alloc(f64, (to - from) * heads * 128); + const logit = try a.alloc(f64, keys); + defer a.free(logit); + const off = keys - rows; + for (from..to) |i| for (0..heads) |h| { + const kh = h / (heads / kvh); + const qi = q[(i * heads + h) * 128 ..][0..128]; + const si = st[(i * heads + h) * 16 ..][0..16]; + var mx: f64 = sinks[i * heads + h]; + for (0..keys) |c| { + logit[c] = -std.math.inf(f64); + if (c > off + i) continue; + const d = off + i - c; + if (window > 0 and d >= window) continue; + var dot: f64 = 0; + for (qi, k[(kh * keys + c) * 128 ..][0..128]) |x, y| dot += @as(f64, x) * @as(f64, y); + var b: f64 = 0; + if (d < r) for (0..16) |j| { + b += @as(f64, si[j]) * @as(f64, p[j * r + d]); + }; + logit[c] = dot * scale + b; + mx = @max(mx, logit[c]); + } + var den: f64 = @exp(@as(f64, sinks[i * heads + h]) - mx); + const o = out[((i - from) * heads + h) * 128 ..][0..128]; + @memset(o, 0); + for (0..keys) |c| { + if (logit[c] == -std.math.inf(f64)) continue; + const w = @exp(logit[c] - mx); + den += w; + for (o, v[(kh * keys + c) * 128 ..][0..128]) |*x, y| x.* += w * @as(f64, y); + } + for (o) |*x| x.* /= den; + }; + return out; +} + +// Bar: every dense trunk tensor of the pack loads at 8 bits (group 64), each within half an 8-bit step of its dense +// values (MLX's dequantize of the loaded triple against the dense pack's tensor), and the pack still serves its prompt. +// The logits are not compared: on this random pack one rounding flips an expert pick and the rows diverge. +test "inkling2 proof: TRUNK_Q8 loads the dense trunk at 8 bits within its rounding" { + const a = testing.allocator; + var dense = try Setup.init(a, false); + defer dense.deinit(a); + var q8 = try Setup.initWith(a, false, true, ""); + defer q8.deinit(a); + // Per layer q, gate, r, sink, k, v and o; the 3 global layers' k and v conv projections; the embedding and head. + try testing.expectEqual(@as(u32, 8 * 7 + 3 * 2 + 2), plugin.trunkQ8Tensors()); + const md: *plugin.Loaded = @ptrCast(@alignCast(dense.pack.model)); + const mq: *plugin.Loaded = @ptrCast(@alignCast(q8.pack.model)); + const Lin = @import("../../sdk/bases/blocks/linear.zig").Linear; + var pairs: std.ArrayList([2]Lin) = .empty; + defer pairs.deinit(a); + try pairs.append(a, .{ md.base.weights.embed.table, mq.base.weights.embed.table }); + try pairs.append(a, .{ md.base.weights.head.lin, mq.base.weights.head.lin }); + for (md.layers, mq.layers) |*ld, *lq| { + for ([_]Lin{ ld.q, ld.gate, ld.r, ld.sink, ld.k, ld.v, ld.o }, [_]Lin{ lq.q, lq.gate, lq.r, lq.sink, lq.k, lq.v, lq.o }) |x, y| try pairs.append(a, .{ x, y }); + if (ld.k_conv == .dynamic) { + try pairs.append(a, .{ ld.k_conv.dynamic.proj, lq.k_conv.dynamic.proj }); + try pairs.append(a, .{ ld.v_conv.dynamic.proj, lq.v_conv.dynamic.proj }); + } + } + const s = md.base.s; + for (pairs.items) |p| { + try testing.expect(p[0].s.ctx == null and p[1].s.ctx != null and p[1].bits == 8 and p[1].group_size == 64); + var g = ops.Graph.init(a, s); + defer g.deinit(); + var deq = mlx.mlx_array_new(); + try mlx.check(mlx.mlx_dequantize(&deq, p[1].w, p[1].s, p[1].b, mlx.mlx_optional_int.some(64), mlx.mlx_optional_int.some(8), "affine", .{ .ctx = null }, .{}, s)); + const dq = try g.adopt(deq); + const dw = try g.astype(p[0].w, .float32); + const diff = try g.call(mlx.mlx_max, .{ try g.abs(try g.sub(try g.astype(dq, .float32), dw)), false }); + const top = try g.call(mlx.mlx_max, .{ try g.abs(dw), false }); + try ops.evalMany(&.{ diff, top }); + var d: f32 = 0; + var w: f32 = 0; + try mlx.check(mlx.mlx_array_item_float32(&d, diff)); + try mlx.check(mlx.mlx_array_item_float32(&w, top)); + // One 8-bit step of a group is at most 2 max|w| / 255 (0.8%; MLX rounds the grid's zero, so an end value can + // sit a whole step off); 2% leaves room and still fails a wrong layout or scale by far. + if (!(d <= 0.02 * w)) std.debug.print("[inkling2 proof] TRUNK_Q8: a tensor {d} off at max |w| {d}\n", .{ d, w }); + try testing.expect(d <= 0.02 * w); + } + const rows = prompt.len; + try testing.expectEqual(rows * VOCAB, q8.whole.len); + for (q8.whole) |x| try testing.expect(std.math.isFinite(x)); +} + +// Bar: on the release (`INKLING2_RELEASE`), greedy draft rounds (`NativeDrafter.step`) accept drafts and commit the +// plain greedy decode's tokens: after one prompt of real code ids, 4 rounds against 16 single-row decode steps on +// another cache give the same tokens up to the first difference, and there a near-tie of the plain step's logits +// (the verify's kernels sum in another order than a decode row's), within 1% of its top logit. The rounds run on +// their own slot. +test "inkling2 release: greedy draft rounds commit the plain decode's tokens and accept drafts" { + const env = @import("../../env.zig"); + const pack_dir = std.mem.span(env.get(.INKLING2_RELEASE) orelse return error.SkipZigTest); + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const rel = try Release.shared(pack_dir); + try testing.expect(rel.m.drafter != null); + const t = &plugin.table; + const n_layers = rel.parsed.shell.num_hidden_layers; + // The release tokenizer's ids of "def fibonacci(n):\n if n < 2:\n ... \n\ndef factorial(n):\n": a continuation a + // drafter can predict. + const ids = [_]u32{ 1719, 220, 46389, 7, 77, 8, 25, 198, 149862, 150003, 149934, 196982, 220, 17, 25, 198, 149860, 149862, 150583, 149934, 198, 149862, 150583, 220, 46389, 7, 77, 196973, 220, 16, 8, 196986, 220, 46389, 7, 77, 196973, 220, 17, 8, 68019, 1719, 150935, 888, 7, 77, 8, 25, 198 }; + const n: u32 = ids.len; + const Arm = struct { name: []const u8 }; + const arms = [_]Arm{.{ .name = "default" }}; + // Slot 0 the plain decode, slot 1 + i arm i's rounds: each its own drafter ring, as the engine's slots are. + var plain = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); + defer plain.deinit(); + var first: u32 = 0; + { + var h = [_]abi.Handle{plain.handle()}; + var out: abi.ForwardOut = .{}; + try testing.expect(t.forward(rel.m, &.{ .mode = .prefill, .logits = .last_row, .rows = n, .tokens = .of(&ids), .slots = .of(&[_]u32{0}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); + first = argmaxOf(try conformance.consumeF32(a, out.logits)); + } + var want: [16]u32 = undefined; + var step_logits: [16][]f32 = undefined; + want[0] = first; + for (1..want.len) |i| { + var h = [_]abi.Handle{plain.handle()}; + var out: abi.ForwardOut = .{}; + try testing.expect(t.forward(rel.m, &.{ .mode = .decode, .logits = .last_row, .rows = 1, .tokens = .of(want[i - 1 .. i]), .slots = .of(&[_]u32{0}), .positions = .of(&[_]u32{n + @as(u32, @intCast(i)) - 1}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); + step_logits[i] = try conformance.consumeF32(a, out.logits); + want[i] = argmaxOf(step_logits[i]); + } + const nd = t.spec.?.native_drafter.?; + for (arms, 0..) |arm, ai| { + const slot: u32 = @intCast(1 + ai); + var spec = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); + defer spec.deinit(); + var t1: u32 = 0; + { + var h = [_]abi.Handle{spec.handle()}; + var out: abi.ForwardOut = .{}; + try testing.expect(t.forward(rel.m, &.{ .mode = .prefill, .logits = .last_row, .rows = n, .tokens = .of(&ids), .slots = .of(&[_]u32{slot}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); + t1 = argmaxOf(try conformance.consumeF32(a, out.logits)); + } + var got: std.ArrayList(u32) = .empty; + var pos: u32 = n; + var accepted: u32 = 0; + for (0..4) |_| { + var h = [_]abi.Handle{spec.handle()}; + var out: abi.ForwardOut = .{}; + const v = nd.step(rel.m, &.{ .mode = .decode, .rows = 1, .tokens = .of(&[_]u32{t1}), .slots = .of(&[_]u32{slot}), .positions = .of(&[_]u32{pos}), .caches = .of(&h), .cache_ops = &test_cache.ops, .accept_cap = 7 }, &out); + if (!v.isOk()) std.debug.print("inkling2 release: {s} round refused: {s}\n", .{ arm.name, v.why.slice() }); + try testing.expect(v.isOk()); + try got.appendSlice(a, out.round.tokens[0..out.round.n]); + accepted += out.round.accepted; + std.debug.print("inkling2 release: {s} round at {d}: {d} verify rows, {d} accepted\n", .{ arm.name, pos, out.round.rows, out.round.accepted }); + t1 = out.round.next_token; + pos = @intCast(out.round.position); + } + const m = @min(got.items.len, want.len); + std.debug.print("inkling2 release: {s} rounds committed {d} tokens, {d} drafts accepted; plain {any}, rounds {any}\n", .{ arm.name, got.items.len, accepted, want[0..m], got.items[0..m] }); + var same: usize = 0; + while (same < m and want[same] == got.items[same]) same += 1; + if (same < m) { + // Only a step past the first: the first token comes from each slot's own prompt forward. + try testing.expect(same >= 1); + const lg = step_logits[same]; + const gap = lg[want[same]] - lg[got.items[same]]; + std.debug.print("inkling2 release: {s} rounds and plain decode part at token {d} ({d} vs {d}): the plain step's logit gap {d:.4} of its top {d:.3}\n", .{ arm.name, same, want[same], got.items[same], gap, lg[want[same]] }); + try testing.expect(gap <= 0.01 * @abs(lg[want[same]])); + } else std.debug.print("inkling2 release: {s} rounds and plain decode agree on all {d} tokens\n", .{ arm.name, m }); + try testing.expect(accepted >= 1); + } +} + +// Bar: on the release, a 3,300-token prompt's last-row logits through the row map (gate_up through the sorted pairs' +// row map, as served) are the gathered rows' logits (main's gather, `kernels.test_main.gather_rowmap`), bit for bit: +// the whole prompt path (the pairs' order, the down, the weighted sum and its scatter back) serves the same values, +// each on its own slot and cache. +test "inkling2 release: a prompt through the experts' row map serves the gathered rows' logits" { + const env = @import("../../env.zig"); + const pack_dir = std.mem.span(env.get(.INKLING2_RELEASE) orelse return error.SkipZigTest); + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const rel = try Release.shared(pack_dir); + const t = &plugin.table; + const n_layers = rel.parsed.shell.num_hidden_layers; + const snippet = [_]u32{ 1719, 220, 46389, 7, 77, 8, 25, 198, 149862, 150003, 149934, 196982, 220, 17, 25, 198, 149860, 149862, 150583, 149934, 198, 149862, 150583, 220, 46389, 7, 77, 196973, 220, 16, 8, 196986, 220, 46389, 7, 77, 196973, 220, 17, 8, 68019, 1719, 150935, 888, 7, 77, 8, 25, 198 }; + const n: u32 = 3300; + const ids = try a.alloc(u32, n); + for (ids, 0..) |*x, i| x.* = snippet[i % snippet.len]; + var got: [2][]f32 = undefined; + const saved = kernels.test_main; + defer kernels.test_main = saved; + for (0..2) |k| { + kernels.test_main.gather_rowmap = k == 0; + const slot: u32 = @intCast(30 + k); + var cache = try test_cache.TestCache.init(std.heap.c_allocator, n_layers); + defer cache.deinit(); + var h = [_]abi.Handle{cache.handle()}; + var out: abi.ForwardOut = .{}; + try testing.expect(t.forward(rel.m, &.{ .mode = .prefill, .logits = .last_row, .rows = n, .tokens = .of(ids), .slots = .of(&[_]u32{slot}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); + got[k] = try conformance.consumeF32(a, out.logits); + } + var differ: usize = 0; + for (got[0], got[1]) |x, y| { + if (@as(u32, @bitCast(x)) != @as(u32, @bitCast(y))) differ += 1; + } + std.debug.print("inkling2 release: a prompt's logits through the row map differ at {d} of {d}\n", .{ differ, got[0].len }); + try testing.expectEqual(@as(usize, 0), differ); +} + +/// The release's last prompt row through an `.all_rows` and a `.last_row` forward of `n` rows (fresh caches): the two +/// rows' f32 logits. +fn releaseLastRows(a: std.mem.Allocator, rel: *Release, n: u32, slot0: u32) ![2][]f32 { + const snippet = [_]u32{ 1719, 220, 46389, 7, 77, 8, 25, 198, 149862, 150003, 149934, 196982, 220, 17, 25, 198 }; + const ids = try a.alloc(u32, n); + for (ids, 0..) |*x, i| x.* = snippet[i % snippet.len]; + var got: [2][]f32 = undefined; + for ([_]abi.Logits{ .all_rows, .last_row }, 0..) |mode, k| { + var cache = try test_cache.TestCache.init(std.heap.c_allocator, rel.parsed.shell.num_hidden_layers); + defer cache.deinit(); + var h = [_]abi.Handle{cache.handle()}; + var out: abi.ForwardOut = .{}; + const slot: u32 = slot0 + @as(u32, @intCast(k)); + try testing.expect(plugin.table.forward(rel.m, &.{ .mode = .prefill, .logits = mode, .rows = n, .tokens = .of(ids), .slots = .of(&[_]u32{slot}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops }, &out).isOk()); + if (out.hidden.ctx != null) _ = mlx.mlx_array_free(.{ .ctx = out.hidden.ctx }); + got[k] = try conformance.consumeF32(a, out.logits); + } + // The last-row result is one row: the all-rows result's last row is its length from the end. + got[0] = got[0][got[0].len - got[1].len ..]; + return got; +} + +fn expectSameLastRow(n: u32, got: [2][]f32) !void { + if (!std.mem.eql(u8, std.mem.sliceAsBytes(got[0]), std.mem.sliceAsBytes(got[1]))) std.debug.print("[inkling2 release] last row differs at {d} rows\n", .{n}); + try testing.expectEqualSlices(u8, std.mem.sliceAsBytes(got[0]), std.mem.sliceAsBytes(got[1])); +} + +// Bar: on the release (`INKLING2_RELEASE`), its dense bf16 head (`TRUNK_Q8=0`): a last-row prompt serves the all-rows +// forward's last row, bit for bit, at 65 and 300 rows (on an M5, MLX's bf16 matmul takes another kernel past 64 rows). +test "inkling2 release: a last-row prompt serves the all-rows forward's last row, bit for bit (dense head, 65 and 300 rows)" { + const env = @import("../../env.zig"); + const pack_dir = std.mem.span(env.get(.INKLING2_RELEASE) orelse return error.SkipZigTest); + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const rel = try Release.sharedWith(pack_dir, false); + for ([_]u32{ 65, 300 }, 0..) |n, i| try expectSameLastRow(n, try releaseLastRows(a, rel, n, @intCast(40 + 2 * i))); +} + +// Bar: on the release, the SwiGLU in the row-mapped gate_up's epilogue serves a prompt's logits its own launch serves, +// bit for bit. +test "inkling2 release: a prompt's SwiGLU in the gate_up epilogue serves the same logits" { + try testing.expectEqual(@as(usize, 0), try releaseMainDiffers(.gu_act)); +} + +// Bar: on the release, its 8-bit head (`TRUNK_Q8=1`): a last-row prompt of 4100 rows serves the all-rows +// forward's last row, bit for bit (the SDK runs a head that wide as a dequantized dense matmul). +test "inkling2 release: a last-row prompt serves the all-rows forward's last row, bit for bit (8-bit head, 4100 rows)" { + const env = @import("../../env.zig"); + const pack_dir = std.mem.span(env.get(.INKLING2_RELEASE) orelse return error.SkipZigTest); + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const rel = try Release.sharedWith(pack_dir, true); + try expectSameLastRow(4100, try releaseLastRows(a, rel, 4100, 50)); +} + +// Bar: on the release (`INKLING2_RELEASE`), every tensor TRUNK_Q8 quantizes at load is byte for byte (weight, scales, +// biases) what tests/convert_inkling2.py --bits 8 writes for it (`INKLING2_Q8_REF`, from q8ref_conv.py: the +// converter's own sanitize and quantize in memory), and the load quantizes exactly the converter's set. +test "inkling2 release: TRUNK_Q8 serves the bytes tests/convert_inkling2.py --bits 8 writes" { + const env = @import("../../env.zig"); + const pack_dir = std.mem.span(env.get(.INKLING2_RELEASE) orelse return error.SkipZigTest); + const ref_path = std.mem.span(env.get(.INKLING2_Q8_REF) orelse return error.SkipZigTest); + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + const Resident = @import("../../sdk/weights/resident.zig").Resident; + const loadWeightsOpt = @import("../../sdk/weights/load.zig").loadWeightsOpt; + const FsPackDir = @import("../../sdk/util/pack_dir.zig").FsPackDir; + const gpa = std.heap.c_allocator; + const io = std.Io.Threaded.global_single_threaded.io(); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const ref_json = try std.Io.Dir.cwd().readFileAlloc(io, ref_path, a, .limited(1 << 22)); + const ref = try std.json.parseFromSliceLeaky(std.json.Value, a, ref_json, .{}); + var fs = try FsPackDir.open(io, pack_dir); + defer fs.close(); + const pd = fs.packDir(); + const cfg_json = try std.Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(a, "{s}/config.json", .{pack_dir}), a, .limited(1 << 20)); + const t = &plugin.table; + var parsed: abi.Parsed = .{}; + try testing.expect(t.parse(&pd, .of(cfg_json), .{}, null, false, &parsed).isOk()); + defer t.free_parsed(&parsed); + const s = mlx.mlx_default_gpu_stream_new(); + defer _ = mlx.mlx_stream_free(s); + test_loads.drop(); + var weights = Resident.adopt(try loadWeightsOpt(io, gpa, pack_dir, .{})); + defer weights.deinit(); + const src = weights.source(); + const ov = env.override(.MLX_SERVE_INKLING2_TRUNK_Q8, "1"); + defer ov.restore(); + var why: abi.Verdict = .{}; + const mp = t.load(&.{ .model_dir = .of(pack_dir), .dir = &pd, .parsed = &parsed, .stream = .{ .ctx = s.ctx }, .weights = &src }, &why) orelse return error.LoadRefused; + defer { + _ = mlx.mlx_synchronize(s); + t.unload(mp); + } + const m: *plugin.Loaded = @ptrCast(@alignCast(mp)); + const Lin = @import("../../sdk/bases/blocks/linear.zig").Linear; + const Named = struct { name: []const u8, lin: Lin }; + var named: std.ArrayList(Named) = .empty; + try named.append(a, .{ .name = "model.language_model.embed_tokens", .lin = m.base.weights.embed.table }); + try named.append(a, .{ .name = "lm_head", .lin = m.base.weights.head.lin }); + for (m.layers, 0..) |*L, i| { + const p = try std.fmt.allocPrint(a, "model.language_model.layers.{d}.self_attn.", .{i}); + for ([_][]const u8{ "q_proj", "gate_proj", "r_proj", "sink_proj", "k_proj", "v_proj", "o_proj" }, [_]Lin{ L.q, L.gate, L.r, L.sink, L.k, L.v, L.o }) |leaf, l| + try named.append(a, .{ .name = try std.mem.concat(a, u8, &.{ p, leaf }), .lin = l }); + if (L.k_conv == .dynamic) { + try named.append(a, .{ .name = try std.mem.concat(a, u8, &.{ p, "k_sconv.weight_proj" }), .lin = L.k_conv.dynamic.proj }); + try named.append(a, .{ .name = try std.mem.concat(a, u8, &.{ p, "v_sconv.weight_proj" }), .lin = L.v_conv.dynamic.proj }); + } + } + try testing.expectEqual(ref.object.count(), named.items.len); + try testing.expectEqual(@as(u32, @intCast(named.items.len)), plugin.trunkQ8Tensors()); + var off: usize = 0; + for (named.items) |nl| { + const want = ref.object.get(nl.name) orelse { + std.debug.print("inkling2 release: {s} is not in the converter's set\n", .{nl.name}); + off += 3; + continue; + }; + try testing.expectEqual(@as(u32, 8), nl.lin.bits); + for ([_][]const u8{ "weight", "scales", "biases" }, [_]mlx.mlx_array{ nl.lin.w, nl.lin.s, nl.lin.b }) |leaf, arr| { + var hex: [64]u8 = undefined; + try sha256Hex(arr, &hex); + const w = want.object.get(leaf).?.object.get("sha256").?.string; + const same = std.mem.eql(u8, w, &hex); + off += @intFromBool(!same); + if (!same) std.debug.print("inkling2 release: {s}.{s}: ours {s}, the converter's {s}\n", .{ nl.name, leaf, hex[0..12], w[0..12] }); + } + } + std.debug.print("inkling2 release: TRUNK_Q8, {d} of {d} tensors differ from tests/convert_inkling2.py --bits 8\n", .{ off, named.items.len * 3 }); + try testing.expectEqual(@as(usize, 0), off); +} + +// Bar: a prompt forwarded with the engine's eval points (every 2 visits) as async evals (as served) serves the rows +// main's synchronous evals serve, bit for bit, on each stream. +test "inkling2 proof: a prompt's eval points as async evals serve the same rows" { + const a = testing.allocator; + for (streams()) |gpu| { + var s = try Setup.init(a, gpu); + defer s.deinit(a); + var rows: [2][]f32 = undefined; + const saved = kernels.test_main; + defer kernels.test_main = saved; + for (0..2) |i| { + kernels.test_main.prefill_async = i == 0; + var cache = try test_cache.TestCache.init(a, s.pack.parsed.shell.num_hidden_layers); + defer cache.deinit(); + var h = [_]abi.Handle{cache.handle()}; + var out: abi.ForwardOut = .{}; + try testing.expect(s.pack.table.forward(s.pack.model, &.{ .mode = .prefill, .logits = .all_rows, .rows = @intCast(prompt.len), .tokens = .of(&prompt), .slots = .of(&[_]u32{0}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops, .eval_every = 2 }, &out).isOk()); + if (out.hidden.ctx != null) _ = mlx.mlx_array_free(.{ .ctx = out.hidden.ctx }); + rows[i] = try conformance.consumeF32(a, out.logits); + } + defer for (rows) |r| a.free(r); + try testing.expectEqualSlices(f32, rows[0], rows[1]); + } +} + +// Bar: as above, on a sliding and a global layer. One row: with and without log-scaling, its bias row for a view +// shorter than, as long as and longer than the relative extent. A prompt's rows: the clipped relative states. +// Bar: a prompt chunk's prep kernel reads a joined projection's parts as views and gives every output's bytes the +// contiguous copies give (a step's prep), at one row and seven (where the prompt copies too) and 16, f32 and bf16. +test "inkling2 kernels: the prep kernel reads a joined projection's parts in place" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + var s = try Stage.init(a); + defer s.deinit(); + const body = s.body; + const cfg = &body.cfg; + const taps: c_int = @intCast(cfg.sconv_kernel); + const width: c_int = @intCast(2 * cfg.kvDim() + 2 * cfg.hidden_size); + var seed: u64 = 9900; + for ([_]usize{ 0, 1 }) |li| for ([_]ops.Dtype{ .float32, .bfloat16 }) |dt| for ([_]c_int{ 1, 7, 16 }) |rows| { + const L = &body.layers[li]; + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + seed += 100; + const proj = try randomProjected(&g, a, seed, L, cfg, rows, dt); + // The six parts as views of one joined row, as `projections` hands a joined layer's. + var parts: [6]ops.Array = undefined; + var widths: [6]c_int = undefined; + for (proj.proj, &widths) |x, *w| w.* = ops.shape(x)[2]; + const joined = try g.concat(&proj.proj, 2); + var at: c_int = 0; + for (&parts, widths) |*x, w| { + x.* = try g.sliceAxis(joined, 2, at, at + w); + at += w; + } + const st = try randomRow(&g, a, seed + 60, &.{ 1, taps - 1, width }, 1.0, .float32); + var outs: [2]kernels.Prep = undefined; + for ([_]kernels.Load{ .step, .prompt }, &outs) |load, *o| { + o.* = (try kernels.prepAt(&g, load, L, cfg, &parts, proj.dyn, st, 1.0, if (rows == 1) 3 else 0, null)) orelse return error.TestUnexpectedResult; + } + for ([_][2]ops.Array{ .{ outs[0].q, outs[1].q }, .{ outs[0].k, outs[1].k }, .{ outs[0].v, outs[1].v }, .{ outs[0].gate, outs[1].gate } }) |pair| try expectClose(pair[1], pair[0], 0, "prep output"); + if (rows == 1) try expectClose(outs[1].bias, outs[0].bias, 0, "bias") else try expectClose(outs[1].rel, outs[0].rel, 0, "relative states"); + }; +} + +// Bar: PIPELINES_AT_LOAD's record holds a first launch and its replay at load builds that pipeline again in a process +// that has not seen it (the record's line parsed back to the launch: its kernel, grid, template arguments, shapes). +test "inkling2 kernels: a recorded first launch is replayed at load" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + const path = "/tmp/inkling2-pipelines-proof.txt"; + _ = std.c.unlink(path); + defer _ = std.c.unlink(path); + const saved = kernels.pipes; + defer kernels.pipes = saved; + kernels.pipes = .{}; + const first = try kernels.pipelinesAtLoad(mlx.gpuStream(), path); + try testing.expectEqual(@as(usize, 0), first[1]); + var cfg: @import("config.zig").Config = undefined; + cfg.hidden_size = 2304; + cfg.rms_norm_eps = 1e-6; + { + var g = ops.Graph.init(a, mlx.gpuStream()); + defer g.deinit(); + const y = try randomRow(&g, a, 8100, &.{ 1, 4, 2304 }, 1.0, .float32); + const nw = try randomRow(&g, a, 8101, &.{2304}, 1.0, .bfloat16); + try ops.evalMany(&.{(try kernels.norm(&g, &cfg, y, @splat(nw), 1, .bfloat16, null))[0]}); + } + // A fresh process's view: nothing seen, the record kept; a malformed line ahead of it is skipped, not the record. + kernels.pipes.n = 0; + kernels.pipes.record_len = 0; + { + var buf: [1 << 16]u8 = undefined; + const rh = std.c.fopen(path, "rb") orelse return error.TestRecordOpen; + const old = buf[0..std.c.fread(&buf, 1, buf.len, rh)]; + _ = std.c.fclose(rh); + const fh = std.c.fopen(path, "wb") orelse return error.TestRecordOpen; + const junk = "msv_inkling2_norm\t1,1\n"; + _ = std.c.fwrite(junk.ptr, 1, junk.len, fh); + _ = std.c.fwrite(old.ptr, 1, old.len, fh); + _ = std.c.fclose(fh); + } + const again = try kernels.pipelinesAtLoad(mlx.gpuStream(), path); + try testing.expect(again[1] >= 1); + try testing.expect(again[0] >= 1); + try testing.expectEqual(@as(usize, 1), again[2]); +} + +// Bar: on NAX, a prompt's message gates on the matrix units (f32 accumulate, the mix in the epilogue) are the f32 +// reference's within 1e-5 of its peak, at 96 rows and a ragged 100. +test "inkling2 kernels: a prompt's message gates on the matrix units are the f32 reference's" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + const d: c_int = 2304; + const rank: c_int = 64; + for ([_]c_int{ 96, 100 }) |rows| { + var g = ops.Graph.init(a, mlx.gpuStream()); + defer g.deinit(); + const streams_in = try randomRow(&g, a, 7310, &.{ 3, rows, d }, 1.0, .float32); + const ms = try randomRow(&g, a, 7311, &.{ 3, rows, d }, 1.0, .float32); + const st = try randomRow(&g, a, 7312, &.{ 3, rows, rank }, 1.0, .bfloat16); + const gates: layers.Gates = .{ .down = st, .forget = try randomRow(&g, a, 7313, &.{ 3, d, rank }, 0.2, .bfloat16), .message = try randomRow(&g, a, 7314, &.{ 3, d, rank }, 0.2, .bfloat16) }; + const cs = mlx.mlx_default_cpu_stream_new(); + defer _ = mlx.mlx_stream_free(cs); + var cpu = ops.Graph.init(a, cs); + defer cpu.deinit(); + const fp = try cpu.matmul(try cpu.astype(st, .float32), try cpu.transpose(try cpu.astype(gates.forget, .float32), &.{ 0, 2, 1 })); + const gp = try cpu.matmul(try cpu.astype(st, .float32), try cpu.transpose(try cpu.astype(gates.message, .float32), &.{ 0, 2, 1 })); + const one = try cpu.ones(&.{1}, .float32); + const want = try cpu.add(try cpu.mul(try cpu.sub(one, try cpu.tanh(fp)), streams_in), try cpu.mul(try cpu.tanh(gp), ms)); + const peak = try parity.maxAbsDiffF32(want, try cpu.zeros(&.{ 3, rows, d }, .float32), cs); + const got = try kernels.gate(&g, &gates, streams_in, ms, st, 0, 3); + const err = try parity.maxAbsDiffF32(got, want, mlx.gpuStream()); + std.debug.print("[inkling2 kernels] prompt gate on the matrix units at {d} rows: max |d| {d:.7} of peak {d:.3}\n", .{ rows, err, peak }); + try testing.expect(err <= 1e-5 * peak); + } +} + +// Bar: the tensor-unit flash read (`relativeNaxStates`, its bias made from the states inside it) against the mask +// kernel with MLX's attention over the projected bias on the same rows at the release's head dim 128 and 8 heads over +// 2 KV heads, global and banded, from the start and behind earlier keys, for row counts on and off its 64-row tiles: +// 5e-2 of unit-RMS bf16 values. +test "inkling2 kernels: the tensor-unit flash read is the masked chain's" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + fx_stream = mlx.gpuStream(); + const R = 16; + const scale = 1.0 / @sqrt(128.0); + var seed: u64 = 13000; + for ([_]c_int{ 0, 48 }) |window| for ([_]c_int{ 70, 128 }) |rows| for ([_]c_int{ 0, 40 }) |offset| { + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + seed += 10; + const total = offset + rows; + const keys = if (window == 0) total else @min(total, window + rows - 1); + const q = try g.transpose(try randomRow(&g, a, seed, &.{ 1, rows, 8, 128 }, 0.6, .bfloat16), &.{ 0, 2, 1, 3 }); + const st = try randomRow(&g, a, seed + 1, &.{ 1, rows, 8, 16 }, 0.5, .bfloat16); + const proj = try randomRow(&g, a, seed + 5, &.{ 16, R }, 0.25, .bfloat16); + const bias = try g.matmul(st, proj); + const relp = try g.contiguous(try g.concat(&.{ try g.zeros(&.{ 16, kernels.relp_before }, .bfloat16), proj, try g.zeros(&.{ 16, 64 }, .bfloat16) }, 1)); + const sinks = try g.astype(try randomRow(&g, a, seed + 2, &.{ 1, rows, 8 }, 1.0, .float32), .float32); + const k = try randomRow(&g, a, seed + 3, &.{ 1, 2, keys, 128 }, 0.6, .bfloat16); + const v = try randomRow(&g, a, seed + 4, &.{ 1, 2, keys, 128 }, 1.0, .bfloat16); + const zero = try g.zeros(&.{ 1, 2, 1, 128 }, .bfloat16); + const read = try g.sdpa(q, try g.concat(&.{ k, zero }, 2), try g.concat(&.{ v, zero }, 2), scale, .{ .array = try kernels.relMask(&g, bias, sinks, keys, window, true) }); + const want = try g.contiguous(try g.transpose(read, &.{ 0, 2, 1, 3 })); + const got = (try kernels.relativeNaxStates(&g, 8, 2, q, k, v, st, relp, sinks, window, rows, keys, R, scale)) orelse return error.TestUnexpectedResult; + try expectClose(try g.contiguous(got), want, 5e-2, "tensor-unit flash read"); + }; +} + +// Bar: MARKOV_Q8's precomputed-kappa + coalesced Q8 Markov kernels pick the exact same tokens and close probabilities as the op chain. +test "inkling2 draft: Q8 Markov kernels match op chain tokens and probabilities" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + fx_stream = mlx.gpuStream(); + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + const H: c_int = 64; + const R: c_int = 32; + const V: c_int = 256; + const vocab: c_int = 250; + var d: draft.Drafter = .{ + .cfg = .{ .layers = 1, .heads = 2, .kv_heads = 1, .head_dim = 16, .intermediate = 48, .window = 16, .block = 5, .rank = @intCast(R), .tap_count = 2 }, + .hidden = @intCast(H), + .s = fx_stream, + }; + d.norm = try g.ones(&.{H}, .bfloat16); + d.prev_rows = try randomRow(&g, a, 61001, &.{ V, R }, 0.3, .bfloat16); + d.rnn = .{ .w = try randomRow(&g, a, 61002, &.{ 3 * R, 2 * R + 2 * H }, 0.15, .bfloat16) }; + d.rnn_bias = try randomRow(&g, a, 61003, &.{3 * R}, 0.1, .bfloat16); + d.rnn_step = try g.contiguous(try g.sliceAxis(d.rnn.w, 1, 0, 2 * R)); + d.rnn_ctx = try g.contiguous(try g.sliceAxis(d.rnn.w, 1, 2 * R, 2 * R + 2 * H)); + d.fold = try randomRow(&g, a, 61004, &.{ R, V }, 0.25, .bfloat16); + const qf = try draft.Drafter.quantizeFoldRows(&g, d.fold); + d.fold_q8 = qf[0]; + d.fold_q8_sc = qf[1]; + d.fold_bias = try randomRow(&g, a, 61005, &.{ 1, 1, V }, 0.2, .bfloat16); + const rows = try randomRow(&g, a, 61006, &.{ 1, 4, H }, 0.8, .bfloat16); + const newest = try randomRow(&g, a, 61007, &.{ 1, 1, H }, 0.8, .bfloat16); + // Clear margins so Q8 quantization (~0.5%) never flips an arbitrary near-tie. + const base = try randomRow(&g, a, 61008, &.{ 1, 4, V }, 4.0, .float32); + const t1 = try g.fromSlice(i32, &.{17}, &.{1}); + const want = try d.markov(&g, t1, rows, newest, base, vocab, 30.0, false, null); + const got = try d.markov(&g, t1, rows, newest, base, vocab, 30.0, true, null); + try expectClose(got.tokens, want.tokens, 0, "q8 drafted tokens"); + try expectClose(got.confidence, want.confidence, 2e-2, "q8 draft probabilities"); +} + +/// The paths built for a prompt's rows, which a decode, a verify and batched slots must not take. +const PromptPath = enum { prep, stream_row, gate_mm, rowmap, gu_act }; + +fn resetPromptPaths() void { + kernels.resetEngaged(.prep_strided); + kernels.resetEngaged(.stream_row); + kernels.resetEngaged(.gate_mm); + kernels.resetEngaged(.gather_rowmap); + kernels.resetEngaged(.gu_act); +} + +fn promptPathEngaged(l: PromptPath) bool { + return switch (l) { + .prep => kernels.wasEngaged(.prep_strided), + .stream_row => kernels.wasEngaged(.stream_row), + .gate_mm => kernels.wasEngaged(.gate_mm), + .rowmap => kernels.wasEngaged(.gather_rowmap), + .gu_act => kernels.wasEngaged(.gu_act), + }; +} + +// Bar: at a grouped verify's 72 rows and batched decode's 12, a step's load takes main's gate, norm and prep (the tiled +// gates, the row norm and the strided prep not engaged); on NAX the same rows as a prompt chunk engage each (control). +test "inkling2 kernels: a verify's or batched slots' rows take main's gate, norm and prep" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + var s = try Stage.init(a); + defer s.deinit(); + defer resetPromptPaths(); + var cfg: @import("config.zig").Config = undefined; + cfg.hidden_size = 2304; + cfg.rms_norm_eps = 1e-6; + const d: c_int = 2304; + const rank: c_int = 64; + for ([_]c_int{ 72, 36 }) |rows| { + var g = ops.Graph.init(a, mlx.gpuStream()); + defer g.deinit(); + const streams_in = try randomRow(&g, a, 7410, &.{ 3, rows, d }, 1.0, .float32); + const ms = try randomRow(&g, a, 7411, &.{ 3, rows, d }, 1.0, .float32); + const st = try randomRow(&g, a, 7412, &.{ 3, rows, rank }, 1.0, .bfloat16); + const gates: layers.Gates = .{ .down = st, .forget = try randomRow(&g, a, 7413, &.{ 3, d, rank }, 0.2, .bfloat16), .message = try randomRow(&g, a, 7414, &.{ 3, d, rank }, 0.2, .bfloat16) }; + const nw = try randomRow(&g, a, 7415, &.{d}, 0.1, .bfloat16); + resetPromptPaths(); + const step_gate = try kernels.gateAt(&g, .step, &gates, streams_in, ms, st, 0, 3); + const step_norm = (try kernels.normAt(&g, .step, &cfg, streams_in, @splat(nw), 3, .bfloat16, null))[0]; + try ops.evalMany(&.{ step_gate, step_norm }); + try testing.expect(!promptPathEngaged(.gate_mm) and !promptPathEngaged(.stream_row)); + try ops.evalMany(&.{ try kernels.gateAt(&g, .prompt, &gates, streams_in, ms, st, 0, 3), (try kernels.normAt(&g, .prompt, &cfg, streams_in, @splat(nw), 3, .bfloat16, null))[0] }); + // The tiled gates need more than `packed_rows`; the row norm a threadgroup this GPU has not narrowed past + // `row_elems`. + try testing.expectEqual(kernels.streamRow(.prompt, rows, d, kernels.streamGroup(2304).?), promptPathEngaged(.stream_row)); + try testing.expectEqual(rows > kernels.packed_rows, promptPathEngaged(.gate_mm)); + } + const body = s.body; + const taps: c_int = @intCast(body.cfg.sconv_kernel); + const width: c_int = @intCast(2 * body.cfg.kvDim() + 2 * body.cfg.hidden_size); + for ([_]usize{ 0, 1 }) |li| for ([_]c_int{ 12, 72 }) |rows| { + const L = &body.layers[li]; + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + const proj = try randomProjected(&g, a, 7500 + li * 10, L, &body.cfg, rows, .bfloat16); + const st = try randomRow(&g, a, 7560 + li, &.{ 1, taps - 1, width }, 1.0, .float32); + resetPromptPaths(); + const as_step = (try kernels.prepAt(&g, .step, L, &body.cfg, &proj.proj, proj.dyn, st, 1.0, 0, null)) orelse return error.TestUnexpectedResult; + try ops.evalMany(&.{as_step.q}); + try testing.expect(!promptPathEngaged(.prep)); + const as_prompt = (try kernels.prepAt(&g, .prompt, L, &body.cfg, &proj.proj, proj.dyn, st, 1.0, 0, null)) orelse return error.TestUnexpectedResult; + try ops.evalMany(&.{as_prompt.q}); + try testing.expect(promptPathEngaged(.prep)); + }; +} + +// Bar: on NAX, a grouped verify's 72 rows over an NVFP4 bank read MLX's gather (neither the row map nor the gate_up +// epilogue engaged); the same rows as a prompt chunk take the row-mapped epilogue (control). +test "inkling2 kernels: a verify's rows past 64 keep MLX's gather" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + var s = try Stage.init(a); + defer s.deinit(); + defer resetPromptPaths(); + var body = s.body.*; + const hidden: c_int = @intCast(body.cfg.hidden_size); + const experts: c_int = @intCast(body.cfg.num_experts); + const kv_dim: c_int = @intCast(body.cfg.kvDim()); + const taps: c_int = @intCast(body.cfg.sconv_kernel); + const inter: c_int = 64; + const rows: c_int = 72; + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + var L = body.layers[3]; + body.cfg.moe_intermediate_size = @intCast(inter); + L.gate_up = try packedBank(&g, a, 7600, &.{ experts, 2 * inter, hidden }, 4, 16, .nvfp4); + L.down = try packedBank(&g, a, 7601, &.{ experts, hidden, inter }, 4, 16, .nvfp4); + L.gate_up_scale = try g.addScalar(try randomRow(&g, a, 7602, &.{experts}, 0.3, .float32), 1.5); + const cfg = &body.cfg; + const x = try randomRow(&g, a, 7604, &.{ 1, rows, hidden }, 1.0, .bfloat16); + const residual = try randomRow(&g, a, 7605, &.{ 1, rows, hidden }, 1.0, .float32); + const st = try randomRow(&g, a, 7606, &.{ 1, taps - 1, 2 * kv_dim + 2 * hidden }, 1.0, .float32); + const kp = try randomRow(&g, a, 7607, &.{ 1, rows, kv_dim }, 1.0, .bfloat16); + const vp = try randomRow(&g, a, 7608, &.{ 1, rows, kv_dim }, 1.0, .bfloat16); + const op = try randomRow(&g, a, 7609, &.{ 1, rows, hidden }, 1.0, .bfloat16); + const scores = try g.matmul(try g.astype(x, .float32), try g.transpose(L.router, &.{ 1, 0 })); + const m: kernels.Middle = .{ .x = x, .scores = scores, .residual = residual, .blocks = null, .op = op }; + resetPromptPaths(); + const step_h = (try kernels.expertsAt(&g, .step, &L, cfg, &m, kp, vp, st, null)).h; + try ops.evalMany(&.{step_h}); + try testing.expect(!promptPathEngaged(.rowmap) and !promptPathEngaged(.gu_act)); + try ops.evalMany(&.{(try kernels.expertsAt(&g, .prompt, &L, cfg, &m, kp, vp, st, null)).h}); + try testing.expect(promptPathEngaged(.rowmap) and promptPathEngaged(.gu_act)); +} + +/// One batched decode step of up to 16 slots: slot i's `tokens[i]` at `positions[i]` on `caches[i]`. +fn batchedStepWide(a: std.mem.Allocator, pack: *conformance.Loaded, caches: []test_cache.TestCache, tokens: []const u32, positions: []const u32) ![]f32 { + var handles: [16]abi.Handle = undefined; + var slots: [16]u32 = undefined; + for (caches, 0..) |*c, i| { + handles[i] = c.handle(); + slots[i] = @intCast(i); + } + var out: abi.ForwardOut = .{}; + const v = pack.table.forward(pack.model, &.{ .mode = .batched_rows, .logits = .last_row, .rows = 1, .tokens = .of(tokens), .slots = .of(slots[0..caches.len]), .positions = .of(positions), .caches = .of(handles[0..caches.len]), .cache_ops = &test_cache.ops }, &out); + try testing.expect(v.isOk()); + if (out.hidden.ctx != null) _ = mlx.mlx_array_free(.{ .ctx = out.hidden.ctx }); + return conformance.consumeF32(a, out.logits); +} + +// Bar: through the plugin's forward, 12 batched slots and a grouped verify of 6 slots x 6 rows (36) engage neither the +// strided prep nor the row norm; on NAX a 36-row prompt chunk engages both (control). +test "inkling2 proof: batched slots and a grouped verify take main's path" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + defer resetPromptPaths(); + var s = try Setup.init(a, true); + defer s.deinit(a); + const m: *plugin.Loaded = @ptrCast(@alignCast(s.pack.model)); + const visits = s.pack.parsed.shell.num_hidden_layers; + var long: [36]u32 = undefined; + for (&long, 0..) |*t, i| t.* = @intCast((i * 7 + 3) % VOCAB); + var caches: [12]test_cache.TestCache = undefined; + var made: usize = 0; + defer for (caches[0..made]) |*c| c.deinit(); + var tokens: [12]u32 = undefined; + var positions: [12]u32 = undefined; + for (&caches, 0..) |*c, i| { + c.* = try test_cache.TestCache.init(a, visits); + made = i + 1; + a.free(try step(a, &s.pack, c, prompt[0 .. 3 + i], 0, .last_row)); + tokens[i] = prompt[3 + i]; + positions[i] = @intCast(3 + i); + } + resetPromptPaths(); + a.free(try batchedStepWide(a, &s.pack, &caches, &tokens, &positions)); + try testing.expect(!promptPathEngaged(.prep) and !promptPathEngaged(.stream_row)); + + var g = ops.Graph.init(a, m.base.s); + defer g.deinit(); + const opens = try a.alloc(kernels.Open, visits); + defer a.free(opens); + @memset(opens, .{ .g = &g }); + var sp: plugin.Spec = .{ .visits = &.{}, .keep = 4 }; + defer { + m.base.weights.spec = null; + for ([_]mlx.mlx_array{ sp.ring, sp.held }) |x| if (x.ctx != null) { + _ = mlx.mlx_array_free(x); + }; + } + m.base.weights.spec = &sp; + sp.opens = opens; + var block: [36]u32 = undefined; + var at: [6]u32 = undefined; + for (0..6) |i| { + @memcpy(block[i * 6 ..][0..6], long[i .. i + 6]); + at[i] = positions[i] + 1; + } + resetPromptPaths(); + a.free(try groupStep(a, &s.pack, caches[0..6], &block, &at, 6)); + sp.opens = null; + try testing.expect(!promptPathEngaged(.prep) and !promptPathEngaged(.stream_row)); + + var fresh = try test_cache.TestCache.init(a, visits); + defer fresh.deinit(); + resetPromptPaths(); + a.free(try step(a, &s.pack, &fresh, &long, 0, .last_row)); + try testing.expect(promptPathEngaged(.prep) and promptPathEngaged(.stream_row)); +} + +// Bar: with the GPU-family fallback forced (`vqmm_nax_probe_override = false`, the test seam of +// `MLX_SERVE_DIAG=force-gpu-family-fallback=1`, an M1-M4's view), a 72-row prompt chunk with eval points engages none +// of the prompt paths (the strided prep, the row norm, the tiled gates, the async eval points, the experts' row map and +// its gate_up epilogue), and its logits are the bytes of the same chunk with every one of them sent down main's path +// (`kernels.test_main`). +test "inkling2 proof: off NAX a prompt takes main's path, byte for byte" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + const nax = @import("../../sdk/blocks/linear/verify_qmm_nax.zig"); + const saved_nax = nax.vqmm_nax_probe_override; + defer nax.vqmm_nax_probe_override = saved_nax; + nax.vqmm_nax_probe_override = false; + defer resetPromptPaths(); + defer kernels.resetEngaged(.prefill_async); + var s = try Setup.init(a, true); + defer s.deinit(a); + const visits = s.pack.parsed.shell.num_hidden_layers; + var long: [72]u32 = undefined; + for (&long, 0..) |*t, i| t.* = @intCast((i * 7 + 3) % VOCAB); + var rows: [2][]f32 = undefined; + var made: usize = 0; + defer for (rows[0..made]) |r| a.free(r); + const saved = kernels.test_main; + defer kernels.test_main = saved; + for (0..2) |i| { + const main = i == 1; + kernels.test_main = .{ .relnax = main, .gather_rowmap = main, .gu_act = main, .prefill_async = main, .gate_mm = main, .prep_strided = main, .stream_row = main }; + resetPromptPaths(); + kernels.resetEngaged(.prefill_async); + var cache = try test_cache.TestCache.init(a, visits); + defer cache.deinit(); + var h = [_]abi.Handle{cache.handle()}; + var out: abi.ForwardOut = .{}; + try testing.expect(s.pack.table.forward(s.pack.model, &.{ .mode = .prefill, .logits = .all_rows, .rows = @intCast(long.len), .tokens = .of(&long), .slots = .of(&[_]u32{0}), .positions = .of(&[_]u32{0}), .caches = .of(&h), .cache_ops = &test_cache.ops, .eval_every = 2 }, &out).isOk()); + if (out.hidden.ctx != null) _ = mlx.mlx_array_free(.{ .ctx = out.hidden.ctx }); + rows[i] = try conformance.consumeF32(a, out.logits); + made = i + 1; + for ([_]PromptPath{ .prep, .stream_row, .gate_mm, .rowmap, .gu_act }) |p| try testing.expect(!promptPathEngaged(p)); + try testing.expect(!kernels.wasEngaged(.prefill_async)); + } + try testing.expectEqualSlices(u8, std.mem.sliceAsBytes(rows[1]), std.mem.sliceAsBytes(rows[0])); +} + +// Bar: the row map's gate takes exactly the expert layouts its kernel's own check decodes (NVFP4, MXFP4, affine 2, 3, 4, +// 8 bits at g32, g64, g128 with bf16 scales) and no other (MXFP8, affine 5 and 6 bits, f32 scales); on NAX a prompt over +// an MXFP8 bank keeps MLX's gather and is declined by name in the log. +test "inkling2 kernels: the row map takes the expert layouts its kernel decodes and declines the others by name" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + var s = try Stage.init(a); + defer s.deinit(); + defer resetPromptPaths(); + var body = s.body.*; + const hidden: c_int = @intCast(body.cfg.hidden_size); + const experts: c_int = @intCast(body.cfg.num_experts); + const inter: c_int = 64; + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + var seed: u64 = 7700; + const Case = struct { mode: QuantMode, bits: u32, group: u32, takes: bool }; + var cases: [5 + 4 * 3]Case = undefined; + cases[0] = .{ .mode = .nvfp4, .bits = 4, .group = 16, .takes = true }; + cases[1] = .{ .mode = .mxfp4, .bits = 4, .group = 32, .takes = true }; + cases[2] = .{ .mode = .mxfp8, .bits = 8, .group = 32, .takes = false }; + cases[3] = .{ .mode = .affine, .bits = 5, .group = 64, .takes = false }; + cases[4] = .{ .mode = .affine, .bits = 6, .group = 64, .takes = false }; + var n: usize = 5; + for ([_]u32{ 2, 3, 4, 8 }) |bits| for ([_]u32{ 32, 64, 128 }) |group| { + cases[n] = .{ .mode = .affine, .bits = bits, .group = group, .takes = true }; + n += 1; + }; + for (cases) |c| { + seed += 1; + // 256 inputs: every group size divides them (the gate reads only the layout). + var bank = try packedBank(&g, a, seed, &.{ experts, 2 * inter, 256 }, c.bits, c.group, c.mode); + if (c.mode == .affine) { + // A pack's affine experts carry bf16 scales and biases; the helper quantizes f32 rows. + try testing.expect(!kernels.rowMapTakes(&bank)); + bank.s = try g.astype(bank.s, .bfloat16); + bank.b = try g.astype(bank.b, .bfloat16); + } + if (kernels.rowMapTakes(&bank) != c.takes) std.debug.print("[inkling2 kernels] row map gate on {s} {d}-bit g{d}: want {}\n", .{ @tagName(c.mode), c.bits, c.group, c.takes }); + try testing.expectEqual(c.takes, kernels.rowMapTakes(&bank)); + } + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return; + const kv_dim: c_int = @intCast(body.cfg.kvDim()); + const taps: c_int = @intCast(body.cfg.sconv_kernel); + const rows: c_int = 72; + var L = body.layers[3]; + body.cfg.moe_intermediate_size = @intCast(inter); + L.gate_up = try packedBank(&g, a, 7790, &.{ experts, 2 * inter, hidden }, 8, 32, .mxfp8); + L.down = try packedBank(&g, a, 7791, &.{ experts, hidden, inter }, 8, 32, .mxfp8); + const x = try randomRow(&g, a, 7792, &.{ 1, rows, hidden }, 1.0, .bfloat16); + const scores = try g.matmul(try g.astype(x, .float32), try g.transpose(L.router, &.{ 1, 0 })); + const m: kernels.Middle = .{ .x = x, .scores = scores, .residual = try randomRow(&g, a, 7793, &.{ 1, rows, hidden }, 1.0, .float32), .blocks = null, .op = try randomRow(&g, a, 7794, &.{ 1, rows, hidden }, 1.0, .bfloat16) }; + const st = try randomRow(&g, a, 7795, &.{ 1, taps - 1, 2 * kv_dim + 2 * hidden }, 1.0, .float32); + const kp = try randomRow(&g, a, 7796, &.{ 1, rows, kv_dim }, 1.0, .bfloat16); + const vp = try randomRow(&g, a, 7797, &.{ 1, rows, kv_dim }, 1.0, .bfloat16); + resetPromptPaths(); + try ops.evalMany(&.{(try kernels.expertsAt(&g, .prompt, &L, &body.cfg, &m, kp, vp, st, null)).h}); + try testing.expect(!promptPathEngaged(.rowmap) and !promptPathEngaged(.gu_act)); + var buf: [96]u8 = undefined; + try testing.expect(kernels.wasDeclined(.gather_rowmap, kernels.rowMapLayout(&buf, &L.gate_up))); +} + +fn recordText(buf: []u8, path: [*:0]const u8) ![]const u8 { + const fh = std.c.fopen(path, "rb") orelse return error.TestRecordOpen; + defer _ = std.c.fclose(fh); + return buf[0..std.c.fread(buf.ptr, 1, buf.len, fh)]; +} + +/// One norm launch on the GPU in `dt` (a pipeline key a dtype names). +fn normLaunch(a: std.mem.Allocator, dt: ops.Dtype) !void { + var cfg: @import("config.zig").Config = undefined; + cfg.hidden_size = 2304; + cfg.rms_norm_eps = 1e-6; + var g = ops.Graph.init(a, mlx.gpuStream()); + defer g.deinit(); + const y = try randomRow(&g, a, 8200, &.{ 1, 4, 2304 }, 1.0, .float32); + const nw = try randomRow(&g, a, 8201, &.{2304}, 1.0, .bfloat16); + try ops.evalMany(&.{(try kernels.norm(&g, &cfg, y, @splat(nw), 1, dt, null))[0]}); +} + +// Bar: before ready a first launch is kept and appended to the record; after `ready` a launch at a new dtype adds no +// record line and leaves the kept launches as they were. +test "inkling2 kernels: the pipeline record takes first launches before ready and none after" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + const path = "/tmp/inkling2-pipelines-ready-proof.txt"; + _ = std.c.unlink(path); + defer _ = std.c.unlink(path); + const saved = kernels.pipes; + defer kernels.pipes = saved; + kernels.pipes = .{}; + _ = try kernels.pipelinesAtLoad(mlx.gpuStream(), path); + try normLaunch(a, .bfloat16); + try testing.expectEqual(@as(usize, 1), kernels.pipes.n); + try testing.expectEqual(@as(u64, 1), kernels.pipes.added); + var buf: [1 << 16]u8 = undefined; + const before = try a.dupe(u8, try recordText(&buf, path)); + defer a.free(before); + try testing.expect(std.mem.indexOf(u8, before, "msv_inkling2_norm\t") != null); + kernels.pipes.ready(); + try testing.expect(!kernels.pipes.watching); + try normLaunch(a, .float32); + try testing.expectEqual(@as(usize, 1), kernels.pipes.n); + try testing.expectEqualStrings(before, try recordText(&buf, path)); +} + +// Bar: with a record open, a kernel's launch repeated is kept once, and its launch at another dtype after the repeats is +// still a first launch (a kernel's seen launches cut the lookup, never a new pipeline). +test "inkling2 kernels: an open record keeps a kernel's new launch after repeats of an old one" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + const path = "/tmp/inkling2-pipelines-repeat-proof.txt"; + _ = std.c.unlink(path); + defer _ = std.c.unlink(path); + const saved = kernels.pipes; + defer kernels.pipes = saved; + kernels.pipes = .{}; + _ = try kernels.pipelinesAtLoad(mlx.gpuStream(), path); + for (0..3) |_| try normLaunch(a, .bfloat16); + try testing.expectEqual(@as(usize, 1), kernels.pipes.n); + try normLaunch(a, .float32); + try testing.expectEqual(@as(usize, 2), kernels.pipes.n); +} + +// Bar: with PIPELINES_AT_LOAD off a launch looks nothing up; a load that adds a first launch leaves the record open at +// ready, the next load that adds none closes it there, and a load that replays the closed record keeps and appends +// nothing more. +test "inkling2 kernels: a launch does no pipeline-record work once the record is off or complete" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + const path = "/tmp/inkling2-pipelines-closed-proof.txt"; + _ = std.c.unlink(path); + defer _ = std.c.unlink(path); + const saved = kernels.pipes; + defer kernels.pipes = saved; + kernels.pipes = .{}; + try normLaunch(a, .bfloat16); + try testing.expectEqual(@as(usize, 0), kernels.pipes.n); + + _ = try kernels.pipelinesAtLoad(mlx.gpuStream(), path); + try testing.expect(kernels.pipes.watching); + try normLaunch(a, .bfloat16); + try testing.expectEqual(@as(usize, 1), kernels.pipes.n); + kernels.pipes.ready(); + var buf: [1 << 16]u8 = undefined; + try testing.expect(!std.mem.endsWith(u8, try recordText(&buf, path), kernels.Pipes.closed_mark ++ "\n")); + + // The next load replays the record and launches nothing new before ready: the record closes there. + kernels.pipes = .{}; + _ = try kernels.pipelinesAtLoad(mlx.gpuStream(), path); + try testing.expect(kernels.pipes.watching); + kernels.pipes.ready(); + const closed = try a.dupe(u8, try recordText(&buf, path)); + defer a.free(closed); + try testing.expect(std.mem.endsWith(u8, closed, kernels.Pipes.closed_mark ++ "\n")); + + // A load that replays the closed record: nothing after it is looked up or appended. + kernels.pipes = .{}; + const got = try kernels.pipelinesAtLoad(mlx.gpuStream(), path); + try testing.expect(got[1] >= 1); + try testing.expect(!kernels.pipes.watching); + const kept = kernels.pipes.n; + try normLaunch(a, .float16); + try testing.expectEqual(kept, kernels.pipes.n); + try testing.expectEqualStrings(closed, try recordText(&buf, path)); +} + +// Bar: a step's norm (one row, a verify's 8) launches main's kernel, `msv_inkling2_norm`, and only a prompt's rows on +// NAX launch the row kernel: what each launch adds to an open pipeline record names its kernel. +test "inkling2 kernels: a step's norm launches main's kernel, a prompt's rows the row kernel" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + fx_stream = mlx.gpuStream(); + const path = "/tmp/inkling2-pipelines-step-kernels.txt"; + _ = std.c.unlink(path); + defer _ = std.c.unlink(path); + const saved = kernels.pipes; + defer kernels.pipes = saved; + kernels.pipes = .{}; + _ = try kernels.pipelinesAtLoad(fx_stream, path); + var cfg: @import("config.zig").Config = undefined; + cfg.hidden_size = 2304; + cfg.rms_norm_eps = 1e-6; + var buf: [1 << 16]u8 = undefined; + for ([_]c_int{ 1, 8, 512 }) |rows| { + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + const y = try randomRow(&g, a, 8700 + @as(u64, @intCast(rows)), &.{ 1, rows, 2304 }, 1.0, .float32); + const nw = try randomRow(&g, a, 8701, &.{2304}, 1.0, .bfloat16); + const load: kernels.Load = if (rows == 512) .prompt else .step; + try ops.evalMany(&.{(try kernels.normAt(&g, load, &cfg, y, @splat(nw), 1, .bfloat16, null))[0]}); + const text = try recordText(&buf, path); + try testing.expect(std.mem.indexOf(u8, text, "msv_inkling2_norm\t") != null); + try testing.expectEqual(rows == 512, std.mem.indexOf(u8, text, "msv_inkling2_norm_row\t") != null); + } +} + +// Bar: the norm kernel writes main's norm.metal bytes at one row, a verify's 8, batched decode's 16 and a prompt's 512 +// (each load's grid, D / TG threadgroups a row, and at 512 a prompt's one threadgroup a row too), three streams and the +// MLP input with the router, f32 and bf16 outputs. +test "inkling2 kernels: the norm kernel writes main's norm bytes at every load" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + fx_stream = mlx.gpuStream(); + const d: c_int = 2304; + const experts: c_int = 128; + var cfg: @import("config.zig").Config = undefined; + cfg.hidden_size = @intCast(d); + cfg.num_experts = @intCast(experts); + cfg.rms_norm_eps = 1e-6; + var seed: u64 = 8300; + for ([_]c_int{ 1, 8, 16, 512 }) |rows| for ([_]bool{ false, true }) |routed| for ([_]ops.Dtype{ .float32, .bfloat16 }) |dt| { + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + seed += 10; + const n: c_int = if (routed) 1 else 3; + const y = try randomRow(&g, a, seed, &.{ n, rows, d }, 1.0, .float32); + var nw: [3]ops.Array = undefined; + for (&nw, 0..) |*w, i| w.* = try randomRow(&g, a, seed + 1 + i, &.{d}, 0.1, .bfloat16); + const rt = try randomRow(&g, a, seed + 5, &.{ experts, d }, 0.2, .float32); + const eps = try g.fromSlice(f32, &.{cfg.rms_norm_eps}, &.{1}); + const tg = kernels.streamGroup(@intCast(d)).?; + const extra: c_int = if (routed) @divTrunc(experts * 32 + tg - 1, tg) * tg else 0; + const want = try kernels.launchGrid(&g, &kernels.norm_kernel, &.{ y, nw[0], nw[1], nw[2], if (routed) rt else y, eps }, 2, .{ + .{ .shape = &.{ n, rows, d }, .dtype = dt }, + if (routed) .{ .shape = &.{ rows, experts }, .dtype = .float32 } else kernels.unused, + }, .{ d + extra, rows, 1 }, .{ tg, 1, 1 }, &.{ + .{ "T", .{ .dtype = dt } }, .{ "TG", .{ .int = tg } }, .{ "D", .{ .int = d } }, .{ "J", .{ .int = n } }, .{ "E", .{ .int = if (routed) experts else 0 } }, + }); + for ([_]kernels.Load{ .step, .prompt }) |load| { + if (load == .prompt and rows != 512) continue; + const got = try kernels.normAt(&g, load, &cfg, y, nw, n, dt, if (routed) rt else null); + try expectClose(got[0], want[0], 0, "norm against main's"); + if (routed) try expectClose(got[1], want[1], 0, "router scores against main's"); + } + }; +} + +// Bar: the prep kernel on contiguous projections (every one-row decode, and a verify or batched step) writes main's +// prep.metal bytes, every output, at 1 row (log-scaled and not), 8, 16 and 512 rows, a sliding and a global layer, f32 +// and bf16. +test "inkling2 kernels: the prep kernel writes main's prep bytes on contiguous projections" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + var s = try Stage.init(a); + defer s.deinit(); + const body = s.body; + const cfg = &body.cfg; + const kt: c_int = @intCast(cfg.sconv_kernel); + const width: c_int = @intCast(2 * cfg.kvDim() + 2 * cfg.hidden_size); + var seed: u64 = 8400; + for ([_]usize{ 0, 1 }) |li| for ([_]ops.Dtype{ .float32, .bfloat16 }) |dt| for ([_]c_int{ 1, 8, 16, 512 }) |rows| for ([_]f32{ 1.0, 1.25 }) |tau| { + if (rows > 1 and tau != 1.0) continue; + const L = &body.layers[li]; + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + seed += 100; + const proj = try randomProjected(&g, a, seed, L, cfg, rows, dt); + const st = try randomRow(&g, a, seed + 60, &.{ 1, kt - 1, width }, 1.0, .float32); + const dynamic = L.k_conv == .dynamic; + const kw = if (dynamic) L.k_conv.dynamic.static else L.k_conv.static; + const vw = if (dynamic) L.v_conv.dynamic.static else L.v_conv.static; + const dyn: [2]ops.Array = proj.dyn orelse .{ proj.proj[4], proj.proj[5] }; + const keys: c_int = if (rows == 1) 3 else 0; + const conv_scale: f32 = 1.0 / @sqrt(@as(f32, @floatFromInt(if (dynamic) 2 * kt + 1 else kt + 1))); + const pr = try g.fromSlice(f32, &.{ cfg.qk_clip, cfg.rel_clip, cfg.rms_norm_eps, tau, conv_scale, @floatFromInt(keys) }, &.{6}); + const ins = [_]ops.Array{ proj.proj[0], proj.proj[1], proj.proj[2], proj.proj[4], proj.proj[5], dyn[0], dyn[1], st, kw, vw, L.q_scale, L.rel_scale, L.rel_proj_rev, pr, try g.zeros(&.{1}, .int32) }; + const dims: kernels.PrepDims = .{ .heads = @intCast(cfg.num_attention_heads), .kv_heads = @intCast(cfg.num_key_value_heads), .hd = @intCast(cfg.head_dim), .d_rel = @intCast(cfg.d_rel), .kt = kt, .keys = keys, .dynamic = dynamic }; + const want = try kernels.prepLaunchOn(&g, &kernels.prep_kernel, &ins, dims); + const got = try kernels.prepLaunch(&g, &ins, dims, false); + for ([_]usize{ 0, 1, 2, 3 }) |i| try expectClose(got[i], want[i], 0, "prep against main's"); + try expectClose(got[if (rows == 1) 4 else 5], want[if (rows == 1) 4 else 5], 0, if (rows == 1) "bias against main's" else "relative states against main's"); + }; +} + +/// l2 and max distance of the rows `from .. to` of `got` (`[S, H, 128]` values) from `want` (those rows in float64). +fn rowDistances(got: []const f32, want: []const f64, from: usize, to: usize, heads: usize) [2]f64 { + return distances(got[from * heads * 128 .. to * heads * 128], want); +} + +fn joinDistances(x: [2]f64, y: [2]f64) [2]f64 { + return .{ @sqrt(x[0] * x[0] + y[0] * y[0]), @max(x[1], y[1]) }; +} + +// Bar: the tensor-unit read as served (its in-read bias) is no farther from the float64 read than main's relattn_nax +// read, in l2 and in max, at the release's shapes (24 heads over 8, R 1,024): sliding 1,024 and global, 100 and 128 +// rows behind 1,100 keys, and a global read of 128 rows at 16,384 keys (its first and last 16 rows against float64); a +// planted control (main's read on states one part in 64 off) is farther. +test "inkling2 kernels: the tensor-unit prompt read is no farther from float64 than main's relattn_nax" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + fx_stream = mlx.gpuStream(); + const H = 24; + const HKV = 8; + const R = 1024; + const scale = 1.0 / @sqrt(128.0); + const Case = struct { window: c_int, rows: c_int, keys: c_int }; + const cases = [_]Case{ + .{ .window = 1024, .rows = 128, .keys = 1024 + 128 - 1 }, .{ .window = 1024, .rows = 100, .keys = 1024 + 100 - 1 }, + .{ .window = 0, .rows = 128, .keys = 1100 + 128 }, .{ .window = 0, .rows = 100, .keys = 1100 + 100 }, + .{ .window = 0, .rows = 128, .keys = 16384 }, + }; + var seed: u64 = 19000; + for (cases) |c| { + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + seed += 10; + const rows = c.rows; + const keys = c.keys; + const q_rows = try randomRow(&g, a, seed, &.{ 1, rows, H, 128 }, 0.6, .bfloat16); + const q = try g.transpose(q_rows, &.{ 0, 2, 1, 3 }); + const st = try randomRow(&g, a, seed + 1, &.{ 1, rows, H, 16 }, 2.0, .bfloat16); + const proj = try randomRow(&g, a, seed + 5, &.{ 16, R }, 1.0, .bfloat16); + const sinks = try randomRow(&g, a, seed + 2, &.{ 1, rows, H }, 1.0, .float32); + const k = try randomRow(&g, a, seed + 3, &.{ 1, HKV, keys, 128 }, 0.6, .bfloat16); + const v = try randomRow(&g, a, seed + 4, &.{ 1, HKV, keys, 128 }, 1.0, .bfloat16); + const rproj = try g.contiguous(try g.transpose(proj, &.{ 1, 0 })); + const old = try kernels.naxRead(&g, q, k, v, try g.contiguous(st), rproj, sinks, c.window); + const off_st = try g.astype(try g.mul(try g.astype(st, .float32), try g.scalar(1.0 + 1.0 / 64.0, .float32)), .bfloat16); + const control = try kernels.naxRead(&g, q, k, v, try g.contiguous(off_st), rproj, sinks, c.window); + const relp = try g.contiguous(try g.concat(&.{ try g.zeros(&.{ 16, kernels.relp_before }, .bfloat16), proj, try g.zeros(&.{ 16, 64 }, .bfloat16) }, 1)); + const inread = (try kernels.relativeNaxStates(&g, H, HKV, q, k, v, st, relp, sinks, c.window, rows, keys, R, scale)) orelse return error.TestUnexpectedResult; + const hq = try hostValues(a, &g, q_rows); + defer a.free(hq); + const hk = try hostValues(a, &g, k); + defer a.free(hk); + const hv = try hostValues(a, &g, v); + defer a.free(hv); + const hs = try hostValues(a, &g, st); + defer a.free(hs); + const hp = try hostValues(a, &g, proj); + defer a.free(hp); + const hsk = try hostValues(a, &g, sinks); + defer a.free(hsk); + const n: usize = @intCast(rows); + // The long read's float64 rows are its first and last 16: the rest cost minutes on the CPU. + const spans: [2][2]usize = if (keys > 4096) .{ .{ 0, 16 }, .{ n - 16, n } } else .{ .{ 0, n }, .{ n, n } }; + var want: [2][]f64 = undefined; + for (&want, spans) |*w, sp| w.* = try readF64Rows(a, hq, hk, hv, hs, hp, hsk, n, H, HKV, @intCast(keys), R, @intCast(c.window), scale, sp[0], sp[1]); + defer for (want) |w| a.free(w); + var dist: [3][2]f64 = undefined; + for ([_]ops.Array{ old, inread, control }, 0..) |x, i| { + const hx = try hostValues(a, &g, x); + defer a.free(hx); + dist[i] = joinDistances(rowDistances(hx, want[0], spans[0][0], spans[0][1], H), rowDistances(hx, want[1], spans[1][0], spans[1][1], H)); + } + std.debug.print("[inkling2 kernels] prompt read, window {d}, {d} rows, {d} keys: l2 / max from float64: main {e:.4} / {e:.4}, in-read {e:.4} / {e:.4}, planted control {e:.4} / {e:.4}\n", .{ c.window, rows, keys, dist[0][0], dist[0][1], dist[1][0], dist[1][1], dist[2][0], dist[2][1] }); + try testing.expect(dist[1][0] <= dist[0][0] and dist[1][1] <= dist[0][1]); + try testing.expect(!(dist[2][0] <= dist[0][0] and dist[2][1] <= dist[0][1])); + } +} + +/// The float64 message gates: `(1 - tanh(F st)) a + tanh(G st) ms` over `n` gates of `rows` rows, `d` wide, `rank` deep. +fn gateF64(a: std.mem.Allocator, x: []const f32, ms: []const f32, st: []const f32, f: []const f32, gm: []const f32, n: usize, rows: usize, d: usize, rank: usize) ![]f64 { + const out = try a.alloc(f64, n * rows * d); + for (0..n) |j| for (0..rows) |r| for (0..d) |c| { + var fp: f64 = 0; + var gp: f64 = 0; + const s_row = st[(j * rows + r) * rank ..][0..rank]; + for (s_row, f[(j * d + c) * rank ..][0..rank], gm[(j * d + c) * rank ..][0..rank]) |sv, fv, gv| { + fp += @as(f64, sv) * @as(f64, fv); + gp += @as(f64, sv) * @as(f64, gv); + } + const at = (j * rows + r) * d + c; + out[at] = (1.0 - std.math.tanh(fp)) * @as(f64, x[at]) + std.math.tanh(gp) * @as(f64, ms[at]); + }; + return out; +} + +// Bar: on NAX (where the tiled gates run and the projected arm's matmuls are TF32), a prompt's gates on the matrix +// units are within 1e-5 of the float64 gates' peak and in the projected arm's precision class (a step's: two f32 matmuls and +// gate.metal): both arms within 1e-6 of the peak in max and 1e-6 x sqrt(n) x peak in l2, the tiled arm within 2x of the +// projected arm in each, at 96, 100 and 128 rows; a planted control (the tiled arm on a forget projection one part in +// 64 off) is outside the class. +test "inkling2 kernels: a prompt's message gates on the matrix units are in the projected arm's precision class" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + const a = testing.allocator; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + fx_stream = mlx.gpuStream(); + const d: c_int = 2304; + const rank: c_int = 64; + for ([_]c_int{ 96, 100, 128 }) |rows| { + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + const seed: u64 = 7800 + @as(u64, @intCast(rows)); + const x = try randomRow(&g, a, seed, &.{ 3, rows, d }, 1.0, .float32); + const ms = try randomRow(&g, a, seed + 1, &.{ 3, rows, d }, 1.0, .float32); + const st = try randomRow(&g, a, seed + 2, &.{ 3, rows, rank }, 1.0, .bfloat16); + const gates: layers.Gates = .{ .down = st, .forget = try randomRow(&g, a, seed + 3, &.{ 3, d, rank }, 0.2, .bfloat16), .message = try randomRow(&g, a, seed + 4, &.{ 3, d, rank }, 0.2, .bfloat16) }; + var off = gates; + off.forget = try g.astype(try g.mul(try g.astype(gates.forget, .float32), try g.scalar(1.0 + 1.0 / 64.0, .float32)), .bfloat16); + var arms: [3]ops.Array = undefined; + arms[0] = try kernels.gateAt(&g, .step, &gates, x, ms, st, 0, 3); + arms[1] = try kernels.gateAt(&g, .prompt, &gates, x, ms, st, 0, 3); + arms[2] = try kernels.gateAt(&g, .prompt, &off, x, ms, st, 0, 3); + var host: [5][]f32 = undefined; + for ([_]ops.Array{ x, ms, st, gates.forget, gates.message }, &host) |arr, *h| h.* = try hostValues(a, &g, arr); + defer for (host) |h| a.free(h); + const want = try gateF64(a, host[0], host[1], host[2], host[3], host[4], 3, @intCast(rows), @intCast(d), @intCast(rank)); + defer a.free(want); + var peak: f64 = 0; + for (want) |w| peak = @max(peak, @abs(w)); + var dist: [3][2]f64 = undefined; + for (arms, 0..) |arm, i| { + const hx = try hostValues(a, &g, arm); + defer a.free(hx); + dist[i] = distances(hx, want); + } + std.debug.print("[inkling2 kernels] prompt gates at {d} rows: l2 / max from float64 (peak {d:.3}): projected arm {e:.4} / {e:.4}, tiled arm {e:.4} / {e:.4}, planted control {e:.4} / {e:.4}\n", .{ rows, peak, dist[0][0], dist[0][1], dist[1][0], dist[1][1], dist[2][0], dist[2][1] }); + try testing.expect(dist[1][1] <= 1e-5 * peak); + // The arms round in a different order at the same precision: a relative bar between them flips on one element. + const n: f64 = @floatFromInt(want.len); + const class = struct { + fn f(dd: [2]f64, top: f64, count: f64) bool { + return dd[1] <= 1e-6 * top and dd[0] <= 1e-6 * @sqrt(count) * top; + } + }.f; + try testing.expect(class(dist[0], peak, n) and class(dist[1], peak, n)); + try testing.expect(dist[1][0] <= 2 * dist[0][0] and dist[1][1] <= 2 * dist[0][1]); + try testing.expect(!class(dist[2], peak, n)); + } +} + +const SdkKvCache = @import("../../sdk/kv/cache.zig").KVCache; +const KvQuant = @import("../../sdk/blocks/attention/kv_quant.zig").KVQuantConfig; + +/// A prompt chunk's view of one layer's cache under `config`: the keys before the chunk appended, then the chunk's +/// `rows`, the view the second append returns (a sliding layer's last `window + rows - 1` keys of it). +const ChunkView = struct { + cache: SdkKvCache, + dv: @import("../../sdk/blocks/attention/kv_view.zig").DenseKVView, + + fn init(a: std.mem.Allocator, g: *ops.Graph, config: KvQuant, k: ops.Array, v: ops.Array, rows: c_int) !ChunkView { + var cache = try SdkKvCache.initWithConfig(a, 1, config); + errdefer cache.deinit(); + const keys = ops.shape(k)[2]; + var first = try cache.update(0, try g.sliceAxis(k, 2, 0, keys - rows), try g.sliceAxis(v, 2, 0, keys - rows), g.s, 0); + first.deinit(); + const dv = try cache.update(0, try g.sliceAxis(k, 2, keys - rows, keys), try g.sliceAxis(v, 2, keys - rows, keys), g.s, 0); + return .{ .cache = cache, .dv = dv }; + } + + fn read(c: *const ChunkView, g: *ops.Graph, window: c_int, rows: c_int) ![2]ops.Array { + const keys = ops.shape(c.dv.k)[2]; + const from = if (window > 0) keys - (window + rows - 1) else 0; + return .{ try g.sliceAxis(c.dv.k, 2, from, keys), try g.sliceAxis(c.dv.v, 2, from, keys) }; + } + + fn deinit(c: *ChunkView) void { + c.dv.deinit(); + c.cache.deinit(); + } +}; + +// Bar: a prompt chunk's reads through the cache's views (`--kv-quant 8`'s dequantized view, and kv-off's strided view +// of the cache's buffer) at the release's shapes, sliding 1,024 and global, 100 and 128 rows behind 1,100 keys: on the +// kv-off view each read (main's relattn_nax, the tensor-unit read) writes the bytes it writes on contiguous K and V; on +// the 8-bit view the tensor-unit read is no farther from the float64 read of the view's values than main's read, in l2 +// and in max. +test "inkling2 kernels: a prompt's reads of an 8-bit cache's view are no farther from float64 than main's read" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + fx_stream = mlx.gpuStream(); + const H = 24; + const HKV = 8; + const R = 1024; + const scale = 1.0 / @sqrt(128.0); + var seed: u64 = 21000; + for ([_]c_int{ 1024, 0 }) |window| for ([_]c_int{ 128, 100 }) |rows| { + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + seed += 10; + const total: c_int = 1100 + rows; + const q_rows = try randomRow(&g, a, seed, &.{ 1, rows, H, 128 }, 0.6, .bfloat16); + const q = try g.transpose(q_rows, &.{ 0, 2, 1, 3 }); + const st = try randomRow(&g, a, seed + 1, &.{ 1, rows, H, 16 }, 2.0, .bfloat16); + const proj = try randomRow(&g, a, seed + 5, &.{ 16, R }, 1.0, .bfloat16); + const sinks = try randomRow(&g, a, seed + 2, &.{ 1, rows, H }, 1.0, .float32); + const k_all = try randomRow(&g, a, seed + 3, &.{ 1, HKV, total, 128 }, 0.6, .bfloat16); + const v_all = try randomRow(&g, a, seed + 4, &.{ 1, HKV, total, 128 }, 1.0, .bfloat16); + const rproj = try g.contiguous(try g.transpose(proj, &.{ 1, 0 })); + const relp = try g.contiguous(try g.concat(&.{ try g.zeros(&.{ 16, kernels.relp_before }, .bfloat16), proj, try g.zeros(&.{ 16, 64 }, .bfloat16) }, 1)); + const Reads = struct { + fn of(gr: *ops.Graph, qq: ops.Array, kv: [2]ops.Array, s_: ops.Array, rp: ops.Array, rl: ops.Array, sk: ops.Array, w: c_int, n: c_int) ![2]ops.Array { + const keys = ops.shape(kv[0])[2]; + return .{ + try kernels.naxRead(gr, qq, kv[0], kv[1], try gr.contiguous(s_), rp, sk, w), + (try kernels.relativeNaxStates(gr, H, HKV, qq, kv[0], kv[1], s_, rl, sk, w, n, keys, R, scale)) orelse return error.TestUnexpectedResult, + }; + } + }; + // kv-off: the cache's view of its buffer reads as contiguous K and V do, bit for bit. + var off = try ChunkView.init(a, &g, KvQuant.dense, k_all, v_all, rows); + defer off.deinit(); + const off_kv = try off.read(&g, window, rows); + const flat = [2]ops.Array{ try g.contiguous(off_kv[0]), try g.contiguous(off_kv[1]) }; + const on_view = try Reads.of(&g, q, off_kv, st, rproj, relp, sinks, window, rows); + const on_flat = try Reads.of(&g, q, flat, st, rproj, relp, sinks, window, rows); + for (on_view, on_flat) |x, y| try expectClose(try g.contiguous(x), try g.contiguous(y), 0, "a read of kv-off's view"); + // kv8: the dequantized view. + var q8 = try ChunkView.init(a, &g, KvQuant.affine(8), k_all, v_all, rows); + defer q8.deinit(); + const q8_kv = try q8.read(&g, window, rows); + const reads = try Reads.of(&g, q, q8_kv, st, rproj, relp, sinks, window, rows); + const hq = try hostValues(a, &g, q_rows); + defer a.free(hq); + const hk = try hostValues(a, &g, q8_kv[0]); + defer a.free(hk); + const hv = try hostValues(a, &g, q8_kv[1]); + defer a.free(hv); + const hs = try hostValues(a, &g, st); + defer a.free(hs); + const hp = try hostValues(a, &g, proj); + defer a.free(hp); + const hsk = try hostValues(a, &g, sinks); + defer a.free(hsk); + const keys = ops.shape(q8_kv[0])[2]; + const want = try readF64(a, hq, hk, hv, hs, hp, hsk, @intCast(rows), H, HKV, @intCast(keys), R, @intCast(window), scale); + defer a.free(want); + var dist: [2][2]f64 = undefined; + for (reads, 0..) |x, i| { + const hx = try hostValues(a, &g, x); + defer a.free(hx); + dist[i] = distances(hx, want); + } + std.debug.print("[inkling2 kernels] 8-bit KV view, window {d}, {d} rows: l2 / max from float64: main {e:.4} / {e:.4}, in-read {e:.4} / {e:.4}\n", .{ window, rows, dist[0][0], dist[0][1], dist[1][0], dist[1][1] }); + try testing.expect(dist[1][0] <= dist[0][0] and dist[1][1] <= dist[0][1]); + }; +} + +// Bar: on NAX, a prompt's read the tensor-unit read does not take (`kernels.test_main.relnax`) is main's relattn_nax +// read (`relativeNax`), bit for bit, and the tensor-unit read does not engage; as served it engages (control). The +// release's shapes: 24 heads over 8 at head dim 128, 16 relative dims, R 1,024, sliding 1,024 and global, 100 rows +// behind 1,100 keys. +test "inkling2 kernels: a prompt read the tensor-unit read does not take is main's relattn_nax, bit for bit" { + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + fx_stream = mlx.gpuStream(); + defer kernels.resetEngaged(.relnax); + const saved = kernels.test_main; + defer kernels.test_main = saved; + var cfg = std.mem.zeroes(@import("config.zig").Config); + cfg.num_attention_heads = 24; + cfg.num_key_value_heads = 8; + cfg.head_dim = 128; + cfg.d_rel = 16; + cfg.sliding_window = 1024; + cfg.log_n_floor = 1 << 20; + const rows: c_int = 100; + const offset: c_int = 1100; + var seed: u64 = 23000; + for ([_]bool{ false, true }) |global| { + var g = ops.Graph.init(a, fx_stream); + defer g.deinit(); + seed += 10; + var L: layers.Layer = undefined; + L.global = global; + L.rel_proj = try randomRow(&g, a, seed, &.{ 16, 1024 }, 1.0, .bfloat16); + L.rel_proj_t = .{}; + const keys = if (global) offset + rows else 1024 + rows - 1; + const q = try randomRow(&g, a, seed + 1, &.{ 1, rows, 24, 128 }, 0.6, .bfloat16); + const st = try randomRow(&g, a, seed + 2, &.{ 1, rows, 24, 16 }, 2.0, .bfloat16); + const sinks = try randomRow(&g, a, seed + 3, &.{ 1, rows, 24 }, 1.0, .float32); + const k = try randomRow(&g, a, seed + 4, &.{ 1, 8, keys, 128 }, 0.6, .bfloat16); + const v = try randomRow(&g, a, seed + 5, &.{ 1, 8, keys, 128 }, 1.0, .bfloat16); + const main_read = try g.contiguous((try kernels.relativeNax(&g, &L, &cfg, q, st, sinks, k, v, offset)) orelse return error.TestUnexpectedResult); + { + kernels.test_main.relnax = true; + defer kernels.test_main.relnax = false; + kernels.resetEngaged(.relnax); + const got = try g.contiguous(try kernels.relativeWith(&g, &L, &cfg, q, st, sinks, k, v, offset, false, null)); + try expectClose(got, main_read, 0, "a declined read against main's relattn_nax"); + try testing.expect(!kernels.wasEngaged(.relnax)); + } + kernels.resetEngaged(.relnax); + try ops.evalMany(&.{try kernels.relativeWith(&g, &L, &cfg, q, st, sinks, k, v, offset, false, null)}); + try testing.expect(kernels.wasEngaged(.relnax)); + } +} diff --git a/src/plugins/inkling2/repro_test.zig b/src/plugins/inkling2/repro_test.zig new file mode 100644 index 0000000000..3160c240e0 --- /dev/null +++ b/src/plugins/inkling2/repro_test.zig @@ -0,0 +1,288 @@ +//! A request's bytes are a function of the request and its server. Inkling 2 on its pack (`INKLING2_RELEASE`, any +//! Inkling 2 pack), served through the engine's chunk loop at the served width: a prompt of three 8192-row chunks and a +//! tail (two chunks past the packs' log-scaling floor, 8192) gives the same first-token logprobs, cache rows and conv +//! states when every buffer the allocator hands out starts as NaN or as a finite pattern (rule B: no kernel reads a +//! byte nobody wrote), and with its eval points async or synchronous. The tensor-unit read behind an earlier chunk's +//! keys repeats bit for bit (no race inside a kernel, which a fill cannot show). + +const std = @import("std"); +const mlx = @import("../../mlx/ffi.zig"); +const env = @import("../../env.zig"); +const model = @import("../../sdk/config/model.zig"); +const driver = @import("../../engines/mlx/plugin/driver.zig"); +const Transformer = @import("../../engines/mlx/transformer.zig").Transformer; +const Generator = @import("../../engines/mlx/generate/generator.zig").Generator; +const Tokenizer = @import("../../sdk/tokenizer/tokenizer.zig").Tokenizer; +const ops = @import("../../mlx/ops.zig"); +const kernels = @import("kernels.zig"); +const test_loads = @import("test_loads.zig"); +const fixture = @import("../../sdk/testing/fixture.zig"); +const SdkKvCache = @import("../../sdk/kv/cache.zig").KVCache; +const KvQuant = @import("../../sdk/blocks/attention/kv_quant.zig").KVQuantConfig; +const TokenLogprob = @import("../../sdk/request/logprob.zig").TokenLogprob; + +const testing = std.testing; +const TOP = 20; +/// The served prompt width. +const chunk = 8192; +const prompt_len = 3 * chunk + 17; +const max_visits = 128; +const max_parts = 16; + +/// A digest of one cached part: `name`'s bytes, its rows from `chunk_at` x `chunk` (null: the whole view). +const Part = struct { d: u64 = 0, name: []const u8 = "", chunk_at: ?usize = null }; + +/// One prefill's bytes: the first token's top logprobs and, per visit, a digest of each cached part (keys and values +/// a chunk at a time where the view holds every row, else whole; quantized triples; the conv state). +const Bytes = struct { + first: [TOP]TokenLogprob = undefined, + parts: [max_visits][max_parts]Part = undefined, + visits: usize = 0, +}; + + +fn promptIds(buf: []u32) void { + for (buf, 0..) |*t, i| t.* = @intCast((i * 7919 + 13) % 50000); +} + +/// XxHash3 of `x`'s dtype, shape and bytes, contiguous on the CPU. +fn digest(x: mlx.mlx_array) !u64 { + const s = mlx.mlx_default_cpu_stream_new(); + defer _ = mlx.mlx_stream_free(s); + var c = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(c); + try mlx.check(mlx.mlx_contiguous(&c, x, false, s)); + try mlx.check(mlx.mlx_array_eval(c)); + const n = mlx.mlx_array_size(c) * mlx.mlx_array_itemsize(c); + const p = mlx.mlx_array_data_uint8(c) orelse return error.NoData; + var h = std.hash.XxHash3.init(0); + h.update(std.mem.asBytes(&@backingInt(mlx.mlx_array_dtype(x)))); + h.update(std.mem.sliceAsBytes(mlx.getShape(x))); + h.update(p[0..n]); + return h.final(); +} + +/// Rows `[from, to)` of a `[B, H, T, D]` view. +fn rows(x: mlx.mlx_array, from: c_int, to: c_int, s: mlx.mlx_stream) !mlx.mlx_array { + const sh = mlx.getShape(x); + const start = [_]c_int{ 0, 0, from, 0 }; + const stop = [_]c_int{ sh[0], sh[1], to, sh[3] }; + const strides = [_]c_int{ 1, 1, 1, 1 }; + var out = mlx.mlx_array_new(); + try mlx.check(mlx.mlx_slice(&out, x, &start, 4, &stop, 4, &strides, 4, s)); + return out; +} + +fn add(b: *Bytes, v: usize, k: *usize, part: Part) !void { + if (k.* == max_parts) return error.TooManyParts; + b.parts[v][k.*] = part; + k.* += 1; +} + +/// The bytes the prefill of `step` rows left in `xfm`'s cache. +fn capture(xfm: *Transformer, b: *Bytes, step: usize) !void { + const cache = &xfm.cache; + b.visits = cache.entries.len; + if (b.visits > max_visits) return error.TooManyVisits; + const s = mlx.mlx_default_cpu_stream_new(); + defer _ = mlx.mlx_stream_free(s); + for (cache.entries, 0..) |*e, v| { + var k: usize = 0; + for (&b.parts[v]) |*p| p.* = .{}; + if (!e.initialized) continue; + const view = try cache.denseView(@intCast(v), xfm.s); + if (view.owned) { + _ = mlx.mlx_array_free(view.k); + _ = mlx.mlx_array_free(view.v); + } + for ([_]mlx.mlx_array{ e.key_view, e.value_view }, [_][]const u8{ "keys", "values" }) |x, nm| { + const t: usize = @intCast(mlx.getShape(x)[2]); + if (t != step) { + try add(b, v, &k, .{ .d = try digest(x), .name = nm }); + continue; + } + var from: usize = 0; + while (from < t) : (from += chunk) { + const r = try rows(x, @intCast(from), @intCast(@min(t, from + chunk)), s); + defer _ = mlx.mlx_array_free(r); + try add(b, v, &k, .{ .d = try digest(r), .name = nm, .chunk_at = from / chunk }); + } + } + for ([_]mlx.mlx_array{ e.key_scales_view, e.key_biases_view, e.value_scales_view, e.value_biases_view }) |x| + if (x.ctx != null) try add(b, v, &k, .{ .d = try digest(x), .name = "a quantized triple" }); + if (xfm.ssm_entries) |ents| if (v < ents.len and ents[v].conv_state.ctx != null) try add(b, v, &k, .{ .d = try digest(ents[v].conv_state), .name = "conv state" }); + } +} + +/// `prompt` cold through the scheduler's generator at the served width. +fn prefill(xfm: *Transformer, prompt: []const u32) !Bytes { + const a = testing.allocator; + try xfm.resetCache(); + _ = mlx.mlx_clear_cache(); + var tok: Tokenizer = undefined; + var b: Bytes = .{}; + { + var gen = try Generator.initWithOptions(testing.io, a, xfm, &tok, prompt, 1, .{ .temperature = 0.0 }, &.{}, .{ .pinned_prefill_chunk = chunk, .logprobs_n = TOP, .skip_lazy_preforward = true }); + defer gen.deinit(a); + try mlx.checkError(); + @memcpy(&b.first, gen.pending_logprob.?.top_logprobs[0..TOP]); + } + try capture(xfm, &b, xfm.cache.step); + return b; +} + +/// Where `got` first differs from `want` (null: byte-equal). +fn firstDiff(want: *const Bytes, got: *const Bytes) ?struct { visit: usize, part: usize } { + if (!std.mem.eql(u8, std.mem.asBytes(&want.first), std.mem.asBytes(&got.first))) return .{ .visit = max_visits, .part = 0 }; + for (0..want.visits) |v| for (want.parts[v], got.parts[v], 0..) |x, y, k| if (x.d != y.d) return .{ .visit = v, .part = k }; + return null; +} + +/// Says where `got` (`what`) first departs from `want`; true when it does. +fn report(what: []const u8, want: *const Bytes, got: *const Bytes) bool { + const d = firstDiff(want, got) orelse return false; + if (d.visit == max_visits) { + std.debug.print("[inkling2 repro] {s}: the first token's logprobs differ, every cached byte equal\n", .{what}); + return true; + } + const p = want.parts[d.visit][d.part]; + if (p.chunk_at) |c| { + std.debug.print("[inkling2 repro] {s}: visit {d} of {d} first differs, its {s} in chunk {d} (rows {d}..)\n", .{ what, d.visit, want.visits, p.name, c, c * chunk }); + } else std.debug.print("[inkling2 repro] {s}: visit {d} of {d} first differs, its {s} (a sliding ring: the whole view)\n", .{ what, d.visit, want.visits, p.name }); + return true; +} + +/// The pack served through the engine, on the C allocator: held for every test that asks (`test_loads.hold`). +const Pack = struct { + cfg: model.ModelConfig, + xfm: Transformer, + + pub fn close(p: *Pack) void { + p.xfm.deinit(); + p.cfg.deinit(std.heap.c_allocator); + } +}; + +/// The pack, loaded with no pipeline record (a test writes nothing under the home folder). +fn loadPack() !*Pack { + const dir = std.mem.span(env.get(.INKLING2_RELEASE) orelse return error.SkipZigTest); + const ov = env.override(.MLX_SERVE_INKLING2_PIPELINES_AT_LOAD, "0"); + defer ov.restore(); + const Opener = struct { + dir: []const u8, + pub fn open(o: @This(), p: *Pack, _: std.mem.Allocator) !void { + const gpa = std.heap.c_allocator; + p.cfg = try model.parseConfig(testing.io, gpa, o.dir); + errdefer p.cfg.deinit(gpa); + p.xfm = try driver.load(testing.io, gpa, &p.cfg, o.dir, mlx.gpuStream()); + } + }; + return test_loads.hold(Pack, &.{dir}, Opener{ .dir = dir }); +} + +// Bar: the prompt's eval points as async evals (as served) give the bytes main's synchronous ones give +// (`kernels.test_main.prefill_async`). +test "inkling2 pack: a prompt's async eval points leave the bytes synchronous ones leave (INKLING2_RELEASE)" { + if (comptime @import("builtin").os.tag != .macos) return error.SkipZigTest; + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + const a = testing.allocator; + const xfm = &(try loadPack()).xfm; + const prompt = try a.alloc(u32, prompt_len); + defer a.free(prompt); + promptIds(prompt); + + const on = try prefill(xfm, prompt); + const off = blk: { + const saved = kernels.test_main; + defer kernels.test_main = saved; + kernels.test_main.prefill_async = true; + break :blk try prefill(xfm, prompt); + }; + try testing.expect(!report("synchronous eval points against async", &on, &off)); +} + +fn random(g: *ops.Graph, seed: u64, shape: []const c_int, scale: f32, dt: ops.Dtype) !ops.Array { + var n: usize = 1; + for (shape) |d| n *= @intCast(d); + const data = try fixture.randomF32(testing.allocator, seed, n, scale); + defer testing.allocator.free(data); + return g.astype(try g.fromSlice(f32, data, shape), dt); +} + +/// The tensor-unit read (`relativeNaxStates`) of a served second chunk: `n_rows` rows behind `earlier` keys an earlier +/// chunk appended to a kv-off cache, read through the cache's view as `layers.appendKv` hands it. Evaluated, owned by `g`. +fn secondChunkOutput(g: *ops.Graph, window: c_int, n_rows: c_int, earlier: c_int, seed: u64) !ops.Array { + const H = 24; + const HKV = 8; + const R = 1024; + const keys = earlier + n_rows; + const q = try g.transpose(try random(g, seed, &.{ 1, n_rows, H, 128 }, 0.6, .bfloat16), &.{ 0, 2, 1, 3 }); + const st = try random(g, seed + 1, &.{ 1, n_rows, H, 16 }, 2.0, .bfloat16); + const sinks = try g.contiguous(try random(g, seed + 2, &.{ 1, n_rows, H }, 1.0, .float32)); + const k_all = try random(g, seed + 3, &.{ 1, HKV, keys, 128 }, 0.6, .bfloat16); + const v_all = try random(g, seed + 4, &.{ 1, HKV, keys, 128 }, 1.0, .bfloat16); + const proj = try random(g, seed + 5, &.{ 16, R }, 1.0, .bfloat16); + const relp = try g.contiguous(try g.concat(&.{ try g.zeros(&.{ 16, kernels.relp_before }, .bfloat16), proj, try g.zeros(&.{ 16, 64 }, .bfloat16) }, 1)); + var cache = try SdkKvCache.initWithConfig(testing.allocator, 1, KvQuant.dense); + defer cache.deinit(); + cache.reserve(@intCast(keys + 4096)); + var first = try cache.update(0, try g.sliceAxis(k_all, 2, 0, earlier), try g.sliceAxis(v_all, 2, 0, earlier), g.s, 0); + first.deinit(); + var dv = try cache.update(0, try g.sliceAxis(k_all, 2, earlier, keys), try g.sliceAxis(v_all, 2, earlier, keys), g.s, 0); + defer dv.deinit(); + const from = if (window > 0) keys - (window + n_rows - 1) else 0; + const k = try g.sliceAxis(dv.k, 2, from, keys); + const v = try g.sliceAxis(dv.v, 2, from, keys); + const ins = [_]ops.Array{ q, st, sinks, relp, k, v }; + for (ins) |x| try mlx.check(mlx.mlx_array_eval(x)); + const o = (try kernels.relativeNaxStates(g, H, HKV, q, k, v, st, relp, sinks, window, n_rows, ops.shape(k)[2], R, 1.0 / @sqrt(128.0))) orelse return error.TestUnexpectedResult; + try mlx.check(mlx.mlx_array_eval(o)); + return o; +} + +/// `x`'s bytes, contiguous on the CPU, owned by the caller. +fn hostBytes(a: std.mem.Allocator, x: mlx.mlx_array) ![]u8 { + const s = mlx.mlx_default_cpu_stream_new(); + defer _ = mlx.mlx_stream_free(s); + var c = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(c); + try mlx.check(mlx.mlx_contiguous(&c, x, false, s)); + try mlx.check(mlx.mlx_array_eval(c)); + const p = mlx.mlx_array_data_uint8(c) orelse return error.NoData; + return a.dupe(u8, p[0 .. mlx.mlx_array_size(c) * mlx.mlx_array_itemsize(c)]); +} + +// Bar: the tensor-unit read behind an earlier chunk's keys writes the same bytes each time it runs on the same inputs, +// 24 times a case: sliding 1,024 and global, its rows ragged or whole against 64-row tiles and its keys ragged or whole +// against 32-key blocks. +test "inkling2 kernels: the tensor-unit prompt read behind an earlier chunk's keys repeats bit for bit" { + if (comptime @import("builtin").os.tag != .macos) return error.SkipZigTest; + if (mlx.noGpuBackend() or mlx.virtualGpu() or !mlx.metalKernelsAvailable()) return error.SkipZigTest; + if (!@import("../../sdk/blocks/linear/verify_qmm_nax.zig").verifyQmmNaxAvailable()) return error.SkipZigTest; + const a = testing.allocator; + const reps = 24; + // Rows behind 4096 keys (a sliding view has window + rows - 1 keys): ragged rows with whole key blocks (4065, 4033, + // 4097), ragged rows and keys (4064), whole rows with ragged keys (4096), and the second 8K chunk (8161 behind 8192). + const cases = [_][3]c_int{ .{ 1024, 4065, 4096 }, .{ 1024, 4033, 4096 }, .{ 1024, 4097, 4096 }, .{ 1024, 4064, 4096 }, .{ 1024, 4096, 4096 }, .{ 1024, 8161, 8192 }, .{ 0, 4065, 4096 }, .{ 0, 8161, 8192 } }; + var failed = false; + for (cases, 0..) |c, ci| { + const seed: u64 = 61000 + 10 * ci; + var g0 = ops.Graph.init(a, mlx.gpuStream()); + const want = try hostBytes(a, try secondChunkOutput(&g0, c[0], c[1], c[2], seed)); + g0.deinit(); + defer a.free(want); + var moved: usize = 0; + for (1..reps) |_| { + var g = ops.Graph.init(a, mlx.gpuStream()); + defer g.deinit(); + const got = try hostBytes(a, try secondChunkOutput(&g, c[0], c[1], c[2], seed)); + defer a.free(got); + if (!std.mem.eql(u8, want, got)) moved += 1; + } + if (moved > 0) { + failed = true; + std.debug.print("[inkling2 repro] relnax window {d}, {d} rows behind {d} keys: {d} of {d} repeats moved\n", .{ c[0], c[1], c[2], moved, reps - 1 }); + } + } + try testing.expect(!failed); +} diff --git a/src/plugins/inkling2/rounds_contract.zig b/src/plugins/inkling2/rounds_contract.zig new file mode 100644 index 0000000000..06e2fca167 --- /dev/null +++ b/src/plugins/inkling2/rounds_contract.zig @@ -0,0 +1,2507 @@ +//! Inkling 2's speculative-round kernels in the kernel contract (`contract.zig` registers them): the DFlash2 draft's +//! grouped dynamic convolution (`dflash_conv`), its selector's sharded top 16 (`dflash_top16_shard`, `_merge`), edge +//! lattice (`dflash_edges`) and tree builder (`dflash_tree`); the verify's sampling (`sample_tree_mass`, `_search`, +//! `_draw`) and its tree walk (`accept_tree`). +//! Indices, tokens and copied values are exact; probabilities and masses carry their f32 and fast-math forward error +//! (`host.Val` style, in `mag`). A kernel whose choices compare computed values (a draw against its uniform, a cut +//! against a mass, a heap of path scores) is given inputs whose every such choice clears the device's error by `TOL`: +//! `prepare` picks the laws, seeds or lattice until it does, so the float64 reference's choice is the device's. +//! Each kernel has one planted control (a wrong tie, an off-by-one, a dropped tap, shard or rank) that gate 3 must +//! catch. Each records its own launch's width as `m1`/`m2`, the least its pipeline must take. + +const std = @import("std"); +const mlx = @import("../../mlx/ffi.zig"); +const ops = @import("../../mlx/ops.zig"); +const kc = @import("../../sdk/testing/kernel_contract/root.zig"); +const source = @import("../../mlx/kernels.zig").source; +const project = @import("../../sdk/bases/blocks/head.zig").project; +const kernels = @import("kernels.zig"); +const dflash2 = @import("dflash2.zig"); + +const spec = kc.spec; +const metal = kc.metal; +const host = kc.host; +const Shape = spec.Shape; +const U = host.U; +const inf = std.math.inf(f64); +const nan = std.math.nan(f64); + +// ── Inkling 2 Mini's sizes ── + +/// The head's real rows (the logits' vocab) and its padded rows (a DFlash2 draft's logits stride). +const VOCAB = 200058; +const HEAD_ROWS = 201024; +/// The selector's candidates a row and the sharded top-k's shards (`dflash2.topCandidates`, `sampleAndAcceptTree`). +const KTOP = 16; +const SHARDS = 16; +/// The DFlash2 selector's rank, the stream width, the draft's block, its conv taps and group. +const RANK = 256; +const HIDDEN = 2304; +const BLOCK = 8; +const CONV_KT = 2; +const CONV_GS = 16; +const SOFTCAP: f64 = 30; +/// The open window's width (keys, values, the output projection and the stream). +const SW = 2 * 1024 + 2 * HIDDEN; +/// A tree lane's copy chain, the stop ids a round carries, the children a node draws (`plugin.stepGroup`'s 4). +const MAX_COPY = dflash2.Drafter.max_copy; +const MAX_STOPS = 16; +const MAX_CH = 4; +/// The codebook rows an edge test binds (the kernel reads only the rows its tokens name). +const TABLE = 1024; +/// The spikes a lane's logits carry above their bulk. +const SPIKES = 24; +/// The least relative gap a computed choice must clear: far past the f32 and fast-math error of every compared value. +const TOL = 0x1p-12; +/// f32 unit roundoff of a precise tanh / exp (a few ulps). +const PRECISE = 4 * 0x1p-24; + +/// A lane's tree rows below its root: the block's rows after the anchor, at most the width less one. +fn rowsOf(w: usize) usize { + return @min(BLOCK - 1, @max(1, w - 1)); +} + +fn vocabOf(shape: Shape) usize { + return @min(shape.k, VOCAB); +} + +fn cint(x: usize) c_int { + return @intCast(x); +} + +fn f32of(v: f64) f64 { + return spec.roundTo(.f32, v); +} + +fn bfOf(v: f64) f64 { + return spec.roundTo(.bf16, v); +} + +/// The f32 whose bits are `id` (`as_type(int)`), as float64: exact, a subnormal for every id here. +fn idBits(id: u32) f64 { + return @as(f32, @bitCast(id)); +} + +fn bitsAt(bytes: []const u8, i: usize) u32 { + return std.mem.readInt(u32, bytes[4 * i ..][0..4], .little); +} + +fn tokU(x: f64) u32 { + return @intFromFloat(x); +} + +/// Metal's fast `log(x)` absolute error: 2^-21 on [0.5, 2], 3 ulps past it. +fn fastLogErr(x: f64) f64 { + return 0x1p-21 + 3 * 0x1p-23 * @abs(@log(x)); +} + +fn none(_: Shape) usize { + return 0; +} + +/// Sums in an accumulator (gate 4) or float64. +const Sim = ?struct { acc: spec.Accum, order: spec.Order }; + +fn inAcc(acc: spec.Accum, v: f64) f64 { + return switch (acc) { + .f32 => spec.roundTo(.f32, v), + .f16 => spec.roundTo(.f16, v), + .bf16 => spec.roundTo(.bf16, v), + .none => v, + }; +} + +fn total(sim: Sim, t: []const f64) f64 { + return if (sim) |x| spec.sumIn(x.acc, x.order, t) else host.sum(t); +} + +/// A running sum's next value (the kernels' cumulative walks run in one chain). +fn step(sim: Sim, s: f64, t: f64) f64 { + return if (sim) |x| inAcc(x.acc, s + inAcc(x.acc, t)) else s + t; +} + +/// `a` and `b` differ by more than the device's error on either: a choice between them is the device's too. +fn clear(a: f64, b: f64) bool { + return @abs(a - b) > TOL * @max(@abs(a), @abs(b)) + 0x1p-40; +} + +/// `got` is `want` within `e` and its f32 rounding (classes exact). +fn close(got: f64, want: f64, e: f64) bool { + if (std.math.isNan(want)) return std.math.isNan(got); + if (got == want) return true; + if (!std.math.isFinite(want) or !std.math.isFinite(got)) return false; + // A GPU that flushes f32 subnormals (M1-M4) reads a value under the normal range as zero. + if (got == 0 and @abs(want) < 4 * std.math.floatMin(f32)) return true; + return @abs(got - want) <= e + U * (@abs(want) + e) + 0x1p-149; +} + +fn mix64(v0: u64) u64 { + var v = v0; + v = (v ^ (v >> 30)) *% 0xbf58476d1ce4e5b9; + v = (v ^ (v >> 27)) *% 0x94d049bb133111eb; + return v ^ (v >> 31); +} + +/// sample_tree_draw's uniform for `row` and `tag`: exact (an integer hash, 23 bits and a half). +fn uniform01(seed: u64, row: usize, tag: u32) f64 { + const t: u32 = @as(u32, @intCast(row)) *% 8 +% tag +% 1; + const h = mix64(seed ^ (0x9e3779b97f4a7c15 *% @as(u64, t))); + return (@as(f64, @floatFromInt(h >> 41)) + 0.5) * 0x1p-23; +} + +fn fail(note: []u8, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.bufPrint(note, fmt, args) catch "an output breaks the rule"; +} + +// ── launches (names, inputs and sources the shipped wrappers' `kernels.Kernel`s carry) ── + +const accept_launch = metal.Launch{ .name = "msv_inkling2_accept_tree", .inputs = &.{ "TOKENS", "PARENT", "SELECTED", "ACCEPT_CAP", "STOPS", "N_STOPS" }, .outputs = &.{"RESULT"}, .source = source("plugins/inkling2/kernels/accept_tree.metal"), .tg_bytes = 0, .m1 = 1, .m2 = 1 }; +// tg_mx, tg_id, tg_sum, tg_adm: eight each. +const mass_launch = metal.Launch{ .name = "msv_inkling2_sample_mass", .inputs = &.{ "LOGITS", "SUPPRESS", "LPARAMS" }, .outputs = &.{"PMASS"}, .source = source("plugins/inkling2/kernels/sample_tree_mass.metal"), .tg_bytes = 4 * 4 * 8, .m1 = 256, .m2 = 256 }; +// The merge's four, ps[8], the 512 bins' counts and masses, the cut's five, the boundary bin's 512 values and ids, +// its count, sg_above[8]. +const search_launch = metal.Launch{ .name = "msv_inkling2_sample_search", .inputs = &.{ "LOGITS", "SUPPRESS", "LPARAMS", "PMASS" }, .outputs = &.{"VROW"}, .source = source("plugins/inkling2/kernels/sample_tree_search.metal"), .tg_bytes = 4 * (4 + 8 + 2 * 512 + 5 + 2 * 512 + 1 + 8), .m1 = 256, .m2 = 256 }; +// sh_done, sh_target_mass, sh_has_cands, sh_cands[K], sg_sums[8], tg_last[256], chosen. +const draw_launch = metal.Launch{ .name = "msv_inkling2_sample_draw", .inputs = &.{ "LOGITS", "SUPPRESS", "LPARAMS", "VROW", "SEEDS", "TMETA", "CANDS", "NEXT_Q", "DRAWS" }, .outputs = &.{"SELECTED"}, .source = source("plugins/inkling2/kernels/sample_tree_draw.metal"), .tg_bytes = 4 * (3 + KTOP + 8 + 256 + 1), .m1 = 256, .m2 = 256 }; +const conv_launch = metal.Launch{ .name = "msv_inkling2_dflash_conv", .inputs = &.{ "X", "DYN", "BASE", "RES" }, .outputs = &.{"OUT"}, .source = source("plugins/inkling2/kernels/dflash_conv.metal"), .tg_bytes = 0, .m1 = 64, .m2 = 64 }; +// sg_v, sg_i, sg_t: eight each, and win_tid. +const shard_launch = metal.Launch{ .name = "msv_inkling2_dflash_top16_shard", .inputs = &.{"LOGITS"}, .outputs = &.{ "PIDS", "PVALS" }, .source = source("plugins/inkling2/kernels/dflash_top16_shard.metal"), .tg_bytes = 4 * (3 * 8 + 1), .m1 = 256, .m2 = 256 }; +const merge_launch = metal.Launch{ .name = "msv_inkling2_dflash_top16_merge", .inputs = &.{ "PIDS", "PVALS" }, .outputs = &.{ "IDS", "VALS" }, .source = source("plugins/inkling2/kernels/dflash_top16_merge.metal"), .tg_bytes = 0, .m1 = 32, .m2 = 32 }; +const edges_launch = metal.Launch{ .name = "msv_inkling2_dflash_edges", .inputs = &.{ "T1", "CANDS", "UNARY", "PROJ", "PRED", "SUCC", "CAP" }, .outputs = &.{"PROBS"}, .source = source("plugins/inkling2/kernels/dflash_edges.metal"), .tg_bytes = 0, .m1 = 32, .m2 = 32 }; +const tree_launch = metal.Launch{ .name = "msv_inkling2_dflash_tree", .inputs = &.{ "T1", "CANDS", "PROBS", "CALIB", "TEMPS", "SEEDS", "COPY_IDS", "COPY_LEN", "COPY_RATE", "STOPS", "PARAMS" }, .outputs = &.{ "TOKENS", "PARENT", "TMETA", "NEXT_Q", "DRAWS", "SCORES" }, .source = source("plugins/inkling2/kernels/dflash_tree.metal"), .tg_bytes = 0, .m1 = 1, .m2 = 1 }; + +// Each dispatch as its wrapper builds it (`kernels.sampleAndAcceptTree`, `dflash2.Drafter`'s +// `prepare`, `finishAdd`, `topCandidates`, `buildTreeFromLogits`), template args in the wrapper's order. + +fn acceptGeometry(b: usize, w: usize) metal.Geometry { + var g = metal.Geometry{ .grid = .{ cint(b), 1, 1 }, .tg = .{ 1, 1, 1 } }; + g.out(&.{ cint(b), cint(2 + 2 * w) }, .int32); + g.int("W", w); + return g; +} + +fn massGeometry(rows: usize, w: usize, v: usize, stride: usize, masked: bool) metal.Geometry { + var g = metal.Geometry{ .grid = .{ SHARDS * 256, cint(rows), 1 }, .tg = .{ 256, 1, 1 } }; + g.out(&.{ cint(rows), SHARDS, 4 }, .float32); + g.dtype("T", .bfloat16); + g.int("V", v); + g.int("STRIDE", stride); + g.int("SHARDS", SHARDS); + g.int("W", w); + g.int("MASK", @intFromBool(masked)); + return g; +} + +fn searchGeometry(rows: usize, w: usize, v: usize, stride: usize, masked: bool) metal.Geometry { + var g = metal.Geometry{ .grid = .{ 256, cint(rows), 1 }, .tg = .{ 256, 1, 1 } }; + g.out(&.{ cint(rows), 4 }, .float32); + g.dtype("T", .bfloat16); + g.int("V", v); + g.int("STRIDE", stride); + g.int("SHARDS", SHARDS); + g.int("W", w); + g.int("MASK", @intFromBool(masked)); + return g; +} + +fn drawGeometry(rows: usize, w: usize, v: usize, stride: usize, masked: bool, r: usize) metal.Geometry { + var g = metal.Geometry{ .grid = .{ 256, cint(rows), 1 }, .tg = .{ 256, 1, 1 } }; + g.out(&.{cint(rows)}, .int32); + g.dtype("T", .bfloat16); + g.int("V", v); + g.int("STRIDE", stride); + g.int("W", w); + g.int("MASK", @intFromBool(masked)); + g.int("TREE", 1); + g.int("R", r); + g.int("K", KTOP); + return g; +} + +fn convGeometry(b: usize, l: usize, stage: usize, kt: usize) metal.Geometry { + const total_n = b * l * HIDDEN; + var g = metal.Geometry{ .grid = .{ cint((total_n + 63) / 64 * 64), 1, 1 }, .tg = .{ 64, 1, 1 } }; + g.out(&.{ cint(b), cint(l), HIDDEN }, .bfloat16); + g.dtype("T", .bfloat16); + g.dtype("BT", .bfloat16); + g.int("H", HIDDEN); + g.int("GS", CONV_GS); + g.int("KT", kt); + g.int("STAGE", stage); + return g; +} + +fn shardGeometry(rt: usize, stride: usize, v: usize) metal.Geometry { + var g = metal.Geometry{ .grid = .{ SHARDS * 256, cint(rt), 1 }, .tg = .{ 256, 1, 1 } }; + g.out(&.{ cint(rt), SHARDS, KTOP }, .int32); + g.out(&.{ cint(rt), SHARDS, KTOP }, .float32); + g.dtype("T", .bfloat16); + g.int("V", v); + g.int("STRIDE", stride); + g.int("SHARDS", SHARDS); + g.int("K", KTOP); + return g; +} + +fn mergeGeometry(rt: usize, shards: usize) metal.Geometry { + var g = metal.Geometry{ .grid = .{ 32, cint(rt), 1 }, .tg = .{ 32, 1, 1 } }; + g.out(&.{ cint(rt), KTOP }, .int32); + g.out(&.{ cint(rt), KTOP }, .float32); + g.int("SHARDS", shards); + g.int("K", KTOP); + return g; +} + +fn edgesGeometry(b: usize, r: usize, rank: usize) metal.Geometry { + var g = metal.Geometry{ .grid = .{ KTOP * 32, cint(r), cint(b) }, .tg = .{ 32, 1, 1 } }; + g.out(&.{ cint(b), cint(r), KTOP, KTOP }, .float32); + g.dtype("PT", .bfloat16); + g.dtype("CT", .bfloat16); + g.int("R", r); + g.int("K", KTOP); + g.int("RANK", rank); + return g; +} + +fn treeGeometry(b: usize, w: usize, r: usize) metal.Geometry { + var g = metal.Geometry{ .grid = .{ cint(b), 1, 1 }, .tg = .{ 1, 1, 1 } }; + g.out(&.{ cint(b), cint(w) }, .int32); + g.out(&.{ cint(b), cint(w) }, .int32); + g.out(&.{ cint(b * w), 2 }, .int32); + g.out(&.{ cint(b), cint(w), KTOP }, .float32); + g.out(&.{ cint(b), cint(w), 4 }, .uint8); + g.out(&.{ cint(b), cint(w) }, .float32); + g.int("W", w); + g.int("R", r); + g.int("K", KTOP); + g.int("MAX_COPY", MAX_COPY); + return g; +} + +// ── accept_tree ── + +/// A verify's tree walk: rows = lanes, n = rows a lane (the tree's width). Small token alphabets, so siblings share +/// tokens and selections match children often; lane 0's root has two children carrying its selection (the walk takes +/// the lower row; the planted control the higher). +const AcceptTree = struct { + rig: metal.Rig, + launch: *const metal.Launch = &accept_launch, + arena: std.heap.ArenaAllocator, + planted: bool = false, + shape: Shape = undefined, + tokens: []f64 = &.{}, + parent: []f64 = &.{}, + selected: []f64 = &.{}, + caps: []f64 = &.{}, + stops: [MAX_STOPS]f64 = @splat(-1), + n_stops: usize = 0, + note: [200]u8 = undefined, + args: [6]mlx.mlx_array = undefined, + + const Self = @This(); + + fn init(a: std.mem.Allocator, planted: bool) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a), .planted = planted }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(_: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.n < 3 or shape.n > 16) return null; + return acceptGeometry(shape.rows, shape.n); + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const b = shape.rows; + const w = shape.n; + self.tokens = try a.alloc(f64, b * w); + self.parent = try a.alloc(f64, b * w); + self.selected = try a.alloc(f64, b * w); + self.caps = try a.alloc(f64, b); + for (0..b) |l| { + const base = l * w; + self.tokens[base] = @floatFromInt(1000 + rng.uintLessThan(u32, 50)); + self.parent[base] = -1; + for (1..w) |r| { + self.parent[base + r] = @floatFromInt(rng.uintLessThan(usize, r)); + self.tokens[base + r] = @floatFromInt(100 + rng.uintLessThan(u32, 6)); + } + for (0..w) |r| self.selected[base + r] = @floatFromInt(100 + rng.uintLessThan(u32, 7)); + self.caps[l] = @floatFromInt(if (rng.uintLessThan(u32, 4) == 0) 15 else rng.uintLessThan(usize, w)); + } + // 105 is an alphabet token; 999 no row carries. + self.stops = @splat(-1); + self.stops[0] = 105; + self.stops[1] = 999; + self.n_stops = 2; + self.selected[0] = 102; + for (1..3) |r| { + self.tokens[r] = 102; + self.parent[r] = 0; + } + self.caps[0] = @max(self.caps[0], 2); + // Gate 1: integers carry no NaN; it plants stop ids in the selections, which end a walk before its child. + if (fill == .nonfinite) for (0..b) |l| { + if (l % 2 == 1) self.selected[l * w] = 105; + self.selected[l * w + w - 1] = 105; + }; + self.rig.reset(); + self.args = .{ + try self.rig.input(.int32, &.{ cint(b), cint(w) }, self.tokens), + try self.rig.input(.int32, &.{ cint(b), cint(w) }, self.parent), + try self.rig.input(.int32, &.{cint(b * w)}, self.selected), + try self.rig.input(.uint32, &.{cint(b)}, self.caps), + try self.rig.input(.int32, &.{MAX_STOPS}, &self.stops), + try self.rig.input(.uint32, &.{1}, &.{@as(f64, @floatFromInt(self.n_stops))}), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return self.shape.rows * (2 + 2 * self.shape.n); + } + + fn isStop(self: *const Self, tok: f64) bool { + for (self.stops[0..self.n_stops]) |s| if (s == tok) return true; + return false; + } + + /// Lane `l`'s walk: { accepted, next token, path rows [W], emitted tokens [W] }. + fn walk(self: *const Self, l: usize, out: []f64) void { + const w = self.shape.n; + const base = l * w; + const cap = @min(tokU(self.caps[l]), w - 1); + @memset(out, 0); + const path = out[2..][0..w]; + const emitted = out[2 + w ..][0..w]; + emitted[0] = self.tokens[base]; + var cur: usize = 0; + var accepted: usize = 0; + var next = self.selected[base]; + while (true) { + const tok = self.selected[base + cur]; + next = tok; + if (accepted >= cap or self.isStop(tok)) break; + var matched: usize = 0; + for (cur + 1..w) |child| { + if (self.parent[base + child] == @as(f64, @floatFromInt(cur)) and self.tokens[base + child] == tok) { + matched = child; + if (!self.planted) break; + } + } + if (matched == 0) break; + accepted += 1; + path[accepted] = @floatFromInt(matched); + emitted[accepted] = tok; + cur = matched; + } + out[0] = @floatFromInt(accepted); + out[1] = next; + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + const stride = 2 + 2 * self.shape.n; + for (0..self.shape.rows) |l| self.walk(l, want[l * stride ..][0..stride]); + @memset(mag, 0); + } + + /// The walk is integers: every output equals the reference's. + pub fn check(self: *Self, _: spec.Gate) !?[]const u8 { + const want = try self.arena.allocator().alloc(f64, 2 * self.count()); + try self.reference(want[0..self.count()], want[self.count()..]); + const bytes = self.rig.outputBytes(); + const stride = 2 + 2 * self.shape.n; + for (want[0..self.count()], 0..) |w, i| { + const got: f64 = @floatFromInt(@as(i32, @bitCast(bitsAt(bytes, i)))); + if (got != w) return fail(&self.note, "lane {d} slot {d}: {d} where the walk gives {d}", .{ i / stride, i % stride, got, w }); + } + return null; + } +}; + +// ── the verify's sampling: shared rows and laws ── + +/// A lane's law as `LPARAMS` and `SEEDS` carry it (f32 values). +const Law = struct { temp: f64 = 0, top_k: f64 = 0, top_p: f64 = 1, min_p: f64 = 0, seed: u64 = 0 }; + +/// A verify's logits: rows = lanes, n = rows a lane, k = the logits' stride (its first `vocabOf` columns real, the +/// rest padding the kernels must not read). A lane's rows share 24 spike columns (14 to 20) above a bulk of +/// N(0, 1.5^2), as a language model's head peaks; bf16 values. +const Rows = struct { + b: usize, + w: usize, + v: usize, + stride: usize, + logits: []f64, + /// [v]: 1 suppresses the column; empty: no mask (`MASK` 0). + mask: []u8, + laws: []Law, + spikes: []usize, + + fn n(self: *const Rows) usize { + return self.b * self.w; + } +}; + +fn makeRows(a: std.mem.Allocator, rng: std.Random, shape: Shape, masked: bool, fill: spec.Fill) !Rows { + const v = vocabOf(shape); + var rows: Rows = .{ + .b = shape.rows, + .w = shape.n, + .v = v, + .stride = shape.k, + .logits = try a.alloc(f64, shape.rows * shape.n * shape.k), + .mask = if (masked) try a.alloc(u8, v) else &.{}, + .laws = try a.alloc(Law, shape.rows), + .spikes = try a.alloc(usize, shape.rows * SPIKES), + }; + for (rows.mask, 0..) |*m, c| m.* = @intFromBool(c % 97 == 13); + for (rows.spikes) |*s| s.* = rng.uintLessThan(usize, v); + for (0..rows.n()) |r| { + const row = rows.logits[r * rows.stride ..][0..rows.stride]; + for (row[0..v]) |*x| x.* = bfOf(1.5 * rng.floatNorm(f64)); + for (row[v..]) |*x| x.* = 900; + for (rows.spikes[(r / rows.w) * SPIKES ..][0..SPIKES]) |c| row[c] = bfOf(14 + 6 * rng.float(f64)); + } + // A suppressed spike. + if (masked) rows.mask[rows.spikes[0]] = 1; + // Row 0's shard 0 holds two equal maxima in two threads' columns. + for ([_]usize{ 3, 700 }) |c| { + rows.logits[c] = 21; + if (masked) rows.mask[c] = 0; + } + // Gate 1: NaN in row 0, +Inf in row 1, -Inf in row 2, both in row 3 (`host.plant`; past `v` the padding). + if (fill == .nonfinite) host.plant(rows.logits, rows.n(), rows.stride); + for (rows.laws) |*law| law.* = .{ .seed = rng.int(u64) }; + return rows; +} + +/// Row `r`'s scaled logits v = f32(raw * f32(1 / temp)) where admitted, NaN where suppressed, NaN or -Inf. +fn scaled(rows: *const Rows, r: usize, vs: []f64) void { + const law = rows.laws[r / rows.w]; + const inv = if (law.temp > 0) f32of(1 / law.temp) else 1; + const src = rows.logits[r * rows.stride ..][0..rows.v]; + for (vs[0..rows.v], src, 0..) |*o, raw, c| { + const off = (rows.mask.len > 0 and rows.mask[c] != 0) or std.math.isNan(raw) or raw == -inf; + o.* = if (off) nan else f32of(raw * inv); + } +} + +const Tok = struct { v: f64, c: u32 }; + +fn rankDesc(_: void, x: Tok, y: Tok) bool { + return x.v > y.v or (x.v == y.v and x.c < y.c); +} + +/// The admitted columns at or above `cut` and `floor`, ranked (value descending, id ascending). +fn collect(vs: []const f64, cut: f64, floor: f64, out: []Tok) []Tok { + var n: usize = 0; + for (vs, 0..) |x, c| if (!std.math.isNan(x) and x >= cut and x >= floor) { + out[n] = .{ .v = x, .c = @intCast(c) }; + n += 1; + }; + std.mem.sort(Tok, out[0..n], {}, rankDesc); + return out[0..n]; +} + +/// A row's admitted max (lowest id at it), count and float64 mass exp(v - max). +const Stats = struct { gmx: f64, adm: usize, rsum: f64 }; + +fn statsOf(vs: []const f64) Stats { + var st: Stats = .{ .gmx = -inf, .adm = 0, .rsum = 0 }; + for (vs) |x| if (!std.math.isNan(x)) { + st.adm += 1; + st.gmx = @max(st.gmx, x); + }; + if (std.math.isFinite(st.gmx)) for (vs) |x| if (!std.math.isNan(x)) { + st.rsum += @exp(x - st.gmx); + }; + return st; +} + +/// A min-p whose cut, on every row of lane `l`, lies clear of every admitted value (0: none found). +fn pickMinP(rows: *Rows, l: usize, rng: std.Random, vs: []f64, toks: []Tok) f64 { + scaled(rows, l * rows.w, vs); + const st0 = statsOf(vs[0..rows.v]); + if (!std.math.isFinite(st0.gmx)) return 0; + const top = collect(vs[0..rows.v], -inf, st0.gmx - 12, toks); + if (top.len < 3) return 0; + var tries: usize = 0; + while (tries < 16) : (tries += 1) { + const j = 1 + rng.uintLessThan(usize, @min(8, top.len - 1)); + if (top[j - 1].v - top[j].v < 0.05) continue; + const mp = f32of(@exp((top[j - 1].v + top[j].v) / 2 - st0.gmx)); + if (!(mp > 0 and mp < 1)) continue; + var ok = true; + for (0..rows.w) |i| { + scaled(rows, l * rows.w + i, vs); + const st = statsOf(vs[0..rows.v]); + const cut = st.gmx + @log(mp); + for (vs[0..rows.v]) |x| if (!std.math.isNan(x) and !clear(x, cut)) { + ok = false; + }; + } + if (ok) return mp; + } + return 0; +} + +/// Every row of lane `l` under `law` stops its ranked walk within the window, its every mass comparison clear. +fn pValid(rows: *Rows, l: usize, law: Law, vs: []f64, toks: []Tok) bool { + for (0..rows.w) |i| { + scaled(rows, l * rows.w + i, vs); + const st = statsOf(vs[0..rows.v]); + const cut = if (law.min_p > 0) st.gmx + @log(law.min_p) else -inf; + const floor = st.gmx - 12; + const ranked = collect(vs[0..rows.v], cut, floor, toks); + const lim = law.top_p * st.rsum; + const top_k = tokU(law.top_k); + const k_lim = if (top_k > 0 and top_k < st.adm) top_k else st.adm; + var cum: f64 = 0; + const stopped = for (ranked, 1..) |t, cnt| { + cum += @exp(t.v - st.gmx); + if (!clear(cum, lim)) return false; + if (cnt >= k_lim or cum >= lim) break t.v >= floor + 0.1; + } else false; + if (!stopped) return false; + } + return true; +} + +/// A top-p whose crossing, on every row of lane `l`, falls mid-token (1: none found). +fn pickTopP(rows: *Rows, l: usize, rng: std.Random, vs: []f64, toks: []Tok) f64 { + const law = rows.laws[l]; + scaled(rows, l * rows.w, vs); + const st0 = statsOf(vs[0..rows.v]); + if (!std.math.isFinite(st0.gmx)) return 1; + const cut = if (law.min_p > 0) st0.gmx + @log(law.min_p) else -inf; + const top = collect(vs[0..rows.v], cut, st0.gmx - 12, toks); + if (top.len < 3) return 1; + var cum: [16]f64 = undefined; + var s: f64 = 0; + for (top[0..@min(16, top.len)], 0..) |t, i| { + s += @exp(t.v - st0.gmx); + cum[i] = s; + } + var tries: usize = 0; + while (tries < 16) : (tries += 1) { + const at = 1 + rng.uintLessThan(usize, @min(15, top.len) - 1); + const p = f32of((cum[at - 1] + cum[at]) / 2 / st0.rsum); + if (!(p > 0 and p < 1)) continue; + var with = law; + with.top_p = p; + if (pValid(rows, l, with, vs, toks)) return p; + } + return 1; +} + +/// Each lane's law: greedy; sampled with no filter; top-k; top-p; min-p; all three; top-k 1 (lane kinds rotated by +/// the seed). Temperatures are powers of two, as any f32 reciprocal is exact on both sides. Gate 1's lane 0 samples +/// with no filter (its rows hold the planted values). +fn chooseLaws(rows: *Rows, rng: std.Random, fill: spec.Fill, vs: []f64, toks: []Tok) void { + const off = rng.uintLessThan(usize, 7); + for (0..rows.b) |l| { + const law = &rows.laws[l]; + const kind = if (fill == .nonfinite and l == 0) 1 else (l + off) % 7; + switch (kind) { + 0 => {}, + 1 => law.temp = 1, + 2 => { + law.temp = 0.5; + law.top_k = @floatFromInt(2 + rng.uintLessThan(u32, 40)); + }, + 3 => { + law.temp = 1; + law.top_p = pickTopP(rows, l, rng, vs, toks); + }, + 4 => { + law.temp = 1; + law.min_p = pickMinP(rows, l, rng, vs, toks); + }, + 5 => { + law.temp = 0.5; + law.top_k = 40; + law.min_p = pickMinP(rows, l, rng, vs, toks); + law.top_p = pickTopP(rows, l, rng, vs, toks); + }, + else => { + law.temp = 1; + law.top_k = 1; + }, + } + } +} + +/// One shard's PMASS entry: its admitted max, sum of exp(v - max) (sampled lanes), count and argmax id. +const Part = struct { mx: f64, sum: f64, e: f64 = 0, adm: usize, id: u32 }; + +/// Shard `s` of a row as sample_tree_mass computes it; `planted` breaks a tie toward the higher id. +fn massOf(v: usize, vs: []const f64, s: usize, sampled: bool, sim: Sim, planted: bool, terms: []f64) Part { + const chunk = (v + SHARDS - 1) / SHARDS; + const lo = @min(v, s * chunk); + const hi = @min(v, lo + chunk); + var p: Part = .{ .mx = -inf, .sum = 0, .adm = 0, .id = @intCast(v) }; + for (lo..hi) |c| { + const x = vs[c]; + if (std.math.isNan(x)) continue; + p.adm += 1; + if (x > p.mx or (planted and x == p.mx)) { + p.mx = x; + p.id = @intCast(c); + } + } + if (!sampled or p.mx == -inf) return p; + if (p.mx == inf) { + // exp(+Inf - +Inf): the sum is not a number. + p.sum = nan; + return p; + } + // Each term passes an exp at its insertion and at most a thread's columns of rescales, then the SIMD group's and + // the threadgroup's: their arguments add to v - max, so their fast-exp errors add to (3 a step + 2 |v - max|) ulps. + const per = (chunk + 255) / 256; + var n: usize = 0; + var e: f64 = 0; + for (lo..hi) |c| { + const x = vs[c]; + if (std.math.isNan(x)) continue; + const t = @exp(x - p.mx); + terms[n] = t; + n += 1; + e += t * (3 * @as(f64, @floatFromInt(per + 3)) + 2 * @abs(x - p.mx)) * 0x1p-23; + } + p.sum = total(sim, terms[0..n]); + // Any order of the shard's adds (gate 4 sums them in each), the kernel's included. + p.e = e + spec.gamma(@floatFromInt(n + 13), U) * p.sum; + return p; +} + +/// A row's VROW: { max, cut logit, cut id, kept mass } and the errors of the cut and the mass. +const Vrow = struct { rmax: f64, cut: f64, cut_e: f64 = 0, id: u32, km: f64, km_e: f64 = 0 }; + +fn binOf(rmax: f64, v: f64) usize { + const diff = f32of(rmax - v); + if (diff <= 0) return 0; + if (diff >= 20) return 511; + return @min(510, 1 + @as(usize, @intFromFloat(@floor(f32of(diff * 25.5))))); +} + +/// sample_tree_search on a row: the shards merged, then the exact top-k / top-p / min-p cut in rank order (value +/// descending, id ascending), as `ranksDescending`; past 512 tokens in the cut's histogram bin, the kernel's stated +/// fallback (keep down to the bin's low edge). `planted` keeps one token past the top-k. +fn vrowOf(law: Law, v: usize, vs: []const f64, parts: []const Part, sim: Sim, planted: bool, toks: []Tok, terms: []f64) Vrow { + const sampled = law.temp > 0; + var gmx = -inf; + var gid: u32 = 0; + var gadm: usize = 0; + for (parts) |p| { + gadm += p.adm; + if (p.mx > gmx or (p.mx == gmx and p.id < gid)) { + gmx = p.mx; + gid = p.id; + } + } + var rsum: f64 = 0; + var rsum_e: f64 = 0; + if (sampled and gmx > -inf) { + var n: usize = 0; + var m: f64 = 0; + for (parts) |p| if (p.mx > -inf) { + const t = p.sum * @exp(p.mx - gmx); + terms[n] = t; + n += 1; + rsum_e += @abs(t) * (host.fastExp(p.mx - gmx) + U); + m += @abs(t); + }; + rsum = total(sim, terms[0..n]); + rsum_e += spec.gamma(SHARDS, U) * m; + } + const top_k = tokU(law.top_k); + if (!sampled or top_k == 1 or gadm <= 1 or !(rsum > 0)) return .{ .rmax = gmx, .cut = gmx, .id = gid, .km = 1 }; + const cut = if (law.min_p > 0) gmx + @log(law.min_p) else -inf; + const cut_e = if (law.min_p > 0) fastLogErr(law.min_p) + U * @abs(cut) else 0; + const has_k = top_k > 0 and top_k < gadm; + const has_p = law.top_p > 0 and law.top_p < 1; + const vid: u32 = @intCast(v); + if (!has_k and !has_p) { + if (!(law.min_p > 0)) return .{ .rmax = gmx, .cut = -inf, .id = vid, .km = rsum, .km_e = rsum_e }; + var n: usize = 0; + var e: f64 = 0; + for (vs[0..v]) |x| if (!std.math.isNan(x) and x >= cut) { + const t = @exp(x - gmx); + terms[n] = t; + n += 1; + e += t * (host.fastExp(x - gmx) + U); + }; + const km = total(sim, terms[0..n]); + return .{ .rmax = gmx, .cut = cut, .cut_e = cut_e, .id = vid, .km = if (km > 0) km else 1, .km_e = e + spec.gamma(@floatFromInt(n + 13), U) * km }; + } + const k_lim = (if (has_k) top_k else gadm) + @intFromBool(planted); + const p_lim = if (has_p) law.top_p * rsum else 2 * rsum; + var floor = gmx - 12; + while (true) { + const ranked = collect(vs[0..v], cut, floor, toks); + var cum: f64 = 0; + var e: f64 = 0; + var stop: ?usize = null; + for (ranked, 0..) |t, i| { + const x = t.v - gmx; + const wt = @exp(x); + cum = step(sim, cum, wt); + e += wt * (host.fastExp(x) + U); + if (i + 1 >= k_lim or cum >= p_lim) { + stop = i; + break; + } + } + if (stop == null and floor != -inf) { + floor = -inf; + continue; + } + if (stop) |i| if (ranked[i].v < floor + 0.1 and floor != -inf) { + floor = -inf; + continue; + }; + // The cut's bin: the crossing token's, or the last bin when the limits are never reached. + const cb = if (stop) |i| binOf(gmx, ranked[i].v) else 511; + var in_bin: usize = 0; + var above: f64 = 0; + var above_n: usize = 0; + for (ranked) |t| { + const bn = binOf(gmx, t.v); + if (bn == cb) in_bin += 1; + if (bn < cb) { + above += @exp(t.v - gmx); + above_n += 1; + } + } + if (in_bin > 0 and in_bin <= 512) { + const at = stop orelse ranked.len - 1; + return .{ .rmax = gmx, .cut = ranked[at].v, .id = ranked[at].c, .km = if (cum > 0) cum else 1, .km_e = e + spec.gamma(@floatFromInt(at + 14), U) * cum }; + } + // The fallback: an empty or overfull bin keeps down to its low edge, or its high edge when the bins above + // already reach a limit. + const hi_lo: [2]f64 = if (cb == 0) .{ gmx, gmx } else if (cb == 511) .{ f32of(gmx - 20), -inf } else .{ f32of(gmx - f32of(@as(f64, @floatFromInt(cb - 1)) / 25.5)), f32of(gmx - f32of(@as(f64, @floatFromInt(cb)) / 25.5)) }; + const reached = above > 0 and (above_n >= k_lim or above >= p_lim); + const cl = if (reached) hi_lo[0] else @max(hi_lo[1], cut); + return .{ .rmax = gmx, .cut = cl, .cut_e = if (!reached and cl == cut) cut_e else 0, .id = vid, .km = if (above > 0) above else rsum, .km_e = if (above > 0) e + spec.gamma(@floatFromInt(above_n + 13), U) * above else rsum_e }; + } +} + +/// A row's draft-tree inputs for sample_tree_draw: each lane's candidates a depth (16 of its spike columns), each +/// row's depth, its drawn candidates (none in a quarter of rows) and the draft's normalized q over the candidates. +const Draws = struct { r: usize, tmeta: []f64, cands: []f64, next_q: []f64, draws: []f64 }; + +fn makeDraws(a: std.mem.Allocator, rng: std.Random, rows: *const Rows) !Draws { + const r = rowsOf(rows.w); + const d: Draws = .{ + .r = r, + .tmeta = try a.alloc(f64, 2 * rows.n()), + .cands = try a.alloc(f64, rows.b * r * KTOP), + .next_q = try a.alloc(f64, rows.n() * KTOP), + .draws = try a.alloc(f64, rows.n() * 4), + }; + for (0..rows.b) |l| for (0..r) |pos| { + var perm: [SPIKES]usize = undefined; + for (&perm, 0..) |*x, i| x.* = i; + rng.shuffle(usize, &perm); + for (0..KTOP) |i| d.cands[(l * r + pos) * KTOP + i] = @floatFromInt(rows.spikes[l * SPIKES + perm[i]]); + }; + for (0..rows.n()) |row| { + d.tmeta[2 * row] = @floatFromInt(rng.uintLessThan(usize, r + 1)); + d.tmeta[2 * row + 1] = 1; + var q: [KTOP]f64 = undefined; + var s: f64 = 0; + for (&q) |*x| { + const u = rng.float(f64); + x.* = u * u + 0.02; + s += x.*; + } + for (q, 0..) |x, i| d.next_q[row * KTOP + i] = f32of(x / s); + var perm: [KTOP]usize = undefined; + for (&perm, 0..) |*x, i| x.* = i; + rng.shuffle(usize, &perm); + const nd = if (rng.uintLessThan(u32, 4) == 0) 0 else 1 + rng.uintLessThan(usize, 4); + for (0..4) |ch| d.draws[row * 4 + ch] = if (ch < nd) @floatFromInt(perm[ch]) else 255; + } + return d; +} + +const Stage = enum { mass, search, draw }; + +/// One of the verify's three sampling kernels over `Rows`: mass (PMASS [rows, 16, 4]), search (VROW [rows, 4] from +/// the mass's PMASS) or draw (SELECTED [rows], from the search's VROW and the draft tree). The planted controls: the +/// mass breaks a tie toward the higher id, the search keeps one token past the top-k, the draw takes the token after +/// the one its uniform lands on. +const Sample = struct { + rig: metal.Rig, + launch: *const metal.Launch, + arena: std.heap.ArenaAllocator, + stage: Stage, + masked: bool, + planted: bool = false, + shape: Shape = undefined, + rows: Rows = undefined, + /// Per row: the PMASS the search reads, the VROW the draw reads. + parts: [][SHARDS]Part = &.{}, + vrows: []Vrow = &.{}, + tree: Draws = undefined, + vs: []f64 = &.{}, + toks: []Tok = &.{}, + terms: []f64 = &.{}, + note: [240]u8 = undefined, + args: [9]mlx.mlx_array = undefined, + n_args: usize = 0, + + const Self = @This(); + + fn init(a: std.mem.Allocator, stage: Stage, masked: bool, planted: bool) Self { + const l: *const metal.Launch = switch (stage) { + .mass => &mass_launch, + .search => &search_launch, + .draw => &draw_launch, + }; + return .{ .rig = metal.Rig.init(a), .launch = l, .arena = .init(a), .stage = stage, .masked = masked, .planted = planted }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(self: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.rows > 16 or shape.n < 2 or shape.n > 16 or shape.k < 4096) return null; + const rows = shape.rows * shape.n; + const v = vocabOf(shape); + return switch (self.stage) { + .mass => massGeometry(rows, shape.n, v, shape.k, self.masked), + .search => searchGeometry(rows, shape.n, v, shape.k, self.masked), + .draw => drawGeometry(rows, shape.n, v, shape.k, self.masked, rowsOf(shape.n)), + }; + } + + fn sampled(self: *const Self, r: usize) bool { + return self.rows.laws[r / self.rows.w].temp > 0; + } + + fn partsOf(self: *Self, r: usize, sim: Sim, planted: bool) [SHARDS]Part { + scaled(&self.rows, r, self.vs); + var out: [SHARDS]Part = undefined; + for (&out, 0..) |*p, s| p.* = massOf(self.rows.v, self.vs[0..self.rows.v], s, self.sampled(r), sim, planted, self.terms); + return out; + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const v = vocabOf(shape); + self.vs = try a.alloc(f64, v); + self.toks = try a.alloc(Tok, v); + self.terms = try a.alloc(f64, v); + self.rows = try makeRows(a, rng, shape, self.masked, fill); + chooseLaws(&self.rows, rng, fill, self.vs, self.toks); + const n = self.rows.n(); + if (self.stage != .mass) { + // The PMASS a device's mass kernel would hand on: its sums rounded to f32. + self.parts = try a.alloc([SHARDS]Part, n); + for (self.parts, 0..) |*p, r| { + p.* = self.partsOf(r, null, false); + for (p) |*x| x.sum = f32of(x.sum); + } + } + if (self.stage == .draw) { + self.vrows = try a.alloc(Vrow, n); + for (self.vrows, 0..) |*x, r| { + scaled(&self.rows, r, self.vs); + x.* = vrowOf(self.rows.laws[r / self.rows.w], v, self.vs[0..v], &self.parts[r], null, false, self.toks, self.terms); + x.cut = f32of(x.cut); + x.km = f32of(x.km); + } + self.tree = try makeDraws(a, rng, &self.rows); + // Gate 1's planted rows draw no candidates; a row whose candidates hold nearly all its kept mass draws + // none either (the outside mass would sit inside the device's error of zero). + for (0..n) |r| { + if (fill == .nonfinite and r < 4) self.tree.tmeta[2 * r] = @floatFromInt(self.tree.r); + if (!self.hasDraw(r)) continue; + scaled(&self.rows, r, self.vs); + var psum: f64 = 0; + for (self.candsOf(r)) |c| psum += self.admittedProb(r, self.vs, c); + if (!clear(1, psum)) self.tree.draws[4 * r] = 255; + } + // Each sampled lane's seed: redrawn until every choice of its rows clears the device's error. + for (self.rows.laws, 0..) |*law, l| { + if (!(law.temp > 0) or law.top_k == 1) continue; + var tries: usize = 0; + while (!self.laneClear(l)) : (tries += 1) { + if (tries == 256) return error.NoClearSeed; + law.seed = rng.int(u64); + } + } + } + try self.bind(); + return true; + } + + fn laneClear(self: *Self, l: usize) bool { + for (l * self.rows.w..(l + 1) * self.rows.w) |r| { + scaled(&self.rows, r, self.vs); + if (!self.drawRow(r, self.vs, null, false).ok) return false; + } + return true; + } + + fn bind(self: *Self) !void { + const rows = &self.rows; + const n = rows.n(); + const a = self.arena.allocator(); + self.rig.reset(); + self.args[0] = try self.rig.input(.bfloat16, &.{ cint(n), cint(rows.stride) }, rows.logits); + self.args[1] = if (self.masked) try self.rig.inputRaw(.bool_, &.{cint(rows.v)}, rows.mask) else try self.rig.inputRaw(.bool_, &.{1}, &.{0}); + const lp = try a.alloc(f64, 4 * rows.b); + for (rows.laws, 0..) |law, l| lp[4 * l ..][0..4].* = .{ law.temp, law.top_k, law.top_p, law.min_p }; + self.args[2] = try self.rig.input(.float32, &.{ cint(rows.b), 4 }, lp); + self.n_args = 3; + switch (self.stage) { + .mass => {}, + .search => { + const pm = try a.alloc(f64, n * SHARDS * 4); + for (self.parts, 0..) |ps, r| for (ps, 0..) |p, s| { + pm[(r * SHARDS + s) * 4 ..][0..4].* = .{ p.mx, p.sum, @floatFromInt(p.adm), idBits(p.id) }; + }; + self.args[3] = try self.rig.input(.float32, &.{ cint(n), SHARDS, 4 }, pm); + self.n_args = 4; + }, + .draw => { + const vr = try a.alloc(f64, n * 4); + for (self.vrows, 0..) |x, r| vr[4 * r ..][0..4].* = .{ x.rmax, x.cut, idBits(x.id), x.km }; + const seeds = try a.alloc(f64, 2 * rows.b); + for (rows.laws, 0..) |law, l| seeds[2 * l ..][0..2].* = .{ @floatFromInt(@as(u32, @truncate(law.seed))), @floatFromInt(@as(u32, @truncate(law.seed >> 32))) }; + const t = &self.tree; + self.args[3] = try self.rig.input(.float32, &.{ cint(n), 4 }, vr); + self.args[4] = try self.rig.input(.uint32, &.{ cint(rows.b), 2 }, seeds); + self.args[5] = try self.rig.input(.int32, &.{ cint(n), 2 }, t.tmeta); + self.args[6] = try self.rig.input(.int32, &.{ cint(rows.b), cint(t.r), KTOP }, t.cands); + self.args[7] = try self.rig.input(.float32, &.{ cint(rows.b), cint(rows.w), KTOP }, t.next_q); + self.args[8] = try self.rig.input(.uint8, &.{ cint(rows.b), cint(rows.w), 4 }, t.draws); + self.n_args = 9; + }, + } + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, self.args[0..self.n_args]); + } + + pub fn count(self: *const Self) usize { + const n = self.shape.rows * self.shape.n; + return switch (self.stage) { + .mass => n * SHARDS * 4, + .search => n * 4, + .draw => n, + }; + } + + // The draw's pieces, as sample_tree_draw's. + + fn hasDraw(self: *const Self, r: usize) bool { + return tokU(self.tree.tmeta[2 * r]) < self.tree.r and self.tree.draws[4 * r] < KTOP; + } + + fn candsOf(self: *const Self, r: usize) []const f64 { + const depth = tokU(self.tree.tmeta[2 * r]); + return self.tree.cands[((r / self.rows.w) * self.tree.r + depth) * KTOP ..][0..KTOP]; + } + + fn admitted(self: *const Self, r: usize, vs: []const f64, c: usize) bool { + const x = vs[c]; + const vr = self.vrows[r]; + return !std.math.isNan(x) and (x > vr.cut or (x == vr.cut and c <= vr.id)); + } + + fn admittedProb(self: *const Self, r: usize, vs: []const f64, cid: f64) f64 { + if (cid < 0 or cid >= @as(f64, @floatFromInt(self.rows.v))) return 0; + const c = tokU(cid); + if (!self.admitted(r, vs, c)) return 0; + return @exp(vs[c] - self.vrows[r].rmax) / self.vrows[r].km; + } + + const Pick = struct { tok: u32, ok: bool }; + + /// The full-vocab walk: the first admitted column (not a candidate, with `excl`) whose running mass reaches + /// `target`; past the end the last admitted one; none admitted, the cut's id. + fn scan(self: *const Self, r: usize, vs: []const f64, excl: ?[]const f64, target: f64, sim: Sim, planted: bool) Pick { + const vr = self.vrows[r]; + var cum: f64 = 0; + var ok = true; + var last: ?usize = null; + var hit: ?usize = null; + for (0..self.rows.v) |c| { + if (!self.admitted(r, vs, c)) continue; + if (excl) |e| if (std.mem.indexOfScalar(f64, e, @floatFromInt(c)) != null) continue; + if (hit != null) return .{ .tok = @intCast(c), .ok = ok }; + const prev = cum; + cum = step(sim, cum, @exp(vs[c] - vr.rmax)); + last = c; + if (cum >= target) { + if (!clear(cum, target) or !clear(prev, target)) ok = false; + hit = c; + if (!planted) break; + } + } + if (hit) |h| return .{ .tok = @intCast(h), .ok = ok }; + if (last) |l| { + if (!std.math.isNan(cum) and !clear(cum, target)) ok = false; + return .{ .tok = @intCast(l), .ok = ok }; + } + return .{ .tok = vr.id, .ok = ok }; + } + + /// Row `r`'s selection, and whether every choice it made clears the device's error. + fn drawRow(self: *const Self, r: usize, vs: []const f64, sim: Sim, planted: bool) Pick { + const law = self.rows.laws[r / self.rows.w]; + const vr = self.vrows[r]; + if (!(law.temp > 0) or law.top_k == 1) return .{ .tok = vr.id, .ok = true }; + if (!self.hasDraw(r)) return self.scan(r, vs, null, f32of(uniform01(law.seed, r, 5) * vr.km), sim, planted); + const cands = self.candsOf(r); + const q_in = self.tree.next_q[r * KTOP ..][0..KTOP]; + var p_rem: [KTOP]f64 = undefined; + var q_rem: [KTOP]f64 = undefined; + for (&p_rem, &q_rem, cands, q_in) |*p, *q, c, qi| { + p.* = self.admittedProb(r, vs, c); + q.* = qi; + } + var ok = true; + const outside = @max(0, 1 - total(sim, &p_rem)); + var oscale: f64 = 1; + var qmass: f64 = 1; + for (0..4) |ch| { + const di = tokU(self.tree.draws[4 * r + ch]); + if (di >= KTOP) break; + const qc = if (qmass > 0) q_rem[di] / qmass else 0; + const ap = if (qc > 0) @min(1, p_rem[di] / qc) else 0; + const u = uniform01(law.seed, r, @intCast(ch)); + if (ap > 0 and ap < 1 and !clear(u, ap)) ok = false; + if (u < ap) return .{ .tok = tokU(cands[if (planted) (di + 1) % KTOP else di]), .ok = ok }; + var next: [KTOP]f64 = undefined; + var z = outside * oscale; + for (&next, p_rem, q_rem) |*x, p, q| { + x.* = @max(0, p - (if (qmass > 0) q / qmass else 0)); + z += x.*; + } + if (!(z > 1e-9)) ok = false; + if (z <= 1e-12) break; + for (&p_rem, next) |*p, x| p.* = x / z; + oscale /= z; + qmass = @max(0, qmass - q_rem[di]); + q_rem[di] = 0; + } + const cand_res = total(sim, &p_rem); + const u_res = uniform01(law.seed, r, 5); + if (!clear(u_res, cand_res)) ok = false; + if (u_res < cand_res or !(outside * oscale > 1e-12)) { + const target = if (u_res < cand_res) u_res else u_res * cand_res; + var acc: f64 = 0; + for (p_rem, 0..) |p, i| { + const prev = acc; + acc = step(sim, acc, p); + if (acc >= target) { + if (!clear(acc, target) or !clear(prev, target)) ok = false; + return .{ .tok = tokU(cands[if (planted) (i + 1) % KTOP else i]), .ok = ok }; + } + } + return .{ .tok = tokU(cands[0]), .ok = ok }; + } + const pick = self.scan(r, vs, cands, f32of((u_res - cand_res) / oscale * vr.km), sim, planted); + return .{ .tok = pick.tok, .ok = ok and pick.ok }; + } + + /// Outputs and their errors (as `mag` allowances) by stage; `sim` runs the sums in an accumulator. + fn emit(self: *Self, want: []f64, mag: []f64, sim: Sim) void { + const v = self.rows.v; + for (0..self.rows.n()) |r| switch (self.stage) { + .mass => { + const ps = self.partsOf(r, sim, self.planted); + for (ps, 0..) |p, s| { + const o = (r * SHARDS + s) * 4; + want[o..][0..4].* = .{ p.mx, p.sum, @floatFromInt(p.adm), idBits(p.id) }; + mag[o..][0..4].* = .{ 0, host.allowance(p.e), 0, 0 }; + } + }, + .search => { + scaled(&self.rows, r, self.vs); + const x = vrowOf(self.rows.laws[r / self.rows.w], v, self.vs[0..v], &self.parts[r], sim, self.planted, self.toks, self.terms); + want[4 * r ..][0..4].* = .{ x.rmax, x.cut, idBits(x.id), x.km }; + mag[4 * r ..][0..4].* = .{ 0, host.allowance(x.cut_e), 0, host.allowance(x.km_e) }; + }, + .draw => { + scaled(&self.rows, r, self.vs); + want[r] = @floatFromInt(self.drawRow(r, self.vs, sim, self.planted).tok); + mag[r] = 0; + }, + }; + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + @constCast(self).emit(want, mag, null); + } + + pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { + const mag = try self.rig.a.alloc(f64, out.len); + defer self.rig.a.free(mag); + @constCast(self).emit(out, mag, .{ .acc = acc, .order = order }); + } + + /// The stated rule: indices and counts exact, an id slot's bits exact, a max or cut a token's value exactly + /// (min-p's cut within its log's error), masses within their f32 and fast-exp error; NaN where a +Inf logit's + /// sampled mass is exp(Inf - Inf). + pub fn check(self: *Self, _: spec.Gate) !?[]const u8 { + const n = self.count(); + const buf = try self.arena.allocator().alloc(f64, 2 * n); + const want = buf[0..n]; + const mag = buf[n..]; + try self.reference(want, mag); + const bytes = self.rig.outputBytes(); + for (want, mag, 0..) |w, m, i| { + const id_slot = switch (self.stage) { + .mass => i % 4 == 3, + .search => i % 4 == 2, + .draw => false, + }; + if (self.stage == .draw or id_slot) { + const got: f64 = if (self.stage == .draw) @floatFromInt(@as(i32, @bitCast(bitsAt(bytes, i)))) else @floatFromInt(bitsAt(bytes, i)); + const ref: f64 = if (self.stage == .draw) w else @floatFromInt(@as(u32, @bitCast(@as(f32, @floatCast(w))))); + if (got != ref) return fail(&self.note, "output {d}: {d} where the reference gives {d}", .{ i, got, ref }); + continue; + } + const got = spec.read(.f32, bytes, i); + // `mag` is an allowance: the error it stands for. + const e = m * U / (1 - U); + if (!close(got, w, e)) return fail(&self.note, "output {d}: {e} where float64 gives {e} (error {e})", .{ i, got, w, e }); + } + return null; + } + + fn wrapperLanes(self: *const Self, out: []kernels.SampleLane, caps: []const f64) void { + for (self.rows.laws, out, caps) |law, *o, c| o.* = .{ .temperature = @floatCast(law.temp), .top_k = tokU(law.top_k), .top_p = @floatCast(law.top_p), .min_p = @floatCast(law.min_p), .seed = law.seed, .accept_cap = tokU(c) }; + } +}; + +// ── dflash_conv ── + +/// The draft's grouped dynamic convolution, both stages: rows = lanes, n = the block, k = the stream width. STAGE 0 +/// (`prepare`) convolves its input; STAGE 1 (`finishAdd`) rounds the convolution to bf16 and adds the residual. bf16 +/// throughout, as the draft runs. The planted control drops a tap (KT 1). +fn Conv(comptime stage: usize) type { + return struct { + rig: metal.Rig, + launch: *const metal.Launch = &conv_launch, + arena: std.heap.ArenaAllocator, + planted: bool = false, + shape: Shape = undefined, + x: []f64 = &.{}, + dyn: []f64 = &.{}, + base: []f64 = &.{}, + res: []f64 = &.{}, + args: [4]mlx.mlx_array = undefined, + + const Self = @This(); + const G = HIDDEN / CONV_GS; + + fn init(a: std.mem.Allocator, planted: bool) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a), .planted = planted }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(self: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.n == 0 or shape.k != HIDDEN) return null; + return convGeometry(shape.rows, shape.n, stage, if (self.planted) CONV_KT - 1 else CONV_KT); + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const bl = shape.rows * shape.n; + self.x = try host.uniform(a, rng, bl * HIDDEN, -2, 2, .bfloat16); + self.dyn = try host.uniform(a, rng, bl * 2 * CONV_KT * G, -0.3, 0.3, .bfloat16); + self.base = try host.uniform(a, rng, 2 * CONV_KT * HIDDEN, -0.5, 0.5, .bfloat16); + self.res = try host.uniform(a, rng, bl * HIDDEN, -2, 2, .bfloat16); + if (fill == .nonfinite) host.plant(self.x, bl, HIDDEN); + self.rig.reset(); + const b = cint(shape.rows); + const l = cint(shape.n); + self.args[0] = try self.rig.input(.bfloat16, &.{ b, l, HIDDEN }, self.x); + self.args[1] = try self.rig.input(.bfloat16, &.{ b, l, 2, CONV_KT, G }, self.dyn); + self.args[2] = try self.rig.input(.bfloat16, &.{ 2, CONV_KT, HIDDEN }, self.base); + // `prepare` hands its input as the unread residual. + self.args[3] = if (stage == 1) try self.rig.input(.bfloat16, &.{ b, l, HIDDEN }, self.res) else self.args[0]; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return self.shape.rows * self.shape.n * HIDDEN; + } + + /// Output `i`'s four products (two a tap: the base's and the dynamic kernel's), zero before the first row. + fn terms(self: *const Self, i: usize, t: *[2 * CONV_KT]f64) void { + const len = self.shape.n; + const c = i % HIDDEN; + const l = (i / HIDDEN) % len; + const b = i / (HIDDEN * len); + for (0..CONV_KT) |tap| { + if (l < tap) { + t[2 * tap] = 0; + t[2 * tap + 1] = 0; + continue; + } + const v = self.x[(b * len + l - tap) * HIDDEN + c]; + const bk = self.base[(stage * CONV_KT + tap) * HIDDEN + c]; + const dk = self.dyn[(((b * len + l) * 2 + stage) * CONV_KT + tap) * G + c / CONV_GS]; + t[2 * tap] = bk * v; + t[2 * tap + 1] = dk * v; + } + } + + fn emit(self: *const Self, want: []f64, mag: ?[]f64, sim: Sim) void { + for (want, 0..) |*w, i| { + var t: [2 * CONV_KT]f64 = undefined; + self.terms(i, &t); + // A tap's two products, then the taps, as the kernel adds them (NaN and infinities included). + var acc: f64 = 0; + for (0..CONV_KT) |tap| acc += t[2 * tap] + t[2 * tap + 1]; + if (sim) |x| acc = spec.sumIn(x.acc, x.order, &t); + const e = spec.gamma(2 * CONV_KT, U) * host.sumAbs(&t); + var out: host.Val = .{ .v = acc, .e = e }; + if (stage == 1) { + const r1 = host.round(.bfloat16, out); + const s = r1.v + self.res[i]; + out = .{ .v = s, .e = r1.e + U * @abs(s) }; + } + w.* = out.v; + if (mag) |m| m[i] = if (std.math.isFinite(out.e)) host.allowance(out.e) else 0; + } + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + self.emit(want, mag, null); + } + + pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { + self.emit(out, null, .{ .acc = acc, .order = order }); + } + }; +} + +/// A drafter carrying only what the conv and selector wrappers read. +fn testDrafter(s: mlx.mlx_stream, hidden: usize) dflash2.Drafter { + return .{ + .cfg = .{ .layers = 1, .heads = 1, .kv_heads = 1, .head_dim = 16, .intermediate = 32, .window = 16, .block = BLOCK, .mask_id = 0, .tap_count = 2, .conv_kernel = CONV_KT, .conv_group = CONV_GS, .rank = RANK, .top_k = KTOP, .softcap = @floatCast(SOFTCAP) }, + .hidden = @intCast(hidden), + .s = s, + }; +} + +// ── dflash_top16_shard, dflash_top16_merge ── + +fn shardOuts(shape: Shape) usize { + return shape.rows * SHARDS * KTOP; +} + +fn mergeOuts(shape: Shape) usize { + return shape.rows * KTOP; +} + +/// Each row's top 16 a shard: rows = the block rows of every lane, n = the logits' stride, k = the vocab. The +/// padding past the vocab holds 1000, which a read past V would rank first. Row 0's shard 0 holds two equal maxima +/// (the lower id ranks first; the planted control ranks the higher). +const Shard = struct { + rig: metal.Rig, + launch: *const metal.Launch = &shard_launch, + arena: std.heap.ArenaAllocator, + planted: bool = false, + shape: Shape = undefined, + logits: []f64 = &.{}, + args: [1]mlx.mlx_array = undefined, + + const Self = @This(); + + fn init(a: std.mem.Allocator, planted: bool) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a), .planted = planted }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(_: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.k < SHARDS * KTOP or shape.n < shape.k) return null; + return shardGeometry(shape.rows, shape.n, shape.k); + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.logits = try a.alloc(f64, shape.rows * shape.n); + for (0..shape.rows) |r| { + const row = self.logits[r * shape.n ..][0..shape.n]; + for (row[0..shape.k]) |*x| x.* = bfOf(2 * rng.floatNorm(f64)); + for (row[shape.k..]) |*x| x.* = 1000; + for (0..SPIKES) |_| row[rng.uintLessThan(usize, shape.k)] = bfOf(10 + 8 * rng.float(f64)); + } + self.logits[5] = 50; + self.logits[9] = 50; + if (fill == .nonfinite) host.plant(self.logits, shape.rows, shape.n); + self.rig.reset(); + self.args[0] = try self.rig.input(.bfloat16, &.{ cint(shape.rows), cint(shape.n) }, self.logits); + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return 2 * shardOuts(self.shape); + } + + /// Rank order; planted: a tie's higher id first. + fn tieLess(planted: bool, x: Tok, y: Tok) bool { + return x.v > y.v or (x.v == y.v and (if (planted) x.c > y.c else x.c < y.c)); + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + const v = self.shape.k; + const chunk = (v + SHARDS - 1) / SHARDS; + const half = shardOuts(self.shape); + const buf = try self.rig.a.alloc(Tok, chunk); + defer self.rig.a.free(buf); + for (0..self.shape.rows) |r| for (0..SHARDS) |s| { + const lo = @min(v, s * chunk); + const hi = @min(v, lo + chunk); + var n: usize = 0; + for (lo..hi) |c| { + const x = self.logits[r * self.shape.n + c]; + if (std.math.isNan(x)) continue; + buf[n] = .{ .v = x, .c = @intCast(c) }; + n += 1; + } + std.mem.sort(Tok, buf[0..n], self.planted, tieLess); + const o = (r * SHARDS + s) * KTOP; + for (0..KTOP) |m| { + const t: Tok = if (m < n) buf[m] else .{ .v = -inf, .c = @intCast(v) }; + want[o + m] = @floatFromInt(t.c); + want[half + o + m] = t.v; + } + }; + for (want, mag) |w, *m| m.* = if (std.math.isFinite(w)) @abs(w) else 0; + } +}; + +/// The shards' lists merged: rows = block rows, n = shards, k = 16. Each shard's list sorted (value descending, id +/// ascending) over its own ids, values on a coarse grid so lists tie within and across shards, some shards padded +/// with (-Inf, V) as a shard short of 16 numbers hands on. Row 0's shard 15 heads the row (the planted control merges +/// 15 shards). +const Merge = struct { + rig: metal.Rig, + launch: *const metal.Launch = &merge_launch, + arena: std.heap.ArenaAllocator, + planted: bool = false, + shape: Shape = undefined, + ids: []f64 = &.{}, + vals: []f64 = &.{}, + args: [2]mlx.mlx_array = undefined, + + const Self = @This(); + + fn init(a: std.mem.Allocator, planted: bool) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a), .planted = planted }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(self: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.n != SHARDS or shape.k != KTOP) return null; + return mergeGeometry(shape.rows, if (self.planted) SHARDS - 1 else SHARDS); + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = shape.rows * SHARDS * KTOP; + self.ids = try a.alloc(f64, n); + self.vals = try a.alloc(f64, n); + const chunk = (VOCAB + SHARDS - 1) / SHARDS; + for (0..shape.rows) |r| for (0..SHARDS) |s| { + var list: [KTOP]Tok = undefined; + for (&list) |*t| t.* = .{ .v = 10 + 0.25 * @as(f64, @floatFromInt(rng.uintLessThan(u32, 40))), .c = @intCast(s * chunk + rng.uintLessThan(usize, chunk)) }; + if (r == 0 and s == SHARDS - 1) list[0].v = 30; + if (fill == .nonfinite) { + if (r == 1 and s == 3) list[0].v = inf; + if (r == 3 and s == 7) list[0].v = inf; + if (r == 2 and s == 0) for (list[10..]) |*t| { + t.v = -inf; + }; + } + std.mem.sort(Tok, &list, {}, rankDesc); + // A shard short of 16 numbers: (-Inf, V) past them. + const real: usize = if (r % 2 == 1 and s == SHARDS - 1) KTOP - 4 else KTOP; + for (list[real..]) |*t| t.* = .{ .v = -inf, .c = VOCAB }; + const o = (r * SHARDS + s) * KTOP; + for (list, 0..) |t, m| { + self.ids[o + m] = @floatFromInt(t.c); + self.vals[o + m] = t.v; + } + }; + self.rig.reset(); + self.args = .{ + try self.rig.input(.int32, &.{ cint(shape.rows), SHARDS, KTOP }, self.ids), + try self.rig.input(.float32, &.{ cint(shape.rows), SHARDS, KTOP }, self.vals), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return 2 * mergeOuts(self.shape); + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + const half = mergeOuts(self.shape); + for (0..self.shape.rows) |r| { + var all: [SHARDS * KTOP]Tok = undefined; + for (&all, 0..) |*t, j| { + const at = r * SHARDS * KTOP + j; + t.* = .{ .v = self.vals[at], .c = tokU(self.ids[at]) }; + } + std.mem.sort(Tok, &all, {}, rankDesc); + for (all[0..KTOP], 0..) |t, m| { + want[r * KTOP + m] = @floatFromInt(t.c); + want[half + r * KTOP + m] = t.v; + } + } + for (want, mag) |w, *m| m.* = if (std.math.isFinite(w)) @abs(w) else 0; + } +}; + +// ── dflash_edges ── + +/// The selector's R x K x K lattice: rows = lanes, n = tree rows R, k = the rank. PRED and SUCC are the codebooks' +/// first TABLE rows (the kernel reads the rows its tokens name). Products of bf16 values are exact in f32: only the +/// sums, the soft cap's tanh and the softmax round. The planted control sums 255 of the 256 rank terms. +const Edges = struct { + rig: metal.Rig, + launch: *const metal.Launch = &edges_launch, + arena: std.heap.ArenaAllocator, + planted: bool = false, + shape: Shape = undefined, + t1: []f64 = &.{}, + cands: []f64 = &.{}, + unary: []f64 = &.{}, + proj: []f64 = &.{}, + pred: []f64 = &.{}, + succ: []f64 = &.{}, + errs: []f64 = &.{}, + note: [200]u8 = undefined, + args: [7]mlx.mlx_array = undefined, + + const Self = @This(); + + fn init(a: std.mem.Allocator, planted: bool) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a), .planted = planted }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(self: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.n == 0 or shape.n > BLOCK - 1 or shape.k != RANK) return null; + return edgesGeometry(shape.rows, shape.n, if (self.planted) RANK - 1 else RANK); + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const b = shape.rows; + const r = shape.n; + self.t1 = try a.alloc(f64, b); + for (self.t1) |*x| x.* = @floatFromInt(rng.uintLessThan(usize, TABLE)); + self.cands = try a.alloc(f64, b * r * KTOP); + for (self.cands) |*x| x.* = @floatFromInt(rng.uintLessThan(usize, TABLE)); + // A row's candidates' logits, descending as the top 16 hands them on. + self.unary = try a.alloc(f64, b * r * KTOP); + for (self.unary, 0..) |*x, i| x.* = f32of(18 - 0.3 * @as(f64, @floatFromInt(i % KTOP)) + 0.2 * rng.float(f64)); + self.proj = try host.uniform(a, rng, b * r * RANK, -1, 1, .bfloat16); + self.pred = try host.uniform(a, rng, TABLE * RANK, -0.5, 0.5, .bfloat16); + self.succ = try host.uniform(a, rng, TABLE * RANK, -0.5, 0.5, .bfloat16); + if (fill == .nonfinite) { + // A NaN candidate logit; a +Inf one (capped to the soft cap); a position with every one -Inf; one -Inf. + self.unary[3] = nan; + if (r > 1) self.unary[KTOP + 5] = inf; + if (r > 2) @memset(self.unary[2 * KTOP ..][0..KTOP], -inf); + if (b > 1) self.unary[r * KTOP] = -inf; + } + self.errs = try a.alloc(f64, b * r * KTOP * KTOP); + self.rig.reset(); + self.args = .{ + try self.rig.input(.int32, &.{cint(b)}, self.t1), + try self.rig.input(.int32, &.{ cint(b), cint(r), KTOP }, self.cands), + try self.rig.input(.float32, &.{ cint(b), cint(r), KTOP }, self.unary), + try self.rig.input(.bfloat16, &.{ cint(b), cint(r), RANK }, self.proj), + try self.rig.input(.bfloat16, &.{ TABLE, RANK }, self.pred), + try self.rig.input(.bfloat16, &.{ TABLE, RANK }, self.succ), + try self.rig.input(.float32, &.{1}, &.{SOFTCAP}), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return self.shape.rows * self.shape.n * KTOP * KTOP; + } + + /// Each probability and its error. A NaN score, or a position whose scores are all -Inf, makes the mass not a + /// number: the kernel then writes the uniform 1/K (its stated rule). + fn emit(self: *const Self, want: []f64, errs: []f64, sim: Sim) void { + const b_n = self.shape.rows; + const r = self.shape.n; + for (0..b_n) |b| for (0..r) |pos| for (0..KTOP) |pi| { + const o = ((b * r + pos) * KTOP + pi) * KTOP; + const out = want[o..][0..KTOP]; + const err = errs[o..][0..KTOP]; + @memset(err, 0); + if (pos == 0 and pi > 0) { + @memset(out, 0); + continue; + } + const prev = tokU(if (pos == 0) self.t1[b] else self.cands[(b * r + pos - 1) * KTOP + pi]); + const row = (b * r + pos) * RANK; + var sc: [KTOP]f64 = undefined; + var se: [KTOP]f64 = undefined; + var bad = false; + var mx = -inf; + var mx_e: f64 = 0; + for (0..KTOP) |s| { + const sid = tokU(self.cands[(b * r + pos) * KTOP + s]); + var t: [RANK]f64 = undefined; + for (&t, 0..) |*x, c| x.* = self.pred[prev * RANK + c] * self.proj[row + c] * self.succ[sid * RANK + c]; + const edge = if (sim) |x| spec.sumIn(x.acc, x.order, &t) else host.sum(&t); + const raw = self.unary[(b * r + pos) * KTOP + s] + edge; + const e_raw = spec.gamma(RANK + 5, U) * host.sumAbs(&t) + U * @abs(raw); + if (raw > -inf and std.math.isFinite(raw)) { + const th = std.math.tanh(raw / SOFTCAP); + sc[s] = SOFTCAP * th; + se[s] = (1 - th * th) * (e_raw + U * @abs(raw)) + (PRECISE + 2 * U) * @abs(sc[s]); + } else { + // +Inf caps to the soft cap exactly; -Inf and NaN pass as they are. + sc[s] = if (raw == inf) SOFTCAP else raw; + se[s] = 0; + } + if (std.math.isNan(sc[s])) bad = true else if (sc[s] > mx) { + mx = sc[s]; + mx_e = se[s]; + } + } + if (bad or mx == -inf) { + @memset(out, 1.0 / @as(f64, KTOP)); + continue; + } + var w: [KTOP]f64 = undefined; + var rel: [KTOP]f64 = undefined; + var m: f64 = 0; + for (&w, &rel, sc, se) |*x, *re, s, e| { + x.* = @exp(s - mx); + re.* = e + mx_e + PRECISE; + m += x.* * re.*; + } + const mass = total(sim, &w); + const mass_rel = (m + spec.gamma(KTOP, U) * mass) / mass; + for (out, err, w, rel) |*p, *e, x, re| { + p.* = x / mass; + e.* = p.* * (re + mass_rel + U); + } + }; + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + self.emit(want, self.errs, null); + for (mag, self.errs) |*m, e| m.* = host.allowance(e); + } + + pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { + const errs = try self.rig.a.alloc(f64, out.len); + defer self.rig.a.free(errs); + self.emit(out, errs, .{ .acc = acc, .order = order }); + } + + /// The stated rule (the uniform 1/K where the mass is not a number), and every probability within its error. + pub fn check(self: *Self, _: spec.Gate) !?[]const u8 { + const want = try self.arena.allocator().alloc(f64, self.count()); + self.emit(want, self.errs, null); + const bytes = self.rig.outputBytes(); + for (want, self.errs, 0..) |w, e, i| { + const got = spec.read(.f32, bytes, i); + if (!close(got, w, e)) return fail(&self.note, "probability {d}: {e} where float64 gives {e} (error {e})", .{ i, got, w, e }); + } + return null; + } +}; + +// ── dflash_tree ── + +fn treeTok(shape: Shape) usize { + return shape.rows * shape.n; +} + +fn treeMeta(shape: Shape) usize { + return 2 * shape.rows * shape.n; +} + +fn treeQ(shape: Shape) usize { + return shape.rows * shape.n * KTOP; +} + +fn treeDraws(shape: Shape) usize { + return 4 * shape.rows * shape.n; +} + +const tree_outs: []const spec.Part = &.{ .{ .elem = .u32, .count = treeTok }, .{ .elem = .u32, .count = treeTok }, .{ .elem = .u32, .count = treeMeta }, .{ .elem = .f32, .count = treeQ }, .{ .elem = .i8, .count = treeDraws }, .{ .elem = .f32, .count = treeTok } }; +/// The tree's outputs as `spec.readOut` reads them. +const tree_read: spec.Spec = .{ .name = "inkling2 dflash_tree", .accum = .none, .depth = none, .out = .u32, .outs = tree_outs, .served = &.{} }; + +const HCAP = 96; + +/// One lane's best-first build, as dflash_tree runs it, in float64; `ok` falls when a comparison of computed values +/// lies inside the device's error. +const Build = struct { + t: *const Tree, + l: usize, + sim: Sim, + ok: bool = true, + sampled: bool, + temp: f64, + copy_n: usize, + copy_r: f64, + tok: [16]f64 = undefined, + par: [16]f64 = undefined, + dep: [16]usize = undefined, + anc: [16]u32 = undefined, + on_copy: [16]bool = undefined, + q: [16]f64 = undefined, + qe: [16]f64 = undefined, + key: [16]u64 = undefined, + draw: [16][4]u8 = undefined, + placed: [16]usize = undefined, + next: [16][KTOP]f64 = undefined, + next_e: [16][KTOP]f64 = undefined, + h_score: [HCAP]f64 = undefined, + h_par: [HCAP]usize = undefined, + h_pos: [HCAP]usize = undefined, + h_idx: [HCAP]usize = undefined, + h_ord: [HCAP]usize = undefined, + h_size: usize = 0, + + fn gt(s: *Build, a: f64, b: f64) bool { + if (a != b and std.math.isFinite(a) and std.math.isFinite(b) and !clear(a, b)) s.ok = false; + return a > b; + } + + fn ge(s: *Build, a: f64, b: f64) bool { + if (a != b and std.math.isFinite(a) and std.math.isFinite(b) and !clear(a, b)) s.ok = false; + return a >= b; + } + + fn isStop(s: *const Build, tok: f64) bool { + for (s.t.stops[0..s.t.n_stops]) |x| if (x == tok) return true; + return false; + } + + fn cand(s: *const Build, pos: usize, i: usize) f64 { + return s.t.cands[(s.l * s.t.r + pos) * KTOP + i]; + } + + fn copyAt(s: *const Build, pos: usize) f64 { + return s.t.copy_ids[s.l * MAX_COPY + pos]; + } + + fn estProb(s: *const Build, q: f64, pos: usize) f64 { + const qc = std.math.clamp(q, f32of(1e-6), f32of(1 - f32of(1e-6))); + const lq = @log(qc / (1 - qc)); + const calib = s.t.calib[s.l * (1 + s.t.r) ..]; + const z = calib[0] * lq + calib[1 + pos]; + return 1 / (1 + @exp(-z)); + } + + fn gumbel(key: u64, tok: u32) f64 { + const h = mix64(key ^ (0xd1b54a32d192ed03 *% (@as(u64, tok) + 1))); + const u = (@as(f64, @floatFromInt(h >> 41)) + 0.5) * 0x1p-23; + return -@log(-@log(u)); + } + + fn push(s: *Build, sc: f64, par: usize, pos: usize, idx: usize, ord: usize) void { + if (s.h_size >= HCAP) return; + var cur = s.h_size; + s.h_size += 1; + while (cur > 0) { + const p = (cur - 1) >> 1; + if (s.ge(s.h_score[p], sc)) break; + s.h_score[cur] = s.h_score[p]; + s.h_par[cur] = s.h_par[p]; + s.h_pos[cur] = s.h_pos[p]; + s.h_idx[cur] = s.h_idx[p]; + s.h_ord[cur] = s.h_ord[p]; + cur = p; + } + s.h_score[cur] = sc; + s.h_par[cur] = par; + s.h_pos[cur] = pos; + s.h_idx[cur] = idx; + s.h_ord[cur] = ord; + } + + const Entry = struct { sc: f64, par: usize, pos: usize, idx: usize, ord: usize }; + + fn pop(s: *Build) Entry { + const top: Entry = .{ .sc = s.h_score[0], .par = s.h_par[0], .pos = s.h_pos[0], .idx = s.h_idx[0], .ord = s.h_ord[0] }; + s.h_size -= 1; + if (s.h_size > 0) { + const n = s.h_size; + const last: Entry = .{ .sc = s.h_score[n], .par = s.h_par[n], .pos = s.h_pos[n], .idx = s.h_idx[n], .ord = s.h_ord[n] }; + var cur: usize = 0; + while (true) { + const l = cur * 2 + 1; + if (l >= n) break; + const r = l + 1; + const best = if (r < n and s.gt(s.h_score[r], s.h_score[l])) r else l; + if (s.ge(last.sc, s.h_score[best])) break; + s.h_score[cur] = s.h_score[best]; + s.h_par[cur] = s.h_par[best]; + s.h_pos[cur] = s.h_pos[best]; + s.h_idx[cur] = s.h_idx[best]; + s.h_ord[cur] = s.h_ord[best]; + cur = best; + } + s.h_score[cur] = last.sc; + s.h_par[cur] = last.par; + s.h_pos[cur] = last.pos; + s.h_idx[cur] = last.idx; + s.h_ord[cur] = last.ord; + } + return top; + } + + fn expand(s: *Build, row: usize, pos: usize, pred_i: usize, path: f64) void { + const t = s.t; + if (pos >= t.r) return; + const q = t.probs[((s.l * t.r + pos) * KTOP + pred_i) * KTOP ..][0..KTOP]; + var top: f64 = 0; + for (q) |x| if (x > top) { + top = x; + }; + var wt: [KTOP]f64 = undefined; + var rel: [KTOP]f64 = undefined; + for (&wt, &rel, q) |*w, *re, x| { + if (!s.sampled or !(x > 0)) { + w.* = x; + re.* = 0; + continue; + } + const d = @log(x) - @log(top); + const z = d / s.temp; + w.* = @exp(z); + re.* = (fastLogErr(x) + fastLogErr(top) + U * @abs(d)) / s.temp + U * @abs(z) + host.fastExp(z) + U; + } + const mass = total(s.sim, &wt); + if (mass > 0) { + var m: f64 = 0; + for (wt, rel) |w, re| m += w * re; + const mass_rel = (m + spec.gamma(KTOP, U) * mass) / mass; + for (&s.next[row], &s.next_e[row], wt, rel) |*n, *e, w, re| { + n.* = w / mass; + e.* = n.* * (re + mass_rel + U); + } + } else for (&s.next[row], &s.next_e[row], wt) |*n, *e, w| { + n.* = w; + e.* = 0; + } + var gkey: [KTOP]f64 = undefined; + if (s.sampled) for (&gkey, s.next[row], 0..) |*g, n, i| { + g.* = if (n > 0) @log(n) + gumbel(s.key[row], tokU(s.cand(pos, i))) else -inf; + }; + const has_copy = s.on_copy[row] and pos < s.copy_n; + const copy_tok: f64 = if (has_copy) s.copyAt(pos) else -1; + const c_rate = if (has_copy) s.copy_r else 0; + var taken: u32 = 0; + var bound = path; + var left = 1 - c_rate; + var reserved = c_rate; + var joined = false; + for (0..@min(t.max_ch, 4)) |ch| { + var picked: usize = KTOP; + for (0..KTOP) |i| { + if (taken & (@as(u32, 1) << @intCast(i)) != 0) continue; + if (!s.sampled) { + if (!(q[i] > 0)) continue; + if (picked == KTOP or q[i] > q[picked] or (t.planted and q[i] == q[picked])) picked = i; + } else { + if (!(gkey[i] > -inf)) continue; + if (picked == KTOP or s.gt(gkey[i], gkey[picked])) picked = i; + } + } + if (picked == KTOP) break; + taken |= @as(u32, 1) << @intCast(picked); + const tok = s.cand(pos, picked); + if (!s.sampled and s.isStop(tok)) continue; + const joins = has_copy and tok == copy_tok; + if (joins) joined = true; + const cap = if (joins) left + reserved else left; + const own = @min(s.estProb(s.next[row][picked], pos), @max(cap, 0)); + const eff = if (joins) @max(own, reserved) else own; + left = if (joins) @max(0, cap - eff) else @max(0, left - own); + if (joins) reserved = 0; + bound = @min(bound, path * eff); + s.draw[row][ch] = @intCast(picked); + s.push(bound, row, pos, picked, ch); + } + if (has_copy and !joined and !s.sampled and !s.isStop(copy_tok)) s.push(path * c_rate, row, pos, 255, 255); + } + + fn run(s: *Build) void { + const t = s.t; + const t1 = t.t1[s.l]; + const seed0 = t.seeds[s.l]; + for (0..16) |i| { + s.tok[i] = t1; + s.par[i] = -1; + s.dep[i] = 0; + s.anc[i] = 1; + s.on_copy[i] = false; + s.q[i] = -1; + s.qe[i] = 0; + s.key[i] = seed0; + s.placed[i] = 0; + s.draw[i] = @splat(255); + s.next[i] = @splat(0); + s.next_e[i] = @splat(0); + } + s.on_copy[0] = s.copy_n > 0; + s.q[0] = 1; + const want_w = @min(t.w, t.want_w); + var made: usize = 1; + if (want_w > 1) s.expand(0, 0, 0, 1.0); + while (s.h_size > 0 and made < want_w) { + const e = s.pop(); + if (s.sampled and e.ord != 255 and e.ord != s.placed[e.par]) continue; + const row = made; + made += 1; + const is_copy = e.idx == 255; + const tok = if (is_copy) s.copyAt(e.pos) else s.cand(e.pos, e.idx); + s.tok[row] = tok; + s.par[row] = @floatFromInt(e.par); + s.dep[row] = e.pos + 1; + s.anc[row] = s.anc[e.par] | (@as(u32, 1) << @intCast(row)); + s.on_copy[row] = s.on_copy[e.par] and e.pos < s.copy_n and tok == s.copyAt(e.pos); + s.q[row] = if (is_copy) -1 else s.next[e.par][e.idx]; + s.qe[row] = if (is_copy) 0 else s.next_e[e.par][e.idx]; + s.key[row] = mix64(s.key[e.par] +% 0x9e3779b97f4a7c15 *% (@as(u64, tokU(tok)) + 1)); + if (e.ord != 255) s.placed[e.par] = e.ord + 1; + if (!s.isStop(tok)) { + if (!is_copy and e.pos + 1 < t.r) { + s.expand(row, e.pos + 1, e.idx, e.sc); + } else if (s.on_copy[row] and e.pos + 1 < s.copy_n and !s.sampled) { + if (!s.isStop(s.copyAt(e.pos + 1))) s.push(e.sc * s.copy_r, row, e.pos + 1, 255, 255); + } + } + } + for (0..t.w) |row| for (s.placed[row]..4) |ch| { + s.draw[row][ch] = 255; + }; + } +}; + +/// The draft tree builder: rows = lanes, n = the tree's width (verify rows), k = 16. Even lanes greedy, odd lanes +/// sampled at 0.8; lattices from softmaxes of random scores; copy chains on some lanes, joining a candidate at some +/// depths; one stop id among the candidates. Inputs are redrawn until every comparison of computed path scores and +/// Gumbel keys clears the device's error. Lane 0's root holds two equal best probabilities (the lower index is drawn +/// first; the planted control draws the higher). +const Tree = struct { + rig: metal.Rig, + launch: *const metal.Launch = &tree_launch, + arena: std.heap.ArenaAllocator, + planted: bool = false, + shape: Shape = undefined, + w: usize = 0, + r: usize = 0, + t1: []f64 = &.{}, + cands: []f64 = &.{}, + probs: []f64 = &.{}, + calib: []f64 = &.{}, + temps: []f64 = &.{}, + seeds: []u64 = &.{}, + copy_ids: []f64 = &.{}, + copy_len: []f64 = &.{}, + copy_rate: []f64 = &.{}, + stops: [MAX_STOPS]f64 = @splat(-1), + n_stops: usize = 0, + max_ch: usize = MAX_CH, + want_w: usize = 0, + errs: []f64 = &.{}, + note: [240]u8 = undefined, + args: [11]mlx.mlx_array = undefined, + + const Self = @This(); + const intercepts = [8]f64{ 0.0, -0.35, -0.8, -0.75, -0.75, -0.85, -0.45, -0.45 }; + + fn init(a: std.mem.Allocator, planted: bool) Self { + return .{ .rig = metal.Rig.init(a), .arena = .init(a), .planted = planted }; + } + + pub fn deinit(self: *Self) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(_: *const Self, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.n < 2 or shape.n > 16 or shape.k != KTOP) return null; + return treeGeometry(shape.rows, shape.n, rowsOf(shape.n)); + } + + fn fillInputs(self: *Self, rng: std.Random, fill: spec.Fill) void { + const b = self.shape.rows; + const r = self.r; + for (0..b) |l| { + self.t1[l] = @floatFromInt(5000 + l); + self.temps[l] = if (l % 2 == 1) f32of(0.8) else 0; + self.seeds[l] = rng.int(u64); + self.calib[l * (1 + r)] = f32of(0.7); + for (0..r) |p| self.calib[l * (1 + r) + 1 + p] = f32of(intercepts[@min(p, 7)]); + for (0..r) |pos| for (0..KTOP) |i| { + self.cands[(l * r + pos) * KTOP + i] = @floatFromInt(100 + l * 1000 + pos * KTOP + i); + }; + // Copy chains on every third lane, joining the candidates at some depths. + const cn: usize = if (l % 3 == 2) 1 + rng.uintLessThan(usize, MAX_COPY) else 0; + self.copy_len[l] = @floatFromInt(cn); + self.copy_rate[l] = f32of(0.9); + for (0..MAX_COPY) |p| self.copy_ids[l * MAX_COPY + p] = if (p >= cn) 0 else if (p < r and rng.boolean()) self.cands[(l * r + p) * KTOP + rng.uintLessThan(usize, 4)] else @floatFromInt(90000 + p); + for (0..r) |pos| for (0..KTOP) |pi| { + const o = ((l * r + pos) * KTOP + pi) * KTOP; + if (pos == 0 and pi > 0) { + @memset(self.probs[o..][0..KTOP], 0); + continue; + } + var sc: [KTOP]f64 = undefined; + var s: f64 = 0; + for (&sc) |*x| { + x.* = @exp(1.5 * rng.floatNorm(f64)); + s += x.*; + } + for (sc, 0..) |x, i| self.probs[o + i] = f32of(x / s); + }; + } + // Lane 0's root: candidates 2 and 5 tie at its best probability. + const root = self.probs[0..KTOP]; + var best: f64 = 0; + for (root) |x| best = @max(best, x); + root[2] = best; + root[5] = best; + self.copy_len[0] = 0; + // A stop id among lane 0's depth-1 candidates (greedy skips it), and one no candidate carries. + self.stops = @splat(-1); + self.stops[0] = if (r > 1) self.cands[KTOP + 1] else 99999; + self.stops[1] = 99998; + self.n_stops = 2; + self.want_w = self.w; + // Gate 1: NaN and -Inf probabilities in greedy lanes' rows the build expands (their rows' weights then stay + // unnormalized, and they are never drawn). + if (fill == .nonfinite) { + self.probs[3] = nan; + self.probs[7] = -inf; + if (b > 2 and r > 1) for (0..KTOP) |pi| { + self.probs[((2 * r + 1) * KTOP + pi) * KTOP + 4] = nan; + }; + } + } + + fn lanes(self: *const Self, out_ok: *bool, want: []f64, errs: []f64, sim: Sim) void { + const shape = self.shape; + const b_n = shape.rows; + const w = self.w; + const nt = treeTok(shape); + const tok_at = want[0..nt]; + const par_at = want[nt..][0..nt]; + const meta_at = want[2 * nt ..][0..treeMeta(shape)]; + const q_at = want[4 * nt ..][0..treeQ(shape)]; + const d_at = want[4 * nt + treeQ(shape) ..][0..treeDraws(shape)]; + const s_at = want[8 * nt + treeQ(shape) ..][0..nt]; + @memset(errs, 0); + const qe_at = errs[4 * nt ..][0..treeQ(shape)]; + const se_at = errs[8 * nt + treeQ(shape) ..][0..nt]; + for (0..b_n) |l| { + var s: Build = .{ + .t = self, + .l = l, + .sim = sim, + .sampled = self.temps[l] > 0, + .temp = self.temps[l], + .copy_n = tokU(@max(0, self.copy_len[l])), + .copy_r = self.copy_rate[l], + }; + s.run(); + if (!s.ok) out_ok.* = false; + for (0..w) |row| { + const at = l * w + row; + tok_at[at] = s.tok[row]; + // -1 read as the u32 it is stored as. + par_at[at] = if (s.par[row] < 0) 4294967295 else s.par[row]; + meta_at[2 * at] = @floatFromInt(s.dep[row]); + meta_at[2 * at + 1] = @floatFromInt(s.anc[row]); + for (0..KTOP) |k| { + q_at[at * KTOP + k] = s.next[row][k]; + qe_at[at * KTOP + k] = s.next_e[row][k]; + } + for (0..4) |ch| d_at[at * 4 + ch] = if (s.draw[row][ch] == 255) -1 else @floatFromInt(s.draw[row][ch]); + s_at[at] = s.q[row]; + se_at[at] = s.qe[row]; + } + } + } + + pub fn prepare(self: *Self, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + self.w = shape.n; + self.r = rowsOf(shape.n); + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const b = shape.rows; + const r = self.r; + self.t1 = try a.alloc(f64, b); + self.cands = try a.alloc(f64, b * r * KTOP); + self.probs = try a.alloc(f64, b * r * KTOP * KTOP); + self.calib = try a.alloc(f64, b * (1 + r)); + self.temps = try a.alloc(f64, b); + self.seeds = try a.alloc(u64, b); + self.copy_ids = try a.alloc(f64, b * MAX_COPY); + self.copy_len = try a.alloc(f64, b); + self.copy_rate = try a.alloc(f64, b); + self.errs = try a.alloc(f64, self.count()); + const want = try a.alloc(f64, self.count()); + var tries: usize = 0; + while (true) : (tries += 1) { + if (tries == 256) return error.NoClearTree; + self.fillInputs(rng, fill); + var ok = true; + self.lanes(&ok, want, self.errs, null); + if (ok) break; + } + const seeds = try a.alloc(f64, 2 * b); + for (self.seeds, 0..) |x, l| seeds[2 * l ..][0..2].* = .{ @floatFromInt(@as(u32, @truncate(x))), @floatFromInt(@as(u32, @truncate(x >> 32))) }; + self.rig.reset(); + self.args = .{ + try self.rig.input(.int32, &.{cint(b)}, self.t1), + try self.rig.input(.int32, &.{ cint(b), cint(r), KTOP }, self.cands), + try self.rig.input(.float32, &.{ cint(b), cint(r), KTOP, KTOP }, self.probs), + try self.rig.input(.float32, &.{ cint(b), cint(1 + r) }, self.calib), + try self.rig.input(.float32, &.{cint(b)}, self.temps), + try self.rig.input(.uint32, &.{ cint(b), 2 }, seeds), + try self.rig.input(.int32, &.{ cint(b), MAX_COPY }, self.copy_ids), + try self.rig.input(.int32, &.{cint(b)}, self.copy_len), + try self.rig.input(.float32, &.{cint(b)}, self.copy_rate), + try self.rig.input(.int32, &.{MAX_STOPS}, &self.stops), + try self.rig.input(.int32, &.{3}, &.{ @as(f64, @floatFromInt(self.n_stops)), @as(f64, @floatFromInt(self.max_ch)), @as(f64, @floatFromInt(self.want_w)) }), + }; + return true; + } + + pub fn run(self: *Self) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const Self) usize { + return 4 * treeTok(self.shape) + treeQ(self.shape) + treeDraws(self.shape) + treeTok(self.shape); + } + + pub fn reference(self: *const Self, want: []f64, mag: []f64) !void { + var ok = true; + self.lanes(&ok, want, self.errs, null); + for (mag, self.errs) |*m, e| m.* = host.allowance(e); + } + + pub fn simulate(self: *const Self, acc: spec.Accum, order: spec.Order, out: []f64) !void { + const errs = try self.rig.a.alloc(f64, out.len); + defer self.rig.a.free(errs); + var ok = true; + self.lanes(&ok, out, errs, .{ .acc = acc, .order = order }); + } + + /// The stated rule: tokens, parents, depths, ancestor masks and draws exact; each node's next-position q and + /// score within its f32 and fast-math error, NaN or -Inf where a greedy row's planted probability leaves its + /// weights unnormalized. + pub fn check(self: *Self, _: spec.Gate) !?[]const u8 { + const n = self.count(); + const want = try self.arena.allocator().alloc(f64, n); + var ok = true; + self.lanes(&ok, want, self.errs, null); + const bytes = self.rig.outputBytes(); + for (want, self.errs, 0..) |w, e, i| { + const o = spec.readOut(tree_read, self.shape, bytes, i); + const good = if (o.elem == .f32) close(o.v, w, e) else o.v == w; + if (!good) return fail(&self.note, "output {d}: {d} where the build gives {d}", .{ i, o.v, w }); + } + return null; + } +}; + +// ── registrations ── + +const served_accept: []const Shape = &.{ .{ .rows = 1, .n = 8, .k = 1 }, .{ .rows = 2, .n = 8, .k = 1 }, .{ .rows = 4, .n = 5, .k = 1 }, .{ .rows = 8, .n = 6, .k = 1 }, .{ .rows = 16, .n = 4, .k = 1 } }; +// One lane, four lanes on the padded head's stride, sixteen sampled lanes, sixteen greedy lanes (`plugin.treeWidth`). +const served_sample: []const Shape = &.{ .{ .rows = 1, .n = 8, .k = VOCAB }, .{ .rows = 4, .n = 5, .k = HEAD_ROWS }, .{ .rows = 16, .n = 4, .k = VOCAB }, .{ .rows = 16, .n = 6, .k = VOCAB } }; +const served_conv: []const Shape = &.{ .{ .rows = 1, .n = BLOCK, .k = HIDDEN }, .{ .rows = 4, .n = BLOCK, .k = HIDDEN }, .{ .rows = 16, .n = BLOCK, .k = HIDDEN } }; +// A draft's block rows past the anchor: one lane at width 8, four at 5, sixteen at 6 (`plugin.treeWidth`). +const served_shard: []const Shape = &.{ .{ .rows = 7, .n = HEAD_ROWS, .k = VOCAB }, .{ .rows = 4 * 4, .n = HEAD_ROWS, .k = VOCAB }, .{ .rows = 16 * 5, .n = HEAD_ROWS, .k = VOCAB } }; +const served_merge: []const Shape = &.{ .{ .rows = 7, .n = SHARDS, .k = KTOP }, .{ .rows = 4 * 4, .n = SHARDS, .k = KTOP }, .{ .rows = 16 * 5, .n = SHARDS, .k = KTOP } }; +const served_edges: []const Shape = &.{ .{ .rows = 1, .n = 7, .k = RANK }, .{ .rows = 2, .n = 7, .k = RANK }, .{ .rows = 4, .n = 4, .k = RANK }, .{ .rows = 16, .n = 5, .k = RANK }, .{ .rows = 16, .n = 3, .k = RANK } }; +const served_tree: []const Shape = &.{ .{ .rows = 1, .n = 8, .k = KTOP }, .{ .rows = 2, .n = 8, .k = KTOP }, .{ .rows = 4, .n = 5, .k = KTOP }, .{ .rows = 16, .n = 6, .k = KTOP }, .{ .rows = 16, .n = 4, .k = KTOP } }; + +const sampled_sums: spec.Sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "sums of exps: the stress inputs check the fp32 sums within the float64 bound" }; + +fn sampleSpec(comptime what: []const u8, comptime masked: bool, stage: Stage) spec.Spec { + return .{ + .name = "inkling2 " ++ what ++ " bf16" ++ (if (masked) " (suppress mask)" else ""), + // The draw's sums only pick a token: no output value for gate 4 to bound. + .accum = if (stage == .draw) .none else .f32, + .depth = host.depthOne, + .out = if (stage == .draw) .u32 else .f32, + .nan = .{ .stated = switch (stage) { + .mass => "a NaN or -Inf logit is never admitted; a sampled shard's +Inf makes its sum exp(Inf - Inf), NaN", + .search => "a row whose mass is not a number keeps its max alone (its cut the max, its mass 1)", + .draw => "a NaN or -Inf logit is never drawn; a +Inf one, kept alone, is drawn", + } }, + .served = served_sample, + .sums = sampled_sums, + }; +} + +pub fn register(set: *kc.Set) !void { + const a = set.a; + try set.add(AcceptTree, .init(a, false), .{ + .name = "inkling2 accept_tree", + .accum = .none, + .depth = none, + .out = .u32, + .nan = .{ .stated = "integer tokens carry no NaN: gate 1 plants stop ids in the selections, which end a walk" }, + .served = served_accept, + }, null); + inline for (.{ false, true }) |masked| try set.add(Sample, .init(a, .mass, masked, false), sampleSpec("sample_tree_mass", masked, .mass), null); + inline for (.{ false, true }) |masked| try set.add(Sample, .init(a, .search, masked, false), sampleSpec("sample_tree_search", masked, .search), null); + inline for (.{ false, true }) |masked| try set.add(Sample, .init(a, .draw, masked, false), sampleSpec("sample_tree_draw", masked, .draw), null); + const conv_sums: spec.Sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "two taps of two products: a half sum's miss stays near the bf16 output's rounding" }; + try set.add(Conv(0), .init(a, false), .{ .name = "inkling2 dflash_conv bf16 (prepare)", .accum = .f32, .depth = host.depthOne, .out = .bf16, .served = served_conv, .sums = conv_sums }, null); + try set.add(Conv(1), .init(a, false), .{ .name = "inkling2 dflash_conv bf16 (finish + residual)", .accum = .f32, .depth = host.depthOne, .out = .bf16, .served = served_conv, .sums = conv_sums }, null); + const shard_outs: []const spec.Part = &.{ .{ .elem = .u32, .count = shardOuts }, .{ .elem = .f32, .count = shardOuts } }; + const merge_outs: []const spec.Part = &.{ .{ .elem = .u32, .count = mergeOuts }, .{ .elem = .f32, .count = mergeOuts } }; + try set.add(Shard, .init(a, false), .{ .name = "inkling2 dflash_top16_shard bf16", .accum = .none, .depth = none, .out = .f32, .outs = shard_outs, .served = served_shard }, null); + try set.add(Merge, .init(a, false), .{ .name = "inkling2 dflash_top16_merge", .accum = .none, .depth = none, .out = .f32, .outs = merge_outs, .served = served_merge }, null); + const edges_spec: spec.Spec = .{ + .name = "inkling2 dflash_edges bf16", + .accum = .f32, + .depth = host.depthOne, + .out = .f32, + .nan = .{ .stated = "a NaN score, or a position whose scores are all -Inf, gives the uniform 1/K; +Inf caps to the soft cap" }, + .served = served_edges, + .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "the edge's sum passes a tanh and an exp: the stress inputs check the fp32 sums within the float64 bound" }, + }; + try set.add(Edges, .init(a, false), edges_spec, null); + const tree_spec: spec.Spec = .{ + .name = "inkling2 dflash_tree", + .accum = .f32, + .depth = host.depthOne, + .out = .u32, + .outs = tree_outs, + .nan = .{ .stated = "a NaN or -Inf probability is never drawn; its row's weights stay unnormalized" }, + .served = served_tree, + .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = "16 weights a row, then a divide: the stress inputs check the fp32 sums within the float64 bound" }, + }; + try set.add(Tree, .init(a, false), tree_spec, null); + + // Planted controls: each must go red at gate 3. + try set.add(AcceptTree, .init(a, true), .{ .name = "control inkling2 accept_tree matching the later of two equal children", .accum = .none, .depth = none, .out = .u32, .nan = .{ .stated = "integers" }, .served = &.{.{ .rows = 4, .n = 5, .k = 1 }} }, .shapes); + var mass_c = sampleSpec("sample_tree_mass", true, .mass); + mass_c.name = "control inkling2 sample_tree_mass breaking a max's tie toward the higher id"; + mass_c.served = served_sample[0..1]; + try set.add(Sample, .init(a, .mass, true, true), mass_c, .shapes); + var search_c = sampleSpec("sample_tree_search", false, .search); + search_c.name = "control inkling2 sample_tree_search keeping one token past its top-k"; + search_c.served = &.{.{ .rows = 8, .n = 5, .k = VOCAB }}; + try set.add(Sample, .init(a, .search, false, true), search_c, .shapes); + var draw_c = sampleSpec("sample_tree_draw", false, .draw); + draw_c.name = "control inkling2 sample_tree_draw taking the token after its uniform's"; + draw_c.served = &.{.{ .rows = 8, .n = 5, .k = VOCAB }}; + try set.add(Sample, .init(a, .draw, false, true), draw_c, .shapes); + try set.add(Conv(1), .init(a, true), .{ .name = "control inkling2 dflash_conv dropping its second tap", .accum = .f32, .depth = host.depthOne, .out = .bf16, .served = served_conv[1..2], .sums = conv_sums }, .shapes); + try set.add(Shard, .init(a, true), .{ .name = "control inkling2 dflash_top16_shard ranking a tie's higher id first", .accum = .none, .depth = none, .out = .f32, .outs = shard_outs, .served = served_shard[0..1] }, .shapes); + try set.add(Merge, .init(a, true), .{ .name = "control inkling2 dflash_top16_merge over 15 of its 16 shards", .accum = .none, .depth = none, .out = .f32, .outs = merge_outs, .served = served_merge[0..1] }, .shapes); + var edges_c = edges_spec; + edges_c.name = "control inkling2 dflash_edges summing 255 of its 256 rank terms"; + edges_c.served = served_edges[2..3]; + try set.add(Edges, .init(a, true), edges_c, .shapes); + var tree_c = tree_spec; + tree_c.name = "control inkling2 dflash_tree drawing a tie's higher index first"; + tree_c.served = served_tree[2..3]; + try set.add(Tree, .init(a, true), tree_c, .shapes); +} + +// ── the drift guard: each declared launch is the shipped wrapper's ── + +fn ptr(comptime T: type, k: kc.gates.Kernel) *T { + return @ptrCast(@alignCast(k.ctx)); +} + +/// Checks this file's declared launches against the shipped wrappers, byte for byte, at served shapes: `items` are +/// `register`'s registrations, in its order. `dflash_conv`'s stages against `Drafter.prepare` and +/// `finishAdd`; the top 16's shard and merge chained against `topCandidates`; shard, merge, edges and tree chained +/// against `buildTreeFromLogits`; mass, search, draw and accept chained against `sampleAndAcceptTree`. +pub fn checkWrappers(a: std.mem.Allocator, items: []const kc.gates.Kernel) !void { + try checkConv(a, ptr(Conv(0), items[7]), ptr(Conv(1), items[8])); + try checkTop(a, ptr(Shard, items[9]), ptr(Merge, items[10])); + try checkTree(a, ptr(Shard, items[9]), ptr(Merge, items[10]), ptr(Edges, items[11]), ptr(Tree, items[12])); + inline for (.{ false, true }) |masked| { + const m: usize = @intFromBool(masked); + try checkSample(a, ptr(Sample, items[1 + m]), ptr(Sample, items[3 + m]), ptr(Sample, items[5 + m]), ptr(AcceptTree, items[0])); + } +} + +fn checkConv(a: std.mem.Allocator, prep: *Conv(0), fin: *Conv(1)) !void { + for (served_conv) |shape| { + // finishAdd: its inputs are the kernel's. + try std.testing.expect(try fin.prepare(shape, .random, 7)); + try fin.run(); + const ours = try a.dupe(u8, fin.rig.outputBytes()); + defer a.free(ours); + var g = ops.Graph.init(a, fin.rig.stream()); + defer g.deinit(); + const d = testDrafter(fin.rig.stream(), HIDDEN); + const conv: dflash2.Conv = .{ .base = fin.args[2], .proj = .{} }; + try std.testing.expectEqualSlices(u8, try fin.rig.bytesOf(&.{try d.finishAdd(&g, &conv, fin.args[0], fin.args[1], fin.args[3])}), ours); + + // prepare: the dynamic kernels are its own projection of the input; the declared launch runs on them. + try std.testing.expect(try prep.prepare(shape, .random, 7)); + var pg = ops.Graph.init(a, prep.rig.stream()); + defer pg.deinit(); + const G = HIDDEN / CONV_GS; + var prng = std.Random.DefaultPrng.init(11); + const w = try host.uniform(a, prng.random(), 2 * CONV_KT * G * HIDDEN, -0.05, 0.05, .float32); + defer a.free(w); + const w32 = try a.alloc(f32, w.len); + defer a.free(w32); + for (w32, w) |*o, x| o.* = @floatCast(x); + const pconv: dflash2.Conv = .{ .base = prep.args[2], .proj = .{ .w = try pg.astype(try pg.fromSlice(f32, w32, &.{ 2 * CONV_KT * G, HIDDEN }), .bfloat16) } }; + const pd = testDrafter(prep.rig.stream(), HIDDEN); + const got = try pd.prepare(&pg, &pconv, prep.args[0]); + const theirs = try a.dupe(u8, try prep.rig.bytesOf(&.{got.out})); + defer a.free(theirs); + try prep.rig.launch(prep.launch, prep.geometry(shape).?, &.{ prep.args[0], got.kernel, prep.args[2], prep.args[0] }); + try std.testing.expectEqualSlices(u8, theirs, prep.rig.outputBytes()); + } +} + +fn checkTop(a: std.mem.Allocator, shard: *Shard, merge: *Merge) !void { + for (served_shard) |shape| { + try std.testing.expect(try shard.prepare(shape, .random, 7)); + try shard.run(); + try merge.rig.launch(merge.launch, mergeGeometry(shape.rows, SHARDS), &.{ shard.rig.output(0), shard.rig.output(1) }); + const ours = try a.dupe(u8, merge.rig.outputBytes()); + defer a.free(ours); + var g = ops.Graph.init(a, shard.rig.stream()); + defer g.deinit(); + const d = testDrafter(shard.rig.stream(), 64); + const top = try d.topCandidates(&g, try g.reshape(shard.args[0], &.{ 1, cint(shape.rows), cint(shape.n) }), cint(shape.k)); + try std.testing.expectEqualSlices(u8, try shard.rig.bytesOf(&top), ours); + } +} + +fn checkTree(a: std.mem.Allocator, shard: *Shard, merge: *Merge, edges: *Edges, tree: *Tree) !void { + const b = 4; + const w = 5; + const r = comptime rowsOf(w); + const h = 64; + const v = TABLE; + const stride = TABLE + 76; + var prng = std.Random.DefaultPrng.init(0x7ee); + const rng = prng.random(); + const s = shard.rig.stream(); + var g = ops.Graph.init(a, s); + defer g.deinit(); + const randoms = struct { + fn make(gr: *ops.Graph, al: std.mem.Allocator, rn: std.Random, n: usize, scale: f32, sh: []const c_int) !mlx.mlx_array { + const buf = try al.alloc(f32, n); + defer al.free(buf); + for (buf) |*x| x.* = rn.floatNorm(f32) * scale; + return gr.astype(try gr.fromSlice(f32, buf, sh), .bfloat16); + } + }; + var d = testDrafter(s, h); + d.pred = try randoms.make(&g, a, rng, v * RANK, 0.3, &.{ v, RANK }); + d.succ = try randoms.make(&g, a, rng, v * RANK, 0.3, &.{ v, RANK }); + d.sel = .{ .w = try randoms.make(&g, a, rng, RANK * h, 0.2, &.{ RANK, h }) }; + const rows = try randoms.make(&g, a, rng, b * r * h, 0.5, &.{ b, r, h }); + const logits = try randoms.make(&g, a, rng, b * r * stride, 2.0, &.{ b, r, stride }); + const copy = [_]u32{ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; + const lanes = [b]dflash2.Drafter.TreeLane{ + .{ .t1 = 5, .anchor = .{}, .taps = .{}, .position = 10, .cache = null, .temperature = 0, .seed = 1, .copy = ©, .copy_rate = 0.9 }, + .{ .t1 = 9, .anchor = .{}, .taps = .{}, .position = 10, .cache = null, .temperature = 0.8, .seed = 42 }, + .{ .t1 = 33, .anchor = .{}, .taps = .{}, .position = 12, .cache = null, .temperature = 0, .seed = 3 }, + .{ .t1 = 70, .anchor = .{}, .taps = .{}, .position = 14, .cache = null, .temperature = 1.0, .seed = 77 }, + }; + const stops = [_]u32{2}; + const tb = try d.buildTreeFromLogits(&g, &lanes, rows, logits, v, w, MAX_CH, &stops); + const theirs = try a.dupe(u8, try tree.rig.bytesOf(&.{ tb.tokens, tb.parent, tb.tmeta, tb.next_q, tb.draws, tb.scores })); + defer a.free(theirs); + + // The same chain through the declared launches, the host arrays built as `buildTreeFromLogits` builds them. + try shard.rig.launch(shard.launch, shardGeometry(b * r, stride, v), &.{try g.reshape(logits, &.{ b * r, stride })}); + try merge.rig.launch(merge.launch, mergeGeometry(b * r, SHARDS), &.{ shard.rig.output(0), shard.rig.output(1) }); + const cands = try g.reshape(merge.rig.output(0), &.{ b, r, KTOP }); + const unary = try g.reshape(merge.rig.output(1), &.{ b, r, KTOP }); + var t1: [b]i32 = undefined; + var calib: [b * (1 + r)]f32 = undefined; + var temps: [b]f32 = undefined; + var seeds: [2 * b]u32 = undefined; + var copy_ids: [b * MAX_COPY]i32 = @splat(0); + var copy_len: [b]i32 = @splat(0); + var copy_rate: [b]f32 = @splat(0); + for (lanes, 0..) |lane, i| { + t1[i] = @intCast(lane.t1); + calib[i * (1 + r)] = lane.calib_slope; + for (0..r) |p| calib[i * (1 + r) + 1 + p] = lane.calib_intercepts[@min(p, lane.calib_intercepts.len - 1)]; + temps[i] = lane.temperature; + seeds[2 * i] = @truncate(lane.seed); + seeds[2 * i + 1] = @truncate(lane.seed >> 32); + const cn = @min(lane.copy.len, MAX_COPY); + copy_len[i] = @intCast(cn); + copy_rate[i] = lane.copy_rate; + for (0..cn) |j| copy_ids[i * MAX_COPY + j] = @intCast(lane.copy[j]); + } + var stop_buf: [MAX_STOPS]i32 = @splat(-1); + stop_buf[0] = @intCast(stops[0]); + const t1_arr = try g.fromSlice(i32, &t1, &.{b}); + const proj = try project(&g, &d.sel, rows); + try edges.rig.launch(edges.launch, edgesGeometry(b, r, RANK), &.{ t1_arr, cands, unary, proj, d.pred, d.succ, try g.fromSlice(f32, &[_]f32{@floatCast(SOFTCAP)}, &.{1}) }); + try tree.rig.launch(tree.launch, treeGeometry(b, w, r), &.{ + t1_arr, + cands, + edges.rig.output(0), + try g.fromSlice(f32, &calib, &.{ b, 1 + r }), + try g.fromSlice(f32, &temps, &.{b}), + try g.fromSlice(u32, &seeds, &.{ b, 2 }), + try g.fromSlice(i32, ©_ids, &.{ b, MAX_COPY }), + try g.fromSlice(i32, ©_len, &.{b}), + try g.fromSlice(f32, ©_rate, &.{b}), + try g.fromSlice(i32, &stop_buf, &.{MAX_STOPS}), + try g.fromSlice(i32, &.{ 1, MAX_CH, w }, &.{3}), + }); + try std.testing.expectEqualSlices(u8, theirs, tree.rig.outputBytes()); +} + +fn checkSample(a: std.mem.Allocator, mass: *Sample, search: *Sample, draw: *Sample, accept: *AcceptTree) !void { + // The draw's inputs: its rows, laws, seeds and draft tree; the accept's: a tree over the same lanes. + const shape = served_sample[1]; + try std.testing.expect(try draw.prepare(shape, .random, 7)); + try std.testing.expect(try accept.prepare(.{ .rows = shape.rows, .n = shape.n, .k = 1 }, .random, 7)); + const rows = &draw.rows; + const n = rows.n(); + const s = draw.rig.stream(); + var g = ops.Graph.init(a, s); + defer g.deinit(); + const logits = draw.args[0]; + const mask = draw.args[1]; + var lanes: [16]kernels.SampleLane = undefined; + draw.wrapperLanes(lanes[0..rows.b], accept.caps); + var stop_u: [2]u32 = undefined; + for (&stop_u, accept.stops[0..2]) |*o, x| o.* = tokU(x); + const r = draw.tree.r; + const tree_in: kernels.SampleTreeIn = .{ .tmeta = draw.args[5], .cands = draw.args[6], .next_q = draw.args[7], .draws = draw.args[8], .r = cint(r), .k = KTOP }; + const result = try kernels.sampleAndAcceptTree(&g, logits, cint(rows.v), if (draw.masked) mask else .{}, accept.args[0], accept.args[1], lanes[0..rows.b], cint(rows.w), &stop_u, tree_in); + const theirs = try a.dupe(u8, try draw.rig.bytesOf(&.{result})); + defer a.free(theirs); + + // The declared launches chained, LPARAMS and SEEDS built as `sampleAndAcceptTree` builds them. + var lp: [16 * 4]f32 = undefined; + var seeds: [16 * 2]u32 = undefined; + var caps: [16]u32 = undefined; + for (lanes[0..rows.b], 0..) |l, i| { + lp[i * 4 ..][0..4].* = .{ l.temperature, @floatFromInt(l.top_k), l.top_p, l.min_p }; + seeds[2 * i] = @truncate(l.seed); + seeds[2 * i + 1] = @truncate(l.seed >> 32); + caps[i] = l.accept_cap; + } + const lparams = try g.fromSlice(f32, lp[0 .. 4 * rows.b], &.{ cint(rows.b), 4 }); + const supp = if (draw.masked) mask else try g.zeros(&.{1}, .bool_); + try mass.rig.launch(mass.launch, massGeometry(n, rows.w, rows.v, rows.stride, draw.masked), &.{ logits, supp, lparams }); + try search.rig.launch(search.launch, searchGeometry(n, rows.w, rows.v, rows.stride, draw.masked), &.{ logits, supp, lparams, mass.rig.output(0) }); + try draw.rig.launch(draw.launch, drawGeometry(n, rows.w, rows.v, rows.stride, draw.masked, r), &.{ logits, supp, lparams, search.rig.output(0), try g.fromSlice(u32, seeds[0 .. 2 * rows.b], &.{ cint(rows.b), 2 }), draw.args[5], draw.args[6], draw.args[7], draw.args[8] }); + var stop_buf: [MAX_STOPS]i32 = @splat(-1); + for (stop_buf[0..2], stop_u) |*o, x| o.* = @intCast(x); + try accept.rig.launch(accept.launch, acceptGeometry(rows.b, rows.w), &.{ + accept.args[0], + accept.args[1], + draw.rig.output(0), + try g.fromSlice(u32, caps[0..rows.b], &.{cint(rows.b)}), + try g.fromSlice(i32, &stop_buf, &.{MAX_STOPS}), + try g.fromSlice(u32, &.{2}, &.{1}), + }); + try std.testing.expectEqualSlices(u8, theirs, accept.rig.outputBytes()); +} diff --git a/src/plugins/inkling2/served_test.zig b/src/plugins/inkling2/served_test.zig index cf594ced7d..af8d9e02d1 100644 --- a/src/plugins/inkling2/served_test.zig +++ b/src/plugins/inkling2/served_test.zig @@ -88,6 +88,7 @@ test "inkling2 pack: a prompt restored from the prefix cache decodes from the lo const a = testing.allocator; var cfg = try model.parseConfig(testing.io, a, std.mem.span(dir)); defer cfg.deinit(a); + @import("test_loads.zig").drop(); var xfm = try driver.load(testing.io, a, &cfg, std.mem.span(dir), mlx.gpuStream()); defer xfm.deinit(); var ids: [1430]u32 = undefined; diff --git a/src/plugins/inkling2/test_loads.zig b/src/plugins/inkling2/test_loads.zig new file mode 100644 index 0000000000..3a770dbc7e --- /dev/null +++ b/src/plugins/inkling2/test_loads.zig @@ -0,0 +1,87 @@ +//! The packs the inkling2 tests load whole (the release, its DFlash2 pair, a pack), held for the test binary: the first +//! test that asks for a load (`hold`) opens it, and a later test that asks for the same load takes the one held. One load +//! is held at a time: an ask for another frees the held one first, and so does a test that opens its own (`drop`). +//! A load's key is its type, the asking test's parts (the pack's directory, its trunk) and every registered Inkling 2 +//! variable as it reads at the ask, so no load made under one value of a variable serves a test that asks under another. +//! A held load lives on the C allocator, never `std.testing.allocator` (whose leak check runs after each test), until +//! the next ask for another load, a `drop`, or the process's exit. + +const std = @import("std"); +const env = @import("../../env.zig"); + +const gpa = std.heap.c_allocator; + +const Held = struct { + key: []u8, + arena: *std.heap.ArenaAllocator, + ptr: *anyopaque, + close: *const fn (*anyopaque) void, +}; + +var held: ?Held = null; + +/// The held `T` for `parts`: the one held when its key matches, else one opened in place of the held load by +/// `opener.open(t, arena)` (`t` the `T` to fill, `arena` an allocator that lives as long as the load). `T` has +/// `close(*T) void`, which `drop` calls. +pub fn hold(comptime T: type, parts: []const []const u8, opener: anytype) !*T { + var key: std.ArrayList(u8) = .empty; + defer key.deinit(gpa); + try keyOf(&key, @typeName(T), parts); + if (held) |h| if (std.mem.eql(u8, h.key, key.items)) { + const t: *T = @ptrCast(@alignCast(h.ptr)); + return t; + }; + drop(); + const own_key = try gpa.dupe(u8, key.items); + errdefer gpa.free(own_key); + const arena = try gpa.create(std.heap.ArenaAllocator); + errdefer gpa.destroy(arena); + arena.* = std.heap.ArenaAllocator.init(gpa); + errdefer arena.deinit(); + const t = try gpa.create(T); + errdefer gpa.destroy(t); + try opener.open(t, arena.allocator()); + held = .{ .key = own_key, .arena = arena, .ptr = t, .close = closeAs(T) }; + return t; +} + +/// Frees the held load, if any. A test that opens a load of its own calls it first, so one load is resident at a time. +pub fn drop() void { + const h = held orelse return; + held = null; + h.close(h.ptr); + h.arena.deinit(); + gpa.destroy(h.arena); + gpa.free(h.key); +} + +fn closeAs(comptime T: type) *const fn (*anyopaque) void { + return &struct { + fn close(p: *anyopaque) void { + const t: *T = @ptrCast(@alignCast(p)); + t.close(); + gpa.destroy(t); + } + }.close; +} + +/// `kind`, then each of `parts`, then each registered variable whose name holds `INKLING2` with its value now (or none +/// when unset), NUL-separated. +fn keyOf(key: *std.ArrayList(u8), kind: []const u8, parts: []const []const u8) !void { + @setEvalBranchQuota(100_000); + try key.appendSlice(gpa, kind); + for (parts) |p| { + try key.append(gpa, 0); + try key.appendSlice(gpa, p); + } + inline for (comptime std.meta.declarations(env.vars)) |n| { + if (comptime std.mem.indexOf(u8, n, "INKLING2") != null) { + try key.append(gpa, 0); + try key.appendSlice(gpa, n); + if (env.named(n)) |v| { + try key.append(gpa, '='); + try key.appendSlice(gpa, std.mem.span(v)); + } + } + } +} diff --git a/src/plugins/inkling2/trunk_contract.zig b/src/plugins/inkling2/trunk_contract.zig new file mode 100644 index 0000000000..6bfbc18544 --- /dev/null +++ b/src/plugins/inkling2/trunk_contract.zig @@ -0,0 +1,229 @@ +//! Inkling 2's trunk kernels in the kernel contract (`contract.zig` registers them): `gate`'s projected arm (the +//! message gates from the projections' products past `packed_rows`: a step's rows, and a prompt's where the tiled +//! gates do not divide the widths). Shape: gates x rows x hidden. The kernel has one planted control (an element +//! short) that gate 3 must catch. + +const std = @import("std"); +const mlx = @import("../../mlx/ffi.zig"); +const ops = @import("../../mlx/ops.zig"); +const kc = @import("../../sdk/testing/kernel_contract/root.zig"); +const source = @import("../../mlx/kernels.zig").source; +const kernels = @import("kernels.zig"); +const layers = @import("layers.zig"); + +const spec = kc.spec; +const metal = kc.metal; +const host = kc.host; +const Shape = spec.Shape; +const U = host.U; + +// ── Inkling 2 Mini's sizes ── + +/// The stream width. +const D = 2304; +const RANK = 64; +/// A precise tanh's error relative to its value (4 ulps). +const TANH = 8 * U; +// ── shared ── + +fn ci(x: usize) c_int { + return @intCast(x); +} + +fn none(_: Shape) usize { + return 0; +} + +/// `n` values of `e` with magnitudes in [lo, hi), either sign. +fn spreadIn(a: std.mem.Allocator, rng: std.Random, n: usize, e: spec.Elem, lo: f64, hi: f64) ![]f64 { + const out = try a.alloc(f64, n); + for (out) |*v| { + const sign: f64 = if (rng.boolean()) 1 else -1; + v.* = spec.roundTo(e, (lo + (hi - lo) * rng.float(f64)) * sign); + } + return out; +} + +// ── gate, a prompt's rows ── + +const gate_launch = metal.Launch{ .name = "msv_inkling2_gate", .inputs = &.{ "A", "MS", "ST", "F", "G" }, .outputs = &.{"Y"}, .source = source("plugins/inkling2/kernels/gate.metal"), .tg_bytes = 0, .m1 = 928, .m2 = 928 }; + +const gate_spec: spec.Spec = .{ + .name = "inkling2 gate (prompt rows, from the projections' products)", + .accum = .none, + .depth = none, + .out = .f32, + // The attention inputs' three gates and the MLP's one over rows past `packed_rows`: a grouped verify's, and a + // prompt's where `gate_mm` does not divide the widths. + .served = &.{ .{ .rows = 3, .n = 65, .k = D }, .{ .rows = 1, .n = 100, .k = D }, .{ .rows = 3, .n = 128, .k = D }, .{ .rows = 1, .n = 512, .k = D } }, +}; + +/// `gate.metal`'s PROJ arm: the loop message gates over the products F st and G st a matmul made (`kernels.gateAt` +/// past `packed_rows` for a step's load): gates x rows x hidden, f32 throughout; the states' only use is their shape. +/// Y = (1 - tanh F) A + tanh(G) MS, no sums: checked within its own allowance (the precise tanh, the products, the add). +const GatePrompt = struct { + rig: metal.Rig, + launch: *const metal.Launch = &gate_launch, + arena: std.heap.ArenaAllocator, + /// The planted control: a grid one thread short, its last element never written. + short: bool = false, + shape: Shape = undefined, + /// `[J, S, D]` each. + a: []f64 = &.{}, + ms: []f64 = &.{}, + f: []f64 = &.{}, + g: []f64 = &.{}, + args: [5]mlx.mlx_array = undefined, + msg: [256]u8 = undefined, + + fn init(al: std.mem.Allocator) GatePrompt { + return .{ .rig = metal.Rig.init(al), .arena = .init(al) }; + } + + pub fn deinit(self: *GatePrompt) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn geometry(self: *const GatePrompt, shape: Shape) ?metal.Geometry { + if (shape.rows == 0 or shape.n <= kernels.packed_rows or shape.k == 0) return null; + const n: c_int = ci(shape.rows * shape.n * shape.k); + var geo = metal.Geometry{ .grid = .{ n - @intFromBool(self.short), 1, 1 }, .tg = .{ 64, 1, 1 } }; + geo.out(&.{ ci(shape.rows), ci(shape.n), ci(shape.k) }, .float32); + geo.int("D", ci(shape.k)); + geo.int("RANK", @as(c_int, RANK)); + geo.int("PROJ", @as(c_int, 1)); + return geo; + } + + pub fn prepare(self: *GatePrompt, shape: Shape, fill: spec.Fill, seed: u64) !bool { + if (self.geometry(shape) == null) return false; + self.shape = shape; + _ = self.arena.reset(.retain_capacity); + const al = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const j = shape.rows; + const s = shape.n; + const d = shape.k; + const n = j * s * d; + self.a = try spreadIn(al, rng, n, .f32, 0.01, 4); + self.ms = try spreadIn(al, rng, n, .f32, 0.01, 4); + // A gate's down projection over its two norms, times a forget or message row: within a few of zero. + self.f = try spreadIn(al, rng, n, .f32, 0.01, 3); + self.g = try spreadIn(al, rng, n, .f32, 0.01, 3); + const st = try spreadIn(al, rng, j * s * RANK, .bf16, 0.01, 1); + if (fill == .nonfinite) { + host.plant(self.a, j * s, d); + // An infinite forget product shuts its gate (the stream leaves); a NaN message product reaches its element. + if (n > 5 * d) { + self.f[4 * d + 1] = std.math.inf(f64); + self.g[4 * d + 2] = std.math.nan(f64); + } + } + self.rig.reset(); + const sh = [_]c_int{ ci(j), ci(s), ci(d) }; + self.args = .{ + try self.rig.input(.float32, &sh, self.a), + try self.rig.input(.float32, &sh, self.ms), + try self.rig.input(.bfloat16, &.{ ci(j), ci(s), RANK }, st), + try self.rig.input(.float32, &sh, self.f), + try self.rig.input(.float32, &sh, self.g), + }; + return true; + } + + pub fn run(self: *GatePrompt) !void { + try self.rig.launch(self.launch, self.geometry(self.shape).?, &self.args); + } + + pub fn count(self: *const GatePrompt) usize { + return self.shape.rows * self.shape.n * self.shape.k; + } + + /// Float64's outputs and what the device may differ by: each tanh's error, the one's complement, the two products + /// and the add, and the floor a flushed subnormal product takes. + fn emit(self: *const GatePrompt, want: []f64, allow: []f64) void { + for (want, allow, 0..) |*w, *l, e| { + const tf = std.math.tanh(self.f[e]); + const tg = std.math.tanh(self.g[e]); + const one = 1 - tf; + const p1 = one * self.a[e]; + const p2 = tg * self.ms[e]; + const y = p1 + p2; + w.* = y; + l.* = @abs(self.a[e]) * (TANH * @abs(tf) + U * @abs(one)) + U * @abs(p1) + @abs(self.ms[e]) * TANH * @abs(tg) + U * @abs(p2) + U * @abs(y) + 3 * 0x1p-126; + } + } + + pub fn reference(self: *const GatePrompt, want: []f64, mag: []f64) !void { + self.emit(want, mag); + } + + /// The rule: within `emit`'s allowance, in the float64 output's class. + pub fn check(self: *GatePrompt, at: spec.Gate) !?[]const u8 { + const al = self.rig.a; + const n = self.count(); + const buf = try al.alloc(f64, 3 * n); + defer al.free(buf); + self.emit(buf[0..n], buf[n .. 2 * n]); + for (buf[2 * n ..], 0..) |*o, i| o.* = spec.read(.f32, self.rig.outputBytes(), i); + return host.within(&self.msg, at, buf[2 * n ..], buf[0..n], buf[n .. 2 * n]); + } + + /// The shipped wrapper (`kernels.gateAt` for a step's load) over states and projections; the declared launch over + /// the products made as the wrapper makes them: the same bytes. + fn parity(self: *GatePrompt) !void { + const j = self.shape.rows; + const s = self.shape.n; + const d = self.shape.k; + const al = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(0x9a7e); + const rng = prng.random(); + const st = try self.rig.input(.bfloat16, &.{ ci(j), ci(s), RANK }, try spreadIn(al, rng, j * s * RANK, .bf16, 0.01, 1)); + const fw = try self.rig.input(.bfloat16, &.{ ci(j), ci(d), RANK }, try spreadIn(al, rng, j * d * RANK, .bf16, 0.005, 0.2)); + const gw = try self.rig.input(.bfloat16, &.{ ci(j), ci(d), RANK }, try spreadIn(al, rng, j * d * RANK, .bf16, 0.005, 0.2)); + var g = ops.Graph.init(self.rig.a, self.rig.stream()); + defer g.deinit(); + const gates: layers.Gates = .{ .down = st, .forget = fw, .message = gw }; + const theirs = try self.rig.a.dupe(u8, try self.rig.bytesOf(&.{try kernels.gateAt(&g, .step, &gates, self.args[0], self.args[1], st, 0, ci(j))})); + defer self.rig.a.free(theirs); + const st32 = try g.astype(st, .float32); + var prods: [2]mlx.mlx_array = undefined; + for (&prods, [_]mlx.mlx_array{ fw, gw }) |*p, wt| p.* = try g.matmul(st32, try g.transpose(try g.astype(try g.sliceAxis(wt, 0, 0, ci(j)), .float32), &.{ 0, 2, 1 })); + try self.rig.launch(self.launch, self.geometry(self.shape).?, &.{ self.args[0], self.args[1], st, prods[0], prods[1] }); + try std.testing.expectEqualSlices(u8, theirs, self.rig.outputBytes()); + } +}; + +// ── registration ── + +pub fn register(set: *kc.Set) !void { + const a = set.a; + try set.add(GatePrompt, .init(a), gate_spec, null); + + // The planted control, last (`checkWrappers` walks the kernels before it): the launch with one fault gate 3 must + // catch. + var gate = GatePrompt.init(a); + gate.short = true; + var gate_c = gate_spec; + gate_c.name = "control inkling2 gate (prompt rows) a thread short (its last element never written)"; + gate_c.served = &.{.{ .rows = 3, .n = 100, .k = D }}; + try set.add(GatePrompt, gate, gate_c, .shapes); +} + +/// `T`'s declared launch against its shipped wrapper at every served shape. +fn drift(comptime T: type, k: kc.gates.Kernel) !void { + const p: *T = @ptrCast(@alignCast(k.ctx)); + for (k.spec.served) |shape| { + try std.testing.expect(try p.prepare(shape, .random, 7)); + try p.run(); + try p.parity(); + } +} + +/// The drift guard of `register`'s kernels, from the first (`items` starts there): each declared launch's bytes equal +/// the shipped wrapper's (`kernels.gateAt`). +pub fn checkWrappers(items: []const kc.gates.Kernel) !void { + try drift(GatePrompt, items[0]); +} diff --git a/src/sdk/bases/kda_hybrid/host.zig b/src/sdk/bases/kda_hybrid/host.zig index b712d44805..07326e4544 100644 --- a/src/sdk/bases/kda_hybrid/host.zig +++ b/src/sdk/bases/kda_hybrid/host.zig @@ -77,12 +77,8 @@ pub fn hostIds(tokens: []const u32) !Array { return mlx.mlx_array_new_data(buf.ptr, &[_]c_int{ 1, @intCast(tokens.len) }, 2, .int32); } -/// The rows a `Caps.prompt_last_row` model's head reads of a last-row prompt (`finish`): past the 16 rows a decode call -/// takes, so the head's matmul runs as the prompt's. -pub const head_tail_rows: c_int = 32; - /// Fills `out` from the final-normed hidden `[1, S, H]` (consumed): the hidden when asked, and the logits the -/// forward wants (`[S, V]` or the last row `[1, V]`). +/// forward wants (`[S, V]`, or the last row `[1, V]` sliced from the same head call over every row). pub fn finish(m: *Model, f: *const abi.Forward, hidden: Array, out: *abi.ForwardOut) !void { defer _ = mlx.mlx_array_free(hidden); if (f.want_hidden) { @@ -92,17 +88,7 @@ pub fn finish(m: *Model, f: *const abi.Forward, hidden: Array, out: *abi.Forward } if (f.logits == .none) return; const s = m.s; - // A model that declares `Caps.prompt_last_row` (bailing_hybrid's streaming pack) runs a last-row prompt's head over - // its last `head_tail_rows` rows only: still a prompt call, whose rows its outside plugin's matmul computes as the - // whole prompt's call does, so the last row keeps its `.all_rows` bytes. - var tail = mlx.mlx_array_new(); - defer _ = mlx.mlx_array_free(tail); - const hsh = mlx.getShape(hidden); - const head_in = if (f.logits == .last_row and m.caps.prompt_last_row and hsh[1] > head_tail_rows) blk: { - try mlx.check(mlx.mlx_slice(&tail, hidden, &[_]c_int{ 0, hsh[1] - head_tail_rows, 0 }, 3, &[_]c_int{ 1, hsh[1], hsh[2] }, 3, &[_]c_int{ 1, 1, 1 }, 3, s)); - break :blk tail; - } else hidden; - const logits = try m.lmHead(head_in); + const logits = try m.lmHead(hidden); defer _ = mlx.mlx_array_free(logits); const sh = mlx.getShape(logits); var rows = mlx.mlx_array_new(); @@ -200,3 +186,51 @@ pub fn settleBank(m: *Model, f: *const abi.Forward, out: *abi.ForwardOut) abi.Ve }; return .ok; } + +// Bar: on the GPU, a last-row ask returns the bytes of the all-rows ask's last row through a dense bf16 head of K 2304 +// and N 8192 at 65 rows, where MLX's matmul takes another kernel at 32 rows than at 65. +test "kda_hybrid finish: a last-row prompt serves the all-rows head's last row bit for bit (dense bf16 head, 65 rows)" { + if (mlx.noGpuBackend() or mlx.virtualGpu()) return error.SkipZigTest; + const testing = std.testing; + const s = mlx.mlx_default_gpu_stream_new(); + defer _ = mlx.mlx_stream_free(s); + const k: c_int = 2304; + const n_out: c_int = 8192; + const rows: c_int = 65; + var prng = std.Random.DefaultPrng.init(65); + const wbuf = try testing.allocator.alloc(f32, @intCast(n_out * k)); + defer testing.allocator.free(wbuf); + for (wbuf) |*x| x.* = prng.random().floatNorm(f32) * 0.02; + const xbuf = try testing.allocator.alloc(f32, @intCast(rows * k)); + defer testing.allocator.free(xbuf); + for (xbuf) |*x| x.* = prng.random().floatNorm(f32); + const wf = mlx.mlx_array_new_data(wbuf.ptr, &[_]c_int{ n_out, k }, 2, .float32); + defer _ = mlx.mlx_array_free(wf); + const xf = mlx.mlx_array_new_data(xbuf.ptr, &[_]c_int{ 1, rows, k }, 3, .float32); + defer _ = mlx.mlx_array_free(xf); + var w = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(w); + try mlx.check(mlx.mlx_astype(&w, wf, .bfloat16, s)); + var x = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(x); + try mlx.check(mlx.mlx_astype(&x, xf, .bfloat16, s)); + var m: Model = .{ .c = undefined, .s = s, .caps = .{ .prompt_last_row = true }, .embed = .{}, .head = .{ .w = w }, .final_norm = .{} }; + var got: [2][]f32 = undefined; + for ([_]abi.Logits{ .all_rows, .last_row }, 0..) |mode, i| { + var h = mlx.mlx_array_new(); + _ = mlx.mlx_array_set(&h, x); + var out: abi.ForwardOut = .{}; + try finish(&m, &.{ .mode = .prefill, .logits = mode, .rows = @intCast(rows), .tokens = .{} }, h, &out); + const l: Array = .{ .ctx = out.logits.ctx }; + defer _ = mlx.mlx_array_free(l); + var f32s = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(f32s); + try mlx.check(mlx.mlx_astype(&f32s, l, .float32, s)); + try mlx.check(mlx.mlx_array_eval(f32s)); + const sh = mlx.getShape(f32s); + const last = mlx.mlx_array_data_float32(f32s).?[@intCast((sh[0] - 1) * sh[1])..@intCast(sh[0] * sh[1])]; + got[i] = try testing.allocator.dupe(f32, last); + } + defer for (got) |g| testing.allocator.free(g); + try testing.expectEqualSlices(u8, std.mem.sliceAsBytes(got[0]), std.mem.sliceAsBytes(got[1])); +} diff --git a/src/sdk/bases/run.zig b/src/sdk/bases/run.zig index 762c0aa6d0..341864c8eb 100644 --- a/src/sdk/bases/run.zig +++ b/src/sdk/bases/run.zig @@ -38,9 +38,6 @@ pub const Run = struct { eval_every: u32 = 0, /// `Ctx.capture_spec`. capture_spec: bool = false, - /// `Caps.prompt_last_row` (the base's `prompt_last_row`): a one-slot `.last_row` head reads the final's last - /// `head_tail_rows` rows only. - head_tail: bool = false, /// `Ctx.row_exact`. row_exact: row_exact.Lane = .off, /// `Ctx.mrope`: the chunk's M-RoPE cos/sin (`Forward.mrope`). @@ -105,15 +102,13 @@ pub const Run = struct { try mlx.check(mlx.mlx_eval(vec)); } - /// The head over every row (a row's logits must not depend on how many rows ride with it), then the rows asked for; - /// under `head_tail` a last-row head over the last `head_tail_rows` rows, still a prompt-sized matmul. + /// The head over every row of the call, then the rows asked for: a `.last_row` result is the slice of the same + /// call an `.all_rows` ask runs, so its bytes do not depend on the mode (a matmul's kernel follows its row count). pub fn finish(r: *const Run, g: *Graph, c: *Ctx, final: Array, comptime Head: type, head: *const Head.Weights) !Out { var out: Out = .{}; if (r.want_hidden) out.hidden = final; if (r.logits == .none) return out; - const n = ops.shape(final)[1]; - const tail = r.head_tail and r.logits == .last_row and r.slots == 1 and n > head_tail_rows; - const logits = try Head.forward(head, c, if (tail) try g.sliceAxis(final, 1, n - head_tail_rows, n) else final); + const logits = try Head.forward(head, c, final); const sh = ops.shape(logits); out.logits = switch (r.logits) { .last_row => try g.reshape(try g.sliceAxis(logits, 1, sh[1] - 1, sh[1]), &.{ sh[0], sh[2] }), @@ -124,14 +119,6 @@ pub const Run = struct { } }; -/// The rows a `head_tail` last-row head reads: at or past `qmm_rows_min`, so its last row keeps the all-rows bits. -pub const head_tail_rows: c_int = 32; -/// Rows from which MLX's quantized matmul runs its prompt kernel, each row's sums independent of the row count. -const qmm_rows_min: c_int = 16; -comptime { - if (head_tail_rows < qmm_rows_min) @compileError("head_tail_rows under qmm_rows_min: the last row's bits would move"); -} - /// A forward's results, owned by its graph: logits `[slots, vocab]` (last row) or `[slots * rows, vocab]`, and the /// final-normed hidden `[slots, rows, hidden]` when asked. pub const Out = struct { @@ -224,7 +211,6 @@ fn run(comptime Base: type, m: *Model(Base), f: *const abi.Forward, out: *abi.Fo .captured = captured, .eval_every = if (f.rows > 1) f.eval_every else 0, // Verify rows roll back on a partial accept; a batched decode step (one row) never does. - .head_tail = @hasDecl(Base, "prompt_last_row") and Base.prompt_last_row, .capture_spec = f.mode == .verify or (f.mode == .batched_rows and f.rows > 1), .mrope = if (f.mrope.ctx != null) .{ try mropeHalf(&g, .{ .ctx = f.mrope.ctx }, 0), try mropeHalf(&g, .{ .ctx = f.mrope.ctx }, 1) } else null, .media = .{ .ctx = f.media.ctx }, @@ -318,33 +304,33 @@ pub const TAIL_MERGE_MAX: usize = 512; /// Slots one batched forward carries (twin of `scheduler.MAX_BATCH_GROUP`). pub const MAX_BATCH_ROWS = 32; -// Bar: a head_tail last-row head reads the last head_tail_rows rows; at or under them, an all-rows ask, several slots -// or no head_tail, every row. -test "run: a head_tail last-row head reads the final's last rows only" { +// Bar: a `.last_row` ask runs the head over every row of the call, one slot or several, and returns the last row of +// the `.all_rows` ask's result, bit for bit. +test "run: a last-row head reads every row of the call and returns the all-rows result's last row" { const H = struct { var rows: c_int = 0; const Weights = struct {}; - fn forward(_: *const Weights, _: *Ctx, x: Array) !Array { + fn forward(_: *const Weights, c: *Ctx, x: Array) !Array { rows = ops.shape(x)[1]; - return x; + return c.g.mulScalar(x, 3.0); } }; var g = Graph.init(std.testing.allocator, mlx.mlx_default_cpu_stream_new()); defer g.deinit(); var c: Ctx = undefined; - const cases = [_]struct { n: c_int, tail: bool, logits: abi.Logits, slots: c_int, reads: c_int }{ - .{ .n = 300, .tail = true, .logits = .last_row, .slots = 1, .reads = head_tail_rows }, - .{ .n = 33, .tail = true, .logits = .last_row, .slots = 1, .reads = head_tail_rows }, - .{ .n = 32, .tail = true, .logits = .last_row, .slots = 1, .reads = 32 }, - .{ .n = 31, .tail = true, .logits = .last_row, .slots = 1, .reads = 31 }, - .{ .n = 300, .tail = true, .logits = .all_rows, .slots = 1, .reads = 300 }, - .{ .n = 300, .tail = true, .logits = .last_row, .slots = 2, .reads = 300 }, - .{ .n = 300, .tail = false, .logits = .last_row, .slots = 1, .reads = 300 }, - }; - for (cases) |k| { - const r: Run = .{ .mode = .prefill, .rows = k.n, .slots = k.slots, .positions = &.{0}, .logits = k.logits, .head_tail = k.tail }; - const out = try r.finish(&g, &c, try g.zeros(&.{ 1, k.n, 4 }, .float32), H, &.{}); - try std.testing.expectEqual(k.reads, H.rows); - if (k.logits == .last_row) try std.testing.expectEqual(@as(c_int, 1), ops.shape(out.logits)[0]); + c.g = &g; + for ([_]c_int{ 1, 31, 33, 300 }) |n| { + const final = try g.arange(0, @floatFromInt(n * 4), 1, .float32); + const x = try g.reshape(final, &.{ 1, n, 4 }); + const all: Run = .{ .mode = .prefill, .rows = n, .slots = 1, .positions = &.{0}, .logits = .all_rows }; + const last: Run = .{ .mode = .prefill, .rows = n, .slots = 1, .positions = &.{0}, .logits = .last_row }; + const a = try all.finish(&g, &c, x, H, &.{}); + try std.testing.expectEqual(n, H.rows); + const l = try last.finish(&g, &c, x, H, &.{}); + try std.testing.expectEqual(n, H.rows); + try std.testing.expectEqual(@as(c_int, 1), ops.shape(l.logits)[0]); + const want = try g.contiguous(try g.sliceAxis(a.logits, 0, n - 1, n)); + try ops.evalMany(&.{ want, l.logits }); + try std.testing.expectEqualSlices(f32, mlx.mlx_array_data_float32(want).?[0..4], mlx.mlx_array_data_float32(l.logits).?[0..4]); } } diff --git a/src/sdk/blocks/moe/gather_qmm_nax.zig b/src/sdk/blocks/moe/gather_qmm_nax.zig index e7e60b19e9..890c783740 100644 --- a/src/sdk/blocks/moe/gather_qmm_nax.zig +++ b/src/sdk/blocks/moe/gather_qmm_nax.zig @@ -9,11 +9,12 @@ const log = @import("../../util/log.zig"); pub const Plan = struct { sched: enum { seg, db }, bm: c_int, bk: c_int, gx: c_int, pad: c_int }; /// `mx`: an FP4 bank (uint8 scales, no biases: e8m0 per 32 for MXFP4, e4m3 per 16 for NVFP4) instead of affine. const CanaryKey = struct { plan: Plan, bits: u32, group: u32, align_n: bool, align_k: bool, mx: bool }; -const MmKey = struct { rows: c_int, n: c_int, k: c_int, max_tiles: c_int, plan: Plan, bits: u32, group: u32, mx: bool, mapped: bool = false, paired: bool = false, weighted: bool = false, limit: u32 = 0 }; +const MmKey = struct { rows: c_int, n: c_int, k: c_int, max_tiles: c_int, plan: Plan, bits: u32, group: u32, mx: bool, mapped: bool = false, paired: bool = false, weighted: bool = false, limit: u32 = 0, il: bool = false }; var scan_kernel: ?mlx.mlx_fast_metal_kernel = null; var mm_kernel: ?mlx.mlx_fast_metal_kernel = null; var mapped_kernel: ?mlx.mlx_fast_metal_kernel = null; var paired_kernel: ?mlx.mlx_fast_metal_kernel = null; +var il_kernel: ?mlx.mlx_fast_metal_kernel = null; var canaries: std.AutoHashMapUnmanaged(CanaryKey, bool) = .{}; var mapped_canaries: std.AutoHashMapUnmanaged(CanaryKey, bool) = .{}; var paired_canaries: std.AutoHashMapUnmanaged(CanaryKey, bool) = .{}; @@ -21,6 +22,7 @@ var weighted_canaries: std.AutoHashMapUnmanaged(CanaryKey, bool) = .{}; var engaged_logged = false; var mapped_engaged_logged = false; var paired_engaged_logged = false; +var il_engaged_logged = false; /// Tile configuration by mean rows per expert and K. The 96+-row rungs are ours: oMLX's /// seg tiles were measured against mlx 0.32.2, whose sorted kernel masked whole row blocks; @@ -39,15 +41,21 @@ pub fn plan(rows: c_int, experts: c_int, k: c_int, n: c_int, paired: bool) Plan return .{ .sched = .seg, .bm = 128, .bk = 128, .gx = 32, .pad = 8192 }; } +/// The bank layouts the sorted and row-mapped kernels decode (`supported`'s layout half): an FP4 bank (`mx`: 4 bits at +/// group 16, NVFP4, or 32, MXFP4, u8 scales, no biases) or affine at 2, 3, 4 or 8 bits, group 32, 64 or 128, bf16 scales +/// and biases. A caller asks this before it builds a call, and names a layout it is false for (MXFP8, affine 5 or 6 +/// bits, f16 scales). +pub fn bankLayoutOk(bits: u32, group: u32, mx: bool, scales: mlx.mlx_dtype, biases: ?mlx.mlx_dtype) bool { + if (mx) return bits == 4 and (group == 32 or group == 16) and biases == null and scales == .uint8; + const b = biases orelse return false; + return (bits == 2 or bits == 3 or bits == 4 or bits == 8) and (group == 32 or group == 64 or group == 128) and scales == .bfloat16 and b == .bfloat16; +} + fn supported(x: mlx.mlx_array, w: mlx.mlx_array, sc: mlx.mlx_array, bi: mlx.mlx_array, idx: mlx.mlx_array, bits: u32, group: u32, mx: bool, row_map: ?mlx.mlx_array, prompt: bool) bool { if (x.ctx == null or w.ctx == null or sc.ctx == null or idx.ctx == null) return false; - if (mx) { - if (bits != 4 or (group != 32 and group != 16) or bi.ctx != null or mlx.mlx_array_dtype(sc) != .uint8) return false; - } else { - if (bi.ctx == null) return false; - if (bits != 2 and bits != 3 and bits != 4 and bits != 8) return false; - if (group != 32 and group != 64 and group != 128) return false; - if (mlx.mlx_array_dtype(sc) != .bfloat16 or mlx.mlx_array_dtype(bi) != .bfloat16 or mlx.mlx_array_ndim(bi) != 3) return false; + if (!bankLayoutOk(bits, group, mx, mlx.mlx_array_dtype(sc), if (bi.ctx != null) mlx.mlx_array_dtype(bi) else null)) return false; + if (!mx) { + if (mlx.mlx_array_ndim(bi) != 3) return false; if (!std.mem.eql(c_int, mlx.getShape(sc), mlx.getShape(bi))) return false; } if (mlx.mlx_array_dtype(x) != .bfloat16 or mlx.mlx_array_dtype(w) != .uint32 or mlx.mlx_array_dtype(idx) != .uint32) return false; @@ -92,8 +100,16 @@ fn kernel(scan: bool) !mlx.mlx_fast_metal_kernel { return value; } -fn mapKernel(paired: bool) !mlx.mlx_fast_metal_kernel { - const slot = if (paired) &paired_kernel else &mapped_kernel; +/// The row-mapped kernel: plain (`.map`), the paired SwiGLU (`.pair`) or the interleaved soft-capped one (`.il`, its +/// `sigtab` f32), each its own instantiation set. +const MapKind = enum { map, pair, il }; + +fn mapKernel(kind: MapKind) !mlx.mlx_fast_metal_kernel { + const slot = switch (kind) { + .map => &mapped_kernel, + .pair => &paired_kernel, + .il => &il_kernel, + }; if (slot.*) |v| return v; const names = [_][*:0]const u8{ "x", "w", "scales", "biases", "up_w", "up_scales", "up_biases", "tiles", "tile_count", "params", "sigtab", "rmap", "row_wt" }; const outs = [_][*:0]const u8{"y"}; @@ -102,7 +118,11 @@ fn mapKernel(paired: bool) !mlx.mlx_fast_metal_kernel { const outs_vec = mlx.mlx_vector_string_new_data(&outs, outs.len); defer _ = mlx.mlx_vector_string_free(outs_vec); const header = kernelSource("kernels/moe/gather_qmm_nax_header.metal") ++ kernelSource("kernels/moe/gather_qmm_nax_mapped_header.metal"); - const value = mlx.mlx_fast_metal_kernel_new(if (paired) "msv_gqmm_affine_pair" else "msv_gqmm_affine_map", ins_vec, outs_vec, kernelSource("kernels/moe/gather_qmm_nax_mapped.metal"), header, true, false); + const value = mlx.mlx_fast_metal_kernel_new(switch (kind) { + .map => "msv_gqmm_affine_map", + .pair => "msv_gqmm_affine_pair", + .il => "msv_gqmm_affine_il", + }, ins_vec, outs_vec, kernelSource("kernels/moe/gather_qmm_nax_mapped.metal"), header, true, false); if (value.ctx == null) return error.MetalKernelCompileFailed; slot.* = value; return value; @@ -170,7 +190,7 @@ fn mmConfig(key: MmKey) !mlx.mlx_fast_metal_kernel_config { try mlx.check(mlx.mlx_fast_metal_kernel_config_add_template_arg_int(cfg, "GX", key.plan.gx)); try mlx.check(mlx.mlx_fast_metal_kernel_config_add_template_arg_int(cfg, "PAD", key.plan.pad)); if (key.mapped) { - try mlx.check(mlx.mlx_fast_metal_kernel_config_add_template_arg_int(cfg, "EPI", if (key.paired) 1 + @as(c_int, @intCast(key.limit)) else 0)); + try mlx.check(mlx.mlx_fast_metal_kernel_config_add_template_arg_int(cfg, "EPI", if (key.il) -1 else if (key.paired) 1 + @as(c_int, @intCast(key.limit)) else 0)); try mlx.check(mlx.mlx_fast_metal_kernel_config_add_template_arg_bool(cfg, "WEIGHTED", key.weighted)); } return cfg; @@ -178,7 +198,9 @@ fn mmConfig(key: MmKey) !mlx.mlx_fast_metal_kernel_config { /// `limit`: a `swiglu_limit` the epilogue clamps at (whole numbers; 0 = none). `up_off`: the up rows' offset in an /// expert of a bank fused along its rows (gate rows, then up rows; `w` is then the gate's bank too), else 0. -const Pair = struct { w: mlx.mlx_array, sc: mlx.mlx_array, bi: mlx.mlx_array, sigtab: mlx.mlx_array, row_wt: mlx.mlx_array = .{ .ctx = null }, limit: u32 = 0, up_off: c_int = 0 }; +/// `il`: one bank `w` of interleaved gate (even) and up (odd) rows under the soft-capped epilogue; `sigtab` is then its +/// f32 caps and per-expert scales. +const Pair = struct { w: mlx.mlx_array, sc: mlx.mlx_array, bi: mlx.mlx_array, sigtab: mlx.mlx_array, row_wt: mlx.mlx_array = .{ .ctx = null }, limit: u32 = 0, up_off: c_int = 0, il: bool = false }; /// An MXFP4 bank has no biases; the kernel signature still binds the slot. 16 /// elements: MLX binds an array under 8 in `constant`, not `device`. @@ -202,7 +224,8 @@ fn launchMapped(x: mlx.mlx_array, row_map: mlx.mlx_array, w: mlx.mlx_array, sc: const m = mlx.getShape(idx)[0]; const e = ws[0]; const up_off: c_int = if (pair) |v| v.up_off else 0; - const n = ws[1] - up_off; + const il = if (pair) |v| v.il else false; + const n = if (il) @divExact(ws[1], 2) else ws[1] - up_off; const k = xs[2]; const t = try scanTiles(idx, m, e, p.bm, s); defer t.deinit(); @@ -214,9 +237,9 @@ fn launchMapped(x: mlx.mlx_array, row_map: mlx.mlx_array, w: mlx.mlx_array, sc: const sigtab = if (pair) |v| v.sigtab else biasArg(.{ .ctx = null }); // unread without a pair const row_wt: mlx.mlx_array = if (pair) |v| v.row_wt else .{ .ctx = null }; const inputs = [_]mlx.mlx_array{ x, w, sc, biasArg(bi), pw, ps, biasArg(pb), t.tiles, t.count, params, sigtab, row_map, wtArg(row_wt) }; - const cfg = try mmConfig(.{ .rows = m, .n = n, .k = k, .max_tiles = t.max_tiles, .plan = p, .bits = bits, .group = group, .mx = mx, .mapped = true, .paired = pair != null, .weighted = row_wt.ctx != null, .limit = if (pair) |v| v.limit else 0 }); + const cfg = try mmConfig(.{ .rows = m, .n = n, .k = k, .max_tiles = t.max_tiles, .plan = p, .bits = bits, .group = group, .mx = mx, .mapped = true, .paired = pair != null, .weighted = row_wt.ctx != null, .limit = if (pair) |v| v.limit else 0, .il = il }); defer _ = mlx.mlx_fast_metal_kernel_config_free(cfg); - return applyOne(try mapKernel(pair != null), &inputs, cfg, s); + return applyOne(try mapKernel(if (il) .il else if (pair != null) .pair else .map), &inputs, cfg, s); } fn applyOne(k: mlx.mlx_fast_metal_kernel, inputs: []const mlx.mlx_array, cfg: mlx.mlx_fast_metal_kernel_config, s: mlx.mlx_stream) !mlx.mlx_array { @@ -623,6 +646,26 @@ fn sortedGateUpFusedWithWt(x: mlx.mlx_array, row_map: mlx.mlx_array, w: mlx.mlx_ return out; } +/// `sortedGatherMappedPrompt` over a bank `[E, 2 n, K]` of interleaved gate (even) and up (odd) rows with the soft-capped +/// SwiGLU in its epilogue (Inkling 2's act on the rounded products): `[M, 1, n]`. `aux` f32 `[4 + E]` holds +/// { 1 / gate cap, gate cap, 1 / up cap, up cap } then each expert's scale (ones for none). The same tile, plan and K +/// order as the plain mapped call, so the products are its products. Null where it does not serve. +pub fn sortedGateUpInterleaved(x: mlx.mlx_array, row_map: mlx.mlx_array, w: mlx.mlx_array, sc: mlx.mlx_array, bi: mlx.mlx_array, idx: mlx.mlx_array, aux: mlx.mlx_array, bits: u32, group: u32, mx: bool, nax_available: bool, s: mlx.mlx_stream) !?mlx.mlx_array { + if (!nax_available or !mlx.streamIsGpu(s)) return null; + if (!supported(x, w, sc, bi, idx, bits, group, mx, row_map, true)) return null; + const ws = mlx.getShape(w); + if (@rem(ws[1], 64) != 0) return null; + if (aux.ctx == null or mlx.mlx_array_dtype(aux) != .float32 or mlx.mlx_array_ndim(aux) != 1 or mlx.getShape(aux)[0] != 4 + ws[0]) return null; + const key = mappedKey(x, w, idx, bits, group, mx, false); + if (!armed(key, s) or !armedMapped(key, false, false, s)) return null; + const out = try launchMapped(x, row_map, w, sc, bi, idx, .{ .w = w, .sc = sc, .bi = bi, .sigtab = aux, .il = true }, bits, group, mx, key.plan, s); + if (!il_engaged_logged) { + il_engaged_logged = true; + log.info("[gather-nax] interleaved soft-capped SwiGLU engaged: M={d} E={d} N={d} K={d}\n", .{ mlx.getShape(idx)[0], ws[0], @divExact(ws[1], 2), mlx.getShape(x)[2] }); + } + return out; +} + fn requireNax() !void { mlx.installErrorHandler(); if (mlx.noGpuBackend() or !@import("../../../mlx/device.zig").naxAvailable()) return error.SkipZigTest; @@ -1077,6 +1120,97 @@ test "segmented NAX sorted gather: weighted paired SwiGLU matches unweighted tim } } +test "segmented NAX sorted gather: the interleaved soft-capped SwiGLU epilogue is the soft-capped SwiGLU of the mapped products" { + try requireNax(); + errdefer dropOwnLatch(); + // Every layout `bankLayoutOk` takes: NVFP4 g16 (the release), MXFP4 g32, affine 2, 3, 4 and 8 bits at g32, 64, 128. + try interleavedCase(4, 16, true, 0x2267); + try interleavedCase(4, 32, true, 0x2268); + var seed: u64 = 0x2270; + for ([_]u32{ 2, 3, 4, 8 }) |bits| for ([_]u32{ 32, 64, 128 }) |group| { + seed += 1; + try interleavedCase(bits, group, false, seed); + }; +} + +test "segmented NAX sorted gather: a bank layout the mapped kernels do not decode is not taken" { + try std.testing.expect(bankLayoutOk(4, 16, true, .uint8, null)); + try std.testing.expect(bankLayoutOk(4, 32, true, .uint8, null)); + try std.testing.expect(bankLayoutOk(4, 64, false, .bfloat16, .bfloat16)); + try std.testing.expect(bankLayoutOk(8, 64, false, .bfloat16, .bfloat16)); + // MXFP8, affine 5 and 6 bits, f16 scales, an affine bank without biases. + try std.testing.expect(!bankLayoutOk(8, 32, true, .uint8, null)); + try std.testing.expect(!bankLayoutOk(5, 64, false, .bfloat16, .bfloat16)); + try std.testing.expect(!bankLayoutOk(6, 64, false, .bfloat16, .bfloat16)); + try std.testing.expect(!bankLayoutOk(4, 64, false, .float16, .float16)); + try std.testing.expect(!bankLayoutOk(4, 64, false, .bfloat16, null)); +} + +/// The interleaved epilogue against the f64 soft-capped SwiGLU of the plain mapped call's products, on a bank of +/// `bits` at `group` (`mx`: FP4) at Inkling 2 Mini's expert shape (2304 -> 2 x 1152, 128 experts, top 8), a short prompt. +fn interleavedCase(bits: u32, group: u32, mx: bool, bank_seed: u64) !void { + const s = mlx.gpuStream(); + const alloc = std.testing.allocator; + const tokens: c_int = 700; + const rows = tokens * 8; + const experts: c_int = 128; + const n2: c_int = 2304; + const k: c_int = 2304; + const ids_data = try alloc.alloc(u32, @intCast(rows)); + defer alloc.free(ids_data); + skewedRouting(ids_data, @intCast(experts)); + const map_data = try alloc.alloc(u32, @intCast(rows)); + defer alloc.free(map_data); + for (map_data, 0..) |*v, i| v.* = @intCast((i * 73 + 11) % @as(usize, @intCast(tokens))); + const ids = mlx.mlx_array_new_data(ids_data.ptr, &[_]c_int{rows}, 1, .uint32); + defer _ = mlx.mlx_array_free(ids); + const row_map = mlx.mlx_array_new_data(map_data.ptr, &[_]c_int{rows}, 1, .uint32); + defer _ = mlx.mlx_array_free(row_map); + const bank = try randomBank(experts, n2, k, bits, group, mx, bank_seed, s); + defer bank.deinit(); + var x = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(x); + try mlx.check(mlx.mlx_random_normal(&x, &[_]c_int{ tokens, 1, k }, 3, .bfloat16, 0, 2.0, bank.key, s)); + // Caps 4 and 25 as the release's, a per-expert scale spread around one. + var aux_host: [4 + 128]f32 = undefined; + aux_host[0] = 1.0 / 4.0; + aux_host[1] = 4.0; + aux_host[2] = 1.0 / 25.0; + aux_host[3] = 25.0; + for (aux_host[4..], 0..) |*v, e| v.* = 0.5 + @as(f32, @floatFromInt(e)) / 64.0; + const aux = mlx.mlx_array_new_data(&aux_host, &[_]c_int{aux_host.len}, 1, .float32); + defer _ = mlx.mlx_array_free(aux); + const prod = (try sortedGatherMappedPrompt(x, row_map, bank.w, bank.sc, bank.bi, ids, bits, group, mx, true, s)) orelse return error.KernelDeclinedTestShape; + defer _ = mlx.mlx_array_free(prod); + const got = (try sortedGateUpInterleaved(x, row_map, bank.w, bank.sc, bank.bi, ids, aux, bits, group, mx, true, s)) orelse return error.KernelDeclinedTestShape; + defer _ = mlx.mlx_array_free(got); + var p32 = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(p32); + try mlx.check(mlx.mlx_astype(&p32, prod, .float32, s)); + var g32 = mlx.mlx_array_new(); + defer _ = mlx.mlx_array_free(g32); + try mlx.check(mlx.mlx_astype(&g32, got, .float32, s)); + try mlx.check(mlx.mlx_array_eval(p32)); + try mlx.check(mlx.mlx_array_eval(g32)); + try std.testing.expectEqualSlices(c_int, &[_]c_int{ rows, 1, @divExact(n2, 2) }, mlx.getShape(got)); + const pd = (mlx.mlx_array_data_float32(p32) orelse return error.NoData)[0..mlx.mlx_array_size(p32)]; + const gd = (mlx.mlx_array_data_float32(g32) orelse return error.NoData)[0..mlx.mlx_array_size(g32)]; + const half: usize = @intCast(@divExact(n2, 2)); + var worst: f64 = 0; + for (0..@intCast(rows)) |r| for (0..half) |i| { + const sc = aux_host[4 + ids_data[r]]; + const g = pd[r * 2 * half + 2 * i] * sc; + const u = pd[r * 2 * half + 2 * i + 1] * sc; + const want: f64 = (std.math.tanh(@as(f64, g) * 0.25) * 4.0) * (std.math.tanh(@as(f64, u) / 25.0) * 25.0) / (1.0 + @exp(-@as(f64, g))); + const have: f64 = gd[r * half + i]; + // A bf16 output: within 2^-7 of the f64 value, relative (one to two of its ulps). + const err = @abs(have - want) / (@abs(want) * 0x1p-7 + 0x1p-30); + worst = @max(worst, err); + }; + std.debug.print("[gather-nax] interleaved SwiGLU epilogue, {s} {d}-bit g{d}: worst error {d:.3} of 2^-7 relative over {d} outputs\n", .{ std.mem.span(modeName(mx, group)), bits, group, worst, gd.len }); + try std.testing.expect(worst <= 1.0); +} + /// `a` and `b` interleaved per rep after one warm run each: per-arm medians of the wall /// time of the build plus the eval of what it returns. fn abMedianMs(reps: comptime_int, ctx: BenchArm, a: BenchBuild, b: BenchBuild) ![2]f64 { diff --git a/src/sdk/config/model.zig b/src/sdk/config/model.zig index a4b5bbbc46..174874e593 100644 --- a/src/sdk/config/model.zig +++ b/src/sdk/config/model.zig @@ -533,6 +533,8 @@ pub const ModelConfig = struct { mtp_greedy_tail_override: ?bool = null, /// null = off (the route changes numerics). int8_prefill_override: ?bool = null, + /// The load declined its plugin's accelerators, which did not fit (`"accel":false` in the load settings). + accel_declined: bool = false, /// LOSSY MXFP8 copy of a dense head; null = `--lm-head-mxfp8`, else the integrated-CUDA default. lm_head_mxfp8_override: ?bool = null, /// The model's `ane` setting: serve it on the Neural Engine; null follows `--ane`. @@ -566,6 +568,11 @@ pub const ModelConfig = struct { /// `generate.effectivePrefillChunk` all read THIS field, so the bill and the /// forward can never disagree. Explicit `--prefill-chunk` still wins. pinned_prefill_chunk: u32 = 0, + /// The weights' committed bytes, set at load from the pack (`committedTextBytes`): the resident term a + /// `repeatable_prefill` model's chunk pin reads in place of live memory. + resident_bytes: u64 = 0, + /// R's boot terms (`engines/mlx/repro.inputsDigest`), hashed once a load for the per-request `[repro]` line. + repro_inputs: u64 = 0, // Stop tokens (populated from config.json) eos_token_ids: [8]u32 = @splat(0), @@ -1341,6 +1348,11 @@ pub const ModelConfig = struct { return self.caps().long_ctx; } + /// `Caps.repeatable_prefill`: the chunk pin reads R, and a repeatable prompt waits, then is refused, at that width. + pub fn repeatablePrefill(self: *const ModelConfig) bool { + return self.caps().repeatable_prefill; + } + /// The keys a batched tick reads per slot: past the gather floor, QSA's indexer budget and its open block. pub fn batchedEffectiveKvLen(self: *const ModelConfig, kv: u32, gather_on: bool, gather_min_kv: u32) u32 { if (!gather_on) return kv; diff --git a/src/tests.zig b/src/tests.zig index 438c00078d..db7fcd615f 100644 --- a/src/tests.zig +++ b/src/tests.zig @@ -62,6 +62,7 @@ test { _ = @import("plugins/inkling2/proof_test.zig"); _ = @import("plugins/inkling2/bill_test.zig"); _ = @import("plugins/inkling2/served_test.zig"); + _ = @import("plugins/inkling2/repro_test.zig"); _ = @import("plugins/nemotron_h/proof_test.zig"); _ = @import("plugins/nemotron_h/mtp_head_test.zig"); _ = @import("plugins/gemma4/proof_test.zig"); @@ -167,6 +168,7 @@ test { _ = @import("engines/mlx/admission/bills.zig"); _ = @import("engines/mlx/admission/bills_test.zig"); _ = @import("engines/mlx/admission/context.zig"); + _ = @import("engines/mlx/admission/pending.zig"); _ = @import("engines/mlx/admission/glm5_bill.zig"); _ = @import("engines/mlx/admission/hot_cache_plan.zig"); _ = @import("engines/mlx/admission/prefill_chunk.zig"); @@ -257,6 +259,9 @@ test { _ = @import("sdk/spec/mtp/mtp.zig"); _ = @import("engines/mlx/spec/mtp_test.zig"); _ = @import("engines/mlx/spec/round_cost.zig"); + _ = @import("engines/mlx/spec/ladder_store.zig"); + _ = @import("engines/mlx/repro.zig"); + _ = @import("engines/mlx/warm_requests.zig"); _ = @import("engines/mlx/spec/mtp_group_planner.zig"); _ = @import("plugins/deepseek_v4/deepseek_v4.zig"); _ = @import("plugins/deepseek_v4/model_config.zig"); diff --git a/src/tests_core.zig b/src/tests_core.zig index 39e94981b5..00a5a96312 100644 --- a/src/tests_core.zig +++ b/src/tests_core.zig @@ -69,6 +69,7 @@ test { _ = @import("engines/mlx/admission/bills.zig"); _ = @import("engines/mlx/admission/bills_test.zig"); _ = @import("engines/mlx/admission/context.zig"); + _ = @import("engines/mlx/admission/pending.zig"); _ = @import("engines/mlx/admission/glm5_bill.zig"); _ = @import("engines/mlx/admission/hot_cache_plan.zig"); _ = @import("engines/mlx/admission/prefill_chunk.zig"); @@ -103,6 +104,9 @@ test { _ = @import("sdk/spec/mtp/mtp.zig"); _ = @import("engines/mlx/spec/mtp_test.zig"); _ = @import("engines/mlx/spec/round_cost.zig"); + _ = @import("engines/mlx/spec/ladder_store.zig"); + _ = @import("engines/mlx/repro.zig"); + _ = @import("engines/mlx/warm_requests.zig"); _ = @import("engines/mlx/spec/mtp_group_planner.zig"); _ = @import("sdk/bases/kda_hybrid/cuts_test.zig"); _ = @import("sdk/tokenizer/tokenizer.zig"); diff --git a/src/tests_llm.zig b/src/tests_llm.zig index 6f666dc409..2dacb14751 100644 --- a/src/tests_llm.zig +++ b/src/tests_llm.zig @@ -35,6 +35,7 @@ test { _ = @import("plugins/inkling2/proof_test.zig"); _ = @import("plugins/inkling2/bill_test.zig"); _ = @import("plugins/inkling2/served_test.zig"); + _ = @import("plugins/inkling2/repro_test.zig"); _ = @import("plugins/nemotron_h/proof_test.zig"); _ = @import("plugins/nemotron_h/mtp_head_test.zig"); _ = @import("plugins/gemma4/proof_test.zig"); diff --git a/tests/q8ref_conv.py b/tests/q8ref_conv.py new file mode 100644 index 0000000000..5b09a57130 --- /dev/null +++ b/tests/q8ref_conv.py @@ -0,0 +1,43 @@ +"""The 8-bit trunk as tests/convert_inkling2.py --bits 8 makes it from the Inkling 2 release, for +EVERY tensor it quantizes: its own sanitize and quantize (group 64, on the default device, the GPU, as the converter +runs), in memory, nothing saved. Writes each quantized module's weight / scales / biases sha256, shape and dtype to a +json the plugin's TRUNK_Q8 test compares against. + +Needs mlx and numpy (an mlx-lm environment). The json goes to the tests as INKLING2_Q8_REF. + +usage: python -I tests/q8ref_conv.py +""" +import hashlib +import importlib.util +import json +import sys +from pathlib import Path + +import mlx.core as mx +import numpy as np + +tree, src, out_path = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]) +spec = importlib.util.spec_from_file_location("convert_inkling2", tree / "tests" / "convert_inkling2.py") +conv = importlib.util.module_from_spec(spec) +spec.loader.exec_module(conv) + +weights = {} +for shard in sorted(src.glob("model-*.safetensors")): + weights.update(mx.load(str(shard))) +weights = conv.sanitize(weights) +names = sorted(k for k in weights if conv.QUANTIZED.match(k)) +ends = {"model.language_model.embed_tokens": 8, "lm_head": 8} +out = {} +for k in names: + q = conv.quantize({k: weights[k]}, 8, (), {}, ends) + base = k.rsplit(".", 1)[0] + rec = {} + for leaf in ("weight", "scales", "biases"): + a = q[f"{base}.{leaf}"] + mx.eval(a) + raw = a.view(mx.uint16) if a.dtype == mx.bfloat16 else a + rec[leaf] = {"sha256": hashlib.sha256(np.array(raw).tobytes()).hexdigest(), "shape": list(a.shape), "dtype": str(a.dtype)} + out[base] = rec + del q +print(f"{len(out)} quantized modules", flush=True) +out_path.write_text(json.dumps(out, indent=1, sort_keys=True)) diff --git a/tests/test_inkling2_first_prompt_warm.sh b/tests/test_inkling2_first_prompt_warm.sh new file mode 100755 index 0000000000..591dcece52 --- /dev/null +++ b/tests/test_inkling2_first_prompt_warm.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# test_inkling2_first_prompt_warm.sh — a boot that reads a stored round ladder serves its +# prompt warm before it listens (`warm_requests.warmPrompt`), while its pipeline record is open: the record closes at +# ready, after the warm and before the server listens, and a request after ready leaves its bytes as they were. +# GPU; a real Mac with the pack. +# BIN (default ./zig-out/bin/mlx-serve, ReleaseFast), PORT (default 8131). +set -uo pipefail +MODEL="${1:?usage: test_inkling2_first_prompt_warm.sh }" +BIN="${BIN:-./zig-out/bin/mlx-serve}"; PORT="${PORT:-8131}" +T=$(mktemp -d "${TMPDIR:-/tmp}/ink2-warm.XXXXXX") +export MLX_SERVE_ROUNDS_LADDER=$T/rounds MLX_SERVE_INKLING2_PIPELINES_AT_LOAD=$T/pipes +mkdir -p "$T/rounds" "$T/pipes" "$T/h1" "$T/h2" +fail() { echo "FAIL: $*"; [ -n "${SRV:-}" ] && kill "$SRV" 2>/dev/null; exit 1; } +boot() { # $1 home, $2 log + HOME=$1 "$BIN" --serve --model "$MODEL" --host 127.0.0.1 --port "$PORT" --ctx-size 8192 --prefix-cache-entries 0 \ + --log-level info > "$2" 2>&1 < /dev/null & + SRV=$! + for _ in $(seq 1 600); do curl -s -m 2 "http://127.0.0.1:$PORT/health" | grep -q ok && return 0; kill -0 "$SRV" 2>/dev/null || break; sleep 1; done + fail "no server ($(tail -3 "$2" | tr '\n' ' '))" +} +stop() { kill "$SRV" 2>/dev/null; wait "$SRV" 2>/dev/null; SRV=; } + +# A first boot times the rounds after ready and stores the ladder. +boot "$T/h1" "$T/boot1.log" +for _ in $(seq 1 900); do grep -aqE '\[rounds\] ladder (stored|read)' "$T/boot1.log" && break; sleep 1; done +stop +grep -aq '\[rounds\] ladder stored' "$T/boot1.log" || fail "the first boot stored no ladder" + +# A second boot reads the ladder, so nothing times the rounds: it serves its prompt warm with the record open, then +# closes the record, before it listens. +boot "$T/h2" "$T/boot2.log" +grep -aq '\[rounds\] ladder read' "$T/boot2.log" || fail "the second boot did not read the ladder" +w=$(grep -an '\[warm\] the load served one' "$T/boot2.log" | head -1 | cut -d: -f1) +c=$(grep -an 'pipelines at load: record closed at ready' "$T/boot2.log" | head -1 | cut -d: -f1) +l=$(grep -an 'Server listening' "$T/boot2.log" | head -1 | cut -d: -f1) +[ -n "$w" ] && [ -n "$c" ] && [ -n "$l" ] && [ "$w" -lt "$c" ] && [ "$c" -lt "$l" ] || fail "the prompt warm did not run with the record open before the server listened (warm line ${w:-none}, record closed ${c:-none}, listening ${l:-none})" +rec=$(ls "$T"/pipes/inkling2-pipelines-*.txt 2>/dev/null | head -1); [ -n "$rec" ] || fail "no pipeline record" +before=$(shasum -a 256 < "$rec") +prompt=$(/usr/bin/python3 -I -c 'print(" ".join(f"def f{i}(x): return x * {i} + {i % 7}" for i in range(110)))') +body=$(/usr/bin/python3 -I -c 'import json,sys; print(json.dumps({"messages":[{"role":"user","content":sys.argv[1]}],"temperature":0,"max_tokens":8,"stream":False}))' "$prompt") +code=$(curl -s -m 300 -o "$T/resp.json" -w '%{http_code}' "http://127.0.0.1:$PORT/v1/chat/completions" -H 'Content-Type: application/json' -d "$body") +[ "$code" = 200 ] || fail "the first request: HTTP $code" +stop +[ "$(shasum -a 256 < "$rec")" = "$before" ] || fail "a request after ready changed the pipeline record (its last lines: $(tail -2 "$rec" | cut -c1-120 | tr '\n' ' '))" +echo "PASS: the warm ran with the record open, the record closed before the server listened, and the first request left it as it was ($T)"