diff --git a/CHANGELOG.md b/CHANGELOG.md index 79d3b9c56c8..d5ef2efba05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -146,6 +146,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: Macs with tensor units (M5) take the flag instead of refusing it, and a paged prompt pass finds each 512-key chunk's two pages once instead of reading the page table at every 32-key step, with every token and cache row unchanged (#3180, part of #1293). Thanks to @CodingEmil. - Nemotron 3.5 Lightning on HIP: the MTP head file is read at the width its own metadata states, so it drafts beside an oQ checkpoint of any width, and a head at a width the launches do not read is refused by name (#3251, part of #3061). Thanks to @gilby. +- Inkling 2 Mini (`inkling2_loop`) now serves natively on one CUDA rank and on Metal. CUDA runs the 48-visit text loop's cross-pass messages, rank-64 gates and separate sliding Q/K/V inputs with per-visit KV and convolution state, prompt snapshots and exact rollback; routed experts decode stored NVFP4 and MXFP8 weights to bf16 with the reference's rounding and ascending-expert FP32 accumulation, without activation quantization. Metal's default serving path stays unchanged, while opt-in DSpark drafting preserves target tokens and rolls back exactly. CUDA TP, vision and DSpark loading remain refused by name. + +- Inkling 2 on CUDA: the family's grouped-expert launches match main's `tf_exl3_grouped_2` bit for bit under the kernel contract, and the vision tower's kernels pass gates 1 to 4 (refs #3476). Thanks to @ajensenwaud. + - Tests: the served-evidence concurrency test pairs its two generated streams in the fake server, so a busy runner can no longer decode them one after the other and turn it red; other conformance fixtures keep their pacing. - GLM-5.3-Flash on CUDA at tensor-parallel widths where a rank's fused KDA input is not a multiple of eight columns (TP=3, 5, 6 or 7): the stack is padded at load to its own width rounded up to eight columns and stays row-major bf16, so prompt windows take the staged B16 tiles with every byte as before; `TF_GLM_KDA_PAD=1` still tiles the stack for glm_mm (#3697, for #3516). Thanks to @ultradaoto. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 02fa97af919..bb22e7fb461 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -554,6 +554,27 @@ those files. `tiny_config.json` and the tensor tables `0a57c72e4e5b68aafe1d983dbb62980344a5fcd7`, a randomly initialised model whose model card names that release as its base model and states no licence; no weights are included. `tools/zig/inkling2_fixtures.py` rebuilds all of these files. +## Inkling 2 Mini fixtures and loop references + +`mini_config.json`, `mini_model_header.txt` and `mini_mtp_header.txt` in +`zig/src/families/inkling2/fixtures/` come from the 2026-11-20 published snapshot of +[thinkingmachines/Inkling-2-Mini at `ed40e7da625f594fc9c4990f5f66be24873c22d7`](https://huggingface.co/thinkingmachines/Inkling-2-Mini), under the Apache License 2.0 +stated on its model card (see [the license text](LICENSES/Apache-2.0.txt)). The public model API supplied that full revision and last-modified time 2026-11-20T22:55:20Z. The fixture config differs from the supplied published `config.json` only by its explicit `_fixture_provenance` annotation; after excluding that annotation, every checkpoint config field matches. The folded tables contain only metadata from the model and MTP safetensors +headers, no tensor data or weights. `tools/zig/inkling2_fixtures.py` rebuilds all three from the Mini release, or from its +extracted headers, with the same revision annotation. No revision was derived from fixture digests. + +The Mini loop host/reference implementations in `zig/src/families/inkling2/loop.zig`, `loop_model.zig`, `loop_engine.zig`, +`loop_math_cuda.zig`, the CUDA and Metal loop kernels and the stored-expert implementations in `modelopt.zig` and +`zig/kernels/cuda/inkling2/modelopt.cu` are independent TensorFold implementations of the supplied math-only Mini +specification. Its primary reference is huggingface/transformers PR #51050 at head `6173a2f6`: the Mini configuration and +forward pass in `models/inkling2_loop/modular_inkling2_loop.py` and `modeling_inkling2_loop.py`, with the temporary +NVFP4/MXFP8 expert dequantization in `core_model_loading.py` and the checkpoint mappings in `conversion_mapping.py`. +ModelOpt here names the checkpoint format and that Transformers arithmetic; no NVIDIA Model Optimizer source was used or +vendored. The specification also records Neywa-Labs/mlx-vlm at `fd6404fb` as its second reading of the loop and DSpark +implementation (`mlx_vlm/models/inkling2/` and `mlx_vlm/speculative/drafters/inkling2_dspark/`). Transformers is Apache-2.0; +mlx-vlm is MIT (see [`LICENSES/MIT.txt`](LICENSES/MIT.txt)). No reference source code is vendored. The supplied materials +give only these two abbreviated reference heads, not their full commit SHAs. + ## Inkling 2 attention kernels `zig/kernels/cuda/inkling2/attention.cu`, `zig/kernels/cuda/inkling2/prompt_attention.cu` and @@ -572,3 +593,13 @@ these layers of Hugging Face transformers' `src/transformers/models/inkling2/mod `Inkling2NormedEmbedding`, `Inkling2BlockAttentionResidual`, `Inkling2ShortConvolution`, `Inkling2DynamicShortConvolution`, `Inkling2TopKRouter`, `Inkling2SoftcappedSwiGLU` and `Inkling2Softcap`. The kernels are TensorFold's own. + +## Inkling 2 expert and vision kernels + +`zig/kernels/cuda/inkling2/experts.cu` and `zig/src/families/inkling2/experts.zig` run `Inkling2Experts` from Hugging +Face transformers' `src/transformers/models/inkling2/modeling_inkling2.py` at commit `109a7d19bf66` +([huggingface/transformers](https://github.com/huggingface/transformers), Apache-2.0) on main's EXL3 grouped-expert +arithmetic. `zig/kernels/cuda/inkling2/vision.cu` and `zig/src/families/inkling2/vision.zig` compute the same file's +vision tower: `Inkling2VisionEmbeddings`, `Inkling2VisionRotaryEmbedding`, `Inkling2VisionAttention`, +`Inkling2VisionMLP` and `Inkling2VisionMerger`. `zig/src/families/inkling2/image.zig` follows `Inkling2ImageProcessor` +in `image_processing_inkling2.py` at the same commit for its 40-pixel patches and the tower's input tables. diff --git a/tools/zig/inkling2_fixtures.py b/tools/zig/inkling2_fixtures.py index 21af5106f97..ac0465d7e4a 100644 --- a/tools/zig/inkling2_fixtures.py +++ b/tools/zig/inkling2_fixtures.py @@ -1,4 +1,4 @@ -"""Rebuild zig/src/families/inkling2/fixtures from the Inkling 2 Small release and tiny-random/inkling-2.""" +"""Rebuild zig/src/families/inkling2/fixtures from the Small, tiny-random and Mini checkpoint inputs.""" import argparse import hashlib import json @@ -10,6 +10,19 @@ FIXTURES = ROOT / "zig/src/families/inkling2/fixtures" RELEASE = "thinkingmachines/Inkling-2-Small@2ad1157016e1aac77b6ff1b770e7c05229403134" TINY = "tiny-random/inkling-2@0a57c72e4e5b68aafe1d983dbb62980344a5fcd7" +MINI_RELEASE = "thinkingmachines/Inkling-2-Mini" +MINI_REVISION = "ed40e7da625f594fc9c4990f5f66be24873c22d7" +MINI_PROVENANCE = { + "release": MINI_RELEASE, + "revision": MINI_REVISION, + "revision_status": "full revision supplied separately; every checkpoint config field matches", + "published": "2026-11-20", + "license": "apache-2.0", +} +MINI_HEADER_PROVENANCE = ( + f"release={MINI_RELEASE} revision={MINI_REVISION} " + "published=2026-11-20 license=apache-2.0" +) PINS = {"transformers": "5.20.0", "tokenizers": "0.23.3", "jinja2": "3.1.6"} MERGES = 1500 @@ -46,13 +59,35 @@ def dump(value, depth=0): def read_header(path): - """The tensors of a safetensors file as {name: (dtype tag, shape)}, read from its first bytes only.""" - with open(path, "rb") as f: - (length,) = struct.unpack(" +#include +#include + +#include "exl3_decode.cuh" +#include "common/fp_pairs.cuh" + +namespace ink2x { +using namespace tf_exl3; + +constexpr int ITEM_THREADS = 1024; + +// tf_ink2x_group's arguments: tf_exl3_group's lists, plus items (u, first, count), runs of at most `per` members. +struct GroupArgs { + const int* pick; // int32 [rows * slots] + int* uids; // int32 [nexp_max] + int* ucount; // int32 [1] + int* members; // int32 [nexp_max, maxm] + int* items; // int32 [3 * max items] (per > 0) + int* nitems; // int32 [1] (per > 0) + int rows, slots, experts, maxm, per, pad; // pad: -1 after each expert's members up to maxm +}; + +// One projection; z, k, n, p, sk, maxm and slots as GroupedArgs has them. +struct WideArgs { + const half* x0; // fp16 [P, K], the rotated gate (or down) inputs + const half* x1; // fp16 [P, K], the rotated up inputs + const long long* tp0; // int64 [E], one trellis pointer per expert + const long long* tp1; + const int* k2_0; // int32 [E], half-bits a value + const int* k2_1; + const int* uids; // int32 [nexp_max], distinct routed experts in id order + const int* items; // int32 [3 * max items], (u, first member, count); null: item u is expert u, maxm <= 16 MT + const int* nitems; // int32 [1]: the items, or the group's count when items is null + const int* members; // int32 [nexp_max, maxm], row * 32 + slot + float* z; // fp32 partials, [(mat * sk + split) * P + p] * N + col + int k, n, p, sk, maxm, slots; +}; + +// A warp's k tiles for MT member tiles in grouped_body's order per output; words and inputs travel a tile ahead. +template +struct Tiles { + static constexpr int TW = tile_words(), LW = lane_words(); + uint32_t nx[NT][LW]; + + __device__ __forceinline__ void first(const uint32_t* tb, int nkt, int lane) { + if (nkt > 0) +#pragma unroll + for (int j = 0; j < NT; ++j) ldg_lane_words(tb + j * TW, lane, nx[j]); + } + + __device__ __forceinline__ static void xload(const half* (&xr)[MT][2], const bool (&ok)[MT][2], int mts, int k, + uint32_t (&a)[MT][4]) { +#pragma unroll + for (int m = 0; m < MT; ++m) { + const bool o0 = m < mts && ok[m][0], o1 = m < mts && ok[m][1]; + a[m][0] = o0 ? *reinterpret_cast(xr[m][0] + k) : 0u; + a[m][1] = o1 ? *reinterpret_cast(xr[m][1] + k) : 0u; + a[m][2] = o0 ? *reinterpret_cast(xr[m][0] + k + 8) : 0u; + a[m][3] = o1 ? *reinterpret_cast(xr[m][1] + k + 8) : 0u; + } + } + + __device__ __forceinline__ void run(const uint32_t* tb, size_t kstride, int kt0, int nkt, const half* (&xr)[MT][2], + const bool (&ok)[MT][2], int mts, int lane, float (&acc)[MT][NT][2][4]) { + uint32_t xa[MT][4]; + if (nkt > 0) xload(xr, ok, mts, kt0 * 16, xa); + for (int i = 0; i < nkt; ++i) { + uint32_t w[NT][LW], a[MT][4]; +#pragma unroll + for (int j = 0; j < NT; ++j) +#pragma unroll + for (int l = 0; l < LW; ++l) w[j][l] = nx[j][l]; +#pragma unroll + for (int m = 0; m < MT; ++m) +#pragma unroll + for (int c = 0; c < 4; ++c) a[m][c] = xa[m][c]; + if (i + 1 < nkt) { +#pragma unroll + for (int j = 0; j < NT; ++j) ldg_lane_words(tb + (size_t)(i + 1) * kstride + j * TW, lane, nx[j]); + xload(xr, ok, mts, (kt0 + i + 1) * 16, xa); + } +#pragma unroll + for (int j = 0; j < NT; ++j) { + uint32_t b0[2], b1[2]; + decode_lane(w[j], lane, b0, b1); +#pragma unroll + for (int m = 0; m < MT; ++m) + if (m < mts) { + mma16816(acc[m][j][0], a[m], b0); + mma16816(acc[m][j][1], a[m], b1); + } + } + } + } +}; + +// This lane's member-row input pointers (rows_sh filled and synced). +template +__device__ __forceinline__ void member_rows(const half* X, int k, const int* rows_sh, int mts, int g, int t, + const half* (&xr)[MT][2], bool (&ok)[MT][2]) { +#pragma unroll + for (int m = 0; m < MT; ++m) { + const int r0 = m < mts ? rows_sh[16 * m + g] : -1, r1 = m < mts ? rows_sh[16 * m + g + 8] : -1; + xr[m][0] = X + (size_t)(r0 < 0 ? 0 : r0) * k + 2 * t; + xr[m][1] = X + (size_t)(r1 < 0 ? 0 : r1) * k + 2 * t; + ok[m][0] = r0 >= 0; + ok[m][1] = r1 >= 0; + } +} + +// Program (n block, item, mat * sk + split): 16 MT members by W_q over the split's K; SEQ: warps add in turn. +template +__device__ __forceinline__ void wide_body(const WideArgs a) { + const int nblock = blockIdx.x, item = blockIdx.y; + if (item >= a.nitems[0]) return; + int u = item, first = 0, cnt = a.maxm; + if (a.items) { + u = a.items[3 * item]; + first = a.items[3 * item + 1]; + cnt = a.items[3 * item + 2]; + } + const int split = blockIdx.z % a.sk, mat = blockIdx.z / a.sk; + const half* X = mat ? a.x1 : a.x0; + const int e = a.uids[u]; + const uint32_t* T = reinterpret_cast(mat ? a.tp1[e] : a.tp0[e]); + const int k2 = mat ? a.k2_1[e] : a.k2_0[e]; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int g = lane >> 2, t = lane & 3; + const int ntiles = a.n >> 4; + const int per_warp = (a.k >> 4) / a.sk / W; + const int kt0 = split * (per_warp * W) + warp * per_warp; + const int nt0 = nblock * NT; + + __shared__ int rows_sh[16 * MT]; + for (int m = threadIdx.x; m < 16 * MT; m += W * 32) { + const int code = m < cnt ? a.members[(size_t)u * a.maxm + first + m] : -1; + rows_sh[m] = code >= 0 ? (code >> 5) * a.slots + (code & 31) : -1; + } + float acc[MT][NT][2][4]; +#pragma unroll + for (int m = 0; m < MT; ++m) +#pragma unroll + for (int i = 0; i < NT; ++i) +#pragma unroll + for (int h = 0; h < 2; ++h) +#pragma unroll + for (int c = 0; c < 4; ++c) acc[m][i][h][c] = 0.f; + + int mts = 0; + switch (k2) { // the first k tile's words are in flight before the members' rows are read +#define TF_INK2X_CASE(K2_) \ + case K2_: { \ + Tiles tl; \ + const size_t kstride = (size_t)ntiles * tile_words(); \ + const uint32_t* tb = T + (size_t)kt0 * kstride + (size_t)nt0 * tile_words(); \ + tl.first(tb, per_warp, lane); \ + __syncthreads(); \ + if (!a.items) \ + while (cnt > 0 && rows_sh[cnt - 1] < 0) --cnt; \ + mts = (cnt + 15) >> 4; \ + if (mts == 0) return; \ + const half* xr[MT][2]; \ + bool ok[MT][2]; \ + member_rows(X, a.k, rows_sh, mts, g, t, xr, ok); \ + tl.run(tb, kstride, kt0, per_warp, xr, ok, mts, lane, acc); \ + break; \ + } + TF_INK2X_CASE(2) + TF_INK2X_CASE(3) + TF_INK2X_CASE(4) + TF_INK2X_CASE(5) + TF_INK2X_CASE(6) + TF_INK2X_CASE(7) + TF_INK2X_CASE(8) +#undef TF_INK2X_CASE + default: + __trap(); + } + + __shared__ __align__(16) float red[SEQ ? 1 : W][16][NT * 16]; +#pragma unroll + for (int m = 0; m < MT; ++m) { + if (m >= mts) break; + if (m) __syncthreads(); // the last tile's sums are read + for (int w = SEQ ? 0 : warp; w < (SEQ ? W : warp + 1); ++w) { + if (w == warp) +#pragma unroll + for (int i = 0; i < NT; ++i) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int col = i * 16 + h * 8 + 2 * t; + float* p0 = &red[SEQ ? 0 : warp][g][col]; + float* p1 = &red[SEQ ? 0 : warp][g + 8][col]; + if (!SEQ || w == 0) { + p0[0] = acc[m][i][h][0]; + p0[1] = acc[m][i][h][1]; + p1[0] = acc[m][i][h][2]; + p1[1] = acc[m][i][h][3]; + } else { + p0[0] += acc[m][i][h][0]; + p0[1] += acc[m][i][h][1]; + p1[0] += acc[m][i][h][2]; + p1[1] += acc[m][i][h][3]; + } + } + if (SEQ) __syncthreads(); + } + if (!SEQ) __syncthreads(); + for (int idx = threadIdx.x; idx < 16 * NT * 16; idx += W * 32) { + const int row = idx / (NT * 16), col = idx % (NT * 16); + const int r = rows_sh[16 * m + row]; + if (r < 0) continue; + float s = red[0][row][col]; +#pragma unroll + for (int w = 1; w < (SEQ ? 1 : W); ++w) s += red[w][row][col]; + a.z[(((size_t)mat * a.sk + split) * a.p + r) * a.n + nt0 * 16 + col] = s; + } + } +} + +// Exclusive sum over the block of one value a thread (ITEM_THREADS threads); `tot` gets the total. +__device__ __forceinline__ int block_scan(int v, int* part, int& tot) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + int inc = v; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int x = __shfl_up_sync(0xffffffffu, inc, o); + if (lane >= o) inc += x; + } + if (lane == 31) part[warp] = inc; + __syncthreads(); + if (warp == 0) { + const int w = part[lane]; + int sum = w; +#pragma unroll + for (int o = 1; o < 32; o <<= 1) { + const int x = __shfl_up_sync(0xffffffffu, sum, o); + if (lane >= o) sum += x; + } + part[lane] = sum - w; + if (lane == 31) part[32] = sum; + } + __syncthreads(); + tot = part[32]; + const int r = part[warp] + inc - v; + __syncthreads(); + return r; +} + +} // namespace ink2x + +// tf_exl3_group's lists and the item list in O(pairs): warp w counts, then places, its 32nd of the pairs in order. +extern "C" __global__ void __launch_bounds__(ink2x::ITEM_THREADS) tf_ink2x_group(const ink2x::GroupArgs a) { + extern __shared__ int sh[]; + __shared__ int part[33]; + const int E = a.experts, n = a.rows * a.slots; + uint16_t* wc = reinterpret_cast(sh); // [32][E]: a warp's pairs of each expert, then its first rank + int* cnt = sh + 16 * E; + int* uidx = cnt + E; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int span = (n + 31) / 32, lo = warp * span, hi = min(n, lo + span); + const unsigned below = (1u << lane) - 1u; + for (int i = threadIdx.x; i < 32 * E; i += ink2x::ITEM_THREADS) wc[i] = 0; + __syncthreads(); + for (int i0 = lo; i0 < hi; i0 += 32) { + const int i = i0 + lane; + const int e = i < hi ? a.pick[i] : -1; + const unsigned m = __match_any_sync(0xffffffffu, e); + if (e >= 0 && e < E && (m & below) == 0) wc[warp * E + e] += __popc(m); + } + __syncthreads(); + int has = 0, k = 0, c = 0; + const int e = threadIdx.x; + if (e < E) { + for (int w = 0; w < 32; ++w) { + const int t = wc[w * E + e]; + wc[w * E + e] = c; + c += t; + } + cnt[e] = c; + has = c > 0; + k = a.per > 0 ? (c + a.per - 1) / a.per : 0; + } + int nu, ni; + const int u = ink2x::block_scan(has, part, nu); + int it = ink2x::block_scan(k, part, ni); + if (e < E) { + uidx[e] = u; + if (has) { + a.uids[u] = e; + for (int j = 0; j < k; ++j, ++it) { + a.items[3 * it] = u; + a.items[3 * it + 1] = j * a.per; + a.items[3 * it + 2] = min(a.per, c - j * a.per); + } + } + } + if (threadIdx.x == 0) { + a.ucount[0] = nu; + if (a.per > 0) a.nitems[0] = ni; + } + __syncthreads(); + for (int i0 = lo; i0 < hi; i0 += 32) { + const int i = i0 + lane; + const int pe = i < hi ? a.pick[i] : -1; + const unsigned m = __match_any_sync(0xffffffffu, pe); + if (pe >= 0 && pe < E) { + const int rank = wc[warp * E + pe] + __popc(m & below); + a.members[(size_t)uidx[pe] * a.maxm + rank] = (i / a.slots) * 32 + i % a.slots; + } + __syncwarp(); + if (pe >= 0 && pe < E && (m & below) == 0) wc[warp * E + pe] += __popc(m); + __syncwarp(); + } + if (a.pad) // -1 after each expert's members, as tf_exl3_group leaves them + for (int x = threadIdx.x; x < E; x += ink2x::ITEM_THREADS) + if (cnt[x] > 0) + for (int j = cnt[x]; j < a.maxm; ++j) a.members[(size_t)uidx[x] * a.maxm + j] = -1; +} + +// Decode rows and short windows: 128 columns and 16 members a block (grouped_body's tile), warp sums apart. +extern "C" __global__ void __launch_bounds__(128) tf_ink2x_rows(const ink2x::WideArgs a) { + ink2x::wide_body(a); +} + +// Prompt chunks: 64 columns and 32 members a block, one sum buffer. +extern "C" __global__ void __launch_bounds__(128) tf_ink2x_wide(const ink2x::WideArgs a) { + ink2x::wide_body(a); +} + +namespace ink2m { + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } + +struct CombineArgs { + const uint16_t* experts; // bf16 [rows * slots, H] + const int* pick; + const float* weights; + uint16_t* out; // bf16 [rows, H] + int rows, h, slots; +}; + +struct TensorActArgs { + const uint16_t* gateup; // bf16 [P, 2 * M], adjacent gate and up projections + uint16_t* out; // bf16 [P, M] + int n; +}; + + +__device__ __forceinline__ float cap(float x, float c) { return c * tanhf(x / c); } + +} // namespace ink2m + + +// Tensor-core gate/up rows are interleaved; keep the scalar baseline's softcapped SwiGLU arithmetic. +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_tensor_act(const ink2m::TensorActArgs a) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= a.n) return; + const float gate = ink2m::bf(a.gateup[2 * (size_t)i]); + const float up = ink2m::bf(a.gateup[2 * (size_t)i + 1]); + const float g = ink2m::cap(gate, 4.0f); + const float u = ink2m::cap(up, 25.0f); + const float sigmoid = 1.0f / (1.0f + expf(-gate)); + const float activated = g * sigmoid * u; + a.out[i] = ink2m::tobf(activated); +} + +// One output element: route in ascending expert id, independent of the router's selection order. +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_combine(const ink2m::CombineArgs a) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= a.rows * a.h) return; + const int row = i / a.h, col = i % a.h; + float total = 0.0f; + uint32_t seen = 0; + for (int n = 0; n < a.slots; ++n) { + int best = -1, id = 0; + for (int s = 0; s < a.slots; ++s) { + if (seen & (1u << s)) continue; + const int e = a.pick[row * a.slots + s]; + if (best < 0 || e < id) { + best = s; + id = e; + } + } + seen |= 1u << best; + const float out = ink2m::bf(a.experts[(size_t)(row * a.slots + best) * a.h + col]); + total = __fadd_rn(total, __fmul_rn(a.weights[row * a.slots + best], out)); + } + a.out[i] = ink2m::tobf(total); +} diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu new file mode 100644 index 00000000000..824ec095042 --- /dev/null +++ b/zig/kernels/cuda/inkling2/loop_math.cu @@ -0,0 +1,285 @@ +// Inkling 2 Mini: raw block residuals, two-bank messages, rank-64 gates and three-input QKV projection. +#include +#include + +namespace ink2l { + +constexpr int kRank = 64; +constexpr int kMaxBlocks = 8; +constexpr int kMaxQueries = 3; + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } +__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } + +__device__ __forceinline__ float warpSum(float v) { + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +// Every call has the same reduction tree: lanes' strided chains, each warp's butterfly, then warp 0 over partials. +template +__device__ __forceinline__ void blockSums(float (&v)[N], float* sh) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; + for (int i = 0; i < N; ++i) v[i] = warpSum(v[i]); + __syncthreads(); + if (lane == 0) + for (int i = 0; i < N; ++i) sh[i * 32 + w] = v[i]; + __syncthreads(); + for (int i = 0; i < N; ++i) { + const float t = lane < nw ? sh[i * 32 + lane] : 0.0f; + v[i] = __shfl_sync(0xffffffffu, warpSum(t), 0); + } +} + +// A14(a): Mini's queried residual and message dot products scale after the dot, by binary32(1 / 48). +__device__ __forceinline__ float queryScale(int c) { + return c == 2304 ? 1.0f / 48.0f : rsqrtf(static_cast(c)); +} + +__device__ __forceinline__ void softmax2(float l0, float l1, float* w) { + const float m = fmaxf(l0, l1); + const float e0 = expf(l0 - m), e1 = expf(l1 - m); + const float d = __fadd_rn(e0, e1); + w[0] = __fdiv_rn(e0, d); + w[1] = __fdiv_rn(e1, d); +} + +struct ArArgs { + const uint16_t* blocks[kMaxBlocks]; // bf16 [rows, C], one completed state a pointer + const void* partial; // the final source, BF16 or FP32 according to partial_bf16 + const float* query; // fp32 [nq, C] + float* out; // fp32 [nq, rows, C], deliberately neither normalized nor rounded + int n_blocks, partial_bf16, nq, rows, C; + float eps; +}; + +// The AR half of Small's residual mix, without its fused RMSNorm. Needed before Mini's controller, not just after it. +__device__ void ar(const ArArgs a) { + __shared__ float sh[32 * (1 + kMaxQueries)]; + __shared__ float wts[kMaxQueries][kMaxBlocks + 1]; + __shared__ float rr[kMaxBlocks + 1]; + const size_t row = blockIdx.x; + const int n = a.n_blocks + 1; + auto entry = [&](int j, int c) -> float { + if (j < a.n_blocks) return bf(a.blocks[j][row * a.C + c]); + return a.partial_bf16 ? bf(static_cast(a.partial)[row * a.C + c]) + : static_cast(a.partial)[row * a.C + c]; + }; + for (int j = 0; j < n; ++j) { + float ss[1] = {0.0f}; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + const float x = entry(j, c); + ss[0] = __fmaf_rn(x, x, ss[0]); + } + blockSums<1>(ss, sh); + if (threadIdx.x == 0) rr[j] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(a.C)), a.eps)); + } + __syncthreads(); + for (int j = 0; j < n; ++j) { + float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + const float normalized = __fmul_rn(entry(j, c), rr[j]); + for (int q = 0; q < a.nq; ++q) + dots[q] = __fmaf_rn(a.query[static_cast(q) * a.C + c], normalized, dots[q]); + } + blockSums(dots, sh); + if (threadIdx.x == 0) + for (int q = 0; q < a.nq; ++q) wts[q][j] = __fmul_rn(dots[q], queryScale(a.C)); + } + __syncthreads(); + if (threadIdx.x < a.nq) { + float* l = wts[threadIdx.x]; + float m = -INFINITY, d = 0.0f; + for (int j = 0; j < n; ++j) m = fmaxf(m, l[j]); + for (int j = 0; j < n; ++j) d = __fadd_rn(d, expf(l[j] - m)); + for (int j = 0; j < n; ++j) l[j] = __fdiv_rn(expf(l[j] - m), d); + } + __syncthreads(); + for (int q = 0; q < a.nq; ++q) { + float* out = a.out + (static_cast(q) * a.rows + row) * a.C; + for (int c = threadIdx.x; c < a.C; c += blockDim.x) { + float h = 0.0f; + for (int j = 0; j < n; ++j) { + const float z = __fmul_rn(entry(j, c), rr[j]); + h = __fmaf_rn(wts[q][j], z, h); + } + out[c] = h; + } + } +} + +} // namespace ink2l + +extern "C" __global__ void __launch_bounds__(512) tf_ink2_loop_ar(const ink2l::ArArgs a) { + ink2l::ar(a); +} + +namespace ink2l { + +// One block handles one token and role, sharing each bank's normalization across all 12 core queries. +__device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, + const float* __restrict__ qm, const float* __restrict__ qkv, + float* __restrict__ out, int rows, int core_layers, int c, float eps) { + __shared__ float sh[2 * 32]; + __shared__ float inv[2], w[2]; + const size_t row = blockIdx.x; + const int role = blockIdx.y; // q, k, v, mlp + const uint16_t* banks[2] = {bank0 + row * c, bank1 + row * c}; + const float* role_queries = role == 0 || role == 3 ? qm : qkv; + const int odd = role == 3 || role == 2; + float ss[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float x0 = bf(banks[0][i]), x1 = bf(banks[1][i]); + ss[0] = __fmaf_rn(x0, x0, ss[0]); + ss[1] = __fmaf_rn(x1, x1, ss[1]); + } + blockSums<2>(ss, sh); + if (threadIdx.x == 0) { + inv[0] = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); + inv[1] = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); + } + __syncthreads(); + for (int j = 0; j < core_layers; ++j) { + const float* query = role_queries + static_cast(2 * j + odd) * c; + float dots[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float q = query[i]; + const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); + const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); + dots[0] = __fmaf_rn(q, b0, dots[0]); + dots[1] = __fmaf_rn(q, b1, dots[1]); + } + blockSums<2>(dots, sh); + if (threadIdx.x == 0) + softmax2(__fmul_rn(dots[0], queryScale(c)), __fmul_rn(dots[1], queryScale(c)), w); + __syncthreads(); + // Plane-major [core][role][rows][c]: the gates read each role's rows as one contiguous plane. + float* dst = out + ((static_cast(j) * 4 + role) * rows + row) * static_cast(c); + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const float b0 = __fmul_rn(bf(banks[0][i]), inv[0]); + const float b1 = __fmul_rn(bf(banks[1][i]), inv[1]); + const float m0 = __fmul_rn(w[0], b0), m1 = __fmul_rn(w[1], b1); + dst[i] = __fadd_rn(m0, m1); + } + } +} + +// One gate a block. A shared BF16 zeta is the sole bottleneck output; forget/gain stay FP32 through tanh (A7(a)). +__device__ void gate(const float* __restrict__ h, const float* __restrict__ m, + const uint16_t* __restrict__ down, const uint16_t* __restrict__ forget, + const uint16_t* __restrict__ gain, float* __restrict__ out, + int c, float eps) { + __shared__ float sh[2 * 32]; + __shared__ float inv_h, inv_m; + __shared__ uint16_t zeta[kRank]; + const size_t row = blockIdx.x; + const float* hr = h + row * c; + const float* mr = m + row * c; + float ss[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + ss[0] = __fmaf_rn(hr[i], hr[i], ss[0]); + ss[1] = __fmaf_rn(mr[i], mr[i], ss[1]); + } + blockSums<2>(ss, sh); + if (threadIdx.x == 0) { + inv_h = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); + inv_m = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); + } + __syncthreads(); + // Pair ranks to reuse each normalized input, but keep every dot's 256-thread chains and two-level reduction tree. + for (int r = 0; r < kRank; r += 2) { + float acc[2] = {0.0f, 0.0f}; + const uint16_t* d0 = down + static_cast(r) * (2 * c); + const uint16_t* d1 = d0 + 2 * c; + for (int i = threadIdx.x; i < 2 * c; i += blockDim.x) { + const bool message = i >= c; + const float x = message ? mr[i - c] : hr[i]; + const float n = bfr(__fmul_rn(x, message ? inv_m : inv_h)); + acc[0] = __fmaf_rn(bf(d0[i]), n, acc[0]); + acc[1] = __fmaf_rn(bf(d1[i]), n, acc[1]); + } + blockSums<2>(acc, sh); + if (threadIdx.x == 0) { + zeta[r] = tobf(acc[0]); + zeta[r + 1] = tobf(acc[1]); + } + } + __syncthreads(); + float* dst = out + row * c; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + const uint16_t* f = forget + static_cast(i) * kRank; + const uint16_t* g = gain + static_cast(i) * kRank; + float sf = 0.0f, sg = 0.0f; + for (int r = 0; r < kRank; ++r) { + const float z = bf(zeta[r]); + sf = __fmaf_rn(bf(f[r]), z, sf); + sg = __fmaf_rn(bf(g[r]), z, sg); + } + const float fg = tanhf(sf), gg = tanhf(sg); + // The reference's four FP32 rounding steps, kept explicit so contraction cannot erase any of them. + const float keep = __fsub_rn(1.0f, fg); + const float old = __fmul_rn(keep, hr[i]); + const float added = __fmul_rn(gg, mr[i]); + dst[i] = __fadd_rn(old, added); + } +} + +} // namespace ink2l + +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_messages(const uint16_t* __restrict__ bank0, const uint16_t* __restrict__ bank1, + const float* __restrict__ qm, const float* __restrict__ qkv, float* __restrict__ out, + int rows, int core_layers, int c, float eps) { + ink2l::messages(bank0, bank1, qm, qkv, out, rows, core_layers, c, eps); +} + +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_gate(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, + const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* __restrict__ out, + int rows, int c, float eps) { + (void)rows; + ink2l::gate(h, m, down, forget, gain, out, c, eps); +} + +// Mini QKV launch uses three independently normalized inputs; other kernels and cache/partial layouts are unchanged. +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_project_qkv(const uint16_t* __restrict__ uq, const uint16_t* __restrict__ uk, + const uint16_t* __restrict__ uv, const uint16_t* __restrict__ wq, + const uint16_t* __restrict__ wk, const uint16_t* __restrict__ wv, + uint16_t* __restrict__ raw_q, uint16_t* __restrict__ raw_k, + uint16_t* __restrict__ raw_v, int rows, int c, int q_width, int kv_width) { + constexpr int kRows = 16, kOutputs = 16, kSlice = 32; + __shared__ uint16_t sx[kRows * kSlice], sw[kOutputs * kSlice]; + const int role = blockIdx.z; // q=0, k=1, v=2 + const int width = role == 0 ? q_width : kv_width; + const int row0 = static_cast(blockIdx.x) * kRows; + const int j0 = static_cast(blockIdx.y) * kOutputs; + if (j0 >= width) return; + const uint16_t* x = role == 0 ? uq : role == 1 ? uk : uv; + const uint16_t* w = role == 0 ? wq : role == 1 ? wk : wv; + const int tr = threadIdx.x / kOutputs, tj = threadIdx.x % kOutputs; + const int row = row0 + tr, j = j0 + tj; + float sum = 0.0f; + // A block reuses each normalized tile for 16 outputs and each weight tile for 16 prompt rows. + for (int k0 = 0; k0 < c; k0 += kSlice) { + for (int e = threadIdx.x; e < kRows * kSlice; e += blockDim.x) { + const int r = e / kSlice, k = k0 + e % kSlice; + sx[e] = row0 + r < rows && k < c ? x[static_cast(row0 + r) * c + k] : 0; + sw[e] = j0 + r < width && k < c ? w[static_cast(j0 + r) * c + k] : 0; + } + __syncthreads(); + for (int k = 0; k < kSlice && k0 + k < c; ++k) + sum = __fmaf_rn(ink2l::bf(sx[tr * kSlice + k]), ink2l::bf(sw[tj * kSlice + k]), sum); + __syncthreads(); + } + uint16_t* out = role == 0 ? raw_q : role == 1 ? raw_k : raw_v; + if (row < rows && j < width) out[static_cast(row) * width + j] = ink2l::tobf(sum); +} + +// Global dynamic taps: dot in FP32, store as BF16, and widen to FP32 before the convolution. +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_round_bf16(const float* __restrict__ in, float* __restrict__ out, long long n) { + const long long i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) out[i] = ink2l::bf(ink2l::tobf(in[i])); +} diff --git a/zig/kernels/cuda/inkling2/modelopt.cu b/zig/kernels/cuda/inkling2/modelopt.cu new file mode 100644 index 00000000000..2f8a4c40bd7 --- /dev/null +++ b/zig/kernels/cuda/inkling2/modelopt.cu @@ -0,0 +1,204 @@ +// Mini routed experts: checkpoint NVFP4/MXFP8 codes decode to BF16 mma fragments; no activation quantization. +#include +#include +#include "experts.cuh" + +namespace ink2o { + +struct Weight { + const uint8_t* codes; + const uint8_t* scales; + const float* amax; + const float* den; + long long E, N, K; + int G, format, row0, row_step; +}; + +__device__ __forceinline__ float e2m1(uint32_t n) { + const uint32_t s = (n & 8) ? 0x80000000u : 0; + const uint32_t e = (n >> 1) & 3, m = n & 1; + if (!e) return __uint_as_float(s | (m ? 0x3f000000u : 0)); + return __uint_as_float(s | ((e + 126) << 23) | (m << 22)); +} + +__device__ __forceinline__ float e4m3(uint32_t n) { + const uint32_t s = (n & 128) ? 0x80000000u : 0; + const uint32_t e = (n >> 3) & 15, m = n & 7; + if (e == 15 && m == 7) return __uint_as_float(s | 0x7fc00000u); + if (!e) return (s ? -1.f : 1.f) * (float)m * 0.001953125f; + return __uint_as_float(s | ((e + 120) << 23) | (m << 20)); +} + +__device__ __forceinline__ float e8m0(uint32_t n) { + if (n == 0) return 0x1p-127f; + return __uint_as_float(n << 23); +} + +__device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); } +__device__ __forceinline__ __nv_bfloat16 decoded(const Weight& w, long long e, long long row, long long col) { + const long long z = e * w.N * w.K + row * w.K + col; + const uint32_t nib = w.format ? w.codes[z] : ((w.codes[z / 2] >> ((col & 1) * 4)) & 15); + float v; + if (w.format) { + v = __fmul_rn(e4m3(nib), e8m0(w.scales[z / w.G])); + } else { + const float outer = __fdiv_rn(bf(__ldg(w.amax + e)), bf(__ldg(w.den))); + v = __fmul_rn(__fmul_rn(e2m1(nib), e4m3(w.scales[z / w.G])), outer); + } + return __float2bfloat16_rn(v); +} + +// One uint4 is eight BF16 weights in the fragment layout of experts_bf16.cu. +__device__ __forceinline__ uint4 ld_w(const Weight& w, long long e, int cb, int g, int lane, int j) { + const int row = w.row0 + w.row_step * (cb * 32 + 8 * j + (lane >> 2)), col = g * 32 + 4 * (lane & 3); + uint16_t h[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int c = col + (i & 3) + 16 * (i >> 2); + h[i] = __bfloat16_as_ushort(decoded(w, e, row, c)); + } + uint4 o; + o.x = h[0] | (uint32_t)h[1] << 16; + o.y = h[2] | (uint32_t)h[3] << 16; + o.z = h[4] | (uint32_t)h[5] << 16; + o.w = h[6] | (uint32_t)h[7] << 16; + return o; +} + +template +__device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, Weight w, + int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, + const int* __restrict__ members, void* __restrict__ out, int N, int skip) { + const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; + const int units = __ldg(item_count) * NB; + for (int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); unit < units; unit += gridDim.x * WARPS) { + const int it = unit / NB, cb = unit - it * NB; + const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); + if (e == skip) continue; + for (int r0 = 0; r0 < cnt; r0 += 16 * RT) { + bool v[RT][2]; + int pr[RT][2]; + const __nv_bfloat16* x[RT][2]; +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int h = 0; h < 2; ++h) { + const int i = r0 + 16 * r + gq + 8 * h; + v[r][h] = i < cnt; + pr[r][h] = v[r][h] ? __ldg(members + first + i) : 0; + x[r][h] = X + (size_t)(slots ? pr[r][h] / slots : pr[r][h]) * x_stride + 4 * t; + } + float acc[1][RT][NTW][4]; +#pragma unroll + for (int r = 0; r < RT; ++r) +#pragma unroll + for (int j = 0; j < NTW; ++j) acc[0][r][j][0] = acc[0][r][j][1] = acc[0][r][j][2] = acc[0][r][j][3] = 0.f; + const uint2 zero = make_uint2(0u, 0u); + for (int g = 0; g < KG; ++g) { + uint4 ww[NTW]; +#pragma unroll + for (int j = 0; j < NTW; ++j) ww[j] = ld_w(w, e, cb, g, lane, j); +#pragma unroll + for (int r = 0; r < RT; ++r) { + uint2 xa[2], xb[2]; +#pragma unroll + for (int q = 0; q < 2; ++q) { + xa[q] = v[r][0] ? __ldg(reinterpret_cast(x[r][0] + 32 * g + 16 * q)) : zero; + xb[q] = v[r][1] ? __ldg(reinterpret_cast(x[r][1] + 32 * g + 16 * q)) : zero; + } +#pragma unroll + for (int q = 0; q < 2; ++q) +#pragma unroll + for (int j = 0; j < NTW; ++j) + mma(acc[0][r][j], xa[q].x, xb[q].x, xa[q].y, xb[q].y, q ? ww[j].z : ww[j].x, q ? ww[j].w : ww[j].y); + } + } +#pragma unroll + for (int r = 0; r < RT; ++r) + epilogue<3, 1, RT>(acc, r, out, N, cb * COLS + 2 * t, pr[r][0], pr[r][1], v[r][0], v[r][1], 0.f); + } + } +} + +__device__ __forceinline__ void act(const __nv_bfloat16* __restrict__ gate, const __nv_bfloat16* __restrict__ up, + __nv_bfloat16* __restrict__ out, int n, float gate_cap, float up_cap) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float raw = __bfloat162float(gate[i]); + const float g = gate_cap * tanhf(raw / gate_cap); + const float u = up_cap * tanhf(__bfloat162float(up[i]) / up_cap); + // σ(raw) is its own FP32 rounding before the two left-to-right products (§6.4). + const float sigmoid = 1.f / (1.f + expf(-raw)); + const float a = g * sigmoid * u; + out[i] = __float2bfloat16_rn(a); +} + +__device__ __forceinline__ void combine(const int32_t* __restrict__ pick, const float* __restrict__ wts, + const __nv_bfloat16* __restrict__ ey, __nv_bfloat16* __restrict__ out, + int rows, int hidden, int slots, int experts) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * hidden) return; + const int r = i / hidden, h = i - r * hidden; + float total = 0.f; + uint32_t seen = 0; + for (int n = 0; n < slots; ++n) { + int best = -1; + int32_t id = 0; + for (int s = 0; s < slots; ++s) { + if (seen & (1u << s)) continue; + const int32_t expert = pick[r * slots + s]; + if (expert < 0 || expert >= experts) continue; + if (best < 0 || expert < id) { + best = s; + id = expert; + } + } + if (best < 0) break; + seen |= 1u << best; + const int pair = r * slots + best; + const float term = __fmul_rn(__ldg(wts + pair), __bfloat162float(ey[pair * hidden + h])); + total = __fadd_rn(total, term); + } + out[i] = __float2bfloat16_rn(total); +} + +} // namespace ink2o + +// Pair indices are row * slots + slot. Items hold a physical expert ID, a global member offset and a count. +extern "C" __global__ void __launch_bounds__(32) tf_ink2moe_plan(const int32_t* __restrict__ pick, + int* __restrict__ items, int* __restrict__ members, int* __restrict__ item_count, + int rows, int slots, int experts, int tile) { + if (blockIdx.x || threadIdx.x) return; + const int pairs = rows * slots; + int used = 0, at = 0; + for (int e = 0; e < experts; ++e) { + const int first = used; + for (int pair = 0; pair < pairs; ++pair) { + if (pick[pair] == e) members[used++] = pair; + } + const int count = used - first; + for (int off = 0; off < count; off += tile) { + items[3 * at] = e; + items[3 * at + 1] = first + off; + items[3 * at + 2] = (count - off < tile) ? count - off : tile; + ++at; + } + } + *item_count = at; +} + +#define TF_INK2_MOE(NAME, RT) \ + extern "C" __global__ void __launch_bounds__(128) NAME(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, \ + ink2o::Weight w, int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, \ + const int* __restrict__ members, void* __restrict__ out, int N, int skip) { \ + ink2o::body(X, x_stride, slots, w, KG, NB, items, item_count, members, out, N, skip); \ + } +TF_INK2_MOE(tf_ink2moe_up, 1) +TF_INK2_MOE(tf_ink2moe_prompt_up, 4) +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_act(const __nv_bfloat16* g, const __nv_bfloat16* u, __nv_bfloat16* o, int n, float gc, float uc) { + ink2o::act(g, u, o, n, gc, uc); +} +extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_combine(const int32_t* p, const float* w, const __nv_bfloat16* e, + __nv_bfloat16* o, int rows, int hidden, int slots, int experts) { + ink2o::combine(p, w, e, o, rows, hidden, slots, experts); +} diff --git a/zig/kernels/cuda/inkling2/ops.cu b/zig/kernels/cuda/inkling2/ops.cu index 2e26fc6892c..648eb50686d 100644 --- a/zig/kernels/cuda/inkling2/ops.cu +++ b/zig/kernels/cuda/inkling2/ops.cu @@ -3,7 +3,6 @@ #include #include #include - #include "exl3_decode.cuh" namespace ink2o { @@ -97,10 +96,20 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix(const MixArgs a) { return a.partial_bf16 ? bf(reinterpret_cast(sp)[i]) : reinterpret_cast(sp)[i]; }; if (a.query) { - // every block's sums in one pass and one reduction: each sum adds in the order it did block by block - float v[kV]; + // Normalize each source before its query dot; both passes retain the declared strided/shuffle reduction. + float ss[kMaxBlocks + 1] = {}; + for (int c0 = 0; c0 < C; c0 += kMixCols) { + mixStage(a, row, c0, sb, sp); + for (int i = threadIdx.x; i < kMixCols && c0 + i < C; i += blockDim.x) { #pragma unroll - for (int i = 0; i < kV; ++i) v[i] = 0.0f; + for (int j = 0; j < kMaxBlocks + 1; ++j) + if (j < n) { const float x = entry(j, i); ss[j] += x * x; } + } + __syncthreads(); + } + blockSums(ss, sh); + if (threadIdx.x == 0) for (int j = 0; j < n; ++j) rr[j] = rsqrtf(ss[j] / C + 1e-6f); __syncthreads(); + float v[kV] = {}; for (int c0 = 0; c0 < C; c0 += kMixCols) { mixStage(a, row, c0, sb, sp); for (int i = threadIdx.x; i < kMixCols && c0 + i < C; i += blockDim.x) { @@ -109,26 +118,18 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix(const MixArgs a) { #pragma unroll for (int q = 0; q < kMaxQueries; ++q) qc[q] = q < a.nq ? a.query[static_cast(q) * C + c] : 0.0f; #pragma unroll - for (int j = 0; j < kMaxBlocks + 1; ++j) { - if (j < n) { - const float x = entry(j, i); - v[j * (1 + kMaxQueries)] += x * x; + for (int j = 0; j < kMaxBlocks + 1; ++j) if (j < n) { + const float normalized = entry(j, i) * rr[j]; #pragma unroll - for (int q = 0; q < kMaxQueries; ++q) - if (q < a.nq) v[j * (1 + kMaxQueries) + 1 + q] += x * qc[q]; - } + for (int q = 0; q < kMaxQueries; ++q) + if (q < a.nq) v[j * (1 + kMaxQueries) + 1 + q] += qc[q] * normalized; } } - __syncthreads(); // the next slice overwrites the staged one + __syncthreads(); } blockSums(v, sh); - if (threadIdx.x == 0) - for (int j = 0; j < n; ++j) { - const float r = rsqrtf(v[j * (1 + kMaxQueries)] / C + 1e-6f); - rr[j] = r; - for (int q = 0; q < a.nq; ++q) - wts[q][j] = v[j * (1 + kMaxQueries) + 1 + q] * r * rsqrtf(static_cast(C)); - } + if (threadIdx.x == 0) for (int j = 0; j < n; ++j) for (int q = 0; q < a.nq; ++q) wts[q][j] = + v[j * (1 + kMaxQueries) + 1 + q] * rsqrtf(static_cast(C)); __syncthreads(); if (threadIdx.x < a.nq) { float* l = wts[threadIdx.x]; @@ -199,18 +200,19 @@ extern "C" __global__ void __launch_bounds__(512) tf_ink2_mix_rows(const MixArgs }; if (a.query) { for (int j = 0; j < n; ++j) { - float v[1 + kMaxQueries] = {0.0f, 0.0f, 0.0f, 0.0f}; + float ss[1] = {0.0f}; + for (int c = threadIdx.x; c < C; c += blockDim.x) { const float x = entry(j, c); ss[0] += x * x; } + blockSums<1>(ss, sh); if (threadIdx.x == 0) rr[j] = rsqrtf(ss[0] / C + 1e-6f); + } + __syncthreads(); + for (int j = 0; j < n; ++j) { + float dots[kMaxQueries] = {0.0f, 0.0f, 0.0f}; for (int c = threadIdx.x; c < C; c += blockDim.x) { - const float x = entry(j, c); - v[0] += x * x; - for (int q = 0; q < a.nq; ++q) v[1 + q] += x * a.query[static_cast(q) * C + c]; - } - blockSums<1 + kMaxQueries>(v, sh); - const float r = rsqrtf(v[0] / C + 1e-6f); - if (threadIdx.x == 0) { - rr[j] = r; - for (int q = 0; q < a.nq; ++q) wts[q][j] = v[1 + q] * r * rsqrtf(static_cast(C)); + const float normalized = entry(j, c) * rr[j]; for (int q = 0; q < a.nq; ++q) + dots[q] += a.query[static_cast(q) * C + c] * normalized; } + blockSums(dots, sh); + if (threadIdx.x == 0) for (int q = 0; q < a.nq; ++q) wts[q][j] = dots[q] * rsqrtf(static_cast(C)); } __syncthreads(); if (threadIdx.x < a.nq) { diff --git a/zig/kernels/cuda/inkling2/vision.cu b/zig/kernels/cuda/inkling2/vision.cu new file mode 100644 index 00000000000..5b0468bb4a7 --- /dev/null +++ b/zig/kernels/cuda/inkling2/vision.cu @@ -0,0 +1,203 @@ +// Inkling 2's vision tower glue: patch rows to the sequence, axial rotary, layer-scaled residuals, full attention. +#include +#include + +#include "prefill_attention.cuh" + +namespace ink2v { + +using namespace tf_prefill_attention; + +constexpr int kWidth = 1024; // the tower's hidden size +constexpr int kHeads = 16; +constexpr int kDim = 64; +constexpr int kPairs = kDim / 2; +constexpr int kThreads = 256; + +__device__ __forceinline__ float bf(__nv_bfloat16 v) { return __bfloat162float(v); } + +__device__ __forceinline__ __nv_bfloat16 tobf(float v) { return __float2bfloat16_rn(v); } + +// prefill_attention.cu's vision_kernel body (v1.2.7, verbatim): 16 query rows a warp, 64-key tiles, online softmax. +template +__device__ __forceinline__ void attend(const __nv_bfloat16* __restrict__ qkv, __nv_bfloat16* __restrict__ out, int W, int HO, + float scale) { + static_assert(D % 16 == 0, "whole 16-dim steps"); + constexpr int C = D / 8, RS = C + 1, K16 = D / 16, NT = BN / 8, THREADS = 32 * WARPS; + extern __shared__ uint4 smem[]; + const int warp = threadIdx.x / 32, lane = threadIdx.x % 32, g = lane / 4, qd = lane % 4, mt = lane / 8; + const int head = blockIdx.y, wrow = (blockIdx.x * WARPS + warp) * 16, last = W - 1, tiles = (W + BN - 1) / BN; + const int64_t stride = 3LL * HO * D; + const __nv_bfloat16* __restrict__ q = qkv + head * D; + const __nv_bfloat16* __restrict__ kc = qkv + (HO + head) * D; + const __nv_bfloat16* __restrict__ vc = qkv + (2 * HO + head) * D; + auto stage = [&](int t) { // tile t's K rows then V rows into buffer t % 2 + uint4* dst = smem + (t & 1) * 2 * BN * RS; + for (int i = threadIdx.x; i < 2 * BN * C; i += THREADS) { + const int kv = i / (BN * C), r = (i / C) % BN, c = i % C, key = t * BN + r; + const bool in = key < W; + cp16z(dst + (kv * BN + r) * RS + c, (kv ? vc : kc) + (int64_t)(in ? key : 0) * stride + c * 8, in); + } + commit(); + }; + uint32_t qa[K16][4]; + const int r0 = wrow + g, r1 = r0 + 8; + { + const uint32_t* q0 = reinterpret_cast(q + (int64_t)min(r0, last) * stride); + const uint32_t* q1 = reinterpret_cast(q + (int64_t)min(r1, last) * stride); +#pragma unroll + for (int k = 0; k < K16; ++k) { + qa[k][0] = r0 < W ? q0[8 * k + qd] : 0u; + qa[k][1] = r1 < W ? q1[8 * k + qd] : 0u; + qa[k][2] = r0 < W ? q0[8 * k + qd + 4] : 0u; + qa[k][3] = r1 < W ? q1[8 * k + qd + 4] : 0u; + } + } + float o[C][4]; +#pragma unroll + for (int i = 0; i < C; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.0f; + float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.0f, l1 = 0.0f; + stage(0); + for (int t = 0; t < tiles; ++t) { + cp_wait<0>(); + __syncthreads(); // tile t landed, and every warp is done with tile t - 1 + if (t + 1 < tiles) stage(t + 1); + const uint4* ks = smem + (t & 1) * 2 * BN * RS; + const uint4* vs = ks + BN * RS; + float sc[NT][4]; +#pragma unroll + for (int k = 0; k < K16; ++k) { +#pragma unroll + for (int n = 0; n < NT; n += 2) { + uint32_t b[4]; + ldmatrix4(b, ks + (8 * (n + mt / 2) + lane % 8) * RS + 2 * k + mt % 2); + if (k == 0) { + mma0(sc[n], qa[k], b[0], b[1]); + mma0(sc[n + 1], qa[k], b[2], b[3]); + } else { + mma(sc[n], qa[k], b[0], b[1]); + mma(sc[n + 1], qa[k], b[2], b[3]); + } + } + } + const int kb = t * BN + 2 * qd; + float tm0 = -INFINITY, tm1 = -INFINITY; +#pragma unroll + for (int n = 0; n < NT; ++n) { + const int c = kb + 8 * n; + sc[n][0] = c <= last ? __fmul_rn(sc[n][0], scale) : -INFINITY; + sc[n][1] = c + 1 <= last ? __fmul_rn(sc[n][1], scale) : -INFINITY; + sc[n][2] = c <= last ? __fmul_rn(sc[n][2], scale) : -INFINITY; + sc[n][3] = c + 1 <= last ? __fmul_rn(sc[n][3], scale) : -INFINITY; + tm0 = fmaxf(tm0, fmaxf(sc[n][0], sc[n][1])); + tm1 = fmaxf(tm1, fmaxf(sc[n][2], sc[n][3])); + } + for (int x = 1; x <= 2; x *= 2) { + tm0 = fmaxf(tm0, __shfl_xor_sync(0xffffffffu, tm0, x)); + tm1 = fmaxf(tm1, __shfl_xor_sync(0xffffffffu, tm1, x)); + } + const bool act0 = tm0 != -INFINITY, act1 = tm1 != -INFINITY; + const float n0 = act0 ? fmaxf(m0, tm0) : m0, n1 = act1 ? fmaxf(m1, tm1) : m1; + const float a0 = act0 ? (m0 == -INFINITY ? 0.0f : texp(__fsub_rn(m0, n0))) : 1.0f; + const float a1 = act1 ? (m1 == -INFINITY ? 0.0f : texp(__fsub_rn(m1, n1))) : 1.0f; + float c0[NT], c1[NT]; +#pragma unroll + for (int n = 0; n < NT; ++n) { + const int c = kb + 8 * n; + sc[n][0] = act0 && c <= last ? texp(__fsub_rn(sc[n][0], n0)) : 0.0f; + sc[n][1] = act0 && c + 1 <= last ? texp(__fsub_rn(sc[n][1], n0)) : 0.0f; + sc[n][2] = act1 && c <= last ? texp(__fsub_rn(sc[n][2], n1)) : 0.0f; + sc[n][3] = act1 && c + 1 <= last ? texp(__fsub_rn(sc[n][3], n1)) : 0.0f; + c0[n] = __fadd_rn(sc[n][0], sc[n][1]); + c1[n] = __fadd_rn(sc[n][2], sc[n][3]); + } + l0 = __fmaf_rn(l0, a0, rowsum(c0)); + l1 = __fmaf_rn(l1, a1, rowsum(c1)); + m0 = n0; + m1 = n1; +#pragma unroll + for (int i = 0; i < C; ++i) { + o[i][0] = __fmul_rn(o[i][0], a0); + o[i][1] = __fmul_rn(o[i][1], a0); + o[i][2] = __fmul_rn(o[i][2], a1); + o[i][3] = __fmul_rn(o[i][3], a1); + } +#pragma unroll + for (int j = 0; j < NT / 2; ++j) { // 16-key chunks, in key order for every output tile + const uint32_t pa[4] = {pack(sc[2 * j][0], sc[2 * j][1]), pack(sc[2 * j][2], sc[2 * j][3]), + pack(sc[2 * j + 1][0], sc[2 * j + 1][1]), pack(sc[2 * j + 1][2], sc[2 * j + 1][3])}; +#pragma unroll + for (int i = 0; i < C; i += 2) { + uint32_t b[4]; + ldmatrix4t(b, vs + (16 * j + 8 * (mt % 2) + lane % 8) * RS + i + mt / 2); + mma(o[i], pa, b[0], b[1]); + mma(o[i + 1], pa, b[2], b[3]); + } + } + } +#pragma unroll + for (int i = 0; i < C; ++i) { + const int d = 8 * i + 2 * qd; + if (r0 < W) + *reinterpret_cast(out + ((int64_t)r0 * HO + head) * D + d) = + pack(tdiv(o[i][0], l0), tdiv(o[i][1], l0)); + if (r1 < W) + *reinterpret_cast(out + ((int64_t)r1 * HO + head) * D + d) = + pack(tdiv(o[i][2], l1), tdiv(o[i][3], l1)); + } +} + +} // namespace ink2v + +using namespace ink2v; + +// Block a head and 128 rows: every row of one picture over all its rows (no mask), q | k | v heads of qkv [W, 3 H 64]. +extern "C" __global__ void __launch_bounds__(256) tf_ink2v_attention(const __nv_bfloat16* __restrict__ qkv, + __nv_bfloat16* __restrict__ out, int W, int HO, + float scale) { + attend(qkv, out, W, HO, scale); +} + +// Block a sequence row: row 0 the class token bf16(cls + cls_pos), row r the patch r - 1 plus its resampled position. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_embed(const __nv_bfloat16* __restrict__ pe, + const __nv_bfloat16* __restrict__ table, + const uint32_t* __restrict__ taps, + const float* __restrict__ wts, + const __nv_bfloat16* __restrict__ cls, + const __nv_bfloat16* __restrict__ cls_pos, + __nv_bfloat16* __restrict__ x) { + const int r = blockIdx.x; + for (int c = threadIdx.x; c < kWidth; c += kThreads) { + float v; + if (r == 0) { + v = __fadd_rn(bf(cls[c]), bf(cls_pos[c])); + } else { + const int p = r - 1; + float s = 0.0f; + for (int t = 0; t < 4; ++t) s = __fadd_rn(s, __fmul_rn(bf(table[(int64_t)taps[p * 4 + t] * kWidth + c]), wts[p * 4 + t])); + v = __fadd_rn(bf(pe[(int64_t)p * kWidth + c]), bf(tobf(s))); + } + x[(int64_t)r * kWidth + c] = tobf(v); + } +} + +// Block a row: q and k of qkv [rows, 3 H 64] turned in place, pair j by cos, sin [rows][32]; fp32 as torch, then bf16. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_rope(__nv_bfloat16* __restrict__ qkv, const float* __restrict__ cs, + const float* __restrict__ sn) { + const int r = blockIdx.x; + for (int i = threadIdx.x; i < 2 * kHeads * kPairs; i += kThreads) { + const int j = i % kPairs; + __nv_bfloat16* p = qkv + (int64_t)r * 3 * kWidth + (i / kPairs) * kDim + 2 * j; + const float c = cs[r * kPairs + j], s = sn[r * kPairs + j], a = bf(p[0]), b = bf(p[1]); + p[0] = tobf(__fadd_rn(__fmul_rn(a, c), __fmul_rn(-b, s))); + p[1] = tobf(__fadd_rn(__fmul_rn(b, c), __fmul_rn(a, s))); + } +} + +// x [count] = bf16(x + bf16(gamma[i % width] y)): the layer-scaled residual add of an attention or MLP output. +extern "C" __global__ void __launch_bounds__(kThreads) tf_ink2v_scale_add(__nv_bfloat16* __restrict__ x, const __nv_bfloat16* __restrict__ y, + const __nv_bfloat16* __restrict__ gamma, int64_t count) { + const int64_t i = (int64_t)blockIdx.x * kThreads + threadIdx.x; + if (i >= count) return; + x[i] = tobf(__fadd_rn(bf(x[i]), bf(tobf(__fmul_rn(bf(gamma[i % kWidth]), bf(y[i])))))); +} diff --git a/zig/kernels/metal/inkling2/attention.metal b/zig/kernels/metal/inkling2/attention.metal new file mode 100644 index 00000000000..cc4aa7a79f7 --- /dev/null +++ b/zig/kernels/metal/inkling2/attention.metal @@ -0,0 +1,170 @@ +//! Inkling 2 Mini's scalar attention preparation, chunk decode and ordered sink/gate merge. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint D = 128, REL = 16, EXTENT = 1024; +constant constexpr float LOG2E = 1.4426950408889634f; + +struct InkSeg { + int row0, n, p0, pad; + long off; +}; +struct InkPrepArgs { + uint heads, kv_heads, ring, global; + float qk_clip, rel_clip, floor_pos, alpha, eps; +}; +struct InkAttnArgs { + uint heads, kv_heads, ring, window, chunk, c0, chunks; + float scale; +}; +struct InkMergeArgs { + uint heads, window, chunk, c0, chunks, subs; +}; + +inline float ink_warp_sum(float v) { + for (uint o = 16; o; o >>= 1) v += simd_shuffle_xor(v, ushort(o)); + return v; +} +inline float ink_clip_factor(float ss, float threshold) { + return fmin(threshold / (precise::sqrt(ss) + 1e-6f), 1.0f); +} + +// One 32-thread group handles a row and head; independent q/k/v and relative rows keep their first BF16 rounding. +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_ink2_prep(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], + const device bfloat* v_raw [[buffer(2)]], const device bfloat* rel_raw [[buffer(3)]], + const device bfloat* q_scale [[buffer(4)]], const device bfloat* rel_scale [[buffer(5)]], + const device int* rpos [[buffer(6)]], const device int* rseg [[buffer(7)]], + const device InkSeg* segs [[buffer(8)]], device bfloat* q_out [[buffer(9)]], + device bfloat* rel_out [[buffer(10)]], device bfloat* kc [[buffer(11)]], device bfloat* vc [[buffer(12)]], + constant InkPrepArgs& a [[buffer(13)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + const uint row = tg.x, unit = tg.y, pos = uint(rpos[row]); + const float tau = a.global ? 1.0f + a.alpha * precise::log(max(float(pos + 1) / a.floor_pos, 1.0f)) : 1.0f; + float x[4]; + if (unit < a.heads) { + const size_t rh = size_t(row) * a.heads + unit; + for (uint i = 0; i < 4; ++i) x[i] = float(q_raw[rh * D + lane * 4 + i]) * float(q_scale[unit * D + lane * 4 + i]); + float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + const float f = ink_clip_factor(ink_warp_sum(ss), a.qk_clip); + for (uint i = 0; i < 4; ++i) { + x[i] *= f; + const bfloat once = bfloat(x[i]); + q_out[rh * D + lane * 4 + i] = a.global ? bfloat(float(once) * tau) : once; + } + const float r = lane < REL ? float(rel_raw[rh * REL + lane]) * float(rel_scale[unit * REL + lane]) : 0.0f; + const float rf = ink_clip_factor(ink_warp_sum(r * r), a.rel_clip); + if (lane < REL) { + const bfloat once = bfloat(r * rf); + rel_out[rh * REL + lane] = a.global ? bfloat(float(once) * tau) : once; + } + return; + } + const bool key = unit < a.heads + a.kv_heads; + const uint h = key ? unit - a.heads : unit - a.heads - a.kv_heads; + const device bfloat* src = (key ? k_raw : v_raw) + (size_t(row) * a.kv_heads + h) * D; + for (uint i = 0; i < 4; ++i) x[i] = float(src[lane * 4 + i]); + float scale; + if (key) { + const float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + scale = ink_clip_factor(ink_warp_sum(ss), a.qk_clip); + } else { + const float ss = ((x[0] * x[0] + x[1] * x[1]) + x[2] * x[2]) + x[3] * x[3]; + scale = precise::rsqrt(ink_warp_sum(ss) / float(D) + a.eps); + } + const InkSeg s = segs[rseg[row]]; + device bfloat* dst = (key ? kc : vc) + s.off + (size_t(h) * a.ring + pos % a.ring) * D; + for (uint i = 0; i < 4; ++i) dst[lane * 4 + i] = bfloat(x[i] * scale); +} + +// The bf16 relative-bias table, one fp32 accumulation in projection tap order. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_rel_table(const device bfloat* rel [[buffer(0)]], const device bfloat* proj [[buffer(1)]], + device bfloat* tab [[buffer(2)]], uint rh [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + float r[REL]; + for (uint j = 0; j < REL; ++j) r[j] = float(rel[rh * REL + j]); + for (uint d = t; d < EXTENT; d += 256) { + float acc = 0.0f; + for (uint j = 0; j < REL; ++j) acc += r[j] * float(proj[j * EXTENT + d]); + tab[rh * EXTENT + d] = bfloat(acc); + } +} + +// A (row, head, key chunk) a simdgroup. Every P is bf16 before both its denominator add and P.V product. +[[max_total_threads_per_threadgroup(32)]] +kernel void tf_ink2_attn_scalar(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]], + const device bfloat* vc [[buffer(2)]], const device bfloat* tab [[buffer(3)]], + const device InkSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]], + const device int* rpos [[buffer(7)]], const device int* rseg [[buffer(8)]], constant InkAttnArgs& a [[buffer(9)]], + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + const uint rh = tg.x, row = rh / a.heads, h = rh % a.heads, group = a.heads / a.kv_heads, kvh = h / group; + const uint pos = uint(rpos[row]); + const uint lo = a.window && pos + 1 > a.window ? pos + 1 - a.window : 0; + const uint first = a.window ? lo / a.chunk : a.c0; + const uint c = first + tg.y; + if (c > pos / a.chunk || (a.window && c < lo / a.chunk)) return; + const uint from = max(lo, c * a.chunk), to = min(pos + 1, (c + 1) * a.chunk); + const InkSeg s = segs[rseg[row]]; + const size_t head = s.off + size_t(kvh) * a.ring * D; + const size_t prow = rh; + float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + float top = -INFINITY, total = 0.0f; + for (uint kp = from; kp < to; ++kp) { + const size_t at = head + size_t(kp % a.ring) * D; + float4 qv = float4(*(const device bfloat4*)(q + prow * D + lane * 4)); + float4 kv = float4(*(const device bfloat4*)(kc + at + lane * 4)); + const float dot_score = ink_warp_sum(dot(qv, kv)); + const uint distance = pos - kp; + const float bias = distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f; + const float score = (dot_score * a.scale + bias) * LOG2E; + const float next = max(top, score), a0 = precise::exp2(top - next), b0 = precise::exp2(score - next); + const bfloat p = bfloat(b0); + total = total * a0 + float(p); + for (uint i = 0; i < 4; ++i) acc[i] = acc[i] * a0 + float(p) * float(vc[at + lane * 4 + i]); + top = next; + } + const size_t slot = size_t(prow) * a.chunks + tg.y; + if (lane == 0) part_ml[slot] = float2(top, total); + for (uint i = 0; i < 4; ++i) part_o[slot * D + lane * 4 + i] = acc[i]; +} + +// Fold chunks and any sub-chunks in order, add the sink logit, apply the gate, round once to bf16. +[[max_total_threads_per_threadgroup(128)]] +kernel void tf_ink2_merge(const device float* part_o [[buffer(0)]], const device float2* part_ml [[buffer(1)]], + const device bfloat* sink [[buffer(2)]], const device bfloat* gate [[buffer(3)]], const device int* rpos [[buffer(4)]], + device bfloat* out [[buffer(5)]], constant InkMergeArgs& a [[buffer(6)]], uint rh [[threadgroup_position_in_grid]], + uint d [[thread_index_in_threadgroup]]) { + const uint row = rh / a.heads, pos = uint(rpos[row]); + const uint lo = a.window && pos + 1 > a.window ? pos + 1 - a.window : 0; + float mm = -INFINITY, ll = 0.0f, o = 0.0f; + for (uint c = lo / a.chunk; c <= pos / a.chunk; ++c) { + float cm, cl, co; + if (a.subs > 1) { + float sm = -INFINITY, sl = 0.0f, so = 0.0f; + const uint last = min(a.subs - 1, (pos - c * a.chunk) / 1024); + for (uint u = 0; u <= last; ++u) { + const size_t at = size_t(rh) * a.chunks + (c - a.c0) * a.subs + u; + const float2 ml = part_ml[at]; + const float mn = max(sm, ml.x); + const float x = precise::exp2(sm - mn), y = precise::exp2(ml.x - mn); + sl = sl * x + ml.y * y; + so = so * x + part_o[at * D + d] * y; + sm = mn; + } + cm = sm; cl = sl; co = so; + } else { + const size_t at = size_t(rh) * a.chunks + c - (a.window ? lo / a.chunk : a.c0); + const float2 ml = part_ml[at]; + cm = ml.x; cl = ml.y; co = part_o[at * D + d]; + } + const float mn = max(mm, cm), x = precise::exp2(mm - mn), y = precise::exp2(cm - mn); + ll = ll * x + cl * y; + o = o * x + co * y; + mm = mn; + } + const float sk = float(sink[rh]) * LOG2E, mf = max(mm, sk), a0 = precise::exp2(mm - mf); + const float y = o * a0 / (ll * a0 + precise::exp2(sk - mf)); + const float gv = float(gate[rh * D + d]); + out[rh * D + d] = bfloat(y * (1.0f / (1.0f + precise::exp(-gv)))); +} diff --git a/zig/kernels/metal/inkling2/attention_sources.zig b/zig/kernels/metal/inkling2/attention_sources.zig new file mode 100644 index 00000000000..1aac8a107e1 --- /dev/null +++ b/zig/kernels/metal/inkling2/attention_sources.zig @@ -0,0 +1,5 @@ +//! Shader texts; the prompt's fragment helpers are inline so both chip paths use the same resolver. + +pub const attention = @embedFile("attention.metal"); +pub const prompt_attention = @embedFile("../nax.h") ++ @embedFile("prompt_attention.metal"); +pub const prompt_attention_pre_m5 = "#define TF_SIMD_FRAGS 1\n" ++ prompt_attention; diff --git a/zig/kernels/metal/inkling2/dspark.metal b/zig/kernels/metal/inkling2/dspark.metal new file mode 100644 index 00000000000..be21a1f33c5 --- /dev/null +++ b/zig/kernels/metal/inkling2/dspark.metal @@ -0,0 +1,295 @@ +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant uint DSP_H = 2304; +constant uint DSP_Q = 3072; +constant uint DSP_KV = 1024; +constant uint DSP_HEAD = 128; +constant uint DSP_RANK = 256; +constant uint DSP_RNN = 768; +constant float DSP_EPS = 1e-6f; +constant float DSP_SCALE = 0x1.6a09e6p-4f; + +struct DsparkPositionArgs { uint base; }; +struct DsparkContextArgs { uint base, rows, ring; }; +struct DsparkAttentionArgs { uint committed, ring, local, from; }; +struct DsparkTokenArgs { uint token; }; +struct DsparkResidualArgs { uint init; }; +struct DsparkCountArgs { uint count; }; +struct DsparkBaseArgs { uint rows, vocab; }; + +kernel void tf_ink2_dspark_init_rows(const device bfloat* anchor [[buffer(0)]], const device bfloat* mask [[buffer(1)]], device bfloat* rows [[buffer(2)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + for (uint d = t; d < DSP_H; d += 256) { + const device bfloat* src = row == 0 ? anchor : mask; + rows[row * DSP_H + d] = src[d]; + } +} + +kernel void tf_ink2_dspark_fuse_taps(const device bfloat* taps [[buffer(0)]], const device bfloat* fuse_weight [[buffer(1)]], const device bfloat* norm_weight [[buffer(2)]], device bfloat* c [[buffer(3)]], device bfloat* newest_f [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint group [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + const uint fusion = group / a.count, row = group % a.count; + threadgroup float alpha[4]; + threadgroup float scale; + if (t == 0) { + float scores[4]; + float peak = -INFINITY; + for (uint j = 0; j < 4; ++j) { scores[j] = float(fuse_weight[fusion * 4 + j]); peak = max(peak, scores[j]); } + float sum = 0.0f; + for (uint j = 0; j < 4; ++j) { scores[j] = exp(scores[j] - peak); sum += scores[j]; } + for (uint j = 0; j < 4; ++j) alpha[j] = float(bfloat(scores[j] / sum)); + float square = 0.0f; + for (uint d = 0; d < DSP_H; ++d) { + float mixed = 0.0f; + for (uint j = 0; j < 4; ++j) mixed += alpha[j] * float(taps[(row * 4 + j) * DSP_H + d]); + square += mixed * mixed; + } + scale = rsqrt(square / float(DSP_H) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < DSP_H; d += 256) { + float mixed = 0.0f; + for (uint j = 0; j < 4; ++j) mixed += alpha[j] * float(taps[(row * 4 + j) * DSP_H + d]); + const bfloat out = bfloat(mixed * scale * float(norm_weight[fusion * DSP_H + d])); + c[(fusion * a.count + row) * DSP_H + d] = out; + if (fusion == 3 && row + 1 == a.count) newest_f[d] = out; + } +} + +static inline float dspark_rope_angle(uint d, uint position) { + const uint pair = d % 64; + const float frequency = pow(1e6f, -float(pair) / 64.0f); + return float(position) * frequency; +} + +kernel void tf_ink2_dspark_block_qkv(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], const device bfloat* v_raw [[buffer(2)]], const device bfloat* q_weight [[buffer(3)]], const device bfloat* k_weight [[buffer(4)]], device bfloat* q [[buffer(5)]], device bfloat* k [[buffer(6)]], device bfloat* v [[buffer(7)]], constant DsparkPositionArgs& a [[buffer(8)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 40, work = group % 40; + threadgroup float scale; + if (work < 32 && d == 0) { + float sum = 0.0f; + if (work < 24) { + const uint h = work; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(q_raw[row * DSP_Q + h * DSP_HEAD + i]); sum += x * x; } + } else { + const uint h = work - 24; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(k_raw[row * DSP_KV + h * DSP_HEAD + i]); sum += x * x; } + } + scale = rsqrt(sum / float(DSP_HEAD) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (work >= 32) { + const uint h = work - 32; + v[row * DSP_KV + h * DSP_HEAD + d] = v_raw[row * DSP_KV + h * DSP_HEAD + d]; + return; + } + const bool query = work < 24; + const uint h = query ? work : work - 24; + const uint at = row * (query ? DSP_Q : DSP_KV) + h * DSP_HEAD + d; + const float x = float(bfloat(float(query ? q_raw[at] : k_raw[at]) * scale * float(query ? q_weight[d] : k_weight[d]))); + const uint partner = d < 64 ? d + 64 : d - 64; + const uint other_at = row * (query ? DSP_Q : DSP_KV) + h * DSP_HEAD + partner; + const float other = float(bfloat(float(query ? q_raw[other_at] : k_raw[other_at]) * scale * float(query ? q_weight[partner] : k_weight[partner]))); + const float angle = dspark_rope_angle(d, a.base + row); + const float cs = cos(angle), sn = sin(angle); + const float rotated = d < 64 ? x * cs - other * sn : other * sn + x * cs; + if (query) q[at] = bfloat(rotated); else k[at] = bfloat(rotated); +} + +kernel void tf_ink2_dspark_context_kv(const device bfloat* k_raw [[buffer(0)]], const device bfloat* v_raw [[buffer(1)]], const device bfloat* weight [[buffer(2)]], device bfloat* keys [[buffer(3)]], device bfloat* values [[buffer(4)]], constant DsparkContextArgs& a [[buffer(5)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 8, h = group % 8; + threadgroup float scale; + if (d == 0) { + float sum = 0.0f; + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(k_raw[row * DSP_KV + h * DSP_HEAD + i]); sum += x * x; } + scale = rsqrt(sum / float(DSP_HEAD) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint position = a.base + row; + const uint at = (position % a.ring) * DSP_KV + h * DSP_HEAD + d; + const uint src = row * DSP_KV + h * DSP_HEAD + d; + const uint partner = d < 64 ? d + 64 : d - 64; + const float x = float(bfloat(float(k_raw[src]) * scale * float(weight[d]))); + const float other = float(bfloat(float(k_raw[row * DSP_KV + h * DSP_HEAD + partner]) * scale * float(weight[partner]))); + const float angle = dspark_rope_angle(d, position); + const float cs = cos(angle), sn = sin(angle); + keys[at] = bfloat(d < 64 ? x * cs - other * sn : other * sn + x * cs); + values[at] = v_raw[src]; +} + +static inline float dspark_attention_score(const device bfloat* q, const device bfloat* k, uint q_at, uint k_at) { + float dot = 0.0f; + for (uint d = 0; d < DSP_HEAD; ++d) dot += float(q[q_at + d]) * float(k[k_at + d]); + return dot * DSP_SCALE; +} + +// A threadgroup a (row, head): thread t scores keys t, t + 128, ...; the denominator and value sums stay in key order. +kernel void tf_ink2_dspark_attention(const device bfloat* q [[buffer(0)]], const device bfloat* block_k [[buffer(1)]], const device bfloat* block_v [[buffer(2)]], const device bfloat* context_k [[buffer(3)]], const device bfloat* context_v [[buffer(4)]], device float* scores [[buffer(5)]], device bfloat* out [[buffer(6)]], constant DsparkAttentionArgs& a [[buffer(7)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + const uint row = group / 24, h = group % 24, kv = h / 3; + const uint q_at = row * DSP_Q + h * DSP_HEAD; + const uint out_at = q_at + d; + const uint first = max(a.from, a.local && a.committed > 1024 ? a.committed - 1024 : 0); + const uint retained = a.committed - first; + const uint count = retained + 8; + const uint score_at = group * count; + threadgroup float peaks[128], peak, denominator; + float m = -INFINITY; + for (uint j = d; j < count; j += 128) { + const float s = j < retained + ? dspark_attention_score(q, context_k, q_at, ((first + j) % a.ring) * DSP_KV + kv * DSP_HEAD) + : dspark_attention_score(q, block_k, q_at, (j - retained) * DSP_KV + kv * DSP_HEAD); + scores[score_at + j] = s; + m = max(m, s); + } + peaks[d] = m; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (d == 0) { + float top = -INFINITY; + for (uint t = 0; t < 128; ++t) top = max(top, peaks[t]); + peak = top; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint j = d; j < count; j += 128) scores[score_at + j] = exp(scores[score_at + j] - peak); + threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device); + if (d == 0) { + float sum = 0.0f; + for (uint j = 0; j < count; ++j) sum += scores[score_at + j]; + denominator = sum; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint j = d; j < count; j += 128) scores[score_at + j] = scores[score_at + j] / denominator; + threadgroup_barrier(mem_flags::mem_threadgroup | mem_flags::mem_device); + float value = 0.0f; + for (uint j = 0; j < retained; ++j) { + const uint position = first + j; + const uint v_at = (position % a.ring) * DSP_KV + kv * DSP_HEAD + d; + value += scores[score_at + j] * float(context_v[v_at]); + } + for (uint j = 0; j < 8; ++j) { + const uint v_at = (j * DSP_KV + kv * DSP_HEAD) + d; + value += scores[score_at + retained + j] * float(block_v[v_at]); + } + out[out_at] = bfloat(value); +} + +kernel void tf_ink2_dspark_residual_norm(const device bfloat* x [[buffer(0)]], const device bfloat* residual [[buffer(1)]], const device bfloat* weight [[buffer(2)]], device bfloat* new_residual [[buffer(3)]], device bfloat* normalized [[buffer(4)]], constant DsparkResidualArgs& a [[buffer(5)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { + threadgroup float scale; + if (t == 0) { + float sum = 0.0f; + for (uint d = 0; d < DSP_H; ++d) { + const uint at = row * DSP_H + d; + const float v = a.init ? float(x[at]) : float(x[at]) + float(residual[at]); + sum += v * v; + } + scale = rsqrt(sum / float(DSP_H) + DSP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint n = 0; n < 9; ++n) { + const uint d = n * 256 + t; + const uint at = row * DSP_H + d; + const float sigma = a.init ? float(x[at]) : float(x[at]) + float(residual[at]); + new_residual[at] = bfloat(sigma); + normalized[at] = bfloat(sigma * scale * float(weight[d])); + } +} + +kernel void tf_ink2_dspark_swiglu(const device bfloat* g [[buffer(0)]], const device bfloat* u [[buffer(1)]], device bfloat* out [[buffer(2)]], constant DsparkCountArgs& a [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const float gate = float(g[i]); + out[i] = bfloat((gate / (1.0f + exp(-gate))) * float(u[i])); +} + +kernel void tf_ink2_dspark_kappa(const device bfloat* y [[buffer(0)]], const device bfloat* f [[buffer(1)]], const device bfloat* weight [[buffer(2)]], const device bfloat* bias [[buffer(3)]], device float* out [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint i [[thread_position_in_grid]]) { + const uint row = i / DSP_RNN, channel = i % DSP_RNN; + if (row >= a.count) return; + float sum = 0.0f; + for (uint d = 0; d < DSP_H; ++d) sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + 512 + d]); + for (uint d = 0; d < DSP_H; ++d) sum += float(f[d]) * float(weight[channel * 5120 + 2816 + d]); + sum += float(bias[channel]); + out[i] = sum; +} + +static inline void dspark_recurrent_step(const device bfloat* state, const device float* kappa, const device bfloat* rnn_weight, const device bfloat* markov, device bfloat* z, device bfloat* next_state, device bfloat* lambda, uint token, uint i) { + if (i >= DSP_RANK) return; + float values[3]; + for (uint part = 0; part < 3; ++part) { + const uint channel = part * DSP_RANK + i; + float sum = 0.0f; + for (uint d = 0; d < DSP_RANK; ++d) sum += float(state[d]) * float(rnn_weight[channel * 5120 + d]); + for (uint d = 0; d < DSP_RANK; ++d) sum += float(markov[uint64_t(token) * DSP_RANK + d]) * float(rnn_weight[channel * 5120 + 256 + d]); + sum += float(kappa[channel]); + const bfloat rounded = bfloat(sum); + z[channel] = rounded; + values[part] = float(rounded); + } + const bfloat gamma = bfloat(1.0f / (1.0f + exp(-values[0]))); + const bfloat candidate = bfloat(tanh(values[1])); + const bfloat keep = bfloat(1.0f - float(gamma)); + const bfloat left = bfloat(float(gamma) * float(state[i])); + const bfloat right = bfloat(float(keep) * float(candidate)); + next_state[i] = bfloat(float(left) + float(right)); + lambda[i] = bfloat(tanh(values[2])); +} + +kernel void tf_ink2_dspark_recurrent(const device bfloat* state [[buffer(0)]], const device float* kappa [[buffer(1)]], const device bfloat* rnn_weight [[buffer(2)]], const device bfloat* markov [[buffer(3)]], device bfloat* z [[buffer(4)]], device bfloat* next_state [[buffer(5)]], device bfloat* lambda [[buffer(6)]], constant DsparkTokenArgs& a [[buffer(7)]], uint i [[thread_position_in_grid]]) { + dspark_recurrent_step(state, kappa, rnn_weight, markov, z, next_state, lambda, a.token, i); +} + +// The recurrent step after held[a.token]: the chain's previous token read on the GPU. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_dspark_chain_step(const device bfloat* state [[buffer(0)]], const device float* kappa [[buffer(1)]], const device bfloat* rnn_weight [[buffer(2)]], const device bfloat* markov [[buffer(3)]], device bfloat* z [[buffer(4)]], device bfloat* next_state [[buffer(5)]], device bfloat* lambda [[buffer(6)]], constant DsparkTokenArgs& a [[buffer(7)]], const device uint* held [[buffer(8)]], uint i [[thread_position_in_grid]]) { + dspark_recurrent_step(state, kappa, rnn_weight, markov, z, next_state, lambda, held[a.token], i); +} + +// held[a.token + 1] = the first greatest of the 200,058 logits; a NaN is never chosen unless logit 0 is one. +[[max_total_threads_per_threadgroup(1024)]] +kernel void tf_ink2_dspark_chain_pick(const device bfloat* logits [[buffer(0)]], device uint* held [[buffer(1)]], constant DsparkTokenArgs& a [[buffer(2)]], uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float values[32]; + threadgroup uint places[32]; + float best = -INFINITY; + uint at = 0xffffffffu; + for (uint i = t; i < 200058u; i += 1024u) { + const float raw = float(logits[i]); + const float v = isnan(raw) ? -INFINITY : raw; + if (v > best || (v == best && i < at)) { best = v; at = i; } + } + for (ushort o = 16; o > 0; o >>= 1) { + const float ov = simd_shuffle_xor(best, o); + const uint oi = simd_shuffle_xor(at, o); + if (ov > best || (ov == best && oi < at)) { best = ov; at = oi; } + } + if (lane == 0) { values[sg] = best; places[sg] = at; } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t != 0) return; + for (uint g = 0; g < 32; ++g) + if (values[g] > best || (values[g] == best && places[g] < at)) { best = values[g]; at = places[g]; } + held[a.token + 1] = isnan(float(logits[0])) ? 0u : at; +} + +// A simdgroup an id: eight columns a lane a step, every row sharing the read of unembed[id]; rounded once to BF16. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_dspark_base(const device bfloat* unembed [[buffer(0)]], const device bfloat* y [[buffer(1)]], device bfloat* out [[buffer(2)]], constant DsparkBaseArgs& a [[buffer(3)]], + uint tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const uint id = tg * 8 + sg; + if (id >= a.vocab) return; + const device bfloat* w = unembed + size_t(id) * DSP_H; + float acc[7] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (uint i = 8 * lane; i < DSP_H; i += 256) { + const float4 w0 = float4(*(const device bfloat4*)(w + i)), w1 = float4(*(const device bfloat4*)(w + i + 4)); + for (uint row = 0; row < a.rows; ++row) { + const device bfloat* x = y + size_t(row) * DSP_H + i; + acc[row] += dot(w0, float4(*(const device bfloat4*)x)) + dot(w1, float4(*(const device bfloat4*)(x + 4))); + } + } + for (uint row = 0; row < a.rows; ++row) { + const float sum = simd_sum(acc[row]); + if (lane == 0) out[size_t(row) * a.vocab + id] = bfloat(sum); + } +} + +kernel void tf_ink2_dspark_logits(const device bfloat* base [[buffer(0)]], const device bfloat* phi [[buffer(1)]], const device bfloat* beta [[buffer(2)]], const device bfloat* lambda [[buffer(3)]], device bfloat* out [[buffer(4)]], constant DsparkCountArgs& a [[buffer(5)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + float dot = 0.0f; + for (uint d = 0; d < DSP_RANK; ++d) dot += float(phi[i * DSP_RANK + d]) * float(lambda[d]); + const bfloat bias = bfloat(float(beta[i]) + dot); + const bfloat logit = bfloat(float(base[i]) + float(bias)); + out[i] = bfloat(30.0f * tanh(float(logit) / 30.0f)); +} diff --git a/zig/kernels/metal/inkling2/dspark_sources.zig b/zig/kernels/metal/inkling2/dspark_sources.zig new file mode 100644 index 00000000000..5188d0ccb79 --- /dev/null +++ b/zig/kernels/metal/inkling2/dspark_sources.zig @@ -0,0 +1,4 @@ +//! Mini DSpark's arithmetic shader and its ten Metal library entry points. + +pub const dspark = @embedFile("dspark.metal"); +pub const dspark_units = @embedFile("../nax.h") ++ @embedFile("dspark_units.metal"); diff --git a/zig/kernels/metal/inkling2/dspark_units.metal b/zig/kernels/metal/inkling2/dspark_units.metal new file mode 100644 index 00000000000..f4e771617a8 --- /dev/null +++ b/zig/kernels/metal/inkling2/dspark_units.metal @@ -0,0 +1,142 @@ +//! Mini DSpark's block attention on the tensor units; dspark_sources prepends the tensor-fragment helpers. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint DSU_D = 128, DSU_KV = 1024, DSU_KEYS = 64, DSU_PAIRS = 24, DSU_GROUP = 3; +constant constexpr float DSU_SCALE = 0x1.6a09e6p-4f, DSU_LOG2E = 1.4426950408889634f; +struct DsparkUnitsArgs { uint committed, ring, first, chunk, chunks; }; + +// The 16x16 block at key row r, column c of a tile in a context ring; a key outside [lo, hi) reads as zero. +inline void dsu_tile_get(thread tfp::frag& f, const device bfloat* tile, int r, int c, short2 home, int lo, int hi) { + const device bfloat* p = tile + (r + home.y) * int(DSU_KV) + (c + home.x); + const bfloat none = bfloat(0); + const bfloat4 zero = bfloat4(none, none, none, none); + const int x = r + home.y, y = x + 8; + f = tfp::frag(x >= lo && x < hi ? bfloat4(*(const device bfloat4*)p) : zero, + y >= lo && y < hi ? bfloat4(*(const device bfloat4*)(p + 8 * int(DSU_KV))) : zero); +} + +inline void dsu_rows(thread const tfp::frag* s, thread float (&r)[2], bool maximum) { + for (uint f = 0; f < 4; ++f) for (uint h = 0; h < 2; ++h) { + const uint b = 4 * h; + float v = maximum ? max(max(s[f][b], s[f][b + 1]), max(s[f][b + 2], s[f][b + 3])) + : (s[f][b] + s[f][b + 1]) + (s[f][b + 2] + s[f][b + 3]); + const float x = simd_shuffle_xor(v, ushort(1)); + v = maximum ? max(v, x) : v + x; + const float y = simd_shuffle_xor(v, ushort(8)); + v = maximum ? max(v, y) : v + y; + r[h] = maximum ? max(r[h], v) : r[h] + v; + } +} + +// A key head's 24 (row, head) pairs and one chunk of the retained context a 64-thread group; a simdgroup owns 16 pairs. +[[max_total_threads_per_threadgroup(64)]] +kernel void tf_ink2_dspark_attn_units(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]], + const device bfloat* vc [[buffer(2)]], device float* part_o [[buffer(3)]], device float2* part_ml [[buffer(4)]], + constant DsparkUnitsArgs& a [[buffer(5)]], uint3 tg [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const uint kvh = tg.y, b_lo = (a.first / a.chunk + tg.x) * a.chunk, k_hi = min(b_lo + a.chunk, a.committed) - 1; + const uint m = 16 * sg; + const short2 home = tfp::frag_home(ushort(lane)); + const uint row_a = m + uint(home.y), row_b = row_a + 8; + const uint pair_a = min(row_a, DSU_PAIRS - 1), pair_b = min(row_b, DSU_PAIRS - 1); + const device bfloat* qb0 = q + ((pair_a / DSU_GROUP) * DSU_PAIRS + kvh * DSU_GROUP + pair_a % DSU_GROUP) * DSU_D; + const device bfloat* qb1 = q + ((pair_b / DSU_GROUP) * DSU_PAIRS + kvh * DSU_GROUP + pair_b % DSU_GROUP) * DSU_D; + tfp::frag acc[8]; + for (uint d = 0; d < 8; ++d) acc[d] = tfp::frag(0); + float top[2] = {-INFINITY, -INFINITY}, mass[2] = {0.0f, 0.0f}; + for (uint kt = b_lo; kt <= k_hi; kt += DSU_KEYS) { + // A tile is 64 keys from a multiple of 64 and a ring is a multiple of 64 rows, so a tile never wraps its ring. + const device bfloat* tile_k = kc + size_t(kt % a.ring) * DSU_KV + kvh * DSU_D; + const device bfloat* tile_v = vc + size_t(kt % a.ring) * DSU_KV + kvh * DSU_D; + const int lo = a.first > kt ? int(a.first - kt) : 0, hi = int(min(kt + DSU_KEYS, a.committed) - kt); + if (lo >= hi) continue; + tfp::frag score[4] = {tfp::frag(0), tfp::frag(0), tfp::frag(0), tfp::frag(0)}; + for (uint d = 0; d < 8; ++d) { + tfp::frag qa, kb0, kb1, kb2, kb3; + tfp::frag_get_rows(qa, qb0, qb1, 16 * d, home, row_a < DSU_PAIRS, row_b < DSU_PAIRS); + dsu_tile_get(kb0, tile_k, 0, 16 * d, home, lo, hi); + dsu_tile_get(kb1, tile_k, 16, 16 * d, home, lo, hi); + dsu_tile_get(kb2, tile_k, 32, 16 * d, home, lo, hi); + dsu_tile_get(kb3, tile_k, 48, 16 * d, home, lo, hi); + tfp::mma_16x32(score[0], score[1], qa, kb0, kb1); + tfp::mma_16x32(score[2], score[3], qa, kb2, kb3); + } + float peak[2] = {top[0], top[1]}; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const uint row = m + uint(home.y) + (e >> 2) * 8; + const int key = int(16 * f) + home.x + int(TF_COL(e)); + const bool live = row < DSU_PAIRS && key >= lo && key < hi; + score[f][e] = live ? score[f][e] * DSU_SCALE * DSU_LOG2E : -INFINITY; + } + dsu_rows(score, peak, true); + float keep[2]; + for (uint h = 0; h < 2; ++h) { + const float mu = peak[h] == -INFINITY ? 0.0f : peak[h]; + keep[h] = precise::exp2(top[h] - mu); + top[h] = peak[h]; mass[h] *= keep[h]; + } + tfp::frag p[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const float mu = peak[e >> 2] == -INFINITY ? 0.0f : peak[e >> 2]; + p[f][e] = bfloat(precise::exp2(score[f][e] - mu)); + } + // Reduce the rounded P, not its pre-bf16 exponential. + tfp::frag rounded[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) rounded[f][e] = float(p[f][e]); + dsu_rows(rounded, mass, false); + for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) acc[d][e] *= keep[e >> 2]; + for (uint f = 0; f < 4; ++f) for (uint d = 0; d < 8; d += 2) { + tfp::frag v0, v1; + dsu_tile_get(v0, tile_v, 16 * f, 16 * d, home, lo, hi); + dsu_tile_get(v1, tile_v, 16 * f, 16 * d + 16, home, lo, hi); + tfp::mma_16x32(acc[d], acc[d + 1], p[f], v0, v1); + } + } + for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) { + const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e); + if (row >= DSU_PAIRS) continue; + const size_t slot = size_t((row / DSU_GROUP) * DSU_PAIRS + kvh * DSU_GROUP + row % DSU_GROUP) * a.chunks + tg.x; + part_o[slot * DSU_D + 16 * d + col] = acc[d][e]; + } + if (home.x == 0) for (uint h = 0; h < 2; ++h) { + const uint row = m + uint(home.y) + 8 * h; + if (row >= DSU_PAIRS) continue; + const size_t slot = size_t((row / DSU_GROUP) * DSU_PAIRS + kvh * DSU_GROUP + row % DSU_GROUP) * a.chunks + tg.x; + part_ml[slot] = float2(top[h], mass[h]); + } +} + +// A (row, head) a 128-thread group: the block's eight keys, then the context's chunks in order, rounded once to bf16. +[[max_total_threads_per_threadgroup(128)]] +kernel void tf_ink2_dspark_attn_merge(const device bfloat* q [[buffer(0)]], const device bfloat* block_k [[buffer(1)]], + const device bfloat* block_v [[buffer(2)]], const device float* part_o [[buffer(3)]], + const device float2* part_ml [[buffer(4)]], device bfloat* out [[buffer(5)]], constant DsparkUnitsArgs& a [[buffer(6)]], + uint group [[threadgroup_position_in_grid]], uint d [[thread_index_in_threadgroup]]) { + const uint kv = (group % DSU_PAIRS) / DSU_GROUP, q_at = group * DSU_D; + threadgroup float bs[8]; + if (d < 8) { + float dot = 0.0f; + for (uint i = 0; i < DSU_D; ++i) dot += float(q[q_at + i]) * float(block_k[d * DSU_KV + kv * DSU_D + i]); + bs[d] = dot * DSU_SCALE * DSU_LOG2E; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float mm = bs[0]; + for (uint j = 1; j < 8; ++j) mm = max(mm, bs[j]); + float ll = 0.0f, o = 0.0f; + for (uint j = 0; j < 8; ++j) { + const float w = float(bfloat(precise::exp2(bs[j] - mm))); + ll += w; + o += w * float(block_v[j * DSU_KV + kv * DSU_D + d]); + } + for (uint c = 0; c < a.chunks; ++c) { + const size_t at = size_t(group) * a.chunks + c; + const float2 ml = part_ml[at]; + const float mn = max(mm, ml.x), x = precise::exp2(mm - mn), y = precise::exp2(ml.x - mn); + ll = ll * x + ml.y * y; + o = o * x + part_o[at * DSU_D + d] * y; + mm = mn; + } + out[q_at + d] = bfloat(o / ll); +} diff --git a/zig/kernels/metal/inkling2/experts.metal b/zig/kernels/metal/inkling2/experts.metal new file mode 100644 index 00000000000..46cb111f91f --- /dev/null +++ b/zig/kernels/metal/inkling2/experts.metal @@ -0,0 +1,427 @@ +// Inkling 2 Mini M3: packed weight decode in registers, BF16 activations, FP32 reductions. +#include +using namespace metal; +#pragma METAL fp contract(off) + +struct Ink2MatrixArgs { uint k, n, topk, experts; }; +struct Ink2DecodeArgs { uint rows, k; }; + +inline float ink2_e2m1(uint code) { + const float magnitude[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f}; + const float v = magnitude[code & 7u]; + return (code & 8u) ? -v : v; +} + +inline float ink2_e4m3(uint code) { + const uint exp = (code >> 3u) & 15u, mant = code & 7u; + if (exp == 15u && mant == 7u) return NAN; + const float v = exp ? ldexp(1.0f + float(mant) * 0.125f, int(exp) - 7) + : float(mant) * (1.0f / 512.0f); + return (code & 0x80u) ? -v : v; +} + +inline float ink2_phi(device const float* amax, device const float* denominator, uint expert) { + // Loader casts both globals to BF16 before the dequantization operation. + return precise::divide(float(bfloat(amax[expert])), float(bfloat(denominator[0]))); +} + +inline float ink2_nv_weight(uchar packed, uint column, uchar scale, float phi) { + const uint code = (column & 1u) ? uint(packed >> 4u) : uint(packed & 15u); + const float inner = ink2_e2m1(code) * ink2_e4m3(scale); + return float(bfloat(inner * phi)); +} + +inline float ink2_mx_weight(uchar value, uchar scale) { + const float w = ldexp(ink2_e4m3(value), int(scale) - 127); + // E4M3 times a power of two is exactly representable in BF16, still round explicitly. + return float(bfloat(w)); +} + +// Four packed bytes as one word, at any byte offset. +inline uint ink2_word(device const uchar* p) { + return as_type(uchar4(*(device const packed_uchar4*)p)); +} + +// E2M1 times two is 0, 1, 2, 3, 4, 6, 8 or 12: one nibble of this word a code. +inline float ink2_e2m1_twice(uint code) { + const float v = float((0xC8643210u >> (4u * (code & 7u))) & 15u); + return (code & 8u) ? -v : v; +} + +// ink2_e4m3 with its finite values built from their bits. +inline float ink2_e4m3_bits(uint code) { + const uint exp = (code >> 3u) & 15u, mant = code & 7u; + const float v = exp ? as_type(((exp + 120u) << 23u) | (mant << 20u)) : float(mant) * (1.0f / 512.0f); + const float s = (code & 0x80u) ? -v : v; + return (exp == 15u && mant == 7u) ? NAN : s; +} + +// One simdgroup a dot: lane l sums blocks l, l + 32, ... in column order, then the 32 lanes are summed. +inline float ink2_dot_nv(device const uchar* w, device const uchar* scales, + device const bfloat* x, float phi, uint k, uint lane) { + float sum = 0.0f; + for (uint b = lane; b < k / 16u; b += 32u) { + // ink2_nv_weight's inner product, exact in fp32 either way: (2 * e2m1) * (e4m3 / 2). + const float half_scale = 0.5f * ink2_e4m3(scales[b]); + const uint lo = ink2_word(w + 8u * b), hi = ink2_word(w + 8u * b + 4u); + for (uint j = 0; j < 16u; ++j) { + const uint code = ((j < 8u ? lo : hi) >> (4u * (j & 7u))) & 15u; + const float weight = float(bfloat(ink2_e2m1_twice(code) * half_scale * phi)); + sum += weight * float(x[16u * b + j]); + } + } + return simd_sum(sum); +} + +// As ink2_dot_nv over 32-column MXFP8 blocks. +inline float ink2_dot_mx(device const uchar* w, device const uchar* scales, + device const bfloat* x, uint k, uint lane) { + float sum = 0.0f; + for (uint b = lane; b < k / 32u; b += 32u) { + const int shift = int(scales[b]) - 127; + for (uint j = 0; j < 32u; ++j) { + const uint c = 32u * b + j; + const float weight = float(bfloat(ldexp(ink2_e4m3_bits(w[c]), shift))); + sum += weight * float(x[c]); + } + } + return simd_sum(sum); +} + +inline float ink2_cap(float x, float cap) { + return cap * precise::tanh(precise::divide(x, cap)); +} + +inline bfloat ink2_act(float gate_dot, float up_dot) { + const float gate = float(bfloat(gate_dot)), up = float(bfloat(up_dot)); + const float left = ink2_cap(gate, 4.0f) * precise::divide(1.0f, 1.0f + precise::exp(-gate)); + // Both GEMM results round before the softcapped SwiGLU; sigmoid uses the rounded gate. + return bfloat(left * ink2_cap(up, 25.0f)); +} + +// The four products: threadgroup (x, y) is outputs 8x to 8x + 7 of route pair y, one simdgroup an output. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], + device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, group = tg.y; + if (n >= a.n) return; + const uint token = group / a.topk, expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * 2u * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 16u); + const float phi = ink2_phi(amax, denominator, expert); + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_nv(W + expert_w + ulong(gr) * (a.k / 2u), + S + expert_s + ulong(gr) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k, lane); + const float u = ink2_dot_nv(W + expert_w + ulong(ur) * (a.k / 2u), + S + expert_s + ulong(ur) * (a.k / 16u), X + ulong(token) * a.k, phi, a.k, lane); + if (lane == 0u) Y[ulong(group) * a.n + n] = ink2_act(g, u); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, group = tg.y; + if (n >= a.n) return; + const uint token = group / a.topk, expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * 2u * a.n * a.k; + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 32u); + const uint gr = 2u * n, ur = gr + 1u; + const float g = ink2_dot_mx(W + expert_w + ulong(gr) * a.k, + S + expert_s + ulong(gr) * (a.k / 32u), X + ulong(token) * a.k, a.k, lane); + const float u = ink2_dot_mx(W + expert_w + ulong(ur) * a.k, + S + expert_s + ulong(ur) * (a.k / 32u), X + ulong(token) * a.k, a.k, lane); + if (lane == 0u) Y[ulong(group) * a.n + n] = ink2_act(g, u); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const int* ids [[buffer(5)]], + device bfloat* Y [[buffer(6)]], constant Ink2MatrixArgs& a [[buffer(7)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, group = tg.y; + if (n >= a.n) return; + const uint expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * a.n * (a.k / 16u); + const float phi = ink2_phi(amax, denominator, expert); + const float d = ink2_dot_nv(W + expert_w + ulong(n) * (a.k / 2u), + S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, phi, a.k, lane); + if (lane == 0u) Y[ulong(group) * a.n + n] = bfloat(d); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const int* ids [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2MatrixArgs& a [[buffer(5)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, group = tg.y; + if (n >= a.n) return; + const uint expert = uint(ids[group]); + const ulong expert_w = ulong(expert) * a.n * a.k; + const ulong expert_s = ulong(expert) * a.n * (a.k / 32u); + const float d = ink2_dot_mx(W + expert_w + ulong(n) * a.k, + S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k, lane); + if (lane == 0u) Y[ulong(group) * a.n + n] = bfloat(d); +} + +// ---- Grouped by expert: the same sums a row as the kernels above, with each weight block decoded once a pass. ---- +struct Ink2GroupArgs { uint pairs, experts, cap; }; +struct Ink2GroupedArgs { uint k, n, topk, cap; }; +#define INK2_PASS 4u + +// Expert e's route pairs in pair order: counts[e], then members[e][0 .. counts[e]). +kernel void tf_ink2_group( + device const int* ids [[buffer(0)]], device uint* counts [[buffer(1)]], + device uint* members [[buffer(2)]], constant Ink2GroupArgs& a [[buffer(3)]], + uint e [[thread_position_in_grid]]) { + if (e >= a.experts) return; + uint n = 0u; + for (uint p = 0u; p < a.pairs; ++p) + if (uint(ids[p]) == e) { + if (n < a.cap) members[e * a.cap + n] = p; + ++n; + } + counts[e] = min(n, a.cap); +} + +// Block b of a packed NVFP4 row as its 16 BF16 weights, each as ink2_dot_nv decodes it. +inline void ink2_nv_block(device const uchar* w, device const uchar* scales, float phi, uint b, thread float* out) { + const float half_scale = 0.5f * ink2_e4m3(scales[b]); + const uint lo = ink2_word(w + 8u * b), hi = ink2_word(w + 8u * b + 4u); + for (uint j = 0; j < 16u; ++j) { + const uint code = ((j < 8u ? lo : hi) >> (4u * (j & 7u))) & 15u; + out[j] = float(bfloat(ink2_e2m1_twice(code) * half_scale * phi)); + } +} + +// Block b of an MXFP8 row as its 32 BF16 weights, each as ink2_dot_mx decodes it. +inline void ink2_mx_block(device const uchar* w, device const uchar* scales, uint b, thread float* out) { + const int shift = int(scales[b]) - 127; + for (uint j = 0; j < 32u; ++j) out[j] = float(bfloat(ldexp(ink2_e4m3_bits(w[32u * b + j]), shift))); +} + +// Threadgroup (x, e): outputs 8x to 8x + 7 of expert e for each of its route pairs, four pairs a pass. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu_grouped( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, expert = tg.y; + if (n >= a.n) return; + const uint count = counts[expert]; + if (count == 0u) return; + const ulong expert_w = ulong(expert) * 2u * a.n * (a.k / 2u); + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 16u); + const float phi = precise::divide(float(bfloat(amax[expert])), float(bfloat(denominator[0]))); + device const uchar* gate_w = W + expert_w + ulong(2u * n) * (a.k / 2u); + device const uchar* gate_s = S + expert_s + ulong(2u * n) * (a.k / 16u); + device const uchar* up_w = gate_w + (a.k / 2u); + device const uchar* up_s = gate_s + (a.k / 16u); + for (uint first = 0u; first < count; first += INK2_PASS) { + uint pair[INK2_PASS]; + device const bfloat* x[INK2_PASS]; + float g[INK2_PASS], u[INK2_PASS]; + for (uint j = 0u; j < INK2_PASS; ++j) { + pair[j] = members[expert * a.cap + min(first + j, count - 1u)]; + x[j] = X + ulong(pair[j] / a.topk) * a.k; + g[j] = 0.0f; + u[j] = 0.0f; + } + for (uint b = lane; b < a.k / 16u; b += 32u) { + float gate[16], up[16]; + ink2_nv_block(gate_w, gate_s, phi, b, gate); + ink2_nv_block(up_w, up_s, phi, b, up); + for (uint j = 0u; j < INK2_PASS; ++j) + for (uint i = 0u; i < 16u; ++i) { + const float v = float(x[j][16u * b + i]); + g[j] += gate[i] * v; + u[j] += up[i] * v; + } + } + for (uint j = 0u; j < INK2_PASS; ++j) { + const float gs = simd_sum(g[j]), us = simd_sum(u[j]); + if (lane == 0u && first + j < count) Y[ulong(pair[j]) * a.n + n] = ink2_act(gs, us); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu_grouped( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, expert = tg.y; + if (n >= a.n) return; + const uint count = counts[expert]; + if (count == 0u) return; + const ulong expert_w = ulong(expert) * 2u * a.n * a.k; + const ulong expert_s = ulong(expert) * 2u * a.n * (a.k / 32u); + device const uchar* gate_w = W + expert_w + ulong(2u * n) * a.k; + device const uchar* gate_s = S + expert_s + ulong(2u * n) * (a.k / 32u); + device const uchar* up_w = gate_w + a.k; + device const uchar* up_s = gate_s + (a.k / 32u); + for (uint first = 0u; first < count; first += INK2_PASS) { + uint pair[INK2_PASS]; + device const bfloat* x[INK2_PASS]; + float g[INK2_PASS], u[INK2_PASS]; + for (uint j = 0u; j < INK2_PASS; ++j) { + pair[j] = members[expert * a.cap + min(first + j, count - 1u)]; + x[j] = X + ulong(pair[j] / a.topk) * a.k; + g[j] = 0.0f; + u[j] = 0.0f; + } + for (uint b = lane; b < a.k / 32u; b += 32u) { + float gate[32], up[32]; + ink2_mx_block(gate_w, gate_s, b, gate); + ink2_mx_block(up_w, up_s, b, up); + for (uint j = 0u; j < INK2_PASS; ++j) + for (uint i = 0u; i < 32u; ++i) { + const float v = float(x[j][32u * b + i]); + g[j] += gate[i] * v; + u[j] += up[i] * v; + } + } + for (uint j = 0u; j < INK2_PASS; ++j) { + const float gs = simd_sum(g[j]), us = simd_sum(u[j]); + if (lane == 0u && first + j < count) Y[ulong(pair[j]) * a.n + n] = ink2_act(gs, us); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down_grouped( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, expert = tg.y; + if (n >= a.n) return; + const uint count = counts[expert]; + if (count == 0u) return; + const float phi = precise::divide(float(bfloat(amax[expert])), float(bfloat(denominator[0]))); + device const uchar* row_w = W + ulong(expert) * a.n * (a.k / 2u) + ulong(n) * (a.k / 2u); + device const uchar* row_s = S + ulong(expert) * a.n * (a.k / 16u) + ulong(n) * (a.k / 16u); + for (uint first = 0u; first < count; first += INK2_PASS) { + uint pair[INK2_PASS]; + device const bfloat* x[INK2_PASS]; + float d[INK2_PASS]; + for (uint j = 0u; j < INK2_PASS; ++j) { + pair[j] = members[expert * a.cap + min(first + j, count - 1u)]; + x[j] = X + ulong(pair[j]) * a.k; + d[j] = 0.0f; + } + for (uint b = lane; b < a.k / 16u; b += 32u) { + float weight[16]; + ink2_nv_block(row_w, row_s, phi, b, weight); + for (uint j = 0u; j < INK2_PASS; ++j) + for (uint i = 0u; i < 16u; ++i) d[j] += weight[i] * float(x[j][16u * b + i]); + } + for (uint j = 0u; j < INK2_PASS; ++j) { + const float ds = simd_sum(d[j]); + if (lane == 0u && first + j < count) Y[ulong(pair[j]) * a.n + n] = bfloat(ds); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down_grouped( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n = tg.x * 8u + sg, expert = tg.y; + if (n >= a.n) return; + const uint count = counts[expert]; + if (count == 0u) return; + device const uchar* row_w = W + ulong(expert) * a.n * a.k + ulong(n) * a.k; + device const uchar* row_s = S + ulong(expert) * a.n * (a.k / 32u) + ulong(n) * (a.k / 32u); + for (uint first = 0u; first < count; first += INK2_PASS) { + uint pair[INK2_PASS]; + device const bfloat* x[INK2_PASS]; + float d[INK2_PASS]; + for (uint j = 0u; j < INK2_PASS; ++j) { + pair[j] = members[expert * a.cap + min(first + j, count - 1u)]; + x[j] = X + ulong(pair[j]) * a.k; + d[j] = 0.0f; + } + for (uint b = lane; b < a.k / 32u; b += 32u) { + float weight[32]; + ink2_mx_block(row_w, row_s, b, weight); + for (uint j = 0u; j < INK2_PASS; ++j) + for (uint i = 0u; i < 32u; ++i) d[j] += weight[i] * float(x[j][32u * b + i]); + } + for (uint j = 0u; j < INK2_PASS; ++j) { + const float ds = simd_sum(d[j]); + if (lane == 0u && first + j < count) Y[ulong(pair[j]) * a.n + n] = bfloat(ds); + } + } +} + +// Weight decode helpers unpack checkpoint bytes and never quantize an activation. +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_nvfp4_quantize( + device const uchar* W [[buffer(0)]], device const uchar* S [[buffer(1)]], + device const float* amax [[buffer(2)]], device const float* denominator [[buffer(3)]], + device bfloat* Y [[buffer(4)]], constant Ink2DecodeArgs& a [[buffer(5)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint at = group * 32u + lane; + if (at >= a.rows * a.k) return; + const uint row = at / a.k, col = at % a.k; + const float phi = ink2_phi(amax, denominator, 0); + Y[at] = bfloat(ink2_nv_weight(W[row * (a.k / 2u) + col / 2u], col, + S[row * (a.k / 16u) + col / 16u], phi)); +} + +[[kernel, max_total_threads_per_threadgroup(32)]] void tf_ink2_mxfp8_quantize( + device const uchar* W [[buffer(0)]], device const uchar* S [[buffer(1)]], + device bfloat* Y [[buffer(2)]], constant Ink2DecodeArgs& a [[buffer(3)]], + uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_threadgroup]]) { + const uint at = group * 32u + lane; + if (at >= a.rows * a.k) return; + const uint row = at / a.k, col = at % a.k; + Y[at] = bfloat(ink2_mx_weight(W[at], S[row * (a.k / 32u) + col / 32u])); +} + +// Threadgroup (x, y) is outputs 256x to 256x + 255 of token y, a thread an output; the first topk order the routes. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_combine( + device const bfloat* down [[buffer(0)]], device const int* ids [[buffer(1)]], + device const float* weights [[buffer(2)]], device bfloat* Y [[buffer(3)]], + constant Ink2MatrixArgs& a [[buffer(4)]], uint2 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + const uint n = tg.x * 256u + t, group = tg.y; + const uint base = group * a.topk; + threadgroup uint order[32]; + if (a.topk > 32u) return; + if (t < a.topk) { + // A route's rank among the token's routes by expert, an equal expert by slot: the reference's accumulation order. + const int id = ids[base + t]; + uint rank = 0; + for (uint o = 0; o < a.topk; ++o) rank += (ids[base + o] < id || (ids[base + o] == id && o < t)) ? 1u : 0u; + order[rank] = t; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (n >= a.n) return; + float sum = 0.0f; + for (uint r = 0; r < a.topk; ++r) { + const uint slot = order[r]; + if (uint(ids[base + slot]) < a.experts) sum += weights[base + slot] * float(down[ulong(base + slot) * a.n + n]); + } + Y[ulong(group) * a.n + n] = bfloat(sum); +} diff --git a/zig/kernels/metal/inkling2/experts_sources.zig b/zig/kernels/metal/inkling2/experts_sources.zig new file mode 100644 index 00000000000..fee223e61b7 --- /dev/null +++ b/zig/kernels/metal/inkling2/experts_sources.zig @@ -0,0 +1,4 @@ +//! Inkling 2 Mini's M3 packed-weight expert kernels; activations stay BF16 throughout. +pub const experts = @embedFile("experts.metal"); +/// The same products on the tensor units, after nax.h, the decode helpers above and the shared op. +pub const experts_units = @embedFile("../nax.h") ++ experts ++ @embedFile("units.metal") ++ @embedFile("experts_units.metal"); diff --git a/zig/kernels/metal/inkling2/experts_units.metal b/zig/kernels/metal/inkling2/experts_units.metal new file mode 100644 index 00000000000..c2f7cb3b5c6 --- /dev/null +++ b/zig/kernels/metal/inkling2/experts_units.metal @@ -0,0 +1,335 @@ +// Inkling 2 Mini's routed experts on the tensor units, after nax.h, experts.metal and units.metal. + +// The columns of a gate-up row and of a down row: constants, since a loop of constant length runs faster here. +#define INK2_GU_K 2304u +#define INK2_DOWN_K 1152u + +// Columns c .. c + 3 of two rows of X (zeros for a row past the expert's pairs) as a left fragment's eight values. +inline tfp::frag ink2_units_x(device const bfloat* x0, device const bfloat* x1, bool live0, bool live1, uint c) { + const bfloat z1 = bfloat(0.0f); + const bfloat4 z = bfloat4(z1, z1, z1, z1); + return tfp::frag(live0 ? *(device const bfloat4*)(x0 + c) : z, live1 ? *(device const bfloat4*)(x1 + c) : z); +} + +// Columns 16b + hx .. + 3 of a packed NVFP4 row as BF16 weights, each as ink2_nv_block decodes it. +inline bfloat4 ink2_nv_quad(device const uchar* w, device const uchar* scales, float phi, uint b, uint hx) { + const float half_scale = 0.5f * ink2_e4m3(scales[b]); + const uint word = ink2_word(w + 8u * b + (hx & 8u) / 2u) >> (4u * (hx & 4u)); + float4 v; + for (uint j = 0; j < 4u; ++j) v[j] = ink2_e2m1_twice((word >> (4u * j)) & 15u) * half_scale * phi; + return bfloat4(bfloat(v[0]), bfloat(v[1]), bfloat(v[2]), bfloat(v[3])); +} + +// Columns 16b + hx .. + 3 of an MXFP8 row as BF16 weights, each as ink2_mx_block decodes it. +inline bfloat4 ink2_mx_quad(device const uchar* w, device const uchar* scales, uint b, uint hx) { + const int shift = int(scales[b / 2u]) - 127; + const uint word = ink2_word(w + 16u * b + hx); + float4 v; + for (uint j = 0; j < 4u; ++j) v[j] = ldexp(ink2_e4m3_bits((word >> (8u * j)) & 255u), shift); + return bfloat4(bfloat(v[0]), bfloat(v[1]), bfloat(v[2]), bfloat(v[3])); +} + +// Threadgroup (x, e): weight rows 32x .. 32x + 31 of expert e by its pairs, 16 a band; FP8 is MXFP8, else NVFP4. +template +inline void ink2_units(device const bfloat* X, device const uchar* W, device const uchar* S, float phi, + device const uint* counts, device const uint* members, device bfloat* Y, + constant Ink2GroupedArgs& a, uint2 tg, uint sg, uint lane, threadgroup float* part) { + // GU: X is by row and the 2n interleaved gate and up rows give Y[pair][n]; else X is by pair. 32 divides the rows. + const uint K = GU ? INK2_GU_K : INK2_DOWN_K, rows_w = GU ? 2u * a.n : a.n, steps = K / 128u; + const uint expert = tg.y, w0 = 32u * tg.x; + const uint count = counts[expert]; + if (count == 0u) return; + const uint wb = FP8 ? K : K / 2u, sb = FP8 ? K / 32u : K / 16u; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + device const uchar* w = W + ulong(expert) * rows_w * wb + ulong(w0 + hy) * wb; + device const uchar* s = S + ulong(expert) * rows_w * sb + ulong(w0 + hy) * sb; + for (uint band = 0u; band < count; band += 16u) { + const uint m0 = band + hy, m1 = band + hy + 8u; + const bool live0 = m0 < count, live1 = m1 < count; + const uint p0 = members[expert * a.cap + min(m0, count - 1u)], p1 = members[expert * a.cap + min(m1, count - 1u)]; + device const bfloat* x0 = X + ulong(GU ? p0 / a.topk : p0) * K + hx; + device const bfloat* x1 = X + ulong(GU ? p1 / a.topk : p1) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + // Simdgroup s sums the columns of eighth s from zero, 16 an op; the eight partial sums are then added in order. + for (uint b = sg * steps; b < (sg + 1u) * steps; ++b) { + const tfp::frag fa = ink2_units_x(x0, x1, live0, live1, 16u * b); + tfp::frag b0, b1; + if (FP8) { + b0 = tfp::frag(ink2_mx_quad(w, s, b, hx), ink2_mx_quad(w + 8u * wb, s + 8u * sb, b, hx)); + b1 = tfp::frag(ink2_mx_quad(w + 16u * wb, s + 16u * sb, b, hx), ink2_mx_quad(w + 24u * wb, s + 24u * sb, b, hx)); + } else { + b0 = tfp::frag(ink2_nv_quad(w, s, phi, b, hx), ink2_nv_quad(w + 8u * wb, s + 8u * sb, phi, b, hx)); + b1 = tfp::frag(ink2_nv_quad(w + 16u * wb, s + 16u * sb, phi, b, hx), ink2_nv_quad(w + 24u * wb, s + 24u * sb, phi, b, hx)); + } + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0u) { + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is pair row hy + 8 (e >> 2), weight row w0 + hx + (e & 3); hi is 16 weight rows on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong pair = q == 0u ? p0 : p1; + for (uint side = 0u; side < 2u; ++side) { + const uint col = w0 + 16u * side + hx; + const float4 v = side == 0u ? float4(lo[4u * q], lo[4u * q + 1u], lo[4u * q + 2u], lo[4u * q + 3u]) + : float4(hi[4u * q], hi[4u * q + 1u], hi[4u * q + 2u], hi[4u * q + 3u]); + if (GU) { + Y[pair * a.n + col / 2u] = ink2_act(v[0], v[1]); + Y[pair * a.n + col / 2u + 1u] = ink2_act(v[2], v[3]); + } else { + for (uint j = 0u; j < 4u; ++j) Y[pair * a.n + col + j] = bfloat(v[j]); + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down_units( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +// Threadgroup (x, e): 16 weight rows of expert e by its pairs, 32 a band: ink2_units' tile turned, for wide chunks. +template +inline void ink2_units_t(device const bfloat* X, device const uchar* W, device const uchar* S, float phi, + device const uint* counts, device const uint* members, device bfloat* Y, + constant Ink2GroupedArgs& a, uint2 tg, uint sg, uint lane, threadgroup float* part) { + const uint K = GU ? INK2_GU_K : INK2_DOWN_K, rows_w = GU ? 2u * a.n : a.n, steps = K / 128u; + const uint expert = tg.y, count = counts[expert]; + if (count == 0u) return; + const uint wb = FP8 ? K : K / 2u, sb = FP8 ? K / 32u : K / 16u; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + // A lane's two weight rows: the gate and up rows of output 8x + hy, or rows 16x + hy and 8 on. + const uint row0 = GU ? 2u * (8u * tg.x + hy) : 16u * tg.x + hy, row1 = GU ? row0 + 1u : row0 + 8u; + device const uchar* w0 = W + ulong(expert) * rows_w * wb + ulong(row0) * wb; + device const uchar* w1 = W + ulong(expert) * rows_w * wb + ulong(row1) * wb; + device const uchar* s0 = S + ulong(expert) * rows_w * sb + ulong(row0) * sb; + device const uchar* s1 = S + ulong(expert) * rows_w * sb + ulong(row1) * sb; + for (uint band = 0u; band < count; band += 32u) { + const uint m0 = band + hy, m1 = m0 + 8u, m2 = m0 + 16u, m3 = m0 + 24u; + const bool live0 = m0 < count, live1 = m1 < count, live2 = m2 < count, live3 = m3 < count; + const uint p0 = members[expert * a.cap + min(m0, count - 1u)], p1 = members[expert * a.cap + min(m1, count - 1u)]; + const uint p2 = members[expert * a.cap + min(m2, count - 1u)], p3 = members[expert * a.cap + min(m3, count - 1u)]; + device const bfloat* x0 = X + ulong(GU ? p0 / a.topk : p0) * K + hx; + device const bfloat* x1 = X + ulong(GU ? p1 / a.topk : p1) * K + hx; + device const bfloat* x2 = X + ulong(GU ? p2 / a.topk : p2) * K + hx; + device const bfloat* x3 = X + ulong(GU ? p3 / a.topk : p3) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * steps; b < (sg + 1u) * steps; ++b) { + tfp::frag fa; + if (FP8) fa = tfp::frag(ink2_mx_quad(w0, s0, b, hx), ink2_mx_quad(w1, s1, b, hx)); + else fa = tfp::frag(ink2_nv_quad(w0, s0, phi, b, hx), ink2_nv_quad(w1, s1, phi, b, hx)); + const tfp::frag b0 = ink2_units_x(x0, x1, live0, live1, 16u * b); + const tfp::frag b1 = ink2_units_x(x2, x3, live2, live3, 16u * b); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0u) { + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is weight row (e >> 2 ? row1 : row0), pair band + hx + (e & 3); hi is 16 pairs on. + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint m = band + 16u * side + hx + j; + if (m >= count) continue; + const ulong pair = members[expert * a.cap + m]; + const float v0 = side == 0u ? lo[j] : hi[j], v1 = side == 0u ? lo[4u + j] : hi[4u + j]; + if (GU) { + Y[pair * a.n + 8u * tg.x + hy] = ink2_act(v0, v1); + } else { + Y[pair * a.n + row0] = bfloat(v0); + Y[pair * a.n + row1] = bfloat(v1); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_gu_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_nvfp4_down_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const float* amax [[buffer(3)]], + device const float* denominator [[buffer(4)]], device const uint* counts [[buffer(5)]], + device const uint* members [[buffer(6)]], device bfloat* Y [[buffer(7)]], + constant Ink2GroupedArgs& a [[buffer(8)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y), counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_gu_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_mxfp8_down_units_t( + device const bfloat* X [[buffer(0)]], device const uchar* W [[buffer(1)]], + device const uchar* S [[buffer(2)]], device const uint* counts [[buffer(3)]], + device const uint* members [[buffer(4)]], device bfloat* Y [[buffer(5)]], + constant Ink2GroupedArgs& a [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + ink2_units_t(X, W, S, 1.0f, counts, members, Y, a, tg, sg, lane, part); +} + +struct Ink2LogitArgs { uint rows, vocab; }; + +// Threadgroup (x, y): vocabulary rows 32x .. + 31 by rows 16y .. + 15 of h, summed as the expert products are. +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_logits_units( + device const bfloat* X [[buffer(0)]], device const bfloat* W [[buffer(1)]], + device float* Y [[buffer(2)]], constant Ink2LogitArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + const uint n0 = 32u * tg.x, r0 = 16u * tg.y, K = INK2_GU_K; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + const bool live0 = r0 + hy < a.rows, live1 = r0 + hy + 8u < a.rows; + device const bfloat* x0 = X + ulong(r0 + hy) * K + hx; + // A vocabulary row past the end reads the last one: its sums are not stored. + const uint last = a.vocab - 1u; + device const bfloat* w0 = W + ulong(min(n0 + hy, last)) * K + hx; + device const bfloat* w1 = W + ulong(min(n0 + hy + 8u, last)) * K + hx; + device const bfloat* w2 = W + ulong(min(n0 + hy + 16u, last)) * K + hx; + device const bfloat* w3 = W + ulong(min(n0 + hy + 24u, last)) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * (K / 128u); b < (sg + 1u) * (K / 128u); ++b) { + const tfp::frag fa = ink2_units_x(x0, x0 + 8u * K, live0, live1, 16u * b); + const tfp::frag b0 = tfp::frag(*(device const bfloat4*)(w0 + 16u * b), *(device const bfloat4*)(w1 + 16u * b)); + const tfp::frag b1 = tfp::frag(*(device const bfloat4*)(w2 + 16u * b), *(device const bfloat4*)(w3 + 16u * b)); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is row r0 + hy + 8 (e >> 2), vocabulary row n0 + hx + (e & 3); hi is 16 vocabulary rows on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong row = r0 + hy + 8u * q; + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint v = n0 + 16u * side + hx + j; + const float dot = side == 0u ? lo[4u * q + j] : hi[4u * q + j]; + if (v < a.vocab) Y[row * a.vocab + v] = 30.0f * precise::tanh(precise::divide(float(bfloat(dot)), 30.0f)); + } + } +} + +struct Ink2DenseArgs { uint rows, n, k; }; + +// Threadgroup (x, y): outputs 32x .. 32x + 31 of rows 16y .. 16y + 15, summed as the expert products are; KC is k. +template +inline void ink2_dense(device const bfloat* X, device const bfloat* W, device bfloat* Y, constant Ink2DenseArgs& a, + uint2 tg, uint sg, uint lane, threadgroup float* part) { + const uint n0 = 32u * tg.x, r0 = 16u * tg.y, K = KC; + const short2 home = tfp::frag_home(ushort(lane)); + const uint hx = uint(home.x), hy = uint(home.y); + const bool live0 = r0 + hy < a.rows, live1 = r0 + hy + 8u < a.rows; + device const bfloat* x0 = X + ulong(r0 + hy) * K + hx; + // An output past the end reads the last one's weights: its sums are not stored. + const uint last = a.n - 1u; + device const bfloat* w0 = W + ulong(min(n0 + hy, last)) * K + hx; + device const bfloat* w1 = W + ulong(min(n0 + hy + 8u, last)) * K + hx; + device const bfloat* w2 = W + ulong(min(n0 + hy + 16u, last)) * K + hx; + device const bfloat* w3 = W + ulong(min(n0 + hy + 24u, last)) * K + hx; + tfp::frag lo = tfp::frag(0.0f), hi = tfp::frag(0.0f); + for (uint b = sg * (K / 128u); b < (sg + 1u) * (K / 128u); ++b) { + const tfp::frag fa = ink2_units_x(x0, x0 + 8u * K, live0, live1, 16u * b); + const tfp::frag b0 = tfp::frag(*(device const bfloat4*)(w0 + 16u * b), *(device const bfloat4*)(w1 + 16u * b)); + const tfp::frag b1 = tfp::frag(*(device const bfloat4*)(w2 + 16u * b), *(device const bfloat4*)(w3 + 16u * b)); + ink2_mma(lo, hi, fa, b0, b1); + } + ink2_part_put(part, lo, hi, sg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0u) return; + ink2_part_sum(part, lo, hi, lane); + // Element e of lo is row r0 + hy + 8 (e >> 2), output n0 + hx + (e & 3); hi is 16 outputs on. + for (uint q = 0u; q < 2u; ++q) { + if (!(q == 0u ? live0 : live1)) continue; + const ulong row = r0 + hy + 8u * q; + for (uint side = 0u; side < 2u; ++side) + for (uint j = 0u; j < 4u; ++j) { + const uint v = n0 + 16u * side + hx + j; + const float dot = side == 0u ? lo[4u * q + j] : hi[4u * q + j]; + if (v < a.n) Y[row * a.n + v] = bfloat(dot); + } + } +} + +[[kernel, max_total_threads_per_threadgroup(256)]] void tf_ink2_dense_units( + device const bfloat* X [[buffer(0)]], device const bfloat* W [[buffer(1)]], + device bfloat* Y [[buffer(2)]], constant Ink2DenseArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4096]; + if (a.k == 2304u) ink2_dense<2304u>(X, W, Y, a, tg, sg, lane, part); + else ink2_dense<3072u>(X, W, Y, a, tg, sg, lane, part); +} diff --git a/zig/kernels/metal/inkling2/glue.metal b/zig/kernels/metal/inkling2/glue.metal new file mode 100644 index 00000000000..221f99d2053 --- /dev/null +++ b/zig/kernels/metal/inkling2/glue.metal @@ -0,0 +1,281 @@ +#include +#pragma METAL fp contract(off) +using namespace metal; + +// Inkling 2 Mini glue. Every reduction is FP32; bfloat stores round nearest-even. +constant float INKLING_EPS = 1e-6f; +constant float INKLING_AR_SCALE = 0x1.555556p-6f; // binary32(1 / 48) + +inline float ink_sigmoid(float x) { + const float e = precise::exp(-fabs(x)); + return x < 0.0f ? precise::divide(e, 1.0f + e) : precise::divide(1.0f, 1.0f + e); +} +inline float ink_cap(float x, float c) { + return c * precise::tanh(precise::divide(x, c)); +} +inline float ink_value(const device bfloat* blocks, const device float* partial, + uint source, uint sources, uint d) { + return source + 1 == sources ? partial[d] : float(blocks[size_t(source) * 2304 + d]); +} + +struct InkEmbedArgs { uint rows; }; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_embed_norm( + const device uint* ids [[buffer(0)]], const device bfloat* table [[buffer(1)]], + const device bfloat* weight [[buffer(2)]], device bfloat* out [[buffer(3)]], + constant InkEmbedArgs& a [[buffer(4)]], uint t [[thread_position_in_threadgroup]], + uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (row >= a.rows) return; + const device bfloat* x = table + size_t(ids[row]) * 2304; + float part = 0.0f; + for (uint d = t; d < 2304; d += 256) { const float v = float(x[d]); part += v * v; } + threadgroup float red[8], inverse; + const float reduced = simd_sum(part); + if (lane == 0) red[t / 32] = reduced; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float total = 0.0f; + for (uint j = 0; j < 8; ++j) total += red[j]; + inverse = precise::rsqrt(precise::divide(total, 2304.0f) + INKLING_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < 2304; d += 256) + out[size_t(row) * 2304 + d] = bfloat(float(weight[d]) * (float(x[d]) * inverse)); +} + +struct InkARArgs { uint sources, queries, rows; }; +// Four consecutive values of a source: a completed block's BF16, or the running partial's FP32 for the last source. +inline float4 ink_values(const device bfloat* blocks, const device float* partial, uint source, uint sources, uint d) { + if (source + 1 == sources) return *(const device float4*)(partial + d); + return float4(*(const device bfloat4*)(blocks + size_t(source) * 2304 + d)); +} + +// Threadgroup (q, row): row's sources mixed by query q into out[q * rows + row], four values a thread. +[[max_total_threads_per_threadgroup(576)]] +kernel void tf_inkling2_ar( + const device bfloat* all_blocks [[buffer(0)]], const device float* all_partial [[buffer(1)]], + const device float* queries [[buffer(2)]], device float* all_out [[buffer(3)]], + constant InkARArgs& a [[buffer(4)]], uint t [[thread_index_in_threadgroup]], + uint2 tg [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + const uint q = tg.x, row = tg.y, d = 4u * t; + if (q >= a.queries || row >= a.rows || a.sources == 0 || a.sources > 5) return; + const device bfloat* blocks = all_blocks + size_t(row) * 4 * 2304; + const device float* partial = all_partial + size_t(row) * 2304; + device float* out = all_out + (size_t(q) * a.rows + row) * 2304; + // Each of the 18 simdgroups folds the partial sums itself, so no thread waits on another's result. + threadgroup float red[5 * 18], dots[5 * 18]; + float4 x[5]; + for (uint s = 0; s < 5; ++s) { + x[s] = s < a.sources ? ink_values(blocks, partial, s, a.sources, d) : float4(0.0f); + const float4 sq = x[s] * x[s]; + const float reduced = simd_sum((sq.x + sq.y) + (sq.z + sq.w)); + if (lane == 0) red[s * 18 + sg] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float4 query = *(const device float4*)(queries + size_t(q) * 2304 + d); + float means[5]; + for (uint s = 0; s < 5; ++s) { + const float ss = simd_sum(lane < 18u ? red[s * 18 + lane] : 0.0f); + means[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_EPS); + const float4 z = query * (x[s] * means[s]); + const float reduced = simd_sum((z.x + z.y) + (z.z + z.w)); + if (lane == 0) dots[s * 18 + sg] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float weights[5], peak = -INFINITY; + for (uint s = 0; s < 5; ++s) { + const float dot = simd_sum(lane < 18u ? dots[s * 18 + lane] : 0.0f); + weights[s] = dot * INKLING_AR_SCALE; + if (s < a.sources) peak = max(peak, weights[s]); + } + float den = 0.0f; + for (uint s = 0; s < a.sources; ++s) { weights[s] = precise::exp(weights[s] - peak); den += weights[s]; } + float4 acc = float4(0.0f); + for (uint s = 0; s < a.sources; ++s) acc += precise::divide(weights[s], den) * (x[s] * means[s]); + *(device float4*)(out + d) = acc; +} + +struct InkConvArgs { uint rows, channels; }; +// Row i of a convolution's taps: a stream's three old rows, then the launch's own. +inline float ink_tap(const device bfloat* old, const device bfloat* fresh, uint i, uint channels, uint c) { + return i < 3u ? float(old[size_t(i) * channels + c]) : float(fresh[size_t(i - 3u) * channels + c]); +} + +kernel void tf_inkling2_conv_static( + const device bfloat* old [[buffer(0)]], const device bfloat* fresh [[buffer(1)]], + const device bfloat* weight [[buffer(2)]], device bfloat* out [[buffer(3)]], + constant InkConvArgs& a [[buffer(4)]], uint2 at [[thread_position_in_grid]]) { + const uint c = at.x, r = at.y; + if (c >= a.channels || r >= a.rows) return; + float sum = ink_tap(old, fresh, r + 3u, a.channels, c); + for (uint tap = 0; tap < 4; ++tap) + sum += float(weight[c * 4 + tap]) * ink_tap(old, fresh, r + tap, a.channels, c); + out[size_t(r) * a.channels + c] = bfloat(precise::divide(sum, precise::sqrt(5.0f))); +} + +kernel void tf_inkling2_conv_dynamic( + const device bfloat* old [[buffer(0)]], const device bfloat* fresh [[buffer(1)]], + const device bfloat* input [[buffer(2)]], const device bfloat* static_w [[buffer(3)]], + const device bfloat* projection [[buffer(4)]], device bfloat* out [[buffer(5)]], + constant InkConvArgs& a [[buffer(6)]], + uint t [[thread_position_in_threadgroup]], uint r [[threadgroup_position_in_grid]]) { + if (r >= a.rows) return; + threadgroup float projected[32]; + if (t < 32) { + float dot = 0.0f; + for (uint d = 0; d < 2304; ++d) + dot += float(projection[size_t(t) * 2304 + d]) * float(input[size_t(r) * 2304 + d]); + projected[t] = float(bfloat(dot)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint c = t; c < a.channels; c += 256) { + float sum = ink_tap(old, fresh, r + 3u, a.channels, c); + for (uint lag = 0; lag < 4; ++lag) { + const float w = float(static_w[lag * a.channels + c]) + projected[4 * (c / 128) + lag]; + sum += w * ink_tap(old, fresh, r + 3u - lag, a.channels, c); + } + out[size_t(r) * a.channels + c] = bfloat(precise::divide(sum, 3.0f)); + } +} + +struct InkRouteArgs { uint rows; }; +// The router's first launch: fp32 dots[row][e] = weight[e] . x[row], a simdgroup an expert, 8 columns a lane a step. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_route_scores( + const device bfloat* x [[buffer(0)]], const device bfloat* weight [[buffer(1)]], + device float* dots [[buffer(2)]], constant InkRouteArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint e = tg.x * 8 + sg, row = tg.y; + if (e >= 128 || row >= a.rows) return; + const device bfloat* w = weight + size_t(e) * 2304; + const device bfloat* v = x + size_t(row) * 2304; + float acc = 0.0f; + for (uint i = 8 * lane; i < 2304; i += 256) { + const float4 w0 = float4(*(const device bfloat4*)(w + i)), w1 = float4(*(const device bfloat4*)(w + i + 4)); + const float4 v0 = float4(*(const device bfloat4*)(v + i)), v1 = float4(*(const device bfloat4*)(v + i + 4)); + acc += dot(w0, v0) + dot(w1, v1); + } + const float sum = simd_sum(acc); + if (lane == 0) dots[row * 128 + e] = sum; +} + +// The second: the eight greatest score + bias, the lowest expert on a tie, written in ascending expert order. +kernel void tf_inkling2_router( + const device float* dots [[buffer(0)]], const device float* bias [[buffer(1)]], + device uint* ids [[buffer(2)]], device float* weights [[buffer(3)]], + constant InkRouteArgs& a [[buffer(4)]], + uint t [[thread_position_in_threadgroup]], uint row [[threadgroup_position_in_grid]]) { + if (row >= a.rows) return; + threadgroup float scores[128], keys[128], chosen[8]; + threadgroup uint ranks[128], picked[8]; + if (t < 128) { + scores[t] = ink_sigmoid(dots[row * 128 + t]); + keys[t] = scores[t] + bias[t]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // Among ordered keys the scan in the last branch takes the greatest first: an expert's rank says the same. + bool unordered = false; + if (t < 128) { + uint rank = 0; + for (uint e = 0; e < 128; ++e) { + unordered = unordered || isnan(keys[e]); + rank += (keys[e] > keys[t] || (keys[e] == keys[t] && e < t)) ? 1u : 0u; + } + ranks[t] = rank; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < 128 && !unordered && ranks[t] < 8) { + // Combining, including the denominator, is in ascending expert index. + uint slot = 0; + for (uint e = 0; e < t; ++e) slot += ranks[e] < 8 ? 1u : 0u; + picked[slot] = t; chosen[slot] = scores[t]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + if (unordered) { + // A NaN key neither wins nor loses a comparison, so the picks follow this scan's order. + bool used[128] = {}; + for (uint j = 0; j < 8; ++j) { + uint best = 128; + for (uint e = 0; e < 128; ++e) if (!used[e]) { + if (best == 128 || keys[e] > keys[best]) best = e; + } + used[best] = true; picked[j] = best; chosen[j] = scores[best]; + } + for (uint j = 1; j < 8; ++j) { + uint id = picked[j]; float score = chosen[j]; uint k = j; + while (k > 0 && picked[k - 1] > id) { picked[k] = picked[k - 1]; chosen[k] = chosen[k - 1]; --k; } + picked[k] = id; chosen[k] = score; + } + } + float den = 1e-20f; + for (uint j = 0; j < 8; ++j) den += chosen[j]; + for (uint j = 0; j < 8; ++j) { + ids[row * 8 + j] = picked[j]; + weights[row * 8 + j] = precise::divide(chosen[j], den) * 8.0f; + } + } +} + +struct InkActArgs { uint rows, width; }; +kernel void tf_inkling2_swiglu( + const device bfloat* gu [[buffer(0)]], device bfloat* out [[buffer(1)]], + constant InkActArgs& a [[buffer(2)]], uint2 at [[thread_position_in_grid]]) { + const uint j = at.x, r = at.y; + if (j >= a.width || r >= a.rows) return; + const float g = float(gu[(size_t(r) * a.width + j) * 2]); + const float u = float(gu[(size_t(r) * a.width + j) * 2 + 1]); + out[size_t(r) * a.width + j] = bfloat(ink_cap(g, 4.0f) * ink_sigmoid(g) * ink_cap(u, 25.0f)); +} + +struct InkLogitArgs { uint rows, vocab; }; +kernel void tf_inkling2_logits( + const device bfloat* h [[buffer(0)]], const device bfloat* unembed [[buffer(1)]], + device float* out [[buffer(2)]], constant InkLogitArgs& a [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + // A thread takes vocabulary row v for up to eight rows of h, so a window reads the row once; a dot adds in d order. + const uint v = at.x, r0 = 8u * at.y; + if (v >= a.vocab || r0 >= a.rows) return; + const uint n = min(8u, a.rows - r0); + const device bfloat* w = unembed + size_t(v) * 2304; + const device bfloat* x = h + size_t(r0) * 2304; + float acc[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (uint d = 0; d < 2304; d += 4) { + const float4 wv = float4(*(const device bfloat4*)(w + d)); + for (uint r = 0; r < n; ++r) { + const float4 xv = float4(*(const device bfloat4*)(x + size_t(r) * 2304 + d)); + float sum = acc[r]; + sum += wv.x * xv.x; sum += wv.y * xv.y; sum += wv.z * xv.z; sum += wv.w * xv.w; + acc[r] = sum; + } + } + for (uint r = 0; r < n; ++r) { + const float dot = acc[r]; + // A9(a): unembedding rounds to bf16 before it widens for softcap30. + out[size_t(r0 + r) * a.vocab + v] = ink_cap(float(bfloat(dot)), 30.0f); + } +} + +struct InkExpertArgs { uint rows, channels; }; +kernel void tf_inkling2_expert_pick( + const device bfloat* experts [[buffer(0)]], const device uint* ids [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant InkExpertArgs& a [[buffer(3)]], + uint3 at [[thread_position_in_grid]]) { + const uint j = at.x, d = at.y, r = at.z; + if (j >= 8 || d >= a.channels || r >= a.rows) return; + out[(size_t(r) * 8 + j) * a.channels + d] = experts[(size_t(r) * 128 + ids[r * 8 + j]) * a.channels + d]; +} + +kernel void tf_inkling2_expert_combine( + const device bfloat* picked [[buffer(0)]], const device float* weights [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant InkExpertArgs& a [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + const uint d = at.x, r = at.y; + if (d >= a.channels || r >= a.rows) return; + float acc = 0.0f; + for (uint j = 0; j < 8; ++j) + acc += weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]); + out[size_t(r) * a.channels + d] = bfloat(acc); +} diff --git a/zig/kernels/metal/inkling2/glue_sources.zig b/zig/kernels/metal/inkling2/glue_sources.zig new file mode 100644 index 00000000000..b0e00911c06 --- /dev/null +++ b/zig/kernels/metal/inkling2/glue_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's embedding, residual, convolution, routing and output glue. +pub const glue = @embedFile("glue.metal"); diff --git a/zig/kernels/metal/inkling2/loop.metal b/zig/kernels/metal/inkling2/loop.metal new file mode 100644 index 00000000000..e82ee231ff8 --- /dev/null +++ b/zig/kernels/metal/inkling2/loop.metal @@ -0,0 +1,161 @@ +#include +#pragma METAL fp contract(off) +using namespace metal; + +// Cross-pass dots use fixed-order FP32 accumulation and SIMD reductions; no BF16 value accumulates. +constant float INKLING_LOOP_EPS = 1e-6f; +constant float INKLING_LOOP_SCALE = 0x1.555556p-6f; // binary32(1 / 48) +constant uint INKLING_LOOP_H = 2304; +constant uint INKLING_LOOP_RANK = 64; +constant uint INKLING_LOOP_MESSAGES = 48; + +// stride: floats from one row's m to the next (the messages interleave 48 entries a row). +struct InkLoopArgs { uint rows, stride; }; + +kernel void tf_inkling2_loop_messages( + const device bfloat* bank0 [[buffer(0)]], const device bfloat* bank1 [[buffer(1)]], + const device float* q_mlp [[buffer(2)]], const device float* kv [[buffer(3)]], + device float* out [[buffer(4)]], constant InkLoopArgs& a [[buffer(5)]], + uint t [[thread_position_in_threadgroup]], uint work [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint row = work / INKLING_LOOP_MESSAGES; + const uint entry = work - row * INKLING_LOOP_MESSAGES; + if (row >= a.rows) return; + const uint layer = entry / 4; + const uint role = entry - 4 * layer; + const device float* queries = (role == 0 || role == 3) ? q_mlp : kv; + // q/mlp and k/v occupy even/odd rows respectively. + const device float* query = queries + size_t(2 * layer + (role >= 2 ? 1 : 0)) * INKLING_LOOP_H; + const device bfloat* banks[2] = { bank0 + size_t(row) * INKLING_LOOP_H, + bank1 + size_t(row) * INKLING_LOOP_H }; + threadgroup float sums[2 * 8], inverse[2], dots[2 * 8], weights[2]; + for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float x = float(banks[s][d]); + ss += x * x; + } + const float reduced = simd_sum(ss); + if (lane == 0) sums[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint j = 0; j < 8; ++j) ss += sums[s * 8 + j]; + inverse[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_LOOP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint s = 0; s < 2; ++s) { + float dot = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float beta = float(banks[s][d]) * inverse[s]; + dot += query[d] * beta; + } + const float reduced = simd_sum(dot); + if (lane == 0) dots[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float logits[2]; + float peak = -INFINITY; + for (uint s = 0; s < 2; ++s) { + float dot = 0.0f; + for (uint j = 0; j < 8; ++j) dot += dots[s * 8 + j]; + weights[s] = dot * INKLING_LOOP_SCALE; + logits[s] = weights[s]; + peak = max(peak, logits[s]); + } + float den = 0.0f; + for (uint s = 0; s < 2; ++s) { + weights[s] = precise::exp(logits[s] - peak); + den += weights[s]; + } + for (uint s = 0; s < 2; ++s) weights[s] = precise::divide(weights[s], den); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float beta0 = float(banks[0][d]) * inverse[0]; + const float beta1 = float(banks[1][d]) * inverse[1]; + out[(size_t(row) * INKLING_LOOP_MESSAGES + entry) * INKLING_LOOP_H + d] = + weights[0] * beta0 + weights[1] * beta1; + } +} + +// The gates' first launch: h and m each to unit RMS and BF16, as normalized[row][h | m]. +kernel void tf_inkling2_loop_gates( + const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], + device bfloat* normalized [[buffer(2)]], constant InkLoopArgs& a [[buffer(3)]], + uint t [[thread_position_in_threadgroup]], + uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (row >= a.rows) return; + const device float* inputs[2] = { h + size_t(row) * INKLING_LOOP_H, + m + size_t(row) * a.stride }; + threadgroup float sums[2 * 8], inverse[2]; + for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float x = inputs[s][d]; + ss += x * x; + } + const float reduced = simd_sum(ss); + if (lane == 0) sums[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint j = 0; j < 8; ++j) ss += sums[s * 8 + j]; + inverse[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_LOOP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device bfloat* y = normalized + size_t(row) * (2 * INKLING_LOOP_H); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + y[d] = bfloat(inputs[0][d] * inverse[0]); + y[INKLING_LOOP_H + d] = bfloat(inputs[1][d] * inverse[1]); + } +} + +// The second: zeta[row][r] = bf16(down[r] . normalized[row]) in fp32, a simdgroup a rank, eight columns a lane a step. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_inkling2_loop_zeta( + const device bfloat* normalized [[buffer(0)]], const device bfloat* down [[buffer(1)]], + device bfloat* zeta [[buffer(2)]], constant InkLoopArgs& a [[buffer(3)]], + uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint r = tg.x * 8 + sg, row = tg.y; + if (r >= INKLING_LOOP_RANK || row >= a.rows) return; + const device bfloat* w = down + size_t(r) * (2 * INKLING_LOOP_H); + const device bfloat* x = normalized + size_t(row) * (2 * INKLING_LOOP_H); + float acc = 0.0f; + for (uint i = 8 * lane; i < 2 * INKLING_LOOP_H; i += 256) { + const float4 w0 = float4(*(const device bfloat4*)(w + i)), w1 = float4(*(const device bfloat4*)(w + i + 4)); + const float4 x0 = float4(*(const device bfloat4*)(x + i)), x1 = float4(*(const device bfloat4*)(x + i + 4)); + acc += dot(w0, x0) + dot(w1, x1); + } + const float sum = simd_sum(acc); + if (lane == 0) zeta[row * INKLING_LOOP_RANK + r] = bfloat(sum); +} + +// The third: each output's forget and gain dots over zeta in rank order, then the four-step blend. +kernel void tf_inkling2_loop_blend( + const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], + const device bfloat* zeta [[buffer(2)]], const device bfloat* forget [[buffer(3)]], + const device bfloat* gain [[buffer(4)]], device float* out [[buffer(5)]], + constant InkLoopArgs& a [[buffer(6)]], uint2 at [[thread_position_in_grid]]) { + const uint d = at.x, row = at.y; + if (d >= INKLING_LOOP_H || row >= a.rows) return; + { + float fdot = 0.0f, gdot = 0.0f; + for (uint r = 0; r < INKLING_LOOP_RANK; ++r) { + const float z = float(zeta[row * INKLING_LOOP_RANK + r]); + fdot += float(forget[size_t(d) * INKLING_LOOP_RANK + r]) * z; + gdot += float(gain[size_t(d) * INKLING_LOOP_RANK + r]) * z; + } + const float f = precise::tanh(fdot); + const float g = precise::tanh(gdot); + // Four separately rounded binary32 steps; do not fold these into one expression. + const float keep = 1.0f - f; + const float left = keep * h[size_t(row) * INKLING_LOOP_H + d]; + const float right = g * m[size_t(row) * a.stride + d]; + out[size_t(row) * INKLING_LOOP_H + d] = left + right; + } +} diff --git a/zig/kernels/metal/inkling2/loop_sources.zig b/zig/kernels/metal/inkling2/loop_sources.zig new file mode 100644 index 00000000000..3e1345c1a82 --- /dev/null +++ b/zig/kernels/metal/inkling2/loop_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's cross-pass message and rank-64 gate shaders. +pub const loop = @embedFile("loop.metal"); diff --git a/zig/kernels/metal/inkling2/prompt_attention.metal b/zig/kernels/metal/inkling2/prompt_attention.metal new file mode 100644 index 00000000000..6d6af9841b8 --- /dev/null +++ b/zig/kernels/metal/inkling2/prompt_attention.metal @@ -0,0 +1,212 @@ +//! Inkling 2 Mini's prompt attention; attention_sources prepends the tensor-fragment helpers. +#include +using namespace metal; +#pragma METAL fp contract(off) + +constant constexpr uint D = 128, EXTENT = 1024, KEYS = 64, PAIRS = 128; +constant constexpr float LOG2E = 1.4426950408889634f; +struct InkPromptSeg { int row0, n, p0, pad; long off; }; +struct InkPromptArgs { uint heads, kv_heads, ring, chunk, c0, chunks; float scale; uint window; }; + +inline size_t ink_prompt_rh(const InkPromptSeg& s, uint heads, uint group, uint kvh, uint pair) { + return (size_t(s.row0) + pair / group) * heads + kvh * group + pair % group; +} + +// The first chunk a row at `pos` reads, which holds its partial slot 0: its window's on a sliding layer, else c0. +inline uint ink_prompt_first(constant InkPromptArgs& a, uint pos) { + return a.window ? (pos + 1 > a.window ? pos + 1 - a.window : 0u) / a.chunk : a.c0; +} + +#ifndef TF_SIMD_FRAGS +// The 16x16 block at key row r, column c of a tile in the cache, two loads a lane; a key from `keys` on reads as zero. +inline void ink_tile_get(thread tfp::frag& f, const device bfloat* tile, int r, int c, short2 home, int keys) { + const device bfloat* q = tile + (r + home.y) * int(D) + (c + home.x); + const bfloat none = bfloat(0); + const bfloat4 zero = bfloat4(none, none, none, none); + f = tfp::frag(r + home.y < keys ? bfloat4(*(const device bfloat4*)q) : zero, + r + home.y + 8 < keys ? bfloat4(*(const device bfloat4*)(q + 8 * int(D))) : zero); +} +#endif + +#ifndef TF_SIMD_FRAGS +// Columns c .. c + 3 of two query rows as a left fragment's eight values; a row that is no pair reads as zero. +inline void ink_rows_get(thread tfp::frag& f, const device bfloat* r0, const device bfloat* r1, int c, bool lo, bool hi) { + const bfloat none = bfloat(0); + const bfloat4 zero = bfloat4(none, none, none, none); + f = tfp::frag(lo ? bfloat4(*(const device bfloat4*)(r0 + c)) : zero, hi ? bfloat4(*(const device bfloat4*)(r1 + c)) : zero); +} +#endif + +inline void ink_fold(float& mm, float& ll, float m, float l, float& a, float& b) { + const float mn = max(mm, m); + a = precise::exp2(mm - mn); + b = precise::exp2(m - mn); + ll = ll * a + l * b; + mm = mn; +} +inline void ink_rows(thread const tfp::frag* s, thread float (&r)[2], bool maximum) { + for (uint f = 0; f < 4; ++f) for (uint h = 0; h < 2; ++h) { + const uint b = 4 * h; + float v = maximum ? max(max(s[f][b], s[f][b + 1]), max(s[f][b + 2], s[f][b + 3])) + : (s[f][b] + s[f][b + 1]) + (s[f][b + 2] + s[f][b + 3]); + const float x = simd_shuffle_xor(v, ushort(1)); + v = maximum ? max(v, x) : v + x; + const float y = simd_shuffle_xor(v, ushort(8)); + v = maximum ? max(v, y) : v + y; + r[h] = maximum ? max(r[h], v) : r[h] + v; + } +} + +// 128 (row, head) pairs and one key head/chunk a 256-thread group; each simdgroup owns 16 pairs. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_attn_prompt(const device bfloat* q [[buffer(0)]], const device bfloat* kc [[buffer(1)]], + const device bfloat* vc [[buffer(2)]], const device bfloat* tab [[buffer(3)]], + const device InkPromptSeg* segs [[buffer(4)]], device float* part_o [[buffer(5)]], device float2* part_ml [[buffer(6)]], + constant InkPromptArgs& a [[buffer(7)]], uint3 tg [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint t [[thread_index_in_threadgroup]]) { +#ifdef TF_SIMD_FRAGS + threadgroup bfloat ks[KEYS * D], vs[KEYS * D]; +#endif + const InkPromptSeg s = segs[0]; + const uint group = a.heads / a.kv_heads, total = uint(s.n) * group, m0 = tg.x * PAIRS; + if (m0 >= total) return; + const uint kvh = tg.y, c = a.c0 + tg.z, b_lo = c * a.chunk; + const uint tile_hi = uint(s.p0) + min(m0 + PAIRS - 1, total - 1) / group; + if (b_lo > tile_hi) return; + // A sliding layer's block starts at its first pair's window: a chunk wholly before it has no key for the block. + const uint first_pos = uint(s.p0) + m0 / group; + if (a.window && first_pos + 1 > a.window && b_lo + a.chunk <= first_pos + 1 - a.window) return; + const uint k_hi = min(b_lo + a.chunk - 1, tile_hi), m = m0 + 16 * sg; + const short2 home = tfp::frag_home(ushort(lane)); + const uint row_a = m + uint(home.y), row_b = row_a + 8; + const uint pair_a = min(row_a, total - 1), pair_b = min(row_b, total - 1); + const device bfloat* qb0 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_a) * D; + const device bfloat* qb1 = q + ink_prompt_rh(s, a.heads, group, kvh, pair_b) * D; + const size_t hb = s.off + size_t(kvh) * a.ring * D; + tfp::frag acc[8]; + for (uint d = 0; d < 8; ++d) acc[d] = tfp::frag(0); + // Where each of the lane's two rows keeps this chunk's folded sums, and whether it has a slot in this chunk at all. + size_t slot[2]; + bool stored[2]; + for (uint h = 0; h < 2; ++h) { + const uint row = min(m + uint(home.y) + 8 * h, total - 1), pos = uint(s.p0) + row / group, first = ink_prompt_first(a, pos); + stored[h] = m + uint(home.y) + 8 * h < total && b_lo <= pos && c >= first; + slot[h] = (ink_prompt_rh(s, a.heads, group, kvh, row) * a.chunks + c - (stored[h] ? first : c)) * D + uint(home.x); + } + // The earlier of the lane's two rows: a tile wholly EXTENT or more before it is live and unbiased for both. + const uint far_pos = uint(s.p0) + min(row_a, total - 1) / group; + float top[2] = {-INFINITY, -INFINITY}, mass[2] = {0.0f, 0.0f}; + float upper[2] = {-INFINITY, -INFINITY}, whole[2] = {0.0f, 0.0f}; + for (uint kt = b_lo; kt <= k_hi; kt += KEYS) { + const uint tile_end = min(kt + KEYS, k_hi + 1); +#ifdef TF_SIMD_FRAGS + for (uint e = t; e < KEYS * D; e += 256) { + const uint key = e / D, col = e % D, kp = kt + key; + const bool live = kp < tile_end; + const size_t at = hb + size_t((live ? kp : kt) % a.ring) * D + col; + ks[e] = live ? kc[at] : bfloat(0); + vs[e] = live ? vc[at] : bfloat(0); + } + threadgroup_barrier(mem_flags::mem_threadgroup); +#else + // A tile is 64 keys from a multiple of 64 and a ring is a multiple of 64 rows, so a tile never wraps its ring. + const device bfloat* tile_k = kc + hb + size_t(kt % a.ring) * D; + const device bfloat* tile_v = vc + hb + size_t(kt % a.ring) * D; + const int keys = int(tile_end - kt); +#endif + if ((kt - b_lo) % 1024 == 0) { + for (uint d = 0; d < 8; ++d) acc[d] = tfp::frag(0); + top[0] = top[1] = -INFINITY; mass[0] = mass[1] = 0.0f; + } + tfp::frag score[4] = {tfp::frag(0), tfp::frag(0), tfp::frag(0), tfp::frag(0)}; + if (m < total && kt <= uint(s.p0) + min(m + 15, total - 1) / group) { + for (uint d = 0; d < 8; ++d) { + tfp::frag qa, kb0, kb1, kb2, kb3; +#ifdef TF_SIMD_FRAGS + tfp::frag_get_rows(qa, qb0, qb1, 16 * d, home, row_a < total, row_b < total); + tfp::frag_get_t(kb0, ks, D, 0, 16 * d, home); + tfp::frag_get_t(kb1, ks, D, 16, 16 * d, home); + tfp::frag_get_t(kb2, ks, D, 32, 16 * d, home); + tfp::frag_get_t(kb3, ks, D, 48, 16 * d, home); +#else + ink_rows_get(qa, qb0, qb1, 16 * d + home.x, row_a < total, row_b < total); + ink_tile_get(kb0, tile_k, 0, 16 * d, home, keys); + ink_tile_get(kb1, tile_k, 16, 16 * d, home, keys); + ink_tile_get(kb2, tile_k, 32, 16 * d, home, keys); + ink_tile_get(kb3, tile_k, 48, 16 * d, home, keys); +#endif + tfp::mma_16x32(score[0], score[1], qa, kb0, kb1); + tfp::mma_16x32(score[2], score[3], qa, kb2, kb3); + } + float peak[2] = {top[0], top[1]}; + const uint sub_lo = b_lo + ((kt - b_lo) / 1024) * 1024, sub_hi = sub_lo + 1023; + if (a.window == 0u && kt + KEYS - 1 + EXTENT <= far_pos) { + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) + score[f][e] = (e >> 2 ? row_b : row_a) < total ? (score[f][e] * a.scale + 0.0f) * LOG2E : -INFINITY; + } else for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const uint row = m + uint(home.y) + (e >> 2) * 8, col = uint(home.x) + TF_COL(e), kp = kt + 16 * f + col; + const uint lr = row < total ? row / group : 0, pos = uint(s.p0) + lr; + const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); + const bool live = row < total && kp <= pos && kp >= sub_lo && kp <= sub_hi && (a.window == 0u || kp + a.window > pos); + const uint distance = live ? pos - kp : 0; + const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f; + score[f][e] = live ? (score[f][e] * a.scale + bias) * LOG2E : -INFINITY; + } + ink_rows(score, peak, true); + float keep[2]; + for (uint h = 0; h < 2; ++h) { + const float mu = peak[h] == -INFINITY ? 0.0f : peak[h]; + keep[h] = precise::exp2(top[h] - mu); + top[h] = peak[h]; mass[h] *= keep[h]; + } + tfp::frag p[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) { + const float mu = peak[e >> 2] == -INFINITY ? 0.0f : peak[e >> 2]; + p[f][e] = bfloat(precise::exp2(score[f][e] - mu)); + } + // Reduce the rounded P, not its pre-bf16 exponential. + tfp::frag rounded[4]; + for (uint f = 0; f < 4; ++f) for (uint e = 0; e < 8; ++e) rounded[f][e] = float(p[f][e]); + ink_rows(rounded, mass, false); + for (uint d = 0; d < 8; ++d) for (uint e = 0; e < 8; ++e) acc[d][e] *= keep[e >> 2]; + for (uint f = 0; f < 4; ++f) for (uint d = 0; d < 8; d += 2) { + tfp::frag v0, v1; +#ifdef TF_SIMD_FRAGS + tfp::frag_get(v0, vs, D, 16 * f, 16 * d, home); + tfp::frag_get(v1, vs, D, 16 * f, 16 * d + 16, home); +#else + ink_tile_get(v0, tile_v, 16 * f, 16 * d, home, keys); + ink_tile_get(v1, tile_v, 16 * f, 16 * d + 16, home, keys); +#endif + tfp::mma_16x32(acc[d], acc[d + 1], p[f], v0, v1); + } + } + const bool fold_now = (kt - b_lo) % 1024 == 960 || kt + KEYS > k_hi; + // The chunk's first fold stores, a later one folds into what is stored; a row with no key yet stores zeros. + const bool opening = kt - b_lo < 1024; + if (fold_now && m < total) for (uint h = 0; h < 2; ++h) { + const bool some = top[h] != -INFINITY; + if (!some && !opening) continue; + float x = 0.0f, y = 0.0f; + if (some) ink_fold(upper[h], whole[h], top[h], mass[h], x, y); + if (!stored[h]) continue; + for (uint d = 0; d < 8; ++d) for (uint e = 4 * h; e < 4 * h + 4; ++e) { + device float* o = part_o + slot[h] + 16 * d + TF_COL(e); + const float before = opening ? 0.0f : *o; + *o = some ? before * x + acc[d][e] * y : before; + } + } +#ifdef TF_SIMD_FRAGS + threadgroup_barrier(mem_flags::mem_threadgroup); // no simdgroup reads ks/vs when the next tile overwrites them +#endif + } + if (m >= total) return; + if (home.x == 0) for (uint h = 0; h < 2; ++h) { + const uint row = m + uint(home.y) + 8 * h; + if (row >= total || b_lo > uint(s.p0) + row / group) continue; + const uint first = ink_prompt_first(a, uint(s.p0) + row / group); + if (c < first) continue; + const size_t prow = ink_prompt_rh(s, a.heads, group, kvh, row); + part_ml[prow * a.chunks + c - first] = float2(upper[h], whole[h]); + } +} diff --git a/zig/kernels/metal/inkling2/runtime.metal b/zig/kernels/metal/inkling2/runtime.metal new file mode 100644 index 00000000000..43be3524e9f --- /dev/null +++ b/zig/kernels/metal/inkling2/runtime.metal @@ -0,0 +1,44 @@ +#include +using namespace metal; +#pragma METAL fp contract(off) +struct InkRuntimeArgs { uint count, boundary; }; +kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = x[i]; +} +kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = x[i]; +} +kernel void tf_ink2_widen(const device bfloat* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < a.count) y[i] = float(x[i]); +} +// Row i of a convolution's taps: a stream's three old rows, then the launch's own. +inline float ink2_tap(const device bfloat* old, const device bfloat* fresh, uint i, uint d) { + return i < 3u ? float(old[i * 2304u + d]) : float(fresh[size_t(i - 3u) * 2304 + d]); +} +// Glue's static convolution of row `row` at d, as the BF16 it stores. +inline bfloat ink2_conv(const device bfloat* old, const device bfloat* fresh, const device bfloat* w, uint row, uint d) { + float sum = ink2_tap(old, fresh, row + 3u, d); + for (uint tap = 0; tap < 4; ++tap) sum += float(w[d * 4 + tap]) * ink2_tap(old, fresh, row + tap, d); + return bfloat(precise::divide(sum, precise::sqrt(5.0f))); +} +// The attention output convolved, then the running sum: t = p + conv, or conv alone where a boundary banks p. +kernel void tf_ink2_attention_partial(const device bfloat* p [[buffer(0)]], const device bfloat* old [[buffer(1)]], const device bfloat* fresh [[buffer(2)]], const device bfloat* w [[buffer(3)]], device bfloat* blocks [[buffer(4)]], device float* t [[buffer(5)]], constant InkRuntimeArgs& a [[buffer(6)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const uint row = i / 2304, d = i % 2304; + const float x = float(ink2_conv(old, fresh, w, row, d)); + t[i] = a.boundary ? x : float(p[i]) + x; + if (a.boundary) blocks[row * 4 * 2304 + (a.boundary - 1) * 2304 + d] = p[i]; +} +// The expert output convolved into the running p, and p widened into `wide`, the next visit's partial source. +kernel void tf_ink2_mlp_partial(const device float* t [[buffer(0)]], const device bfloat* old [[buffer(1)]], const device bfloat* fresh [[buffer(2)]], const device bfloat* w [[buffer(3)]], device bfloat* p [[buffer(4)]], device float* wide [[buffer(5)]], constant InkRuntimeArgs& a [[buffer(6)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const bfloat v = bfloat(t[i] + float(ink2_conv(old, fresh, w, i / 2304, i % 2304))); + p[i] = v; + wide[i] = float(v); +} + +kernel void tf_ink2_capture_tap(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= a.count) return; + const uint row = i / 2304, d = i % 2304; + y[row * 4 * 2304 + a.boundary * 2304 + d] = x[i]; +} diff --git a/zig/kernels/metal/inkling2/runtime_sources.zig b/zig/kernels/metal/inkling2/runtime_sources.zig new file mode 100644 index 00000000000..e987c44855e --- /dev/null +++ b/zig/kernels/metal/inkling2/runtime_sources.zig @@ -0,0 +1,2 @@ +//! Inkling 2 Mini's copy, widening and partial-residual shaders. +pub const runtime = @embedFile("runtime.metal"); diff --git a/zig/kernels/metal/inkling2/units.metal b/zig/kernels/metal/inkling2/units.metal new file mode 100644 index 00000000000..7075e8e9e6f --- /dev/null +++ b/zig/kernels/metal/inkling2/units.metal @@ -0,0 +1,43 @@ +// The tensor-unit op Inkling 2 Mini's expert products are built on, after nax.h: FP32 sums of BF16 products. +using namespace metal; + +// (lo | hi) += a (b0 | b1)^T, b's blocks as stored, [output][column]: nax.h's 16x32x16 op without relaxed precision. +inline void ink2_mma(thread tfp::frag& lo, thread tfp::frag& hi, thread const tfp::frag& a, + thread const tfp::frag& b0, thread const tfp::frag& b1) { + using namespace mpp::tensor_ops; + constexpr auto shape = matmul2d_descriptor(16, 32, 16, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + auto left = op.template get_left_input_cooperative_tensor(); + auto right = op.template get_right_input_cooperative_tensor(); + auto acc = op.template get_destination_cooperative_tensor, + metal::remove_addrspace_t, float>(); + TF_UNROLL + for (short e = 0; e < 8; e++) { + left[e] = a[e]; + right[e] = b0[e]; + right[8 + e] = b1[e]; + acc[e] = lo[e]; + acc[8 + e] = hi[e]; + } + op.run(left, right, acc); + TF_UNROLL + for (short e = 0; e < 8; e++) { + lo[e] = acc[e]; + hi[e] = acc[8 + e]; + } +} + +// A simdgroup's partial sums into the threadgroup's block, and the eight simdgroups' partials added in order. +inline void ink2_part_put(threadgroup float* part, thread const tfp::frag& lo, thread const tfp::frag& hi, uint sg, uint lane) { + for (uint e = 0u; e < 8u; ++e) { + part[(sg * 16u + e) * 32u + lane] = lo[e]; + part[(sg * 16u + 8u + e) * 32u + lane] = hi[e]; + } +} +inline void ink2_part_sum(threadgroup float* part, thread tfp::frag& lo, thread tfp::frag& hi, uint lane) { + for (uint e = 0u; e < 8u; ++e) + for (uint o = 1u; o < 8u; ++o) { + lo[e] += part[(o * 16u + e) * 32u + lane]; + hi[e] += part[(o * 16u + 8u + e) * 32u + lane]; + } +} diff --git a/zig/kernels/metal/inkling2_sources.zig b/zig/kernels/metal/inkling2_sources.zig new file mode 100644 index 00000000000..254b260a343 --- /dev/null +++ b/zig/kernels/metal/inkling2_sources.zig @@ -0,0 +1,12 @@ +//! Mini Metal shaders for the family and kernel contract, rooted beside nax.h for prompt-header package scope. + +pub const attention = @import("inkling2/attention_sources.zig").attention; +pub const prompt_attention = @import("inkling2/attention_sources.zig").prompt_attention; +pub const prompt_attention_pre_m5 = @import("inkling2/attention_sources.zig").prompt_attention_pre_m5; +pub const glue = @import("inkling2/glue_sources.zig").glue; +pub const experts = @import("inkling2/experts_sources.zig").experts; +pub const experts_units = @import("inkling2/experts_sources.zig").experts_units; +pub const loop = @import("inkling2/loop_sources.zig").loop; +pub const runtime = @import("inkling2/runtime_sources.zig").runtime; +pub const inkling2_dspark = @import("inkling2/dspark_sources.zig").dspark; +pub const inkling2_dspark_units = @import("inkling2/dspark_sources.zig").dspark_units; diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index b07432e1270..9ef118b2ea1 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -299,3 +299,6 @@ pub const glm_draft_topk = @embedFile("glm_draft_topk.metal"); pub const glm_draft_accept = @embedFile("glm_draft_accept.metal"); /// GLM-5.3-Flash's DFlash2 inline follow: copies accepted tap rows into the drafter ring ahead of its block. pub const glm_draft_follow = @embedFile("glm_draft_follow.metal"); + +/// Inkling 2 Mini's runtime helpers, the exact source compiled by its model and kernel contract. +pub const inkling2_runtime = @embedFile("inkling2/runtime.metal"); diff --git a/zig/src/core/checkpoint_metal.zig b/zig/src/core/checkpoint_metal.zig index 39e081ba863..3801b8d195c 100644 --- a/zig/src/core/checkpoint_metal.zig +++ b/zig/src/core/checkpoint_metal.zig @@ -2,8 +2,8 @@ const std = @import("std"); const platform = @import("sys"); const mtl = @import("metal"); -const st = @import("safetensors.zig"); -const file_cache = @import("checkpoint_file_cache.zig"); +const st = @import("core").safetensors; +const file_cache = @import("core").checkpoint_file_cache; pub const DType = st.DType; @@ -311,7 +311,7 @@ pub const Stage = struct { fn readAll(fd: platform.c.fd_t, dest: []u8, at: usize) !void { var done: usize = 0; while (done < dest.len) { - const n = platform.c.pread(fd, dest.ptr + done, dest.len - done, @intCast(at + done)); + const n = platform.c.pread(fd, dest.ptr + done, @min(dest.len - done, 1 << 30), @intCast(at + done)); if (n <= 0) return error.ShortRead; done += @intCast(n); } diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 2b352571903..4848f409ad1 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -11,6 +11,10 @@ pub const dense = @import("contract/dense.zig"); pub const bf16_round = @import("bf16_round"); pub const attention_range = @import("attention_range.zig"); pub const limits = @import("contract/limits.zig"); +pub const inkling2_glue_metal_records = @import("contract/inkling2_glue_metal_records.zig"); +pub const inkling2_dspark_metal_records = @import("contract/inkling2_dspark_metal_records.zig"); +pub const inkling2_loop_metal_records = @import("contract/inkling2_loop_metal_records.zig"); +pub const inkling2_runtime_metal_records = @import("contract/inkling2_runtime_metal_records.zig"); pub const lane_q8 = @import("contract/lane_q8_records.zig"); pub const q27_prompt = @import("contract/qwen27_prompt_records.zig"); pub const registry = @import("contract/registry.zig"); diff --git a/zig/src/core/contract/fakes.zig b/zig/src/core/contract/fakes.zig index 1e761d9339e..e344775cfe7 100644 --- a/zig/src/core/contract/fakes.zig +++ b/zig/src/core/contract/fakes.zig @@ -156,6 +156,25 @@ test "correct CPU kernels pass gates 1-4 and every planted fault goes red at its try std.testing.expectEqual(@as(usize, 0), t.problems()); } +test "initialization failures are tallied and later kernels and controls still run" { + const a = std.testing.allocator; + var f = Fake{ .a = a, .op = .sum }; + defer f.deinit(); + const missing: g.Kernel = .{ .spec = spec("missing library", .sum), .ctx = undefined, .vt = undefined, .init_error = error.NoFunction }; + const missed_control: g.Kernel = .{ .spec = spec("missing control library", .sum), .ctx = undefined, .vt = undefined, .control = .shapes, .init_error = error.NoFunction }; + g.quiet = true; + defer g.quiet = false; + var t: g.Tally = .{}; + try g.runAll(a, &.{ missing, missed_control, f.kernel("after missing library", null) }, 0x5eed, &t); + try std.testing.expectEqual(@as(usize, 2), t.kernels); + try std.testing.expectEqual(@as(usize, 1), t.failed); + try std.testing.expectEqual(@as(usize, 1), t.passed); + try std.testing.expectEqual(@as(usize, 1), t.controls); + try std.testing.expectEqual(@as(usize, 1), t.missed); + try std.testing.expectEqual(@as(usize, 2), t.problems()); + try std.testing.expect(f.runs > 0); +} + test "a tail fault passes at whole tiles: the edges are what catch it" { const a = std.testing.allocator; var f = Fake{ .a = a, .op = .sum, .fault = .tail }; diff --git a/zig/src/core/contract/gates.zig b/zig/src/core/contract/gates.zig index a815417a16b..eed00563a16 100644 --- a/zig/src/core/contract/gates.zig +++ b/zig/src/core/contract/gates.zig @@ -19,6 +19,8 @@ pub const Kernel = struct { ctx: *anyopaque, vt: *const VTable, control: ?Gate = null, + /// An initialization error to tally without reading ctx or vt. + init_error: ?anyerror = null, }; /// The hooks a kernel's test gives the harness; the harness owns no device memory. @@ -351,6 +353,18 @@ pub fn one(a: std.mem.Allocator, which: Gate, k: Kernel, seed: u64) !Verdict { /// Gates 1-4 on each kernel, and each control at its own gate (which must fail). pub fn runAll(a: std.mem.Allocator, kernels: []const Kernel, seed: u64, t: *Tally) !void { for (kernels) |k| { + if (k.init_error) |err| { + if (k.control) |gate| { + t.controls += 1; + t.missed += 1; + if (!quiet) std.debug.print("CONTROL ERROR {s}: {t} at {t}, so it proves nothing\n", .{ k.spec.name, err, gate }); + } else { + t.kernels += 1; + t.failed += 1; + if (!quiet) std.debug.print("FAIL init {s}: {t}\n", .{ k.spec.name, err }); + } + continue; + } defer if (k.vt.release) |free| free(k.ctx); const s = std.hash.Wyhash.hash(seed, k.spec.name); if (k.control) |g| { diff --git a/zig/src/core/contract/inkling2_attention_metal_records.zig b/zig/src/core/contract/inkling2_attention_metal_records.zig new file mode 100644 index 00000000000..14a887d12dd --- /dev/null +++ b/zig/src/core/contract/inkling2_attention_metal_records.zig @@ -0,0 +1,15 @@ +//! Inkling 2 Mini attention launches; prompt tensor ops have no ahead-of-time M1/M2 translator. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 attention prep tf_ink2_prep", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 attention relative table tf_ink2_rel_table", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 attention scalar tf_ink2_attn_scalar", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 attention merge tf_ink2_merge", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "metal inkling2 prompt m5 tf_ink2_attn_prompt", .threads = 256, .tg_memory = 32768, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 prompt pre-m5 tf_ink2_attn_prompt", .threads = 256, .tg_memory = 32768, .reserved = 256, .offline = false }, +}; + +test "Inkling 2 Metal launches respect their resource declarations" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/inkling2_cuda_records.zig b/zig/src/core/contract/inkling2_cuda_records.zig index a448fb73d8d..b24f4ea1efe 100644 --- a/zig/src/core/contract/inkling2_cuda_records.zig +++ b/zig/src/core/contract/inkling2_cuda_records.zig @@ -1,7 +1,8 @@ //! Inkling 2's CUDA kernels: their compile records, one file per kernel group. const attn = @import("inkling2_attn_records.zig"); const ops = @import("inkling2_ops_records.zig"); +const experts = @import("inkling2_experts_records.zig"); -pub const cuda = attn.cuda ++ ops.cuda; -pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132; -pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133; +pub const cuda = attn.cuda ++ ops.cuda ++ experts.cuda; +pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132 ++ experts.cuda_132; +pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133 ++ experts.cuda_133; diff --git a/zig/src/core/contract/inkling2_dspark_chain_metal_records.zig b/zig/src/core/contract/inkling2_dspark_chain_metal_records.zig new file mode 100644 index 00000000000..cbb25291518 --- /dev/null +++ b/zig/src/core/contract/inkling2_dspark_chain_metal_records.zig @@ -0,0 +1,15 @@ +//! Mini DSpark's greedy chain launches (zig/tests/contract/metal_inkling2_dspark_chain.zig). +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 dspark chain_step tf_ink2_dspark_chain_step", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark chain_pick tf_ink2_dspark_chain_pick", .threads = 1024, .tg_memory = 256, .reserved = 1024 }, +}; + +test "the chain's launches reserve their threads" { + for (records) |record| { + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 dspark chain_")); + } +} diff --git a/zig/src/core/contract/inkling2_dspark_metal_records.zig b/zig/src/core/contract/inkling2_dspark_metal_records.zig new file mode 100644 index 00000000000..e996a6b0a5b --- /dev/null +++ b/zig/src/core/contract/inkling2_dspark_metal_records.zig @@ -0,0 +1,15 @@ +//! Mini DSpark Metal launches (zig/tests/contract/metal_inkling2_dspark.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 dspark init_rows tf_ink2_dspark_init_rows", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark fuse_taps tf_ink2_dspark_fuse_taps", .threads = 256, .tg_memory = 32, .reserved = 256 }, + .{ .name = "metal inkling2 dspark block_qkv tf_ink2_dspark_block_qkv", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark context_kv tf_ink2_dspark_context_kv", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark attention tf_ink2_dspark_attention", .threads = 128, .tg_memory = 528, .reserved = 128 }, + .{ .name = "metal inkling2 dspark residual_norm tf_ink2_dspark_residual_norm", .threads = 256, .tg_memory = 16, .reserved = 256 }, + .{ .name = "metal inkling2 dspark swiglu tf_ink2_dspark_swiglu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark kappa tf_ink2_dspark_kappa", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark recurrent tf_ink2_dspark_recurrent", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark base tf_ink2_dspark_base", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark logits tf_ink2_dspark_logits", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/inkling2_dspark_units_metal_records.zig b/zig/src/core/contract/inkling2_dspark_units_metal_records.zig new file mode 100644 index 00000000000..224d39d1088 --- /dev/null +++ b/zig/src/core/contract/inkling2_dspark_units_metal_records.zig @@ -0,0 +1,18 @@ +//! Mini DSpark's tensor-unit attention launches (zig/tests/contract/metal_inkling2_dspark_units.zig). +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 dspark_units tf_ink2_dspark_attn_units", .threads = 64, .tg_memory = 0, .reserved = 64, .offline = false }, + .{ .name = "metal inkling2 dspark_units tf_ink2_dspark_attn_merge", .threads = 128, .tg_memory = 32, .reserved = 128, .offline = false }, +}; + +test "the tensor-unit attention's launches reserve their threads and carry no M1/M2 compile receipts" { + for (records) |record| { + try std.testing.expectEqual(@as(u32, 0), record.m1); + try std.testing.expectEqual(@as(u32, 0), record.m2); + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(!record.offline); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 dspark_units ")); + } +} diff --git a/zig/src/core/contract/inkling2_experts_metal_records.zig b/zig/src/core/contract/inkling2_experts_metal_records.zig new file mode 100644 index 00000000000..b7fd6d01929 --- /dev/null +++ b/zig/src/core/contract/inkling2_experts_metal_records.zig @@ -0,0 +1,22 @@ +//! Inkling 2 Mini M3 Metal launches; every thread count is reserved by its kernel, so no M1/M2 receipt is needed. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_gu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_down", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_gu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_down", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 experts tf_ink2_nvfp4_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_mxfp8_quantize", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 experts tf_ink2_combine", .threads = 256, .tg_memory = 128, .reserved = 256 }, +}; + +test "Inkling2 expert launches carry no fabricated M1/M2 compile receipts" { + for (records) |record| { + try std.testing.expectEqual(@as(u32, 0), record.m1); + try std.testing.expectEqual(@as(u32, 0), record.m2); + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 experts ")); + } +} diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig new file mode 100644 index 00000000000..8b89b5c5ac4 --- /dev/null +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -0,0 +1,27 @@ +//! Inkling 2's inkling2_experts, inkling2_vision images: every SM's compile records (nvcc 13.0, 13.2, 13.3). +const registry = @import("registry.zig"); + +/// nvcc 13.0's usage (nvcc -cubin per SM at the images' flags); 13.2 pending, 13.3 in measurements/pending_133.zig. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_group", .symbol = "tf_ink2x_group", .image = "inkling2_experts", .threads = 1024, .dynamic = 27648, .min_sm = 80 }, .usage = .{ .{ .regs = 28, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_rows", .symbol = "tf_ink2x_rows", .image = "inkling2_experts", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_experts tf_ink2x_wide", .symbol = "tf_ink2x_wide", .image = "inkling2_experts", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 167, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_attention", .symbol = "tf_ink2v_attention", .image = "inkling2_vision", .threads = 256, .dynamic = 36864, .min_sm = 80 }, .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_embed", .symbol = "tf_ink2v_embed", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 272, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true }, +}; +/// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. +pub const cuda_132 = [_]registry.Override{}; +/// nvcc 13.3's: none here, as later_pending reads 13.3 from measurements/pending_133.zig (all seven launches). +pub const cuda_133 = [_]registry.Override{}; diff --git a/zig/src/core/contract/inkling2_glue_metal_records.zig b/zig/src/core/contract/inkling2_glue_metal_records.zig new file mode 100644 index 00000000000..5256ba3cf5e --- /dev/null +++ b/zig/src/core/contract/inkling2_glue_metal_records.zig @@ -0,0 +1,13 @@ +//! Inkling 2 Mini glue launches (zig/tests/contract/metal_inkling2_glue.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 glue embed_norm tf_inkling2_embed_norm", .threads = 256, .tg_memory = 48, .reserved = 256 }, + .{ .name = "metal inkling2 glue ar tf_inkling2_ar", .threads = 576, .tg_memory = 720, .reserved = 576 }, + .{ .name = "metal inkling2 glue conv_static tf_inkling2_conv_static", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", .threads = 256, .tg_memory = 128, .reserved = 256 }, + .{ .name = "metal inkling2 glue router tf_inkling2_router", .threads = 256, .tg_memory = 1600, .reserved = 256 }, + .{ .name = "metal inkling2 glue swiglu tf_inkling2_swiglu", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue logits tf_inkling2_logits", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue expert_pick tf_inkling2_expert_pick", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue expert_combine tf_inkling2_expert_combine", .threads = 32, .tg_memory = 0, .reserved = 32 }, +}; diff --git a/zig/src/core/contract/inkling2_loop_metal_records.zig b/zig/src/core/contract/inkling2_loop_metal_records.zig new file mode 100644 index 00000000000..1a11442bb46 --- /dev/null +++ b/zig/src/core/contract/inkling2_loop_metal_records.zig @@ -0,0 +1,6 @@ +//! Inkling 2 Mini loop launches (zig/tests/contract/metal_inkling2_loop.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 loop messages tf_inkling2_loop_messages", .threads = 256, .tg_memory = 144, .reserved = 256 }, + .{ .name = "metal inkling2 loop gates tf_inkling2_loop_gates", .threads = 256, .tg_memory = 80, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/inkling2_ops_records.zig b/zig/src/core/contract/inkling2_ops_records.zig index e5ce0103f66..fbfd8cc5f45 100644 --- a/zig/src/core/contract/inkling2_ops_records.zig +++ b/zig/src/core/contract/inkling2_ops_records.zig @@ -4,7 +4,7 @@ const registry = @import("registry.zig"); /// nvcc 13.0's usage (nvcc -cubin per SM at the images' flags), the compiler of the release fatbins; 13.2 pending. pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2 ops tf_ink2_embed", .symbol = "tf_ink2_embed", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 21, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 22, .static = 128, .bound = 256 }, .{ .regs = 22, .static = 128, .bound = 256 } } }, - .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix", .symbol = "tf_ink2_mix", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 } } }, + .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix", .symbol = "tf_ink2_mix", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 76, .static = 45712, .bound = 512 }, .{ .regs = 72, .static = 45712, .bound = 512 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_mix_rows", .symbol = "tf_ink2_mix_rows", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_rowdot", .symbol = "tf_ink2_rowdot", .image = "inkling2_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "inkling2 ops tf_ink2_topk", .symbol = "tf_ink2_topk", .image = "inkling2_ops", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 24, .static = 384, .bound = 512 }, .{ .regs = 23, .static = 384, .bound = 512 }, .{ .regs = 23, .static = 384, .bound = 512 }, .{ .regs = 36, .static = 384, .bound = 512 }, .{ .regs = 36, .static = 384, .bound = 512 } } }, diff --git a/zig/src/core/contract/inkling2_runtime_metal_records.zig b/zig/src/core/contract/inkling2_runtime_metal_records.zig new file mode 100644 index 00000000000..4f1a7ffc40f --- /dev/null +++ b/zig/src/core/contract/inkling2_runtime_metal_records.zig @@ -0,0 +1,10 @@ +//! Inkling 2 Mini runtime helper launches (zig/tests/contract/metal_inkling2_runtime.zig). +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime copy_f32 tf_ink2_copy_f32", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime widen tf_ink2_widen", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime attention_partial tf_ink2_attention_partial", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 runtime capture_tap tf_ink2_capture_tap", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; diff --git a/zig/src/core/contract/inkling2_units_metal_records.zig b/zig/src/core/contract/inkling2_units_metal_records.zig new file mode 100644 index 00000000000..dcfdbb217c3 --- /dev/null +++ b/zig/src/core/contract/inkling2_units_metal_records.zig @@ -0,0 +1,26 @@ +//! Inkling 2 Mini's tensor-unit launches: tensor-op kernels, so no M1/M2 compile and 256 reserved threads. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 units tf_ink2_nvfp4_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_gu_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_nvfp4_down_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_gu_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_mxfp8_down_units_t", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_logits_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, + .{ .name = "metal inkling2 units tf_ink2_dense_units", .threads = 256, .tg_memory = 16384, .reserved = 256, .offline = false }, +}; + +test "Inkling2 units launches reserve their threads and carry no M1/M2 compile receipts" { + for (records) |record| { + try std.testing.expectEqual(@as(u32, 0), record.m1); + try std.testing.expectEqual(@as(u32, 0), record.m2); + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(!record.offline); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 units ")); + } +} diff --git a/zig/src/core/contract/measurements/pending_133.zig b/zig/src/core/contract/measurements/pending_133.zig index c89f898270c..ba09ea61ed0 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -5,6 +5,13 @@ pub const records = [_]Override{ .{ .name = "exl3_experts tf_exl3_grouped_0", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_experts tf_exl3_grouped_1", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 }, .{ .regs = 158, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_experts tf_exl3_grouped_2", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 148, .static = 32832, .bound = 0 }, .{ .regs = 148, .static = 32832, .bound = 0 } } }, + .{ .name = "inkling2_experts tf_ink2x_group", .usage = .{ .{ .regs = 28, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 36, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 }, .{ .regs = 35, .static = 144, .bound = 1024 } } }, + .{ .name = "inkling2_experts tf_ink2x_rows", .usage = .{ .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 156, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 }, .{ .regs = 144, .static = 32832, .bound = 128 } } }, + .{ .name = "inkling2_experts tf_ink2x_wide", .usage = .{ .{ .regs = 167, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 165, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 }, .{ .regs = 128, .static = 4224, .bound = 128 } } }, + .{ .name = "inkling2_vision tf_ink2v_attention", .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_embed", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_rope", .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2_vision tf_ink2v_scale_add", .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_0", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 127, .static = 32832, .bound = 0 }, .{ .regs = 127, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_1", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 } } }, .{ .name = "exl3_grouped tf_ctl_exl3_grouped_old_2", .usage = .{ .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 }, .{ .regs = 128, .static = 32832, .bound = 0 } } }, diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index e696c6929e5..1e5b64d1683 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -93,6 +93,15 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("qwen27_moe_records.zig").records ++ @import("qwen27_prompt_records.zig").records ++ @import("affine_gather_records.zig").records ++ + @import("inkling2_attention_metal_records.zig").records ++ + @import("inkling2_glue_metal_records.zig").records ++ + @import("inkling2_experts_metal_records.zig").records ++ + @import("inkling2_units_metal_records.zig").records ++ + @import("inkling2_loop_metal_records.zig").records ++ + @import("inkling2_runtime_metal_records.zig").records ++ + @import("inkling2_dspark_metal_records.zig").records ++ + @import("inkling2_dspark_chain_metal_records.zig").records ++ + @import("inkling2_dspark_units_metal_records.zig").records ++ @import("flint_records.zig").records ++ @import("hy4_records.zig").metal ++ @import("uocr_records.zig").records ++ @@ -136,4 +145,13 @@ pub const dsv41_pending = @import("registry_union.zig").extra( test { _ = @import("mla_cuda_records.zig"); _ = @import("inkling2_cuda_records.zig"); + _ = @import("inkling2_attention_metal_records.zig"); + _ = @import("inkling2_glue_metal_records.zig"); + _ = @import("inkling2_experts_metal_records.zig"); + _ = @import("inkling2_units_metal_records.zig"); + _ = @import("inkling2_loop_metal_records.zig"); + _ = @import("inkling2_runtime_metal_records.zig"); + _ = @import("inkling2_dspark_metal_records.zig"); + _ = @import("inkling2_dspark_chain_metal_records.zig"); + _ = @import("inkling2_dspark_units_metal_records.zig"); } diff --git a/zig/src/core/contract/registry_union.zig b/zig/src/core/contract/registry_union.zig index fa4deb8fd85..41dff1701e2 100644 --- a/zig/src/core/contract/registry_union.zig +++ b/zig/src/core/contract/registry_union.zig @@ -5,7 +5,7 @@ fn has(comptime prior: anytype, comptime record: anytype) bool { return false; } fn count(comptime prior: anytype, comptime additional: anytype) usize { - @setEvalBranchQuota(4000000); + @setEvalBranchQuota(5000000); var n: usize = 0; for (additional) |r| if (!has(prior, r)) { n += 1; @@ -13,7 +13,7 @@ fn count(comptime prior: anytype, comptime additional: anytype) usize { return n; } pub fn extra(comptime prior: anytype, comptime additional: anytype) [count(prior, additional)]@TypeOf(additional[0]) { - @setEvalBranchQuota(4000000); + @setEvalBranchQuota(5000000); var out: [count(prior, additional)]@TypeOf(additional[0]) = undefined; var n: usize = 0; for (additional) |r| if (!has(prior, r)) { diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index 2806a0a65c5..180944cbba3 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -87,6 +87,8 @@ pub const Backend = struct { first_before_draft: bool = false, /// A single-slot target lets its asynchronous keep progress between host steps before drafting again. defer_lone_draft: bool = false, + /// Commit a fully accepted lone chain; Inkling 2 Mini needs this transaction commit. + keep_full_lone: bool = false, /// Every draw (first, queue and verify rows) takes `Stream.penalties` from the reply's tokens; wrappers copy it. penalties: bool = false, /// Prompt fill gives the same tokens at any chunk cut, so --decode-share may cap its chunk rows; wrappers copy it. diff --git a/zig/src/core/lanes/drafted.zig b/zig/src/core/lanes/drafted.zig index 330f1125566..c4480a85647 100644 --- a/zig/src/core/lanes/drafted.zig +++ b/zig/src/core/lanes/drafted.zig @@ -72,7 +72,7 @@ pub const Drafted = struct { }; pub fn backend(x: *Drafted) be.Backend { const planned = if (x.drafter.proposal_head) |service| service.mode != .legacy and x.drafter.vtable.hold_planned != null and x.drafter.vtable.clear_proposals != null else false; - return .{ .proposal_head = x.drafter.proposal_head, .ptr = x, .round_observer = x.target.round_observer, .first_before_draft = x.target.first_before_draft, .penalties = x.target.penalties, .chunk_invariant = x.target.chunk_invariant, .vtable = vtableFor(planned, x.target.vtable.prefill_step != null and x.target.vtable.reports_fill and x.target.vtable.features != null, x.target.vtable.cancel_prefill != null, x.first_rows) }; + return .{ .proposal_head = x.drafter.proposal_head, .ptr = x, .round_observer = x.target.round_observer, .first_before_draft = x.target.first_before_draft, .keep_full_lone = x.target.keep_full_lone, .penalties = x.target.penalties, .chunk_invariant = x.target.chunk_invariant, .vtable = vtableFor(planned, x.target.vtable.prefill_step != null and x.target.vtable.reports_fill and x.target.vtable.features != null, x.target.vtable.cancel_prefill != null, x.first_rows) }; } const cancellable: [4]be.Backend.VTable = blk: { diff --git a/zig/src/core/lanes/drafted_role_test.zig b/zig/src/core/lanes/drafted_role_test.zig index 7c28f3ddab6..ff096e26f30 100644 --- a/zig/src/core/lanes/drafted_role_test.zig +++ b/zig/src/core/lanes/drafted_role_test.zig @@ -38,9 +38,11 @@ test "the drafter wrapper sees the committed callback before its first hold" { defer head.deinit(); var backend = target.backend(); backend.first_before_draft = true; + backend.keep_full_lone = true; var wrapped = try Drafted.init(gpa, backend, head.drafter()); defer wrapped.deinit(); try std.testing.expect(wrapped.backend().first_before_draft); + try std.testing.expect(wrapped.backend().keep_full_lone); var cfg = try Config.init(gpa, wrapped.facts(base()), 16, 15); defer cfg.deinit(gpa); var clock: fake.FixedClock = .{}; diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index 285fd9c9c27..a92eb0f659f 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -221,7 +221,7 @@ pub const Engine = struct { const tokens = try win.tokens(e, windows[0], out[0]); const parents = try win.rowParents(e, windows[0]); const o = try e.conclude(s, plan, out[0].sampled, out[0].rows, tokens, parents, windows[0].positions); - if (o.path.len < rows or plan.parents != null) try e.backend.keep(&windows, &.{o.path}); + if (o.path.len < rows or plan.parents != null or e.backend.keep_full_lone) try e.backend.keep(&windows, &.{o.path}); const held_levels = s.held_levels; const timed_copy = e.cfg.family_mtp and s.drafts and @import("lone_copy.zig").records(e, s, plan.kind); const verified: ?f64 = if (timed_copy) e.clock.elapsedMs(.cost) else null; // its read moves before the head drafts diff --git a/zig/src/core/lanes/fake.zig b/zig/src/core/lanes/fake.zig index 4f68632ce70..0c807d5cd91 100644 --- a/zig/src/core/lanes/fake.zig +++ b/zig/src/core/lanes/fake.zig @@ -92,6 +92,7 @@ pub const Fake = struct { image_rows: usize = 0, // image rows fed (`image_words`): the rows a tower had to make gpu_charge: ?f64 = null, // each verify and step charges its streams this many GPU seconds, as a timed backend does head_accepts: ?usize = null, // head drafts a round right before one wrong (null: one in five wrong) + keep_calls: usize = 0, // backend keep calls, including fully accepted lone windows when opted in pub fn deinit(x: *Fake) void { var it = x.lanes.valueIterator(); @@ -479,6 +480,7 @@ pub const Fake = struct { fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { const x = self(ptr); + x.keep_calls += 1; for (windows, paths) |w, path| { const l = x.lane(w.stream); l.history.shrinkRetainingCapacity(l.base); diff --git a/zig/src/core/lanes/recorder.zig b/zig/src/core/lanes/recorder.zig index a21b8bc252f..f4e4b78c263 100644 --- a/zig/src/core/lanes/recorder.zig +++ b/zig/src/core/lanes/recorder.zig @@ -239,7 +239,7 @@ pub const Recorded = struct { pub fn backend(x: *Recorded) be.Backend { const v = x.inner.vtable; x.table = .{ .prefill = prefill, .prefill_step = if (v.prefill_step != null) prefillStep else null, .cancel_prefill = if (v.cancel_prefill != null) cancelPrefill else null, .prefill_many = if (v.prefill_many != null) prefillMany else null, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .draft_capacity = if (v.draft_capacity != null) draftCapacity else null, .proposal_draft = if (v.proposal_draft != null) plannedDraft else null, .clear_proposals = if (v.clear_proposals != null) clearProposals else null, .unspeculate = if (v.unspeculate != null) unspeculate else null, .probabilities = if (v.probabilities != null) probabilities else null, .tree = if (v.tree != null) tree else null, .alternatives = if (v.alternatives != null) alternatives else null, .prepare_features = if (v.prepare_features != null) prepareFeatures else null, .features = features, .first_row = if (v.first_row != null) firstRow else null, .first_masked = if (v.first_masked != null) firstMasked else null, .score = if (v.score != null) score else null, .held = if (v.held != null) held else null, .prompt_rows = v.prompt_rows, .release = release }; - return .{ .proposal_head = x.inner.proposal_head, .ptr = x, .round_observer = x.inner.round_observer, .vtable = &x.table, .first_before_draft = x.inner.first_before_draft, .penalties = x.inner.penalties, .chunk_invariant = x.inner.chunk_invariant }; + return .{ .proposal_head = x.inner.proposal_head, .ptr = x, .round_observer = x.inner.round_observer, .vtable = &x.table, .first_before_draft = x.inner.first_before_draft, .keep_full_lone = x.inner.keep_full_lone, .penalties = x.inner.penalties, .chunk_invariant = x.inner.chunk_invariant }; } fn of(p: *anyopaque) *Recorded { diff --git a/zig/src/core/lanes/recorder_test.zig b/zig/src/core/lanes/recorder_test.zig index e0d48b2640e..43bb3b004f2 100644 --- a/zig/src/core/lanes/recorder_test.zig +++ b/zig/src/core/lanes/recorder_test.zig @@ -270,7 +270,7 @@ test "a target that gives no rows cannot be recorded" { try std.testing.expectError(error.NoFeatures, rec.Recorded.init(.{ .ptr = &target, .vtable = &table }, &recorder)); } -test "recorded backend preserves both values of first_before_draft, penalties and chunk invariance" { +test "recorded backend preserves first-before-draft, penalties, chunk invariance and lone keep" { var target: fake.Fake = .{ .gpa = gpa }; defer target.deinit(); var tmp = std.testing.tmpDir(.{}); @@ -283,10 +283,12 @@ test "recorded backend preserves both values of first_before_draft, penalties an inner.first_before_draft = enabled; inner.penalties = enabled; inner.chunk_invariant = enabled; + inner.keep_full_lone = enabled; var recorded = try rec.Recorded.init(inner, &recorder); try std.testing.expectEqual(enabled, recorded.backend().first_before_draft); try std.testing.expectEqual(enabled, recorded.backend().penalties); try std.testing.expectEqual(enabled, recorded.backend().chunk_invariant); + try std.testing.expectEqual(enabled, recorded.backend().keep_full_lone); } } diff --git a/zig/src/core/lanes/rollback_test.zig b/zig/src/core/lanes/rollback_test.zig index 683d0c40a9f..f4763e224d1 100644 --- a/zig/src/core/lanes/rollback_test.zig +++ b/zig/src/core/lanes/rollback_test.zig @@ -157,6 +157,23 @@ test "rollback: heads landing no draft, some or all commit the one-token decode, }; } +test "rollback: fully accepted lone keep is opt-in and preserves main's default call count" { + for ([_]bool{ false, true }) |enabled| { + const r = try Rig.create(every, 0); + defer r.destroy(); + r.engine.backend.keep_full_lone = enabled; + const s = try r.open(0, .{ .prompt = &p1, .max_new = 24 }); + try r.engine.addStream(s); + _ = try r.finish(); + try expectFresh(.{ .prompt = &p1, .max_new = 24 }, s); + if (enabled) { + try expect(r.target.keep_calls > 0); + } else { + try std.testing.expectEqual(@as(usize, 0), r.target.keep_calls); + } + } +} + /// Steps of the uncancelled run of `reqs`, which bound where a cancel can land. fn stepsOf(accepts: ?usize, reqs: []const Req) !usize { const r = try Rig.create(accepts, 0); diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 83ceaa32e28..1d489df68ef 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -14,6 +14,7 @@ pub const digest_cache = @import("digest_cache.zig"); pub const checkpoint_identity = @import("checkpoint_identity.zig"); pub const checkpoint_read_ahead = @import("checkpoint_read_ahead.zig"); pub const checkpoint = @import("checkpoint.zig"); +pub const checkpoint_file_cache = @import("checkpoint_file_cache.zig"); pub const dfloat11_config = @import("dfloat11_config.zig"); pub const checkpoint_fixture = @import("checkpoint_fixture.zig"); pub const dfloat11_fixtures = @import("dfloat11_fixtures.zig"); diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 68f917f8362..b1071d1275c 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -114,6 +114,10 @@ pub const inkling2_attn: []const u8 = if (available) &Blob("fatbin_inkling2_attn pub const inkling2_pattn: []const u8 = if (available) &Blob("fatbin_inkling2_pattn").bytes else &.{}; pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops").bytes else &.{}; pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; +pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_experts").bytes else &.{}; +pub const inkling2_modelopt: []const u8 = if (available) &Blob("fatbin_inkling2_modelopt").bytes else &.{}; +pub const inkling2_loop_math: []const u8 = if (available) &Blob("fatbin_inkling2_loop_math").bytes else &.{}; +pub const inkling2_vision: []const u8 = if (available) &Blob("fatbin_inkling2_vision").bytes else &.{}; pub const glm_quant: []const u8 = if (available) &Blob("fatbin_glm_quant").bytes else &.{}; pub const glm_vision: []const u8 = if (available) &Blob("fatbin_glm_vision").bytes else &.{}; pub const glm_mm: []const u8 = if (available) &Blob("fatbin_glm_mm").bytes else &.{}; diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index b4143603140..9d30527e4d8 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -1,9 +1,12 @@ -//! Inkling 2 Small's shape from config.json (inkling2), refusing every layout the engine does not run. +//! Inkling 2 Small and Mini shapes from config.json, refusing every layout the engine does not run. const std = @import("std"); /// The most backbone layers the plan tables hold (Inkling 2 Small has 48). pub const max_layers = 128; +/// The most scheduled layer visits the visit-plan table holds. +pub const max_visits = max_layers * 8; + /// Every sixth layer attends over the whole context; the reference derives its layer types the same way. pub const global_every = 6; @@ -37,6 +40,14 @@ pub const Why = struct { /// One attention geometry: sliding layers read the `swa_*` keys, global layers the plain ones. pub const Heads = struct { q: u32, kv: u32, dim: u32 }; +/// The fixed loop schedule: all layers once, then only the core on each later pass. +pub const Loop = struct { + core_start: u32, // inclusive physical layer id + core_end: u32, // exclusive physical layer id + passes: u32, + gate_rank: u32, +}; + pub const Text = struct { hidden: u32, layers: u32, @@ -61,6 +72,13 @@ pub const Text = struct { up_cap: f32, logit_cap: f32, max_context: u32, + loop: ?Loop, + + /// The number of scheduled layer visits; a drafter target equal to this is the final norm. + pub fn visitCount(c: *const Text) u32 { + const l = c.loop orelse return c.layers; + return c.layers + (l.passes - 1) * (l.core_end - l.core_start); + } pub fn heads(c: *const Text, i: u32) Heads { return if (isGlobal(i)) c.global else c.local; @@ -72,7 +90,7 @@ pub const Text = struct { } }; -/// The draft head's shape (mtp_config); the target taps are indices into the backbone, `layers` meaning the final norm. +/// The draft head's shape (mtp_config); target taps are visit ids, with `visitCount` meaning the final norm. pub const Mtp = struct { layers: u32, q_heads: u32, @@ -133,6 +151,15 @@ fn int(o: std.json.ObjectMap, key: []const u8, why: *Why) !u32 { return @intCast(v.integer); } +fn index(o: std.json.ObjectMap, key: []const u8, why: *Why) !u32 { + const v = try get(o, key, why); + if (v != .integer or v.integer < 0 or v.integer > std.math.maxInt(u32)) { + why.set("config.json's {s} is not a non-negative whole number", .{key}); + return error.BadConfig; + } + return @intCast(v.integer); +} + fn float(o: std.json.ObjectMap, key: []const u8, why: *Why) !f32 { const v = try get(o, key, why); const x: f64 = switch (v) { @@ -192,8 +219,33 @@ fn layerTypes(o: std.json.ObjectMap, layers: u32, why: *Why) !void { } } +fn parseLoop(o: std.json.ObjectMap, layers: u32, block: u32, why: *Why) !Loop { + const l: Loop = .{ + .core_start = try index(o, "core_start", why), + .core_end = try int(o, "core_end", why), + .passes = try int(o, "num_passes", why), + .gate_rank = try int(o, "gate_rank", why), + }; + try fixed(o, "is_varloop", false, why); + if (l.core_start == 0 or l.core_start >= l.core_end or l.core_end > layers) { + why.set("loop_config core range {d}..{d} must start after layer 0, be nonempty and fit inside the {d} physical layers", .{ l.core_start, l.core_end, layers }); + return error.Layout; + } + if (l.core_start % block != 0 or l.core_end % block != 0 or l.core_start != block or l.core_end + block != layers) { + why.set("loop_config core_start and core_end must be multiples of the {d}-layer attention-residual block, leaving its first and last blocks outside the loop", .{block}); + return error.Layout; + } + const visits = @as(u64, layers) + @as(u64, l.passes - 1) * @as(u64, l.core_end - l.core_start); + if (visits > max_visits) { + why.set("loop_config makes {d} layer visits: the plan tables hold {d}", .{ visits, max_visits }); + return error.Layout; + } + return l; +} + fn parseText(o: std.json.ObjectMap, why: *Why) !Text { var t: Text = undefined; + t.loop = null; t.hidden = try int(o, "hidden_size", why); t.layers = try int(o, "num_hidden_layers", why); t.vocab = try int(o, "vocab_size", why); @@ -261,6 +313,7 @@ fn parseText(o: std.json.ObjectMap, why: *Why) !Text { return error.Unsupported; }; try layerTypes(o, t.layers, why); + if (o.get("loop_config")) |_| t.loop = try parseLoop(try object(o, "loop_config", why), t.layers, t.block, why); return t; } @@ -311,7 +364,7 @@ fn parseMtp(o: std.json.ObjectMap, t: *const Text, why: *Why) !Mtp { m.local[@intCast(e.integer)] = true; } for (taps.array.items) |e| { - if (e != .integer or e.integer < 0 or e.integer > t.layers) { + if (e != .integer or e.integer < 0 or e.integer > t.visitCount()) { why.set("mtp_config's target_layer_ids names a layer the backbone does not have", .{}); return error.Layout; } @@ -349,15 +402,26 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8, why: *Why) !Config { } const o = parsed.value.object; const arch = o.get("architectures"); - const ok = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string and - std.mem.eql(u8, arch.?.array.items[0].string, "Inkling2ForConditionalGeneration"); - if (!ok or !std.mem.eql(u8, text(o, "model_type") orelse "", "inkling2")) { - why.set("not an Inkling 2 checkpoint: architectures Inkling2ForConditionalGeneration, model_type inkling2", .{}); + const arch_ok = arch != null and arch.? == .array and arch.?.array.items.len == 1 and arch.?.array.items[0] == .string; + const arch_name: []const u8 = if (arch_ok) arch.?.array.items[0].string else ""; + const model_name = text(o, "model_type") orelse ""; + const small = std.mem.eql(u8, arch_name, "Inkling2ForConditionalGeneration") and std.mem.eql(u8, model_name, "inkling2"); + const looped = std.mem.eql(u8, arch_name, "Inkling2LoopForConditionalGeneration") and std.mem.eql(u8, model_name, "inkling2_loop"); + if (!small and !looped) { + why.set("not an Inkling 2 checkpoint: Small or Mini model_type and architectures must match", .{}); return error.NotInkling2; } try fixed(o, "tie_word_embeddings", false, why); try quantization(o, why); const t = try parseText(try object(o, "text_config", why), why); + if (looped and t.loop == null) { + why.set("inkling2_loop requires text_config.loop_config", .{}); + return error.BadConfig; + } + if (small and t.loop != null) { + why.set("loop_config requires the inkling2_loop model and architecture", .{}); + return error.Unsupported; + } const eos = try int(o, "eos_token_id", why); if (eos >= t.vocab) { why.set("eos_token_id is not a token of the {d}-token vocabulary", .{t.vocab}); diff --git a/zig/src/families/inkling2/config_test.zig b/zig/src/families/inkling2/config_test.zig index 3d24d543b66..a8ad85ab3c7 100644 --- a/zig/src/families/inkling2/config_test.zig +++ b/zig/src/families/inkling2/config_test.zig @@ -5,6 +5,7 @@ const config = @import("config.zig"); const t = std.testing; pub const real = @embedFile("fixtures/config.json"); pub const tiny = @embedFile("fixtures/tiny_config.json"); +pub const mini = @embedFile("fixtures/mini_config.json"); fn refused(json: []const u8, from: []const u8, to: []const u8, want: anyerror, says: []const u8) !void { if (std.mem.count(u8, json, from) != 1) return error.EditAnchor; @@ -46,6 +47,40 @@ test "Inkling 2 Small's config.json parses: 48 layers, 8 global, 384 experts, 8 try t.expectEqualSlices(bool, &.{ true, true, false, true, true }, m.local[0..5]); } +test "Inkling 2 Mini's config.json parses: 24 weight layers, 48 visits and four drafter taps" { + var why: config.Why = .{}; + const c = try config.parse(t.allocator, mini, &why); + try t.expectEqual(@as(u32, 2304), c.text.hidden); + try t.expectEqual(@as(u32, 24), c.text.layers); + try t.expectEqual(@as(u32, 48), c.text.visitCount()); + try t.expectEqual(config.Heads{ .q = 24, .kv = 8, .dim = 128 }, c.text.global); + try t.expectEqual(@as(u32, 8192), c.text.log_floor); + try t.expectEqual(@as(u32, 128), c.text.experts); + try t.expectEqual(@as(u32, 1152), c.text.expert_inter); + try t.expectEqual(@as(f32, 8), c.text.route_scale); + const loop = c.text.loop.?; + try t.expectEqual(@as(u32, 6), loop.core_start); + try t.expectEqual(@as(u32, 18), loop.core_end); + try t.expectEqual(@as(u32, 3), loop.passes); + try t.expectEqual(@as(u32, 64), loop.gate_rank); + try t.expectEqual(@as(u32, 2304), c.vision.text_hidden); + const m = c.mtp.?; + try t.expectEqual(@as(u32, 3), m.layers); + try t.expectEqual(@as(u32, 9216), m.inter); + try t.expectEqualSlices(u32, &.{ 5, 23, 41, 48 }, m.taps[0..m.taps_n]); + try t.expectEqualSlices(bool, &.{ true, false, true }, m.local[0..3]); +} + +test "loop layouts the engine does not run are refused by their config key" { + try refused(mini, "\"is_varloop\": false", "\"is_varloop\": true", error.Unsupported, "is_varloop must be false"); + try refused(mini, "\"core_start\": 6", "\"core_start\": 0", error.Layout, "must start after layer 0"); + try refused(mini, "\"core_start\": 6", "\"core_start\": 7", error.Layout, "multiples of the 6-layer"); + try refused(mini, "\"core_end\": 18", "\"core_end\": 24", error.Layout, "multiples of the 6-layer"); + try refused(mini, "\"core_end\": 18,", "\"core_end\": 30,", error.Layout, "fit inside the 24 physical layers"); + try refused(mini, "Inkling2LoopForConditionalGeneration", "Inkling2ForConditionalGeneration", error.NotInkling2, "model_type and architectures must match"); + try refused(mini, "\"model_type\": \"inkling2_loop\"", "\"model_type\": \"inkling2\"", error.NotInkling2, "model_type and architectures must match"); +} + test "tiny-random's config.json parses: 12 layers, 96 experts, width 128, no quantization_config" { var why: config.Why = .{}; const c = try config.parse(t.allocator, tiny, &why); diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig new file mode 100644 index 00000000000..981c85b925c --- /dev/null +++ b/zig/src/families/inkling2/cuda_native.zig @@ -0,0 +1,179 @@ +//! Inkling 2 Mini's complete one-rank, text-only CUDA engine and checkpoint/snapshot admission. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const core = @import("core"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const loop = @import("loop.zig"); +const engine = @import("loop_engine.zig"); +const backend = @import("loop_backend.zig"); + +pub const model_type = "inkling2_loop"; +pub const formats: []const []const u8 = &.{"modelopt-mixed"}; +pub const default_context: i64 = 1_048_576; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = engine.prompt_rows; +pub const window_rows: u32 = engine.window_rows; +pub const explains_open = true; + +pub const VisionOptions = struct { image_tokens: u32, max_images: u32 }; +pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; +pub const Options = struct { + context: usize, + drafts: bool, + segments: usize = 1, + slide: bool = false, + vision: ?VisionOptions = null, + precision: ?enum { full } = null, + room: ?Room = null, + drafter: ?[]const u8 = null, + tp: usize = 1, + rank: usize = 0, + master: ?[]const u8 = null, + master_port: u16 = 29551, +}; + +pub const Owned = struct { + gpa: std.mem.Allocator, + admission: loop.Admission, + kernels: engine.Kernels, + stream: cuda.Stream, + weights: @import("loop_weights.zig").Weights, + model: engine.Model, + backend: backend.Backend, +}; + +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + stream_bytes: usize, + free_streams: u32 = 1, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + reserve: *const fn (*anyopaque, u32) anyerror!void = reserve, + target: *Owned, +}; + +fn own(ptr: *anyopaque) *Owned { + return @ptrCast(@alignCast(ptr)); +} + +fn release(p: *anyopaque) void { + const o = own(p); + o.stream.synchronize() catch {}; + o.backend.deinit(); + o.stream.deinit(); + o.model.deinit(); + o.kernels.deinit(); + o.weights.deinit(); + const gpa = o.gpa; + gpa.destroy(o); +} + +/// The server's stream count: a cache slot each, past the one allocated at load. +fn reserve(p: *anyopaque, streams: u32) anyerror!void { + return own(p).backend.reserve(streams); +} + +pub fn fits(p: *anyopaque, prompt: u32, max_tokens: u32) bool { + const o: *const Owned = @ptrCast(@alignCast(p)); + return o.admission.fits(prompt, max_tokens) and o.backend.admits(prompt, max_tokens); +} + +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + if (kernels != null) return error.Inkling2CapturedKernels; + if (o.segments != 1 or o.tp != 1 or o.rank != 0) return error.Inkling2LoopOneRankOnly; + if (o.vision != null) return error.Inkling2LoopTextOnly; + if (o.drafter != null) return error.Inkling2DSparkPending; + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); + defer gpa.free(bytes); + var why: config.Why = .{}; + const c = config.parse(gpa, bytes, &why) catch |err| { + std.log.err("Inkling 2 Mini config refused: {s}", .{why.text()}); + return err; + }; + try loop.validateLoad(&c, 1, false); + if (o.context == 0 or o.context > c.text.max_context or o.context > std.math.maxInt(u32)) return error.BadLoopCache; + var ck = try core.Checkpoint.openModel(gpa, io, dir); + defer ck.close(); + try ck.skip("model.visual."); // The checkpoint carries Small's tower; text-only Mini never loads or executes it. + var precisions: [config.max_layers]plan_.Precision = undefined; + @memset(&precisions, .nvfp4); + var header_arena = std.heap.ArenaAllocator.init(gpa); + defer header_arena.deinit(); + var merged: core.safetensors.Header = .empty; + for (ck.files.items) |file| try @import("names.zig").merge(header_arena.allocator(), &merged, file.names); + try @import("names.zig").precisions(merged, c.text.layers, &precisions); + const p = try plan_.build(&c.text, precisions[0..c.text.layers]); + var w = try @import("loop_weights.zig").load(gpa, ctx.d, &ck, &c, p); + errdefer w.deinit(); + if (ck.unused() != 0) return error.UnusedCheckpointTensor; + ck.release(); + var k = try engine.Kernels.load(ctx); + errdefer k.deinit(); + var stream = try cuda.Stream.init(ctx.d, true); + errdefer stream.deinit(); + var m = try engine.Model.init(gpa, ctx.d, stream, &w, o.context); + errdefer m.deinit(); + var be = try backend.Backend.init(gpa, ctx.d, &m, &k, stream); + errdefer be.deinit(); + const out = try gpa.create(Owned); + errdefer gpa.destroy(out); + out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = k, .stream = stream, .weights = w, .model = m, .backend = be }; + // The value copies above own pointers to their old stack homes; retarget the live model/backend now. + out.model.w = &out.weights; + out.backend.m = &out.model; + out.backend.k = &out.kernels; + return .{ .backend = out.backend.backend(), .facts = out.backend.facts(), .rows = window_rows, .stream_bytes = out.model.layout.bytes, .ctx = out, .deinit = release, .target = out }; +} + +pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { + return own(ptr).model.snapshotBytes(at); +} + +pub fn snap_save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + return @ptrCast(try own(ptr).backend.saveState(owner, at)); +} + +pub fn snap_restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + return own(ptr).backend.restoreState(owner, @ptrCast(@alignCast(saved))); +} + +pub fn snap_drop(ptr: *anyopaque, saved: *anyopaque) void { + own(ptr).backend.dropState(@ptrCast(@alignCast(saved))); +} + +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return switch (err) { + error.Inkling2LoopOneRankOnly => "Inkling 2 Mini runs at one CUDA rank with one segment; TP and multi-segment modes are refused", + error.Inkling2LoopTextOnly => "Inkling 2 Mini is text-only on CUDA: images and --vision are refused", + error.Inkling2DSparkPending => "the Mini DSpark drafter has names and taps but no native draft engine in this build", + error.Inkling2CapturedKernels => "Inkling 2 Mini runs the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", + error.Inkling2TooManyStreams => "Inkling 2 Mini on CUDA holds at most 16 streams: lower --parallel", + error.StructuresUnsupported, error.ChainsOnly => "Inkling 2 Mini serves only unconstrained, non-branching text drafts", + else => null, + }; +} + +test "Mini native registration and refusal wording are explicit" { + try std.testing.expectEqualStrings("inkling2_loop", model_type); + try std.testing.expect(max_segments == 1 and prompt_rows == 2048 and window_rows == 16); + try std.testing.expectEqual(16, engine.max_slots); // the stream cap explain() names + for ([_]anyerror{ error.Inkling2LoopOneRankOnly, error.Inkling2LoopTextOnly, error.Inkling2DSparkPending, error.Inkling2CapturedKernels, error.Inkling2TooManyStreams }) |err| { + try std.testing.expect(explain(null, err) != null); + } +} + +test "the complete prompt snapshot hooks match the store vtable" { + const pc: struct { + bytes: *const fn (*anyopaque, u32) u64, + save: *const fn (*anyopaque, ?*anyopaque, u32) anyerror!*anyopaque, + restore: *const fn (*anyopaque, ?*anyopaque, *anyopaque) anyerror!void, + drop: *const fn (*anyopaque, *anyopaque) void, + } = .{ .bytes = snap_bytes, .save = snap_save, .restore = snap_restore, .drop = snap_drop }; + try std.testing.expect(@intFromPtr(pc.save) != 0); +} diff --git a/zig/src/families/inkling2/dspark_lanes.zig b/zig/src/families/inkling2/dspark_lanes.zig new file mode 100644 index 00000000000..0fed398d4f7 --- /dev/null +++ b/zig/src/families/inkling2/dspark_lanes.zig @@ -0,0 +1,240 @@ +//! Mini DSpark's backend-neutral host: lane geometry and bytes, each stream's committed rows and held drafts. +const std = @import("std"); +const lanes = @import("lanes"); + +const dr = lanes.drafter; +const Stream = lanes.Stream; +const Features = lanes.backend.Features; + +pub const hidden = 2304; +pub const kv = 1024; +pub const heads = 24; +pub const block = 8; +pub const depth = block - 1; +pub const absorb_rows = 64; +pub const vocabulary = 200058; +pub const max_context = 1 << 20; +pub const taps = [_]u32{ 5, 23, 41, 48 }; +pub const feature_row_bytes = taps.len * hidden * 2; +/// A global ring grows this many rows at a time, so it rounds a window up by at most `ring_slack` tokens. +pub const ring_step = 128; +pub const ring_slack = ring_step - 1; +/// A sliding layer's ring: its 1024-token window and a block, on the ring step. +pub const local_ring = std.mem.alignForward(usize, 1024 + block, ring_step); + +/// What one token of the window costs: each stream's global K and V rows, and its row of the shared score scratch. +pub const TokenBytes = struct { lane: u64, shared: u64 }; + +pub fn tokenBytes() TokenBytes { + return .{ .lane = 2 * kv * 2, .shared = block * heads * 4 }; +} + +pub fn globalRing(capacity: usize) usize { + return std.mem.alignForward(usize, capacity, ring_step); +} + +/// Layers 0 and 2 slide over their window; layer 1 attends to the whole committed context. +pub fn rings(capacity: usize) [3]usize { + return .{ local_ring, globalRing(capacity), local_ring }; +} + +/// The two sliding layers' K and V rings and the newest target row: a lane's bytes at any window. +pub fn laneFixedBytes() u64 { + return 2 * 2 * local_ring * kv * 2 + hidden * 2; +} + +pub fn laneBytes(capacity: usize) u64 { + return laneFixedBytes() + globalRing(capacity) * tokenBytes().lane; +} + +/// The attention scores the streams' holds share: a block's rows by heads, for each key of the window and the block. +pub fn scoreBytes(capacity: usize) u64 { + return tokenBytes().shared * (capacity + block); +} + +/// The opener's window fit: a stream costs at most `fixed + window * lane`, the shared scores `shared` a token more. +pub const Fit = struct { fixed: u64, lane: u64, shared: u64 }; + +pub fn fit() Fit { + const t = tokenBytes(); + return .{ .fixed = laneBytes(0) + ring_slack * t.lane, .lane = t.lane, .shared = t.shared }; +} + +/// One stream's committed context, target rows [from, end) in its rings, and the drafts its last hold left. +pub const Book = struct { + rings: [3]usize, + from: u64 = 0, + end: u64 = 0, + held: [depth]u32 = @splat(0), + held_len: u32 = 0, + + pub fn init(capacity: usize) !Book { + if (capacity == 0 or capacity > max_context) return error.DSparkLaneGeometry; + return .{ .rings = rings(capacity) }; + } + + /// Commits rows [start, start + n): a gap past `end` starts the context anew there, a step back is refused. + pub fn absorb(b: *Book, start: u64, n: u64) !void { + if (n == 0 or n > max_context) return error.DraftFeaturesUnsupported; + if (start < b.end or start + n > max_context) return error.DraftContextGap; + if (start > b.end) b.from = start; + b.end = start + n; + b.held_len = 0; + } + + /// The drafts a hold at `position` makes: at most `depth`, and only once every row before its anchor is committed. + pub fn hold(b: *const Book, position: u64, want: u32) !u32 { + if (want == 0 or position == 0) return error.DraftDepth; + if (b.end != position - 1) return error.DraftContextGap; + return @min(want, depth); + } + + /// Keeps a hold's drafts for `take`; a draft past the vocabulary means its logits were not finite. + pub fn keep(b: *Book, drafts: []const u32) !void { + for (drafts) |t| if (t >= vocabulary) return error.DraftNonfinite; + @memcpy(b.held[0..drafts.len], drafts); + b.held_len = @intCast(drafts.len); + } + + pub fn take(b: *const Book, out: []u32) !void { + if (out.len > b.held_len) return error.DraftHeldFewer; + @memcpy(out, b.held[0..out.len]); + } +}; + +/// A backend's piece of an absorb: `rows` target rows at `offset` of `features`, into a lane's rings at `position`. +pub fn Absorb(comptime Lane: type) type { + return struct { lane: *Lane, rings: [3]usize, features: Features, offset: u64, position: u64, rows: u32 }; +} + +/// A backend's piece of a hold: `depth` drafts after `pending`, its block anchored after the rows [from, anchor). +pub fn Hold(comptime Lane: type) type { + return struct { lane: *Lane, rings: [3]usize, from: u64, anchor: u64, pending: u32, position: u64, depth: u32, sampling: ?lanes.Sampling }; +} + +/// What the round loop's depth rule takes from the backend: a draft's cost, plain rounds, one batch a round. +pub const Policy = struct { step_ms: f64 = 0, plain_guard: bool = true, batched: bool = false }; + +/// The drafter over `B`: Lane, openLane, closeLane, setScores, absorb and hold (all streams a call), policy. +pub fn Drafter(comptime B: type) type { + return struct { + const Self = @This(); + const Entry = struct { book: Book, lane: B.Lane }; + + gpa: std.mem.Allocator, + backend: *B, + capacity: usize = 1, + streams: std.AutoHashMapUnmanaged(*Stream, Entry) = .empty, + absorbs: std.ArrayList(Absorb(B.Lane)) = .empty, + holds: std.ArrayList(Hold(B.Lane)) = .empty, + books: std.ArrayList(*Book) = .empty, + drafts: std.ArrayList([depth]u32) = .empty, + + pub fn init(gpa: std.mem.Allocator, backend: *B) Self { + return .{ .gpa = gpa, .backend = backend }; + } + + pub fn deinit(d: *Self) void { + var it = d.streams.valueIterator(); + while (it.next()) |e| d.backend.closeLane(&e.lane); + d.streams.deinit(d.gpa); + d.absorbs.deinit(d.gpa); + d.holds.deinit(d.gpa); + d.books.deinit(d.gpa); + d.drafts.deinit(d.gpa); + d.* = undefined; + } + + /// The selected window fixes every new lane's global ring and the shared score scratch's size. + pub fn setContext(d: *Self, window: u32) !void { + const capacity: usize = window; + if (capacity == 0 or capacity > max_context) return error.DSparkLaneGeometry; + if (d.streams.count() != 0) return error.DSparkContextActive; + try d.backend.setScores(scoreBytes(capacity)); + d.capacity = capacity; + } + + pub fn drafter(d: *Self) dr.Drafter { + return .{ .ptr = d, .vtable = &.{ .taps = tapsFn, .facts = factsFn, .open = openFn, .absorb = absorbFn, .hold = holdFn, .held = heldFn, .release = releaseFn } }; + } + + fn cast(ptr: *anyopaque) *Self { + return @ptrCast(@alignCast(ptr)); + } + + fn tapsFn(_: *anyopaque) []const u32 { + return &taps; + } + + fn factsFn(ptr: *anyopaque) dr.Facts { + const d = cast(ptr); + const p = d.backend.policy(); + return .{ .depth = depth, .step_ms = p.step_ms, .plain_guard = p.plain_guard, .batched = p.batched, .stream_bytes = @intCast(laneBytes(d.capacity)) }; + } + + fn openFn(ptr: *anyopaque, stream: *Stream) anyerror!void { + const d = cast(ptr); + if (d.streams.contains(stream)) return error.DraftStreamOpen; + const book = try Book.init(d.capacity); + var lane = try d.backend.openLane(book.rings); + errdefer d.backend.closeLane(&lane); + try d.streams.put(d.gpa, stream, .{ .book = book, .lane = lane }); + } + + fn releaseFn(ptr: *anyopaque, stream: *Stream) void { + const d = cast(ptr); + if (d.streams.fetchRemove(stream)) |entry| { + var lane = entry.value.lane; + d.backend.closeLane(&lane); + } + } + + fn heldFn(ptr: *anyopaque, streams: []const *Stream, out: []const []u32) anyerror!void { + const d = cast(ptr); + for (streams, out) |stream, tokens| { + const e = d.streams.getPtr(stream) orelse return error.DraftStreamUnknown; + try e.book.take(tokens); + } + } + + /// Commits each stream's rows, then hands the backend every stream's pieces of `absorb_rows` rows at once. + fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const d = cast(ptr); + d.absorbs.clearRetainingCapacity(); + for (items) |item| { + const e = d.streams.getPtr(item.stream) orelse return error.DraftStreamUnknown; + const f = item.features; + if (f.space != .device or f.dtype != .bf16 or f.row_bytes != feature_row_bytes) return error.DraftFeaturesUnsupported; + if (item.rows != null) return error.TreesNotBuilt; + try e.book.absorb(item.start, f.rows); + var position = item.start; + while (position < e.book.end) { + const rows: u32 = @intCast(@min(absorb_rows, e.book.end - position)); + const offset = f.offset + (position - item.start) * feature_row_bytes; + try d.absorbs.append(d.gpa, .{ .lane = &e.lane, .rings = e.book.rings, .features = f, .offset = offset, .position = position, .rows = rows }); + position += rows; + } + } + if (d.absorbs.items.len > 0) try d.backend.absorb(d.absorbs.items); + } + + /// Checks every stream's hold first, then one backend call drafts them all; each stream keeps its own drafts. + fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const d = cast(ptr); + d.holds.clearRetainingCapacity(); + d.books.clearRetainingCapacity(); + for (items) |item| { + const e = d.streams.getPtr(item.stream) orelse return error.DraftStreamUnknown; + if (item.lanes != null) return error.TreesNotBuilt; + const n = try e.book.hold(item.position, item.depth); + const b = &e.book; + try d.holds.append(d.gpa, .{ .lane = &e.lane, .rings = b.rings, .from = b.from, .anchor = b.end, .pending = item.pending, .position = item.position, .depth = n, .sampling = item.sampling }); + try d.books.append(d.gpa, b); + } + if (d.holds.items.len == 0) return; + try d.drafts.resize(d.gpa, d.holds.items.len); + try d.backend.hold(d.holds.items, d.drafts.items); + for (d.holds.items, d.books.items, d.drafts.items) |h, b, *drafts| try b.keep(drafts[0..h.depth]); + } + }; +} diff --git a/zig/src/families/inkling2/dspark_lanes_test.zig b/zig/src/families/inkling2/dspark_lanes_test.zig new file mode 100644 index 00000000000..a5db1b74763 --- /dev/null +++ b/zig/src/families/inkling2/dspark_lanes_test.zig @@ -0,0 +1,162 @@ +//! The shared DSpark host's prices and rules, over a recording backend; Metal's drafter is a backend of it. +const std = @import("std"); +const lanes = @import("lanes"); +const dl = @import("dspark_lanes.zig"); +const metal_state = @import("metal/dspark_state.zig"); + +const testing = std.testing; +const dr = lanes.drafter; + +test "one tokenBytes prices the opener's fit, a lane and the score scratch" { + const t = dl.tokenBytes(); + try testing.expectEqual(@as(u64, 4096), t.lane); + try testing.expectEqual(@as(u64, 768), t.shared); + try testing.expectEqual(@as(usize, 1152), dl.local_ring); + try testing.expectEqual(@as(u64, 9_437_184 + 4608), dl.laneFixedBytes()); + try testing.expectEqual(dl.laneFixedBytes() + 128 * 4096, dl.laneBytes(1)); + try testing.expectEqual(dl.laneFixedBytes() + 1152 * 4096, dl.laneBytes(1025)); + try testing.expectEqual(@as(u64, 768 * 1032), dl.scoreBytes(1024)); + for ([_]usize{ 1, 127, 128, 129, 1025, 4096, 262143, 1 << 20 }) |n| { + try testing.expectEqual(std.mem.alignForward(usize, n, dl.ring_step), dl.rings(n)[1]); + // The fit never prices a stream under its lane, and over it by at most the ring's slack. + const f = dl.fit(); + const bound = f.fixed + n * f.lane; + try testing.expect(bound >= dl.laneBytes(n) and bound - dl.laneBytes(n) <= dl.ring_slack * f.lane); + try testing.expectEqual(dl.scoreBytes(0) + n * f.shared, dl.scoreBytes(n)); + } + try testing.expectEqual(@as(u32, metal_state.block), dl.block); + try testing.expectEqual(@as(u32, metal_state.absorb_rows), dl.absorb_rows); + try testing.expectEqual(@as(u32, metal_state.vocabulary), dl.vocabulary); + try testing.expectEqual(@as(u32, metal_state.hidden), dl.hidden); +} + +/// Records what the shared host asks of a backend; its drafts are `pending + 1 + step`, or one past the vocabulary. +const Fake = struct { + pub const Lane = struct { id: u32, rings: [3]usize }; + const Piece = struct { lane: u32, offset: u64, position: u64, rows: u32 }; + const Drafted = struct { lane: u32, from: u64, anchor: u64, pending: u32, depth: u32, sampled: bool }; + + opened: u32 = 0, + closed: u32 = 0, + scores: u64 = 0, + absorb_calls: u32 = 0, + hold_calls: u32 = 0, + nonfinite: bool = false, + pieces: [8]Piece = undefined, + n_pieces: usize = 0, + holds: [4]Drafted = undefined, + n_holds: usize = 0, + + pub fn openLane(f: *Fake, rings: [3]usize) !Lane { + f.opened += 1; + return .{ .id = f.opened, .rings = rings }; + } + pub fn closeLane(f: *Fake, _: *Lane) void { + f.closed += 1; + } + pub fn setScores(f: *Fake, bytes: u64) !void { + f.scores = bytes; + } + pub fn policy(_: *const Fake) dl.Policy { + return .{ .step_ms = 0.5, .plain_guard = false, .batched = true }; + } + pub fn absorb(f: *Fake, pieces: []const dl.Absorb(Lane)) !void { + f.absorb_calls += 1; + f.n_pieces = pieces.len; + for (pieces, 0..) |p, i| f.pieces[i] = .{ .lane = p.lane.id, .offset = p.offset, .position = p.position, .rows = p.rows }; + } + pub fn hold(f: *Fake, items: []const dl.Hold(Lane), drafts: [][dl.depth]u32) !void { + f.hold_calls += 1; + f.n_holds = items.len; + for (items, drafts, 0..) |h, *out, i| { + f.holds[i] = .{ .lane = h.lane.id, .from = h.from, .anchor = h.anchor, .pending = h.pending, .depth = h.depth, .sampled = h.sampling != null }; + for (out[0..h.depth], 0..) |*t, s| t.* = if (f.nonfinite) dl.vocabulary else h.pending + 1 + @as(u32, @intCast(s)); + } + } +}; + +fn features(rows: u32, offset: u64) lanes.backend.Features { + return .{ .buffer = 0x1000, .offset = offset, .rows = rows, .row_bytes = dl.feature_row_bytes, .space = .device, .dtype = .bf16 }; +} + +fn stream(id: []const u8) !lanes.Stream { + return lanes.Stream.init(testing.allocator, .{ .id = id, .prompt = &.{ 1, 2, 3 }, .max_new = 4 }); +} + +test "a stream's rows commit in order: chunks of 64, a gap starts the context anew, a step back is refused" { + var fake: Fake = .{}; + var host = dl.Drafter(Fake).init(testing.allocator, &fake); + defer host.deinit(); + try host.setContext(300); + try testing.expectEqual(dl.scoreBytes(300), fake.scores); + const d = host.drafter(); + try testing.expectEqual(dl.laneBytes(300), d.facts().stream_bytes); + try testing.expect(d.facts().batched and !d.facts().plain_guard and d.facts().depth == 7); + var s = try stream("a"); + defer s.deinit(testing.allocator); + try d.open(&s); + try testing.expectError(error.DraftStreamOpen, d.open(&s)); + try d.absorb(&.{.{ .stream = &s, .features = features(130, 64), .start = 0, .follow = &.{} }}); + try testing.expectEqual(@as(usize, 3), fake.n_pieces); + const row = dl.feature_row_bytes; + try testing.expectEqual(Fake.Piece{ .lane = 1, .offset = 64 + 64 * row, .position = 64, .rows = 64 }, fake.pieces[1]); + try testing.expectEqual(Fake.Piece{ .lane = 1, .offset = 64 + 128 * row, .position = 128, .rows = 2 }, fake.pieces[2]); + try d.hold(&.{.{ .stream = &s, .pending = 9, .position = 131, .depth = 12 }}); + try testing.expectEqual(Fake.Drafted{ .lane = 1, .from = 0, .anchor = 130, .pending = 9, .depth = 7, .sampled = false }, fake.holds[0]); + var got: [7]u32 = undefined; + try d.held(&.{&s}, &.{&got}); + try testing.expectEqualSlices(u32, &.{ 10, 11, 12, 13, 14, 15, 16 }, &got); + var more: [8]u32 = undefined; + try testing.expectError(error.DraftHeldFewer, d.held(&.{&s}, &.{&more})); + try testing.expectError(error.DraftContextGap, d.absorb(&.{.{ .stream = &s, .features = features(1, 0), .start = 129, .follow = &.{} }})); + // A gap: the context starts at 200 and the held drafts are gone, as Metal's absorb leaves them. + try d.absorb(&.{.{ .stream = &s, .features = features(5, 0), .start = 200, .follow = &.{} }}); + try testing.expectError(error.DraftHeldFewer, d.held(&.{&s}, &.{got[0..1]})); + try d.hold(&.{.{ .stream = &s, .pending = 1, .position = 206, .depth = 3, .sampling = .{ .seed = 1, .temperature = 0.5 } }}); + try testing.expectEqual(Fake.Drafted{ .lane = 1, .from = 200, .anchor = 205, .pending = 1, .depth = 3, .sampled = true }, fake.holds[0]); + try testing.expectError(error.DraftFeaturesUnsupported, d.absorb(&.{.{ .stream = &s, .features = .{ .buffer = 1, .rows = 1, .row_bytes = dl.feature_row_bytes, .space = .host, .dtype = .bf16 }, .start = 205, .follow = &.{} }})); + try testing.expectError(error.TreesNotBuilt, d.absorb(&.{.{ .stream = &s, .features = features(1, 0), .start = 205, .follow = &.{}, .rows = &.{0} }})); + try testing.expectError(error.DSparkContextActive, host.setContext(400)); + d.release(&s); + try testing.expectEqual(@as(u32, 1), fake.closed); + try host.setContext(400); + try testing.expectEqual(dl.scoreBytes(400), fake.scores); +} + +test "one backend call drafts every stream's hold, and a refused hold reaches no backend" { + var fake: Fake = .{}; + var host = dl.Drafter(Fake).init(testing.allocator, &fake); + defer host.deinit(); + try host.setContext(1024); + const d = host.drafter(); + var a = try stream("a"); + defer a.deinit(testing.allocator); + var b = try stream("b"); + defer b.deinit(testing.allocator); + var c = try stream("c"); + defer c.deinit(testing.allocator); + try d.open(&a); + try d.open(&b); + try d.absorb(&.{ .{ .stream = &a, .features = features(3, 0), .start = 0, .follow = &.{} }, .{ .stream = &b, .features = features(5, 0), .start = 0, .follow = &.{} } }); + try testing.expectEqual(@as(u32, 1), fake.absorb_calls); + try testing.expectEqual(@as(usize, 2), fake.n_pieces); + try d.hold(&.{ .{ .stream = &a, .pending = 100, .position = 4, .depth = 7 }, .{ .stream = &b, .pending = 200, .position = 6, .depth = 2 } }); + try testing.expectEqual(@as(u32, 1), fake.hold_calls); + try testing.expectEqual(@as(usize, 2), fake.n_holds); + var ga: [7]u32 = undefined; + var gb: [2]u32 = undefined; + try d.held(&.{ &a, &b }, &.{ &ga, &gb }); + try testing.expectEqualSlices(u32, &.{ 101, 102, 103, 104, 105, 106, 107 }, &ga); + try testing.expectEqualSlices(u32, &.{ 201, 202 }, &gb); + const refused = [_]struct { anyerror, []const dr.Hold }{ + .{ error.DraftStreamUnknown, &.{ .{ .stream = &a, .pending = 1, .position = 4, .depth = 1 }, .{ .stream = &c, .pending = 1, .position = 1, .depth = 1 } } }, + .{ error.DraftContextGap, &.{ .{ .stream = &a, .pending = 1, .position = 4, .depth = 1 }, .{ .stream = &b, .pending = 1, .position = 5, .depth = 1 } } }, + .{ error.DraftDepth, &.{.{ .stream = &a, .pending = 1, .position = 4, .depth = 0 }} }, + }; + for (refused) |r| try testing.expectError(r[0], d.hold(r[1])); + try testing.expectEqual(@as(u32, 1), fake.hold_calls); + fake.nonfinite = true; + try testing.expectError(error.DraftNonfinite, d.hold(&.{.{ .stream = &a, .pending = 1, .position = 4, .depth = 2 }})); + try testing.expectError(error.DraftStreamUnknown, d.held(&.{&c}, &.{gb[0..1]})); + try testing.expectEqual(@as(u32, 2), fake.opened); +} diff --git a/zig/src/families/inkling2/experts.zig b/zig/src/families/inkling2/experts.zig new file mode 100644 index 00000000000..2d0d017d95f --- /dev/null +++ b/zig/src/families/inkling2/experts.zig @@ -0,0 +1,148 @@ +//! Inkling 2's routed experts: the family's grouping and grouped projections, main's rotation and combine. +const std = @import("std"); +const cuda = @import("cuda"); +const ops = @import("ops.zig"); + +const ex = cuda.exl3_experts; + +/// The two SwiGLU softcaps (config.json mlp_gate_softcap, mlp_up_softcap). +pub const Caps = struct { gate: f32, up: f32 }; + +/// Calls of at least this many rows take an item list (runs of one expert's members), not one item an expert. +pub const listed_from = 17; +/// Calls of at least this many rows take the prompt kernel (32 members by 64 columns a block). +pub const wide_from = 512; + +/// main's experts module beside the family's grouped projections. +pub const Kernels = struct { + main: ex.Experts, + mod: cuda.Module, + group: cuda.Function, + rows: cuda.Function, + wide: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + var main = try ex.Experts.load(d); + errdefer main.unload(); + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_experts); + errdefer mod.unload(); + return .{ + .main = main, + .mod = mod, + .group = try mod.function("tf_ink2x_group"), + .rows = try mod.function("tf_ink2x_rows"), + .wide = try mod.function("tf_ink2x_wide"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.main.unload(); + } +}; + +fn i32d(v: usize) i32 { + return @intCast(v); +} + +fn align256(n: usize) usize { + return (n + 255) / 256 * 256; +} + +/// Items at most a call of `rows` rows lists: runs of 16 members, plus one partial run a distinct expert. +fn maxItems(l: ex.Layer, rows: usize, slots: usize) usize { + const p = rows * slots; + return (p + 15) / 16 + @min(p, l.experts); +} + +/// main's scratch, then the item count and the item list (three int32 an item). +pub fn scratchBytes(l: ex.Layer, rows: usize, slots: usize) !usize { + return try ex.scratchBytes(l, rows, slots) + 256 + align256(maxItems(l, rows, slots) * 12); +} + +/// Where the item count sits in scratch laid out by ex.scratch over scratchBytes(); the list follows 256 bytes on. +fn itemsAt(l: ex.Layer, sc: ex.Scratch) u64 { + return sc.members + align256(@min(sc.rows * sc.slots, l.experts) * sc.rows * 4); +} + +/// exl3_experts.Experts.run's launches in its order: the family's grouped projections, ops.cu's tf_ink2_gateup. +pub fn run(e: *const Kernels, k: *const ops.Kernels, s: cuda.Stream, l: ex.Layer, caps: Caps, x: u64, x_stride: usize, x_dtype: ex.DType, pick: u64, wts: u64, rows: usize, out: u64, sc: ex.Scratch) !void { + const d = l.dims; + const w = l.width; + const slots = sc.slots; + if (rows < 1 or rows > sc.rows or slots < 1 or slots > 32) return error.BadExperts; + if (l.experts < 1 or l.experts > 512 or l.codebook != .mul1 or l.gu_stride != 0) return error.BadExperts; + const g_sk = try ex.plan(d, w, true); + const d_sk = try ex.plan(w, d, false); + const p = rows * slots; + const maxu = @min(p, l.experts); + + const listed = rows >= listed_from; + const wide = rows >= wide_from; + const per: usize = if (wide) 32 else 16; + const at = itemsAt(l, sc); + var a: cuda.Args = .{}; + for ([_]u64{ pick, sc.ids, sc.count, sc.members, at + 256, at }) |v| a.add(v); + for ([_]usize{ rows, slots, l.experts, rows, if (listed) per else 0, @intFromBool(!listed) }) |v| a.add(i32d(v)); + const shared: u32 = @intCast(l.experts * (32 * 2 + 2 * 4)); // per-warp uint16 counts, then counts and places + try cuda.launch.launch(e.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = shared }, s, &a); + const items: u64 = if (listed) at + 256 else 0; + const count: u64 = if (listed) at else sc.count; + const gy: u32 = @intCast(if (listed) (p + per - 1) / per + maxu else maxu); + const f = if (wide) e.wide else e.rows; + const cols: usize = if (wide) 64 else 128; + + var r: cuda.Args = .{}; + r.add(x); + r.add(i32d(x_stride)); + r.add(@as(i32, @backingInt(x_dtype))); + for ([_]u64{ pick, l.suh_g, l.suh_u, sc.xg, sc.xu }) |v| r.add(v); + for ([_]usize{ d, slots, l.experts }) |v| r.add(i32d(v)); + const rot: cuda.Dim3 = .{ .x = @intCast(p), .y = @intCast(d / 128), .z = 2 }; + try cuda.launch.launch(e.main.rot_in, .{ .grid = rot, .block = .{ .x = 32 } }, s, &r); + + var g: cuda.Args = .{}; + for ([_]u64{ sc.xg, sc.xu, l.gate, l.up, l.gate_k2, l.up_k2, sc.ids }) |v| g.add(v); + for ([_]u64{ items, count, sc.members, sc.z }) |v| g.add(v); + for ([_]usize{ d, w, p, g_sk, rows, slots }) |v| g.add(i32d(v)); + const gu: cuda.Dim3 = .{ .x = @intCast(w / cols), .y = gy, .z = @intCast(2 * g_sk) }; + try cuda.launch.launch(f, .{ .grid = gu, .block = .{ .x = 128 } }, s, &g); + + try ops.gateup(k, s, .{ .z = sc.z, .pick = pick, .svh_g = l.svh_g, .svh_u = l.svh_u, .suh_d = l.suh_d, .xd = sc.xd, .p = i32d(p), .n = i32d(w), .sk = i32d(g_sk), .experts = i32d(l.experts), .gate_cap = caps.gate, .up_cap = caps.up }); + + var dn: cuda.Args = .{}; + for ([_]u64{ sc.xd, sc.xd, l.down, l.down, l.down_k2, l.down_k2, sc.ids }) |v| dn.add(v); + for ([_]u64{ items, count, sc.members, sc.z }) |v| dn.add(v); + for ([_]usize{ w, d, p, d_sk, rows, slots }) |v| dn.add(i32d(v)); + const down: cuda.Dim3 = .{ .x = @intCast(d / cols), .y = gy, .z = @intCast(d_sk) }; + try cuda.launch.launch(f, .{ .grid = down, .block = .{ .x = 128 } }, s, &dn); + + var cb: cuda.Args = .{}; + for ([_]u64{ sc.z, pick, l.svh_d, sc.y, wts, out }) |v| cb.add(v); + for ([_]usize{ p, d, d_sk, l.experts, slots }) |v| cb.add(i32d(v)); + const comb: cuda.Dim3 = .{ .x = @intCast(rows), .y = @intCast(d / 128) }; + try cuda.launch.launch(e.main.down_combine, .{ .grid = comb, .block = .{ .x = @intCast(32 * slots) } }, s, &cb); +} + +test "experts: Inkling's expert shapes have built tiles (gate/up 4608 -> 2304 whole and a rank's 1152, down back)" { + try std.testing.expectEqual(@as(u32, 4), try ex.plan(4608, 2304, true)); + try std.testing.expectEqual(@as(u32, 4), try ex.plan(4608, 1152, true)); + _ = try ex.plan(2304, 4608, false); + _ = try ex.plan(1152, 4608, false); +} + +test "experts: the item list sits past main's scratch and holds a 2,048-row call's items" { + var l = std.mem.zeroes(ex.Layer); + l.experts = 384; + l.dims = 4608; + l.width = 1152; + l.codebook = .mul1; + const bytes = try scratchBytes(l, 2048, 8); + const sc = try ex.scratch(0, l, 2048, 8); + const at = itemsAt(l, sc); + try std.testing.expectEqual(@as(u64, try ex.scratchBytes(l, 2048, 8)), at); + try std.testing.expectEqual(@as(usize, 16384 / 16 + 384), maxItems(l, 2048, 8)); + try std.testing.expect(at + 256 + maxItems(l, 2048, 8) * 12 <= bytes); + // the kernels' column blocks: the rows kernel 128 columns, the wide one 64, of a rank's 1152 and the 4608 width + try std.testing.expect(1152 % 128 == 0 and 4608 % 128 == 0); +} diff --git a/zig/src/families/inkling2/fixtures/mini_config.json b/zig/src/families/inkling2/fixtures/mini_config.json new file mode 100644 index 00000000000..71dca9f656e --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_config.json @@ -0,0 +1,129 @@ +{ + "_fixture_provenance": { + "release": "thinkingmachines/Inkling-2-Mini", + "revision": "ed40e7da625f594fc9c4990f5f66be24873c22d7", + "revision_status": "full revision supplied separately; every checkpoint config field matches", + "published": "2026-11-20", + "license": "apache-2.0" + }, + "dtype": "bfloat16", + "architectures": [ + "Inkling2LoopForConditionalGeneration" + ], + "model_type": "inkling2_loop", + "eos_token_id": 200006, + "text_config": { + "model_type": "inkling2_loop_text", + "model_max_length": 1048576, + "torch_dtype": "bfloat16", + "hidden_size": 2304, + "num_hidden_layers": 24, + "vocab_size": 201024, + "num_attention_heads": 24, + "num_key_value_heads": 8, + "head_dim": 128, + "d_rel": 16, + "rel_extent": 1024, + "q_bias": false, + "o_bias": false, + "log_scaling_n_floor": 8192, + "log_scaling_alpha": 0.1, + "rms_norm_eps": 1e-06, + "use_value_norm_no_gamma": true, + "qk_l2_clip_threshold": 22.627416997969522, + "rel_l2_clip_threshold": 8.0, + "local_layer_ids": [ + 0, + 1, + 2, + 3, + 4, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 18, + 19, + 20, + 21, + 22 + ], + "sconv_kernel_size": 4, + "unpadded_vocab_size": 200058, + "final_logit_softcapping": 30.0, + "swa_head_dim": 128, + "swa_num_attention_heads": 24, + "swa_num_key_value_heads": 8, + "sliding_window_size": 1024, + "n_layers_per_attn_res_block": 6, + "attn_res_normalize_values": true, + "n_routed_experts": 128, + "num_experts_per_tok": 8, + "n_shared_experts": 0, + "intermediate_size": 1152, + "mlp_gate_softcap": 4.0, + "mlp_up_softcap": 25.0, + "route_scale": 8.0, + "use_gate_bias": true, + "loop_config": { + "core_start": 6, + "core_end": 18, + "num_passes": 3, + "gate_rank": 64, + "is_varloop": false + } + }, + "vision_config": { + "model_type": "inkling2_vision", + "text_hidden_size": 2304, + "temporal_patch_size": 2, + "native_patch_size": 20, + "adapter_merge_size": 2, + "projection_hidden_dim": 4096, + "projector_bias": false, + "hidden_size": 1024, + "num_hidden_layers": 23, + "num_attention_heads": 16, + "mlp_ratio": 4.0, + "posemb_grid_size": 32, + "layer_norm_eps": 1e-05 + }, + "mtp_config": { + "hidden_size": 2304, + "num_hidden_layers": 3, + "num_attention_heads": 24, + "num_key_value_heads": 8, + "head_dim": 128, + "intermediate_size": 9216, + "max_position_embeddings": 1048576, + "torch_dtype": "bfloat16", + "q_bias": false, + "o_bias": false, + "rms_norm_eps": 1e-06, + "rope_theta": 1000000.0, + "local_layer_ids": [ + 0, + 2 + ], + "sliding_window_size": 1024, + "block_size": 8, + "markov_rank": 256, + "markov_head_type": "rnn_hidden", + "target_layer_ids": [ + 5, + 23, + 41, + 48 + ] + }, + "quantization_config": { + "quant_method": "modelopt", + "quant_algo": "NVFP4" + } +} diff --git a/zig/src/families/inkling2/fixtures/mini_model_header.txt b/zig/src/families/inkling2/fixtures/mini_model_header.txt new file mode 100644 index 00000000000..0ec22c72d2b --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_model_header.txt @@ -0,0 +1,86 @@ +inkling2-mini-model 1244 dfcec4225659aceabe432e4daadb4e6291f3718e2015d412f97f60200de32141 release=thinkingmachines/Inkling-2-Mini revision=ed40e7da625f594fc9c4990f5f66be24873c22d7 published=2026-11-20 license=apache-2.0 +model.llm.attn_res.attn_queries.{L} F32 2304 0-3,5-9,11-15,17-21 +model.llm.attn_res.attn_queries.{L} F32 3x2304 4,10,16,22 +model.llm.attn_res.mlp_queries.{L} F32 2304 0-23 +model.llm.attn_res.output_query F32 2304 +model.llm.embed.weight BF16 201024x2304 +model.llm.embed_norm.weight BF16 2304 +model.llm.layers.{L}.attn.attn_sink_proj.weight BF16 24x2304 0-23 +model.llm.layers.{L}.attn.gate_attn.weight BF16 3072x2304 0-23 +model.llm.layers.{L}.attn.k_sconv.static_w BF16 4x1024 5,11,17,23 +model.llm.layers.{L}.attn.k_sconv.weight BF16 1024x1x4 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn.k_sconv.weight_proj BF16 32x2304 5,11,17,23 +model.llm.layers.{L}.attn.q_l2_clip.scale BF16 24x128 0-23 +model.llm.layers.{L}.attn.rel_l2_clip.scale BF16 24x16 0-23 +model.llm.layers.{L}.attn.rel_logits_proj.proj BF16 16x1024 0-23 +model.llm.layers.{L}.attn.v_sconv.static_w BF16 4x1024 5,11,17,23 +model.llm.layers.{L}.attn.v_sconv.weight BF16 1024x1x4 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn.v_sconv.weight_proj BF16 32x2304 5,11,17,23 +model.llm.layers.{L}.attn.wk_dv.weight BF16 1024x2304 0-23 +model.llm.layers.{L}.attn.wo_ud.weight BF16 2304x3072 0-23 +model.llm.layers.{L}.attn.wq_du.weight BF16 3072x2304 0-23 +model.llm.layers.{L}.attn.wr_du.weight BF16 384x2304 0-23 +model.llm.layers.{L}.attn.wv_dv.weight BF16 1024x2304 0-23 +model.llm.layers.{L}.attn_norm.weight BF16 2304 0-4,6-10,12-16,18-22 +model.llm.layers.{L}.attn_sconv.weight BF16 2304x1x4 0-23 +model.llm.layers.{L}.controllers.attn.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.attn.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.attn.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.k.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.k.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.k.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.mlp.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.mlp.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.mlp.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.v.down_weight BF16 64x4608 6-17 +model.llm.layers.{L}.controllers.v.forget_weight BF16 2304x64 6-17 +model.llm.layers.{L}.controllers.v.gain_weight BF16 2304x64 6-17 +model.llm.layers.{L}.k_input_norm.weight BF16 2304 5,11,17,23 +model.llm.layers.{L}.mlp.experts.w13_weight F8_E4M3 128x2304x2304 20-23 +model.llm.layers.{L}.mlp.experts.w13_weight U8 128x2304x1152 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_amax F32 128 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_outer_scale_denominator F32 1 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_scale F8_E4M3 128x2304x144 0-19 +model.llm.layers.{L}.mlp.experts.w13_weight_scale U8 128x2304x72 20-23 +model.llm.layers.{L}.mlp.experts.w2_weight F8_E4M3 128x2304x1152 20-23 +model.llm.layers.{L}.mlp.experts.w2_weight U8 128x2304x576 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_amax F32 128 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_outer_scale_denominator F32 1 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_scale F8_E4M3 128x2304x72 0-19 +model.llm.layers.{L}.mlp.experts.w2_weight_scale U8 128x2304x36 20-23 +model.llm.layers.{L}.mlp.gate.bias F32 128 0-23 +model.llm.layers.{L}.mlp.gate.weight BF16 128x2304 0-23 +model.llm.layers.{L}.mlp_norm.weight BF16 2304 0-23 +model.llm.layers.{L}.mlp_sconv.weight BF16 2304x1x4 0-23 +model.llm.layers.{L}.q_input_norm.weight BF16 2304 5,11,17,23 +model.llm.layers.{L}.v_input_norm.weight BF16 2304 5,11,17,23 +model.llm.middle_cycle_cross_pass_kv_queries F32 24x2304 +model.llm.middle_cycle_cross_pass_queries F32 24x2304 +model.llm.norm.weight BF16 2304 +model.llm.unembed.weight BF16 201024x2304 +model.visual.backbone.embeddings.class_embedding BF16 1024 +model.visual.backbone.embeddings.cls_position_embedding BF16 1024 +model.visual.backbone.embeddings.patch_embedding.weight BF16 1024x1200 +model.visual.backbone.embeddings.position_embedding BF16 1024x1024 +model.visual.backbone.layers.{L}.ln_1.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_1.weight BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_2.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.ln_2.weight BF16 1024 0-22 +model.visual.backbone.layers.{L}.ls_1.gamma BF16 1024 0-22 +model.visual.backbone.layers.{L}.ls_2.gamma BF16 1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_fc.bias BF16 4096 0-22 +model.visual.backbone.layers.{L}.mlp.c_fc.weight BF16 4096x1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.mlp.c_proj.weight BF16 1024x4096 0-22 +model.visual.backbone.layers.{L}.self_attn.k_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.k_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.out_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.out_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.q_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.q_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.layers.{L}.self_attn.v_proj.bias BF16 1024 0-22 +model.visual.backbone.layers.{L}.self_attn.v_proj.weight BF16 1024x1024 0-22 +model.visual.backbone.ln_pre.bias BF16 1024 +model.visual.backbone.ln_pre.weight BF16 1024 +model.visual.proj_in.weight BF16 4096x4096 +model.visual.proj_out.weight BF16 2304x4096 diff --git a/zig/src/families/inkling2/fixtures/mini_mtp_header.txt b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt new file mode 100644 index 00000000000..1f02401ebcb --- /dev/null +++ b/zig/src/families/inkling2/fixtures/mini_mtp_header.txt @@ -0,0 +1,25 @@ +inkling2-mini-mtp 54 f962cd87735ebbd1af0639f7513f99eed98b61d8a30b083fb33fc1bb1c3a70d1 release=thinkingmachines/Inkling-2-Mini revision=ed40e7da625f594fc9c4990f5f66be24873c22d7 published=2026-11-20 license=apache-2.0 +fuse_weight BF16 4x4 +layers.{L}.dflare_norm.weight BF16 2304 0-2 +layers.{L}.input_layernorm.weight BF16 2304 0-2 +layers.{L}.mlp.down_proj.weight BF16 2304x9216 0-2 +layers.{L}.mlp.gate_proj.weight BF16 9216x2304 0-2 +layers.{L}.mlp.up_proj.weight BF16 9216x2304 0-2 +layers.{L}.post_attention_layernorm.weight BF16 2304 0-2 +layers.{L}.self_attn.k_norm.weight BF16 128 0-2 +layers.{L}.self_attn.k_norm_ctx.weight BF16 128 0-2 +layers.{L}.self_attn.k_proj.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.k_proj_ctx.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.o_proj.weight BF16 2304x3072 0-2 +layers.{L}.self_attn.q_norm.weight BF16 128 0-2 +layers.{L}.self_attn.q_proj.weight BF16 3072x2304 0-2 +layers.{L}.self_attn.v_proj.weight BF16 1024x2304 0-2 +layers.{L}.self_attn.v_proj_ctx.weight BF16 1024x2304 0-2 +markov_head.dflare_norm.weight BF16 2304 +markov_head.hidden_out.bias BF16 2304 +markov_head.hidden_out.weight BF16 2304x256 +markov_head.markov_w1.weight BF16 201024x256 +markov_head.rnn_proj.bias BF16 768 +markov_head.rnn_proj.weight BF16 768x5120 +mask_embed BF16 2304 +norm.weight BF16 2304 diff --git a/zig/src/families/inkling2/host_test.zig b/zig/src/families/inkling2/host_test.zig index 4f8b47e83b3..0f507ef37b3 100644 --- a/zig/src/families/inkling2/host_test.zig +++ b/zig/src/families/inkling2/host_test.zig @@ -5,6 +5,12 @@ test { _ = @import("names.zig"); _ = @import("names_test.zig"); _ = @import("plan.zig"); + _ = @import("loop.zig"); + _ = @import("kept_state.zig"); + _ = @import("dspark_lanes.zig"); + _ = @import("dspark_lanes_test.zig"); + _ = @import("loop_model.zig"); + _ = @import("loop_model_test.zig"); _ = @import("prompt.zig"); _ = @import("template_test.zig"); _ = @import("tokenizer_test.zig"); diff --git a/zig/src/families/inkling2/image.zig b/zig/src/families/inkling2/image.zig new file mode 100644 index 00000000000..9b62e00d518 --- /dev/null +++ b/zig/src/families/inkling2/image.zig @@ -0,0 +1,242 @@ +//! Inkling 2's image processor on the host: Inkling2ImageProcessor's 40-pixel patches and the tower's input tables. +const std = @import("std"); +const core = @import("core"); + +const picture = core.picture; +const b16 = core.bf16_round; + +pub const side = 40; // pixels a decoder token covers: the native 20-pixel patch, 2 x 2 merged +pub const patch = 20; +pub const merge = 2; +pub const grid = 32; // the learned position table's side +pub const patch_width = 3 * patch * patch; // a native patch's inputs: row, column, channel +pub const pairs = 32; // rotary pairs a 64-wide head: 16 by column, then 16 by row +const theta: f32 = 10000; +const pad: f32 = -1; // pixels outside the picture, on the 0-255 scale +const mean: f32 = 0.5 * 255.0; // the fused mean and std (0.5 each, rescale 1/255) as fp32 +const std_: f32 = 0.5 * 255.0; + +/// The release's placeholder: one per decoder image token, its rows replaced by the tower's. +pub const image_token: u32 = 200054; +/// The chat template's marker ahead of an image's placeholders. +pub const image_marker = "<|content_image|>"; + +/// One picture: its normalized patches ([tokens][40][40][3] fp32, the processor's pixel_values) and its grid. +pub const Prepared = struct { + pixels: []f32, + rows: u32, + cols: u32, + + pub fn tokens(p: Prepared) u32 { + return p.rows * p.cols; + } + + pub fn deinit(p: *Prepared, a: std.mem.Allocator) void { + a.free(p.pixels); + p.* = undefined; + } +}; + +/// Decoder tokens a picture of `w` x `h` pixels takes: no resize, one per 40-pixel cell of the padded grid. +pub fn tokensFor(w: usize, h: usize) usize { + return ((h + side - 1) / side) * ((w + side - 1) / side); +} + +/// PNG, JPEG or WebP bytes as the processor reads them: EXIF-oriented, alpha over its 8-pixel checkerboard. +pub fn decode(io: std.Io, a: std.mem.Allocator, bytes: []const u8, limits: picture.Limits) picture.Error!picture.Rgb { + const s = switch (picture.sniff(bytes)) { + .png => try picture.png.decodeWithLimits(a, bytes, limits), + .jpeg => try picture.jpeg.decodeWithLimits(io, a, bytes, limits), + .webp => try picture.webp.decodeWithLimits(io, a, bytes, limits), + .unknown => return error.Invalid, + }; + defer a.free(s.data); + if (s.channels != 4) return picture.finish(a, s); + // orient the alpha with the colours (finish on a 4-channel copy keeps it), then composite + const rgba = try a.alloc(u8, s.width * s.height * 4); + defer a.free(rgba); + const turned = orient4(s, rgba); + const out = try a.alloc(u8, turned.w * turned.h * 3); + for (0..turned.h) |y| for (0..turned.w) |x| { + const px = rgba[(y * turned.w + x) * 4 ..][0..4]; + const bg: u32 = if ((y / 8 + x / 8) % 2 == 0) 204 else 153; + for (out[(y * turned.w + x) * 3 ..][0..3], px[0..3]) |*c, v| c.* = over(v, px[3], bg); + }; + return .{ .width = turned.w, .height = turned.h, .pixels = out }; +} + +/// The processor's composite: (c * alpha + bg * (255 - alpha) + 127) // 255 in integers. +pub fn over(c: u8, alpha: u8, bg: u32) u8 { + return @intCast((@as(u32, c) * alpha + bg * (255 - alpha) + 127) / 255); +} + +/// picture.finish's transpose of 4-channel samples into `out`. +fn orient4(s: picture.Samples, out: []u8) struct { w: usize, h: usize } { + const o = if (s.orientation >= 2 and s.orientation <= 8) s.orientation else 1; + const w, const h = if (o >= 5) .{ s.height, s.width } else .{ s.width, s.height }; + for (0..h) |y| for (0..w) |x| { + const sx, const sy = switch (o) { + 2 => .{ s.width - 1 - x, y }, + 3 => .{ s.width - 1 - x, s.height - 1 - y }, + 4 => .{ x, s.height - 1 - y }, + 5 => .{ y, x }, + 6 => .{ y, s.height - 1 - x }, + 7 => .{ s.width - 1 - y, s.height - 1 - x }, + 8 => .{ s.width - 1 - y, x }, + else => .{ x, y }, + }; + @memcpy(out[(y * w + x) * 4 ..][0..4], s.data[(sy * s.width + sx) * 4 ..][0..4]); + }; + return .{ .w = w, .h = h }; +} + +/// RGB rows to the processor's pixel_values: padded with -1 to the 40-pixel grid, (v - 127.5) / 127.5 in fp32. +pub fn patches(a: std.mem.Allocator, img: picture.Rgb) !Prepared { + const rows: u32 = @intCast((img.height + side - 1) / side); + const cols: u32 = @intCast((img.width + side - 1) / side); + const px = try a.alloc(f32, @as(usize, rows) * cols * side * side * 3); + for (0..rows) |r| for (0..cols) |c| for (0..side) |y| for (0..side) |x| { + const iy = r * side + y; + const ix = c * side + x; + const at = ((((r * cols + c) * side + y) * side) + x) * 3; + for (0..3) |ch| { + const v: f32 = if (iy < img.height and ix < img.width) @floatFromInt(img.pixels[(iy * img.width + ix) * 3 + ch]) else pad; + px[at + ch] = (v - mean) / std_; + } + }; + return .{ .pixels = px, .rows = rows, .cols = cols }; +} + +/// Bytes to patches: decode, then patches; refuses pictures over `max_tokens`. +pub fn prepare(io: std.Io, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) !Prepared { + var img = try decode(io, a, bytes, .{}); + defer img.deinit(a); + if (tokensFor(img.width, img.height) > max_tokens) return error.ImageTooLarge; + return patches(a, img); +} + +/// The words for a refusal of prepare's own. +pub fn explain(err: anyerror) ?[]const u8 { + return switch (err) { + error.ImageTooLarge => "image too large for the tower's limit (one token per 40 x 40 pixels, no resize)", + error.Invalid => picture.problem(error.Invalid), + error.Oversized => picture.problem(error.Oversized), + error.Animated => picture.problem(error.Animated), + else => picture.decoderProblem(err), + }; +} + +/// Native patches a picture holds: 4 a token, in merge order (token raster, then the 2 x 2 block raster). +pub fn patchCount(p: Prepared) usize { + return @as(usize, p.tokens()) * merge * merge; +} + +/// A merge-order patch's (row, column) on the native patch grid. +pub fn place(i: usize, cols: u32) [2]usize { + const t = i / (merge * merge); + const in = i % (merge * merge); + return .{ t / cols * merge + in / merge, t % cols * merge + in % merge }; +} + +/// The patch embedding's input rows as bf16 bits: [patches][row][column][channel] (the tower's reshape). +pub fn patchRows(p: Prepared, out: []u16) void { + for (0..patchCount(p)) |i| { + const t = i / (merge * merge); + const my = i % (merge * merge) / merge; + const mx = i % merge; + for (0..patch) |y| for (0..patch) |x| for (0..3) |ch| { + const v = p.pixels[((t * side + my * patch + y) * side + mx * patch + x) * 3 + ch]; + out[i * patch_width + (y * patch + x) * 3 + ch] = b16.bits(v); + }; + } +} + +/// One axis's two bilinear taps and weights (torch's align_corners=False interpolation, edge taps clamped). +const Taps = struct { t: [2]u32, w: [2]f32 }; + +fn axis(index: usize, size: usize) Taps { + const src = (@as(f32, @floatFromInt(index)) + 0.5) * @as(f32, grid) / @as(f32, @floatFromInt(size)) - 0.5; + const fl = @floor(src); + var out: Taps = undefined; + for (0..2) |o| { + const raw = @as(i64, @intFromFloat(fl)) + @as(i64, @intCast(o)); + out.t[o] = @intCast(std.math.clamp(raw, 0, grid - 1)); + out.w[o] = @max(1 - @abs(src - fl - @as(f32, @floatFromInt(o))), 0); + } + return out; +} + +/// Each patch's four position-table rows and fp32 weights (h0 w0, h0 w1, h1 w0, h1 w1), as the tower resamples. +pub fn positionTaps(p: Prepared, taps: []u32, weights: []f32) void { + const H = @as(usize, p.rows) * merge; + const W = @as(usize, p.cols) * merge; + for (0..patchCount(p)) |i| { + const rc = place(i, p.cols); + const h = axis(rc[0], H); + const w = axis(rc[1], W); + for (0..2) |a| for (0..2) |b| { + taps[i * 4 + a * 2 + b] = h.t[a] * grid + w.t[b]; + weights[i * 4 + a * 2 + b] = h.w[a] * w.w[b]; + }; + } +} + +/// Rotary cos and sin a sequence row ([rows][32] fp32): row 0 the class token at (0, 0), patch i at its place + 1. +pub fn rotary(p: Prepared, cs: []f32, sn: []f32, on: bool) void { + var inv: [pairs / 2]f32 = undefined; + for (&inv, 0..) |*f, i| f.* = 1.0 / std.math.pow(f32, theta, @as(f32, @floatFromInt(2 * i)) / @as(f32, pairs)); + for (0..patchCount(p) + 1) |r| { + const rc: [2]usize = if (r == 0) .{ 0, 0 } else blk: { + const q = place(r - 1, p.cols); + break :blk .{ q[0] + 1, q[1] + 1 }; + }; + for (0..pairs) |j| { + const pos: f32 = @floatFromInt(if (j < pairs / 2) rc[1] else rc[0]); + const ang = pos * inv[j % (pairs / 2)]; + cs[r * pairs + j] = if (on) @cos(ang) else 1; + sn[r * pairs + j] = if (on) @sin(ang) else 0; + } + } +} + +test "tokens: one per 40-pixel cell, padded up" { + try std.testing.expectEqual(@as(usize, 15), tokensFor(200, 120)); + try std.testing.expectEqual(@as(usize, 117), tokensFor(333, 517)); + try std.testing.expectEqual(@as(usize, 2), tokensFor(37, 45)); +} + +test "checkerboard composite as the processor rounds it" { + try std.testing.expectEqual(@as(u8, 10), over(10, 255, 204)); + try std.testing.expectEqual(@as(u8, 204), over(10, 0, 204)); + try std.testing.expectEqual(@as(u8, (100 * 128 + 153 * 127 + 127) / 255), over(100, 128, 153)); +} + +test "merge order and bilinear taps against torch's interpolation formula" { + try std.testing.expectEqual([2]usize{ 0, 1 }, place(1, 5)); + try std.testing.expectEqual([2]usize{ 1, 0 }, place(2, 5)); + try std.testing.expectEqual([2]usize{ 0, 2 }, place(4, 5)); + try std.testing.expectEqual([2]usize{ 2, 0 }, place(20, 5)); + // a 6-patch axis on the 32 grid: src = (i + 0.5) * 32 / 6 - 0.5 + const a0 = axis(0, 6); + try std.testing.expectEqual([2]u32{ 2, 3 }, a0.t); + try std.testing.expectApproxEqAbs(@as(f32, 0.8333333), a0.w[0], 1e-6); + const e = axis(0, 64); // src -0.25: floor -1 clamped to 0 twice, weights 0.25 and 0.75 + try std.testing.expectEqual([2]u32{ 0, 0 }, e.t); + try std.testing.expectEqual([2]f32{ 0.25, 0.75 }, e.w); +} + +test "patches: padding reads -1 on the 0-255 scale, the patch rows reorder by 20-pixel blocks" { + const a = std.testing.allocator; + var px: [41 * 3]u8 = @splat(0); + px[40 * 3] = 255; + var p = try patches(a, .{ .width = 41, .height = 1, .pixels = &px }); + defer p.deinit(a); + try std.testing.expectEqual(@as(u32, 2), p.cols); + try std.testing.expectEqual(@as(f32, -1), p.pixels[0]); + try std.testing.expectEqual(@as(f32, (-1 - 127.5) / 127.5), p.pixels[3 * side]); + try std.testing.expectEqual(@as(f32, 1), p.pixels[side * side * 3]); + const rows = try a.alloc(u16, patchCount(p) * patch_width); + defer a.free(rows); + patchRows(p, rows); + try std.testing.expectEqual(b16.bits(1), rows[4 * patch_width]); // token 1's first patch, pixel (0, 0) +} diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index 556bca61b13..f0c113205f2 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -1,12 +1,30 @@ //! Inkling 2 Small (model_type inkling2) on CUDA: config, chat, reply split, admission, kernels, EXL3 weights, forward. +pub const image = @import("image.zig"); +pub const vision = @import("vision.zig"); pub const kernels = @import("kernels.zig"); pub const ops = @import("ops.zig"); +pub const experts = @import("experts.zig"); +pub const modelopt = @import("modelopt.zig"); +pub const loop = @import("loop.zig"); +pub const kept_state = @import("kept_state.zig"); +pub const loop_model = @import("loop_model.zig"); +pub const loop_math_cuda = @import("loop_math_cuda.zig"); +pub const native = @import("cuda_native.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; test { + _ = image; + _ = vision; _ = kernels; _ = ops; + _ = experts; + _ = modelopt; + _ = native; + _ = loop; + _ = kept_state; + _ = loop_model; + _ = loop_math_cuda; } diff --git a/zig/src/families/inkling2/kept_state.zig b/zig/src/families/inkling2/kept_state.zig new file mode 100644 index 00000000000..f56755cffeb --- /dev/null +++ b/zig/src/families/inkling2/kept_state.zig @@ -0,0 +1,154 @@ +//! A kept prompt state's attention rows for any backend: which rows of which key head of which visit, in packed order. +const std = @import("std"); + +/// One visit's K and V caches, each head-major ([key head][ring][row]); `k` and `v` are where they start. +pub const Visit = struct { k: u64, v: u64, heads: u32, ring: u64, row: u64, global: bool }; + +/// Rows a visit keeps at `at`: a global layer all of them, a sliding one the `window - 1` its next token reads. +pub fn kept(global: bool, window: u32, at: u64) u64 { + return if (global) at else @min(at, window - 1); +} + +/// The packed bytes of every visit's kept rows at `at`; a backend's other state (its convolutions) follows them. +pub fn bytes(visits: []const Visit, window: u32, at: u64) u64 { + var n: u64 = 0; + for (visits) |v| n += 2 * @as(u64, v.heads) * kept(v.global, window, at) * v.row; + return n; +} + +/// Whether every visit's ring holds the rows it keeps at `at` (a cache too short for the state cannot take it). +pub fn fits(visits: []const Visit, window: u32, at: u64) bool { + for (visits) |v| if (kept(v.global, window, at) > v.ring) return false; + return true; +} + +/// One contiguous copy: `len` bytes at `cache` (an address in a visit's caches) and at `offset` in the packed state. +pub const Piece = struct { cache: u64, offset: u64, len: u64 }; + +/// Every piece of the kept rows, in packed order: visit, K then V, key head, position; a ring wrap splits a head. +pub const Walk = struct { + visits: []const Visit, + window: u32, + at: u64, + visit: usize = 0, + side: u1 = 0, + head: u32 = 0, + pos: ?u64 = null, + offset: u64 = 0, + + pub fn init(visits: []const Visit, window: u32, at: u64) Walk { + return .{ .visits = visits, .window = window, .at = at }; + } + + pub fn next(w: *Walk) ?Piece { + while (w.visit < w.visits.len) { + const v = w.visits[w.visit]; + if (w.head == v.heads) { + w.head = 0; + if (w.side == 1) w.visit += 1; + w.side +%= 1; + continue; + } + const pos = w.pos orelse w.at - kept(v.global, w.window, w.at); + if (pos == w.at) { + w.pos = null; + w.head += 1; + continue; + } + const slot = pos % v.ring; + const n = @min(w.at - pos, v.ring - slot); + const base = (if (w.side == 0) v.k else v.v) + w.head * v.ring * v.row; + const piece: Piece = .{ .cache = base + slot * v.row, .offset = w.offset, .len = n * v.row }; + w.offset += piece.len; + w.pos = pos + n; + return piece; + } + return null; + } +}; + +const testing = std.testing; + +/// A host cache: `visits` laid out one after another, rings of `global` or `sliding` rows, each row `row` bytes. +fn layout(out: []Visit, global: u64, sliding: u64) u64 { + const heads = 3; + const row = 4; + var at: u64 = 0; + for (out, 0..) |*v, i| { + const g = i % 3 == 1; + const ring = if (g) global else sliding; + v.* = .{ .k = at, .v = at + heads * ring * row, .heads = heads, .ring = ring, .row = row, .global = g }; + at += 2 * heads * ring * row; + } + return at; +} + +/// The row a fresh prompt leaves at `pos` of a visit's key head: what any later reader of that position must see. +fn rowOf(visit: usize, side: u1, head: u32, pos: u64) [4]u8 { + const x: u32 = @truncate((visit * 2 + side) * 7919 + head * 104729 + pos * 31); + return @bitCast(x); +} + +/// Writes positions 0..at in order, as a prompt does: a sliding ring's later rows overwrite its earlier ones. +fn fill(cache: []u8, visits: []const Visit, at: u64) void { + for (visits, 0..) |v, i| for (0..2) |side| for (0..v.heads) |h| for (0..at) |pos| { + const base = (if (side == 0) v.k else v.v) + h * v.ring * v.row; + @memcpy(cache[base + (pos % v.ring) * v.row ..][0..4], &rowOf(i, @intCast(side), @intCast(h), pos)); + }; +} + +fn copyAll(cache: []u8, state: []u8, visits: []const Visit, window: u32, at: u64, out: bool) u64 { + var w = Walk.init(visits, window, at); + while (w.next()) |p| { + const c = cache[p.cache..][0..p.len]; + const s = state[p.offset..][0..p.len]; + if (out) @memcpy(s, c) else @memcpy(c, s); + } + return w.offset; +} + +test "a state restores each head's kept rows into a cache of another capacity" { + const window = 6; + var from_v: [6]Visit = undefined; + var to_v: [6]Visit = undefined; + // Sliding rings 8 and 12, global rings 16 and 40: every kept row lands at another slot after the restore. + const from_len = layout(&from_v, 16, 8); + const to_len = layout(&to_v, 40, 12); + const from = try testing.allocator.alloc(u8, from_len); + defer testing.allocator.free(from); + const to = try testing.allocator.alloc(u8, to_len); + defer testing.allocator.free(to); + const state = try testing.allocator.alloc(u8, bytes(&from_v, window, 16)); + defer testing.allocator.free(state); + for ([_]u64{ 1, 4, 5, 6, 9, 13, 16 }) |at| { + try testing.expect(fits(&from_v, window, at) and fits(&to_v, window, at)); + @memset(from, 0); + fill(from, &from_v, at); + try testing.expectEqual(bytes(&from_v, window, at), copyAll(from, state, &from_v, window, at, true)); + @memset(to, 0xa5); + try testing.expectEqual(bytes(&to_v, window, at), copyAll(to, state, &to_v, window, at, false)); + for (to_v, 0..) |v, i| for (0..2) |side| for (0..v.heads) |h| { + for (at - kept(v.global, window, at)..at) |pos| { + const base = (if (side == 0) v.k else v.v) + h * v.ring * v.row; + const want = rowOf(i, @intCast(side), @intCast(h), pos); + try testing.expectEqualSlices(u8, &want, to[base + (pos % v.ring) * v.row ..][0..4]); + } + }; + } +} + +test "the walk keeps a sliding layer's window less one and splits a head where its ring wraps" { + const v = [_]Visit{.{ .k = 0, .v = 1000, .heads = 2, .ring = 8, .row = 10, .global = false }}; + var w = Walk.init(&v, 6, 11); + // Positions 6..10 sit in slots 6, 7, then 0..2: two pieces a head, K's two heads before V's. + const want = [_]Piece{ + .{ .cache = 60, .offset = 0, .len = 20 }, .{ .cache = 0, .offset = 20, .len = 30 }, + .{ .cache = 140, .offset = 50, .len = 20 }, .{ .cache = 80, .offset = 70, .len = 30 }, + .{ .cache = 1060, .offset = 100, .len = 20 }, .{ .cache = 1000, .offset = 120, .len = 30 }, + .{ .cache = 1140, .offset = 150, .len = 20 }, .{ .cache = 1080, .offset = 170, .len = 30 }, + }; + for (want) |p| try testing.expectEqual(p, w.next().?); + try testing.expectEqual(@as(?Piece, null), w.next()); + try testing.expectEqual(bytes(&v, 6, 11), w.offset); + try testing.expect(!fits(&.{.{ .k = 0, .v = 0, .heads = 1, .ring = 8, .row = 1, .global = true }}, 6, 9)); +} diff --git a/zig/src/families/inkling2/loop.zig b/zig/src/families/inkling2/loop.zig new file mode 100644 index 00000000000..7c6e8db290f --- /dev/null +++ b/zig/src/families/inkling2/loop.zig @@ -0,0 +1,154 @@ +//! Inkling 2 Mini's loop host layout: 48 private visit caches, whole-state snapshots and one-rank admission. +const std = @import("std"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); + +pub fn validateLoad(c: *const config.Config, rank: usize, images: bool) !void { + if (rank != 1) return error.Inkling2LoopOneRankOnly; + if (images) return error.Inkling2LoopTextOnly; + const lp = c.text.loop orelse return error.Inkling2LoopRequired; + if (lp.gate_rank != 64) return error.UnsupportedLoopGateRank; +} + +pub const SnapshotSlot = struct { + kv_offset: u64, + kv_bytes: u64, + conv_offset: u64, + conv_bytes: u64, +}; + +/// A stream or a saved prompt owns the same complete layout: no visit shares KV or convolution state with another. +pub const CacheLayout = struct { + slots: [config.max_visits]SnapshotSlot, + n: u32, + bytes: u64, + + pub fn init(c: *const config.Text, p: *const plan_.Plan, context: u32) !CacheLayout { + if (context == 0 or context > c.max_context or p.n_visits != c.visitCount()) return error.BadLoopCache; + var out: CacheLayout = undefined; + out.n = p.n_visits; + out.bytes = 0; + const conv_values = 3 * (2 * @as(u64, c.local.kv * c.local.dim) + 2 * @as(u64, c.hidden)); + for (p.visits[0..p.n_visits], 0..) |visit, i| { + const layer = p.layers[visit.layer]; + const rows: u32 = @intCast(@min(2048, context)); + const tokens = if (layer.kind == .global) + std.mem.alignForward(u32, context, 64) + else + std.mem.alignForward(u32, c.window + rows - 1, 64); + const kv = try std.math.mul(u64, tokens, 2 * @as(u64, layer.heads.kv * layer.heads.dim * 2)); + // The recurrence rounds each site then widens its complete state to FP32 before the FMAs. + const conv = try std.math.mul(u64, conv_values, 4); + out.slots[i] = .{ .kv_offset = out.bytes, .kv_bytes = kv, .conv_offset = 0, .conv_bytes = conv }; + out.bytes = try std.math.add(u64, out.bytes, kv); + } + var conv_offset = out.bytes; + for (out.slots[0..out.n]) |*slot| { + slot.conv_offset = conv_offset; + conv_offset = try std.math.add(u64, conv_offset, slot.conv_bytes); + } + out.bytes = conv_offset; + return out; + } + + pub fn at(l: *const CacheLayout, visit: u32) SnapshotSlot { + return l.slots[visit]; + } +}; + +/// The serial lane adapter's admission rule. One request occupies one complete 48-visit stream. +pub const Admission = struct { + context: u32, + + pub fn fits(a: Admission, prompt: u32, max_tokens: u32) bool { + return prompt <= a.context and max_tokens <= a.context - prompt; + } +}; + +/// A prompt-cache save or restore copies every byte of this layout, including all four convolution recurrences. +pub fn snapshotBytes(l: *const CacheLayout) u64 { + return l.bytes; +} + +pub const Snapshot = struct { + bytes: []u8, + + pub fn save(gpa: std.mem.Allocator, state: []const u8, l: *const CacheLayout) !Snapshot { + if (state.len != l.bytes) return error.BadLoopSnapshot; + return .{ .bytes = try gpa.dupe(u8, state) }; + } + + pub fn restore(s: *const Snapshot, state: []u8, l: *const CacheLayout) !void { + if (s.bytes.len != l.bytes or state.len != l.bytes) return error.BadLoopSnapshot; + @memcpy(state, s.bytes); + } + + pub fn deinit(s: *Snapshot, gpa: std.mem.Allocator) void { + gpa.free(s.bytes); + s.* = undefined; + } +}; + +test "a saved prompt restores every visit byte and owns its copy" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const layout = try CacheLayout.init(&c.text, &p, 1); + const state = try std.testing.allocator.alloc(u8, @intCast(layout.bytes)); + defer std.testing.allocator.free(state); + for (state, 0..) |*v, i| v.* = @truncate(i * 29 + 7); + var saved = try Snapshot.save(std.testing.allocator, state, &layout); + defer saved.deinit(std.testing.allocator); + @memset(state, 0xa5); + try saved.restore(state, &layout); + try std.testing.expectEqualSlices(u8, saved.bytes, state); + try std.testing.expectError(error.BadLoopSnapshot, Snapshot.save(std.testing.allocator, state[0 .. state.len - 1], &layout)); +} + +test "Mini has 48 independent KV and convolution slots and a whole-state snapshot" { + const config_test = @import("config_test.zig"); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var why: config.Why = .{}; + const c = try config.parse(a, config_test.mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const layout = try CacheLayout.init(&c.text, &p, 1_048_576); + try std.testing.expectEqual(@as(u32, 48), layout.n); + try std.testing.expectEqual(@as(u64, 3072 * 2 * 8 * 128 * 2), layout.at(0).kv_bytes); + try std.testing.expectEqual(@as(u64, 1_048_576 * 2 * 8 * 128 * 2), layout.at(5).kv_bytes); + try std.testing.expectEqual(@as(u64, 34_866_888_704), layout.bytes); + try std.testing.expectEqual(layout.bytes, snapshotBytes(&layout)); + try std.testing.expect((Admission{ .context = 8192 }).fits(8000, 192)); + try std.testing.expectEqual(@as(u64, 79_872), layout.at(0).conv_bytes); +} + +test "Mini loop load is one-rank text-only with rank-64 gated controllers" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + try validateLoad(&c, 1, false); + try std.testing.expectError(error.Inkling2LoopOneRankOnly, validateLoad(&c, 2, false)); + try std.testing.expectError(error.Inkling2LoopTextOnly, validateLoad(&c, 1, true)); +} + +test "pass two resets and only completed passes with a successor capture message banks" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), @import("config_test.zig").mini, &why); + var prec: [24]plan_.Precision = @splat(.nvfp4); + const p = try plan_.build(&c.text, &prec); + const lp = c.text.loop.?; + var banks: u32 = 0; + for (p.visits[0..p.n_visits]) |visit| { + if (visit.pass == 2 and visit.layer == lp.core_start) try std.testing.expect(visit.hasMessages()); + if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) banks += 1; + } + try std.testing.expectEqual(lp.passes - 1, banks); +} diff --git a/zig/src/families/inkling2/loop_backend.zig b/zig/src/families/inkling2/loop_backend.zig new file mode 100644 index 00000000000..8eab684e398 --- /dev/null +++ b/zig/src/families/inkling2/loop_backend.zig @@ -0,0 +1,333 @@ +//! Inkling 2 Mini lane execution and snapshot adapter. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const engine = @import("loop_engine.zig"); +const ops = @import("ops.zig"); + +const Model = engine.Model; +const Kernels = engine.Kernels; +const prompt_rows = engine.prompt_rows; +const window_rows = engine.window_rows; +const token_ring = 1024; + +const Lane = struct { + len: usize = 0, + fill: ?usize = null, + base: usize = 0, + rows: std.ArrayList(u32) = .empty, + last: u64, + rule: u64, + sampled: bool = false, +}; + +pub const Backend = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + m: *Model, + k: *const Kernels, + s: cuda.Stream, + lanes_: [engine.max_slots]?Lane = @splat(null), + streams: [engine.max_slots]?*lanes.Stream = @splat(null), // the stream each model slot holds + tokens: cuda.DeviceBuffer, + logits16: cuda.DeviceBuffer, + meta: cuda.DeviceBuffer, + slot: [engine.max_slots][2]cuda.DeviceBuffer = undefined, // each slot's last prompt logits and sampling rule + next: u64 = 0, + held: usize = 0, // slots with buffers + + const be = lanes.backend; + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, m: *Model, k: *const Kernels, s: cuda.Stream) !Backend { + const v = m.w.c.text.unpadded_vocab; + var tokens = try cuda.DeviceBuffer.alloc(d, (token_ring + window_rows) * 4); + errdefer tokens.free(); + var logits16 = try cuda.DeviceBuffer.alloc(d, window_rows * v * 2); + errdefer logits16.free(); + var meta = try cuda.DeviceBuffer.alloc(d, 16); + errdefer meta.free(); + var b: Backend = .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .tokens = tokens, .logits16 = logits16, .meta = meta }; + try b.slotBuffers(m.n_slots); + return b; + } + + /// Each model slot's own last-logits and rule buffers, up to `n`. + fn slotBuffers(b: *Backend, n: usize) !void { + for (0..n) |i| { + if (i < b.held) continue; + var last = try cuda.DeviceBuffer.alloc(b.d, b.m.w.c.text.unpadded_vocab * 4); + errdefer last.free(); + b.slot[i] = .{ last, try cuda.DeviceBuffer.alloc(b.d, @sizeOf(cuda.sample.Rule)) }; + b.held = i + 1; + } + } + + /// The server's stream count: one model slot and its buffers per stream. + pub fn reserve(b: *Backend, streams: u32) !void { + if (streams > engine.max_slots) return error.Inkling2TooManyStreams; + try b.m.addSlots(b.s, streams); + try b.slotBuffers(streams); + } + + pub fn deinit(b: *Backend) void { + for (&b.lanes_) |*x| if (x.*) |*l| l.rows.deinit(b.gpa); + for (b.slot[0..b.held]) |*pair| for (pair) |*x| x.free(); + b.meta.free(); + b.logits16.free(); + b.tokens.free(); + b.* = undefined; + } + + pub fn backend(b: *Backend) be.Backend { + return .{ .ptr = b, .vtable = &vtable }; + } + + pub fn facts(_: *const Backend) lanes.Model { + return .{ .exact_width = window_rows, .gpu_tokens = false, .mtp = false, .speculate = false, .hidden_rows = true, .batch_rows = prompt_rows, .max_streams = 1, .streams_exact = true }; + } + + pub fn admits(b: *const Backend, prompt: usize, max_new: usize) bool { + return b.freeSlot() != null and prompt <= b.m.context and max_new <= b.m.context - prompt; + } + + fn freeSlot(b: *const Backend) ?usize { + for (b.streams[0..@min(b.m.n_slots, b.held)], 0..) |x, i| if (x == null) return i; + return null; + } + + fn slotOf(b: *const Backend, s: *const lanes.Stream) ?usize { + for (b.streams, 0..) |x, i| if (x == s) return i; + return null; + } + + /// The device buffer holding `s`'s last prompt logits. + pub fn lastOf(b: *const Backend, s: *const lanes.Stream) !u64 { + const i = b.slotOf(s) orelse return error.UnknownStream; + return b.lanes_[i].?.last; + } + + fn self(ptr: *anyopaque) *Backend { + return @ptrCast(@alignCast(ptr)); + } + + fn upload(b: *Backend, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(b.d, dst, bytes, b.s); + } + + /// `s`'s lane, its model slot selected for the calls that follow. + fn laneOf(b: *Backend, s: *const lanes.Stream) !*Lane { + const i = b.slotOf(s) orelse return error.UnknownStream; + if (i >= b.m.n_slots) return error.UnknownStream; + b.m.slot = i; + return if (b.lanes_[i]) |*l| l else error.UnknownStream; + } + + fn resumeSaved(b: *Backend, s: *lanes.Stream) usize { + const saved = s.reuse.saved orelse return 0; + const k: *const Model.Saved = @ptrCast(@alignCast(saved)); + if (k.at != s.reuse.at or k.at == 0 or k.at >= s.prompt().len) { + s.reuse_failed = true; + return 0; + } + b.m.restore(b.s, k) catch { + s.reuse_failed = true; + return 0; + }; + s.cached = k.at; + return k.at; + } + + fn opening(b: *Backend, s: *lanes.Stream) !*Lane { + const prompt = s.prompt(); + if (prompt.len == 0) return error.EmptyPrompt; + if (prompt.len > b.m.context or s.max_new > b.m.context - prompt.len) return error.PastContext; + if (b.slotOf(s) == null) { + const i = b.freeSlot() orelse return error.NoFreeSlot; + b.lanes_[i] = .{ .last = b.slot[i][0].ptr, .rule = b.slot[i][1].ptr }; + b.streams[i] = s; + } + const l = try b.laneOf(s); + l.sampled = false; + if (cuda.sample.ruleFor(s.sampling)) |r| { + try b.upload(l.rule, std.mem.asBytes(&r)); + l.sampled = true; + } + l.len = 0; + try b.m.reset(b.s); + const at = b.resumeSaved(s); + l.len = at; + l.fill = at; + s.fill_at.store(@intCast(at), .monotonic); + return l; + } + + fn chunk(b: *Backend, s: *lanes.Stream, l: *Lane) !bool { + const prompt = s.prompt(); + const at = l.fill.?; + if (s.isCancelled()) return error.Cancelled; + var end = @min(prompt.len, (at / prompt_rows + 1) * prompt_rows); + for (s.reuse.marks) |mark| { + if (mark > at and mark < end) end = mark; + } + const done = end == prompt.len; + try b.m.forward(b.k, b.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); + if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last, b.m.s.logits, b.m.w.c.text.unpadded_vocab * 4, b.s.handle), "cuMemcpyDtoDAsync"); + l.len = end; + l.fill = if (done) null else end; + s.fill_at.store(@intCast(end), .monotonic); + if (s.reuse.hook) |hook| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) + hook.at(hook.ptr, s, @intCast(end)); + return done; + } + + fn handle(b: *Backend) usize { + const h = b.next; + b.next += 1; + return @intCast(h % token_ring); + } + + fn drawRows(b: *Backend, l: *const Lane, logits: u64, rows: usize, position0: u64, at: usize) !void { + const v = b.m.w.c.text.unpadded_vocab; + if (!l.sampled) return ops.top1(&b.k.glue, b.s, logits, rows, v, v, 0, b.m.s.t + at * 4, b.tokens.ptr + at * 4); + try ops.tobf(&b.k.glue, b.s, logits, rows, v, v, b.logits16.ptr, v, 0, v); + const metadata = [4]i32{ @intCast(position0 - 1), 0, 0, 0 }; + try b.upload(b.meta.ptr, std.mem.asBytes(&metadata)); + try b.k.draws.draw(b.s, b.logits16.ptr, v, l.rule, b.meta.ptr, 0, b.tokens.ptr + at * 4, rows, null, null); + } + + fn read(ptr: *anyopaque, h: u64) anyerror!u32 { + const b = self(ptr); + if (h >= b.next or b.next - h > token_ring) return error.NoSuchToken; + var out: [1]u32 = undefined; + try b.s.synchronize(); + try b.tokens.download(@intCast((h % token_ring) * 4), std.mem.sliceAsBytes(&out)); + return out[0]; + } + + const vtable: be.Backend.VTable = .{ + .prefill = prefill, + .prefill_step = prefillStep, + .first = first, + .first_masked = firstMasked, + .queue = queue, + .read = read, + .verify = verify, + .keep = keep, + .draft = draft, + .release = release, + .reports_fill = true, + }; + + fn prefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + const b = self(ptr); + const l = try b.opening(s); + errdefer release(ptr, s); + while (!try b.chunk(s, l)) {} + } + + fn prefillStep(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { + const b = self(ptr); + const going = if (b.slotOf(s)) |i| b.lanes_[i].?.fill != null else false; + const l = if (going) try b.laneOf(s) else try b.opening(s); + errdefer release(ptr, s); + return b.chunk(s, l); + } + + fn first(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + const b = self(ptr); + const l = try b.laneOf(s); + if (position != l.len or l.fill != null) return error.PositionMismatch; + const h = b.next; + try b.drawRows(l, l.last, 1, position, b.handle()); + return h; + } + + fn firstMasked(_: *anyopaque, _: *lanes.Stream, _: u64, _: []const u32) anyerror!u64 { + return error.StructuresUnsupported; + } + + fn feed(b: *Backend, value: be.Feed) !u32 { + return switch (value) { + .value => |v| v, + .handle => |h| read(b, h), + }; + } + + fn queue(ptr: *anyopaque, s: *lanes.Stream, value: be.Feed, position: u64) anyerror!u64 { + const b = self(ptr); + const l = try b.laneOf(s); + const token = try b.feed(value); + if (position != l.len + 1) return error.PositionMismatch; + try b.m.forward(b.k, b.s, &.{token}, l.len, 0, 1, false); + l.len += 1; + const h = b.next; + try b.drawRows(l, b.m.s.logits, 1, position, b.handle()); + return h; + } + + fn verify(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const b = self(ptr); + if (windows.len != 1 or out.len != 1) return error.OneStreamOnly; + const w = windows[0]; + if (w.held != 0) return error.NoHeldDrafts; + if (w.parents != null) return error.ChainsOnly; + if (w.masks.len != 0) return error.StructuresUnsupported; + const l = try b.laneOf(w.stream); + const n = w.rows(); + if (n == 0 or n > window_rows) return error.WindowTooWide; + l.base = l.len; + l.rows.clearRetainingCapacity(); + try l.rows.append(b.gpa, w.pending); + try l.rows.appendSlice(b.gpa, w.tokens); + for (w.positions, 0..) |position, i| if (position != l.base + i + 1) return error.PositionMismatch; + try b.m.forward(b.k, b.s, l.rows.items, l.base, 0, n, true); + try b.drawRows(l, b.m.s.logits, n, w.positions[0], token_ring); + var got: [window_rows]u32 = undefined; + try b.s.synchronize(); + try b.tokens.download(token_ring * 4, std.mem.sliceAsBytes(got[0..n])); + @memcpy(out[0].sampled[0..n], got[0..n]); + @memcpy(out[0].drafts[0 .. n - 1], l.rows.items[1..n]); + l.len = l.base + n; + } + + fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const b = self(ptr); + if (windows.len != 1 or paths.len != 1) return error.OneStreamOnly; + const l = try b.laneOf(windows[0].stream); + const path = paths[0]; + if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; + for (path, 0..) |row, i| if (row != i) return error.ChainsOnly; + try b.m.rewind(b.k, b.s, path.len); + l.len = l.base + path.len; + } + + fn draft(_: *anyopaque, requests: []const be.DraftRequest) anyerror!void { + for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; + } + + pub fn saveState(b: *Backend, owner: ?*anyopaque, at: u32) !*Model.Saved { + const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = try b.laneOf(s); + if ((l.fill orelse l.len) != at) return error.NotAtMark; + return b.m.save(b.s, at); + } + + pub fn restoreState(b: *Backend, owner: ?*anyopaque, saved: *const Model.Saved) !void { + const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const l = try b.laneOf(s); + try b.m.restore(b.s, saved); + l.len = saved.at; + } + + pub fn dropState(b: *Backend, saved: *Model.Saved) void { + b.m.drop(b.s, saved); + } + + fn release(ptr: *anyopaque, s: *lanes.Stream) void { + const b = self(ptr); + const i = b.slotOf(s) orelse return; + if (b.lanes_[i]) |*l| l.rows.deinit(b.gpa); + b.lanes_[i] = null; + b.streams[i] = null; + } +}; diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig new file mode 100644 index 00000000000..262f6001436 --- /dev/null +++ b/zig/src/families/inkling2/loop_engine.zig @@ -0,0 +1,582 @@ +//! One-rank, text-only Inkling 2 Mini: the complete 48-visit CUDA forward. +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const loop = @import("loop.zig"); +const weights_ = @import("loop_weights.zig"); +const ops = @import("ops.zig"); +const attention = @import("kernels.zig"); +const modelopt = @import("modelopt.zig"); +const loop_math = @import("loop_math_cuda.zig"); +const kept_state = @import("kept_state.zig"); + +pub const prompt_rows: usize = 2048; +pub const window_rows: usize = 16; + +pub const Kernels = struct { + glue: ops.Kernels, + attn: attention.Kernels, + moe: modelopt.Kernels, + loop: loop_math.Kernels, + sample_mod: cuda.Module, + draws: cuda.sample.Draws, + + pub fn load(ctx: *const cuda.Context) !Kernels { + const d = ctx.d; + var glue = try ops.Kernels.load(d); + errdefer glue.unload(); + var attn = try attention.Kernels.load(d); + errdefer attn.unload(); + const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); + var moe = try modelopt.Kernels.load(d, sms); + errdefer moe.unload(); + var lm = try loop_math.Kernels.load(d); + errdefer lm.unload(); + var sample_mod = try cuda.Module.load(d, cuda.kernels.sample); + errdefer sample_mod.unload(); + return .{ + .glue = glue, + .attn = attn, + .moe = moe, + .loop = lm, + .sample_mod = sample_mod, + .draws = try cuda.sample.Draws.resolve(sample_mod), + }; + } + + pub fn deinit(k: *Kernels) void { + k.sample_mod.unload(); + k.loop.unload(); + k.moe.unload(); + k.attn.unload(); + k.glue.unload(); + k.* = undefined; + } +}; + +const Scratch = struct { + ids: u64, + pos: u64, + seg_of: u64, + segs: u64, + tiles: u64, + blocks: [ops.max_blocks]u64 = @splat(0), + partial_a: u64, + partial_b: u64, + prelude: u64, + bank0: u64, + bank1: u64, + raw: u64, // three FP32 AR/gate rows per token + messages: u64, // four FP32 message rows per token + normalized: u64, // three BF16 rows per token + t: u64, + q_raw: u64, + rel_raw: u64, + sink: u64, + gate: u64, + k_raw: u64, + v_raw: u64, + k_conv: u64, + v_conv: u64, + k_dynamic: u64, + v_dynamic: u64, + q_prepared: u64, + rel_prepared: u64, + rel_table: u64, + part_o: u64, + part_ml: u64, + attn_heads: u64, + attn_out: u64, + route_scores: u64, + route_pick: u64, + route_weights: u64, + moe_out: u64, + moe_scratch: u64, + hidden: u64, + logits: u64, + backup: u64, + hist: u64, +}; + +/// A stream's state (every visit's K/V rows and conv states, its rewind sites); at most `max_slots`, one in use. +const Slot = struct { cache: cuda.DeviceBuffer, sites: cuda.DeviceBuffer }; +pub const max_slots = 16; + +pub const Model = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + w: *const weights_.Weights, + context: usize, + layout: loop.CacheLayout, + slots: [max_slots]Slot = undefined, + n_slots: usize = 0, + slot: usize = 0, // the slot forwards, snapshots and rewinds use; forwards share the scratch + recorded: ?usize = null, // the slot whose window `backup` and `hist` hold + s: Scratch = undefined, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + fn slotBase(m: *const Model) u64 { + return m.slots[m.slot].cache.ptr; + } + + /// Allocates slots until `n` exist, each with zeroed conv states and its own rewind sites. + pub fn addSlots(m: *Model, s: cuda.Stream, n: usize) !void { + if (n > max_slots) return error.TooManySlots; + const keep = m.slot; + defer m.slot = keep; + const kv: usize = @as(usize, m.w.c.text.local.kv) * m.w.c.text.local.dim; + var sites: [config.max_visits * 4]ops.RewindSite = undefined; + while (m.n_slots < n) { + var cache = try cuda.DeviceBuffer.alloc(m.d, m.layout.bytes); + errdefer cache.free(); + var table = try cuda.DeviceBuffer.alloc(m.d, m.w.p.n_visits * 4 * @sizeOf(ops.RewindSite)); + errdefer table.free(); + m.slots[m.n_slots] = .{ .cache = cache, .sites = table }; + m.slot = m.n_slots; + for (0..m.w.p.n_visits) |v| for (0..4) |site| { + const c = if (site < 2) kv else m.w.c.text.hidden; + const hist = m.histOf(@intCast(v), site) - m.s.hist; + sites[v * 4 + site] = .{ .state = m.convOf(@intCast(v), site), .hist = @intCast(hist), .backup = @intCast(m.backupOf(@intCast(v), site)), .c = @intCast(c) }; + }; + try m.upload(s, table.ptr, std.mem.sliceAsBytes(sites[0 .. m.w.p.n_visits * 4])); + try m.reset(s); + try s.synchronize(); + m.n_slots += 1; + } + } + + fn alloc(m: *Model, bytes: usize) !u64 { + var b = try cuda.DeviceBuffer.alloc(m.d, @max(bytes, 256)); + errdefer b.free(); + try m.buffers.append(m.gpa, b); + return b.ptr; + } + + fn upload(m: *const Model, s: cuda.Stream, dst: u64, bytes: []const u8) !void { + try cuda.copy_source.enqueue(m.d, dst, bytes, s); + } + + fn copy(m: *const Model, s: cuda.Stream, dst: u64, src: u64, bytes: usize) !void { + try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, s.handle), "cuMemcpyDtoDAsync"); + } + + fn zeros(m: *const Model, s: cuda.Stream, ptr: u64, bytes: usize) !void { + try m.d.check(m.d.api.cuMemsetD8Async(ptr, 0, bytes, s.handle), "cuMemsetD8Async"); + } + + fn layerGeometry(m: *const Model, layer: u32) attention.Layer { + return if (config.isGlobal(layer)) + attention.Layer.global(@intCast(m.context)) + else + attention.Layer.sliding(m.w.c.text.window, @intCast(@min(prompt_rows, m.context))); + } + + fn cacheOf(m: *const Model, visit: u32) attention.Cache { + const slot = m.layout.at(visit); + const base = m.slotBase() + slot.kv_offset; + return .{ .k = base, .v = base + slot.kv_bytes / 2 }; + } + + fn convOf(m: *const Model, visit: u32, site: usize) u64 { + const c = m.w.c.text; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const h: usize = c.hidden; + const widths = [4]usize{ kv, kv, h, h }; + var at = m.slotBase() + m.layout.at(visit).conv_offset; + for (0..site) |i| at += 3 * widths[i] * 4; + return at; + } + + fn histOf(m: *const Model, visit: u32, site: usize) u64 { + const c = m.w.c.text; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const h: usize = c.hidden; + const widths = [4]usize{ kv, kv, h, h }; + var at = m.s.hist + visit * window_rows * (2 * kv + 2 * h) * 4; + for (0..site) |i| at += window_rows * widths[i] * 4; + return at; + } + + fn backupOf(m: *const Model, visit: u32, site: usize) usize { + return m.convOf(visit, site) - (m.slotBase() + m.layout.at(0).conv_offset); + } + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, w: *const weights_.Weights, context: usize) !Model { + const layout = try loop.CacheLayout.init(&w.c.text, &w.p, @intCast(context)); + var m: Model = .{ + .gpa = gpa, + .d = d, + .w = w, + .context = context, + .layout = layout, + }; + errdefer m.deinitBuffers(); + const c = w.c.text; + const h: usize = c.hidden; + const q: usize = @as(usize, c.global.q) * c.global.dim; + const kv: usize = @as(usize, c.local.kv) * c.local.dim; + const rows = prompt_rows; + const rel_rows = rows * c.global.q * attention.extent; + const local = attention.Layer.sliding(c.window, @intCast(@min(prompt_rows, context))); + const global = attention.Layer.global(@intCast(context)); + const local_slots = attention.slotsFor(local, context); + const global_slots = attention.slotsFor(global, context); + const part_slots = @max(rows * c.local.q * local_slots, rows * c.global.q * global_slots); + const hist_values = @as(usize, w.p.n_visits) * (2 * kv + 2 * h) * window_rows; + m.s = .{ + .ids = try m.alloc(rows * 4), + .pos = try m.alloc(rows * 4), + .seg_of = try m.alloc(rows * 4), + .segs = try m.alloc(@sizeOf(attention.Seg)), + .tiles = try m.alloc(128 * @sizeOf(attention.Tile)), + .partial_a = try m.alloc(rows * h * 2), + .partial_b = try m.alloc(rows * h * 2), + .prelude = try m.alloc(rows * h * 2), + .bank0 = try m.alloc(rows * h * 2), + .bank1 = try m.alloc(rows * h * 2), + .raw = try m.alloc(3 * rows * h * 4), + .messages = try m.alloc(4 * rows * h * 4), + .normalized = try m.alloc(3 * rows * h * 2), + .t = try m.alloc(rows * h * 4), + .q_raw = try m.alloc(rows * q * 2), + .rel_raw = try m.alloc(rows * c.global.q * c.d_rel * 2), + .sink = try m.alloc(rows * c.global.q * 2), + .gate = try m.alloc(rows * q * 2), + .k_raw = try m.alloc(rows * kv * 2), + .v_raw = try m.alloc(rows * kv * 2), + .k_conv = try m.alloc(rows * kv * 2), + .v_conv = try m.alloc(rows * kv * 2), + .k_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), + .v_dynamic = try m.alloc(rows * c.global.kv * config.conv_taps * 4), + .q_prepared = try m.alloc(rows * q * 2), + .rel_prepared = try m.alloc(rows * c.global.q * c.d_rel * 2), + .rel_table = try m.alloc(rel_rows * 2), + .part_o = try m.alloc(part_slots * attention.head_dim * 4), + .part_ml = try m.alloc(part_slots * 8), + .attn_heads = try m.alloc(rows * q * 2), + .attn_out = try m.alloc(rows * h * 2), + .route_scores = try m.alloc(rows * c.experts * 4), + .route_pick = try m.alloc(rows * c.experts * 4), + .route_weights = try m.alloc(rows * c.experts * 4), + .moe_out = try m.alloc(rows * h * 2), + .moe_scratch = try m.alloc(try modelopt.scratchBytes(rows, c.topk, h, c.expert_inter)), + .hidden = try m.alloc(rows * h * 2), + .logits = try m.alloc(window_rows * c.unpadded_vocab * 4), + .backup = try m.alloc(layout.bytes - layout.at(0).conv_offset), + .hist = try m.alloc(hist_values * 4), + }; + for (0..ops.max_blocks) |i| m.s.blocks[i] = try m.alloc(rows * h * 2); + try m.addSlots(s, 1); + return m; + } + + fn deinitBuffers(m: *Model) void { + for (m.buffers.items) |*b| b.free(); + m.buffers.deinit(m.gpa); + } + + pub fn deinit(m: *Model) void { + m.deinitBuffers(); + for (m.slots[0..m.n_slots]) |*slot| for ([2]*cuda.DeviceBuffer{ &slot.sites, &slot.cache }) |b| b.free(); + m.* = undefined; + } + + pub fn reset(m: *const Model, s: cuda.Stream) !void { + try m.zeros(s, m.slotBase() + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); + } + + pub fn rewind(m: *const Model, k: *const Kernels, s: cuda.Stream, kept: usize) !void { + if (kept > window_rows) return error.WindowTooWide; + if (m.recorded != m.slot) return error.RewindOfAnotherSlot; + try ops.rewind(&k.glue, s, m.slots[m.slot].sites.ptr, m.w.p.n_visits * 4, m.w.c.text.hidden, m.s.backup, m.s.hist, 0, 0, kept); + } + + fn arBlocks(m: *const Model, blocks: []const u64, partial: u64, query: u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) loop_math.ArArgs { + var a: loop_math.ArArgs = .{ + .partial = partial, + .query = query, + .out = out, + .n_blocks = @intCast(blocks.len), + .partial_bf16 = @intFromBool(partial_bf16), + .nq = @intCast(nq), + .rows = @intCast(rows), + .c = @intCast(m.w.c.text.hidden), + .eps = m.w.c.text.eps, + }; + for (blocks, 0..) |b, i| a.blocks[i] = b; + return a; + } + + fn mixArgs(m: *const Model, blocks: []const u64, partial: u64, query: u64, norms: [3]u64, out: u64, nq: usize, partial_bf16: bool, rows: usize) ops.MixArgs { + var a: ops.MixArgs = .{ + .partial = partial, + .query = query, + .out = out, + .n_blocks = @intCast(blocks.len), + .partial_bf16 = @intFromBool(partial_bf16), + .nq = @intCast(nq), + .rows = @intCast(rows), + .c = @intCast(m.w.c.text.hidden), + .eps = m.w.c.text.eps, + }; + for (blocks, 0..) |b, i| a.blocks[i] = b; + a.norm = norms; + return a; + } + + /// One prompt chunk or one decode window. `record` retains every convolution input for exact prefix rollback. + pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, tokens: []const u32, p0: usize, head0: usize, heads: usize, record: bool) !void { + const c = m.w.c.text; + const rows = tokens.len; + const h: usize = c.hidden; + if (rows == 0 or rows > prompt_rows or p0 + rows > m.context or (!record and heads > window_rows) or head0 + heads > rows) + return error.BadLoopRows; + if (record and rows > window_rows) return error.WindowTooWide; + var ids: [prompt_rows]i32 = undefined; + var pos: [prompt_rows]i32 = undefined; + var seg_of: [prompt_rows]i32 = @splat(0); + for (tokens, 0..) |token, i| { + ids[i] = @intCast(token); + pos[i] = @intCast(p0 + i); + } + try m.upload(s, m.s.ids, std.mem.sliceAsBytes(ids[0..rows])); + try m.upload(s, m.s.pos, std.mem.sliceAsBytes(pos[0..rows])); + try m.upload(s, m.s.seg_of, std.mem.sliceAsBytes(seg_of[0..rows])); + const seg: attention.Seg = .{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p0), .off = 0 }; + try m.upload(s, m.s.segs, std.mem.asBytes(&seg)); + m.recorded = if (record) m.slot else null; + if (record) try m.copy(s, m.s.backup, m.slotBase() + m.layout.at(0).conv_offset, m.layout.bytes - m.layout.at(0).conv_offset); + + try ops.embed(&k.glue, s, m.s.ids, rows, m.w.embed, m.w.embed_norm, m.s.partial_a, h, c.eps); + var partial = m.s.partial_a; + var next = m.s.partial_b; + var n_blocks: usize = 0; + const lp = c.loop.?; + + for (m.w.p.visits[0..m.w.p.n_visits]) |visit| { + const layer = m.w.p.at(visit.layer); + const lw = &m.w.layers[visit.layer]; + if (visit.pass >= 2 and visit.layer == lp.core_start) { + try m.copy(s, partial, m.s.prelude, rows * h * 2); + n_blocks = 1; // block zero is the embedding; later passes never inherit completed blocks + } + const messages = visit.hasMessages(); + if (messages) { + const core_j = visit.layer - lp.core_start; + try loop_math.messages(&k.loop, s, m.s.bank0, m.s.bank1, m.w.cross_qm + 2 * core_j * h * 4, m.w.cross_kv + 2 * core_j * h * 4, m.s.messages, rows, 1, h, c.eps); + } + const nq: usize = if (layer.kind == .global) 3 else 1; + const query = m.w.attn_queries[visit.layer]; + const blocks = m.s.blocks[0..n_blocks]; + const raw_stride = rows * h * 4; + const norm_stride = rows * h * 2; + if (messages) { + if (nq == 3) { + try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw, 3, true, rows)); + } else { + // A sliding layer stores one query; each gated role gets its own AR result from that query. + for (0..3) |role| try loop_math.ar(&k.loop, s, m.arBlocks(blocks, partial, query, m.s.raw + role * raw_stride, 1, true, rows)); + } + for (0..3) |role| { + const ctl = lw.controllers[role]; + try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw + role * raw_stride, rows, h, c.eps); + const norms = [3]u64{ lw.attn.norms[role], lw.attn.norms[role], lw.attn.norms[role] }; + try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw + role * raw_stride, 0, norms, m.s.normalized + role * norm_stride, 1, false, rows)); + } + } else { + try ops.mix(&k.glue, s, m.mixArgs(blocks, partial, query, lw.attn.norms, m.s.normalized, nq, true, rows)); + } + const u_q = m.s.normalized; + const u_k = if (layer.kind == .global or messages) m.s.normalized + norm_stride else u_q; + const u_v = if (layer.kind == .global or messages) m.s.normalized + 2 * norm_stride else u_q; + const q_width: usize = @as(usize, layer.heads.q) * layer.heads.dim; + const kv_width: usize = @as(usize, layer.heads.kv) * layer.heads.dim; + try loop_math.projectQkv(&k.loop, s, u_q, u_k, u_v, lw.attn.wq, lw.attn.wk, lw.attn.wv, m.s.q_raw, m.s.k_raw, m.s.v_raw, rows, h, q_width, kv_width); + try ops.rowdot(&k.glue, s, u_q, lw.attn.wr, m.s.rel_raw, rows, layer.heads.q * c.d_rel, h, true, false); + try ops.rowdot(&k.glue, s, u_q, lw.attn.gate, m.s.gate, rows, q_width, h, true, false); + try ops.rowdot(&k.glue, s, u_q, lw.attn.sink, m.s.sink, rows, layer.heads.q, h, true, false); + + const geometry = m.layerGeometry(visit.layer); + const cache = m.cacheOf(visit.cache_slot); + const dynamic = layer.kind == .global; + for (0..2) |kind| { + const input = if (kind == 0) u_k else u_v; + const dyn_out = if (kind == 0) m.s.k_dynamic else m.s.v_dynamic; + if (dynamic) { + try ops.rowdot(&k.glue, s, input, if (kind == 0) lw.attn.k_dynamic else lw.attn.v_dynamic, dyn_out, rows, layer.heads.kv * config.conv_taps, h, false, false); + try loop_math.roundBf16(&k.loop, s, dyn_out, dyn_out, rows * layer.heads.kv * config.conv_taps); + } + try ops.conv(&k.glue, s, .{ + .x = if (kind == 0) m.s.k_raw else m.s.v_raw, + .state = m.convOf(visit.cache_slot, kind), + .w = if (kind == 0) lw.attn.k_conv else lw.attn.v_conv, + .dyn = if (dynamic) dyn_out else 0, + .out = if (kind == 0) m.s.k_conv else m.s.v_conv, + .hist = if (record) m.histOf(visit.cache_slot, kind) else 0, + .x_bf16 = 1, + .heads = @intCast(layer.heads.kv), + .c = @intCast(kv_width), + .rows = @intCast(rows), + .mode = 0, + }, 1); + } + var tiles: [128]attention.Tile = undefined; + const n_tiles = try attention.tiles(&.{seg}, layer.heads.q / layer.heads.kv, &tiles); + try m.upload(s, m.s.tiles, std.mem.sliceAsBytes(tiles[0..n_tiles])); + const stride = attention.slotsFor(geometry, m.context); + const part_capacity = prompt_rows * layer.heads.q * stride; + const r: attention.Rows = .{ + .rows = @intCast(rows), + .heads = layer.heads.q, + .kv_heads = layer.heads.kv, + .pos = m.s.pos, + .seg_of = m.s.seg_of, + .segs = m.s.segs, + .tiles = m.s.tiles, + .n_tiles = @intCast(n_tiles), + .last_pos = @intCast(p0 + rows - 1), + }; + const prep: attention.Prep = .{ .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor = @floatFromInt(c.log_floor), .alpha = c.log_alpha, .eps = c.eps }; + try attention.prep(&k.attn, s, r, geometry, prep, .{ m.s.q_raw, m.s.k_conv, m.s.v_conv, m.s.rel_raw }, .{ lw.attn.q_scale, lw.attn.rel_scale }, m.s.q_prepared, m.s.rel_prepared, cache); + try attention.relTable(&k.attn, s, r, m.s.rel_prepared, lw.attn.rel_proj, m.s.rel_table); + try attention.attend(&k.attn, s, r, geometry, stride, part_capacity, m.s.q_prepared, cache, m.s.rel_table, m.s.part_o, m.s.part_ml, m.s.sink, m.s.gate, m.s.attn_heads); + try ops.rowdot(&k.glue, s, m.s.attn_heads, lw.attn.wo, m.s.attn_out, rows, h, q_width, true, false); + + if (layer.boundary) { + try m.copy(s, m.s.blocks[n_blocks], partial, rows * h * 2); + n_blocks += 1; + } + try ops.conv(&k.glue, s, .{ + .x = m.s.attn_out, + .state = m.convOf(visit.cache_slot, 2), + .w = lw.attn_conv, + .base = if (layer.boundary) 0 else partial, + .resid = m.s.t, + .hist = if (record) m.histOf(visit.cache_slot, 2) else 0, + .x_bf16 = 1, + .c = @intCast(h), + .rows = @intCast(rows), + .mode = 1, + }, 1); + + const mlp_query = m.w.mlp_queries[visit.layer]; + const mlp_blocks = m.s.blocks[0..n_blocks]; + if (messages) { + try loop_math.ar(&k.loop, s, m.arBlocks(mlp_blocks, m.s.t, mlp_query, m.s.raw, 1, false, rows)); + const ctl = lw.controllers[3]; + try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw, rows, h, c.eps); + try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw, 0, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); + } else { + try ops.mix(&k.glue, s, m.mixArgs(mlp_blocks, m.s.t, mlp_query, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); + } + try ops.rowdot(&k.glue, s, m.s.normalized, lw.router, m.s.route_scores, rows, c.experts, h, false, true); + try ops.topk(&k.glue, s, m.s.route_scores, lw.router_bias, m.s.route_pick, m.s.route_weights, rows, c.experts, c.topk, c.route_scale); + try modelopt.run(&k.moe, s, lw.experts, .{ .gate = c.gate_cap, .up = c.up_cap }, m.s.normalized, h, m.s.route_pick, m.s.route_weights, rows, c.topk, m.s.moe_out, m.s.moe_scratch); + try ops.conv(&k.glue, s, .{ + .x = m.s.moe_out, + .state = m.convOf(visit.cache_slot, 3), + .w = lw.mlp_conv, + .resid = m.s.t, + .out = next, + .hist = if (record) m.histOf(visit.cache_slot, 3) else 0, + .x_bf16 = 1, + .c = @intCast(h), + .rows = @intCast(rows), + .mode = 2, + }, 1); + std.mem.swap(u64, &partial, &next); + + if (visit.layer + 1 == lp.core_start) try m.copy(s, m.s.prelude, partial, rows * h * 2); + if (visit.pass > 0 and visit.pass < lp.passes and visit.layer + 1 == lp.core_end) { + try m.copy(s, m.s.bank0, m.s.blocks[n_blocks - 1], rows * h * 2); + try m.copy(s, m.s.bank1, partial, rows * h * 2); + } + } + + if (heads == 0) return; + try ops.mix(&k.glue, s, m.mixArgs(m.s.blocks[0..n_blocks], partial, m.w.output_query, .{ m.w.norm, m.w.norm, m.w.norm }, m.s.hidden, 1, true, rows)); + try ops.rowdot(&k.glue, s, m.s.hidden + head0 * h * 2, m.w.unembed, m.s.logits, heads, c.unpadded_vocab, h, false, false); + try loop_math.roundBf16(&k.loop, s, m.s.logits, m.s.logits, heads * c.unpadded_vocab); + try ops.softcap(&k.glue, s, m.s.logits, heads * c.unpadded_vocab, c.logit_cap); + } + + pub const Saved = struct { + at: u32, + visits: u32, + passes: u32, + hidden: u32, + buf: cuda.DeviceBuffer, + }; + + /// Every visit's caches as the shared kept-state walk sees them: head-major `[kv head][ring][dim]` (attention.cu). + pub fn keptVisits(m: *const Model, out: *[config.max_visits]kept_state.Visit) []const kept_state.Visit { + for (out[0..m.w.p.n_visits], m.w.p.visits[0..m.w.p.n_visits]) |*kv, visit| { + const layer = m.w.p.at(visit.layer); + const cache = m.cacheOf(visit.cache_slot); + const ring = m.layerGeometry(visit.layer).ring; + kv.* = .{ .k = cache.k, .v = cache.v, .heads = layer.heads.kv, .ring = ring, .row = @as(u64, layer.heads.dim) * 2, .global = layer.kind == .global }; + } + return out[0..m.w.p.n_visits]; + } + + /// Compact bytes for all valid K/V rows and every convolution state of all 48 visits. + pub fn snapshotBytes(m: *const Model, at: usize) u64 { + var visits: [config.max_visits]kept_state.Visit = undefined; + return m.layout.bytes - m.layout.at(0).conv_offset + kept_state.bytes(m.keptVisits(&visits), m.w.c.text.window, at); + } + + fn copyState(m: *const Model, s: cuda.Stream, saved: *const Saved, out: bool) !void { + var visits: [config.max_visits]kept_state.Visit = undefined; + var walk = kept_state.Walk.init(m.keptVisits(&visits), m.w.c.text.window, saved.at); + while (walk.next()) |p| { + const kept = saved.buf.ptr + p.offset; + try m.copy(s, if (out) kept else p.cache, if (out) p.cache else kept, p.len); + } + const conv = m.slotBase() + m.layout.at(0).conv_offset; + const bytes = m.layout.bytes - m.layout.at(0).conv_offset; + const off = saved.buf.ptr + walk.offset; + try m.copy(s, if (out) off else conv, if (out) conv else off, bytes); + } + + pub fn save(m: *const Model, s: cuda.Stream, at: u32) !*Saved { + if (at == 0 or at > m.context) return error.NotAtMark; + const gpa = m.gpa; + const saved = try gpa.create(Saved); + errdefer gpa.destroy(saved); + const lp = m.w.c.text.loop.?; + saved.* = .{ .at = at, .visits = m.w.p.n_visits, .passes = lp.passes, .hidden = m.w.c.text.hidden, .buf = try cuda.DeviceBuffer.alloc(m.d, @intCast(@max(snapshotBytes(m, at), 256))) }; + errdefer saved.buf.free(); + try m.copyState(s, saved, true); + return saved; + } + + pub fn restore(m: *const Model, s: cuda.Stream, saved: *const Saved) !void { + const lp = m.w.c.text.loop.?; + if (saved.visits != m.w.p.n_visits or saved.passes != lp.passes or saved.hidden != m.w.c.text.hidden) + return error.StateOfAnotherModel; + if (saved.at == 0 or saved.at > m.context or saved.buf.len < snapshotBytes(m, saved.at)) return error.BadLoopSnapshot; + var visits: [config.max_visits]kept_state.Visit = undefined; + if (!kept_state.fits(m.keptVisits(&visits), m.w.c.text.window, saved.at)) return error.BadLoopSnapshot; + try m.copyState(s, saved, false); + } + + pub fn drop(m: *const Model, s: cuda.Stream, saved: *Saved) void { + s.synchronize() catch {}; + saved.buf.free(); + m.gpa.destroy(saved); + } +}; + +test "pass snapshots and rollback layout cover every visit" { + const config_test = @import("config_test.zig"); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = try config.parse(arena.allocator(), config_test.mini, &why); + var precisions: [24]@import("plan.zig").Precision = @splat(.nvfp4); + const p = try @import("plan.zig").build(&c.text, &precisions); + const layout = try loop.CacheLayout.init(&c.text, &p, 4096); + try std.testing.expectEqual(@as(u32, 48), layout.n); + try std.testing.expect(layout.at(17).kv_offset != layout.at(29).kv_offset); + try std.testing.expectEqual(@as(u64, layout.at(46).conv_offset + layout.at(46).conv_bytes), layout.at(47).conv_offset); +} diff --git a/zig/src/families/inkling2/loop_math_cuda.zig b/zig/src/families/inkling2/loop_math_cuda.zig new file mode 100644 index 00000000000..9a0d4cc4b63 --- /dev/null +++ b/zig/src/families/inkling2/loop_math_cuda.zig @@ -0,0 +1,158 @@ +//! Inkling 2 Mini loop math (inkling2/loop_math.cu): raw AR, two-bank messages, rank-64 gates and split QKV inputs. +const std = @import("std"); +const cuda = @import("cuda"); + +pub const rank = 64; +pub const max_blocks = 8; +pub const max_queries = 3; + +/// loop_math.cu's ArArgs, field for field. `out[q][row][c]` is FP32 AR output before any controller or RMSNorm. +pub const ArArgs = extern struct { + blocks: [max_blocks]u64 = @splat(0), // BF16 [rows][c], each a completed block state + partial: u64, // BF16 when partial_bf16 != 0, otherwise FP32; always the final AR source + query: u64, // FP32 [nq][c] + out: u64, // FP32 [nq][rows][c] + n_blocks: i32, + partial_bf16: i32, + nq: i32, + rows: i32, + c: i32, + eps: f32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + ar_fn: cuda.Function, + messages_fn: cuda.Function, + gate_fn: cuda.Function, + project_qkv_fn: cuda.Function, + round_bf16_fn: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_loop_math); + errdefer mod.unload(); + return .{ + .mod = mod, + .ar_fn = try mod.function("tf_ink2_loop_ar"), + .messages_fn = try mod.function("tf_ink2_loop_messages"), + .gate_fn = try mod.function("tf_ink2_loop_gate"), + .project_qkv_fn = try mod.function("tf_ink2_loop_project_qkv"), + .round_bf16_fn = try mod.function("tf_ink2_loop_round_bf16"), + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +fn int(x: anytype) i32 { + return @intCast(x); +} + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); +} + +/// Unnormalized block attention residual. No scratch; nq <= 3 and at most 8 completed blocks plus `partial`. +pub fn ar(k: *const Kernels, s: cuda.Stream, a: ArArgs) !void { + if (a.n_blocks < 0 or a.n_blocks > max_blocks or a.nq <= 0 or a.nq > max_queries or a.rows <= 0 or a.c <= 0) + return error.Inkling2LoopArShape; + var args: cuda.Args = .{}; + args.add(a); + try go(k.ar_fn, s, .{ .x = @intCast(a.rows) }, 512, &args); +} + +/// Messages: BF16 banks, even/odd qm/kv FP32 queries/output; row-local q/k/v/mlp, no scratch/position/mask/cache. +pub fn messages( + k: *const Kernels, + s: cuda.Stream, + bank0_bf16: u64, + bank1_bf16: u64, + queries_qm_f32: u64, + queries_kv_f32: u64, + out_f32: u64, + rows: usize, + core_layers: usize, + c: usize, + eps: f32, +) !void { + if (rows == 0 or core_layers == 0 or c == 0) return error.Inkling2LoopMessageShape; + var a: cuda.Args = .{}; + for ([_]u64{ bank0_bf16, bank1_bf16, queries_qm_f32, queries_kv_f32, out_f32 }) |v| a.add(v); + for ([_]i32{ int(rows), int(core_layers), int(c) }) |v| a.add(v); + a.add(eps); + try go(k.messages_fn, s, .{ .x = @intCast(rows), .y = 4 }, 256, &a); +} + +/// Controller: BF16 D[64][2c]/F/G[c][64] and down I/O; FP32 F/G dots/tanh/four-step output; pre-offset msg, no scratch. +pub fn gate( + k: *const Kernels, + s: cuda.Stream, + state_f32: u64, + message_f32: u64, + down_bf16: u64, + forget_bf16: u64, + gain_bf16: u64, + out_f32: u64, + rows: usize, + c: usize, + eps: f32, +) !void { + if (rows == 0 or c == 0) return error.Inkling2LoopGateShape; + var a: cuda.Args = .{}; + for ([_]u64{ state_f32, message_f32, down_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v); + for ([_]i32{ int(rows), int(c) }) |v| a.add(v); + a.add(eps); + try go(k.gate_fn, s, .{ .x = @intCast(rows) }, 256, &a); +} + +/// Mini QKV: normalized BF16 uq/uk/uv, query-side u_q; per-visit K/V conv/cache, then wo/post-conv; no history. +pub fn projectQkv( + k: *const Kernels, + s: cuda.Stream, + u_q: u64, + u_k: u64, + u_v: u64, + wq: u64, + wk: u64, + wv: u64, + raw_q: u64, + raw_k: u64, + raw_v: u64, + rows: usize, + c: usize, + q_width: usize, + kv_width: usize, +) !void { + if (rows == 0 or c == 0 or q_width == 0 or kv_width == 0) return error.Inkling2LoopQkvShape; + var a: cuda.Args = .{}; + for ([_]u64{ u_q, u_k, u_v, wq, wk, wv, raw_q, raw_k, raw_v }) |v| a.add(v); + for ([_]i32{ int(rows), int(c), int(q_width), int(kv_width) }) |v| a.add(v); + try go(k.project_qkv_fn, s, .{ .x = @intCast((rows + 15) / 16), .y = @intCast((@max(q_width, kv_width) + 15) / 16), .z = 3 }, 256, &a); +} + +/// BF16-round FP32 then widen, preserving section 6.3 unlike rowdot(false); in/out may alias, no scratch, n=0 no-op. +pub fn roundBf16(k: *const Kernels, s: cuda.Stream, in_f32: u64, out_f32: u64, n: usize) !void { + if (n == 0) return; + var a: cuda.Args = .{}; + for ([_]u64{ in_f32, out_f32 }) |v| a.add(v); + a.add(@as(i64, @intCast(n))); + try go(k.round_bf16_fn, s, .{ .x = @intCast((n + 255) / 256) }, 256, &a); +} + +test "loop math argument ABI and message role offsets" { + try std.testing.expectEqual(@as(usize, 112), @sizeOf(ArArgs)); + const c = 2304; + const j = 7; + const row = 3; + const core_layers = 12; + const base = ((row * core_layers + j) * 4) * c; + for ([_]usize{ 0, 1, 2, 3 }, 0..) |role, i| { + const at = base + role * c; + const queries = @as(usize, 2 * j + @as(usize, @intFromBool(i == 2 or i == 3))) * c; + try std.testing.expect(at >= base and queries < 24 * c); + } +} diff --git a/zig/src/families/inkling2/loop_model.zig b/zig/src/families/inkling2/loop_model.zig new file mode 100644 index 00000000000..c56b1ce7a2e --- /dev/null +++ b/zig/src/families/inkling2/loop_model.zig @@ -0,0 +1,464 @@ +//! f64 Mini: f32 sums/combine ascend (A12), bf16 experts/acts (A1/A2), f32 F/G (A7), postdot scale (A14); casts round. +const std = @import("std"); +const bf = @import("bf16_round"); + +pub const hidden_size = 2304; +pub const gate_rank = 64; +pub const physical_layers = 24; +pub const core_start = 6; +pub const core_end = 18; +pub const core_layers = core_end - core_start; +pub const num_passes = 3; +pub const visit_count = 48; +pub const message_roles = 4; +pub const rms_eps = 1e-6; + +pub const ShapeError = error{BadShape}; +pub const VisitError = error{BadVisit}; +pub const DriverError = error{ BadShape, BadVisit, BadDriverState, BadSequence }; + +fn narrow32(v: f64) f32 { + return @floatCast(v); +} + +fn widen32(v: f32) f64 { + return @floatCast(v); +} + +/// One round to nearest-even bf16; the returned f64 is exactly that bf16 value. +pub fn bf16(v: f64) f64 { + return bf.bf16(v); +} + +/// rho(x), with an f32 ordered sum of squares and the specified f32 mean/rsqrt/multiply. +pub fn rms(x: []const f64, eps: f64, out: []f64) ShapeError!void { + if (x.len == 0 or out.len != x.len or !std.math.isFinite(eps) or eps < 0) return error.BadShape; + var squares: f32 = 0; + for (x) |v| { + const a = narrow32(v); + squares += a * a; + } + const mean = squares / @as(f32, @floatFromInt(x.len)); + const inverse: f32 = 1 / @sqrt(mean + narrow32(eps)); + for (x, out) |v, *o| o.* = widen32(narrow32(v) * inverse); +} + +/// N_w(x): no bf16 rounding between rho and the weight product, one bf16 rounding at the end. +pub fn weightedRms(x: []const f64, weight: []const f64, eps: f64, out: []f64, scratch: []f64) ShapeError!void { + if (weight.len != x.len or scratch.len != x.len) return error.BadShape; + try rms(x, eps, scratch); + for (scratch, weight, out) |v, w, *o| o.* = bf16(widen32(narrow32(w) * narrow32(v))); +} + +/// binary32(1/sqrt(H)); in particular Mini's value is binary32(1/48), not a double scale. +pub fn residualScale(hidden: usize) ShapeError!f32 { + if (hidden == 0) return error.BadShape; + return narrow32(1 / @sqrt(@as(f64, @floatFromInt(hidden)))); +} + +fn normalizeSources(states: []const f64, partial: []const f64, eps: f64, normalized: []f64) ShapeError!usize { + if (partial.len == 0 or states.len % partial.len != 0) return error.BadShape; + const h = partial.len; + const count = states.len / h + 1; + if (normalized.len != count * h) return error.BadShape; + for (0..count - 1) |i| try rms(states[i * h ..][0..h], eps, normalized[i * h ..][0..h]); + try rms(partial, eps, normalized[(count - 1) * h ..][0..h]); + return count; +} + +fn retrieve(normalized: []const f64, query: []const f64, out: []f64, weights: []f64) ShapeError!void { + if (query.len == 0 or out.len != query.len or normalized.len % query.len != 0) return error.BadShape; + const h = query.len; + const count = normalized.len / h; + if (count == 0 or weights.len != count) return error.BadShape; + const scale = try residualScale(h); + var top: f32 = -std.math.inf(f32); + for (0..count) |i| { + var dot: f32 = 0; + for (query, normalized[i * h ..][0..h]) |q, v| dot += narrow32(q) * narrow32(v); + const logit = dot * scale; + weights[i] = widen32(logit); + top = @max(top, logit); + } + var denominator: f32 = 0; + for (weights) |*w| { + const d = narrow32(w.* - widen32(top)); + const e = @exp(d); + w.* = widen32(e); + denominator += e; + } + @memset(out, 0); + for (0..count) |i| { + const weight = narrow32(weights[i]) / denominator; + for (out, normalized[i * h ..][0..h]) |*o, v| { + const a = narrow32(o.*); + o.* = widen32(a + weight * narrow32(v)); + } + } +} + +/// AR_Q(S,p): states[S][H], queries/out[Q][H] row-major; empty S okay, partial last, normalize before attention. +pub fn attentionResidual(gpa: std.mem.Allocator, states: []const f64, partial: []const f64, queries: []const f64, query_rows: usize, eps: f64, out: []f64) !void { + if (partial.len == 0 or query_rows == 0 or states.len % partial.len != 0) return error.BadShape; + const h = partial.len; + if (queries.len != query_rows * h or out.len != queries.len) return error.BadShape; + const count = states.len / h + 1; + const normalized = try gpa.alloc(f64, count * h); + defer gpa.free(normalized); + const weights = try gpa.alloc(f64, count); + defer gpa.free(weights); + _ = try normalizeSources(states, partial, eps, normalized); + for (0..query_rows) |q| try retrieve(normalized, queries[q * h ..][0..h], out[q * h ..][0..h], weights); +} + +pub const MessageRole = enum(u2) { q = 0, k = 1, v = 2, mlp = 3 }; + +/// The previous pass's B_12 and P_18. No embedding, prelude, or current-pass state is included. +pub const MessageBank = struct { + block: []const f64, + partial: []const f64, +}; + +/// Both checkpoint tensors in their stored row-major layouts: 24 rows by H. +pub const MessageQueries = struct { + q_mlp: []const f64, + kv: []const f64, + + /// Core j uses row 2j for q/k and row 2j+1 for mlp/v, in their respective tensors. + pub fn row(q: MessageQueries, core: usize, role: MessageRole, hidden: usize) ShapeError![]const f64 { + if (core >= core_layers or hidden == 0 or q.q_mlp.len != 2 * core_layers * hidden or q.kv.len != 2 * core_layers * hidden) return error.BadShape; + const odd: usize = @intFromBool(role == .mlp or role == .v); + const row_index = 2 * core + odd; + const source = if (role == .q or role == .mlp) q.q_mlp else q.kv; + return source[row_index * hidden ..][0..hidden]; + } +}; + +fn bankNormalized(gpa: std.mem.Allocator, bank: MessageBank, eps: f64) ![]f64 { + if (bank.block.len == 0 or bank.partial.len != bank.block.len) return error.BadShape; + const normalized = try gpa.alloc(f64, 2 * bank.block.len); + errdefer gpa.free(normalized); + try rms(bank.block, eps, normalized[0..bank.block.len]); + try rms(bank.partial, eps, normalized[bank.block.len..]); + return normalized; +} + +/// One of the 48 cross-pass messages. Its bank values and output are binary32 values held in f64. +pub fn crossPassMessage(gpa: std.mem.Allocator, bank: MessageBank, query: []const f64, eps: f64, out: []f64) !void { + if (query.len != bank.block.len or out.len != query.len) return error.BadShape; + const normalized = try bankNormalized(gpa, bank, eps); + defer gpa.free(normalized); + var weights: [2]f64 = undefined; + try retrieve(normalized, query, out, &weights); +} + +/// All messages in [core layer][q,k,v,mlp][H] order. Queries are shared by passes two and three. +pub fn crossPassMessages(gpa: std.mem.Allocator, bank: MessageBank, queries: MessageQueries, eps: f64, out: []f64) !void { + const h = bank.block.len; + if (h == 0 or bank.partial.len != h or out.len != core_layers * message_roles * h) return error.BadShape; + const normalized = try bankNormalized(gpa, bank, eps); + defer gpa.free(normalized); + var weights: [2]f64 = undefined; + const roles = [_]MessageRole{ .q, .k, .v, .mlp }; + for (0..core_layers) |j| for (roles, 0..) |role, r| { + const query = try queries.row(j, role, h); + const at = (j * message_roles + r) * h; + try retrieve(normalized, query, out[at..][0..h], &weights); + }; +} + +/// Mini's rank-64 controller, represented with smaller ranks too for inexpensive host probes. +pub const GateWeights = struct { + down: []const f64, // [rank][2H], with the h half before the message half + forget: []const f64, // [H][rank] + gain: []const f64, // [H][rank] + rank: usize, +}; + +fn gateDot(row: []const f64, values: []const f64) f32 { + var sum: f32 = 0; + for (row, values) |w, v| sum += narrow32(w) * narrow32(v); + return sum; +} + +/// G(h,m) = (1-f)*h + g*m. The joined norm and bottleneck are bf16; F/G stay f32 (A7). +pub fn messageGate(gpa: std.mem.Allocator, h: []const f64, m: []const f64, w: GateWeights, eps: f64, out: []f64) !void { + const width = h.len; + if (width == 0 or m.len != width or out.len != width or w.rank == 0) return error.BadShape; + if (w.down.len != w.rank * 2 * width or w.forget.len != width * w.rank or w.gain.len != width * w.rank) return error.BadShape; + const joined = try gpa.alloc(f64, 2 * width); + defer gpa.free(joined); + const zeta = try gpa.alloc(f64, w.rank); + defer gpa.free(zeta); + try rms(h, eps, joined[0..width]); + try rms(m, eps, joined[width..]); + for (joined) |*v| v.* = bf16(v.*); + for (0..w.rank) |r| zeta[r] = bf16(widen32(gateDot(w.down[r * 2 * width ..][0 .. 2 * width], joined))); + for (0..width) |i| { + const forget = std.math.tanh(gateDot(w.forget[i * w.rank ..][0..w.rank], zeta)); + const gain = std.math.tanh(gateDot(w.gain[i * w.rank ..][0..w.rank], zeta)); + const keep: f32 = 1 - forget; + const left = keep * narrow32(h[i]); + const right = gain * narrow32(m[i]); + out[i] = widen32(left + right); + } +} + +pub const AttentionKind = enum { sliding, global }; + +/// One row of the fixed 48-visit schedule. cache_slot is visit numbering; reference_slot is HF's. +pub const Visit = struct { + index: u8, + layer: u8, + pass: u8, // zero outside the core, one-based inside it + cache_slot: u8, + reference_slot: u8, + kind: AttentionKind, + boundary: bool, + has_messages: bool, + ar_queries: u8, + attention_sources: u8, + mlp_sources: u8, +}; + +pub fn visit(index: usize) VisitError!Visit { + if (index >= visit_count) return error.BadVisit; + const layer: u8 = if (index < core_start) + @intCast(index) + else if (index < 42) + @intCast(core_start + (index - core_start) % core_layers) + else + @intCast(index - 24); + const pass: u8 = if (index >= 18 and index < 42) @intCast(1 + (index - core_start) / core_layers) else if (index >= core_start and index < 18) 1 else 0; + const reference: u8 = if (pass >= 2) @intCast(24 + (@as(usize, pass) - 2) * core_layers + layer - core_start) else layer; + const global = (@as(usize, layer) + 1) % 6 == 0; + const boundary = layer % 6 == 0; + const blocks: u8 = (layer + 5) / 6; + return .{ + .index = @intCast(index), + .layer = layer, + .pass = pass, + .cache_slot = @intCast(index), + .reference_slot = reference, + .kind = if (global) .global else .sliding, + .boundary = boundary, + .has_messages = pass >= 2, + .ar_queries = if (layer == 0) 0 else if (global) 3 else 1, + .attention_sources = if (layer == 0) 0 else blocks + 1, + .mlp_sources = blocks + 1 + @intFromBool(boundary), + }; +} + +pub const Sources = struct { + blocks: []const f64, // [completed block][H] + partial: []const f64, // p before attention, or unrounded t before the MLP +}; + +/// Residual/block only; caller attention/conv/MoE. Visit: begin->attentionSources->afterAttention->mlpSources->finish. +pub const Driver = struct { + gpa: std.mem.Allocator, + hidden: usize, + storage: []f64, // blocks[4H], prelude snapshot[2H], bank[2H], p[H], t[H] + block_count: usize, + next: usize, + phase: enum { ready, attention, mlp }, + active: Visit, + have_snapshot: bool, + + pub fn init(gpa: std.mem.Allocator, embedding: []const f64) !Driver { + if (embedding.len == 0) return error.BadShape; + const h = embedding.len; + const storage = try gpa.alloc(f64, 10 * h); + @memset(storage, 0); + for (embedding, storage[8 * h .. 9 * h]) |v, *p| p.* = bf16(v); + return .{ .gpa = gpa, .hidden = h, .storage = storage, .block_count = 0, .next = 0, .phase = .ready, .active = undefined, .have_snapshot = false }; + } + + pub fn deinit(d: *Driver) void { + d.gpa.free(d.storage); + d.* = undefined; + } + + fn blocks(d: *Driver) []f64 { + return d.storage[0 .. d.block_count * d.hidden]; + } + + fn partial(d: *Driver) []f64 { + return d.storage[8 * d.hidden .. 9 * d.hidden]; + } + + fn work(d: *Driver) []f64 { + return d.storage[9 * d.hidden .. 10 * d.hidden]; + } + + /// Applies the pass reset before visits 18 and 30, after saving that previous pass's two bank states. + pub fn begin(d: *Driver, index: usize) DriverError!Visit { + if (index >= visit_count) return error.BadVisit; + if (d.phase != .ready or d.next != index) return error.BadSequence; + if (index == core_start) { + if (d.block_count != 1) return error.BadDriverState; + @memcpy(d.storage[4 * d.hidden .. 5 * d.hidden], d.partial()); + @memcpy(d.storage[5 * d.hidden .. 6 * d.hidden], d.blocks()); + d.have_snapshot = true; + } + if (index == 18 or index == 30) { + if (!d.have_snapshot or d.block_count != 3) return error.BadDriverState; + @memcpy(d.storage[6 * d.hidden .. 7 * d.hidden], d.storage[2 * d.hidden .. 3 * d.hidden]); + @memcpy(d.storage[7 * d.hidden .. 8 * d.hidden], d.partial()); + @memcpy(d.partial(), d.storage[4 * d.hidden .. 5 * d.hidden]); + @memcpy(d.storage[0..d.hidden], d.storage[5 * d.hidden .. 6 * d.hidden]); + d.block_count = 1; + } + d.active = visit(index) catch return error.BadVisit; + d.phase = .attention; + return d.active; + } + + pub fn attentionSources(d: *Driver) DriverError!Sources { + if (d.phase != .attention) return error.BadSequence; + return .{ .blocks = d.blocks(), .partial = d.partial() }; + } + + /// Saves p as a completed boundary block, then forms f32 t without rounding it to bf16. + pub fn afterAttention(d: *Driver, attention: []const f64) DriverError!void { + if (d.phase != .attention) return error.BadSequence; + if (attention.len != d.hidden) return error.BadShape; + if (d.active.boundary) { + if (d.block_count == 4) return error.BadDriverState; + @memcpy(d.storage[d.block_count * d.hidden ..][0..d.hidden], d.partial()); + d.block_count += 1; + for (d.work(), attention) |*t, a| t.* = widen32(narrow32(a)); + } else { + for (d.work(), d.partial(), attention) |*t, p, a| t.* = widen32(narrow32(p) + narrow32(a)); + } + d.phase = .mlp; + } + + /// AR's second call sees the extended block list and t, not bf16(t). + pub fn mlpSources(d: *Driver) DriverError!Sources { + if (d.phase != .mlp) return error.BadSequence; + return .{ .blocks = d.blocks(), .partial = d.work() }; + } + + /// p_out = bf16(t + f32(post-MLP-convolution output)); the residual itself is never gated. + pub fn finish(d: *Driver, mlp: []const f64) DriverError!void { + if (d.phase != .mlp) return error.BadSequence; + if (mlp.len != d.hidden) return error.BadShape; + for (d.partial(), d.work(), mlp) |*p, t, o| p.* = bf16(widen32(narrow32(t) + narrow32(o))); + d.phase = .ready; + d.next += 1; + } + + /// Raw B_12 and P_18 of the immediately previous pass; valid until the next pass reset. + pub fn messageBank(d: *Driver) DriverError!MessageBank { + if (d.phase == .ready or !d.active.has_messages) return error.BadDriverState; + return .{ .block = d.storage[6 * d.hidden .. 7 * d.hidden], .partial = d.storage[7 * d.hidden .. 8 * d.hidden] }; + } + + /// The five final AR sources after visit 47: four completed blocks and P_24. + pub fn finalSources(d: *Driver) DriverError!Sources { + if (d.phase != .ready or d.next != visit_count or d.block_count != 4) return error.BadDriverState; + return .{ .blocks = d.blocks(), .partial = d.partial() }; + } +}; + +pub fn e2m1(code: u8) f64 { + const table = [_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const magnitude = table[code & 7]; + return std.math.copysign(magnitude, if (code & 8 != 0) @as(f64, -1) else @as(f64, 1)); +} + +/// OCP E4M3FN, including its subnormals and sole NaN encodings. +pub fn e4m3(code: u8) f64 { + const negative = code & 0x80 != 0; + const exponent: u8 = (code >> 3) & 0xf; + const mantissa: u8 = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f64); + const magnitude = if (exponent == 0) + std.math.ldexp(@as(f64, @floatFromInt(mantissa)), -9) + else + std.math.ldexp(1 + @as(f64, @floatFromInt(mantissa)) / 8, @as(i32, exponent) - 7); + return if (negative) -magnitude else magnitude; +} + +/// A2(a): both source f32 scalars are cast to bf16 before one binary32 division. +pub fn nvfp4OuterFactor(amax: f64, denominator: f64) f64 { + const a = narrow32(bf16(amax)); + const d = narrow32(bf16(denominator)); + return widen32(a / d); +} + +fn nvWeight(code: u8, scale: u8, factor: f32) f64 { + const inner = narrow32(e2m1(code) * e4m3(scale)); // the E2M1*E4M3 product is exact + return bf16(widen32(inner * factor)); +} + +pub fn nvfp4ReferenceWeight(code: u8, scale: u8, amax: f64, denominator: f64) f64 { + return nvWeight(code, scale, narrow32(nvfp4OuterFactor(amax, denominator))); +} + +/// Decode one packed NVFP4 row: low nibble is the even input, one E4M3 scale per 16 inputs. +pub fn nvfp4ReferenceRow(codes: []const u8, scales: []const u8, amax: f64, denominator: f64, out: []f64) ShapeError!void { + if (out.len == 0 or out.len % 16 != 0 or codes.len != out.len / 2 or scales.len != out.len / 16) return error.BadShape; + const factor = narrow32(nvfp4OuterFactor(amax, denominator)); + for (out, 0..) |*v, c| { + const packed_byte = codes[c / 2]; + const code = if (c % 2 == 0) packed_byte & 0xf else packed_byte >> 4; + v.* = nvWeight(code, scales[c / 16], factor); + } +} + +pub fn mxfp8Scale(scale: u8) f64 { + return std.math.ldexp(@as(f64, 1), @as(i32, scale) - 127); +} + +pub fn mxfp8ReferenceWeight(code: u8, scale: u8) f64 { + return bf16(e4m3(code) * mxfp8Scale(scale)); +} + +/// Decode one MXFP8 row using the stored per-row exponent for each group of 32 input columns (A4). +pub fn mxfp8ReferenceRow(codes: []const u8, scales: []const u8, out: []f64) ShapeError!void { + if (out.len == 0 or out.len % 32 != 0 or codes.len != out.len or scales.len != out.len / 32) return error.BadShape; + for (out, codes, 0..) |*v, code, c| v.* = mxfp8ReferenceWeight(code, scales[c / 32]); +} + +/// A bf16 reference GEMM output, with ascending f32 accumulation and no activation quantization. +pub fn expertProjection(weights: []const f64, x: []const f64, rows: usize, out: []f64) ShapeError!void { + if (rows == 0 or x.len == 0 or out.len != rows or weights.len != rows * x.len) return error.BadShape; + for (0..rows) |r| { + var sum: f32 = 0; + for (weights[r * x.len ..][0..x.len], x) |w, v| sum += narrow32(w) * narrow32(v); + out[r] = bf16(widen32(sum)); + } +} + +fn softcap32(x: f32, cap: f32) f32 { + return cap * std.math.tanh(x / cap); +} + +/// bf16(softcap4(g) * sigmoid(g) * softcap25(u)), evaluated left to right in f32. +pub fn expertActivation(gate: f64, up: f64) f64 { + const g = narrow32(gate); + const sigmoid: f32 = 1 / (1 + @exp(-g)); + const act = softcap32(g, 4) * sigmoid * softcap32(narrow32(up), 25); + return bf16(widen32(act)); +} + +/// Combine f32 from zero by ascending id, not route order (A12); expert_outputs [route][H], ids/route_weights [route]. +pub fn combineExperts(expert_count: usize, ids: []const u32, route_weights: []const f64, expert_outputs: []const f64, hidden: usize, out: []f64) ShapeError!void { + if (expert_count == 0 or hidden == 0 or ids.len != route_weights.len or expert_outputs.len != ids.len * hidden or out.len != hidden) return error.BadShape; + @memset(out, 0); + for (0..expert_count) |e| { + var found = false; + for (ids, 0..) |id, r| if (id == e) { + if (found) return error.BadShape; + found = true; + const weight = narrow32(route_weights[r]); + for (out, expert_outputs[r * hidden ..][0..hidden]) |*sum, value| { + const term = weight * narrow32(value); + sum.* = widen32(narrow32(sum.*) + term); + } + } else if (id >= expert_count) return error.BadShape; + } + for (out) |*v| v.* = bf16(v.*); +} diff --git a/zig/src/families/inkling2/loop_model_test.zig b/zig/src/families/inkling2/loop_model_test.zig new file mode 100644 index 00000000000..ee0bcf64dab --- /dev/null +++ b/zig/src/families/inkling2/loop_model_test.zig @@ -0,0 +1,214 @@ +const std = @import("std"); +const model = @import("loop_model.zig"); + +const Driver = model.Driver; +const GateWeights = model.GateWeights; +const MessageBank = model.MessageBank; +const MessageQueries = model.MessageQueries; +const attentionResidual = model.attentionResidual; +const bf16 = model.bf16; +const combineExperts = model.combineExperts; +const crossPassMessage = model.crossPassMessage; +const crossPassMessages = model.crossPassMessages; +const e2m1 = model.e2m1; +const e4m3 = model.e4m3; +const expertActivation = model.expertActivation; +const expertProjection = model.expertProjection; +const hidden_size = model.hidden_size; +const messageGate = model.messageGate; +const mxfp8ReferenceRow = model.mxfp8ReferenceRow; +const mxfp8ReferenceWeight = model.mxfp8ReferenceWeight; +const mxfp8Scale = model.mxfp8Scale; +const nvfp4OuterFactor = model.nvfp4OuterFactor; +const nvfp4ReferenceRow = model.nvfp4ReferenceRow; +const nvfp4ReferenceWeight = model.nvfp4ReferenceWeight; +const residualScale = model.residualScale; +const rms = model.rms; +const visit = model.visit; +const visit_count = model.visit_count; +const weightedRms = model.weightedRms; + +fn widen32(v: f32) f64 { + return @floatCast(v); +} + +fn expectClose(actual: f64, expected: f64, tolerance: f64) !void { + try std.testing.expectApproxEqAbs(expected, actual, tolerance); +} + +test "norm scale and weighted RMS's sole final bf16 rounding" { + const x = [_]f64{ 3, 4, 0, 0 }; + var out: [4]f64 = undefined; + var scratch: [4]f64 = undefined; + try rms(&x, 0, &out); + try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.2))), out[0]); + try std.testing.expectEqual(@as(f64, widen32(@as(f32, 1.6))), out[1]); + try weightedRms(&x, &.{ 2, 0.5, 1, 1 }, 0, &out, &scratch); + // Hand: rho=[1.2,1.6,0,0], then [2.4,0.8,0,0]. BF16(0.8) is 0.80078125. + try std.testing.expectEqualSlices(f64, &.{ 2.40625, 0.80078125, 0, 0 }, &out); +} + +test "attention residual normalizes values and applies binary32 inverse-root-H after its dot" { + const state = [_]f64{ 3, 4, 0, 0 }; + const partial = [_]f64{ 0, 10, 0, 0 }; + const query = [_]f64{ 1, 0, 0, 0 }; + var out: [4]f64 = undefined; + try attentionResidual(std.testing.allocator, &state, &partial, &query, 1, 0, &out); + // rho(S)=[1.2,1.6,0,0], rho(p)=[0,2,0,0], logits .6 and zero; w0=1/(1+exp(-.6)), output=w0*rho(S)+(1-w0)*rho(p). + const w0 = 1 / (1 + @exp(@as(f64, -0.6))); + try expectClose(out[0], 1.2 * w0, 2e-7); + try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); + try std.testing.expectEqual(@as(u32, 0x3caaaaab), @as(u32, @bitCast(try residualScale(hidden_size)))); +} + +test "message bank normalizes exactly its two states and checkpoint query rows are role-interleaved" { + const a = [_]f64{ 3, 4, 0, 0 }; + const p = [_]f64{ 0, 10, 0, 0 }; + var out: [4]f64 = undefined; + try crossPassMessage(std.testing.allocator, .{ .block = &a, .partial = &p }, &.{ 1, 0, 0, 0 }, 0, &out); + const w0 = 1 / (1 + @exp(@as(f64, -0.6))); + try expectClose(out[0], 1.2 * w0, 2e-7); + try expectClose(out[1], 1.6 * w0 + 2 * (1 - w0), 2e-7); + + var q_rows: [24]f64 = undefined; + var kv_rows: [24]f64 = undefined; + for (&q_rows, 0..) |*v, i| v.* = @floatFromInt(i); + for (&kv_rows, 0..) |*v, i| v.* = @floatFromInt(100 + i); + const queries: MessageQueries = .{ .q_mlp = &q_rows, .kv = &kv_rows }; + try std.testing.expectEqual(@as(f64, 4), (try queries.row(2, .q, 1))[0]); + try std.testing.expectEqual(@as(f64, 5), (try queries.row(2, .mlp, 1))[0]); + try std.testing.expectEqual(@as(f64, 104), (try queries.row(2, .k, 1))[0]); + try std.testing.expectEqual(@as(f64, 105), (try queries.row(2, .v, 1))[0]); + + var messages: [visit_count]f64 = undefined; + const one_bank: MessageBank = .{ .block = &.{3}, .partial = &.{4} }; + try crossPassMessages(std.testing.allocator, one_bank, queries, 0, &messages); + for (messages) |message| try std.testing.expectEqual(@as(f64, 1), message); +} + +test "rank gate rounds both joined norms and its down projection before f32 forget and gain" { + const h = [_]f64{ 3, 4, 0, 0 }; + const m = [_]f64{ 0, 10, 0, 0 }; + const weights: GateWeights = .{ + .down = &.{ 0.5, 1.5, 0, 0, 0.5, 1.0078125, 0, 0 }, + .forget = &.{ 1, 0, 0, 0 }, + .gain = &.{ 0, 1, 0, 0 }, + .rank = 1, + }; + var out: [4]f64 = undefined; + try messageGate(std.testing.allocator, &h, &m, weights, 0, &out); + // bf16 rho(h)=[1.203125,1.6015625,0,0], rho(m)=[0,2,0,0]; D*n=5.01953125 rounds to z=5.03125 (else 5.0). + const z: f32 = 5.03125; + const a: f32 = std.math.tanh(z); + const expected0: f32 = (1 - a) * 3; + const expected1: f32 = 4 + a * 10; + try std.testing.expectEqual(@as(f64, widen32(expected0)), out[0]); + try std.testing.expectEqual(@as(f64, widen32(expected1)), out[1]); + try std.testing.expectEqualSlices(f64, &.{ 0, 0 }, out[2..4]); +} + +test "48 visits reset from the prelude and bank B12 plus final partial of only the previous pass" { + var driver = try Driver.init(std.testing.allocator, &.{7}); + defer driver.deinit(); + const zero = [_]f64{0}; + for (0..visit_count) |v| { + _ = try driver.begin(v); + if (v == 6 or v == 18 or v == 30) { + const src = try driver.attentionSources(); + try std.testing.expectEqual(@as(usize, 1), src.blocks.len); + try std.testing.expectEqual(@as(f64, 7), src.blocks[0]); + try std.testing.expectEqual(@as(f64, 21), src.partial[0]); // sum of attention deltas 1...6 + } + if (v == 18) { + const bank = try driver.messageBank(); + try std.testing.expectEqual(@as(f64, 57), bank.block[0]); // sum 7...12 + try std.testing.expectEqual(@as(f64, 93), bank.partial[0]); // sum 13...18 + } else if (v == 30) { + const bank = try driver.messageBank(); + try std.testing.expectEqual(@as(f64, 129), bank.block[0]); // sum 19...24 + try std.testing.expectEqual(@as(f64, 165), bank.partial[0]); // sum 25...30 + } + const delta = [_]f64{@floatFromInt(v + 1)}; + try driver.afterAttention(&delta); + try driver.finish(&zero); + } + const final = try driver.finalSources(); + // Pass 3 supplies the last two core blocks. BF16 rounds the final exact sum 273 to even 272. + try std.testing.expectEqualSlices(f64, &.{ 7, 21, 201, 237 }, final.blocks); + try std.testing.expectEqual(@as(f64, 272), final.partial[0]); +} + +test "visit table preserves layer kinds, AR counts, private visit slots and reference slots" { + const expected = [_]struct { index: usize, layer: u8, pass: u8, reference: u8, messages: bool, ar: u8, attn: u8, mlp: u8 }{ + .{ .index = 0, .layer = 0, .pass = 0, .reference = 0, .messages = false, .ar = 0, .attn = 0, .mlp = 2 }, + .{ .index = 5, .layer = 5, .pass = 0, .reference = 5, .messages = false, .ar = 3, .attn = 2, .mlp = 2 }, + .{ .index = 6, .layer = 6, .pass = 1, .reference = 6, .messages = false, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 17, .layer = 17, .pass = 1, .reference = 17, .messages = false, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 18, .layer = 6, .pass = 2, .reference = 24, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 29, .layer = 17, .pass = 2, .reference = 35, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 30, .layer = 6, .pass = 3, .reference = 36, .messages = true, .ar = 1, .attn = 2, .mlp = 3 }, + .{ .index = 41, .layer = 17, .pass = 3, .reference = 47, .messages = true, .ar = 3, .attn = 4, .mlp = 4 }, + .{ .index = 42, .layer = 18, .pass = 0, .reference = 18, .messages = false, .ar = 1, .attn = 4, .mlp = 5 }, + .{ .index = 47, .layer = 23, .pass = 0, .reference = 23, .messages = false, .ar = 3, .attn = 5, .mlp = 5 }, + }; + for (expected) |e| { + const v = try visit(e.index); + try std.testing.expectEqual(e.layer, v.layer); + try std.testing.expectEqual(e.pass, v.pass); + try std.testing.expectEqual(e.reference, v.reference_slot); + try std.testing.expectEqual(@as(u8, @intCast(e.index)), v.cache_slot); + try std.testing.expectEqual(e.messages, v.has_messages); + try std.testing.expectEqual(e.ar, v.ar_queries); + try std.testing.expectEqual(e.attn, v.attention_sources); + try std.testing.expectEqual(e.mlp, v.mlp_sources); + } + try std.testing.expectError(error.BadVisit, visit(48)); +} + +test "NVFP4 uses bf16 amax and denominator and low nibble before high nibble" { + // 2689 rounds to bf16 2688, so the reference factor is exactly one rather than 2689/2688. + try std.testing.expectEqual(@as(f64, 1), nvfp4OuterFactor(2689, 2688)); + try std.testing.expectEqual(@as(f64, 1.5), nvfp4ReferenceWeight(3, 0x38, 2689, 2688)); + var row: [16]f64 = undefined; + var codes: [8]u8 = @splat(0); + codes[0] = 0xb3; + const scales = [_]u8{0x38}; + try nvfp4ReferenceRow(&codes, &scales, 2689, 2688, &row); + try std.testing.expectEqual(@as(f64, 1.5), row[0]); + try std.testing.expectEqual(@as(f64, -1.5), row[1]); + try std.testing.expectEqual(@as(f64, 0x1p-9), e4m3(1)); + try std.testing.expectEqual(@as(f64, -0.0), e2m1(8)); +} + +test "MXFP8 exponent is UE8M0 and each stored scale covers one row's 32 inputs" { + try std.testing.expectEqual(@as(f64, 8), mxfp8Scale(130)); + try std.testing.expectEqual(@as(f64, 12), mxfp8ReferenceWeight(0x3c, 130)); // 1.5 * 2^3 + var codes: [64]u8 = @splat(0); + codes[0] = 0x38; // one + codes[31] = 0x3c; // 1.5, still group zero + codes[32] = 0x3c; // group one + var out: [64]f64 = undefined; + try mxfp8ReferenceRow(&codes, &.{ 130, 129 }, &out); + try std.testing.expectEqual(@as(f64, 8), out[0]); + try std.testing.expectEqual(@as(f64, 12), out[31]); + try std.testing.expectEqual(@as(f64, 6), out[32]); +} + +test "expert projection and softcapped SwiGLU have no activation quantization" { + var projected: [2]f64 = undefined; + try expertProjection(&.{ 1, 2, -1, 0.5 }, &.{ 3, 4 }, 2, &projected); + try std.testing.expectEqualSlices(f64, &.{ 11, -1 }, &projected); + const g: f32 = 1; + const expected: f32 = 4 * std.math.tanh(g / 4) * (1 / (1 + @exp(-g))) * (25 * std.math.tanh(g / 25)); + try std.testing.expectEqual(@as(f64, bf16(widen32(expected))), expertActivation(1, 1)); +} + +test "expert sum is ascending id even when f32 route-order association gives another bf16 result" { + const ids = [_]u32{ 2, 1, 0 }; + const weights = [_]f64{ 1, 1, 1 }; + // Route order gives -1 + 2^-24 + 1 = 2^-24 in f32; ascending id gives (1 + 2^-24) - 1 = 0 by a tie to even. + const outputs = [_]f64{ -1, 0x1p-24, 1 }; + var out: [1]f64 = undefined; + try combineExperts(3, &ids, &weights, &outputs, 1, &out); + try std.testing.expectEqual(@as(f64, 0), out[0]); +} diff --git a/zig/src/families/inkling2/loop_weights.zig b/zig/src/families/inkling2/loop_weights.zig new file mode 100644 index 00000000000..7bc6263c0fa --- /dev/null +++ b/zig/src/families/inkling2/loop_weights.zig @@ -0,0 +1,228 @@ +//! Inkling 2 Mini's text checkpoint on one CUDA rank. Every scheduled visit shares these physical layer weights. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const config = @import("config.zig"); +const plan_ = @import("plan.zig"); +const modelopt = @import("modelopt.zig"); + +pub const Controller = struct { + down: u64, + forget: u64, + gain: u64, +}; + +pub const Attention = struct { + wq: u64, + wk: u64, + wv: u64, + wr: u64, + wo: u64, + gate: u64, + sink: u64, + q_scale: u64, + rel_scale: u64, + rel_proj: u64, + k_conv: u64, + v_conv: u64, + k_dynamic: u64 = 0, + v_dynamic: u64 = 0, + /// Sliding layers use entry zero for q, k and v. Global layers use the three separate norms. + norms: [3]u64, +}; + +/// Controller order is q, k, v and MLP, matching loop_math_cuda.messages' message layout. +pub const Layer = struct { + attn: Attention, + attn_conv: u64, + mlp_norm: u64, + mlp_conv: u64, + router: u64, + router_bias: u64, + experts: modelopt.Layer, + controllers: [4]Controller, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + c: config.Config, + p: plan_.Plan, + embed: u64 = 0, + embed_norm: u64 = 0, + norm: u64 = 0, + unembed: u64 = 0, + output_query: u64 = 0, + attn_queries: []u64 = &.{}, + mlp_queries: []u64 = &.{}, + cross_qm: u64 = 0, + cross_kv: u64 = 0, + layers: []Layer = &.{}, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + bytes: usize = 0, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.gpa.free(w.attn_queries); + w.gpa.free(w.mlp_queries); + w.* = undefined; + } +}; + +/// All text tensors occupy one aligned device arena; expert uploads use this same bump allocator. +const Loader = struct { + w: *Weights, + arena: cuda.DeviceBuffer, + used: usize = 0, + + pub fn alloc(l: *Loader, len: usize) !u64 { + const at = std.mem.alignForward(usize, l.used, 256); + const end = try std.math.add(usize, at, len); + if (end > l.arena.len) return error.LoopWeightsOverflow; + l.used = end; + l.w.bytes += len; + return l.arena.ptr + at; + } + + fn put(l: *Loader, bytes: []const u8) !u64 { + const p = try l.alloc(bytes.len); + try l.arena.upload(p - l.arena.ptr, bytes); + return p; + } + + fn tensor(l: *Loader, ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: core.safetensors.DType, dims: []const usize) !u64 { + var buf: [256]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, fmt, args); + return l.put((try ck.expect(name, dtype, dims)).bytes); + } +}; + +fn checkpointBytes(ck: *const core.Checkpoint) !usize { + var total: usize = 0; + for (ck.files.items) |file| for (file.names.keys(), file.names.values()) |name, entry| { + if (!std.mem.startsWith(u8, name, "model.llm.")) continue; + const padded = std.mem.alignForward(usize, entry.end - entry.begin, 256); + total = try std.math.add(usize, total, padded); + }; + return total; +} + +fn controllers(l: *Loader, ck: *core.Checkpoint, c: *const config.Text, i: u32, rank: u32, out: *[4]Controller) !void { + const h: usize = c.hidden; + const names = [4][]const u8{ "attn", "k", "v", "mlp" }; + for (names, out) |role, *g| { + var prefix: [160]u8 = undefined; + const p = try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.controllers.{s}", .{ i, role }); + var down: [224]u8 = undefined; + var forget: [224]u8 = undefined; + var gain: [224]u8 = undefined; + g.* = .{ + .down = try l.put((try ck.expect(try std.fmt.bufPrint(&down, "{s}.down_weight", .{p}), .bf16, &.{ rank, 2 * h })).bytes), + .forget = try l.put((try ck.expect(try std.fmt.bufPrint(&forget, "{s}.forget_weight", .{p}), .bf16, &.{ h, rank })).bytes), + .gain = try l.put((try ck.expect(try std.fmt.bufPrint(&gain, "{s}.gain_weight", .{p}), .bf16, &.{ h, rank })).bytes), + }; + } +} + +/// Load every text tensor, including all four controller triplets and both cross-pass query matrices. +pub fn load(gpa: std.mem.Allocator, d: *const cuda.Driver, ck: *core.Checkpoint, c: *const config.Config, p: plan_.Plan) !Weights { + if (c.text.loop == null) return error.Inkling2LoopRequired; + var formats: [config.max_layers]modelopt.Format = undefined; + for (p.layers[0..c.text.layers], 0..) |layer, k| { + formats[k] = switch (layer.precision) { + .nvfp4 => .nvfp4, + .mxfp8 => .mxfp8, + }; + } + const total = try checkpointBytes(ck); + var arena = try cuda.DeviceBuffer.alloc(d, @max(total, 256)); + var w: Weights = .{ .gpa = gpa, .c = c.*, .p = p }; + errdefer w.deinit(); + w.buffers.append(gpa, arena) catch |err| { + arena.free(); + return err; + }; + w.layers = try gpa.alloc(Layer, c.text.layers); + w.attn_queries = try gpa.alloc(u64, c.text.layers); + w.mlp_queries = try gpa.alloc(u64, c.text.layers); + var l: Loader = .{ .w = &w, .arena = arena }; + const h: usize = c.text.hidden; + w.embed = try l.tensor(ck, "model.llm.embed.weight", .{}, .bf16, &.{ c.text.vocab, h }); + w.embed_norm = try l.tensor(ck, "model.llm.embed_norm.weight", .{}, .bf16, &.{h}); + w.norm = try l.tensor(ck, "model.llm.norm.weight", .{}, .bf16, &.{h}); + w.unembed = try l.tensor(ck, "model.llm.unembed.weight", .{}, .bf16, &.{ c.text.vocab, h }); + w.output_query = try l.tensor(ck, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); + w.cross_qm = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); + w.cross_kv = try l.tensor(ck, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 2 * (c.text.loop.?.core_end - c.text.loop.?.core_start), h }); + + for (w.layers, 0..) |*layer, k| { + const i: u32 = @intCast(k); + const L = .{i}; + const hd = c.text.heads(i); + const q: usize = @as(usize, hd.q) * hd.dim; + const kv: usize = @as(usize, hd.kv) * hd.dim; + w.mlp_queries[k] = try l.tensor(ck, "model.llm.attn_res.mlp_queries.{d}", L, .f32, &.{h}); + if (i == 0) { + w.attn_queries[k] = 0; + } else if (config.isGlobal(i)) { + w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{ 3, h }); + } else { + w.attn_queries[k] = try l.tensor(ck, "model.llm.attn_res.attn_queries.{d}", .{i - 1}, .f32, &.{h}); + } + const A = struct { + fn put(loader: *Loader, checkpoint: *core.Checkpoint, comptime fmt: []const u8, args: anytype, dims: []const usize) !u64 { + return loader.tensor(checkpoint, fmt, args, .bf16, dims); + } + }; + layer.attn = .{ + .wq = try A.put(&l, ck, "model.llm.layers.{d}.attn.wq_du.weight", L, &.{ q, h }), + .wk = try A.put(&l, ck, "model.llm.layers.{d}.attn.wk_dv.weight", L, &.{ kv, h }), + .wv = try A.put(&l, ck, "model.llm.layers.{d}.attn.wv_dv.weight", L, &.{ kv, h }), + .wr = try A.put(&l, ck, "model.llm.layers.{d}.attn.wr_du.weight", L, &.{ @as(usize, hd.q) * c.text.d_rel, h }), + .wo = try A.put(&l, ck, "model.llm.layers.{d}.attn.wo_ud.weight", L, &.{ h, q }), + .gate = try A.put(&l, ck, "model.llm.layers.{d}.attn.gate_attn.weight", L, &.{ q, h }), + .sink = try A.put(&l, ck, "model.llm.layers.{d}.attn.attn_sink_proj.weight", L, &.{ hd.q, h }), + .q_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.q_l2_clip.scale", L, &.{ hd.q, hd.dim }), + .rel_scale = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_l2_clip.scale", L, &.{ hd.q, c.text.d_rel }), + .rel_proj = try A.put(&l, ck, "model.llm.layers.{d}.attn.rel_logits_proj.proj", L, &.{ c.text.d_rel, c.text.extent(i) }), + .k_conv = undefined, + .v_conv = undefined, + .norms = undefined, + }; + inline for ([2][]const u8{ "k", "v" }, 0..) |kind, j| { + const conv = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.static_w", L, &.{ config.conv_taps, kv }) + else + try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight", L, &.{ kv, 1, config.conv_taps }); + if (j == 0) layer.attn.k_conv = conv else layer.attn.v_conv = conv; + if (config.isGlobal(i)) { + const dyn = try A.put(&l, ck, "model.llm.layers.{d}.attn." ++ kind ++ "_sconv.weight_proj", L, &.{ @as(usize, hd.kv) * config.conv_taps, h }); + if (j == 0) layer.attn.k_dynamic = dyn else layer.attn.v_dynamic = dyn; + } + const norm = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}." ++ kind ++ "_input_norm.weight", L, &.{h}) + else if (j == 0) + try A.put(&l, ck, "model.llm.layers.{d}.attn_norm.weight", L, &.{h}) + else + layer.attn.norms[1]; // a sliding layer's k and v share one attn_norm upload + layer.attn.norms[j + 1] = norm; + } + layer.attn.norms[0] = if (config.isGlobal(i)) + try A.put(&l, ck, "model.llm.layers.{d}.q_input_norm.weight", L, &.{h}) + else + layer.attn.norms[1]; + layer.attn_conv = try A.put(&l, ck, "model.llm.layers.{d}.attn_sconv.weight", L, &.{ h, 1, config.conv_taps }); + layer.mlp_norm = try A.put(&l, ck, "model.llm.layers.{d}.mlp_norm.weight", L, &.{h}); + layer.mlp_conv = try A.put(&l, ck, "model.llm.layers.{d}.mlp_sconv.weight", L, &.{ h, 1, config.conv_taps }); + layer.router = try A.put(&l, ck, "model.llm.layers.{d}.mlp.gate.weight", L, &.{ c.text.experts, h }); + layer.router_bias = try l.tensor(ck, "model.llm.layers.{d}.mlp.gate.bias", L, .f32, &.{c.text.experts}); + var prefix: [96]u8 = undefined; + layer.experts = try modelopt.load(&l, ck, try std.fmt.bufPrint(&prefix, "model.llm.layers.{d}.mlp.experts.", L), formats[k], c.text.experts, h, c.text.expert_inter); + @memset(&layer.controllers, .{ .down = 0, .forget = 0, .gain = 0 }); + const lp = c.text.loop.?; + if (i >= lp.core_start and i < lp.core_end) try controllers(&l, ck, &c.text, i, lp.gate_rank, &layer.controllers); + } + if (ck.unused() != 0) return error.UnusedCheckpointTensor; + return w; +} diff --git a/zig/src/families/inkling2/metal/attention.zig b/zig/src/families/inkling2/metal/attention.zig new file mode 100644 index 00000000000..9fe310d564f --- /dev/null +++ b/zig/src/families/inkling2/metal/attention.zig @@ -0,0 +1,103 @@ +//! Real Metal pipeline loading and encoder dispatch for Inkling 2 Mini attention. +const std = @import("std"); +const mtl = @import("metal"); +const src = @import("inkling2_metal"); +pub const planning = @import("attention_plan.zig"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const Cache = struct { k: Ref, v: Ref }; +pub const RowMeta = struct { pos: Ref, seg_of: Ref, segs: Ref }; + +pub const Kernels = struct { + scalar_lib: mtl.Library, + prompt_lib: mtl.Library, + prep: mtl.Pipeline, + rel_table: mtl.Pipeline, + decode: mtl.Pipeline, + merge: mtl.Pipeline, + prompt: mtl.Pipeline, + units: bool, + + pub fn init(a: std.mem.Allocator, device: mtl.Device) !Kernels { + var scalar_lib = try mtl.Library.fromSource(device, src.attention, mtl.CompileOptions.mlx()); + errdefer scalar_lib.deinit(); + const units = device.tensorUnits(); + const prompt_src = try a.dupe(u8, if (units) src.prompt_attention else src.prompt_attention_pre_m5); + defer a.free(prompt_src); + var prompt_lib = try mtl.Library.fromSource(device, prompt_src, mtl.CompileOptions.mlx()); + errdefer prompt_lib.deinit(); + var pipes: [5]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for ([_]mtl.Library{ scalar_lib, scalar_lib, scalar_lib, scalar_lib, prompt_lib }, [_][]const u8{ "tf_ink2_prep", "tf_ink2_rel_table", "tf_ink2_attn_scalar", "tf_ink2_merge", "tf_ink2_attn_prompt" }, &pipes) |lib, name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + return .{ .scalar_lib = scalar_lib, .prompt_lib = prompt_lib, .prep = pipes[0], .rel_table = pipes[1], .decode = pipes[2], .merge = pipes[3], .prompt = pipes[4], .units = units }; + } + pub fn deinit(k: *Kernels) void { + k.prompt.deinit(); + k.merge.deinit(); + k.decode.deinit(); + k.rel_table.deinit(); + k.prep.deinit(); + k.prompt_lib.deinit(); + k.scalar_lib.deinit(); + k.* = undefined; + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref, first: usize) void { + for (refs, first..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} + +/// raw holds independent q/k/v rows followed by q-side relative rows; gated sliding visits never infer K or V from Q. +pub fn prep(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, c: planning.Prep, meta: RowMeta, raw: [4]Ref, scales: [2]Ref, q: Ref, rel: Ref, kv: Cache) void { + e.setPipeline(k.prep); + bind(e, &raw, 0); + bind(e, &scales, 4); + bind(e, &.{ meta.pos, meta.seg_of, meta.segs, q, rel, kv.k, kv.v }, 6); + e.setValue(planning.PrepArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .global = @intFromBool(l.tau), .qk_clip = c.qk_clip, .rel_clip = c.rel_clip, .floor_pos = c.floor, .alpha = c.alpha, .eps = c.eps }, 13); + e.dispatchGroups(mtl.Size.of(r.rows, r.heads + 2 * r.kv_heads, 1), mtl.Size.of(32, 1, 1)); +} + +pub fn relTable(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, rel: Ref, proj: Ref, tab: Ref) void { + e.setPipeline(k.rel_table); + bind(e, &.{ rel, proj, tab }, 0); + e.dispatchGroups(mtl.Size.of(r.rows * r.heads, 1, 1), mtl.Size.of(256, 1, 1)); +} + +/// The partial sums of every row and head: `merge` reads them after a barrier. +pub fn partials(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, tab: Ref, part_o: Ref, part_ml: Ref) !void { + const launch = try planning.attend(r, l, stride, slots); + const scale: f32 = 1.0 / @sqrt(@as(f32, planning.head_dim)); + if (launch.path == .decode) { + e.setPipeline(k.decode); + bind(e, &.{ q, kv.k, kv.v, tab, meta.segs, part_o, part_ml, meta.pos, meta.seg_of }, 0); + e.setValue(planning.AttnArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .scale = scale }, 9); + } else { + e.setPipeline(k.prompt); + bind(e, &.{ q, kv.k, kv.v, tab, meta.segs, part_o, part_ml }, 0); + e.setValue(planning.PromptArgs{ .heads = r.heads, .kv_heads = r.kv_heads, .ring = l.ring, .chunk = l.chunk, .c0 = launch.c0, .chunks = launch.partials_rh, .scale = scale, .window = l.window }, 7); + } + e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(launch.threads, 1, 1)); +} + +/// The partials of `partials` merged, with the sink and gate, into each row's attention output. +pub fn merge(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { + const launch = try planning.attend(r, l, stride, slots); + e.setPipeline(k.merge); + bind(e, &.{ part_o, part_ml, sink, gate, meta.pos, out }, 0); + e.setValue(planning.MergeArgs{ .heads = r.heads, .window = l.window, .chunk = l.chunk, .c0 = 0, .chunks = launch.partials_rh, .subs = launch.subs }, 6); + e.dispatchGroups(mtl.Size.of(launch.merge_grid[0], 1, 1), mtl.Size.of(planning.merge_threads, 1, 1)); +} + +pub fn attend(k: *const Kernels, e: mtl.ComputeEncoder, r: planning.Rows, l: planning.Layer, stride: u32, slots: usize, meta: RowMeta, q: Ref, kv: Cache, tab: Ref, part_o: Ref, part_ml: Ref, sink: Ref, gate: Ref, out: Ref) !void { + try partials(k, e, r, l, stride, slots, meta, q, kv, tab, part_o, part_ml); + e.barrier(); + try merge(k, e, r, l, stride, slots, meta, part_o, part_ml, sink, gate, out); +} + +test { + _ = @import("attention_plan.zig"); +} diff --git a/zig/src/families/inkling2/metal/attention_plan.zig b/zig/src/families/inkling2/metal/attention_plan.zig new file mode 100644 index 00000000000..7647210f26b --- /dev/null +++ b/zig/src/families/inkling2/metal/attention_plan.zig @@ -0,0 +1,113 @@ +//! Pure host geometry and ABI declarations for Inkling 2 Mini Metal attention. +const std = @import("std"); + +pub const head_dim = 128; +pub const d_rel = 16; +pub const extent = 1024; +pub const tile_keys = 64; +pub const sliding_chunk = 32; +pub const global_chunk = 16384; +pub const global_sub = 1024; +pub const subs = global_chunk / global_sub; +pub const split_rows = 64; +pub const prompt_pairs = 128; +pub const prompt_threads = 256; +pub const decode_threads = 32; +pub const merge_threads = head_dim; + +pub const Seg = extern struct { row0: i32, n: i32, p0: i32, pad: i32 = 0, off: i64 }; +pub const PrepArgs = extern struct { + heads: u32, + kv_heads: u32, + ring: u32, + global: u32, + qk_clip: f32, + rel_clip: f32, + floor_pos: f32, + alpha: f32, + eps: f32, +}; +pub const AttnArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, window: u32, chunk: u32, c0: u32, chunks: u32, scale: f32 }; +pub const MergeArgs = extern struct { heads: u32, window: u32, chunk: u32, c0: u32, chunks: u32, subs: u32 = 1 }; +pub const PromptArgs = extern struct { heads: u32, kv_heads: u32, ring: u32, chunk: u32, c0: u32, chunks: u32, scale: f32, window: u32 = 0 }; +comptime { + if (@sizeOf(Seg) != 24 or @sizeOf(PrepArgs) != 36 or @sizeOf(AttnArgs) != 32) @compileError("Inkling attention ABI drift"); + if (@sizeOf(MergeArgs) != 24 or @sizeOf(PromptArgs) != 32) @compileError("Inkling prompt ABI drift"); +} + +pub const Layer = struct { + window: u32, + ring: u32, + chunk: u32, + tau: bool, + pub fn sliding(window: u32, rows: u32) Layer { + return .{ .window = window, .ring = ringFor(window, rows), .chunk = sliding_chunk, .tau = false }; + } + pub fn global(capacity: u32) Layer { + return .{ .window = 0, .ring = @intCast(std.mem.alignForward(usize, capacity, tile_keys)), .chunk = globalChunk(capacity), .tau = true }; + } + pub fn cacheBytes(l: Layer, kv: usize) usize { + return @as(usize, l.ring) * kv * head_dim * 2; + } +}; +pub const Prep = struct { qk_clip: f32 = 22.627416997969522, rel_clip: f32 = 8, floor: f32 = 8192, alpha: f32 = 0.1, eps: f32 = 1e-6 }; +/// `prompt`: a prompt's rows, whose sliding layers take the prompt kernel too. +pub const Rows = struct { rows: u32, heads: u32 = 24, kv_heads: u32 = 8, last_pos: u32, streams: u32 = 1, prompt: bool = false }; + +/// The fewest keys a slot that fit `capacity` in 64 slots; any whole number of 1,024-key folds gives the same bits. +pub fn globalChunk(capacity: u32) u32 { + var chunk: u32 = global_sub; + while (@as(u64, chunk) * 64 < capacity and chunk < global_chunk) chunk *= 2; + return chunk; +} + +pub fn ringFor(window: u32, rows: u32) u32 { + return @intCast(std.mem.alignForward(usize, @as(usize, window) + rows - 1, tile_keys)); +} +pub fn chunks(last_pos: usize, chunk: u32) u32 { + return @intCast(last_pos / chunk + 1); +} +pub fn slotsFor(l: Layer, context: usize) u32 { + if (l.window > 0) return (l.window - 1) / l.chunk + 2; + return chunks(context - 1, l.chunk); +} +pub fn split(r: Rows, stride: u32, slots: usize) bool { + return r.rows <= split_rows and @as(usize, r.rows) * r.heads * stride * subs <= slots; +} +pub fn usePrompt(r: Rows, l: Layer, stride: u32, slots: usize) bool { + if (l.window > 0) return r.prompt and r.streams == 1; + return r.streams == 1 and !split(r, stride, slots); +} +pub fn partialSlot(l: Layer, c: usize, pos: usize) ?usize { + const lo = if (l.window > 0) (pos + 1) -| l.window else 0; + if (c < lo / l.chunk or c > pos / l.chunk) return null; + return c - lo / l.chunk; +} +pub fn tableBytes(rows: usize, heads: u32) usize { + return rows * heads * extent * 2; +} +pub fn partialBytes(rows: usize, heads: u32, n_chunks: u32) usize { + return rows * heads * n_chunks * (head_dim * 4 + 8); +} + +pub const Path = enum { decode, prompt }; +pub const Launch = struct { path: Path, grid: [3]u32, threads: u32, merge_grid: [3]u32, partials_rh: u32, subs: u32 = 1, c0: u32 = 0 }; +pub fn attend(r: Rows, l: Layer, stride: u32, slots: usize) error{Inkling2Partials}!Launch { + if (slotsFor(l, @as(usize, r.last_pos) + 1) > stride) return error.Inkling2Partials; + const merge_grid = [3]u32{ r.rows * r.heads, 1, 1 }; + if (usePrompt(r, l, stride, slots)) { + const blocks = std.math.divCeil(u32, r.rows * (r.heads / r.kv_heads), prompt_pairs) catch unreachable; + if (l.window > 0) { + // A sliding layer's chunks run from the first row's window to the last row. + const first_pos = r.last_pos + 1 - r.rows; + const c0 = ((first_pos + 1) -| l.window) / l.chunk; + return .{ .path = .prompt, .grid = .{ blocks, r.kv_heads, r.last_pos / l.chunk - c0 + 1 }, .threads = prompt_threads, .merge_grid = merge_grid, .partials_rh = stride, .c0 = c0 }; + } + return .{ .path = .prompt, .grid = .{ blocks, r.kv_heads, stride }, .threads = prompt_threads, .merge_grid = merge_grid, .partials_rh = stride }; + } + return .{ .path = .decode, .grid = .{ r.rows * r.heads, stride, 1 }, .threads = decode_threads, .merge_grid = merge_grid, .partials_rh = stride }; +} + +test { + _ = @import("attention_test.zig"); +} diff --git a/zig/src/families/inkling2/metal/attention_test.zig b/zig/src/families/inkling2/metal/attention_test.zig new file mode 100644 index 00000000000..885fb201d17 --- /dev/null +++ b/zig/src/families/inkling2/metal/attention_test.zig @@ -0,0 +1,66 @@ +//! Host-only Mini window, ring, tau and dispatch/ABI checks; no Metal import. +const std = @import("std"); +const p = @import("attention_plan.zig"); +const t = std.testing; + +fn tau(pos: usize) f64 { + return 1 + 0.1 * @log(@max(@as(f64, @floatFromInt(pos + 1)) / 8192, 1)); +} + +test "inkling2 metal ABI matches the shaders" { + try t.expectEqual(@as(usize, 24), @sizeOf(p.Seg)); + try t.expectEqual(@as(usize, 36), @sizeOf(p.PrepArgs)); + try t.expectEqual(@as(usize, 24), @sizeOf(p.MergeArgs)); + try t.expectEqual(@as(usize, 32), @sizeOf(p.PromptArgs)); + try t.expectEqual(@as(u32, 24), (p.Rows{ .rows = 1, .last_pos = 0 }).heads); + try t.expectEqual(@as(u32, 8), (p.Rows{ .rows = 1, .last_pos = 0 }).kv_heads); + try t.expectEqual(@as(f32, 8192), (p.Prep{}).floor); +} + +test "inkling2 metal Mini ring and window boundaries" { + try t.expectEqual(@as(u32, 1024), p.ringFor(1024, 1)); + try t.expectEqual(@as(u32, 1088), p.ringFor(1024, 2)); + try t.expectEqual(@as(u32, 3072), p.Layer.sliding(1024, 2048).ring); + const l = p.Layer.sliding(1024, 1); + try t.expectEqual(@as(u32, 33), p.slotsFor(l, 1048576)); + try t.expectEqual(@as(?usize, 31), p.partialSlot(l, 31, 1023)); + try t.expectEqual(@as(?usize, null), p.partialSlot(l, 32, 1023)); + try t.expectEqual(@as(?usize, 32), p.partialSlot(l, 32, 1024)); + try t.expectEqual(@as(?usize, 31), p.partialSlot(l, 63, 2047)); + try t.expectEqual(@as(usize, 1023), @as(usize, 8191) % 1024); + try t.expectEqual(@as(usize, 0), @as(usize, 8192) % 8192); +} + +test "inkling2 metal tau starts strictly above its 8192 floor" { + try t.expectEqual(@as(f64, 1), tau(0)); + try t.expectEqual(@as(f64, 1), tau(8191)); + try t.expect(tau(8192) > 1); + try t.expectApproxEqAbs(1 + 0.1 * @log(@as(f64, 2)), tau(16383), 1e-15); +} + +test "inkling2 metal decode and prompt dispatch geometry" { + const sl = p.Layer.sliding(1024, 8); + const sr = p.Rows{ .rows = 8, .last_pos = 4095, .streams = 2 }; + const sd = try p.attend(sr, sl, 33, 8 * 24 * 33); + try t.expectEqual(p.Path.decode, sd.path); + try t.expectEqual([3]u32{ 192, 33, 1 }, sd.grid); + try t.expectEqual([3]u32{ 192, 1, 1 }, sd.merge_grid); + try t.expectEqual(@as(u32, 32), sd.threads); + const gl = p.Layer.global(1048576); + try t.expectEqual(@as(u32, 16384), gl.chunk); + try t.expectEqual(@as(u32, 1024), p.Layer.global(65536).chunk); + try t.expectEqual(@as(u32, 4096), p.Layer.global(262144).chunk); + const one = p.Rows{ .rows = 1, .last_pos = 1048575 }; + const gd = try p.attend(one, gl, 64, 24 * 64 * p.subs - 1); + try t.expectEqual(p.Path.prompt, gd.path); + try t.expectEqual([3]u32{ 1, 8, 64 }, gd.grid); + try t.expectEqual(@as(u32, 256), gd.threads); + const streamed = p.Rows{ .rows = 1, .last_pos = 1048575, .streams = 2 }; + const scalar = try p.attend(streamed, gl, 64, 0); + try t.expectEqual(p.Path.decode, scalar.path); + try t.expectEqual([3]u32{ 24, 64, 1 }, scalar.grid); + try t.expectError(error.Inkling2Partials, p.attend(streamed, gl, 63, 0)); + const prompt = try p.attend(.{ .rows = 130, .last_pos = 20000 }, gl, 2, 130 * 24 * 2); + try t.expectEqual(p.Path.prompt, prompt.path); + try t.expectEqual([3]u32{ 4, 8, 2 }, prompt.grid); // ceil(130 * 3 / 128) +} diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig new file mode 100644 index 00000000000..6f1be9c3ef7 --- /dev/null +++ b/zig/src/families/inkling2/metal/backend.zig @@ -0,0 +1,588 @@ +//! Inkling 2 Mini behind the lane engine: independent visit state and exact copy-window rollback. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const st = @import("state.zig"); +const fwd = @import("forward.zig"); +const Model = @import("model.zig").Model; +const snapshot = @import("snapshot.zig"); +const cfg = @import("../config.zig"); +const be = lanes.backend; + +pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64 }; +const ring = 4096; + +/// The prompt cache gets the bytes left by live streams and never evicts the state being restored. +pub const Room = struct { ctx: *anyopaque, fit: *const fn (ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const u32) void }; + +/// Mini's DSpark ABI is fixed: four visit taps in checkpoint order. +pub fn validateTaps(c: *const cfg.Config, taps: []const u32) !void { + const mtp = c.mtp orelse return error.UnsupportedInkling2Taps; + const expected = [_]u32{ 5, 23, 41, 48 }; + if (mtp.taps_n != expected.len or !std.mem.eql(u32, mtp.taps[0..mtp.taps_n], &expected) or !std.mem.eql(u32, taps, &expected)) + return error.UnsupportedInkling2Taps; +} + +/// Drafts a stream of a shared round takes at most: four streams' rows then fill one window's 16. +const shared_drafts = 3; + +pub const Metal = struct { + gpa: std.mem.Allocator, + model: *Model, + options: Options, + scratch: st.Scratch, + prompt: st.Scratch, + caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty, + held: u64 = 0, + room: ?Room = null, + tokens: []u32, + next: u64 = 0, + values: []f32, + prepared: bool = false, + sink: ?be.FeatureSink = null, + /// A forward's ms by window width, timed by `warm`: the depth rule prices a lone stream's drafts with them. + costs: [st.window_rows]lanes.config.Cost = undefined, + timed: usize = 0, + tap_gen: u64 = 0, + + pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { + const out = try gpa.create(Metal); + errdefer gpa.destroy(out); + var scratch = try st.Scratch.init(model.device, st.batch_rows); + errdefer scratch.deinit(); + var prompt = try st.Scratch.init(model.device, st.prompt_rows); + errdefer prompt.deinit(); + const tokens = try gpa.alloc(u32, ring); + errdefer gpa.free(tokens); + const values = try gpa.alloc(f32, model.config.text.unpadded_vocab); + out.* = .{ .gpa = gpa, .model = model, .options = options, .scratch = scratch, .prompt = prompt, .tokens = tokens, .values = values }; + return out; + } + + pub fn deinit(self: *Metal) void { + var it = self.caches.valueIterator(); + while (it.next()) |cache| { + cache.*.deinit(); + self.gpa.destroy(cache.*); + } + self.caches.deinit(self.gpa); + self.scratch.deinit(); + self.prompt.deinit(); + self.gpa.free(self.tokens); + self.gpa.free(self.values); + self.gpa.destroy(self); + } + + pub fn createCache(self: *Metal, capacity: usize) !*st.Cache { + const cache = try self.gpa.create(st.Cache); + errdefer self.gpa.destroy(cache); + cache.* = try st.Cache.init(self.model.device, capacity, &self.model.weight_plan); + return cache; + } + + pub fn facts(self: *const Metal) lanes.Model { + return .{ .exact_width = st.window_rows, .gpu_tokens = false, .hidden_rows = true, .batch_rows = st.batch_rows, .mtp = false, .speculate = false, .speculate_early = false, .drafts = 1, .max_streams = self.options.streams, .streams_exact = true, .window_costs = self.costs[0..self.timed], .window_costs_lone = true, .shared_drafts = shared_drafts }; + } + + fn prepareFn(ptr: *anyopaque, taps: []const u32) !void { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (self.prepared) return; + const device = self.model.device; + const decode = self.scratch.taps orelse try device.buffer(st.captureBytes(st.batch_rows), mtl.ResourceOptions.shared); + errdefer if (self.scratch.taps == null) decode.deinit(); + const prompt = self.prompt.taps orelse try device.buffer(st.captureBytes(st.prompt_rows), mtl.ResourceOptions.shared); + errdefer if (self.prompt.taps == null) prompt.deinit(); + self.scratch.taps = decode; + self.prompt.taps = prompt; + self.prepared = true; + } + + fn featuresFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, start: u64, count: u32) !be.Features { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (!self.prepared) return error.UnpreparedInkling2Taps; + const cache = try self.cacheOf(stream); + var tp = cache.tap; + const off = st.featureOffset(tp, start, count, self.tap_gen) catch |err| blk: { + tp = cache.fill_tap; + break :blk st.featureOffset(tp, start, count, self.tap_gen) catch return err; + }; + const buf = tp.buf orelse return error.Inkling2TapsNotHeld; + return .{ .buffer = @intFromPtr(buf.id), .offset = off, .rows = count, .row_bytes = @intCast(st.feature_row_bytes), .space = .device, .dtype = .bf16 }; + } + + fn prefillFeaturesFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, sink: be.FeatureSink) !void { + const self = cast(ptr); + try validateTaps(&self.model.config, taps); + if (!self.prepared) return error.UnpreparedInkling2Taps; + self.sink = sink; + defer self.sink = null; + return prefillFn(ptr, stream); + } + + fn nextTapGeneration(self: *Metal) u64 { + self.tap_gen +%= 1; + return self.tap_gen; + } + + pub fn backend(self: *Metal) be.Backend { + return .{ .keep_full_lone = true, .chunk_invariant = self.model.experts.units != null, .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .reports_fill = true, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; + } + + fn cast(ptr: *anyopaque) *Metal { + return @ptrCast(@alignCast(ptr)); + } + + fn cacheOf(self: *Metal, stream: *lanes.Stream) !*st.Cache { + return self.caches.get(stream) orelse error.UnknownInklingStream; + } + + fn vocab(self: *const Metal) usize { + return self.model.config.text.unpadded_vocab; + } + + fn logits(self: *Metal, cache: *st.Cache) []const f32 { + return cache.logits.slice(f32, self.vocab()); + } + + fn draw(self: *Metal, l: []const f32, sampling: ?lanes.Sampling, position: u64, mask: []const u32) !u32 { + const t = sampled(sampling) orelse { + if (mask.len == 0 and l.len > 0) return firstGreatest(l); + var best: ?usize = null; + for (l, 0..) |w, id| { + if (mask.len > 0 and !lanes.grammar.allows(mask, id)) continue; + if (best == null or w > l[best.?]) best = id; + } + return @intCast(best orelse return error.InklingEmptyTokenMask); + }; + const values = if (mask.len == 0) l else blk: { + for (l, self.values, 0..) |w, *v, id| v.* = if (lanes.grammar.allows(mask, id)) w else -std.math.inf(f32); + break :blk self.values; + }; + return lanes.gpu_full.draw(self.gpa, values, t, @intCast(position), null); + } + + /// The first index of the greatest logit, as draw's scan picks it: a NaN is picked only at index 0. + fn firstGreatest(l: []const f32) u32 { + if (l[0] != l[0]) return 0; + const V = @Vector(16, f32); + const least: V = @splat(-std.math.inf(f32)); + var top = least; + var i: usize = 0; + while (i + 16 <= l.len) : (i += 16) { + const v: V = l[i..][0..16].*; + top = @max(top, @select(f32, v != v, least, v)); + } + var best = @reduce(.Max, top); + for (l[i..]) |w| if (w > best) { + best = w; + }; + const want: V = @splat(best); + i = 0; + while (i + 16 <= l.len) : (i += 16) { + const v: V = l[i..][0..16].*; + if (@reduce(.Or, v == want)) break; + } + for (l[i..], i..) |w, id| if (w == best) return @intCast(id); + return 0; + } + + fn sampled(sampling: ?lanes.Sampling) ?lanes.Sampling { + const t = sampling orelse return null; + return if (t.temperature > 0) t else null; + } + + fn take(self: *Metal) u64 { + const h = self.next; + self.next += 1; + return h; + } + + fn put(self: *Metal, token: u32) u64 { + const h = self.take(); + self.tokens[h % ring] = token; + return h; + } + + fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream) !void { + var at: usize = 0; + while (at < ids.len) at += try self.feedChunk(cache, ids[at..], stream, 0); + } + + /// One chunk of `ids` from the cache's length, of at most `cap` rows when set, cut at planned chunks and marks. + fn feedChunk(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, cap: u32) !usize { + const base = cache.len; + var end: usize = @min(ids.len, if (cap > 0) @min(st.prompt_rows, cap) else st.prompt_rows); + if (stream) |sm| { + if (sm.isCancelled()) return error.Cancelled; + for (sm.chunks) |x| if (x > base and x < base + end) { + end = x - base; + }; + for (sm.reuse.marks) |x| if (x > base and x < base + end) { + end = x - base; + }; + } + const s = if (end > st.batch_rows) &self.prompt else &self.scratch; + const capture = self.prepared and stream != null; + if (capture) _ = self.nextTapGeneration(); + const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; + try fwd.run(self.model, s, cache, ids[0..end], .{ .taps = taps, .prompt = true }); + if (capture) { + if (self.sink) |k| try k.take(k.ptr, stream.?, .{ + .buffer = @intFromPtr(s.taps.?.id), + .offset = 0, + .rows = @intCast(end), + .row_bytes = @intCast(st.feature_row_bytes), + .space = .device, + .dtype = .bf16, + }, @intCast(base)) else { + cache.fill_tap = .{ .buf = s.taps, .start = @intCast(base), .rows = end, .gen = self.tap_gen }; + } + if (base + end == stream.?.prompt().len) { + if (cache.last_tap == null) { + cache.last_tap = try self.model.device.buffer(st.feature_row_bytes, mtl.ResourceOptions.shared); + if (cache.follow) |f| f.join(f.ctx, cache.last_tap.?); + } + const bytes = s.taps.?.slice(u8, end * st.feature_row_bytes); + @memcpy(cache.last_tap.?.slice(u8, st.feature_row_bytes), bytes[(end - 1) * st.feature_row_bytes ..][0..st.feature_row_bytes]); + cache.tap = .{ .buf = cache.last_tap, .start = @intCast(base + end - 1), .rows = 1 }; + } + } + cache.len += end; + if (stream) |sm| { + lanes.prefill_widths.completed(self.gpa, sm, end); + sm.fill_at.store(@intCast(cache.len), .monotonic); + if (std.mem.indexOfScalar(u32, sm.reuse.marks, @intCast(cache.len)) != null) if (sm.reuse.hook) |k| k.at(k.ptr, sm, @intCast(cache.len)); + } + return end; + } + + /// The stream's cache made and a kept prefix restored: the pass goes on from the cache's length. + fn opening(self: *Metal, stream: *lanes.Stream) !*st.Cache { + const ids = stream.prompt(); + if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidInklingPrompt; + if (stream.images.len > 0) return error.InklingHasNoImageTower; + const need = st.cacheBytes(ids.len + stream.max_new); + if (self.held + need > self.options.budget) { + std.log.warn("inkling2_loop: a stream needs {d:.1} GiB of state; {d:.1} of {d:.1} GiB are held", .{ gib(need), gib(self.held), gib(self.options.budget) }); + return error.InklingStateFull; + } + self.held += need; + errdefer self.held -= need; + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, stream.reuse.saved, ids); + const cache = try self.createCache(ids.len + stream.max_new); + errdefer self.gpa.destroy(cache); + errdefer cache.deinit(); + try self.caches.put(self.gpa, stream, cache); + errdefer _ = self.caches.remove(stream); + stream.cached = 0; + if (stream.reuse.saved) |saved| { + const snap: *const snapshot.Snap = @ptrCast(@alignCast(saved)); + if (snap.at < ids.len) { + if (snapshot.restore(cache, self.model.queue, snap)) stream.cached = @intCast(snap.at) else |_| stream.reuse_failed = true; + } else stream.reuse_failed = true; + } + return cache; + } + + /// A pass that failed: its cache goes, as the whole pass's error leaves it. + fn drop(self: *Metal, stream: *lanes.Stream) void { + const entry = self.caches.fetchRemove(stream) orelse return; + self.held -= st.cacheBytes(entry.value.capacity); + entry.value.deinit(); + self.gpa.destroy(entry.value); + } + + fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { + const self = cast(ptr); + const cache = try self.opening(stream); + errdefer self.drop(stream); + try self.feed(cache, stream.prompt()[cache.len..], stream); + } + + /// One chunk a call, other streams' rounds between; the host's `max_rows` caps a chunk while replies decode. + fn prefillStepFn(ptr: *anyopaque, stream: *lanes.Stream, max_rows: u32) !bool { + const self = cast(ptr); + const cache = self.caches.get(stream) orelse try self.opening(stream); + errdefer self.drop(stream); + const ids = stream.prompt(); + // Beside other streams a chunk is at most `busy_rows`, so their rounds wait no longer than a short chunk. + const busy: u32 = if (self.caches.count() > 1) busy_rows else 0; + const cap = if (max_rows > 0 and busy > 0) @min(max_rows, busy) else @max(max_rows, busy); + _ = try self.feedChunk(cache, ids[cache.len..], stream, cap); + return cache.len == ids.len; + } + + pub fn warm(self: *Metal) !void { + var cache = try st.Cache.init(self.model.device, st.prompt_rows + st.window_rows, &self.model.weight_plan); + defer cache.deinit(); + var ids: [st.prompt_rows]u32 = undefined; + for (&ids, 0..) |*t, i| t.* = @intCast(1000 + i * 37 % 20000); + try self.feed(&cache, &ids, null); + try fwd.run(self.model, &self.scratch, &cache, ids[0..st.window_rows], .{ .all = true }); + // A window of each width after that prompt, the second of two runs timed. + for (1..st.window_rows + 1) |rows| { + var ms: f64 = 0; + for (0..2) |attempt| { + const t0 = now(); + try fwd.run(self.model, &self.scratch, &cache, ids[0..rows], .{ .all = true }); + if (attempt == 1) ms = now() - t0; + } + self.costs[rows - 1] = .{ .width = @intCast(rows), .ms = ms }; + } + self.timed = st.window_rows; + } + + fn now() f64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(f64, @floatFromInt(ts.sec)) * 1000.0 + @as(f64, @floatFromInt(ts.nsec)) * 1e-6; + } + + fn firstFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64) !u64 { + return cast(ptr).firstSlot(stream, position, &.{}); + } + + fn firstMaskedFn(ptr: *anyopaque, stream: *lanes.Stream, position: u64, mask: []const u32) !u64 { + return cast(ptr).firstSlot(stream, position, mask); + } + + fn firstSlot(self: *Metal, stream: *lanes.Stream, position: u64, mask: []const u32) !u64 { + const cache = try self.cacheOf(stream); + if (position != cache.len or cache.pending != null) return error.InvalidInklingPosition; + return self.put(try self.draw(self.logits(cache), stream.sampling, position, mask)); + } + + fn queueFn(ptr: *anyopaque, stream: *lanes.Stream, what: be.Feed, position: u64) !u64 { + const self = cast(ptr); + const cache = try self.cacheOf(stream); + if (position != cache.len + 1 or cache.pending != null) return error.InvalidInklingPosition; + const token = switch (what) { + .handle => |h| try self.read(h), + .value => |v| v, + }; + if (token >= self.vocab()) return error.InvalidInklingToken; + const generation = if (self.prepared) self.nextTapGeneration() else 0; + const taps: ?st.Ref = if (self.prepared) .{ .buf = self.scratch.taps.? } else null; + try fwd.run(self.model, &self.scratch, cache, &.{token}, .{ .taps = taps }); + if (self.prepared) cache.tap = .{ .buf = self.scratch.taps, .start = @intCast(cache.len), .rows = 1, .gen = generation }; + cache.len += 1; + return self.put(try self.draw(self.logits(cache), stream.sampling, position, &.{})); + } + + fn read(self: *Metal, handle: u64) !u32 { + if (handle >= self.next) return error.InvalidInklingTokenHandle; + const token = self.tokens[handle % ring]; + if (token >= self.vocab()) return error.InvalidInklingToken; + return token; + } + + fn readFn(ptr: *anyopaque, handle: u64) !u32 { + return cast(ptr).read(handle); + } + + fn firstRowFn(ptr: *anyopaque, stream: *lanes.Stream) !lanes.LogprobRow { + const self = cast(ptr); + const l = self.logits(try self.cacheOf(stream)); + return firstLogprobRow(l, self.tokens, self.next, stream.logprobs orelse 0); + } + + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + const self = cast(ptr); + const words = maskWords(self.model.config.text.vocab); + if (windows.len != out.len or windows.len > st.batch_rows) return error.InvalidInklingWindows; + var segments: [st.batch_rows]fwd.Segment = undefined; + var ids: [st.batch_rows]u32 = undefined; + var total: usize = 0; + var begun: usize = 0; + errdefer for (segments[0..begun]) |seg| seg.cache.rollback(self.model.queue) catch {}; + for (windows, out, 0..) |w, o, i| { + const rows = w.rows(); + if (rows == 0 or rows > st.window_rows or total + rows > st.batch_rows or w.parents != null or w.held != 0 or o.sampled.len != rows or o.drafts.len != rows - 1 or w.positions.len != rows) return error.UnsupportedInklingWindow; + if (w.masks.len != 0 and w.masks.len != rows * words) return error.InvalidInklingMasks; + const cache = try self.cacheOf(w.stream); + if (cache.pending != null) return error.InklingWindowAlreadyOpen; + for (w.positions, 0..) |p, r| if (p != cache.len + r + 1) return error.InvalidInklingPosition; + segments[i] = .{ .cache = cache, .rows = rows }; + ids[total] = w.pending; + @memcpy(ids[total + 1 ..][0..w.tokens.len], w.tokens); + total += rows; + } + for (segments[0..windows.len]) |seg| { + try seg.cache.begin(self.model.queue, seg.rows); + begun += 1; + } + const generation = if (self.prepared) self.nextTapGeneration() else 0; + const taps: ?st.Ref = if (self.prepared) .{ .buf = self.scratch.taps.? } else null; + try fwd.runShared(self.model, &self.scratch, segments[0..windows.len], ids[0..total], .{ .all = true, .taps = taps }); + const all = self.scratch.logits_all.slice(f32, total * self.vocab()); + var base: usize = 0; + for (windows, out, segments[0..windows.len]) |w, o, seg| { + if (self.prepared) seg.cache.tap = .{ .buf = self.scratch.taps, .off = base * st.feature_row_bytes, .start = @intCast(seg.cache.len), .rows = seg.rows, .gen = generation }; + @memcpy(o.drafts, w.tokens); + for (0..seg.rows) |r| { + const l = all[(base + r) * self.vocab() ..][0..self.vocab()]; + const mask = maskRow(w.masks, words, r); + o.sampled[r] = try self.draw(l, w.stream.sampling, w.positions[r], mask); + if (o.rows.len == seg.rows) o.rows[r] = logprobRow(l, o.sampled[r], w.stream.logprobs orelse 0); + } + @memcpy(seg.cache.logits.slice(f32, self.vocab()), all[(base + seg.rows - 1) * self.vocab() ..][0..self.vocab()]); + base += seg.rows; + } + } + + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void { + const self = cast(ptr); + if (windows.len != paths.len) return error.InvalidInklingWindows; + for (windows, paths) |w, path| { + const cache = try self.cacheOf(w.stream); + for (path, 0..) |r, i| if (r != i) return error.UnsupportedInklingTree; + if (path.len == 0 or path.len > w.rows() or cache.pending == null or cache.pending.? != w.rows()) return error.UnsupportedInklingWindow; + try cache.commit(self.model.queue, path.len); + } + } + + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) !void { + _ = ptr; + for (requests) |r| if (r.depth != 0 or r.lanes != null or r.plan != null) return error.InklingHasNoDraftHead; + } + + fn heldFn(_: *anyopaque, _: *lanes.Stream, out: []u32) !void { + if (out.len > 0) return error.InklingDraftsNotHeld; + } + + fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void { + const self = cast(ptr); + if (self.caches.fetchRemove(stream)) |entry| { + const cache = entry.value; + if (cache.pending != null) cache.rollback(self.model.queue) catch |err| std.log.err("inkling2_loop rollback at release: {s}", .{@errorName(err)}); + self.held -= st.cacheBytes(cache.capacity); + cache.deinit(); + self.gpa.destroy(cache); + if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, null, &.{}); + } + } + + pub fn snapBytes(ptr: *anyopaque, at: u32) u64 { + _ = ptr; + return snapshot.bytes(at); + } + + pub fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + const self = cast(ptr); + const cache = try self.cacheOf(@ptrCast(@alignCast(owner orelse return error.NoStream))); + if (cache.len != at or cache.pending != null) return error.SnapshotOutOfStep; + const snap = try self.gpa.create(snapshot.Snap); + errdefer self.gpa.destroy(snap); + snap.* = try snapshot.save(self.model.device, self.model.queue, cache); + return snap; + } + + pub fn snapRestore(_: *anyopaque, _: ?*anyopaque, _: *anyopaque) anyerror!void { + return error.BackendRestores; + } + + pub fn snapDrop(ptr: *anyopaque, saved: *anyopaque) void { + const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); + snap.free(); + cast(ptr).gpa.destroy(snap); + } +}; + +/// A grammar mask's words a row: a bit a token of the tokenizer's vocabulary, which passes the unembedding's rows. +fn maskWords(vocab: u32) usize { + return (@as(usize, vocab) + 31) / 32; +} + +/// Row `r` of a window's masks, or none where the window has none. +fn maskRow(masks: []const u32, words: usize, r: usize) []const u32 { + return if (masks.len == 0) &.{} else masks[r * words ..][0..words]; +} + +test "a window's masks step by the padded vocabulary's words" { + const words = maskWords(201024); + try std.testing.expectEqual(@as(usize, 6282), words); + var masks: [3 * 6282]u32 = @splat(0); + masks[2 * 6282] = 1; + try std.testing.expectEqual(@as(usize, 0), maskRow(&.{}, words, 2).len); + try std.testing.expectEqual(@as(u32, 0), maskRow(&masks, words, 1)[0]); + try std.testing.expect(lanes.grammar.allows(maskRow(&masks, words, 2), 0)); + try std.testing.expect(!lanes.grammar.allows(maskRow(&masks, words, 1), 0)); +} + +/// A stepped prompt chunk's rows while another stream holds state. +const busy_rows: u32 = 256; + +fn gib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +fn firstLogprobRow(l: []const f32, tokens: []const u32, next: usize, count: u8) lanes.LogprobRow { + std.debug.assert(tokens.len == ring and next > 0); + return logprobRow(l, tokens[(next - 1) % ring], count); +} + +fn logprobRow(l: []const f32, pick: u32, count: u8) lanes.LogprobRow { + const top = lanes.logprob.max_top; + var most: f64 = -std.math.inf(f64); + for (l) |w| most = @max(most, w); + var sum: f64 = 0; + for (l) |w| sum += @exp(@as(f64, w) - most); + const lse: f32 = @floatCast(most + @log(sum)); + var r: lanes.LogprobRow = .{ .token = pick, .logprob = l[pick] - lse, .count = 0 }; + var filled: usize = 0; + for (l, 0..) |w, id| { + if (filled == top and w <= r.logprobs[top - 1] + lse) continue; + var at = @min(filled, top - 1); + while (at > 0 and w > r.logprobs[at - 1] + lse) : (at -= 1) { + r.ids[at] = r.ids[at - 1]; + r.logprobs[at] = r.logprobs[at - 1]; + } + r.ids[at] = @intCast(id); + r.logprobs[at] = w - lse; + filled = @min(filled + 1, top); + } + r.count = @min(count, top); + return r; +} + +test "a greedy pick is the scan's: the first of equal maxima, and a NaN only at index 0" { + const scan = struct { + fn pick(l: []const f32) u32 { + var best: usize = 0; + for (l, 0..) |w, id| if (w > l[best]) { + best = id; + }; + return @intCast(best); + } + }.pick; + var l: [203]f32 = undefined; + for (0..64) |round| { + for (&l, 0..) |*v, i| v.* = @floatFromInt(@as(i32, @intCast((i * 37 + round * 11) % 101)) - 50); + // Equal maxima, NaNs, both infinities and zeros of both signs, at places that move with the round. + l[(round * 7) % l.len] = 60; + l[(round * 13 + 5) % l.len] = 60; + if (round % 3 == 0) l[(round * 5 + 1) % l.len] = std.math.nan(f32); + if (round % 4 == 0) l[(round * 17 + 2) % l.len] = std.math.inf(f32); + if (round % 5 == 0) l[(round * 3) % l.len] = -std.math.inf(f32); + if (round % 7 == 0) l[0] = std.math.nan(f32); + try std.testing.expectEqual(scan(&l), Metal.firstGreatest(&l)); + try std.testing.expectEqual(scan(l[0..17]), Metal.firstGreatest(l[0..17])); + } + var z = [_]f32{ -0.0, 0.0, -std.math.inf(f32) }; + try std.testing.expectEqual(@as(u32, 0), Metal.firstGreatest(&z)); + z = .{ -std.math.inf(f32), std.math.nan(f32), -std.math.inf(f32) }; + try std.testing.expectEqual(@as(u32, 0), Metal.firstGreatest(&z)); +} + +test "sampled first-token logprob uses the last written handle, not argmax" { + const logits = [_]f32{ 0, -1, -2, -3 }; + var tokens: [ring]u32 = @splat(0); + tokens[2] = 3; + const row = firstLogprobRow(&logits, &tokens, 3, 0); + try std.testing.expectEqual(@as(u32, 3), row.token); + try std.testing.expect(std.math.isFinite(row.logprob)); + const lse = @log(@as(f64, 1) + @exp(-@as(f64, 1)) + @exp(-@as(f64, 2)) + @exp(-@as(f64, 3))); + try std.testing.expectApproxEqAbs(@as(f32, -3) - @as(f32, @floatCast(lse)), row.logprob, 1e-6); +} diff --git a/zig/src/families/inkling2/metal/dspark.zig b/zig/src/families/inkling2/metal/dspark.zig new file mode 100644 index 00000000000..70afd6115da --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark.zig @@ -0,0 +1,314 @@ +//! Inkling 2 Mini DSpark on Metal, the kernels behind the shared lane host: features, blocks, folded Markov logits. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const gpu_rule = lanes.gpu_rule; +const ck = @import("../../../core/checkpoint_metal.zig"); +const Model = @import("model.zig").Model; +const fwd = @import("forward.zig"); +const glue = @import("glue.zig"); +const k = @import("dspark_kernels.zig"); +const weight_loader = @import("dspark_weights.zig"); +const state = @import("dspark_state.zig"); +const host = @import("../dspark_lanes.zig"); + +const Ref = k.Ref; +/// Drafts a hold offers at most: the block after its anchor. The depth rule prices how many a round takes. +const hold_depth: u32 = host.depth; +/// The partials of the tensor-unit attention at a window under 1,024 tokens, where the host has fewer score bytes. +const units_floor = k.unitsBytes(1024 / k.units_chunk + 2); + +/// A lane and what the shared host books of it: its rings and its committed rows [from, end). +const Context = struct { lane: *const state.Lane, rings: [3]usize, from: u64, end: u64 }; +/// Streams one greedy hold can chain on the GPU; a wider hold samples on the host as sampled streams do. +const chain_streams = 16; + +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn failed(cb: mtl.CommandBuffer, what: []const u8) !void { + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop DSpark {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +pub const Drafter = struct { + /// What the shared host opens a stream: its rings and its newest row. + pub const Lane = state.Lane; + + gpa: std.mem.Allocator, + target: *const Model, + weights: weight_loader.Loaded, + pipelines: k.Pipelines, + scratch: state.Scratch, + /// Scratch for the second and later streams of one hold; the first uses `scratch`, as absorb does. + more: std.ArrayList(state.Scratch) = .empty, + /// The greedy chain's kernels, and each held stream's eight tokens: the anchor, then its drafts. + chain: k.Chain = undefined, + chain_tokens: mtl.Buffer = undefined, + scores: ?mtl.Buffer = null, + /// The block attention's tensor-unit kernels, on the chips that have the units. + units: ?k.Units = null, + /// A draft's share of a full hold, timed by `measure`. + step_ms: f64 = 0, + /// The round loop's drafter: the shared host's books over these kernels. + lanes: host.Drafter(Drafter) = undefined, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, target: *const Model, drafter_dir: []const u8) !*Drafter { + _ = io; // Native factory convention; Checkpoint.addFile uses platform file calls. + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const d = try gpa.create(Drafter); + errdefer gpa.destroy(d); + d.* = .{ + .gpa = gpa, + .target = target, + .weights = weight_loader.load(gpa, target, drafter_dir) catch |err| return err, + .pipelines = undefined, + .scratch = undefined, + }; + d.lanes = host.Drafter(Drafter).init(gpa, d); + errdefer d.weights.deinit(); + d.pipelines = try k.Pipelines.load(device); + errdefer d.pipelines.deinit(); + d.scratch = try state.Scratch.init(device); + errdefer d.scratch.deinit(); + d.chain = try k.Chain.load(device, @import("inkling2_metal").inkling2_dspark); + errdefer d.chain.deinit(); + d.chain_tokens = try device.buffer(chain_streams * 8 * @sizeOf(u32), mtl.ResourceOptions.shared); + errdefer d.chain_tokens.deinit(); + if (device.tensorUnits()) d.units = try k.Units.load(device, @import("inkling2_metal").inkling2_dspark_units); + return d; + } + + pub fn deinit(d: *Drafter) void { + d.lanes.deinit(); + if (d.scores) |scores| scores.deinit(); + if (d.units) |*u| u.deinit(); + d.chain_tokens.deinit(); + d.chain.deinit(); + for (d.more.items) |*extra| extra.deinit(); + d.more.deinit(d.gpa); + d.scratch.deinit(); + d.pipelines.deinit(); + d.weights.deinit(); + d.gpa.destroy(d); + } + + pub fn fixedBytes(d: *const Drafter) u64 { + return d.weights.fixedBytes() + state.scratchBytes() + units_floor; + } + + pub fn openLane(d: *Drafter, rings: [3]usize) !Lane { + return Lane.init(d.target.device, rings); + } + + pub fn closeLane(_: *Drafter, lane: *Lane) void { + lane.deinit(); + } + + /// The holds' shared attention scratch: the host's bytes, or the tensor-unit partials' floor where that is more. + pub fn setScores(d: *Drafter, bytes: u64) !void { + const scores = try d.target.device.buffer(@intCast(@max(bytes, units_floor)), mtl.ResourceOptions.private); + if (d.scores) |old| old.deinit(); + d.scores = scores; + } + + pub fn policy(d: *const Drafter) host.Policy { + // No plain rounds: one draft pays from about a third landing, and the guard's estimate near that line is noise. + return .{ .step_ms = d.step_ms, .plain_guard = false, .batched = true }; + } + + fn absorbRows(d: *Drafter, e: mtl.ComputeEncoder, lane: *const Lane, rings: [3]usize, taps: Ref, start: u64, rows: usize) void { + const n: u32 = @intCast(rows); + k.fuseTaps(&d.pipelines, e, taps, r(d.weights.weights.fuse), at(d.weights.dflare, 0), at(d.scratch.fused, 0), at(lane.newest, 0), n); + for (d.weights.weights.layers, 0..) |layer, i| { + const c = at(d.scratch.fused, i * rows * state.hidden * 2); + fwd.dense(d.target, e, layer.k_ctx, c, at(d.scratch.ck, 0), rows); + fwd.dense(d.target, e, layer.v_ctx, c, at(d.scratch.cv, 0), rows); + k.commitContext(&d.pipelines, e, at(d.scratch.ck, 0), at(d.scratch.cv, 0), r(layer.k_norm_ctx), at(lane.k[i], 0), at(lane.v[i], 0), @intCast(start), n, @intCast(rings[i])); + } + } + + /// Every stream's pieces of an absorb in one command buffer, in the order the host hands them. + pub fn absorb(d: *Drafter, pieces: []const host.Absorb(Lane)) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + for (pieces) |p| { + const source = mtl.Buffer{ .id = @ptrFromInt(p.features.buffer) }; + d.absorbRows(e, p.lane, p.rings, at(source, @intCast(p.offset)), p.position, p.rows); + } + e.end(); + cb.commit(); + try failed(cb, "absorb"); + } + + fn encodeBlock(d: *Drafter, e: mtl.ComputeEncoder, s: *const state.Scratch, c: Context, pending: u32, depth: u32) void { + s.ids.slice(u32, 1)[0] = pending; + glue.embedNorm(&d.target.glue, e, at(s.ids, 0), r(d.target.weights.embed), r(d.target.weights.embed_norm), at(s.x, 0), 1); + k.initializeRows(&d.pipelines, e, at(s.x, 0), r(d.weights.weights.mask), at(s.x, 0)); + k.residualNorm(&d.pipelines, e, at(s.x, 0), at(s.resid, 0), r(d.weights.weights.layers[0].input_norm), at(s.resid, 0), at(s.x, 0), 8, true); + for (d.weights.weights.layers, 0..) |layer, i| { + fwd.dense(d.target, e, layer.q, at(s.x, 0), at(s.q_raw, 0), 8); + fwd.dense(d.target, e, layer.k, at(s.x, 0), at(s.k_raw, 0), 8); + fwd.dense(d.target, e, layer.v, at(s.x, 0), at(s.v_raw, 0), 8); + k.blockQkv(&d.pipelines, e, at(s.q_raw, 0), at(s.k_raw, 0), at(s.v_raw, 0), r(layer.q_norm), r(layer.k_norm), at(s.q, 0), at(s.kb, 0), at(s.vb, 0), @intCast(c.end)); + if (d.units) |*u| k.attendUnits(u, e, at(s.q, 0), at(s.kb, 0), at(s.vb, 0), at(c.lane.k[i], 0), at(c.lane.v[i], 0), at(d.scores.?, 0), at(s.attn, 0), @intCast(c.end), @intCast(c.rings[i]), i != 1, @intCast(c.from)) else k.attend(&d.pipelines, e, at(s.q, 0), at(s.kb, 0), at(s.vb, 0), at(c.lane.k[i], 0), at(c.lane.v[i], 0), at(d.scores.?, 0), at(s.attn, 0), @intCast(c.end), @intCast(c.rings[i]), i != 1, @intCast(c.from)); + fwd.dense(d.target, e, layer.o, at(s.attn, 0), at(s.y, 0), 8); + k.residualNorm(&d.pipelines, e, at(s.y, 0), at(s.resid, 0), r(layer.post_norm), at(s.next_resid, 0), at(s.x, 0), 8, false); + fwd.dense(d.target, e, layer.gate, at(s.x, 0), at(s.gate, 0), 8); + fwd.dense(d.target, e, layer.up, at(s.x, 0), at(s.up, 0), 8); + k.swiglu(&d.pipelines, e, at(s.gate, 0), at(s.up, 0), at(s.act, 0), 8 * state.intermediate); + fwd.dense(d.target, e, layer.down, at(s.act, 0), at(s.y, 0), 8); + const next_norm = if (i + 1 < d.weights.weights.layers.len) d.weights.weights.layers[i + 1].input_norm else d.weights.weights.norm; + k.residualNorm(&d.pipelines, e, at(s.y, 0), at(s.next_resid, 0), r(next_norm), at(s.resid, 0), at(s.x, 0), 8, false); + } + k.base(&d.pipelines, e, r(d.target.weights.unembed), at(s.x, state.hidden * 2), at(s.base, 0), depth, state.vocabulary); + k.kappa(&d.pipelines, e, at(s.x, state.hidden * 2), at(c.lane.newest, 0), r(d.weights.weights.rnn), r(d.weights.weights.rnn_bias), at(s.kappa, 0), depth); + } + + fn recurrent(d: *Drafter, e: mtl.ComputeEncoder, s: *const state.Scratch, step: usize, previous: u32, second_bank: bool) void { + const current = if (second_bank) s.next_state else s.state; + const next = if (second_bank) s.state else s.next_state; + k.recurrentStep(&d.pipelines, e, at(current, 0), at(s.kappa, step * 3 * state.rank * 4), r(d.weights.weights.rnn), r(d.weights.weights.markov_w1), at(s.z, 0), at(next, 0), at(s.lambda, 0), previous); + k.finalLogits(&d.pipelines, e, at(s.base, step * state.vocabulary * 2), at(d.weights.phi, 0), at(d.weights.beta, 0), at(s.lambda, 0), at(s.logits, 0)); + } + + fn slot(d: *Drafter, index: usize) !*const state.Scratch { + if (index == 0) return &d.scratch; + while (d.more.items.len < index) { + var extra = try state.Scratch.init(d.target.device); + errdefer extra.deinit(); + try d.more.append(d.gpa, extra); + } + return &d.more.items[index - 1]; + } + + /// One stream's greedy hold: its block, then each step's recurrent pass, logits and pick; `held` takes the drafts. + fn encodeChain(d: *Drafter, e: mtl.ComputeEncoder, s: *const state.Scratch, c: Context, held: Ref, pending: u32, depth: usize) void { + d.encodeBlock(e, s, c, pending, @intCast(depth)); + var second_bank = false; + for (0..depth) |step| { + const current = if (second_bank) s.next_state else s.state; + const next = if (second_bank) s.state else s.next_state; + k.chainStep(&d.chain, e, at(current, 0), at(s.kappa, step * 3 * state.rank * 4), r(d.weights.weights.rnn), r(d.weights.weights.markov_w1), at(s.z, 0), at(next, 0), at(s.lambda, 0), held, @intCast(step)); + k.finalLogits(&d.pipelines, e, at(s.base, step * state.vocabulary * 2), at(d.weights.phi, 0), at(d.weights.beta, 0), at(s.lambda, 0), at(s.logits, 0)); + k.chainPick(&d.chain, e, at(s.logits, 0), held, @intCast(step)); + second_bank = !second_bank; + } + } + + /// A full hold on an empty context, the third of three runs timed: the depth rule prices a draft at its share. + pub fn measure(d: *Drafter) !void { + const rings = host.rings(d.lanes.capacity); + var lane = try Lane.init(d.target.device, rings); + defer lane.deinit(); + const held = Ref{ .buf = d.chain_tokens, .off = 0 }; + var ms: f64 = 0; + for (0..3) |attempt| { + var t0: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &t0); + @memset(d.scratch.state.slice(u16, state.rank), 0); + d.chain_tokens.slice(u32, 8)[0] = 2; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + d.encodeChain(e, &d.scratch, .{ .lane = &lane, .rings = rings, .from = 0, .end = 0 }, held, 2, hold_depth); + e.end(); + cb.commit(); + try failed(cb, "timed hold"); + var t1: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &t1); + if (attempt == 2) ms = @as(f64, @floatFromInt(t1.sec - t0.sec)) * 1e3 + @as(f64, @floatFromInt(t1.nsec - t0.nsec)) / 1e6; + } + d.step_ms = ms / @as(f64, @floatFromInt(hold_depth)); + } + + /// Greedy streams: the blocks and every step in one command buffer, each draft picked on the GPU for the next. + fn holdChained(d: *Drafter, items: []const host.Hold(Lane), drafts: [][host.depth]u32) !void { + const tokens = d.chain_tokens.slice(u32, chain_streams * 8); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + for (items, 0..) |item, i| { + const s = try d.slot(i); + const held = Ref{ .buf = d.chain_tokens, .off = i * 8 * @sizeOf(u32) }; + tokens[i * 8] = item.pending; + d.encodeChain(e, s, .{ .lane = item.lane, .rings = item.rings, .from = item.from, .end = item.anchor }, held, item.pending, item.depth); + } + e.end(); + cb.commit(); + try failed(cb, "chained block"); + // A token past the vocabulary says the logits were not finite; the host refuses it when it keeps the drafts. + for (items, drafts, 0..) |item, *out, i| @memcpy(out[0..item.depth], tokens[i * 8 + 1 ..][0..item.depth]); + } + + /// One call a hold for all its streams: greedy ones chain in one command buffer, sampled ones a step a buffer. + pub fn hold(d: *Drafter, items: []const host.Hold(Lane), drafts: [][host.depth]u32) !void { + var deepest: usize = 0; + for (items, 0..) |item, i| { + deepest = @max(deepest, item.depth); + @memset((try d.slot(i)).state.slice(u16, state.rank), 0); + } + var greedy = items.len <= chain_streams; + for (items) |item| greedy = greedy and item.sampling == null; + if (greedy) return d.holdChained(items, drafts); + const previous = try d.gpa.alloc(u32, items.len); + defer d.gpa.free(previous); + const values = try d.gpa.alloc(f32, state.vocabulary); + defer d.gpa.free(values); + var second_bank = false; + for (0..deepest) |step| { + { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + for (items, 0..) |item, i| { + if (step >= item.depth) continue; + const s = try d.slot(i); + if (step == 0) { + d.encodeBlock(e, s, .{ .lane = item.lane, .rings = item.rings, .from = item.from, .end = item.anchor }, item.pending, item.depth); + previous[i] = item.pending; + } + d.recurrent(e, s, step, previous[i], second_bank); + } + e.end(); + cb.commit(); + try failed(cb, if (step == 0) "block" else "recurrent step"); + } + for (items, drafts, 0..) |item, *out, i| { + if (step >= item.depth) continue; + const raw = (try d.slot(i)).logits.slice(u16, state.vocabulary); + for (raw, values) |bits, *value| value.* = @bitCast(@as(u32, bits) << 16); + const base_position = std.math.cast(u32, item.position) orelse return error.DraftDepth; + const position = std.math.add(u32, base_position, @intCast(step)) catch return error.DraftDepth; + previous[i] = try gpu_rule.sample(d.gpa, values, item.sampling, position, null); + if (previous[i] >= state.vocabulary) return error.DraftNonfinite; + out[step] = previous[i]; + } + second_bank = !second_bank; + } + } +}; + +test "Mini taps and block depth match checkpoint section eight" { + try std.testing.expectEqualSlices(u32, &.{ 5, 23, 41, 48 }, &host.taps); + try std.testing.expectEqual(@as(u32, 48), host.taps[3]); + try std.testing.expectEqual(@as(u32, 7), hold_depth); + try std.testing.expectEqual(@as(u32, state.block), host.block); +} + +test "the host's score bytes hold the tensor-unit partials from 1,024 tokens up, and the floor holds them below" { + for ([_]usize{ 1024, 1025, 4096, 65536, 262144, 1 << 20 }) |n| try std.testing.expect(host.scoreBytes(n) >= k.unitsBytes(n / k.units_chunk + 2)); + for ([_]usize{ 1, 255, 256, 1023 }) |n| try std.testing.expect(units_floor >= k.unitsBytes(@max(n, 1024) / k.units_chunk + 2)); +} diff --git a/zig/src/families/inkling2/metal/dspark_fold.zig b/zig/src/families/inkling2/metal/dspark_fold.zig new file mode 100644 index 00000000000..04b5a787a05 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_fold.zig @@ -0,0 +1,103 @@ +//! One-time binary64 folding of DSpark's rank-256 hidden head into the target unembedding. +const std = @import("std"); +const bf = @import("bf16_round"); + +pub const hidden = 2304; +pub const rank = 256; +pub const vocabulary = 201024; + +pub fn value(h: u16) f64 { + const x: f32 = @bitCast(@as(u32, h) << 16); + return x; +} + +/// The reference's binary64 dot, rounded once through binary32 to BF16. +pub fn dot(u: []const f64, w: []const f64) u16 { + std.debug.assert(u.len == w.len); + var sum: f64 = 0; + for (u, w) |x, y| sum += x * y; + return bf.bits(@floatCast(sum)); +} + +const Work = struct { + unembed: []const u16, + hidden_w: []const f64, + hidden_b: []const f64, + phi: []u16, + beta: []u16, + begin: usize, + end: usize, + + fn run(w: *const Work) void { + var u: [hidden]f64 = undefined; + for (w.begin..w.end) |v| { + for (&u, w.unembed[v * hidden ..][0..hidden]) |*x, h| x.* = value(h); + for (0..rank) |r| w.phi[v * rank + r] = dot(&u, w.hidden_w[r * hidden ..][0..hidden]); + w.beta[v] = dot(&u, w.hidden_b); + } + } +}; + +/// Φ[v,r] = bf16(f32(f64(U[v]) · f64(hidden_out[:,r]))), β[v] likewise for its bias. +pub fn fold( + a: std.mem.Allocator, + unembed: []const u16, + hidden_weight: []const u16, + hidden_bias: []const u16, + phi: []u16, + beta: []u16, +) !void { + const v = beta.len; + if (unembed.len != v * hidden or hidden_weight.len != hidden * rank or hidden_bias.len != hidden or phi.len != v * rank or v == 0) + return error.DSparkFoldShape; + const hw = try a.alloc(f64, hidden * rank); + defer a.free(hw); + const hb = try a.alloc(f64, hidden); + defer a.free(hb); + for (hidden_weight, 0..) |h, i| hw[(i % rank) * hidden + i / rank] = value(h); + for (hb, hidden_bias) |*x, h| x.* = value(h); + + const count = @min(@as(usize, 8), v); + const chunk = (v + count - 1) / count; + var work: [8]Work = undefined; + var threads: [8]?std.Thread = @splat(null); + for (0..count) |i| { + const begin = @min(i * chunk, v); + const end = @min(begin + chunk, v); + work[i] = .{ .unembed = unembed, .hidden_w = hw, .hidden_b = hb, .phi = phi, .beta = beta, .begin = begin, .end = end }; + threads[i] = std.Thread.spawn(.{}, Work.run, .{&work[i]}) catch null; + if (threads[i] == null) work[i].run(); + } + for (threads) |thread| if (thread) |t| t.join(); +} + +test "the binary64 fold does not collapse a discriminating binary32 intermediate" { + var u: [4]f64 = @splat(0); + u[0] = 1; + u[1] = 0x1p-8; + u[2] = 0x1p-24; + u[3] = 0x1p-24; + const w: [4]f64 = @splat(1); + const got = bf.value(dot(&u, &w)); + try std.testing.expectEqual(@as(f32, 1.0078125), got); + var sum: f32 = 0; + for (u, w) |x, y| sum += @as(f32, @floatCast(x * y)); + try std.testing.expectEqual(@as(f32, 1), bf.value(bf.bits(sum))); +} + +test "fold checks every published shape" { + var u: [hidden]u16 = @splat(0); + var w: [hidden * rank]u16 = @splat(0); + var p: [rank]u16 = undefined; + var b: [1]u16 = undefined; + try std.testing.expectError(error.DSparkFoldShape, fold(std.testing.allocator, &.{}, &w, &u, &p, &b)); + try fold(std.testing.allocator, &u, &w, &u, &p, &b); + for (p) |x| try std.testing.expectEqual(@as(u16, 0), x); + try std.testing.expectEqual(@as(u16, 0), b[0]); + u[1] = bf.bits(1); + w[rank + 2] = bf.bits(1); // hidden row 1, rank column 2 in the checkpoint's row-major layout + try fold(std.testing.allocator, &u, &w, &u, &p, &b); + try std.testing.expectEqual(bf.bits(1), p[2]); + try std.testing.expectEqual(bf.bits(1), b[0]); + for (p, 0..) |x, r| if (r != 2) try std.testing.expectEqual(@as(u16, 0), x); +} diff --git a/zig/src/families/inkling2/metal/dspark_kernels.zig b/zig/src/families/inkling2/metal/dspark_kernels.zig new file mode 100644 index 00000000000..d6d65528338 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_kernels.zig @@ -0,0 +1,318 @@ +//! Mini DSpark's fixed-shape arithmetic: Metal entry points and exact launch ABIs. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); + +pub const hidden: u32 = 2304; +pub const query_width: u32 = 3072; +pub const kv_width: u32 = 1024; +pub const block_rows: u32 = 8; +pub const rank: u32 = 256; +pub const rnn_width: u32 = 768; +pub const intermediate: u32 = 9216; +pub const vocab: u32 = 200058; +pub const Ref = @import("inkling2_metal_ref").Ref; +pub const PositionArgs = extern struct { base: u32 }; +pub const ContextArgs = extern struct { base: u32, rows: u32, ring: u32 }; +pub const AttentionArgs = extern struct { committed: u32, ring: u32, local: u32, from: u32 }; +pub const UnitsArgs = extern struct { committed: u32, ring: u32, first: u32, chunk: u32, chunks: u32 }; +/// The keys a threadgroup of the tensor-unit attention takes: a multiple of 64. +pub const units_chunk: u32 = 256; +pub const TokenArgs = extern struct { token: u32 }; +pub const CountArgs = extern struct { count: u32 }; +pub const BaseArgs = extern struct { rows: u32, vocab: u32 }; + +/// Round through binary32 and nearest-even BF16, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) @truncate((bits >> 16) | 0x40) else @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +/// Rotate-half RoPE partner is d+64 below the midpoint and d-64 above it. +pub fn ropeRotateHalf(x: f32, other: f32, d: u32, angle: f32) f32 { + return if (d < 64) x * @cos(angle) - other * @sin(angle) else other * @sin(angle) + x * @cos(angle); +} + +/// Every recurrent blend operation rounds independently to model precision. +pub fn recurrentBlend(gamma: f32, candidate: f32, previous: f32) f64 { + const keep: f32 = @floatCast(roundBf16(@as(f32, 1.0 - gamma))); + const left: f32 = @floatCast(roundBf16(@as(f32, gamma * previous))); + const right: f32 = @floatCast(roundBf16(@as(f32, keep * candidate))); + return roundBf16(@as(f32, left + right)); +} + +/// Folded bias and base each round before the target-style softcap. +pub fn foldedLogit(base_value: f32, beta: f32, dot: f32) f64 { + const bias: f32 = @floatCast(roundBf16(@as(f32, beta + dot))); + const logit: f32 = @floatCast(roundBf16(@as(f32, base_value + bias))); + return roundBf16(@as(f32, 30.0) * std.math.tanh(logit / @as(f32, 30.0))); +} +pub const ResidualArgs = extern struct { init: u32 }; + +pub const Kind = enum { + init_rows, + fuse_taps, + block_qkv, + context_kv, + attention, + residual_norm, + swiglu, + kappa, + recurrent, + base, + logits, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .init_rows => "tf_ink2_dspark_init_rows", + .fuse_taps => "tf_ink2_dspark_fuse_taps", + .block_qkv => "tf_ink2_dspark_block_qkv", + .context_kv => "tf_ink2_dspark_context_kv", + .attention => "tf_ink2_dspark_attention", + .residual_norm => "tf_ink2_dspark_residual_norm", + .swiglu => "tf_ink2_dspark_swiglu", + .kappa => "tf_ink2_dspark_kappa", + .recurrent => "tf_ink2_dspark_recurrent", + .base => "tf_ink2_dspark_base", + .logits => "tf_ink2_dspark_logits", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + inline else => |v| std.fmt.comptimePrint("metal inkling2 dspark {s} {s}", .{ @tagName(v), comptime v.symbol() }), + }; + } +}; + +pub const Pipelines = struct { + init_rows: mtl.Pipeline, + fuse_taps: mtl.Pipeline, + block_qkv: mtl.Pipeline, + context_kv: mtl.Pipeline, + attention: mtl.Pipeline, + residual_norm: mtl.Pipeline, + swiglu: mtl.Pipeline, + kappa: mtl.Pipeline, + recurrent: mtl.Pipeline, + base: mtl.Pipeline, + logits: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.inkling2_dspark); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var out: Pipelines = undefined; + var loaded: usize = 0; + errdefer inline for (@typeInfo(Pipelines).@"struct".field_names, 0..) |name, i| { + if (loaded > i) @field(out, name).deinit(); + }; + inline for (@typeInfo(Pipelines).@"struct".field_names, 0..) |name, i| { + @field(out, name) = try mtl.Pipeline.init(device, lib, @as(Kind, @fromBackingInt(@intCast(i))).symbol(), false); + loaded += 1; + } + return out; + } + pub fn deinit(p: *Pipelines) void { + inline for (@typeInfo(Pipelines).@"struct".field_names) |name| @field(p, name).deinit(); + p.* = undefined; + } +}; + +/// The greedy chain's two kernels, outside `Pipelines`: its entries are the block's `Kind`s one for one. +pub const Chain = struct { + step: mtl.Pipeline, + pick: mtl.Pipeline, + + pub fn load(device: mtl.Device, text: []const u8) !Chain { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const step = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_chain_step", false); + errdefer step.deinit(); + return .{ .step = step, .pick = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_chain_pick", false) }; + } + pub fn deinit(c: *Chain) void { + c.pick.deinit(); + c.step.deinit(); + c.* = undefined; + } +}; + +/// The block attention on the tensor units, outside `Pipelines`: a chunk's partial sums, then their fold. +pub const Units = struct { + partials: mtl.Pipeline, + merge: mtl.Pipeline, + + pub fn load(device: mtl.Device, text: []const u8) !Units { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const partials = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_attn_units", false); + errdefer partials.deinit(); + return .{ .partials = partials, .merge = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_attn_merge", false) }; + } + pub fn deinit(u: *Units) void { + u.merge.deinit(); + u.partials.deinit(); + u.* = undefined; + } +}; + +/// The first key a block reads and the chunks its retained context spans. +pub fn unitsSpan(committed: u32, local: bool, from: u32) struct { first: u32, chunks: u32 } { + const first = @max(from, if (local and committed > 1024) committed - 1024 else 0); + return .{ .first = first, .chunks = if (committed == first) 0 else (committed - 1) / units_chunk - first / units_chunk + 1 }; +} + +/// The partial store a block's attention needs: a float pair and 128 sums a (row, head) and chunk. +pub fn unitsBytes(chunks: usize) usize { + return 8 * 24 * chunks * (8 + 128 * 4); +} + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { + for (refs, 0..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} +fn groups(e: mtl.ComputeEncoder, count: usize, width: usize) void { + e.dispatchGroups(mtl.Size.of(count, 1, 1), mtl.Size.of(width, 1, 1)); +} +fn threads(e: mtl.ComputeEncoder, count: usize, width: usize) void { + e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(width, 1, 1)); +} + +/// Row zero copies the target's normalized anchor; the other seven rows copy the raw mask embedding. +pub fn initializeRows(p: *const Pipelines, e: mtl.ComputeEncoder, anchor: Ref, mask_embed: Ref, out: Ref) void { + e.setPipeline(p.init_rows); + bind(e, &.{ anchor, mask_embed, out }); + groups(e, block_rows, 256); +} + +/// Input taps are [row][tap][H], output c is [fusion][row][H], and newest_f is one [H] row. +pub fn fuseTaps(p: *const Pipelines, e: mtl.ComputeEncoder, taps: Ref, fuse_weight: Ref, norm_weight: Ref, c: Ref, newest_f: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.fuse_taps); + bind(e, &.{ taps, fuse_weight, norm_weight, c, newest_f }); + e.setValue(CountArgs{ .count = rows }, 5); + groups(e, 4 * @as(usize, rows), 256); +} + +/// Raw projections become per-head RMS-normalized rotate-half Q/K and an unchanged BF16 V. +pub fn blockQkv(p: *const Pipelines, e: mtl.ComputeEncoder, q_raw: Ref, k_raw: Ref, v_raw: Ref, q_norm: Ref, k_norm: Ref, q: Ref, k: Ref, v: Ref, base_position: u32) void { + e.setPipeline(p.block_qkv); + bind(e, &.{ q_raw, k_raw, v_raw, q_norm, k_norm, q, k, v }); + e.setValue(PositionArgs{ .base = base_position }, 8); + groups(e, 8 * 40, 128); +} + +/// Context K/V is written at absolute-position modulo ring_capacity for committed rows only. +pub fn commitContext(p: *const Pipelines, e: mtl.ComputeEncoder, k_raw: Ref, v_raw: Ref, k_norm_ctx: Ref, keys: Ref, values: Ref, base_position: u32, rows: u32, ring_capacity: u32) void { + std.debug.assert(rows > 0 and ring_capacity > 0); + e.setPipeline(p.context_kv); + bind(e, &.{ k_raw, v_raw, k_norm_ctx, keys, values }); + e.setValue(ContextArgs{ .base = base_position, .rows = rows, .ring = ring_capacity }, 5); + groups(e, @as(usize, rows) * 8, 128); +} + +/// Scores is FP32 scratch sized 8*24*(retained_context+8); global layers retain all context. +pub fn attend(p: *const Pipelines, e: mtl.ComputeEncoder, q: Ref, block_k: Ref, block_v: Ref, context_k: Ref, context_v: Ref, scores: Ref, out: Ref, committed: u32, ring_capacity: u32, local: bool, from: u32) void { + std.debug.assert(ring_capacity > 0 and from <= committed); + e.setPipeline(p.attention); + bind(e, &.{ q, block_k, block_v, context_k, context_v, scores, out }); + e.setValue(AttentionArgs{ .committed = committed, .ring = ring_capacity, .local = @intFromBool(local), .from = from }, 7); + groups(e, 8 * 24, 128); +} + +/// `attend` on the tensor units; `partials` is FP32 scratch of `unitsBytes` of the context's chunks. +pub fn attendUnits(u: *const Units, e: mtl.ComputeEncoder, q: Ref, block_k: Ref, block_v: Ref, context_k: Ref, context_v: Ref, partials: Ref, out: Ref, committed: u32, ring_capacity: u32, local: bool, from: u32) void { + std.debug.assert(ring_capacity > 0 and ring_capacity % 64 == 0 and from <= committed); + const span = unitsSpan(committed, local, from); + const args = UnitsArgs{ .committed = committed, .ring = ring_capacity, .first = span.first, .chunk = units_chunk, .chunks = span.chunks }; + const sums = Ref{ .buf = partials.buf, .off = partials.off + 8 * 24 * @as(usize, span.chunks) * 8 }; + if (span.chunks != 0) { + e.setPipeline(u.partials); + bind(e, &.{ q, context_k, context_v, sums, partials }); + e.setValue(args, 5); + e.dispatchGroups(mtl.Size.of(span.chunks, 8, 1), mtl.Size.of(64, 1, 1)); + } + mergeUnits(u, e, q, block_k, block_v, partials, out, args); +} + +/// The fold alone: the block's own keys, then the partials of `args.chunks` chunks in order. +pub fn mergeUnits(u: *const Units, e: mtl.ComputeEncoder, q: Ref, block_k: Ref, block_v: Ref, partials: Ref, out: Ref, args: UnitsArgs) void { + const sums = Ref{ .buf = partials.buf, .off = partials.off + 8 * 24 * @as(usize, args.chunks) * 8 }; + e.setPipeline(u.merge); + bind(e, &.{ q, block_k, block_v, sums, partials, out }); + e.setValue(args, 6); + groups(e, 8 * 24, 128); +} + +/// Normalization consumes the FP32 residual sum, independently of the rounded BF16 residual store. +pub fn residualNorm(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, residual: Ref, weight: Ref, new_residual: Ref, normalized: Ref, rows: u32, init: bool) void { + std.debug.assert(rows > 0); + e.setPipeline(p.residual_norm); + bind(e, &.{ x, residual, weight, new_residual, normalized }); + e.setValue(ResidualArgs{ .init = @intFromBool(init) }, 5); + groups(e, rows, 256); +} + +/// Gate and up projections are BF16 rows with 9216 entries; only this SwiGLU product is stored here. +pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, gate: Ref, up: Ref, out: Ref, count: u32) void { + std.debug.assert(count == 8 * intermediate); + e.setPipeline(p.swiglu); + bind(e, &.{ gate, up, out }); + e.setValue(CountArgs{ .count = count }, 3); + threads(e, count, 256); +} + +/// Kappa is FP32 [rows][768], using RNN columns 512..2815 for y and 2816..5119 for newest_f. +pub fn kappa(p: *const Pipelines, e: mtl.ComputeEncoder, y: Ref, newest_f: Ref, rnn_weight: Ref, rnn_bias: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0 and rows <= 7); + e.setPipeline(p.kappa); + bind(e, &.{ y, newest_f, rnn_weight, rnn_bias, out }); + e.setValue(CountArgs{ .count = rows }, 5); + threads(e, @as(usize, rows) * rnn_width, 256); +} + +/// One recurrent step writes rounded Z, the next BF16 state and BF16 lambda for rows 1..7 in turn. +pub fn recurrentStep(p: *const Pipelines, e: mtl.ComputeEncoder, state: Ref, kappa_row: Ref, rnn_weight: Ref, markov_w1: Ref, z: Ref, next_state: Ref, lambda: Ref, previous_token: u32) void { + e.setPipeline(p.recurrent); + bind(e, &.{ state, kappa_row, rnn_weight, markov_w1, z, next_state, lambda }); + e.setValue(TokenArgs{ .token = previous_token }, 7); + threads(e, rank, 256); +} + +/// recurrentStep on the token `held[step]` holds: the chain's previous draft, read on the GPU. +pub fn chainStep(c: *const Chain, e: mtl.ComputeEncoder, state: Ref, kappa_row: Ref, rnn_weight: Ref, markov_w1: Ref, z: Ref, next_state: Ref, lambda: Ref, held: Ref, step: u32) void { + e.setPipeline(c.step); + bind(e, &.{ state, kappa_row, rnn_weight, markov_w1, z, next_state, lambda }); + e.setValue(TokenArgs{ .token = step }, 7); + e.setBuffer(held.buf, held.off, 8); + threads(e, rank, 256); +} + +/// held[step + 1] = the first greatest of a row of final logits: one threadgroup of 1,024. +pub fn chainPick(c: *const Chain, e: mtl.ComputeEncoder, logits: Ref, held: Ref, step: u32) void { + e.setPipeline(c.pick); + bind(e, &.{ logits, held }); + e.setValue(TokenArgs{ .token = step }, 2); + groups(e, 1, 1024); +} + +/// Raw U*y rows round once to BF16, with no target unembedding softcap. +pub fn base(p: *const Pipelines, e: mtl.ComputeEncoder, unembed: Ref, y: Ref, out: Ref, rows: u32, vocabulary_count: u32) void { + std.debug.assert(rows > 0 and vocabulary_count > 0 and vocabulary_count <= vocab); + e.setPipeline(p.base); + bind(e, &.{ unembed, y, out }); + e.setValue(BaseArgs{ .rows = rows, .vocab = vocabulary_count }, 3); + std.debug.assert(rows <= 7); + groups(e, (@as(usize, vocabulary_count) + 7) / 8, 256); +} +/// Folded Phi/beta correction and target-style 30 tanh softcap, restricted to Mini's 200058 logits. +pub fn finalLogits(p: *const Pipelines, e: mtl.ComputeEncoder, base_values: Ref, phi: Ref, beta: Ref, lambda: Ref, out: Ref) void { + e.setPipeline(p.logits); + bind(e, &.{ base_values, phi, beta, lambda, out }); + e.setValue(CountArgs{ .count = vocab }, 5); + threads(e, vocab, 256); +} diff --git a/zig/src/families/inkling2/metal/dspark_kernels_test.zig b/zig/src/families/inkling2/metal/dspark_kernels_test.zig new file mode 100644 index 00000000000..6da89b8b598 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_kernels_test.zig @@ -0,0 +1,167 @@ +//! Host-only FP64 witnesses for Mini DSpark rounding, pairing, reach and launch contracts. +const std = @import("std"); +const k = @import("dspark_kernels.zig"); +const records = @import("core").contract.inkling2_dspark_metal_records.records; +const shader = @import("inkling2_metal").inkling2_dspark; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} +fn bf(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) @truncate((bits >> 16) | 0x40) else @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const out: f32 = @bitCast(@as(u32, rounded) << 16); + return out; +} +fn f32v(v: f64) f64 { + return @as(f32, @floatCast(v)); +} + +test "DSpark symbols, records, ABIs and disabled contraction are exact" { + for (std.enums.values(k.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + const width: u32 = switch (kind) { + .block_qkv, .context_kv, .attention => 128, + else => 256, + }; + try t.expectEqual(width, record.threads); + try t.expectEqual(record.threads, record.reserved); + const threadgroup: u32 = switch (kind) { + .fuse_taps => 32, + .block_qkv, .context_kv, .residual_norm => 16, + .attention => 528, + else => 0, + }; + try t.expectEqual(threadgroup, record.tg_memory); + } + try t.expectEqual(@as(usize, 4), @sizeOf(k.PositionArgs)); + try t.expectEqual(@as(usize, 12), @sizeOf(k.ContextArgs)); + try t.expectEqual(@as(usize, 16), @sizeOf(k.AttentionArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.ResidualArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.TokenArgs)); + try t.expectEqual(@as(usize, 4), @sizeOf(k.CountArgs)); + try t.expectEqual(@as(usize, 8), @sizeOf(k.BaseArgs)); + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "DSP_SCALE = 0x1.6a09e6p-4f") != null); +} + +test "raw base projection rounds the dot without applying target softcap" { + const unembed: [k.hidden]f32 = @splat(1); + const y: [k.hidden]f32 = @splat(1); + var dot: f32 = 0; + for (unembed, y) |u, v| dot += u * v; + try near(2304, bf(dot)); + try near(30, bf(30.0 * std.math.tanh(dot / 30.0))); + try t.expect(std.mem.indexOf(u8, shader, "kernel void tf_ink2_dspark_base") != null); +} + +test "fusion rounds each softmax alpha through BF16 before ordered FP32 taps" { + const weights = [_]f64{ 0, 0.5, -0.25, 2 }; + const taps = [_]f64{ 303.2126159667969, -170.3546905517578, 454.9715576171875, -93.47307586669922 }; + var expv: [4]f64 = undefined; + var den: f64 = 0; + for (weights, 0..) |w, j| { + expv[j] = @exp(w - 2); + den += expv[j]; + } + var rounded: f32 = 0; + var raw: f32 = 0; + for (0..4) |j| { + const a = f32v(expv[j] / f32v(den)); + const alpha: f32 = @floatCast(bf(a)); + rounded += alpha * @as(f32, @floatCast(taps[j])); + raw += @as(f32, @floatCast(a)) * @as(f32, @floatCast(taps[j])); + } + try t.expect(bf(rounded) != bf(raw)); + var ordered: f32 = 0; + for (0..4) |j| ordered += @as(f32, @floatCast(bf(f32v(expv[j] / f32v(den))))) * @as(f32, @floatCast(taps[j])); + try t.expectEqual(ordered, rounded); +} + +test "residual normalized output sees sigma rather than rounded BF16 storage" { + const x: f32 = 1.0; + const res: f32 = 0.00390625; + const sigma: f32 = x + res; + const stored = bf(sigma); + const weight = 0.0; + const scale: f32 = 1.00390625; + const from_sigma = bf(sigma * scale); + const from_store = bf(@as(f32, @floatCast(stored)) * scale); + try t.expect(from_sigma != from_store); + try near(@as(f64, weight) + 1, 1.0); +} + +test "rotate-half RoPE pairs d with d plus 64 at absolute positions" { + const x = [_]f64{ 1, 2 }; + const angle = std.math.pi / 2.0; + const first = x[0] * @cos(angle) - x[1] * @sin(angle); + const second = x[0] * @sin(angle) + x[1] * @cos(angle); + try near(-2, first); + try near(1, second); + try t.expect(@abs(second - (-1)) > 1); + try t.expect(@abs(k.ropeRotateHalf(1, 2, 0, @floatCast(angle)) - @as(f32, @floatCast(first))) < 2e-6); + try t.expect(@abs(k.ropeRotateHalf(2, 1, 64, @floatCast(angle)) - @as(f32, @floatCast(second))) < 2e-6); +} + +test "local reach starts at committed minus 1024 without crossing a restored lower bound" { + const committed: usize = 1027; + const from: usize = 5; + const local_first = @max(from, committed - 1024); + const global_first = from; + try t.expectEqual(@as(usize, 5), local_first); + try t.expectEqual(@as(usize, 1022 + 8), committed - local_first + 8); + try t.expectEqual(committed - from + 8, committed - global_first + 8); + for (0..8) |row| { + const position = 5000 + row; + try t.expectEqual(position, 5000 + row); + } +} + +test "recurrence rounds z activations and every state operation through BF16" { + const gamma: f32 = @floatCast(bf(@as(f32, 0.431640625))); + const candidate: f32 = @floatCast(bf(@as(f32, 0.030029296875))); + const previous: f32 = -14.5625; + const keep: f32 = @floatCast(bf(1.0 - gamma)); + const left: f32 = @floatCast(bf(gamma * previous)); + const right: f32 = @floatCast(bf(keep * candidate)); + const stepped = bf(left + right); + const unrounded = bf(@as(f32, gamma) * previous + (1.0 - @as(f32, gamma)) * candidate); + try t.expect(stepped != unrounded); + try near(stepped, bf(@as(f32, left + right))); + try near(stepped, k.recurrentBlend(gamma, candidate, previous)); + const z = bf(@as(f32, 0.33333334)); + const lambda = bf(std.math.tanh(z)); + try near(lambda, bf(std.math.tanh(z))); +} + +test "folded correction rounds bias then logits before the thirty softcap" { + const beta: f32 = 0.125; + const dot: f32 = 0.0001; + const base: f32 = 40.0; + const bias: f32 = @floatCast(bf(beta + dot)); + const logit: f32 = @floatCast(bf(base + bias)); + const capped = bf(30.0 * std.math.tanh(logit / 30.0)); + const uncapped = bf(@as(f32, 30.0) * @as(f32, @floatCast(std.math.tanh(logit / 30.0)))); + try near(capped, uncapped); + try near(capped, k.foldedLogit(base, beta, dot)); + const no_bias_round: f32 = @floatCast(bf(base + (beta + dot))); + try t.expect(logit != no_bias_round); + try t.expect(@abs(capped) < @abs(logit)); + const saturated = bf(30.0 * std.math.tanh(@as(f64, 1000) / 30.0)); + try t.expect(saturated <= 30 and saturated > 29.9); +} + +test "the tensor-unit attention spans the kept keys in whole chunks, and none without a key" { + try t.expectEqual(@as(u32, 0), k.unitsSpan(0, false, 0).chunks); + try t.expectEqual(@as(u32, 0), k.unitsSpan(700, false, 700).chunks); + try t.expectEqual(@as(u32, 1), k.unitsSpan(1, false, 0).chunks); + try t.expectEqual(@as(u32, 3), k.unitsSpan(2 * k.units_chunk + 1, false, 0).chunks); + const sliding = k.unitsSpan(5000, true, 3); + try t.expectEqual(@as(u32, 3976), sliding.first); + try t.expectEqual((4999 / k.units_chunk) - (3976 / k.units_chunk) + 1, sliding.chunks); + try t.expectEqual(@as(u32, 4000), k.unitsSpan(5000, true, 4000).first); + try t.expectEqual(@as(usize, 8 * 24 * 2 * 520), k.unitsBytes(2)); +} diff --git a/zig/src/families/inkling2/metal/dspark_state.zig b/zig/src/families/inkling2/metal/dspark_state.zig new file mode 100644 index 00000000000..f3978599b4d --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_state.zig @@ -0,0 +1,120 @@ +//! Fixed eight-row DSpark scratch and a stream's context rings; the shared lane host sizes and books them. +const std = @import("std"); +const mtl = @import("metal"); + +pub const hidden = 2304; +pub const query = 3072; +pub const kv = 1024; +pub const intermediate = 9216; +pub const rank = 256; +pub const vocabulary = 200058; +pub const block = 8; +pub const absorb_rows = 64; + +const fields = [_][]const u8{ + "ids", "resid", "next_resid", "x", "y", "q_raw", "k_raw", "v_raw", "q", "kb", "vb", "attn", + "gate", "up", "act", "base", "fused", "ck", "cv", "kappa", "state", "next_state", "z", "lambda", + "logits", +}; + +fn sizes() [fields.len]usize { + const r = block; + const a = absorb_rows; + const b = 2; + return .{ + r * 4, r * hidden * b, r * hidden * b, r * hidden * b, r * hidden * b, + r * query * b, r * kv * b, r * kv * b, r * query * b, r * kv * b, + r * kv * b, r * query * b, r * intermediate * b, r * intermediate * b, r * intermediate * b, + (r - 1) * 201024 * b, 4 * a * hidden * b, a * kv * b, a * kv * b, (r - 1) * 3 * rank * 4, + rank * b, rank * b, 3 * rank * b, rank * b, vocabulary * b, + }; +} + +pub fn scratchBytes() usize { + var bytes: usize = 0; + for (sizes()) |n| bytes += n; + return bytes; +} + +pub const Scratch = struct { + ids: mtl.Buffer, + resid: mtl.Buffer, + next_resid: mtl.Buffer, + x: mtl.Buffer, + y: mtl.Buffer, + q_raw: mtl.Buffer, + k_raw: mtl.Buffer, + v_raw: mtl.Buffer, + q: mtl.Buffer, + kb: mtl.Buffer, + vb: mtl.Buffer, + attn: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + act: mtl.Buffer, + base: mtl.Buffer, + fused: mtl.Buffer, + ck: mtl.Buffer, + cv: mtl.Buffer, + kappa: mtl.Buffer, + state: mtl.Buffer, + next_state: mtl.Buffer, + z: mtl.Buffer, + lambda: mtl.Buffer, + logits: mtl.Buffer, + + pub fn init(device: mtl.Device) !Scratch { + @setEvalBranchQuota(10_000); + const ns = sizes(); + var s: Scratch = undefined; + var made: usize = 0; + errdefer inline for (fields, 0..) |f, i| if (i < made) @field(s, f).deinit(); + inline for (fields, 0..) |f, i| { + @field(s, f) = try device.buffer(@max(ns[i], 16), mtl.ResourceOptions.shared); + made += 1; + } + return s; + } + + pub fn deinit(s: *Scratch) void { + inline for (fields) |f| @field(s, f).deinit(); + s.* = undefined; + } +}; +/// One stream's K and V rings of the drafter's three layers, and its newest target row. +pub const Lane = struct { + k: [3]mtl.Buffer, + v: [3]mtl.Buffer, + newest: mtl.Buffer, + + pub fn init(device: mtl.Device, rings: [3]usize) !Lane { + var l: Lane = .{ .k = undefined, .v = undefined, .newest = undefined }; + var made: usize = 0; + errdefer { + for (0..made) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + } + } + for (rings, 0..) |ring, i| { + const bytes = ring * kv * 2; + l.k[i] = try device.buffer(bytes, mtl.ResourceOptions.private); + l.v[i] = device.buffer(bytes, mtl.ResourceOptions.private) catch |err| { + l.k[i].deinit(); + return err; + }; + made += 1; + } + l.newest = try device.buffer(hidden * 2, mtl.ResourceOptions.private); + return l; + } + + pub fn deinit(l: *Lane) void { + l.newest.deinit(); + for (0..3) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + } + l.* = undefined; + } +}; diff --git a/zig/src/families/inkling2/metal/dspark_weights.zig b/zig/src/families/inkling2/metal/dspark_weights.zig new file mode 100644 index 00000000000..00082911738 --- /dev/null +++ b/zig/src/families/inkling2/metal/dspark_weights.zig @@ -0,0 +1,174 @@ +//! Validated mtp.safetensors weights and the one-time folded Markov output head. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const cfg = @import("../config.zig"); +const Model = @import("model.zig").Model; +const fold = @import("dspark_fold.zig"); + +pub const hidden = 2304; +pub const query = 3072; +pub const kv = 1024; +pub const intermediate = 9216; +pub const rank = 256; +pub const vocabulary = 201024; + +pub const Layer = struct { + dflare: ck.Tensor, + input_norm: ck.Tensor, + post_norm: ck.Tensor, + q_norm: ck.Tensor, + k_norm: ck.Tensor, + k_norm_ctx: ck.Tensor, + q: ck.Tensor, + k: ck.Tensor, + v: ck.Tensor, + k_ctx: ck.Tensor, + v_ctx: ck.Tensor, + o: ck.Tensor, + gate: ck.Tensor, + up: ck.Tensor, + down: ck.Tensor, +}; + +pub const Weights = struct { + fuse: ck.Tensor, + mask: ck.Tensor, + norm: ck.Tensor, + markov_norm: ck.Tensor, + hidden_out: ck.Tensor, + hidden_bias: ck.Tensor, + markov_w1: ck.Tensor, + rnn: ck.Tensor, + rnn_bias: ck.Tensor, + layers: [3]Layer, +}; + +pub const Loaded = struct { + checkpoint: ck.Checkpoint, + weights: Weights, + dflare: mtl.Buffer, // four H-wide rows: three layers, then the Markov head + phi: mtl.Buffer, // [201024,256] BF16, folded once in binary64 + beta: mtl.Buffer, // [201024] BF16 + + pub fn deinit(l: *Loaded) void { + l.beta.deinit(); + l.phi.deinit(); + l.dflare.deinit(); + l.checkpoint.deinit(); + l.* = undefined; + } + + pub fn fixedBytes(l: *const Loaded) u64 { + return l.checkpoint.residentBytes() + l.dflare.length() + l.phi.length() + l.beta.length(); + } +}; + +fn require(t: ck.Tensor, dims: []const usize, _: []const u8) !ck.Tensor { + if (t.dtype != .bf16 or t.rank != dims.len) { + return error.DSparkTensorShape; + } + var count: usize = 1; + for (dims, 0..) |d, i| { + if (t.shape[i] != d) { + return error.DSparkTensorShape; + } + count = std.math.mul(usize, count, d) catch return error.DSparkTensorShape; + } + if (t.bytes != count * 2) return error.DSparkTensorShape; + return t; +} + +fn get(c: *const ck.Checkpoint, name: []const u8, dims: []const usize) !ck.Tensor { + const t = c.get(name) catch { + std.log.err("DSpark mtp.safetensors is missing {s}", .{name}); + return error.DSparkMissingTensor; + }; + return require(t, dims, name); +} + +fn admit(c: *const cfg.Config) !void { + const m = c.mtp orelse return error.DSparkNotConfigured; + if (m.layers != 3 or m.q_heads != 24 or m.kv_heads != 8 or m.head_dim != 128 or m.inter != intermediate or + m.window != 1024 or m.block != 8 or m.rank != rank or m.rope_theta != 1e6 or m.taps_n != 4 or + !m.local[0] or m.local[1] or !m.local[2] or !std.mem.eql(u32, m.taps[0..4], &.{ 5, 23, 41, 48 })) + return error.UnsupportedDSparkConfig; +} + +fn layer(c: *const ck.Checkpoint, i: usize) !Layer { + var b: [128]u8 = undefined; + const g = struct { + fn layerTensor(cp: *const ck.Checkpoint, buf: []u8, i_: usize, suffix: []const u8, dims: []const usize) !ck.Tensor { + const name = try std.fmt.bufPrint(buf, "layers.{d}.{s}", .{ i_, suffix }); + return get(cp, name, dims); + } + }.layerTensor; + return .{ + .dflare = try g(c, &b, i, "dflare_norm.weight", &.{hidden}), + .input_norm = try g(c, &b, i, "input_layernorm.weight", &.{hidden}), + .post_norm = try g(c, &b, i, "post_attention_layernorm.weight", &.{hidden}), + .q_norm = try g(c, &b, i, "self_attn.q_norm.weight", &.{128}), + .k_norm = try g(c, &b, i, "self_attn.k_norm.weight", &.{128}), + .k_norm_ctx = try g(c, &b, i, "self_attn.k_norm_ctx.weight", &.{128}), + .q = try g(c, &b, i, "self_attn.q_proj.weight", &.{ query, hidden }), + .k = try g(c, &b, i, "self_attn.k_proj.weight", &.{ kv, hidden }), + .v = try g(c, &b, i, "self_attn.v_proj.weight", &.{ kv, hidden }), + .k_ctx = try g(c, &b, i, "self_attn.k_proj_ctx.weight", &.{ kv, hidden }), + .v_ctx = try g(c, &b, i, "self_attn.v_proj_ctx.weight", &.{ kv, hidden }), + .o = try g(c, &b, i, "self_attn.o_proj.weight", &.{ hidden, query }), + .gate = try g(c, &b, i, "mlp.gate_proj.weight", &.{ intermediate, hidden }), + .up = try g(c, &b, i, "mlp.up_proj.weight", &.{ intermediate, hidden }), + .down = try g(c, &b, i, "mlp.down_proj.weight", &.{ hidden, intermediate }), + }; +} + +pub fn load(gpa: std.mem.Allocator, target: *const Model, dir: []const u8) !Loaded { + try admit(&target.config); + var checkpoint = ck.Checkpoint.init(gpa); + errdefer checkpoint.deinit(); + const path: [:0]u8 = if (std.mem.endsWith(u8, dir, ".safetensors")) + try std.fmt.allocPrintSentinel(gpa, "{s}", .{dir}, 0) + else + try std.fmt.allocPrintSentinel(gpa, "{s}/mtp.safetensors", .{dir}, 0); + defer gpa.free(path); + checkpoint.addFile(target.device, path, "") catch |err| { + std.log.err("DSpark cannot open {s}: {s}", .{ path, @errorName(err) }); + return error.DSparkMissingFile; + }; + const c = &checkpoint; + var layers: [3]Layer = undefined; + for (&layers, 0..) |*l, i| l.* = try layer(c, i); + const weights: Weights = .{ + .fuse = try get(c, "fuse_weight", &.{ 4, 4 }), + .mask = try get(c, "mask_embed", &.{hidden}), + .norm = try get(c, "norm.weight", &.{hidden}), + .markov_norm = try get(c, "markov_head.dflare_norm.weight", &.{hidden}), + .hidden_out = try get(c, "markov_head.hidden_out.weight", &.{ hidden, rank }), + .hidden_bias = try get(c, "markov_head.hidden_out.bias", &.{hidden}), + .markov_w1 = try get(c, "markov_head.markov_w1.weight", &.{ vocabulary, rank }), + .rnn = try get(c, "markov_head.rnn_proj.weight", &.{ 3 * rank, 2 * hidden + 2 * rank }), + .rnn_bias = try get(c, "markov_head.rnn_proj.bias", &.{3 * rank}), + .layers = layers, + }; + const dflare = try target.device.buffer(4 * hidden * 2, mtl.ResourceOptions.shared); + errdefer dflare.deinit(); + const dflare_packed = dflare.slice(u16, 4 * hidden); + for (weights.layers, 0..) |l, i| @memcpy(dflare_packed[i * hidden ..][0..hidden], l.dflare.host(u16)); + @memcpy(dflare_packed[3 * hidden ..][0..hidden], weights.markov_norm.host(u16)); + const phi = try target.device.buffer(vocabulary * rank * 2, mtl.ResourceOptions.shared); + errdefer phi.deinit(); + const beta = try target.device.buffer(vocabulary * 2, mtl.ResourceOptions.shared); + errdefer beta.deinit(); + try fold.fold(gpa, target.weights.unembed.host(u16), weights.hidden_out.host(u16), weights.hidden_bias.host(u16), phi.slice(u16, vocabulary * rank), beta.slice(u16, vocabulary)); + return .{ .checkpoint = checkpoint, .weights = weights, .dflare = dflare, .phi = phi, .beta = beta }; +} + +test "a misshapen DSpark tensor has a named refusal" { + if (comptime @import("builtin").os.tag != .macos) return error.SkipZigTest; + var t: ck.Tensor = .{ .buffer = undefined, .offset = 0, .bytes = 8, .dtype = .bf16, .rank = 1 }; + t.shape[0] = 4; + _ = try require(t, &.{4}, "witness"); + try std.testing.expectError(error.DSparkTensorShape, require(t, &.{ 2, 2 }, "witness")); + t.dtype = .f32; + try std.testing.expectError(error.DSparkTensorShape, require(t, &.{4}, "witness")); +} diff --git a/zig/src/families/inkling2/metal/experts.zig b/zig/src/families/inkling2/metal/experts.zig new file mode 100644 index 00000000000..9662e36c2e2 --- /dev/null +++ b/zig/src/families/inkling2/metal/experts.zig @@ -0,0 +1,291 @@ +//! Real Metal dispatch for Inkling 2 Mini's M3 NVFP4/MXFP8 routed experts. +const std = @import("std"); +const mtl = @import("metal"); +const src = @import("inkling2_metal"); +const plan = @import("experts_plan.zig"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const Format = plan.Format; +pub const Call = plan.Call; +pub const Operation = enum { nvfp4_gu, nvfp4_down, mxfp8_gu, mxfp8_down, nvfp4_quantize, mxfp8_quantize, combine, group, nvfp4_gu_grouped, nvfp4_down_grouped, mxfp8_gu_grouped, mxfp8_down_grouped }; + +pub const function_names = [_][:0]const u8{ + "tf_ink2_nvfp4_gu", + "tf_ink2_nvfp4_down", + "tf_ink2_mxfp8_gu", + "tf_ink2_mxfp8_down", + "tf_ink2_nvfp4_quantize", + "tf_ink2_mxfp8_quantize", + "tf_ink2_combine", + "tf_ink2_group", + "tf_ink2_nvfp4_gu_grouped", + "tf_ink2_nvfp4_down_grouped", + "tf_ink2_mxfp8_gu_grouped", + "tf_ink2_mxfp8_down_grouped", +}; + +/// The columns the units kernels read a row: experts_units.metal's INK2_GU_K and INK2_DOWN_K. +const units_gu_k = 2304; +const units_down_k = 1152; +const units_names = [_][:0]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units", "tf_ink2_logits_units", "tf_ink2_dense_units", "tf_ink2_nvfp4_gu_units_t", "tf_ink2_nvfp4_down_units_t", "tf_ink2_mxfp8_gu_units_t", "tf_ink2_mxfp8_down_units_t" }; +/// A chunk of more rows than this gives an expert enough pairs for the turned tiles, 32 pairs a band. +const turned_rows: u32 = 512; + +/// A chunk of at least this many rows runs grouped by expert; a row's sums are the same either way. +pub const grouped_rows: u32 = 8; +const group_cap: u32 = 1024; + +pub const Pipelines = struct { + entries: [function_names.len]mtl.Pipeline, + /// Each expert's count, then its route pairs: launches in one encoder run in order, so they share it. + groups: mtl.Buffer, + /// The gate-up and down products on the tensor units (NVFP4 then MXFP8), where the GPU has them. + units: ?[units_names.len]mtl.Pipeline = null, + + pub fn load(device: mtl.Device) !Pipelines { + var out = try loadSource(device, src.experts); + errdefer out.deinit(); + if (device.tensorUnits()) try out.loadUnits(device, src.experts_units); + return out; + } + + /// The tensor-unit kernels from `text`; the contract's controls pass an edited one. The GPU must have the units. + pub fn loadUnits(p: *Pipelines, device: mtl.Device, text: []const u8) !void { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var pipes: [units_names.len]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for (units_names, &pipes) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + p.units = pipes; + } + + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var out: Pipelines = undefined; + var made: usize = 0; + errdefer for (out.entries[0..made]) |pipe| pipe.deinit(); + for (function_names, 0..) |name, i| { + out.entries[i] = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + const scalar = std.mem.endsWith(u8, name, "quantize") or std.mem.endsWith(u8, name, "group"); + if (out.entries[i].maxThreads() < @as(usize, if (scalar) 32 else 256)) return error.ExpertThreads; + } + out.groups = try device.buffer((plan.expert_count + plan.expert_count * group_cap) * @sizeOf(u32), mtl.ResourceOptions.shared); + out.units = null; + return out; + } + + pub fn deinit(p: *Pipelines) void { + if (p.units) |pipes| for (pipes) |pipe| pipe.deinit(); + p.groups.deinit(); + for (p.entries) |pipe| pipe.deinit(); + } + + fn get(p: *const Pipelines, op: Operation) mtl.Pipeline { + return p.entries[@backingInt(op)]; + } +}; + +fn args(c: Call) plan.MatrixArgs { + return .{ .k = c.k, .n = c.n, .topk = c.topk, .experts = c.experts }; +} + +fn launch(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, groups: u32) void { + e.setPipeline(p.get(op)); + e.dispatchGroups(mtl.Size.of(groups, 1, 1), mtl.Size.of(32, 1, 1)); +} + +fn launchGrid(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, g: plan.Geometry) void { + e.setPipeline(p.get(op)); + e.dispatchGroups(mtl.Size.of(g.outputs, g.pairs, 1), mtl.Size.of(g.threads, 1, 1)); +} + +/// Packed NVFP4 GU: X [rows,k], ids [rows,topk], Y [rows*topk,n]. +pub fn nvfp4Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .nvfp4) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ x, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 7); + launchGrid(p, e, .nvfp4_gu, plan.geometry(c)); +} + +/// Packed MXFP8 GU with UE8M0 scales per row/block32. +pub fn mxfp8Gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .mxfp8) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ x, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 5); + launchGrid(p, e, .mxfp8_gu, plan.geometry(c)); +} + +pub fn nvfp4Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, amax: Ref, denominator: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .nvfp4) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ act, w, scales, amax, denominator, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 7); + launchGrid(p, e, .nvfp4_down, plan.geometry(c)); +} + +pub fn mxfp8Down(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, ids: Ref, out: Ref, c: Call) !void { + if (c.format != .mxfp8) return error.WrongExpertFormat; + try plan.check(c); + for ([_]Ref{ act, w, scales, ids, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 5); + launchGrid(p, e, .mxfp8_down, plan.geometry(c)); +} + +/// Decode one expert matrix to BF16, not an activation quantization operation. +pub fn nvfp4Quantize(p: *const Pipelines, e: mtl.ComputeEncoder, w: Ref, scales: Ref, amax: Ref, denominator: Ref, out: Ref, rows: u32, k: u32) !void { + if (k == 0 or k % 16 != 0 or rows == 0) return error.BadExpertBlock; + for ([_]Ref{ w, scales, amax, denominator, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(plan.DecodeArgs{ .rows = rows, .k = k }, 5); + launch(p, e, .nvfp4_quantize, (rows * k + 31) / 32); +} + +pub fn mxfp8Quantize(p: *const Pipelines, e: mtl.ComputeEncoder, w: Ref, scales: Ref, out: Ref, rows: u32, k: u32) !void { + if (k == 0 or k % 32 != 0 or rows == 0) return error.BadExpertBlock; + for ([_]Ref{ w, scales, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(plan.DecodeArgs{ .rows = rows, .k = k }, 3); + launch(p, e, .mxfp8_quantize, (rows * k + 31) / 32); +} + +/// Sum per-token BF16 down outputs in ascending expert index and round once to BF16. +pub fn combine(p: *const Pipelines, e: mtl.ComputeEncoder, down: Ref, ids: Ref, weights: Ref, out: Ref, c: Call) !void { + try plan.check(c); + for ([_]Ref{ down, ids, weights, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(args(c), 4); + launchGrid(p, e, .combine, plan.combineGeometry(c)); +} + +const GroupArgs = extern struct { pairs: u32, experts: u32, cap: u32 }; +const GroupedArgs = extern struct { k: u32, n: u32, topk: u32, cap: u32 }; + +fn groupedArgs(c: Call) GroupedArgs { + return .{ .k = c.k, .n = c.n, .topk = c.topk, .cap = group_cap }; +} + +fn counts(p: *const Pipelines) Ref { + return .{ .buf = p.groups }; +} + +fn members(p: *const Pipelines) Ref { + return .{ .buf = p.groups, .off = plan.expert_count * @sizeOf(u32) }; +} + +fn launchGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, op: Operation, c: Call) void { + e.setPipeline(p.get(op)); + e.dispatchGroups(mtl.Size.of((c.n + 7) / 8, c.experts, 1), mtl.Size.of(256, 1, 1)); +} + +/// Each expert's route pairs for the grouped launches that follow; at most 1,024 rows. +pub fn group(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, c: Call) !void { + try plan.check(c); + if (c.rows > group_cap or c.experts != plan.expert_count) return error.BadExpertShape; + for ([_]Ref{ ids, counts(p), members(p) }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(GroupArgs{ .pairs = c.rows * c.topk, .experts = c.experts, .cap = group_cap }, 3); + e.setPipeline(p.get(.group)); + e.dispatchThreads(mtl.Size.of(c.experts, 1, 1), mtl.Size.of(32, 1, 1)); +} + +/// gu after group: the same outputs, each expert's weight blocks decoded once a pass of four rows. +pub fn guGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?struct { amax: Ref, denominator: Ref }, out: Ref, c: Call) !void { + try plan.check(c); + switch (c.format) { + .nvfp4 => { + const g = nv_globals orelse return error.MissingNvfp4Globals; + for ([_]Ref{ x, w, scales, g.amax, g.denominator, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 8); + launchGrouped(p, e, .nvfp4_gu_grouped, c); + }, + .mxfp8 => { + for ([_]Ref{ x, w, scales, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 6); + launchGrouped(p, e, .mxfp8_gu_grouped, c); + }, + } +} + +const Globals = struct { amax: Ref, denominator: Ref }; + +/// gu, or the down products (`down`), after group on the tensor units: an op is 16 of an expert's pairs by 32 rows. +pub fn units(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + return launchUnits(p, e, down, c.rows > turned_rows, x, w, scales, nv_globals, out, c); +} + +/// The same products on the turned tiles, 16 rows by 32 of an expert's pairs an op: the same sums, for wide chunks. +pub fn unitsTurned(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + return launchUnits(p, e, down, true, x, w, scales, nv_globals, out, c); +} + +fn launchUnits(p: *const Pipelines, e: mtl.ComputeEncoder, down: bool, turned: bool, x: Ref, w: Ref, scales: Ref, nv_globals: ?Globals, out: Ref, c: Call) !void { + try plan.check(c); + const pipes = p.units orelse return error.NoTensorUnits; + // Gate and up rows interleave, so gu has two weight rows an output; the kernels fix the columns of each product. + const weight_rows = if (down) c.n else 2 * c.n; + if (c.k != @as(u32, if (down) units_down_k else units_gu_k) or weight_rows % 32 != 0) return error.BadExpertShape; + switch (c.format) { + .nvfp4 => { + const g = nv_globals orelse return error.MissingNvfp4Globals; + for ([_]Ref{ x, w, scales, g.amax, g.denominator, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 8); + e.setPipeline(pipes[(if (turned) @as(usize, 6) else 0) + @intFromBool(down)]); + }, + .mxfp8 => { + for ([_]Ref{ x, w, scales, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 6); + e.setPipeline(pipes[(if (turned) @as(usize, 6) else 0) + 2 + @as(usize, @intFromBool(down))]); + }, + } + e.dispatchGroups(mtl.Size.of(if (turned) weight_rows / 16 else (weight_rows + 31) / 32, c.experts, 1), mtl.Size.of(256, 1, 1)); +} + +const LogitArgs = extern struct { rows: u32, vocab: u32 }; +/// Rows of h against the vocabulary on the tensor units: fp32 out[row][v], bf16-rounded and capped as the glue's. +pub fn logitsUnits(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, unembed: Ref, out: Ref, rows: u32, vocab: u32) !void { + const pipes = p.units orelse return error.NoTensorUnits; + for ([_]Ref{ h, unembed, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(LogitArgs{ .rows = rows, .vocab = vocab }, 3); + e.setPipeline(pipes[4]); + e.dispatchGroups(mtl.Size.of((vocab + 31) / 32, (rows + 15) / 16, 1), mtl.Size.of(256, 1, 1)); +} + +const DenseArgs = extern struct { rows: u32, n: u32, k: u32 }; +/// A prompt's rows of x [rows][k] against a bf16 weight [n][k] on the tensor units; k is 2,304 or 3,072. +pub fn denseUnits(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, out: Ref, rows: u32, n: u32, k: u32) !void { + const pipes = p.units orelse return error.NoTensorUnits; + if ((k != 2304 and k != 3072) or rows == 0 or n == 0) return error.BadExpertShape; + for ([_]Ref{ x, w, out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(DenseArgs{ .rows = rows, .n = n, .k = k }, 3); + e.setPipeline(pipes[5]); + e.dispatchGroups(mtl.Size.of((n + 31) / 32, (rows + 15) / 16, 1), mtl.Size.of(256, 1, 1)); +} + +/// The down products after group, as guGrouped. +pub fn downGrouped(p: *const Pipelines, e: mtl.ComputeEncoder, act: Ref, w: Ref, scales: Ref, nv_globals: ?struct { amax: Ref, denominator: Ref }, out: Ref, c: Call) !void { + try plan.check(c); + switch (c.format) { + .nvfp4 => { + const g = nv_globals orelse return error.MissingNvfp4Globals; + for ([_]Ref{ act, w, scales, g.amax, g.denominator, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 8); + launchGrouped(p, e, .nvfp4_down_grouped, c); + }, + .mxfp8 => { + for ([_]Ref{ act, w, scales, counts(p), members(p), out }, 0..) |b, i| e.setBuffer(b.buf, b.off, i); + e.setValue(groupedArgs(c), 6); + launchGrouped(p, e, .mxfp8_down_grouped, c); + }, + } +} + +pub fn gu(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, w: Ref, scales: Ref, nv_globals: ?struct { amax: Ref, denominator: Ref }, ids: Ref, out: Ref, c: Call) !void { + switch (c.format) { + .nvfp4 => if (nv_globals) |g| return nvfp4Gu(p, e, x, w, scales, g.amax, g.denominator, ids, out, c) else return error.MissingNvfp4Globals, + .mxfp8 => return mxfp8Gu(p, e, x, w, scales, ids, out, c), + } +} diff --git a/zig/src/families/inkling2/metal/experts_plan.zig b/zig/src/families/inkling2/metal/experts_plan.zig new file mode 100644 index 00000000000..c493e848da3 --- /dev/null +++ b/zig/src/families/inkling2/metal/experts_plan.zig @@ -0,0 +1,109 @@ +//! Pure M3 layout, decode and activation math shared by the host and its scalar tests. +const std = @import("std"); + +pub const hidden: u32 = 2304; +pub const intermediate: u32 = 1152; +pub const expert_count: u32 = 128; +pub const top_k: u32 = 8; + +pub const Format = enum { + nvfp4, + mxfp8, + + pub fn block(f: Format) u32 { + return if (f == .nvfp4) 16 else 32; + } + pub fn codeBytes(f: Format, k: u32) u32 { + return if (f == .nvfp4) k / 2 else k; + } +}; + +pub const Call = struct { + rows: u32, + k: u32, + n: u32, + experts: u32 = expert_count, + topk: u32 = top_k, + format: Format, +}; + +pub const Geometry = struct { + outputs: u32, + pairs: u32, + threads: u32 = 256, +}; + +/// A product's grid: eight outputs a threadgroup (one simdgroup each) by one route pair. +pub fn geometry(c: Call) Geometry { + return .{ .outputs = (c.n + 7) / 8, .pairs = c.rows * c.topk }; +} + +/// The combine's grid: 256 outputs a threadgroup (one thread each) by one token. +pub fn combineGeometry(c: Call) Geometry { + return .{ .outputs = (c.n + 255) / 256, .pairs = c.rows }; +} + +pub fn check(c: Call) !void { + if (c.rows == 0 or c.k == 0 or c.n == 0 or c.experts == 0 or c.topk == 0 or c.topk > c.experts) + return error.BadExpertShape; + if (c.k % c.format.block() != 0 or (c.format == .nvfp4 and c.k % 2 != 0)) + return error.BadExpertBlock; +} + +pub fn formatForLayer(layer: u32) !Format { + if (layer < 20) return .nvfp4; + if (layer < 24) return .mxfp8; + return error.BadExpertLayer; +} + +pub fn roundBf16(v: f32) f32 { + const bits: u32 = @bitCast(v); + const rounded: u16 = if (std.math.isNan(v)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + return @bitCast(@as(u32, rounded) << 16); +} + +pub fn e2m1(code: u8) f32 { + const values = [_]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const v = values[code & 7]; + return if (code & 8 != 0) -v else v; +} + +pub fn e4m3(code: u8) f32 { + const exponent = (code >> 3) & 15; + const mantissa = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f32); + const value = if (exponent == 0) + @as(f32, @floatFromInt(mantissa)) / 512.0 + else + std.math.ldexp(@as(f32, 1) + @as(f32, @floatFromInt(mantissa)) / 8.0, @as(i32, exponent) - 7); + return if (code & 0x80 != 0) -value else value; +} + +pub fn phi(amax: f32, denominator: f32) f32 { + return roundBf16(amax) / roundBf16(denominator); +} + +pub fn nvWeight(codes: u8, column: u32, scale: u8, factor: f32) f32 { + const code = if (column & 1 != 0) codes >> 4 else codes & 15; + return roundBf16(e2m1(code) * e4m3(scale) * factor); +} + +pub fn mxWeight(value: u8, scale: u8) f32 { + return roundBf16(std.math.ldexp(e4m3(value), @as(i32, scale) - 127)); +} + +pub fn softcap(x: f32, cap: f32) f32 { + return @floatCast(@as(f64, cap) * std.math.tanh(@as(f64, x) / @as(f64, cap))); +} + +/// Inputs are the two already-BF16-rounded GU results; the result rounds once at the end. +pub fn swiglu(gate: f32, up: f32) f32 { + const left = softcap(gate, 4) * (1 / (1 + std.math.exp(-gate))); + return roundBf16(left * softcap(up, 25)); +} + +pub const MatrixArgs = extern struct { k: u32, n: u32, topk: u32, experts: u32 }; +pub const DecodeArgs = extern struct { rows: u32, k: u32 }; diff --git a/zig/src/families/inkling2/metal/experts_test.zig b/zig/src/families/inkling2/metal/experts_test.zig new file mode 100644 index 00000000000..1be0e3d54e2 --- /dev/null +++ b/zig/src/families/inkling2/metal/experts_test.zig @@ -0,0 +1,147 @@ +//! Host-only M3 format, layout, BF16-rounding and dispatch-geometry tests. +const std = @import("std"); +const p = @import("experts_plan.zig"); + +fn bf16Chain(terms: []const f32, stride: usize, first: usize) f32 { + var sum: f32 = 0; + var i = first; + while (i < terms.len) : (i += stride) sum = p.roundBf16(sum + p.roundBf16(terms[i])); + return sum; +} + +fn bf16Halves(terms: []const f32) f32 { + if (terms.len == 0) return 0; + if (terms.len == 1) return p.roundBf16(terms[0]); + const mid = terms.len / 2; + return p.roundBf16(bf16Halves(terms[0..mid]) + bf16Halves(terms[mid..])); +} + +fn bf16Strided(terms: []const f32) f32 { + var lanes: [32]f32 = @splat(0); + for (&lanes, 0..) |*lane, i| lane.* = bf16Chain(terms, 32, i); + return bf16Halves(&lanes); +} + +test "Mini layer formats and dimensions are a clean cut at layer 20" { + for (0..20) |layer| try std.testing.expectEqual(p.Format.nvfp4, try p.formatForLayer(@intCast(layer))); + for (20..24) |layer| try std.testing.expectEqual(p.Format.mxfp8, try p.formatForLayer(@intCast(layer))); + try std.testing.expectError(error.BadExpertLayer, p.formatForLayer(24)); + try std.testing.expectEqual(@as(u32, 2304), p.hidden); + try std.testing.expectEqual(@as(u32, 1152), p.intermediate); + try std.testing.expectEqual(@as(u32, 128), p.expert_count); + try std.testing.expectEqual(@as(u32, 8), p.top_k); +} + +test "every E2M1 code decodes low/high nibble and signed zero" { + const magnitude = [_]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + for (0..16) |code| { + const want = if (code & 8 != 0) -magnitude[code & 7] else magnitude[code & 7]; + try std.testing.expectEqual(want, p.e2m1(@intCast(code))); + } + const byte: u8 = 0xa7; // low 7 = 6, high 10 = -1 + try std.testing.expectEqual(@as(f32, 6), p.nvWeight(byte, 0, 0x38, 1)); + try std.testing.expectEqual(@as(f32, -1), p.nvWeight(byte, 1, 0x38, 1)); + try std.testing.expectEqual(@as(f32, 0), p.e2m1(8)); +} + +test "all E4M3 values match the independent half-bit decode" { + for (0..256) |raw| { + const code: u8 = @intCast(raw); + const h: f16 = @bitCast(@as(u16, code & 0x7f) << 7); + const magnitude = @as(f32, h) * 256; + const want = if ((code & 0x80) != 0) -magnitude else magnitude; + const got = p.e4m3(code); + // E4M3FN reserves 0x7f for NaN; the half-bit helper alone does not encode that case. + if ((code & 0x7f) == 0x7f) { + try std.testing.expect(std.math.isNan(got)); + } else try std.testing.expectEqual(want, got); + } +} + +test "NVFP4 globals round to BF16 before one FP32 division" { + const amax: f32 = @bitCast(@as(u32, 0x3f80_8001)); + const den: f32 = @bitCast(@as(u32, 0x4534_0001)); + const rounded_den = p.roundBf16(den); + try std.testing.expect(den != rounded_den); + try std.testing.expectEqual(p.roundBf16(amax) / rounded_den, p.phi(amax, den)); + try std.testing.expect(p.phi(amax, den) != amax / den); // A2: the reference rounds both loader inputs. + const raw = p.e2m1(7) * p.e4m3(0x40) * p.phi(amax, den); + try std.testing.expectEqual(p.roundBf16(raw), p.nvWeight(7, 0, 0x40, p.phi(amax, den))); +} + +test "every MXFP8 value and UE8M0 exponent is exactly BF16 decoded" { + for ([_]u8{ 0, 1, 126, 127, 128, 129, 254, 255 }) |scale| for (0..256) |raw| { + const code: u8 = @intCast(raw); + const want = std.math.ldexp(p.e4m3(code), @as(i32, scale) - 127); + if (std.math.isNan(want)) { + try std.testing.expect(std.math.isNan(p.mxWeight(code, scale))); + } else try std.testing.expectEqual(p.roundBf16(want), p.mxWeight(code, scale)); + }; +} + +test "GU BF16 round precedes cap sigmoid cap and final BF16 activation" { + const raw_gate: f32 = -10; + const raw_up: f32 = -9.4; + const g = p.roundBf16(raw_gate); + const u = p.roundBf16(raw_up); + const capped_g: f64 = 4 * std.math.tanh(@as(f64, g) / 4); + const sigmoid: f64 = 1 / (1 + @exp(-@as(f64, g))); + const capped_u: f64 = 25 * std.math.tanh(@as(f64, u) / 25); + const wide = capped_g * sigmoid * capped_u; + try std.testing.expectEqual(@as(f32, @floatCast(@import("bf16_round").bf16(wide))), p.swiglu(g, u)); + try std.testing.expect(p.swiglu(raw_gate, raw_up) != p.swiglu(g, u)); +} + +test "combine route control overflows slot order while ascending experts remain finite" { + const values = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; + const weights = [_]f32{ 0x1p127, 0x1p126, -0x1p127 / 3.0, 0.25, -0.2, 1.0 / 3.0, -2.0 / 7.0, 0.375 }; + var terms: [8]f32 = undefined; + for (&terms, values, weights) |*term, value, weight| term.* = value * weight; + var route_sum: f32 = 0; + for (terms) |term| route_sum += term; + try std.testing.expect(std.math.isInf(route_sum) and route_sum > 0); + + const ids = [_]i32{ 2, 0, 1, 7, 3, 6, 4, 5 }; + var expert_sum: f32 = 0; + for (0..8) |expert| for (0..8) |slot| if (ids[slot] == expert) { + expert_sum += terms[slot]; + }; + try std.testing.expect(std.math.isFinite(expert_sum) and expert_sum > 0); +} + +test "eight-term combine stress separates FP32 and BF16 in every contract order" { + const terms = [_]f32{ 1024, 1, 1, 1, 1, 1, 1, -1029 }; + var forward: f32 = 0; + var reverse: f32 = 0; + for (terms) |term| forward += term; + for (1..terms.len + 1) |n| reverse += terms[terms.len - n]; + try std.testing.expectEqual(@as(f32, 1), forward); + try std.testing.expectEqual(@as(f32, 1), reverse); + + const reduced = [_]f32{ bf16Chain(&terms, 1, 0), bf16Halves(&terms), bf16Strided(&terms) }; + for (reduced) |sum| try std.testing.expectEqual(@as(f32, -8), sum); + const exact_allowance = (3 * 0x1p-24 + 0x1p-8) + 0x1p-38; + try std.testing.expect(9.0 / exact_allowance >= 100); +} + +test "launch geometry is a simdgroup an output by route pair and validates block/layout edges" { + const nv = p.Call{ .rows = 3, .k = 2304, .n = 1152, .format = .nvfp4 }; + try p.check(nv); + try std.testing.expectEqual(@as(u32, 144), p.geometry(nv).outputs); + try std.testing.expectEqual(@as(u32, 24), p.geometry(nv).pairs); + try std.testing.expectEqual(@as(u32, 256), p.geometry(nv).threads); + try std.testing.expectEqual(@as(u32, 5), p.combineGeometry(nv).outputs); + try std.testing.expectEqual(@as(u32, 3), p.combineGeometry(nv).pairs); + const mx = p.Call{ .rows = 1, .k = 1152, .n = 2304, .format = .mxfp8 }; + try p.check(mx); + var bad = nv; + bad.k = 17; + try std.testing.expectError(error.BadExpertBlock, p.check(bad)); + bad = nv; + bad.topk = 129; + try std.testing.expectError(error.BadExpertShape, p.check(bad)); + try std.testing.expectEqual(@as(usize, 16), @sizeOf(p.MatrixArgs)); + try std.testing.expectEqual(@as(usize, 8), @sizeOf(p.DecodeArgs)); + try std.testing.expectEqual(@as(usize, 0), @offsetOf(p.MatrixArgs, "k")); + try std.testing.expectEqual(@as(usize, 12), @offsetOf(p.MatrixArgs, "experts")); +} diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig new file mode 100644 index 00000000000..d48c920f87e --- /dev/null +++ b/zig/src/families/inkling2/metal/forward.zig @@ -0,0 +1,495 @@ +//! Mini's whole 48-visit forward, encoded entirely on Metal for prompt chunks and decode. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const layer_plan = @import("../plan.zig"); +const ap = @import("attention_plan.zig"); +const attention = @import("attention.zig"); +const glue = @import("glue.zig"); +const experts = @import("experts.zig"); +const loop = @import("loop.zig"); +const state = @import("state.zig"); +const model_file = @import("model.zig"); +const Model = model_file.Model; + +pub const Ref = state.Ref; +pub const Segment = struct { cache: *state.Cache, rows: usize }; +pub const Options = struct { + all: bool = false, + ids: ?Ref = null, + flight: ?*mtl.CommandBuffer = null, + taps: ?state.Ref = null, + /// A prompt's rows: its projections run on the tensor units where the GPU has them. + prompt: bool = false, +}; + +pub const FinalPlan = struct { work_rows: usize, logits_rows: usize, logits_row: usize, capture_rows: usize }; + +/// Features normalize all rows; without full logits, only the last unembeds. taps=null preserves the original plan. +pub fn finalPlan(rows: usize, all: bool, taps: bool) FinalPlan { + std.debug.assert(rows > 0); + return .{ + .work_rows = if (all or taps) rows else 1, + .logits_rows = if (all) rows else 1, + .logits_row = if (!all and taps) rows - 1 else 0, + .capture_rows = if (taps) rows else 0, + }; +} + +const RArgs = extern struct { count: u32, boundary: u32 = 0 }; +const NormArgs = extern struct { rows: u32, width: u32, heads: u32 = 0, bits: u32 = 0, group: u32 = 0, eps: f32 }; +const DenseArgs = extern struct { rows: u32, n: u32, k: u32, ldy: u32 }; + +fn r(t: ck.Tensor) Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} +fn at(buf: mtl.Buffer, off: usize) Ref { + return .{ .buf = buf, .off = off }; +} +fn row(buf: mtl.Buffer, i: usize, row_bytes: usize) Ref { + return at(buf, i * row_bytes); +} +fn a(x_: Ref) attention.Ref { + return .{ .buf = x_.buf, .off = x_.off }; +} +fn x(x_: Ref) experts.Ref { + return .{ .buf = x_.buf, .off = x_.off }; +} +fn l(x_: Ref) loop.Ref { + return .{ .buf = x_.buf, .off = x_.off }; +} +fn arRow(s: *state.Scratch, role: usize, rows: usize, i: usize, gated: bool) Ref { + return at(if (gated) s.gated else s.ar, (role * rows + i) * state.hidden * 4); +} +fn messageRow(s: *state.Scratch, core: usize, role: usize, i: usize) Ref { + return at(s.messages, ((i * state.message_entries + core * 4 + role) * state.hidden) * 4); +} + +fn runtime(m: *const Model, e: mtl.ComputeEncoder, op: model_file.RuntimeOp, refs: []const Ref, count: usize, boundary: usize) void { + e.setPipeline(m.runtime[@backingInt(op)]); + for (refs, 0..) |r_, i| e.setBuffer(r_.buf, r_.off, i); + e.setValue(RArgs{ .count = @intCast(count), .boundary = @intCast(boundary) }, refs.len); + e.dispatchThreads(mtl.Size.of(count, 1, 1), mtl.Size.of(256, 1, 1)); +} + +fn copyBf16(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { + runtime(m, e, .copy_bf16, &.{ from, to }, count, 0); +} +fn captureTap(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, rows: usize, channel: usize) void { + std.debug.assert(channel < state.feature_taps); + runtime(m, e, .capture_tap, &.{ from, to }, rows * state.hidden, channel); +} +fn widen(m: *const Model, e: mtl.ComputeEncoder, from: Ref, to: Ref, count: usize) void { + runtime(m, e, .widen, &.{ from, to }, count, 0); +} + +fn norm(m: *const Model, e: mtl.ComputeEncoder, input: Ref, weight: ck.Tensor, out: Ref, rows: usize) void { + e.setPipeline(m.norm); + e.setBuffer(input.buf, input.off, 0); + e.setBuffer(weight.buffer, weight.offset, 1); + e.setValue(NormArgs{ .rows = @intCast(rows), .width = state.hidden, .eps = 1e-6 }, 2); + e.setBuffer(out.buf, out.off, 3); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +/// Every projection uses the shared BF16 matvec's FP32 reduction and one BF16 store. +pub fn dense(m: *const Model, e: mtl.ComputeEncoder, weight: ck.Tensor, input: Ref, out: Ref, rows: usize) void { + const k = weight.shape[weight.rank - 1]; + const n = weight.shape[weight.rank - 2]; + var base: usize = 0; + while (base < rows) { + const left = rows - base; + // One launch of the next size up: the kernel stores only `take` rows, and reads one pass of the weights. + const take: usize = @min(left, 32); + const variant: usize = if (take > 16) 5 else if (take > 8) 4 else if (take > 4) 3 else if (take > 2) 2 else if (take > 1) 1 else 0; + e.setPipeline(m.dense[variant]); + e.setBuffer(input.buf, input.off + base * k * 2, 0); + e.setBuffer(weight.buffer, weight.offset, 1); + e.setValue(DenseArgs{ .rows = @intCast(take), .n = @intCast(n), .k = @intCast(k), .ldy = @intCast(n) }, 2); + e.setBuffer(out.buf, out.off + base * n * 2, 3); + e.dispatchGroups(mtl.Size.of((n + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); + base += take; + } +} + +/// A visit's projection: a prompt's rows on the tensor units, a round's rows as `dense`. +fn project(m: *const Model, e: mtl.ComputeEncoder, prompt: bool, weight: ck.Tensor, input: Ref, out: Ref, rows: usize) !void { + const k = weight.shape[weight.rank - 1]; + if (!prompt or m.experts.units == null or (k != 2304 and k != 3072)) return dense(m, e, weight, input, out, rows); + try experts.denseUnits(&m.experts, e, x(input), x(.{ .buf = weight.buffer, .off = weight.offset }), x(out), @intCast(rows), @intCast(weight.shape[weight.rank - 2]), @intCast(k)); +} + +/// One row because M2's AR ABI is [sources,H] -> [queries,H]. Batch composition never mixes rows. +fn residual(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, queries: ck.Tensor, sources: usize, rows: usize) void { + glue.arRows(&m.glue, e, at(s.blocks, 0), at(s.partial, 0), r(queries), at(s.mlp_ar, 0), @intCast(sources), 1, @intCast(rows)); +} + +/// Ends with a barrier: the cross-pass messages and the restored p are written. +fn bankAndReset(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, rows: usize) void { + for (0..rows) |i| { + // The second completed block of the previous pass is B12; its final p is P18. + copyBf16(m, e, at(s.blocks, (i * state.block_slots + 2) * state.hidden * 2), row(s.bank0, i, state.hidden * 2), state.hidden); + } + copyBf16(m, e, at(s.p, 0), at(s.bank1, 0), rows * state.hidden); + e.barrier(); + loop.crossPassMessageAttention(&m.loop, e, l(at(s.bank0, 0)), l(at(s.bank1, 0)), l(r(m.weights.cross_queries)), l(r(m.weights.cross_kv_queries)), l(at(s.messages, 0)), @intCast(rows)); + // The prelude p is restored, but every visit's KV and convolution state remains live. + copyBf16(m, e, at(s.prelude, 0), at(s.p, 0), rows * state.hidden); + e.barrier(); +} + +/// Ends with a barrier: the norms are written. +fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, rows: usize) void { + const lp = m.weight_plan.at(v.layer); + const w = &m.weights.layers[v.layer]; + if (v.layer == 0) { + widen(m, e, at(s.p, 0), at(s.ar, 0), rows * state.hidden); + } else { + const q = m.weights.attn_queries[v.layer - 1]; + glue.arRows(&m.glue, e, at(s.blocks, 0), at(s.partial, 0), r(q), at(s.ar, 0), lp.attn_sources, @intCast(lp.attn_queries), @intCast(rows)); + } + e.barrier(); + const gated = v.hasMessages(); + if (gated) { + const controllers = w.controllers.?; + const core = v.layer - 6; + var roles: [3]loop.Gate = undefined; + for (&roles, 0..) |*g, role| { + const c = controllers[role]; + const source_role = if (lp.kind == .local) 0 else role; + g.* = .{ .h = l(arRow(s, source_role, rows, 0, false)), .m = l(messageRow(s, core, role, 0)), .down = l(r(c.down)), .forget = l(r(c.forget)), .gain = l(r(c.gain)), .out = l(arRow(s, role, rows, 0, true)) }; + } + loop.gatesEach(&m.loop, e, &roles, @intCast(rows), state.message_entries * state.hidden); + e.barrier(); + } + // An ungated local visit has exactly one AR result and one norm result; Q/K/V alias. + if (!gated and lp.kind == .local) { + norm(m, e, arRow(s, 0, rows, 0, false), w.attn.q_norm, at(s.q_norm, 0), rows); + } else { + norm(m, e, arRow(s, 0, rows, 0, gated), w.attn.q_norm, at(s.q_norm, 0), rows); + norm(m, e, arRow(s, 1, rows, 0, gated), w.attn.k_norm, at(s.k_norm, 0), rows); + norm(m, e, arRow(s, 2, rows, 0, gated), w.attn.v_norm, at(s.v_norm, 0), rows); + } + e.barrier(); +} + +/// A stream's staged taps, which the commit reads: a chunk wider than a window stages in the scratch, one stream's. +fn staged(s: *const state.Scratch, cache: *const state.Cache, rows: usize, slot: usize, conv_state: usize, rows_before: usize) Ref { + return if (rows > state.window_rows) s.staged(slot, conv_state, rows_before) else cache.staged(slot, conv_state, rows_before); +} + +fn stagePostConv(m: *const Model, e: mtl.ComputeEncoder, s: *const state.Scratch, cache: *state.Cache, slot: usize, conv_state: usize, raw: Ref, base: usize, rows: usize) void { + const channels = state.convWidth(conv_state); + copyBf16(m, e, cache.history(slot, conv_state), staged(s, cache, rows, slot, conv_state, 0), 3 * channels); + copyBf16(m, e, at(raw.buf, raw.off + base * channels * 2), staged(s, cache, rows, slot, conv_state, 3), rows * channels); +} + +/// Every stream's attention output convolved and added to the running sum, beside the staging of its taps; a barrier. +fn attentionPartial(m: *const Model, e: mtl.ComputeEncoder, s: *const state.Scratch, segments: []const Segment, v: *const layer_plan.Visit, boundary: usize) void { + const H = state.hidden; + var base: usize = 0; + for (segments) |seg| { + stagePostConv(m, e, s, seg.cache, v.cache_slot, 2, at(s.attn_dense, 0), base, seg.rows); + runtime(m, e, .attention_partial, &.{ at(s.p, base * H * 2), seg.cache.history(v.cache_slot, 2), at(s.attn_dense, base * H * 2), r(m.weights.layers[v.layer].attn_conv), at(s.blocks, base * state.block_slots * H * 2), at(s.partial, base * H * 4) }, seg.rows * H, boundary); + base += seg.rows; + } + e.barrier(); +} + +/// Every stream's expert output convolved into the running p, which it leaves widened as the next visit's partial. +fn mlpPartial(m: *const Model, e: mtl.ComputeEncoder, s: *const state.Scratch, segments: []const Segment, v: *const layer_plan.Visit) void { + const H = state.hidden; + var base: usize = 0; + for (segments) |seg| { + const t = at(s.partial, base * H * 4); + stagePostConv(m, e, s, seg.cache, v.cache_slot, 3, at(s.mlp_out, 0), base, seg.rows); + runtime(m, e, .mlp_partial, &.{ t, seg.cache.history(v.cache_slot, 3), at(s.mlp_out, base * H * 2), r(m.weights.layers[v.layer].mlp_conv), at(s.p, base * H * 2), t }, seg.rows * H, 0); + base += seg.rows; + } + e.barrier(); +} + +/// One stream's rows of a visit's attention. +const Attend = struct { + cache: *state.Cache, + base: usize, + rows: usize, + rr: ap.Rows, + layer: ap.Layer, + meta: attention.RowMeta, + kv: attention.Cache, +}; + +/// Every stream's attention a step at a time: a step's launches run side by side, and a barrier ends each step. +fn attendSegments(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment, prompt: bool) !void { + const w = &m.weights.layers[v.layer]; + const prep = ap.Prep{ .qk_clip = m.config.text.qk_clip, .rel_clip = m.config.text.rel_clip, .floor = @floatFromInt(m.config.text.log_floor), .alpha = m.config.text.log_alpha, .eps = m.config.text.eps }; + var items: [state.max_segments]Attend = undefined; + var base: usize = 0; + for (segments, items[0..segments.len], 0..) |seg, *it, si| { + const cache = seg.cache; + const layer0 = cache.attentionLayer(&m.weight_plan, v.cache_slot, seg.rows); + it.* = .{ + .cache = cache, + .base = base, + .rows = seg.rows, + // A prompt's rows on a sliding layer: the prompt kernel, a tile of keys a chunk. + .rr = .{ .rows = @intCast(seg.rows), .heads = 24, .kv_heads = 8, .last_pos = @intCast(cache.len + seg.rows - 1), .streams = 1, .prompt = prompt and m.attention.units and layer0.window > 0 }, + .layer = .{ .window = layer0.window, .ring = @intCast(cache.ring(v.cache_slot)), .chunk = if (prompt and m.attention.units and layer0.window > 0) ap.tile_keys else layer0.chunk, .tau = layer0.tau }, + .meta = .{ .pos = a(at(s.pos, base * 4)), .seg_of = a(at(s.seg_of, base * 4)), .segs = a(at(s.segs, si * @sizeOf(ap.Seg))) }, + .kv = .{ .k = a(cache.keys(v.cache_slot)), .v = a(cache.values(v.cache_slot)) }, + }; + base += seg.rows; + } + const all = items[0..segments.len]; + for (all) |it| for ([_]bool{ true, false }) |key| stageConvInput(m, e, s, it.cache, v, it.base, key, it.rows); + for (all) |it| for ([_]bool{ true, false }) |key| convInputForAttention(m, e, s, it.cache, v, it.base, it.rows, key); + e.barrier(); + for (all) |it| { + const b = it.base; + attention.prep(&m.attention, e, it.rr, it.layer, prep, it.meta, .{ a(at(s.q_raw, b * state.query_width * 2)), a(at(s.k_conv, b * state.kv_width * 2)), a(at(s.v_conv, b * state.kv_width * 2)), a(at(s.rel_raw, b * state.rel_width * 2)) }, .{ a(r(w.attn.q_scale)), a(r(w.attn.rel_scale)) }, a(at(s.q_prep, b * state.query_width * 2)), a(at(s.rel_prep, b * state.rel_width * 2)), it.kv); + } + e.barrier(); + for (all) |it| attention.relTable(&m.attention, e, it.rr, a(at(s.rel_prep, it.base * state.rel_width * 2)), a(r(w.attn.rel_projection)), a(at(s.rel_tab, it.base * 24 * ap.extent * 2))); + e.barrier(); + for (all) |it| { + const b = it.base; + try attention.partials(&m.attention, e, it.rr, it.layer, state.max_attention_stride, 0, it.meta, a(at(s.q_prep, b * state.query_width * 2)), it.kv, a(at(s.rel_tab, b * 24 * ap.extent * 2)), a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, b * 24 * state.max_attention_stride * 8))); + } + e.barrier(); + for (all) |it| { + const b = it.base; + try attention.merge(&m.attention, e, it.rr, it.layer, state.max_attention_stride, 0, it.meta, a(at(s.part_o, b * 24 * state.max_attention_stride * ap.head_dim * 4)), a(at(s.part_ml, b * 24 * state.max_attention_stride * 8)), a(at(s.sink, b * 24 * 2)), a(at(s.gate, b * state.query_width * 2)), a(at(s.att, b * state.query_width * 2))); + } + e.barrier(); +} + +const ConvInput = struct { raw: Ref, projected: Ref, normalized: Ref, taps: Ref, old: Ref, state: usize }; + +fn convInput(s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, local_ungated: bool, base: usize, key: bool, rows: usize) ConvInput { + const cs: usize = if (key) 0 else 1; + const normalized = if (key) at(s.k_norm, 0) else if (local_ungated) at(s.q_norm, 0) else at(s.v_norm, 0); + return .{ + .raw = if (key) at(s.k_conv, base * state.kv_width * 2) else at(s.v_conv, base * state.kv_width * 2), + .projected = if (key) at(s.k_raw, base * state.kv_width * 2) else at(s.v_raw, base * state.kv_width * 2), + .normalized = at(normalized.buf, normalized.off + base * state.hidden * 2), + .taps = staged(s, cache, rows, v.cache_slot, cs, 0), + .old = cache.history(v.cache_slot, cs), + .state = cs, + }; +} + +/// A convolution's three old rows and its new rows staged for the commit, beside the convolution that reads both. +fn stageConvInput(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, key: bool, rows: usize) void { + const c = convInput(s, cache, v, !v.hasMessages() and m.weight_plan.at(v.layer).kind != .global, base, key, rows); + copyBf16(m, e, cache.history(v.cache_slot, c.state), c.taps, 3 * state.kv_width); + copyBf16(m, e, c.projected, staged(s, cache, rows, v.cache_slot, c.state, 3), rows * state.kv_width); +} + +fn convInputForAttention(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, cache: *state.Cache, v: *const layer_plan.Visit, base: usize, rows: usize, key: bool) void { + const w = &m.weights.layers[v.layer]; + const c = convInput(s, cache, v, !v.hasMessages() and m.weight_plan.at(v.layer).kind != .global, base, key, rows); + switch (if (key) w.attn.k_conv else w.attn.v_conv) { + .static => |weight| glue.convStatic(&m.glue, e, c.old, c.projected, r(weight), c.raw, @intCast(rows), state.kv_width), + .dynamic => |d| glue.convDynamic(&m.glue, e, c.old, c.projected, c.normalized, r(d.static_w), r(d.projection), c.raw, @intCast(rows), state.kv_width), + } +} + +/// The combine's output is written by the last launch: the caller's barrier follows. +fn routedExperts(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, layer: usize, rows: usize) !void { + const w = &m.weights.layers[layer]; + const precision: experts.Format = switch (m.weight_plan.at(@intCast(layer)).precision) { + .nvfp4 => .nvfp4, + .mxfp8 => .mxfp8, + }; + const gu_call = experts.Call{ .rows = @intCast(rows), .k = state.hidden, .n = state.intermediate, .format = precision }; + const down_call = experts.Call{ .rows = @intCast(rows), .k = state.intermediate, .n = state.hidden, .format = precision }; + if (m.experts.units != null) { + // On the tensor units a row's sums are the same at every width, so every chunk and window takes this path. + try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call); + e.barrier(); + if (precision == .nvfp4) { + try experts.units(&m.experts, e, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.gu, 0)), gu_call); + e.barrier(); + try experts.units(&m.experts, e, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), .{ .amax = x(r(w.down.amax.?)), .denominator = x(r(w.down.denominator.?)) }, x(at(s.down, 0)), down_call); + } else { + try experts.units(&m.experts, e, false, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.gu, 0)), gu_call); + e.barrier(); + try experts.units(&m.experts, e, true, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), null, x(at(s.down, 0)), down_call); + } + e.barrier(); + return experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + } + if (rows >= experts.grouped_rows) { + try experts.group(&m.experts, e, x(at(s.route_ids, 0)), gu_call); + e.barrier(); + if (precision == .nvfp4) { + try experts.guGrouped(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.gu, 0)), gu_call); + e.barrier(); + try experts.downGrouped(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), .{ .amax = x(r(w.down.amax.?)), .denominator = x(r(w.down.denominator.?)) }, x(at(s.down, 0)), down_call); + e.barrier(); + } else { + try experts.guGrouped(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.gu, 0)), gu_call); + e.barrier(); + try experts.downGrouped(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), null, x(at(s.down, 0)), down_call); + e.barrier(); + } + return experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); + } + if (precision == .nvfp4) { + try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), .{ .amax = x(r(w.gu.amax.?)), .denominator = x(r(w.gu.denominator.?)) }, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); + e.barrier(); + } else { + try experts.gu(&m.experts, e, x(at(s.mlp_normed, 0)), x(r(w.gu.weight)), x(r(w.gu.scale)), null, x(at(s.route_ids, 0)), x(at(s.gu, 0)), gu_call); + e.barrier(); + } + switch (precision) { + .nvfp4 => try experts.nvfp4Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(r(w.down.amax.?)), x(r(w.down.denominator.?)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), + .mxfp8 => try experts.mxfp8Down(&m.experts, e, x(at(s.gu, 0)), x(r(w.down.weight)), x(r(w.down.scale)), x(at(s.route_ids, 0)), x(at(s.down, 0)), down_call), + } + e.barrier(); + try experts.combine(&m.experts, e, x(at(s.down, 0)), x(at(s.route_ids, 0)), x(at(s.route_weights, 0)), x(at(s.mlp_out, 0)), down_call); +} + +/// A visit's launches in dependency order; a barrier follows every step a later launch reads. +fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const layer_plan.Visit, segments: []const Segment, rows: usize, taps: ?state.Ref, prompt: bool) !void { + const lp = m.weight_plan.at(v.layer); + const gated = v.hasMessages(); + if (taps) |to| { + const channel: ?usize = switch (v.cache_slot) { + 5 => 0, + 23 => 1, + 41 => 2, + else => null, + }; + if (channel) |ch| captureTap(m, e, at(s.p, 0), to, rows, ch); + } + const w = &m.weights.layers[v.layer]; + // The partial AR source is p widened, which the visit before left; a reset restores p, so it widens again. + if (v.pass > 1 and v.layer == 6) { + bankAndReset(m, e, s, rows); + widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + e.barrier(); + } + prepareAttentionInputs(m, e, s, v, rows); + const knorm = if (gated or lp.kind == .global) at(s.k_norm, 0) else at(s.q_norm, 0); + const vnorm = if (gated or lp.kind == .global) at(s.v_norm, 0) else at(s.q_norm, 0); + try project(m, e, prompt, w.attn.wq, at(s.q_norm, 0), at(s.q_raw, 0), rows); + try project(m, e, prompt, w.attn.wk, knorm, at(s.k_raw, 0), rows); + try project(m, e, prompt, w.attn.wv, vnorm, at(s.v_raw, 0), rows); + try project(m, e, prompt, w.attn.wr, at(s.q_norm, 0), at(s.rel_raw, 0), rows); + try project(m, e, prompt, w.attn.sink, at(s.q_norm, 0), at(s.sink, 0), rows); + try project(m, e, prompt, w.attn.gate, at(s.q_norm, 0), at(s.gate, 0), rows); + e.barrier(); + try attendSegments(m, e, s, v, segments, prompt); + try project(m, e, prompt, w.attn.wo, at(s.att, 0), at(s.attn_dense, 0), rows); + e.barrier(); + attentionPartial(m, e, s, segments, v, if (lp.boundary) lp.blocks_in + 1 else 0); + residual(m, e, s, m.weights.mlp_queries[v.layer], lp.mlp_sources, rows); + e.barrier(); + if (gated) { + const c = w.controllers.?[3]; + const core = v.layer - 6; + loop.gatesStrided(&m.loop, e, l(at(s.mlp_ar, 0)), l(messageRow(s, core, 3, 0)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(at(s.mlp_gated, 0)), @intCast(rows), state.message_entries * state.hidden); + e.barrier(); + norm(m, e, at(s.mlp_gated, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); + } else norm(m, e, at(s.mlp_ar, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); + e.barrier(); + glue.router(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); + e.barrier(); + try routedExperts(m, e, s, v.layer, rows); + e.barrier(); + mlpPartial(m, e, s, segments, v); + if (v.cache_slot == 5) copyBf16(m, e, at(s.p, 0), at(s.prelude, 0), rows * state.hidden); +} + +fn commitFullHistories(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, segments: []const Segment) void { + for (segments) |seg| for (0..state.visit_slots) |slot| for (0..state.conv_states) |cs| { + copyBf16(m, e, staged(s, seg.cache, seg.rows, slot, cs, seg.rows), seg.cache.history(slot, cs), 3 * state.convWidth(cs)); + }; +} + +pub fn run(m: *const Model, s: *state.Scratch, cache: *state.Cache, ids: []const u32, options: Options) !void { + return runShared(m, s, &.{.{ .cache = cache, .rows = ids.len }}, ids, options); +} + +pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, ids: []const u32, options: Options) !void { + const rows = ids.len; + if (rows == 0 or rows > s.rows or segments.len == 0 or segments.len > state.max_segments or (!options.all and segments.len != 1)) return error.Inkling2RowsExceeded; + var total: usize = 0; + var base: usize = 0; + for (segments, 0..) |seg, si| { + if (seg.rows == 0 or seg.rows > state.max_rows or seg.cache.len + seg.rows > seg.cache.capacity) return error.Inkling2ContextFull; + if (seg.rows > state.window_rows and seg.cache.pending != null) return error.Inkling2CacheTransaction; + if (seg.cache.pending) |pending| if (pending != seg.rows) return error.Inkling2CacheTransaction; + total += seg.rows; + for (0..seg.rows) |i| { + s.pos.slice(i32, rows)[base + i] = @intCast(seg.cache.len + i); + s.seg_of.slice(i32, rows)[base + i] = 0; + } + s.segs.slice(ap.Seg, state.max_segments)[si] = .{ .row0 = 0, .n = @intCast(seg.rows), .p0 = @intCast(seg.cache.len), .off = 0 }; + base += seg.rows; + } + if (total != rows) return error.Inkling2Segments; + if (options.ids == null) { + for (ids) |id| if (id >= m.config.text.vocab) return error.Inkling2Token; + @memcpy(s.ids.slice(u32, rows), ids); + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var cb = m.queue.commandBuffer(); + var e = cb.compute(.concurrent); + // Earlier parts of this forward, already committed: the GPU runs them while the host encodes the next. + var parts: [cuts.len]mtl.CommandBuffer = undefined; + var n_parts: usize = 0; + defer for (parts[0..n_parts]) |part| part.release(); + errdefer if (n_parts > 0) parts[n_parts - 1].wait(); + glue.embedNorm(&m.glue, e, options.ids orelse at(s.ids, 0), r(m.weights.embed), r(m.weights.embed_norm), at(s.p, 0), @intCast(rows)); + e.barrier(); + widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); + e.barrier(); + for (m.weight_plan.visits[0..m.weight_plan.n_visits], 0..) |*v, vi| { + try visit(m, e, s, v, segments, rows, options.taps, options.prompt); + if (n_parts < cuts.len and vi + 1 == cuts[n_parts]) { + e.end(); + cb.commit(); + parts[n_parts] = cb.retain(); + n_parts += 1; + cb = m.queue.commandBuffer(); + e = cb.compute(.concurrent); + } + } + const final = finalPlan(rows, options.all, options.taps != null); + if (final.work_rows == rows) { + glue.arRows(&m.glue, e, at(s.blocks, 0), at(s.partial, 0), r(m.weights.output_query), at(s.mlp_ar, 0), m.weight_plan.final_sources, 1, @intCast(rows)); + } else { + const i = rows - 1; + glue.ar(&m.glue, e, at(s.blocks, i * state.block_slots * state.hidden * 2), row(s.partial, i, state.hidden * 4), r(m.weights.output_query), at(s.mlp_ar, 0), m.weight_plan.final_sources, 1); + } + e.barrier(); + norm(m, e, at(s.mlp_ar, 0), m.weights.norm, at(s.mlp_normed, 0), final.work_rows); + e.barrier(); + if (options.taps) |to| captureTap(m, e, at(s.mlp_normed, 0), to, final.capture_rows, 3); + if (options.all and rows > state.batch_rows) return error.Inkling2RowsExceeded; + const logits = if (options.all) at(s.logits_all, 0) else at(segments[0].cache.logits, 0); + if (m.experts.units != null) try experts.logitsUnits(&m.experts, e, x(at(s.mlp_normed, final.logits_row * state.hidden * 2)), x(r(m.weights.unembed)), x(logits), @intCast(final.logits_rows), m.config.text.unpadded_vocab) else glue.logits(&m.glue, e, at(s.mlp_normed, final.logits_row * state.hidden * 2), r(m.weights.unembed), logits, @intCast(final.logits_rows), m.config.text.unpadded_vocab); + commitFullHistories(m, e, s, segments); + e.end(); + cb.commit(); + if (options.flight) |flight| { + flight.* = cb.retain(); + return; + } + cb.wait(); + for (parts[0..n_parts]) |part| if (part.failure()) |msg| { + std.log.err("inkling2_loop forward: {s}", .{msg}); + return error.GpuFailed; + }; + if (cb.failure()) |msg| { + std.log.err("inkling2_loop forward: {s}", .{msg}); + return error.GpuFailed; + } +} + +/// Visits after which a forward's command buffer is committed and the next begun. +const cuts = [_]usize{ 2, 12, 24, 36 }; diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig new file mode 100644 index 00000000000..c85b46d4f93 --- /dev/null +++ b/zig/src/families/inkling2/metal/glue.zig @@ -0,0 +1,168 @@ +//! Inkling 2 Mini glue on Metal: the production shader and its real encoder dispatches. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); +pub const plan = @import("inkling2_glue_plan"); + +pub const hidden: u32 = 2304; +pub const experts: u32 = 128; +pub const intermediate: u32 = 1152; +pub const top: u32 = 8; +pub const Ref = @import("inkling2_metal_ref").Ref; +const unit = mtl.Size.of(32, 1, 1); + +pub const Pipelines = struct { + embed_norm: mtl.Pipeline, + ar: mtl.Pipeline, + conv_static: mtl.Pipeline, + conv_dynamic: mtl.Pipeline, + router: mtl.Pipeline, + swiglu: mtl.Pipeline, + logits: mtl.Pipeline, + expert_pick: mtl.Pipeline, + expert_combine: mtl.Pipeline, + route_scores: mtl.Pipeline, + /// The router's dots for up to 1,024 rows; launches in one encoder run in order, so they share it. + route_dots: mtl.Buffer, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.glue); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var pipes: [10]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pipe| pipe.deinit(); + for ([_][]const u8{ + "tf_inkling2_embed_norm", + "tf_inkling2_ar", + "tf_inkling2_conv_static", + "tf_inkling2_conv_dynamic", + "tf_inkling2_router", + "tf_inkling2_swiglu", + "tf_inkling2_logits", + "tf_inkling2_expert_pick", + "tf_inkling2_expert_combine", + "tf_inkling2_route_scores", + }, &pipes) |name, *pipe| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + return .{ + .embed_norm = pipes[0], + .ar = pipes[1], + .conv_static = pipes[2], + .conv_dynamic = pipes[3], + .router = pipes[4], + .swiglu = pipes[5], + .logits = pipes[6], + .expert_pick = pipes[7], + .expert_combine = pipes[8], + .route_scores = pipes[9], + .route_dots = try device.buffer(1024 * experts * @sizeOf(f32), mtl.ResourceOptions.shared), + }; + } + pub fn deinit(p: *Pipelines) void { + inline for (@typeInfo(Pipelines).@"struct".field_names) |name| @field(p, name).deinit(); + } +}; + +const EmbedArgs = extern struct { rows: u32 }; +pub fn embedNorm(p: *const Pipelines, e: mtl.ComputeEncoder, ids: Ref, table: Ref, weight: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.embed_norm); + inline for (.{ ids, table, weight, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(EmbedArgs{ .rows = rows }, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const ARArgs = extern struct { sources: u32, queries: u32, rows: u32 }; +/// sources = completed BF16 blocks plus one unrounded F32 partial; output is one FP32 row per query. +pub fn ar(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, partial: Ref, queries: Ref, out: Ref, sources_: u32, queries_: u32) void { + arRows(p, e, blocks, partial, queries, out, sources_, queries_, 1); +} + +/// As ar for `rows` rows in one launch: blocks [row][4][H], partial [row][H], output [query][row][H]. +pub fn arRows(p: *const Pipelines, e: mtl.ComputeEncoder, blocks: Ref, partial: Ref, queries: Ref, out: Ref, sources_: u32, queries_: u32, rows: u32) void { + std.debug.assert(sources_ > 0 and sources_ <= 5 and queries_ > 0 and queries_ <= 3 and rows > 0); + e.setPipeline(p.ar); + inline for (.{ blocks, partial, queries, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ARArgs{ .sources = sources_, .queries = queries_, .rows = rows }, 4); + e.dispatchGroups(mtl.Size.of(queries_, rows, 1), mtl.Size.of(ar_threads, 1, 1)); +} + +/// The depth mix's threads a threadgroup: a row's 2,304 values, four a thread. +const ar_threads = 576; +const ConvArgs = extern struct { rows: u32, channels: u32 }; +/// A static convolution over a stream's three old rows (`old`) and the launch's `rows` rows (`fresh`). +pub fn convStatic(p: *const Pipelines, e: mtl.ComputeEncoder, old: Ref, fresh: Ref, weight: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.conv_static); + inline for (.{ old, fresh, weight, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ConvArgs{ .rows = rows, .channels = channels }, 4); + e.dispatchThreads(mtl.Size.of(channels, rows, 1), unit); +} + +/// Dynamic static_w is [lag][channel], the opposite orientation to static convolution taps. +pub fn convDynamic(p: *const Pipelines, e: mtl.ComputeEncoder, old: Ref, fresh: Ref, input: Ref, static_w: Ref, projection: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0 and channels <= 1024); + e.setPipeline(p.conv_dynamic); + inline for (.{ old, fresh, input, static_w, projection, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ConvArgs{ .rows = rows, .channels = channels }, 6); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const RouteArgs = extern struct { rows: u32 }; +/// Router IDs and weights are sorted by ascending expert index for the deterministic expert sum. +pub fn router(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: Ref, bias: Ref, ids: Ref, weights: Ref, rows: u32) void { + std.debug.assert(rows > 0); + std.debug.assert(rows <= 1024); + e.setPipeline(p.route_scores); + inline for (.{ x, weight }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(p.route_dots, 0, 2); + e.setValue(RouteArgs{ .rows = rows }, 3); + e.dispatchGroups(mtl.Size.of(experts / 8, rows, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); + e.setPipeline(p.router); + e.setBuffer(p.route_dots, 0, 0); + inline for (.{ bias, ids, weights }, 1..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(RouteArgs{ .rows = rows }, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const ActArgs = extern struct { rows: u32, width: u32 }; +pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, gu: Ref, out: Ref, rows: u32, width: u32) void { + std.debug.assert(rows > 0 and width > 0); + e.setPipeline(p.swiglu); + inline for (.{ gu, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ActArgs{ .rows = rows, .width = width }, 2); + e.dispatchThreads(mtl.Size.of(width, rows, 1), unit); +} + +const LogitArgs = extern struct { rows: u32, vocab: u32 }; +pub fn logits(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, unembed: Ref, out: Ref, rows: u32, vocab: u32) void { + std.debug.assert(rows > 0 and vocab > 0 and vocab <= 200058); + e.setPipeline(p.logits); + inline for (.{ h, unembed, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(LogitArgs{ .rows = rows, .vocab = vocab }, 3); + // A thread takes a vocabulary row for eight rows of h. + e.dispatchThreads(mtl.Size.of(vocab, (rows + 7) / 8, 1), unit); +} + +const ExpertArgs = extern struct { rows: u32, channels: u32 }; +pub fn expertPick(p: *const Pipelines, e: mtl.ComputeEncoder, all: Ref, ids: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.expert_pick); + inline for (.{ all, ids, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ExpertArgs{ .rows = rows, .channels = channels }, 3); + e.dispatchThreads(mtl.Size.of(8, channels, rows), unit); +} + +pub fn expertCombine(p: *const Pipelines, e: mtl.ComputeEncoder, picked: Ref, weights: Ref, out: Ref, rows: u32, channels: u32) void { + std.debug.assert(rows > 0 and channels > 0); + e.setPipeline(p.expert_combine); + inline for (.{ picked, weights, out }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(ExpertArgs{ .rows = rows, .channels = channels }, 3); + e.dispatchThreads(mtl.Size.of(channels, rows, 1), unit); +} diff --git a/zig/src/families/inkling2/metal/glue_plan.zig b/zig/src/families/inkling2/metal/glue_plan.zig new file mode 100644 index 00000000000..f100405d77e --- /dev/null +++ b/zig/src/families/inkling2/metal/glue_plan.zig @@ -0,0 +1,250 @@ +//! Pure Inkling 2 Mini glue launch shapes and independent FP64 arithmetic. +const std = @import("std"); + +pub const hidden = 2304; +pub const expert_count = 128; +pub const intermediate = 1152; +pub const top_k = 8; +pub const ar_scale: f64 = @as(f32, @bitCast(@as(u32, 0x3caaaaab))); + +pub const Kind = enum { + embed_norm, + ar, + conv_static, + conv_dynamic, + router, + swiglu, + logits, + expert_pick, + expert_combine, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .embed_norm => "tf_inkling2_embed_norm", + .ar => "tf_inkling2_ar", + .conv_static => "tf_inkling2_conv_static", + .conv_dynamic => "tf_inkling2_conv_dynamic", + .router => "tf_inkling2_router", + .swiglu => "tf_inkling2_swiglu", + .logits => "tf_inkling2_logits", + .expert_pick => "tf_inkling2_expert_pick", + .expert_combine => "tf_inkling2_expert_combine", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .embed_norm => "metal inkling2 glue embed_norm tf_inkling2_embed_norm", + .ar => "metal inkling2 glue ar tf_inkling2_ar", + .conv_static => "metal inkling2 glue conv_static tf_inkling2_conv_static", + .conv_dynamic => "metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", + .router => "metal inkling2 glue router tf_inkling2_router", + .swiglu => "metal inkling2 glue swiglu tf_inkling2_swiglu", + .logits => "metal inkling2 glue logits tf_inkling2_logits", + .expert_pick => "metal inkling2 glue expert_pick tf_inkling2_expert_pick", + .expert_combine => "metal inkling2 glue expert_combine tf_inkling2_expert_combine", + }; + } +}; + +pub const Call = struct { rows: usize, n: usize, k: usize }; +pub fn valid(kind: Kind, c: Call) bool { + const key_depth: usize = if (kind == .expert_combine) top_k else 4; + const max_width: usize = if (kind == .conv_dynamic) 1024 else hidden; + if (c.rows == 0 or c.rows > 1024) return false; + return switch (kind) { + .embed_norm => c.k == hidden and c.n == hidden, + .router => c.k == hidden and c.n == top_k, + .logits => c.k == hidden and c.n > 0 and c.n <= 200058, + .ar => c.k == hidden and c.n == hidden and c.rows >= 2 and c.rows <= 5, + .conv_static, .conv_dynamic, .expert_combine => c.k == key_depth and c.n > 0 and c.n <= max_width, + .swiglu => c.k == 2 and c.n > 0 and c.n <= intermediate, + .expert_pick => c.k == top_k and c.n > 0 and c.n <= hidden, + }; +} +pub fn count(kind: Kind, c: Call) usize { + const copies: usize = if (kind == .expert_pick) top_k else 1; + return c.rows * c.n * copies; +} + +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} +pub fn cap(x: f64, c: f64) f64 { + return c * std.math.tanh(x / c); +} +pub fn sigmoid(x: f64) f64 { + return 1 / (1 + std.math.exp(-x)); +} + +/// One normalized BF16 embedding result, before its final BF16 store. +pub fn embedValue(x: []const f32, weight: []const f32, d: usize) f64 { + var ss: f64 = 0; + for (x) |v| ss += @as(f64, v) * v; + const inv = 1 / @sqrt(ss / @as(f64, @floatFromInt(x.len)) + 1e-6); + return @as(f64, weight[d]) * (@as(f64, x[d]) * inv); +} + +/// Accumulation alternatives for the AR host model. Null means the independent FP64 oracle. +pub const ArAccum = enum { none, f32, f16, bf16 }; +pub const ArOrder = enum { sequential, pairwise, strided }; +pub const ArSum = struct { accum: ArAccum, order: ArOrder }; + +fn arRound(v: f64, accum: ArAccum) f64 { + return switch (accum) { + .none => v, + .f32 => @as(f32, @floatCast(v)), + .f16 => @as(f16, @floatCast(v)), + .bf16 => roundBf16(v), + }; +} +fn arChain(terms: []const f64, sim: ArSum, stride: usize, first: usize) f64 { + var total: f64 = 0; + var i = first; + while (i < terms.len) : (i += stride) total = arRound(total + arRound(terms[i], sim.accum), sim.accum); + return total; +} +fn arHalves(terms: []const f64, sim: ArSum) f64 { + if (terms.len == 0) return 0; + if (terms.len == 1) return arRound(terms[0], sim.accum); + const mid = terms.len / 2; + return arRound(arHalves(terms[0..mid], sim) + arHalves(terms[mid..], sim), sim.accum); +} +fn arSumIn(terms: []const f64, sim: ?ArSum) f64 { + if (sim) |s| return switch (s.order) { + .sequential => arChain(terms, s, 1, 0), + .pairwise => arHalves(terms, s), + .strided => blk: { + var lanes: [32]f64 = @splat(0); + for (&lanes, 0..) |*lane, i| lane.* = arChain(terms, s, 32, i); + break :blk arHalves(&lanes, s); + }, + }; + var total: f64 = 0; + for (terms) |term| total += term; + return total; +} + +/// Squares for one AR RMS reduction, optionally under a precision/order model. +pub fn arSourceSquares(blocks: []const f32, partial: []const f32, sources: usize, s: usize, sim: ?ArSum) f64 { + var terms: [hidden]f64 = undefined; + for (&terms, 0..) |*term, d| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + term.* = @as(f64, x) * x; + } + return arSumIn(&terms, sim); +} + +/// One normalized AR query dot. Its terms are in ascending hidden-coordinate order. +pub fn arQueryDot(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, s: usize, inverse: f64, sim: ?ArSum) f64 { + var terms: [hidden]f64 = undefined; + for (&terms, 0..) |*term, d| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + term.* = @as(f64, queries[q * hidden + d]) * (@as(f64, x) * inverse); + } + return arSumIn(&terms, sim); +} + +/// AR with explicitly modeled reductions; non-reduction arithmetic remains FP64. +pub fn blockResidualIn(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, sim: ?ArSum, out: []f64) void { + var inv: [5]f64 = undefined; + var weight: [5]f64 = undefined; + var peak = -std.math.inf(f64); + for (0..sources) |s| { + const ss = arSourceSquares(blocks, partial, sources, s, sim); + inv[s] = 1 / @sqrt(ss / hidden + 1e-6); + const dot = arQueryDot(blocks, partial, queries, sources, q, s, inv[s], sim); + weight[s] = dot * ar_scale; + peak = @max(peak, weight[s]); + } + var den_terms: [5]f64 = undefined; + for (0..sources) |s| { + den_terms[s] = std.math.exp(weight[s] - peak); + weight[s] = den_terms[s]; + } + const den = arSumIn(den_terms[0..sources], sim); + var terms: [5]f64 = undefined; + for (0..hidden) |d| { + for (0..sources) |s| { + const x = if (s + 1 == sources) partial[d] else blocks[s * hidden + d]; + terms[s] = weight[s] / den * (@as(f64, x) * inv[s]); + } + out[d] = arSumIn(terms[0..sources], sim); + } +} + +/// AR over BF16 blocks widened to f32 and an unrounded f32 partial. FP64 is only the oracle. +pub fn blockResidual(blocks: []const f32, partial: []const f32, queries: []const f32, sources: usize, q: usize, out: []f64) void { + blockResidualIn(blocks, partial, queries, sources, q, null, out); +} + +pub fn staticConv(taps: []const f32, weight: []const f32, channels: usize, r: usize, c: usize) f64 { + var sum: f64 = taps[(r + 3) * channels + c]; + for (0..4) |tap| sum += @as(f64, weight[c * 4 + tap]) * taps[(r + tap) * channels + c]; + return sum / @sqrt(5.0); +} + +pub fn dynamicConv(taps: []const f32, input: []const f32, static_w: []const f32, projection: []const f32, channels: usize, r: usize, c: usize) f64 { + var sum: f64 = taps[(r + 3) * channels + c]; + for (0..4) |lag| { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, projection[(4 * (c / 128) + lag) * hidden + d]) * input[r * hidden + d]; + const w = @as(f64, static_w[lag * channels + c]) + roundBf16(dot); + sum += w * taps[(r + 3 - lag) * channels + c]; + } + return sum / 3; +} + +pub const Route = struct { ids: [top_k]u32, weights: [top_k]f64 }; +pub fn route(x: []const f32, matrix: []const f32, bias: []const f32) Route { + var score: [expert_count]f64 = undefined; + var used: [expert_count]bool = @splat(false); + var out: Route = undefined; + for (0..expert_count) |e| { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, matrix[e * hidden + d]) * x[d]; + score[e] = sigmoid(dot); + } + for (0..top_k) |j| { + var best: ?usize = null; + for (0..expert_count) |e| if (!used[e]) { + if (best == null or score[e] + bias[e] > score[best.?] + bias[best.?]) best = e; + }; + out.ids[j] = @intCast(best.?); + out.weights[j] = score[best.?]; + used[best.?] = true; + } + std.mem.sort(u32, &out.ids, {}, std.sort.asc(u32)); + // Recover scores after sorting IDs, not route-order positions. + var den: f64 = 1e-20; + for (out.ids, 0..) |id, j| { + out.weights[j] = score[id]; + den += score[id]; + } + for (&out.weights) |*w| w.* = w.* / den * 8; + return out; +} + +pub fn swiglu(gate: f32, up: f32) f64 { + return cap(gate, 4) * sigmoid(gate) * cap(up, 25); +} +pub fn logit(h: []const f32, unembed: []const f32, v: usize) f64 { + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, unembed[v * hidden + d]) * h[d]; + return cap(roundBf16(dot), 30); +} +pub fn combine(picked: []const f32, weights: []const f32, channels: usize, d: usize) f64 { + var sum: f64 = 0; + for (0..top_k) |j| sum += @as(f64, weights[j]) * picked[j * channels + d]; + return sum; +} + +pub fn pick(all_experts: []const f32, ids: []const u32, channels: usize, row: usize, j: usize, d: usize) f32 { + return all_experts[(row * expert_count + ids[row * top_k + j]) * channels + d]; +} diff --git a/zig/src/families/inkling2/metal/glue_test.zig b/zig/src/families/inkling2/metal/glue_test.zig new file mode 100644 index 00000000000..f1480f33b33 --- /dev/null +++ b/zig/src/families/inkling2/metal/glue_test.zig @@ -0,0 +1,199 @@ +//! Host-only proof of Mini's glue formulas, source inventory and shape admission. +const std = @import("std"); +const p = @import("inkling2_glue_plan"); +const records = @import("core").contract.inkling2_glue_metal_records.records; +const shader = @import("inkling2_metal").glue; +const c = @import("core").contract.spec; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} + +test "glue entries have one shader, symbol, unique launch record and honest scalar reservation" { + for (std.enums.values(p.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(record.threads, record.reserved); + } + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "INKLING_AR_SCALE = 0x1.555556p-6f") != null); + try t.expectEqual(@as(u32, 256), records[@backingInt(p.Kind.conv_dynamic)].threads); + try t.expectEqual(@as(u32, 128), records[@backingInt(p.Kind.conv_dynamic)].tg_memory); +} + +test "shape admission fixes Mini's hidden and routed dimensions" { + try t.expect(p.valid(.embed_norm, .{ .rows = 4, .n = p.hidden, .k = p.hidden })); + try t.expect(!p.valid(.ar, .{ .rows = 6, .n = p.hidden, .k = p.hidden })); + try t.expect(!p.valid(.router, .{ .rows = 1, .n = 8, .k = 128 })); + try t.expect(!p.valid(.conv_dynamic, .{ .rows = 1, .n = 2304, .k = 4 })); + try t.expect(!p.valid(.swiglu, .{ .rows = 1, .n = p.intermediate + 1, .k = 2 })); + try t.expect(p.valid(.logits, .{ .rows = 1, .n = 200058, .k = p.hidden })); + try t.expectEqual(@as(usize, 8 * 1152), p.count(.expert_pick, .{ .rows = 1, .n = 1152, .k = 8 })); +} + +test "embedding uses one FP32 RMS, weighted product and final BF16 rounding" { + var x: [p.hidden]f32 = @splat(1); + var w: [p.hidden]f32 = @splat(2); + try near(@as(f64, 2) / @sqrt(@as(f64, 1) + 1e-6), p.embedValue(&x, &w, 17)); + x[3] = 3; + try t.expect(p.embedValue(&x, &w, 3) != 2); + try t.expectEqual(@as(f64, 1), p.roundBf16(1.003)); +} + +test "AR normalizes each source, scales learned FP32 query dots after reduction and softmaxes" { + const a = t.allocator; + const blocks = try a.alloc(f32, p.hidden); + defer a.free(blocks); + var partial: [p.hidden]f32 = @splat(2); + var queries: [p.hidden]f32 = @splat(0); + @memset(blocks, 1); + const out = try a.alloc(f64, p.hidden); + defer a.free(out); + p.blockResidual(blocks, &partial, &queries, 2, 0, out); + const expected = (1 / @sqrt(@as(f64, 1) + 1e-6) + 2 / @sqrt(@as(f64, 4) + 1e-6)) / 2; + try near(expected, out[0]); + try near(expected, out[1]); + queries[0] = 48; + p.blockResidual(blocks, &partial, &queries, 2, 0, out); + // The first dot is 48/sqrt(2304+eps), multiplied by 1/48 only after that dot. + try t.expect(out[0] < 1.1 and out[0] > 0.9); + try t.expectEqual(p.ar_scale, @as(f64, @as(f32, @bitCast(@as(u32, 0x3caaaaab))))); +} + +test "AR query logits use each normalized source before softmax" { + var blocks: [p.hidden]f32 = @splat(0); + var partial: [p.hidden]f32 = @splat(0); + var queries: [p.hidden]f32 = @splat(0); + var out: [p.hidden]f64 = undefined; + blocks[0] = 1; + partial[1] = 1; + queries[0] = 1; + p.blockResidual(&blocks, &partial, &queries, 2, 0, &out); + const inv = 1 / @sqrt(@as(f64, 1) / p.hidden + 1e-6); + const first = 1 / (1 + @exp(-inv * p.ar_scale)); + try near(first * inv, out[0]); + try near((1 - first) * inv, out[1]); +} + +test "AR FP32 query-dot model distinguishes partial precision and order" { + const blocks: [0]f32 = .{}; + var partial: [p.hidden]f32 = @splat(1); + var queries: [p.hidden]f32 = @splat(0.1); + const sequential = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .f32, .order = .sequential }); + var expected: f32 = 0; + for (0..p.hidden) |d| expected += queries[d] * partial[d]; + try t.expectEqual(@as(f64, expected), sequential); + + const pairwise = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .f32, .order = .pairwise }); + try t.expect(pairwise != sequential); + const bf16 = p.arQueryDot(&blocks, &partial, &queries, 1, 0, 0, 1, .{ .accum = .bf16, .order = .sequential }); + var lowered: f64 = 0; + for (0..p.hidden) |d| { + const term = p.roundBf16(@as(f64, queries[d]) * partial[d]); + lowered = p.roundBf16(lowered + term); + } + try t.expectEqual(lowered, bf16); + try t.expect(bf16 != sequential); +} + +test "AR integer stress meets the exact FP32 gate and rejects lower-precision sums" { + const sources = 4; + var blocks: [(sources - 1) * p.hidden]f32 = undefined; + for (0..sources - 1) |s| @memset(blocks[s * p.hidden ..][0..p.hidden], if (s % 2 == 0) 256 else -256); + var partial: [p.hidden]f32 = @splat(-256); + var queries: [2 * p.hidden]f32 = undefined; + for (0..2) |query_row| { + const row = queries[query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + d % 64); + row[d] = v; + row[p.hidden / 2 + d] = (if (d < 8) @as(f32, 1) else 0) - v; + } + } + var want: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidualIn(&blocks, &partial, &queries, sources, q, null, want[q * p.hidden ..][0..p.hidden]); + const spec: c.Spec = .{ .name = "AR stress", .accum = .f32, .depth = undefined, .ops = 96, .out = .f32, .served = &.{} }; + var margins = [_]f64{ std.math.inf(f64), std.math.inf(f64) }; + for ([_]p.ArOrder{ .sequential, .pairwise, .strided }) |order| { + for ([_]p.ArAccum{ .f32, .f16, .bf16 }, 0..) |accum, ai| { + var got: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidualIn(&blocks, &partial, &queries, sources, q, .{ .accum = accum, .order = order }, got[q * p.hidden ..][0..p.hidden]); + var most: f64 = 0; + for (want, got) |w, g| { + const miss = if (g == w) 0 else if (std.math.isFinite(g) or !std.math.isFinite(w)) @abs(g - w) / c.boundExact(spec, w) else std.math.inf(f64); + most = @max(most, miss); + } + if (ai == 0) try t.expect(most <= 1) else margins[ai - 1] = @min(margins[ai - 1], most); + } + } + try t.expect(margins[0] >= 100); + try t.expect(margins[1] >= 100); +} + +test "static convolution's stored tap three is current and carries the residual input" { + const taps = [_]f32{ 1, 2, 3, 4 }; + const weights = [_]f32{ 10, 20, 30, 40 }; + // This addresses channel zero at output row zero with one channel. + try near((1 * 10 + 2 * 20 + 3 * 30 + 4 * 40 + 4) / @as(f64, @sqrt(5.0)), p.staticConv(&taps, &weights, 1, 0, 0)); +} + +test "dynamic convolution rounds 32 projections to BF16 and uses lag zero for current" { + var taps: [7]f32 = @splat(0); + var input: [p.hidden]f32 = @splat(0); + var projection: [32 * p.hidden]f32 = @splat(0); + taps[3] = 2; // r=0, c=0, current + input[0] = 1; + projection[0] = 1; + const static_w = [_]f32{ 5, 0, 0, 0 }; + // lag zero: (5 + BF16(1))*current + current, all divided by three. + try near(@as(f64, 14.0) / 3, p.dynamicConv(&taps, &input, &static_w, &projection, 1, 0, 0)); + try t.expect(p.dynamicConv(&taps, &input, &static_w, &projection, 1, 0, 0) != p.staticConv(&taps, &static_w, 1, 0, 0)); +} + +test "router bias affects top-8 only; sigmoid weights normalize to eight after ascending IDs" { + var x: [p.hidden]f32 = @splat(0); + var matrix: [p.expert_count * p.hidden]f32 = @splat(0); + var bias: [p.expert_count]f32 = @splat(0); + for (120..128) |e| bias[e] = 1; + matrix[127 * p.hidden] = 1; + x[0] = 1; + const r = p.route(&x, &matrix, &bias); + for (r.ids, 0..) |id, j| try t.expectEqual(@as(u32, @intCast(120 + j)), id); + var sum: f64 = 0; + for (r.weights) |w| sum += w; + try near(8, sum); + try t.expect(r.weights[7] > r.weights[0]); + bias[127] = -1; + const changed = p.route(&x, &matrix, &bias); + try t.expect(changed.ids[7] != 127); +} + +test "interleaved SwiGLU caps gate and up separately with one BF16 activation store" { + try near(p.cap(3, 4) * p.sigmoid(3) * p.cap(7, 25), p.swiglu(3, 7)); + try t.expect(p.swiglu(40, 100) < 100); + try near(16.5, p.roundBf16(p.swiglu(3, 7))); +} + +test "A9(a) rounds the BF16 unembed before widening to the FP32 softcap30" { + var h: [p.hidden]f32 = @splat(0); + var u: [p.hidden]f32 = @splat(0); + h[0] = 1; + u[0] = 60; + try near(30 * std.math.tanh(@as(f64, 2)), p.logit(&h, &u, 0)); + u[0] = 1.003; + try near(p.cap(p.roundBf16(1.003), 30), p.logit(&h, &u, 0)); + try t.expect(p.logit(&h, &u, 0) != p.cap(1.003, 30)); +} + +test "expert pick uses sorted IDs and combine accumulates those experts from FP32 zero" { + var all: [p.expert_count]f32 = undefined; + for (&all, 0..) |*v, e| v.* = @floatFromInt(e); + const ids = [_]u32{ 2, 7, 11, 19, 40, 61, 90, 127 }; + try t.expectEqual(@as(f32, 90), p.pick(&all, &ids, 1, 0, 6, 0)); + var picked: [8]f32 = undefined; + for (&picked, 0..) |*v, j| v.* = @floatFromInt(ids[j]); + const weights = [_]f32{ 0, 0, 0, 0, 0, 0, 1, 0 }; + try near(90, p.combine(&picked, &weights, 1, 0)); + try near(2 * p.sigmoid(-3), p.sigmoid(-3) * 2); +} diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig new file mode 100644 index 00000000000..8598da235d9 --- /dev/null +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -0,0 +1,18 @@ +//! Host-only Inkling 2 Mini Metal launch plans and scalar arithmetic references. +const serving = if (@import("builtin").os.tag.isDarwin()) @import("serving_test.zig") else struct {}; + +test { + _ = @import("attention_test.zig"); + _ = @import("glue_test.zig"); + _ = @import("experts_test.zig"); + _ = @import("loop_test.zig"); + _ = @import("runtime_test.zig"); + _ = @import("runtime_kernels_test.zig"); + _ = @import("dspark_kernels_test.zig"); + _ = @import("dspark_fold.zig"); + _ = @import("dspark_weights.zig"); + _ = @import("dspark_state.zig"); + _ = @import("dspark.zig"); + _ = @import("backend.zig"); + _ = serving; +} diff --git a/zig/src/families/inkling2/metal/loop.zig b/zig/src/families/inkling2/metal/loop.zig new file mode 100644 index 00000000000..7a34448392b --- /dev/null +++ b/zig/src/families/inkling2/metal/loop.zig @@ -0,0 +1,111 @@ +//! Inkling 2 Mini cross-pass messages and message gates: real Metal dispatches. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); +pub const plan = @import("inkling2_loop_plan"); + +pub const hidden: u32 = plan.hidden; +pub const rank: u32 = plan.rank; +pub const message_entries: u32 = plan.message_entries; +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const RowsArgs = plan.RowsArgs; + +/// Bytes of gate scratch a row: normalized [h | m] in BF16, then zeta's 64 BF16. +const gate_row_bytes: usize = (2 * hidden + rank) * 2; + +pub const Pipelines = struct { + messages: mtl.Pipeline, + gates: mtl.Pipeline, + zeta: mtl.Pipeline, + blend: mtl.Pipeline, + /// The gates' intermediates for up to 1,024 rows of each of `max_gates` tuples. + scratch: mtl.Buffer, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.loop); + } + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var messages = try mtl.Pipeline.init(device, lib, plan.Kind.messages.symbol(), false); + errdefer messages.deinit(); + const gate_pipeline = try mtl.Pipeline.init(device, lib, plan.Kind.gates.symbol(), false); + errdefer gate_pipeline.deinit(); + const zeta = try mtl.Pipeline.init(device, lib, "tf_inkling2_loop_zeta", false); + errdefer zeta.deinit(); + const blend = try mtl.Pipeline.init(device, lib, "tf_inkling2_loop_blend", false); + errdefer blend.deinit(); + const scratch = try device.buffer(max_gates * 1024 * gate_row_bytes, mtl.ResourceOptions.shared); + return .{ .messages = messages, .gates = gate_pipeline, .zeta = zeta, .blend = blend, .scratch = scratch }; + } + pub fn deinit(p: *Pipelines) void { + p.scratch.deinit(); + p.blend.deinit(); + p.zeta.deinit(); + p.gates.deinit(); + p.messages.deinit(); + p.* = undefined; + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { + for (refs, 0..) |r, slot| e.setBuffer(r.buf, r.off, slot); +} + +/// Output layout is [token][12 core layers][q,k,v,mlp][H], all binary32. +pub fn crossPassMessageAttention(p: *const Pipelines, e: mtl.ComputeEncoder, bank0: Ref, bank1: Ref, q_mlp: Ref, kv: Ref, out: Ref, rows: u32) void { + std.debug.assert(rows > 0 and rows <= 1024); + e.setPipeline(p.messages); + bind(e, &.{ bank0, bank1, q_mlp, kv, out }); + e.setValue(GateArgs{ .rows = rows, .stride = hidden }, 5); + e.dispatchGroups(mtl.Size.of(rows * message_entries, 1, 1), mtl.Size.of(256, 1, 1)); +} + +const GateArgs = extern struct { rows: u32, stride: u32 }; + +/// One controller tuple; h, m and output are [token][H] binary32 tensors. +pub fn gates(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out: Ref, rows: u32) void { + gatesStrided(p, e, h, m, down, forget, gain, out, rows, hidden); +} + +/// As gates, with row r's m at `m_stride` binary32 values from row r - 1's. +pub fn gatesStrided(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out: Ref, rows: u32, m_stride: u32) void { + gatesEach(p, e, &.{.{ .h = h, .m = m, .down = down, .forget = forget, .gain = gain, .out = out }}, rows, m_stride); +} + +/// Controller tuples one call gates together: a visit's three attention roles. +pub const max_gates = 3; +pub const Gate = struct { h: Ref, m: Ref, down: Ref, forget: Ref, gain: Ref, out: Ref }; + +/// gatesStrided for each tuple a step at a time, a barrier between steps; the tuples' outputs must be distinct. +pub fn gatesEach(p: *const Pipelines, e: mtl.ComputeEncoder, items: []const Gate, rows: u32, m_stride: u32) void { + std.debug.assert(rows > 0 and rows <= 1024 and items.len > 0 and items.len <= max_gates); + const args = GateArgs{ .rows = rows, .stride = m_stride }; + for (items, 0..) |g, i| { + e.setPipeline(p.gates); + bind(e, &.{ g.h, g.m, normalizedOf(p, i) }); + e.setValue(args, 3); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + e.barrier(); + for (items, 0..) |g, i| { + e.setPipeline(p.zeta); + bind(e, &.{ normalizedOf(p, i), g.down, zetaOf(p, i) }); + e.setValue(args, 3); + e.dispatchGroups(mtl.Size.of(rank / 8, rows, 1), mtl.Size.of(256, 1, 1)); + } + e.barrier(); + for (items, 0..) |g, i| { + e.setPipeline(p.blend); + bind(e, &.{ g.h, g.m, zetaOf(p, i), g.forget, g.gain, g.out }); + e.setValue(args, 6); + e.dispatchThreads(mtl.Size.of(hidden, rows, 1), mtl.Size.of(32, 1, 1)); + } +} + +fn normalizedOf(p: *const Pipelines, tuple: usize) Ref { + return .{ .buf = p.scratch, .off = tuple * 1024 * gate_row_bytes }; +} +fn zetaOf(p: *const Pipelines, tuple: usize) Ref { + return .{ .buf = p.scratch, .off = tuple * 1024 * gate_row_bytes + 1024 * 2 * hidden * 2 }; +} diff --git a/zig/src/families/inkling2/metal/loop_plan.zig b/zig/src/families/inkling2/metal/loop_plan.zig new file mode 100644 index 00000000000..79fc638356a --- /dev/null +++ b/zig/src/families/inkling2/metal/loop_plan.zig @@ -0,0 +1,166 @@ +//! Pure Inkling 2 Mini loop launch geometry and independent FP64 arithmetic. +const std = @import("std"); + +pub const hidden = 2304; +pub const rank = 64; +pub const core_layers = 12; +pub const roles = 4; +pub const message_entries = core_layers * roles; +pub const eps = 1e-6; +pub const message_scale: f64 = @as(f32, @bitCast(@as(u32, 0x3caaaaab))); +pub const RowsArgs = extern struct { rows: u32 }; + +pub const Role = enum(u8) { q, k, v, mlp }; +pub const Kind = enum { + messages, + gates, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .messages => "tf_inkling2_loop_messages", + .gates => "tf_inkling2_loop_gates", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .messages => "metal inkling2 loop messages tf_inkling2_loop_messages", + .gates => "metal inkling2 loop gates tf_inkling2_loop_gates", + }; + } +}; + +pub const Call = struct { rows: usize, n: usize, k: usize }; +pub const Geometry = struct { groups: usize, threads: u32 = 256, tg_memory: u32 }; + +pub fn valid(kind: Kind, c: Call) bool { + if (c.rows == 0 or c.rows > 1024) return false; + return switch (kind) { + .messages => c.n == message_entries * hidden and c.k == hidden, + .gates => c.n == hidden and c.k == rank, + }; +} +pub fn count(kind: Kind, c: Call) usize { + return switch (kind) { + .messages => c.rows * message_entries * hidden, + .gates => c.rows * hidden, + }; +} +pub fn geometry(kind: Kind, c: Call) Geometry { + return .{ + .groups = switch (kind) { + .messages => c.rows * message_entries, + .gates => c.rows, + }, + .tg_memory = switch (kind) { + .messages => 144, + .gates => 80, + }, + }; +} + +/// q/mlp and k/v each occupy even/odd rows of their separate 24xH tensors. +pub fn queryRow(role: Role, layer: usize) usize { + std.debug.assert(layer < core_layers); + return 2 * layer + switch (role) { + .q, .k => @as(usize, 0), + .v, .mlp => 1, + }; +} +pub fn usesQueryMessageTensor(role: Role) bool { + return role == .q or role == .mlp; +} + +/// Round through FP32 and BF16 nearest-even, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +pub fn rmsScale(x: []const f32) f64 { + std.debug.assert(x.len == hidden); + var ss: f64 = 0; + for (x) |v| ss += @as(f64, v) * v; + return 1 / @sqrt(ss / hidden + eps); +} + +/// One of the 48 messages. Banks contain their already-decoded BF16 values as f32. +pub fn message(bank0: []const f32, bank1: []const f32, q_mlp: []const f32, kv: []const f32, layer: usize, role: Role, out: []f64) void { + std.debug.assert(bank0.len == hidden and bank1.len == hidden and out.len == hidden); + std.debug.assert(q_mlp.len == 2 * core_layers * hidden and kv.len == q_mlp.len); + const queries = if (usesQueryMessageTensor(role)) q_mlp else kv; + const query = queries[queryRow(role, layer) * hidden ..][0..hidden]; + const inverse = [2]f64{ rmsScale(bank0), rmsScale(bank1) }; + var logits: [2]f64 = undefined; + var peak = -std.math.inf(f64); + inline for (0..2) |s| { + const bank = if (s == 0) bank0 else bank1; + var dot: f64 = 0; + for (0..hidden) |d| dot += @as(f64, query[d]) * (@as(f64, bank[d]) * inverse[s]); + logits[s] = dot * message_scale; + peak = @max(peak, logits[s]); + } + var weights: [2]f64 = undefined; + var den: f64 = 0; + for (0..2) |s| { + weights[s] = @exp(logits[s] - peak); + den += weights[s]; + } + for (0..hidden) |d| { + const beta0 = @as(f64, bank0[d]) * inverse[0]; + const beta1 = @as(f64, bank1[d]) * inverse[1]; + out[d] = weights[0] / den * beta0 + weights[1] / den * beta1; + } +} + +/// BF16(concat(rho(h), rho(m))) D projection and the BF16 zeta endpoint, with FP64 sums. +pub fn downProjection(h: []const f32, m: []const f32, down: []const f32, zeta: *[rank]f64) void { + std.debug.assert(h.len == hidden and m.len == hidden and down.len == rank * 2 * hidden); + const ih = rmsScale(h); + const im = rmsScale(m); + var normalized: [2 * hidden]f64 = undefined; + for (0..hidden) |d| { + normalized[d] = roundBf16(@as(f64, h[d]) * ih); + normalized[hidden + d] = roundBf16(@as(f64, m[d]) * im); + } + for (0..rank) |r| { + var dot: f64 = 0; + for (0..2 * hidden) |d| dot += @as(f64, down[r * 2 * hidden + d]) * normalized[d]; + zeta[r] = roundBf16(dot); + } +} + +/// The reference's four explicit binary32 blend nodes. FP64 carries values between nodes. +pub fn blend(forget_value: f64, gain_value: f64, h: f64, m: f64) f64 { + const f: f32 = @floatCast(forget_value); + const g: f32 = @floatCast(gain_value); + const state: f32 = @floatCast(h); + const message_value: f32 = @floatCast(m); + const keep: f32 = 1.0 - f; + const left: f32 = keep * state; + const right: f32 = g * message_value; + const sum: f32 = left + right; + return sum; +} + +/// Full rank-64 gate. Matrix slices contain their exact BF16 values widened to f32. +pub fn gate(h: []const f32, m: []const f32, down: []const f32, forget: []const f32, gain: []const f32, out: []f64) void { + std.debug.assert(h.len == hidden and m.len == hidden and out.len == hidden); + std.debug.assert(forget.len == hidden * rank and gain.len == forget.len); + var zeta: [rank]f64 = undefined; + downProjection(h, m, down, &zeta); + for (0..hidden) |d| { + var fdot: f64 = 0; + var gdot: f64 = 0; + for (0..rank) |r| { + fdot += @as(f64, forget[d * rank + r]) * zeta[r]; + gdot += @as(f64, gain[d * rank + r]) * zeta[r]; + } + out[d] = blend(std.math.tanh(fdot), std.math.tanh(gdot), h[d], m[d]); + } +} diff --git a/zig/src/families/inkling2/metal/loop_test.zig b/zig/src/families/inkling2/metal/loop_test.zig new file mode 100644 index 00000000000..9634fc44573 --- /dev/null +++ b/zig/src/families/inkling2/metal/loop_test.zig @@ -0,0 +1,208 @@ +//! Host-only proof of Mini's loop formulas, launch ABI, source inventory and rounding. +const std = @import("std"); +const p = @import("inkling2_loop_plan"); +const records = @import("core").contract.inkling2_loop_metal_records.records; +const shader = @import("inkling2_metal").loop; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-10); +} + +test "loop entries have unique symbols, launch records and disabled FP contraction" { + for (std.enums.values(p.Kind), records) |kind, record| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(@as(u32, 256), record.threads); + try t.expectEqual(record.threads, record.reserved); + try t.expectEqual(p.geometry(kind, .{ .rows = 1, .n = 1, .k = 1 }).tg_memory, record.tg_memory); + } + try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); + try t.expect(std.mem.indexOf(u8, shader, "INKLING_LOOP_SCALE = 0x1.555556p-6f") != null); + try t.expect(std.mem.indexOf(u8, shader, "LoopMathSpecMissing") == null); +} + +test "shape admission and dispatch geometry fix H=2304, rank 64 and 48 messages" { + const mc = p.Call{ .rows = 7, .n = 48 * p.hidden, .k = p.hidden }; + const gc = p.Call{ .rows = 7, .n = p.hidden, .k = p.rank }; + try t.expect(p.valid(.messages, mc)); + try t.expect(p.valid(.gates, gc)); + try t.expectEqual(@as(usize, 7 * 48), p.geometry(.messages, mc).groups); + try t.expectEqual(@as(usize, 7), p.geometry(.gates, gc).groups); + try t.expectEqual(@as(usize, 7 * 48 * p.hidden), p.count(.messages, mc)); + try t.expectEqual(@as(usize, 7 * p.hidden), p.count(.gates, gc)); + try t.expect(!p.valid(.messages, .{ .rows = 1, .n = 47 * p.hidden, .k = p.hidden })); + try t.expect(!p.valid(.messages, .{ .rows = 1, .n = 48 * p.hidden, .k = 4608 })); + try t.expect(!p.valid(.gates, .{ .rows = 1, .n = p.hidden, .k = 32 })); + try t.expect(!p.valid(.gates, .{ .rows = 0, .n = p.hidden, .k = p.rank })); + try t.expectEqual(@as(usize, 4), @sizeOf(p.RowsArgs)); + try t.expectEqual(@as(usize, 0), @offsetOf(p.RowsArgs, "rows")); +} + +test "message with zero query is the exact mean of independently normalized banks" { + var bank0: [p.hidden]f32 = @splat(1); + var bank1: [p.hidden]f32 = @splat(2); + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var out: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, 11, .v, &out); + const expected = (@as(f64, 1) / @sqrt(@as(f64, 1) + p.eps) + + @as(f64, 2) / @sqrt(@as(f64, 4) + p.eps)) / 2; + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); + try t.expectEqual(p.message_scale, @as(f64, @as(f32, @bitCast(@as(u32, 0x3caaaaab))))); +} + +test "q/mlp and k/v even-odd layouts select all four roles and scale after the dot" { + var bank0: [p.hidden]f32 = @splat(1); + var bank1: [p.hidden]f32 = @splat(2); + bank1[0] = 4; + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + const layer = 5; + const all = [_]p.Role{ .q, .k, .v, .mlp }; + for (all) |role| { + const expected_row = @as(usize, 2 * layer) + @as(usize, @intFromBool(role == .v or role == .mlp)); + try t.expectEqual(expected_row, p.queryRow(role, layer)); + const matrix = if (p.usesQueryMessageTensor(role)) &q_mlp else &kv; + matrix[expected_row * p.hidden] = 48; + } + var first: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, layer, all[0], &first); + const scale0 = p.rmsScale(&bank0); + const scale1 = p.rmsScale(&bank1); + const l0 = 48 * scale0 * p.message_scale; + const l1 = 48 * 4 * scale1 * p.message_scale; + const peak = @max(l0, l1); + const e0 = @exp(l0 - peak); + const e1 = @exp(l1 - peak); + const expected = e0 / (e0 + e1) * scale0 + e1 / (e0 + e1) * 4 * scale1; + try near(expected, first[0]); + try t.expect(first[0] != (scale0 + 4 * scale1) / 2); + var out: [p.hidden]f64 = undefined; + for (all[1..]) |role| { + p.message(&bank0, &bank1, &q_mlp, &kv, layer, role, &out); + for (first, out) |a, b| try near(a, b); + } +} + +test "message stress dots are exact in FP32 and discriminate BF16 accumulation" { + var bank0: [p.hidden]f32 = @splat(256); + var bank1: [p.hidden]f32 = @splat(-256); + var q_mlp: [2 * p.core_layers * p.hidden]f32 = @splat(0); + var kv: [2 * p.core_layers * p.hidden]f32 = @splat(0); + const query = q_mlp[0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + d % 64); + const nudge: f32 = if (d < 8) 1 else 0; + query[d] = v; + query[p.hidden / 2 + d] = nudge - v; + } + var fp: f32 = 0; + var bf: f64 = 0; + for (query) |v| { + fp += v; + bf = p.roundBf16(bf + v); + } + try t.expectEqual(@as(f32, 8), fp); + try t.expect(bf != 8); + var out: [p.hidden]f64 = undefined; + p.message(&bank0, &bank1, &q_mlp, &kv, 0, .q, &out); + const expected = std.math.tanh(8 * p.message_scale); + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); +} + +test "rank gate hand witness shares one BF16 zeta and uses FP32 tanh projections" { + var h: [p.hidden]f32 = @splat(1); + var m: [p.hidden]f32 = @splat(2); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + var forget: [p.hidden * p.rank]f32 = @splat(0); + var gain: [p.hidden * p.rank]f32 = @splat(0); + down[0] = 1; + for (0..p.hidden) |d| { + forget[d * p.rank] = 1; + gain[d * p.rank] = 1; + } + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); + for (zeta[1..]) |z| try near(0, z); + var out: [p.hidden]f64 = undefined; + p.gate(&h, &m, &down, &forget, &gain, &out); + const expected = p.blend(std.math.tanh(@as(f64, 1)), std.math.tanh(@as(f64, 1)), 1, 2); + try near(expected, out[0]); + try near(expected, out[p.hidden - 1]); + + // The message half starts at D column H; it is not interleaved with h. + @memset(&down, 0); + down[p.hidden] = 1; + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); + down[p.hidden] = 0; + down[0] = 1; + @memset(&m, 0); + p.downProjection(&h, &m, &down, &zeta); + try near(1, zeta[0]); +} + +test "concatenated normalized gate inputs round to BF16 before D accumulation" { + var h: [p.hidden]f32 = @splat(0); + var m: [p.hidden]f32 = @splat(0); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + for (&h, 0..) |*v, d| v.* = @as(f32, @floatFromInt(d % 19 + 1)) / 32; + for (0..p.hidden) |d| down[d] = 1; + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + // Fixed witness rounds to 2024; accumulating unrounded normalized values would round to 2016. + try near(2024, zeta[0]); +} + +test "gate stress projections are exact in FP32 and expose BF16 sums" { + var h: [p.hidden]f32 = @splat(256); + var m: [p.hidden]f32 = @splat(-256); + var down: [p.rank * 2 * p.hidden]f32 = @splat(0); + var forget: [p.hidden * p.rank]f32 = @splat(0); + var gain: [p.hidden * p.rank]f32 = @splat(0); + for (0..p.rank) |r| for (0..p.hidden) |d| { + const w: f32 = @floatFromInt(1 + (r + d) % 64); + down[r * 2 * p.hidden + d] = w; + down[r * 2 * p.hidden + p.hidden + d] = if (d == 0) w - 1 else w; + }; + for ([_][]f32{ &forget, &gain }) |weights| for (0..p.hidden) |d| for (0..p.rank / 2) |r| { + const w: f32 = @floatFromInt(1 + (d + r) % 7); + weights[d * p.rank + r] = w; + weights[d * p.rank + r + p.rank / 2] = if (r == 0) 1 - w else -w; + }; + var fp: f32 = 0; + var bf: f64 = 0; + for (0..2 * p.hidden) |d| { + const term = @as(f64, down[d]) * (if (d < p.hidden) @as(f64, 1) else -1); + fp += @as(f32, @floatCast(term)); + bf = p.roundBf16(bf + term); + } + try t.expectEqual(@as(f32, 1), fp); + try t.expect(bf != 1); + var zeta: [p.rank]f64 = undefined; + p.downProjection(&h, &m, &down, &zeta); + for (zeta) |z| try near(1, z); + var out: [p.hidden]f64 = undefined; + p.gate(&h, &m, &down, &forget, &gain, &out); + const expected = p.blend(std.math.tanh(@as(f64, 1)), std.math.tanh(@as(f64, 1)), 256, -256); + for (out) |v| try near(expected, v); +} + +test "BF16 nearest-even and all four binary32 blend steps have exact witnesses" { + try near(1, p.roundBf16(1.00390625)); // midpoint: even mantissa is zero + try near(1.015625, p.roundBf16(1.01171875)); // midpoint: two is even + const f: f32 = 0.33333334; + const g: f32 = 0.14285715; + const h: f32 = 1.003; + const m: f32 = 1.007; + const keep: f32 = 1.0 - f; + const left: f32 = keep * h; + const right: f32 = g * m; + const rounded: f32 = left + right; + try t.expectEqual(@as(f64, rounded), p.blend(f, g, h, m)); + try t.expect(p.blend(f, g, h, m) != (1 - @as(f64, f)) * h + @as(f64, g) * m); +} diff --git a/zig/src/families/inkling2/metal/metal.zig b/zig/src/families/inkling2/metal/metal.zig new file mode 100644 index 00000000000..bef58022713 --- /dev/null +++ b/zig/src/families/inkling2/metal/metal.zig @@ -0,0 +1,7 @@ +//! Inkling 2 Mini's Metal launchers and their shader sources. + +pub const attention = @import("attention.zig"); +pub const glue = @import("glue.zig"); +pub const experts = @import("experts.zig"); +pub const experts_plan = @import("experts_plan.zig"); +pub const loop = @import("loop.zig"); diff --git a/zig/src/families/inkling2/metal/model.zig b/zig/src/families/inkling2/metal/model.zig new file mode 100644 index 00000000000..87c98f36fcf --- /dev/null +++ b/zig/src/families/inkling2/metal/model.zig @@ -0,0 +1,294 @@ +//! Inkling 2 Mini's resident text model: validated checkpoint weights and every Metal pipeline. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const cfg = @import("../config.zig"); +const layer_plan = @import("../plan.zig"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const shards = @import("core").checkpoint_host; +const attention = @import("attention.zig"); +const glue = @import("glue.zig"); +const experts = @import("experts.zig"); +const loop = @import("loop.zig"); + +pub const Tensor = ck.Tensor; +pub const DynamicConv = struct { static_w: Tensor, projection: Tensor }; +pub const Conv = union(enum) { static: Tensor, dynamic: DynamicConv }; +pub const Controller = struct { down: Tensor, forget: Tensor, gain: Tensor }; +pub const AttentionWeights = struct { + wq: Tensor, + wk: Tensor, + wv: Tensor, + wr: Tensor, + wo: Tensor, + gate: Tensor, + sink: Tensor, + q_scale: Tensor, + rel_scale: Tensor, + rel_projection: Tensor, + k_conv: Conv, + v_conv: Conv, + q_norm: Tensor, + k_norm: Tensor, + v_norm: Tensor, +}; +pub const ExpertMatrix = struct { + weight: Tensor, + scale: Tensor, + amax: ?Tensor = null, + denominator: ?Tensor = null, +}; +pub const LayerWeights = struct { + attn: AttentionWeights, + attn_conv: Tensor, + mlp_norm: Tensor, + mlp_conv: Tensor, + router_weight: Tensor, + router_bias: Tensor, + gu: ExpertMatrix, + down: ExpertMatrix, + controllers: ?[4]Controller, +}; +pub const Weights = struct { + embed: Tensor, + embed_norm: Tensor, + norm: Tensor, + unembed: Tensor, + output_query: Tensor, + cross_queries: Tensor, + cross_kv_queries: Tensor, + attn_queries: [23]Tensor, + mlp_queries: [24]Tensor, + layers: [24]LayerWeights, +}; + +/// Scalar copies and residuals around dispatch stay on Metal; forward never reads tensors back to the host. +pub const runtime_source = sources.inkling2_runtime; + +pub const RuntimeOp = enum { copy_bf16, copy_f32, widen, attention_partial, mlp_partial, capture_tap }; +pub const runtime_names = [_][:0]const u8{ + "tf_ink2_copy_bf16", + "tf_ink2_copy_f32", + "tf_ink2_widen", + "tf_ink2_attention_partial", + "tf_ink2_mlp_partial", + "tf_ink2_capture_tap", +}; + +pub fn admitConfig(c: *const cfg.Config) !void { + const t = c.text; + const l = t.loop orelse return error.Inkling2NotMini; + if (l.passes != 3 or l.core_start != 6 or l.core_end != 18 or l.gate_rank != 64) + return error.UnsupportedInkling2Loop; + if (t.hidden != 2304 or t.layers != 24 or t.vocab != 201024 or t.unpadded_vocab != 200058 or + t.window != 1024 or t.d_rel != 16 or t.rel_extent != 1024 or t.log_floor != 8192 or + t.block != 6 or t.experts != 128 or t.topk != 8 or t.expert_inter != 1152 or + t.max_context != 1048576) return error.UnsupportedInkling2Geometry; + for ([_]cfg.Heads{ t.local, t.global }) |h| if (h.q != 24 or h.kv != 8 or h.dim != 128) + return error.UnsupportedInkling2Geometry; + if (t.eps != 1e-6 or t.log_alpha != 0.1 or t.qk_clip != 22.627416997969522 or + t.rel_clip != 8 or t.route_scale != 8 or t.gate_cap != 4 or t.up_cap != 25 or + t.logit_cap != 30) return error.UnsupportedInkling2Constants; +} + +fn require(t: Tensor, dtype: ck.DType, dims: []const usize) !Tensor { + if (t.dtype != dtype or t.rank != dims.len) return error.UnexpectedInkling2Tensor; + for (dims, 0..) |d, i| if (t.shape[i] != d) return error.UnexpectedInkling2Tensor; + var count: usize = 1; + for (dims) |d| count = std.math.mul(usize, count, d) catch return error.UnexpectedInkling2Tensor; + if (t.bytes != count * dtype.size()) return error.UnexpectedInkling2Tensor; + return t; +} + +fn get(c: *const ck.Checkpoint, comptime fmt: []const u8, args: anytype, dtype: ck.DType, dims: []const usize) !Tensor { + var buf: [256]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, fmt, args); + return require(try c.get(name), dtype, dims); +} + +fn matrix(c: *const ck.Checkpoint, layer: u32, comptime suffix: []const u8, precision: layer_plan.Precision, rows: usize, k: usize) !ExpertMatrix { + const base = "model.llm.layers.{d}.mlp.experts." ++ suffix; + const e = 128; + switch (precision) { + .nvfp4 => return .{ + .weight = try get(c, base ++ "_weight", .{layer}, .u8, &.{ e, rows, k / 2 }), + .scale = try get(c, base ++ "_weight_scale", .{layer}, .f8_e4m3, &.{ e, rows, k / 16 }), + .amax = try get(c, base ++ "_weight_amax", .{layer}, .f32, &.{e}), + .denominator = try get(c, base ++ "_weight_outer_scale_denominator", .{layer}, .f32, &.{1}), + }, + .mxfp8 => return .{ + .weight = try get(c, base ++ "_weight", .{layer}, .f8_e4m3, &.{ e, rows, k }), + .scale = try get(c, base ++ "_weight_scale", .{layer}, .u8, &.{ e, rows, k / 32 }), + }, + } +} + +fn loadConv(c: *const ck.Checkpoint, layer: u32, comptime role: []const u8, global: bool) !Conv { + if (!global) return .{ .static = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.weight", .{layer}, .bf16, &.{ 1024, 1, 4 }) }; + return .{ .dynamic = .{ + .static_w = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.static_w", .{layer}, .bf16, &.{ 4, 1024 }), + .projection = try get(c, "model.llm.layers.{d}.attn." ++ role ++ "_sconv.weight_proj", .{layer}, .bf16, &.{ 32, 2304 }), + } }; +} + +fn loadWeights(c: *const ck.Checkpoint, config: *const cfg.Config, wp: *const layer_plan.Plan) !Weights { + var w: Weights = undefined; + w.embed = try get(c, "model.llm.embed.weight", .{}, .bf16, &.{ 201024, 2304 }); + w.embed_norm = try get(c, "model.llm.embed_norm.weight", .{}, .bf16, &.{2304}); + w.norm = try get(c, "model.llm.norm.weight", .{}, .bf16, &.{2304}); + w.unembed = try get(c, "model.llm.unembed.weight", .{}, .bf16, &.{ 201024, 2304 }); + w.output_query = try get(c, "model.llm.attn_res.output_query", .{}, .f32, &.{2304}); + w.cross_queries = try get(c, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ 24, 2304 }); + w.cross_kv_queries = try get(c, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ 24, 2304 }); + for (&w.attn_queries, 0..) |*q, i| { + const global = cfg.isGlobal(@intCast(i + 1)); + const dims: []const usize = if (global) &.{ 3, 2304 } else &.{2304}; + q.* = try get(c, "model.llm.attn_res.attn_queries.{d}", .{i}, .f32, dims); + } + for (&w.mlp_queries, 0..) |*q, i| q.* = try get(c, "model.llm.attn_res.mlp_queries.{d}", .{i}, .f32, &.{2304}); + for (&w.layers, 0..) |*l, i| { + const layer: u32 = @intCast(i); + const p = wp.at(layer); + const global = p.kind == .global; + const q_width: usize = @as(usize, p.heads.q) * p.heads.dim; + const local_norm = if (!global) try get(c, "model.llm.layers.{d}.attn_norm.weight", .{layer}, .bf16, &.{2304}) else undefined; + l.attn = .{ + .wq = try get(c, "model.llm.layers.{d}.attn.wq_du.weight", .{layer}, .bf16, &.{ q_width, 2304 }), + .wk = try get(c, "model.llm.layers.{d}.attn.wk_dv.weight", .{layer}, .bf16, &.{ 1024, 2304 }), + .wv = try get(c, "model.llm.layers.{d}.attn.wv_dv.weight", .{layer}, .bf16, &.{ 1024, 2304 }), + .wr = try get(c, "model.llm.layers.{d}.attn.wr_du.weight", .{layer}, .bf16, &.{ 384, 2304 }), + .wo = try get(c, "model.llm.layers.{d}.attn.wo_ud.weight", .{layer}, .bf16, &.{ 2304, q_width }), + .gate = try get(c, "model.llm.layers.{d}.attn.gate_attn.weight", .{layer}, .bf16, &.{ q_width, 2304 }), + .sink = try get(c, "model.llm.layers.{d}.attn.attn_sink_proj.weight", .{layer}, .bf16, &.{ 24, 2304 }), + .q_scale = try get(c, "model.llm.layers.{d}.attn.q_l2_clip.scale", .{layer}, .bf16, &.{ 24, 128 }), + .rel_scale = try get(c, "model.llm.layers.{d}.attn.rel_l2_clip.scale", .{layer}, .bf16, &.{ 24, 16 }), + .rel_projection = try get(c, "model.llm.layers.{d}.attn.rel_logits_proj.proj", .{layer}, .bf16, &.{ 16, p.extent }), + .k_conv = try loadConv(c, layer, "k", global), + .v_conv = try loadConv(c, layer, "v", global), + .q_norm = if (global) try get(c, "model.llm.layers.{d}.q_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + .k_norm = if (global) try get(c, "model.llm.layers.{d}.k_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + .v_norm = if (global) try get(c, "model.llm.layers.{d}.v_input_norm.weight", .{layer}, .bf16, &.{2304}) else local_norm, + }; + l.attn_conv = try get(c, "model.llm.layers.{d}.attn_sconv.weight", .{layer}, .bf16, &.{ 2304, 1, 4 }); + l.mlp_norm = try get(c, "model.llm.layers.{d}.mlp_norm.weight", .{layer}, .bf16, &.{2304}); + l.mlp_conv = try get(c, "model.llm.layers.{d}.mlp_sconv.weight", .{layer}, .bf16, &.{ 2304, 1, 4 }); + l.router_weight = try get(c, "model.llm.layers.{d}.mlp.gate.weight", .{layer}, .bf16, &.{ 128, 2304 }); + l.router_bias = try get(c, "model.llm.layers.{d}.mlp.gate.bias", .{layer}, .f32, &.{128}); + l.gu = try matrix(c, layer, "w13", p.precision, 2304, 2304); + l.down = try matrix(c, layer, "w2", p.precision, 2304, 1152); + l.controllers = null; + if (config.text.loop) |lp| if (layer >= lp.core_start and layer < lp.core_end) { + var controllers: [4]Controller = undefined; + inline for (.{ "attn", "k", "v", "mlp" }, 0..) |role, j| controllers[j] = .{ + .down = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".down_weight", .{layer}, .bf16, &.{ 64, 4608 }), + .forget = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".forget_weight", .{layer}, .bf16, &.{ 2304, 64 }), + .gain = try get(c, "model.llm.layers.{d}.controllers." ++ role ++ ".gain_weight", .{layer}, .bf16, &.{ 2304, 64 }), + }; + l.controllers = controllers; + }; + } + return w; +} + +pub const Model = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + config: cfg.Config, + checkpoint: ck.Checkpoint, + weights: Weights, + weight_plan: layer_plan.Plan, + attention: attention.Kernels, + glue: glue.Pipelines, + experts: experts.Pipelines, + loop: loop.Pipelines, + dense: [6]mtl.Pipeline, + norm: mtl.Pipeline, + runtime: [runtime_names.len]mtl.Pipeline, + + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*Model { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const m = try gpa.create(Model); + errdefer gpa.destroy(m); + m.gpa = gpa; + const config_path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(config_path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, config_path, gpa, .limited(1 << 24)); + defer gpa.free(text); + var why: cfg.Why = .{}; + m.config = cfg.parse(gpa, text, &why) catch |err| { + std.log.err("inkling2_loop: {s}", .{why.text()}); + return err; + }; + try admitConfig(&m.config); + m.device = try mtl.Device.init(); + errdefer m.device.deinit(); + m.queue = try m.device.queue(); + errdefer m.queue.deinit(); + m.checkpoint = ck.Checkpoint.init(gpa); + errdefer m.checkpoint.deinit(); + const files = try shards.shardFiles(gpa, io, dir); + defer shards.freeShardFiles(gpa, files); + + // Mini uses NVFP4 for layers 0-19 and MXFP8 for 20-23; matrix() rechecks all stored tensor metadata and bytes. + var precisions: [24]layer_plan.Precision = undefined; + for (&precisions, 0..) |*p, i| p.* = if (i < 20) .nvfp4 else .mxfp8; + m.weight_plan = try layer_plan.build(&m.config.text, &precisions); + if (m.weight_plan.n_visits != 48) return error.UnsupportedInkling2Loop; + for (files) |path| try m.checkpoint.addFileSelected(m.device, path, "", "model.llm."); + m.weights = try loadWeights(&m.checkpoint, &m.config, &m.weight_plan); + + m.attention = try attention.Kernels.init(gpa, m.device); + errdefer m.attention.deinit(); + m.glue = try glue.Pipelines.load(m.device); + errdefer m.glue.deinit(); + m.experts = try experts.Pipelines.load(m.device); + errdefer m.experts.deinit(); + m.loop = try loop.Pipelines.load(m.device); + errdefer m.loop.deinit(); + { + const lib = try mtl.Library.fromSource(m.device, sources.spark25_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + var made: usize = 0; + errdefer for (m.dense[0..made]) |p| p.deinit(); + for ([_]u32{ 1, 2, 4, 8, 16, 32 }, 0..) |rows, i| { + var buf: [32]u8 = undefined; + const name = try std.fmt.bufPrintSentinel(&buf, "sp_matvec_{d}", .{rows}, 0); + m.dense[i] = try mtl.Pipeline.init(m.device, lib, name, false); + made += 1; + } + m.norm = try mtl.Pipeline.init(m.device, lib, "sp_norm", false); + } + errdefer { + m.norm.deinit(); + for (m.dense) |p| p.deinit(); + } + { + const lib = try mtl.Library.fromSource(m.device, runtime_source, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var made: usize = 0; + errdefer for (m.runtime[0..made]) |p| p.deinit(); + for (runtime_names, 0..) |name, i| { + m.runtime[i] = try mtl.Pipeline.init(m.device, lib, name, false); + made += 1; + } + } + errdefer for (m.runtime) |p| p.deinit(); + return m; + } + + pub fn deinit(m: *Model) void { + for (m.runtime) |p| p.deinit(); + m.norm.deinit(); + for (m.dense) |p| p.deinit(); + m.loop.deinit(); + m.experts.deinit(); + m.glue.deinit(); + m.attention.deinit(); + m.checkpoint.deinit(); + m.queue.deinit(); + m.device.deinit(); + m.gpa.destroy(m); + } +}; diff --git a/zig/src/families/inkling2/metal/ref.zig b/zig/src/families/inkling2/metal/ref.zig new file mode 100644 index 00000000000..1e6f5a69622 --- /dev/null +++ b/zig/src/families/inkling2/metal/ref.zig @@ -0,0 +1,4 @@ +//! Shared Metal buffer reference for Inkling 2 launchers and their state buffers. +const mtl = @import("metal"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; diff --git a/zig/src/families/inkling2/metal/runtime_kernels_test.zig b/zig/src/families/inkling2/metal/runtime_kernels_test.zig new file mode 100644 index 00000000000..e8f58c8bc39 --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_kernels_test.zig @@ -0,0 +1,135 @@ +//! Host-only proof of Mini's runtime source identity, launch ABI, block layout and rounding. +const std = @import("std"); +const p = @import("runtime_plan.zig"); +const model = @import("model.zig"); +const records = @import("core").contract.inkling2_runtime_metal_records.records; +const shader = @import("inkling2_metal").runtime; +const t = std.testing; + +fn near(want: f64, got: f64) !void { + try t.expectApproxEqAbs(want, got, 1e-12); +} + +test "runtime source is the one exported source and every helper has one launch record" { + try t.expectEqualStrings(shader, model.runtime_source); + try t.expectEqualStrings(shader, @import("kernel_sources").inkling2_runtime); + try t.expectEqual(std.enums.values(p.Kind).len, model.runtime_names.len); + try t.expectEqual(std.enums.values(p.Kind).len, records.len); + for (std.enums.values(p.Kind), records, model.runtime_names) |kind, record, runtime_name| { + try t.expectEqualStrings(kind.label(), record.name); + try t.expectEqualStrings(kind.symbol(), runtime_name); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); + try t.expectEqual(p.threads, record.threads); + try t.expectEqual(record.threads, record.reserved); + try t.expectEqual(@as(u32, 0), record.tg_memory); + } + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, "#pragma METAL fp contract(off)")); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, "struct InkRuntimeArgs { uint count, boundary; };")); +} + +test "linear launches bind H=2304 rows and the exact eight-byte argument ABI" { + try t.expectEqual(@as(usize, 8), @sizeOf(p.RuntimeArgs)); + try t.expectEqual(@as(usize, 0), @offsetOf(p.RuntimeArgs, "count")); + try t.expectEqual(@as(usize, 4), @offsetOf(p.RuntimeArgs, "boundary")); + for (std.enums.values(p.Kind)) |kind| { + const call = p.Call{ .rows = 7, .n = p.hidden, .k = if (kind == .attention_partial) 4 else 1 }; + try t.expect(p.valid(kind, call)); + const a = p.args(kind, call); + try t.expectEqual(@as(u32, 7 * p.hidden), a.count); + try t.expectEqual(@as(u32, if (kind == .attention_partial) 4 else if (kind == .capture_tap) 1 else 0), a.boundary); + try t.expectEqual(@as(usize, 7 * p.hidden), p.geometry(call).count); + try t.expectEqual(p.threads, p.geometry(call).threads); + try t.expectEqual(@as(u32, 0), p.geometry(call).tg_memory); + const outputs: usize = 7 * p.hidden * (if (kind == .capture_tap) @as(usize, p.tap_channels) else 1); + try t.expectEqual(outputs, p.outputCount(kind, call)); + try t.expect(!p.valid(kind, .{ .rows = 0, .n = p.hidden, .k = call.k })); + if (kind == .copy_bf16 or kind == .copy_f32) { + try t.expect(p.valid(kind, .{ .rows = 5, .n = 1024, .k = 1 })); + } else { + try t.expect(!p.valid(kind, .{ .rows = 1, .n = p.hidden - 1, .k = call.k })); + } + } + try t.expect(!p.valid(.copy_bf16, .{ .rows = 1, .n = 0, .k = 1 })); + try t.expect(p.valid(.attention_partial, .{ .rows = 1, .n = p.hidden, .k = 0 })); + try t.expect(!p.valid(.attention_partial, .{ .rows = 1, .n = p.hidden, .k = 5 })); + try t.expect(!p.valid(.widen, .{ .rows = 1, .n = p.hidden, .k = 0 })); + try t.expect(p.valid(.capture_tap, .{ .rows = 1, .n = p.hidden, .k = 3 })); + try t.expect(!p.valid(.capture_tap, .{ .rows = 1, .n = p.hidden, .k = 4 })); +} + +test "DSpark capture channels are packed [row][tap][H] in visit order" { + try t.expectEqual(@as(usize, 4), p.tap_channels); + try t.expectEqual(@as(usize, 0), p.tapOffset(0, 0)); + try t.expectEqual(p.hidden, p.tapOffset(0, 1)); + try t.expectEqual(3 * p.hidden, p.tapOffset(0, 3)); + try t.expectEqual(4 * p.hidden, p.tapOffset(1, 0)); + try t.expectEqual(7 * p.hidden, p.tapOffset(1, 3)); + try t.expectEqual(2 * 4 * p.hidden, p.outputCount(.capture_tap, .{ .rows = 2, .n = p.hidden, .k = 0 })); + try t.expectEqual(2 * p.hidden, p.args(.capture_tap, .{ .rows = 2, .n = p.hidden, .k = 0 }).count); +} + +test "four completed BF16 blocks are row-major and disjoint from the partial source" { + try t.expectEqual(@as(usize, 0), p.blockOffset(0, 1)); + try t.expectEqual(3 * p.hidden, p.blockOffset(0, 4)); + try t.expectEqual(4 * p.hidden, p.blockOffset(1, 1)); + try t.expectEqual(15 * p.hidden, p.blockOffset(3, 4)); + var previous: usize = 0; + for (0..4) |row| for (1..5) |boundary| { + const at = p.blockOffset(row, boundary); + if (at != 0) try t.expectEqual(previous + p.hidden, at); + previous = at; + }; + try t.expectEqual(4 * 4 * p.hidden, previous + p.hidden); +} + +test "attention restart and addition references cover every valid boundary" { + const partial: f32 = 1.5; + const attention: f32 = -0.25; + try near(1.25, p.attentionPartial(partial, attention, 0)); + for (1..5) |boundary| try near(-0.25, p.attentionPartial(partial, attention, boundary)); + // One binary32 addition rounds this midpoint to one; unrounded FP64 addition would not. + const ulp: f32 = 0x1p-24; + try near(1, p.attentionPartial(1, ulp, 0)); + try t.expect(p.attentionPartial(1, ulp, 0) != 1 + @as(f64, ulp)); + for (1..5) |boundary| try near(@as(f64, ulp), p.attentionPartial(std.math.nan(f32), ulp, boundary)); +} + +test "the folded convolution reads three old rows then the launch's, and rounds once to BF16" { + const a = t.allocator; + const taps = try a.alloc(f32, 5 * p.hidden); + defer a.free(taps); + const weight = try a.alloc(f32, 4 * p.hidden); + defer a.free(weight); + @memset(taps, 0); + @memset(weight, 0); + // Row 1 at d = 7: its own tap is row 4 of the taps, and weight j multiplies row 1 + j. + taps[4 * p.hidden + 7] = 2; + try near(p.roundBf16(@as(f32, 2) / @sqrt(@as(f32, 5))), p.conv(taps, weight, 1, 7)); + taps[1 * p.hidden + 7] = 3; + weight[7 * 4 + 0] = 0.5; + try near(p.roundBf16(@as(f32, 3.5) / @sqrt(@as(f32, 5))), p.conv(taps, weight, 1, 7)); + weight[7 * 4 + 3] = -1; + try near(p.roundBf16(@as(f32, 1.5) / @sqrt(@as(f32, 5))), p.conv(taps, weight, 1, 7)); + try near(0, p.conv(taps, weight, 0, 7)); +} + +test "MLP partial rounds its FP32 sum to nearest-even BF16" { + try near(1, p.roundBf16(@as(f32, 1.00390625))); + try near(1.015625, p.roundBf16(@as(f32, 1.01171875))); + try near(1, p.mlpPartial(1, 0.00390625)); + try near(1.015625, p.mlpPartial(1, 0.01171875)); + try t.expect(p.mlpPartial(1, 0.00390625) != 1.00390625); +} + +test "copy and widening witnesses preserve actual BF16 and FP32 values" { + const bf16 = @import("bf16_round"); + const bf_values = [_]f32{ -0.0, 1.0, -2.5, 0.0078125, std.math.inf(f32) }; + for (bf_values) |x| { + const bits = bf16.bits(x); + const stored: f32 = @bitCast(@as(u32, bits) << 16); + try t.expectEqual(@as(u32, @bitCast(x)), @as(u32, bits) << 16); + try near(x, stored); + } + const f32_values = [_]f32{ -0.0, 1.00000011920928955078125, -8192.25 }; + for (f32_values) |x| try t.expectEqual(@as(u32, @bitCast(x)), @as(u32, @bitCast(@as(f32, @floatCast(@as(f64, x)))))); +} diff --git a/zig/src/families/inkling2/metal/runtime_plan.zig b/zig/src/families/inkling2/metal/runtime_plan.zig new file mode 100644 index 00000000000..a52251ac13f --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_plan.zig @@ -0,0 +1,112 @@ +//! Pure Inkling 2 Mini runtime launch geometry and independent FP64 references. +const std = @import("std"); + +pub const hidden = 2304; +pub const block_slots = 4; +pub const tap_channels = 4; +pub const max_rows = 1024; +pub const threads: u32 = 256; +pub const RuntimeArgs = extern struct { count: u32, boundary: u32 }; + +pub const Kind = enum { + copy_bf16, + copy_f32, + widen, + attention_partial, + mlp_partial, + capture_tap, + + pub fn symbol(k: Kind) []const u8 { + return switch (k) { + .copy_bf16 => "tf_ink2_copy_bf16", + .copy_f32 => "tf_ink2_copy_f32", + .widen => "tf_ink2_widen", + .attention_partial => "tf_ink2_attention_partial", + .mlp_partial => "tf_ink2_mlp_partial", + .capture_tap => "tf_ink2_capture_tap", + }; + } + pub fn label(k: Kind) []const u8 { + return switch (k) { + .copy_bf16 => "metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", + .copy_f32 => "metal inkling2 runtime copy_f32 tf_ink2_copy_f32", + .widen => "metal inkling2 runtime widen tf_ink2_widen", + .attention_partial => "metal inkling2 runtime attention_partial tf_ink2_attention_partial", + .mlp_partial => "metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", + .capture_tap => "metal inkling2 runtime capture_tap tf_ink2_capture_tap", + }; + } +}; + +/// `k` is one for pointwise helpers, a boundary for attention, or a DSpark tap channel. +pub const Call = struct { rows: usize, n: usize, k: usize }; +pub const Geometry = struct { count: usize, threads: u32 = threads, tg_memory: u32 = 0 }; + +pub fn valid(kind: Kind, c: Call) bool { + if (c.rows == 0 or c.rows > max_rows or c.n == 0 or c.rows > std.math.maxInt(u32) / c.n) return false; + return switch (kind) { + .copy_bf16, .copy_f32 => c.k == 1, + .capture_tap => c.n == hidden and c.k < tap_channels, + .widen, .attention_partial, .mlp_partial => c.n == hidden and switch (kind) { + .attention_partial => c.k <= block_slots, + else => c.k == 1, + }, + }; +} + +pub fn geometry(c: Call) Geometry { + return .{ .count = c.rows * c.n }; +} + +/// Values in the full destination for one capture launch; its dispatch still reads rows*n. +pub fn outputCount(kind: Kind, c: Call) usize { + const channels: usize = if (kind == .capture_tap) tap_channels else 1; + return c.rows * c.n * channels; +} + +pub fn args(kind: Kind, c: Call) RuntimeArgs { + std.debug.assert(valid(kind, c)); + return .{ .count = @intCast(c.rows * c.n), .boundary = if (kind == .attention_partial or kind == .capture_tap) @intCast(c.k) else 0 }; +} + +/// Completed blocks are [row][four BF16 blocks][H]; the separate partial is not stored here. +pub fn blockOffset(row: usize, boundary: usize) usize { + std.debug.assert(row < max_rows and boundary >= 1 and boundary <= block_slots); + return (row * block_slots + boundary - 1) * hidden; +} + +/// DSpark features are [row][four taps][H]; a capture launch writes one tap channel. +pub fn tapOffset(row: usize, channel: usize) usize { + std.debug.assert(row < max_rows and channel < tap_channels); + return (row * tap_channels + channel) * hidden; +} + +/// Round through binary32 and nearest-even BF16, returning an exactly representable FP64 value. +pub fn roundBf16(v: anytype) f64 { + const x: f32 = @floatCast(v); + const bits: u32 = @bitCast(x); + const rounded: u16 = if (std.math.isNan(x)) + @truncate((bits >> 16) | 0x40) + else + @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + const value: f32 = @bitCast(@as(u32, rounded) << 16); + return value; +} + +/// The static convolution both partial kernels take first, in their FP32 order, as the BF16 value it yields. +pub fn conv(taps: []const f32, weight: []const f32, row: usize, d: usize) f32 { + var sum: f32 = taps[(row + 3) * hidden + d]; + for (0..4) |tap| sum += weight[d * 4 + tap] * taps[(row + tap) * hidden + d]; + return @floatCast(roundBf16(sum / @sqrt(@as(f32, 5)))); +} + +/// Boundary restarts the FP32 partial; otherwise the two exact BF16 inputs undergo one FP32 add. +pub fn attentionPartial(p: f32, x: f32, boundary: usize) f64 { + std.debug.assert(boundary <= block_slots); + return if (boundary != 0) x else @as(f32, p + x); +} + +/// FP32 residual addition followed by the required BF16 endpoint. +pub fn mlpPartial(t: f32, x: f32) f64 { + return roundBf16(@as(f32, t + x)); +} diff --git a/zig/src/families/inkling2/metal/runtime_test.zig b/zig/src/families/inkling2/metal/runtime_test.zig new file mode 100644 index 00000000000..7a8f98bfab1 --- /dev/null +++ b/zig/src/families/inkling2/metal/runtime_test.zig @@ -0,0 +1,307 @@ +//! Host-only schedule, cache-layout, accepted-history and compact-snapshot checks. +const std = @import("std"); +const mtl = @import("metal"); +const ap = @import("attention_plan.zig"); +const cfg = @import("../config.zig"); +const layer_plan = @import("../plan.zig"); +const state = @import("state.zig"); +const snapshot = @import("snapshot.zig"); +const model = @import("model.zig"); +const fwd = @import("forward.zig"); +const backend = @import("backend.zig"); + +fn mini() cfg.Config { + return .{ + .text = .{ + .hidden = 2304, + .layers = 24, + .vocab = 201024, + .unpadded_vocab = 200058, + .local = .{ .q = 24, .kv = 8, .dim = 128 }, + .global = .{ .q = 24, .kv = 8, .dim = 128 }, + .window = 1024, + .d_rel = 16, + .rel_extent = 1024, + .log_floor = 8192, + .log_alpha = 0.1, + .eps = 1e-6, + .qk_clip = 22.627416997969522, + .rel_clip = 8, + .block = 6, + .experts = 128, + .topk = 8, + .expert_inter = 1152, + .route_scale = 8, + .gate_cap = 4, + .up_cap = 25, + .logit_cap = 30, + .max_context = 1048576, + .loop = .{ .core_start = 6, .core_end = 18, .passes = 3, .gate_rank = 64 }, + }, + .vision = undefined, + .mtp = null, + .eos = 200055, + .image_token = 200054, + }; +} + +fn schedule() layer_plan.Plan { + const c = mini(); + var precision: [24]layer_plan.Precision = @splat(.nvfp4); + for (precision[4..]) |*p| p.* = .mxfp8; + return layer_plan.build(&c.text, &precision) catch unreachable; +} + +test "Mini admits only its fixed geometry and expands 24 weights to 48 visits" { + const c = mini(); + try model.admitConfig(&c); + const p = schedule(); + try std.testing.expectEqual(@as(u32, 48), p.n_visits); + try std.testing.expectEqual(@as(u32, 8), p.visitCount(.global)); + try std.testing.expectEqual(@as(u32, 5), p.final_sources); + for (p.visits[0..p.n_visits], 0..) |v, i| { + try std.testing.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try std.testing.expect(v.layer < 24); + } + for ([_]usize{ 18, 30 }) |i| { + try std.testing.expect(p.visits[i].pass > 1); + try std.testing.expectEqual(@as(u32, 6), p.visits[i].layer); + try std.testing.expect(p.visits[i].hasMessages()); + } + try std.testing.expect(!p.visits[0].hasMessages()); + try std.testing.expect(!(p.visits[17].pass > 1 and p.visits[17].layer == 6)); +} + +test "Every visit and convolution role has disjoint persistent and staged bytes" { + var previous_persistent: usize = 0; + for (0..state.visit_slots) |slot| for (0..state.conv_states) |cs| { + const off = state.convByteOffset(slot, cs, 0, 3); + const len = 3 * state.convWidth(cs) * 2; + if (slot != 0 or cs != 0) try std.testing.expect(off >= previous_persistent); + previous_persistent = off + len; + for (0..4) |accepted| { + const source = state.convByteOffset(slot, cs, accepted, state.stage_rows); + try std.testing.expect(source + len <= state.taps_bytes); + } + }; + try std.testing.expectEqual(state.conv_bytes, previous_persistent); + // Decode acceptance k preserves exactly old[k], old[k+1], old[k+2] through raw[k..k+3]. + for (0..state.window_rows + 1) |accepted| { + const old = state.convByteOffset(47, 3, 0, state.stage_rows); + const selected = state.convByteOffset(47, 3, accepted, state.stage_rows); + try std.testing.expectEqual(old + accepted * state.hidden * 2, selected); + } +} + +test "Compact snapshots charge global prefixes and a sliding layer's window less one" { + const one_layer_pair: u64 = state.kv_width * 2 * 2; + for ([_]usize{ 0, 1, 1023, 1024, state.sliding_ring, state.sliding_ring + 1 }) |at| { + const n: u64 = @intCast(at); + const live = @as(u64, 8) * n + @as(u64, 40) * @as(u64, @intCast(@min(at, state.sliding_window - 1))); + const kv = live * one_layer_pair; + const expected = kv + state.conv_bytes; + try std.testing.expectEqual(expected, snapshot.bytes(at)); + } + try std.testing.expect(snapshot.bytes(4096) < snapshot.bytes(8192)); + try std.testing.expectEqual(state.conv_bytes, state.visit_slots * 3 * state.conv_row_values * 2); +} + +test "DSpark feature rows are 4x2304 BF16 and ranges expose only live accepted rows" { + try std.testing.expectEqual(@as(usize, 4 * 2304 * 2), state.feature_row_bytes); + try std.testing.expectEqual(@as(usize, 7 * 4 * 2304 * 2), state.captureBytes(7)); + const off = 3 * state.feature_row_bytes; + const tp = state.Tap{ .buf = null, .off = off, .start = 100, .rows = 4, .gen = 9 }; + try std.testing.expectEqual(off, try state.featureOffset(tp, 100, 4, 9)); + try std.testing.expectEqual(off + 2 * state.feature_row_bytes, try state.featureOffset(tp, 102, 2, 9)); + try std.testing.expectError(error.StaleInkling2Taps, state.featureOffset(tp, 100, 1, 10)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 99, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 102, 3, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 104, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(tp, 100, 0, 9)); + var accepted = tp; + accepted.rows = 2; + try std.testing.expectEqual(off + state.feature_row_bytes, try state.featureOffset(accepted, 101, 1, 9)); + try std.testing.expectError(error.Inkling2TapsNotHeld, state.featureOffset(accepted, 102, 1, 9)); + accepted.gen = null; // the copied prompt-last row survives later scratch generations + try std.testing.expectEqual(off, try state.featureOffset(accepted, 100, 1, 1000)); +} + +test "tap48 captures every final-norm row but last-row-only logits keep their exact source" { + const captured = fwd.finalPlan(7, false, true); + try std.testing.expectEqual(@as(usize, 7), captured.work_rows); + try std.testing.expectEqual(@as(usize, 7), captured.capture_rows); + try std.testing.expectEqual(@as(usize, 1), captured.logits_rows); + try std.testing.expectEqual(@as(usize, 6), captured.logits_row); + try std.testing.expectEqual(@as(usize, 6 * state.hidden * 2), captured.logits_row * state.hidden * 2); + const all = fwd.finalPlan(7, true, true); + try std.testing.expectEqual(@as(usize, 7), all.logits_rows); + try std.testing.expectEqual(@as(usize, 0), all.logits_row); +} + +test "no-draft defaults retain KIM2's single last-row final norm and no capture" { + const options: fwd.Options = .{}; + try std.testing.expect(options.taps == null); + const plain = fwd.finalPlan(7, false, options.taps != null); + try std.testing.expectEqual(@as(usize, 1), plain.work_rows); + try std.testing.expectEqual(@as(usize, 0), plain.capture_rows); + try std.testing.expectEqual(@as(usize, 1), plain.logits_rows); + try std.testing.expectEqual(@as(usize, 0), plain.logits_row); + const all = fwd.finalPlan(7, true, false); + try std.testing.expectEqual(@as(usize, 7), all.work_rows); + try std.testing.expectEqual(@as(usize, 7), all.logits_rows); + try std.testing.expectEqual(@as(usize, 0), all.capture_rows); +} + +test "prepare_features requires exactly Mini's checkpoint tap list" { + var c = mini(); + c.mtp = .{ + .layers = 3, + .q_heads = 24, + .kv_heads = 8, + .head_dim = 128, + .inter = 9216, + .rope_theta = 1e6, + .window = 1024, + .local = .{ true, false, true, false, false, false, false, false }, + .block = 8, + .rank = 256, + .taps = .{ 5, 23, 41, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + .taps_n = 4, + }; + try backend.validateTaps(&c, &.{ 5, 23, 41, 48 }); + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41 })); + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 11, 41, 48 })); + c.mtp.?.taps[1] = 22; + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41, 48 })); + c.mtp = null; + try std.testing.expectError(error.UnsupportedInkling2Taps, backend.validateTaps(&c, &.{ 5, 23, 41, 48 })); +} + +/// Every head's first `rows` rows of every slot's keys and values, then the convolution states, to or from `flat`. +fn moveLive(queue: mtl.Queue, cache: *const state.Cache, flat: mtl.Buffer, rows: usize, into: bool) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + const n = rows * ap.head_dim * 2; + var at: usize = 0; + for (0..state.visit_slots) |slot| for ([_]usize{ cache.key_at[slot], cache.value_at[slot] }) |base| for (0..state.kv_width / ap.head_dim) |h| { + const off = base + h * cache.ring(slot) * ap.head_dim * 2; + if (into) e.copy(flat, at, cache.kv, off, n) else e.copy(cache.kv, off, flat, at, n); + at += n; + }; + if (into) e.copy(flat, at, cache.conv, 0, state.conv_bytes) else e.copy(cache.conv, 0, flat, at, state.conv_bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; +} + +test "A snapshot restores each head's live rows into a cache of another capacity" { + const device = mtl.Device.init() catch return error.SkipZigTest; + const queue = try device.queue(); + defer queue.deinit(); + const p = schedule(); + const rows = 100; + var from = try state.Cache.init(device, 200, &p); + defer from.deinit(); + var to = try state.Cache.init(device, 500, &p); + defer to.deinit(); + try std.testing.expect(from.ring(5) != to.ring(5) and from.globals[5] and rows < from.ring(0)); + const size = state.visit_slots * 2 * state.kv_width * 2 * rows + state.conv_bytes; + const want = try device.buffer(size, mtl.ResourceOptions.shared); + defer want.deinit(); + const got = try device.buffer(size, mtl.ResourceOptions.shared); + defer got.deinit(); + var prng = std.Random.DefaultPrng.init(7); + prng.random().bytes(want.slice(u8, size)); + try moveLive(queue, &from, want, rows, true); + from.len = rows; + var snap = try snapshot.save(device, queue, &from); + defer snap.deinit(); + try snapshot.restore(&to, queue, &snap); + try std.testing.expectEqual(@as(usize, rows), to.len); + try moveLive(queue, &to, got, rows, false); + try std.testing.expect(std.mem.eql(u8, want.slice(u8, size), got.slice(u8, size))); +} + +/// One head's whole ring of a slot's keys or values, to or from `flat` at `at`. +fn moveHead(e: mtl.BlitEncoder, cache: *const state.Cache, slot: usize, values: bool, head: usize, flat: mtl.Buffer, at: usize, rows: usize, into: bool) void { + const row = ap.head_dim * 2; + const off = (if (values) cache.value_at[slot] else cache.key_at[slot]) + head * cache.ring(slot) * row; + if (into) e.copy(flat, at, cache.kv, off, rows * row) else e.copy(cache.kv, off, flat, at, rows * row); +} + +test "A snapshot keeps a wrapped sliding ring's window less one by position, and no row before it" { + const device = mtl.Device.init() catch return error.SkipZigTest; + const queue = try device.queue(); + defer queue.deinit(); + const p = schedule(); + // Past the sliding ring, so it has wrapped: the kept rows are positions at - 1023 to at - 1, in two runs of slots. + const at = state.sliding_ring + 452; + var from = try state.Cache.init(device, 3000, &p); + defer from.deinit(); + var to = try state.Cache.init(device, 3500, &p); + defer to.deinit(); + const row = ap.head_dim * 2; + const heads = state.kv_width / ap.head_dim; + // A sliding slot and a global one, the first and last head of each side. + var sliding: usize = 0; + var global: usize = 0; + for (0..state.visit_slots) |slot| { + if (from.globals[slot]) global = slot else sliding = slot; + } + try std.testing.expect(from.ring(global) != to.ring(global) and from.ring(sliding) == state.sliding_ring and from.ring(global) >= at); + const span = @max(state.sliding_ring, from.ring(global)); + const picks = [_]struct { slot: usize, values: bool, head: usize }{ + .{ .slot = sliding, .values = false, .head = 0 }, .{ .slot = sliding, .values = true, .head = heads - 1 }, + .{ .slot = global, .values = false, .head = heads - 1 }, .{ .slot = global, .values = true, .head = 0 }, + }; + const want = try device.buffer(picks.len * span * row, mtl.ResourceOptions.shared); + defer want.deinit(); + const got = try device.buffer(picks.len * span * row, mtl.ResourceOptions.shared); + defer got.deinit(); + var prng = std.Random.DefaultPrng.init(11); + prng.random().bytes(want.slice(u8, picks.len * span * row)); + { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + for (picks, 0..) |pick, i| moveHead(e, &from, pick.slot, pick.values, pick.head, want, i * span * row, from.ring(pick.slot), true); + e.end(); + cb.commit(); + cb.wait(); + } + from.len = at; + var snap = try snapshot.save(device, queue, &from); + defer snap.deinit(); + try snapshot.restore(&to, queue, &snap); + { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + for (picks, 0..) |pick, i| moveHead(e, &to, pick.slot, pick.values, pick.head, got, i * span * row, @min(to.ring(pick.slot), span), false); + e.end(); + cb.commit(); + cb.wait(); + } + const w = want.slice(u8, picks.len * span * row); + const g = got.slice(u8, picks.len * span * row); + for (picks, 0..) |pick, i| { + const base = i * span * row; + const first = if (from.globals[pick.slot]) 0 else at - (state.sliding_window - 1); + // A kept position sits at its slot of the saver's ring in `want` and of the restorer's in `got`. + for (first..at) |pos| { + const a = base + (pos % from.ring(pick.slot)) * row; + const b = base + (pos % to.ring(pick.slot)) * row; + try std.testing.expect(std.mem.eql(u8, w[a..][0..row], g[b..][0..row])); + } + // The position before a sliding layer's kept rows was not carried over: its slot is still empty. + if (!from.globals[pick.slot]) { + const b = base + ((first - 1) % to.ring(pick.slot)) * row; + try std.testing.expect(std.mem.allEqual(u8, g[b..][0..row], 0)); + } + } +} diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/families/inkling2/metal/serving_test.zig new file mode 100644 index 00000000000..c0b9898e240 --- /dev/null +++ b/zig/src/families/inkling2/metal/serving_test.zig @@ -0,0 +1,341 @@ +//! Real-checkpoint Mini serving: serial target references, cache restore, DSpark and exact transactions. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const api = @import("engine_api"); +const native = @import("../../../native/inkling2.zig"); +const Model = @import("model.zig").Model; +const backend = @import("backend.zig"); +const st = @import("state.zig"); +const dspark = @import("dspark.zig"); + +const gpa = std.testing.allocator; +const io = std.testing.io; +/// A history the prompt cache can end a state on: the family's chunk grid. +const history = st.prompt_rows; +const context = 4 * history; +const made = 24; +const taps = [_]u32{ 5, 23, 41, 48 }; + +fn checkpoint() ![]const u8 { + return @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse error.SkipZigTest; +} + +fn prompt(comptime n: usize, salt: u32) [n]u32 { + var ids: [n]u32 = undefined; + for (&ids, 0..) |*id, i| id.* = @intCast(1000 + (i * 37 + @as(usize, salt) * 101) % 20000); + return ids; +} + +const TapSink = struct { + bytes: [st.feature_row_bytes]u8 = @splat(0), + seen: usize = 0, + + fn take(ptr: *anyopaque, s: *lanes.Stream, f: lanes.backend.Features, start: u64) !void { + const self: *TapSink = @ptrCast(@alignCast(ptr)); + try std.testing.expectEqual(lanes.backend.Features.Space.device, f.space); + try std.testing.expectEqual(lanes.backend.Features.Dtype.bf16, f.dtype); + try std.testing.expectEqual(@as(u32, st.feature_row_bytes), f.row_bytes); + try std.testing.expect(f.rows > 0); + if (start + f.rows != s.prompt_len) return; + const buf: mtl.Buffer = .{ .id = @ptrFromInt(f.buffer) }; + const bytes = buf.slice(u8, @intCast(f.offset + f.rows * f.row_bytes)); + const last = bytes[@intCast(f.offset + (f.rows - 1) * f.row_bytes)..][0..st.feature_row_bytes]; + @memcpy(&self.bytes, last); + self.seen += 1; + } +}; + +fn featureRow(b: lanes.backend.Backend, s: *lanes.Stream, start: u64) ![st.feature_row_bytes]u8 { + const f = try b.features(s, &taps, start, 1); + try std.testing.expectEqual(lanes.backend.Features.Space.device, f.space); + try std.testing.expectEqual(lanes.backend.Features.Dtype.bf16, f.dtype); + try std.testing.expectEqual(@as(u32, 1), f.rows); + try std.testing.expectEqual(@as(u32, st.feature_row_bytes), f.row_bytes); + const buf: mtl.Buffer = .{ .id = @ptrFromInt(f.buffer) }; + const bytes = buf.slice(u8, @intCast(f.offset + f.row_bytes)); + var row: [st.feature_row_bytes]u8 = undefined; + @memcpy(&row, bytes[@intCast(f.offset)..][0..st.feature_row_bytes]); + return row; +} + +const Reference = struct { + tokens: [made]u32, + first: lanes.LogprobRow, + tap: [st.feature_row_bytes]u8, + full_tap: [st.feature_row_bytes]u8 = undefined, + partial_tap: [st.feature_row_bytes]u8 = undefined, + continuation_tap: [st.feature_row_bytes]u8 = undefined, +}; + +fn serial(b: lanes.backend.Backend, ids: []const u32) !Reference { + var sink: TapSink = .{}; + var s = try lanes.Stream.init(gpa, .{ .id = "host-reference", .prompt = ids, .max_new = made, .drafts = false, .logprobs = 3 }); + defer s.deinit(gpa); + try b.vtable.prefill_features.?(b.ptr, &s, &taps, .{ .ptr = &sink, .take = TapSink.take }); + defer b.release(&s); + try std.testing.expectEqual(@as(usize, 1), sink.seen); + var next = try b.read(try b.first(&s, ids.len)); + const first = try b.firstRow(&s); + var out: Reference = .{ .tokens = undefined, .first = first, .tap = sink.bytes }; + out.tokens[0] = next; + try std.testing.expectEqual(next, first.token); + for (1..made) |i| { + next = try b.read(try b.queue(&s, .{ .value = next }, ids.len + i)); + out.tokens[i] = next; + switch (i) { + 8 => out.full_tap = try featureRow(b, &s, ids.len + 7), + 15 => out.partial_tap = try featureRow(b, &s, ids.len + 14), + 16 => out.continuation_tap = try featureRow(b, &s, ids.len + 15), + else => {}, + } + } + return out; +} + +fn withReference(dir: []const u8, ids: []const u32, extended: ?[]const u32) !struct { first: Reference, second: ?Reference } { + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 1, .budget = 2 * st.cacheBytes(context) }); + defer target.deinit(); + try target.warm(); + const b = target.backend(); + try b.vtable.prepare_features.?(b.ptr, &taps); + const first = try serial(b, ids); + const repeated = try serial(b, ids); + try std.testing.expectEqualSlices(u8, &first.tap, &repeated.tap); + try std.testing.expectEqualSlices(u32, &first.tokens, &repeated.tokens); + try expectFirstRow(first.first, repeated.first); + const second = if (extended) |p| try serial(b, p) else null; + return .{ .first = first, .second = second }; +} + +fn expectFirstRow(want: lanes.LogprobRow, got: lanes.LogprobRow) !void { + try std.testing.expectEqual(want.token, got.token); + try std.testing.expectEqual(@as(u32, @bitCast(want.logprob)), @as(u32, @bitCast(got.logprob))); + try std.testing.expectEqual(want.count, got.count); + try std.testing.expectEqualSlices(u32, want.ids[0..want.count], got.ids[0..got.count]); + try std.testing.expectEqualSlices(f32, want.logprobs[0..want.count], got.logprobs[0..got.count]); +} + +const Reply = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + rows: std.ArrayList(lanes.LogprobRow) = .empty, + cached: ?u32 = null, + drafted: u64 = 0, + accepted: u64 = 0, + done: ?api.Reason = null, + + fn event(ptr: *anyopaque, _: api.Id, item: *const api.Event) void { + const self: *Reply = @ptrCast(@alignCast(ptr)); + self.mutex.lockUncancelable(io); + defer self.mutex.unlock(io); + switch (item.*) { + .tokens => |ids| self.tokens.appendSlice(gpa, ids) catch {}, + .logprobs => |rows| self.rows.appendSlice(gpa, rows) catch {}, + .prefilled => |n| self.cached = n, + .finished => |f| { + self.done = f.reason; + self.drafted = f.stats.drafted; + self.accepted = f.stats.accepted; + }, + else => {}, + } + } + + fn wait(self: *Reply) !api.Reason { + for (0..600_000) |_| { + self.mutex.lockUncancelable(io); + const done = self.done; + self.mutex.unlock(io); + if (done) |reason| return reason; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return error.Timeout; + } + + fn deinit(self: *Reply) void { + self.tokens.deinit(gpa); + self.rows.deinit(gpa); + } +}; + +fn serve(native_opened: api.Opened, id: api.Id, request: *const api.Request) !Reply { + var reply: Reply = .{}; + errdefer reply.deinit(); + try native_opened.engine.submit(id, request, .{ .ctx = &reply, .event = Reply.event }); + try std.testing.expectEqual(api.Reason.length, try reply.wait()); + try std.testing.expectEqual(@as(usize, made), reply.tokens.items.len); + return reply; +} + +fn opened(dir: []const u8, drafter: ?[]const u8, cache_gib: ?f64) !api.Opened { + var why: []const u8 = ""; + const result = try native.open(gpa, gpa, io, .{ + .dir = dir, + .model_type = "inkling2_loop", + .context = context, + .lanes = 1, + .drafts = drafter != null, + .drafter = drafter, + .prompt_cache_gib = cache_gib, + .decode_share = 0.5, + }, &why); + if (result == null) { + std.debug.print("Mini Metal open refused: {s}\n", .{why}); + return error.MiniMetalOpenRefused; + } + return result.?; +} + +fn expectTokens(want: *const Reference, got: *const Reply) !void { + try std.testing.expectEqualSlices(u32, &want.tokens, got.tokens.items); + try std.testing.expect(got.rows.items.len >= 1); + try expectFirstRow(want.first, got.rows.items[0]); +} + +fn transactions(dir: []const u8, drafter_dir: []const u8, ids: []const u32, want: *const Reference) !void { + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 1, .budget = st.cacheBytes(context) }); + defer target.deinit(); + const draft_head = try dspark.Drafter.init(gpa, io, model.device, model, drafter_dir); + defer draft_head.deinit(); + try draft_head.lanes.setContext(context); + var wrapped = try lanes.drafted.Drafted.init(gpa, target.backend(), draft_head.lanes.drafter()); + defer wrapped.deinit(); + wrapped.first_rows = true; + const b = wrapped.backend(); + const target_b = target.backend(); + var s = try lanes.Stream.init(gpa, .{ .id = "transactions", .prompt = ids, .max_new = made, .drafts = true, .logprobs = 3 }); + defer s.deinit(gpa); + try b.prefill(&s); + defer b.release(&s); + try std.testing.expectEqual(want.tokens[0], try b.read(try b.first(&s, ids.len))); + try expectFirstRow(want.first, try b.firstRow(&s)); + try std.testing.expectEqualSlices(u8, &want.tap, &(try featureRow(target_b, &s, ids.len - 1))); + + const full_drafts = want.tokens[1..8]; + const full_positions = [_]u64{ ids.len + 1, ids.len + 2, ids.len + 3, ids.len + 4, ids.len + 5, ids.len + 6, ids.len + 7, ids.len + 8 }; + const full_path = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7 }; + const full = [_]lanes.backend.Window{.{ .stream = &s, .pending = want.tokens[0], .held = 0, .tokens = full_drafts, .parents = null, .positions = &full_positions }}; + var sampled: [8]u32 = undefined; + var echo: [7]u32 = undefined; + var full_out = [_]lanes.backend.Verified{.{ .sampled = &sampled, .drafts = &echo }}; + try b.verify(&full, &full_out); + try std.testing.expectEqualSlices(u32, want.tokens[1..9], &sampled); + try std.testing.expectEqualSlices(u32, full_drafts, &echo); + try b.keep(&full, &.{&full_path}); + try std.testing.expectEqualSlices(u8, &want.full_tap, &(try featureRow(target_b, &s, ids.len + 7))); + try b.draft(&.{.{ .stream = &s, .follow = want.tokens[1..9], .rows = &full_path, .start = ids.len, .position = ids.len + 9, .depth = 7 }}); + + var partial_drafts = want.tokens[9..16].*; + partial_drafts[6] = (want.tokens[15] + 1) % model.config.text.unpadded_vocab; + const partial_positions = [_]u64{ ids.len + 9, ids.len + 10, ids.len + 11, ids.len + 12, ids.len + 13, ids.len + 14, ids.len + 15, ids.len + 16 }; + const partial = [_]lanes.backend.Window{.{ .stream = &s, .pending = want.tokens[8], .held = 0, .tokens = &partial_drafts, .parents = null, .positions = &partial_positions }}; + const path = [_]u32{ 0, 1, 2, 3, 4, 5, 6 }; + var partial_out = [_]lanes.backend.Verified{.{ .sampled = &sampled, .drafts = &echo }}; + try b.verify(&partial, &partial_out); + try std.testing.expectEqualSlices(u32, want.tokens[9..16], sampled[0..7]); + try b.keep(&partial, &.{&path}); + try std.testing.expectEqualSlices(u8, &want.partial_tap, &(try featureRow(target_b, &s, ids.len + 14))); + try b.draft(&.{.{ .stream = &s, .follow = want.tokens[9..16], .rows = &path, .start = ids.len + 8, .position = ids.len + 16, .depth = 7 }}); + const next = try b.read(try b.queue(&s, .{ .value = want.tokens[15] }, ids.len + 16)); + try std.testing.expectEqual(want.tokens[16], next); + try std.testing.expectEqualSlices(u8, &want.continuation_tap, &(try featureRow(target_b, &s, ids.len + 15))); +} + +test "Mini Metal serving matches the host reference token for token" { + const dir = try checkpoint(); + const ids = prompt(history, 1); + var turn: [history + 16]u32 = undefined; + @memcpy(turn[0..history], &ids); + @memcpy(turn[history..], &prompt(16, 2)); + const refs = try withReference(dir, &ids, &turn); + var tap_nonzero = false; + for (refs.first.tap) |byte| tap_nonzero = tap_nonzero or byte != 0; + try std.testing.expect(tap_nonzero); + + const opened_once = try opened(dir, null, 1); + defer opened_once.close(opened_once.ctx); + try std.testing.expectEqual(@as(?f64, 0.5), opened_once.engine.info().decode_share); + const keepalive = opened_once.engine.keepaliveTarget() orelse return error.MissingMiniKeepalive; + keepalive.tick(keepalive.ctx); + var first = try serve(opened_once, 1, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer first.deinit(); + try expectTokens(&refs.first, &first); + var fresh = try serve(opened_once, 2, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer fresh.deinit(); + try std.testing.expectEqual(@as(?u32, 0), fresh.cached); + try expectTokens(&refs.second.?, &fresh); + var restored = try serve(opened_once, 3, &.{ .prompt = &turn, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer restored.deinit(); + try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); + try expectTokens(&refs.second.?, &restored); +} + +test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back exactly" { + const dir = try checkpoint(); + const drafter = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + const ids = prompt(history, 3); + var turn: [history + 16]u32 = undefined; + @memcpy(turn[0..history], &ids); + @memcpy(turn[history..], &prompt(16, 2)); + const refs = try withReference(dir, &ids, &turn); + try transactions(dir, drafter, &ids, &refs.first); + + const opened_once = try opened(dir, drafter, 1); + defer opened_once.close(opened_once.ctx); + var plain = try serve(opened_once, 10, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); + defer plain.deinit(); + try expectTokens(&refs.first, &plain); + try std.testing.expectEqual(@as(u64, 0), plain.drafted); + var drafted = try serve(opened_once, 11, &.{ .prompt = &ids, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + defer drafted.deinit(); + try expectTokens(&refs.first, &drafted); + try std.testing.expect(drafted.drafted > 0); + try std.testing.expect(drafted.accepted > 0); + var fresh = try serve(opened_once, 12, &.{ .prompt = &turn, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + defer fresh.deinit(); + try std.testing.expectEqual(@as(?u32, 0), fresh.cached); + try expectTokens(&refs.second.?, &fresh); + var restored = try serve(opened_once, 13, &.{ .prompt = &turn, .max_tokens = made, .drafts = true, .logprobs = 3, .history_len = ids.len }); + defer restored.deinit(); + try std.testing.expectEqual(@as(?u32, ids.len), restored.cached); + try expectTokens(&refs.second.?, &restored); +} + +test "Mini Metal fills a prompt a chunk a call to the whole pass's first row and features" { + const dir = try checkpoint(); + const ids = prompt(64, 5); + const cuts = [_]u32{ 20, 41 }; + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 2, .budget = 2 * st.cacheBytes(context) }); + defer target.deinit(); + const b = target.backend(); + try b.vtable.prepare_features.?(b.ptr, &taps); + var whole = try lanes.Stream.init(gpa, .{ .id = "whole", .prompt = &ids, .max_new = made, .drafts = false, .logprobs = 3, .chunks = &cuts }); + defer whole.deinit(gpa); + try b.prefill(&whole); + defer b.release(&whole); + try std.testing.expectEqual(@as(u32, ids.len), whole.fill_at.load(.monotonic)); + var stepped = try lanes.Stream.init(gpa, .{ .id = "stepped", .prompt = &ids, .max_new = made, .drafts = false, .logprobs = 3, .chunks = &cuts }); + defer stepped.deinit(gpa); + defer b.release(&stepped); + var from: u32 = 0; + for ([_]u32{ 20, 41, ids.len }) |end| { + try std.testing.expectEqual(end == ids.len, try b.vtable.prefill_step.?(b.ptr, &stepped, 0)); + try std.testing.expectEqual(end, stepped.fill_at.load(.monotonic)); + // A chunk's rows are held until the next forward, and an earlier chunk's are not. + try std.testing.expectEqual(end - from, (try b.features(&stepped, &taps, from, end - from)).rows); + if (from > 0) try std.testing.expectError(error.Inkling2TapsNotHeld, b.features(&stepped, &taps, 0, from)); + from = end; + } + try std.testing.expectEqualSlices(u8, &(try featureRow(b, &whole, ids.len - 1)), &(try featureRow(b, &stepped, ids.len - 1))); + const whole_first = try b.read(try b.first(&whole, ids.len)); + const whole_row = try b.firstRow(&whole); + try std.testing.expectEqual(whole_first, try b.read(try b.first(&stepped, ids.len))); + try expectFirstRow(whole_row, try b.firstRow(&stepped)); +} diff --git a/zig/src/families/inkling2/metal/snapshot.zig b/zig/src/families/inkling2/metal/snapshot.zig new file mode 100644 index 00000000000..e7b9c850b8f --- /dev/null +++ b/zig/src/families/inkling2/metal/snapshot.zig @@ -0,0 +1,89 @@ +//! Compact retained snapshots: the rows the shared kept-state walk names, then all convolution states. +const std = @import("std"); +const mtl = @import("metal"); +const state = @import("state.zig"); +const ap = @import("attention_plan.zig"); +const kept = @import("../kept_state.zig"); + +/// Eight global layers keep [0, at); forty sliding ones the window less one that their next row reads. +pub fn bytes(at: usize) u64 { + const rows = @as(u64, 8) * kept.kept(true, state.sliding_window, at) + @as(u64, 40) * kept.kept(false, state.sliding_window, at); + return rows * @as(u64, state.kv_width) * 4 + state.conv_bytes; +} + +/// A cache's visits as the shared walk reads them: a slot's K and V, each head-major, and its ring. +fn visits(cache: *const state.Cache) [state.visit_slots]kept.Visit { + var out: [state.visit_slots]kept.Visit = undefined; + for (&out, 0..) |*v, slot| v.* = .{ .k = cache.key_at[slot], .v = cache.value_at[slot], .heads = state.kv_width / ap.head_dim, .ring = cache.ring(slot), .row = ap.head_dim * 2, .global = cache.globals[slot] }; + return out; +} + +pub const Snap = struct { + buf: mtl.Buffer, + at: usize, + bytes: u64, + freed: bool = false, + follow: ?mtl.ResidencySet.Follow = null, + + pub fn free(s: *Snap) void { + if (!s.freed) { + s.setResident(null); + s.buf.deinit(); + s.freed = true; + } + } + + pub fn deinit(s: *Snap) void { + s.free(); + } + + pub fn setResident(s: *Snap, hook: ?mtl.ResidencySet.Follow) void { + if (s.freed) return; + if (s.follow) |f| f.leave(f.ctx, s.buf); + s.follow = hook; + if (hook) |f| f.join(f.ctx, s.buf); + } +}; + +fn encode(queue: mtl.Queue, cache: *const state.Cache, snap_buf: mtl.Buffer, snap: ?*const Snap, comptime what: []const u8) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + const len = if (snap) |image| image.at else cache.len; + // Rows go by position, so a state restores into rings of another size; a wrapped ring is two pieces a head. + const all = visits(cache); + var walk = kept.Walk.init(&all, state.sliding_window, len); + while (walk.next()) |p| { + const in_cache: usize = @intCast(p.cache); + const in_state: usize = @intCast(p.offset); + if (snap) |image| e.copy(image.buf, in_state, cache.kv, in_cache, @intCast(p.len)) else e.copy(cache.kv, in_cache, snap_buf, in_state, @intCast(p.len)); + } + const at: usize = @intCast(walk.offset); + if (snap) |image| e.copy(image.buf, at, cache.conv, 0, state.conv_bytes) else e.copy(cache.conv, 0, snap_buf, at, state.conv_bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop snapshot {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +/// GPU-private snapshots keep only the rows a later row can read, never full-capacity allocations. +pub fn save(device: mtl.Device, queue: mtl.Queue, cache: *const state.Cache) !Snap { + if (cache.pending != null) return error.Inkling2CacheTransaction; + const size = bytes(cache.len); + const buf = try device.buffer(@intCast(size), mtl.ResourceOptions.private); + errdefer buf.deinit(); + try encode(queue, cache, buf, null, "save"); + return .{ .buf = buf, .at = cache.len, .bytes = size }; +} + +/// Restore into an empty cache whose rings hold the kept rows; they may be of another size than the saver's. +pub fn restore(cache: *state.Cache, queue: mtl.Queue, snap: *const Snap) !void { + if (snap.freed or cache.len != 0 or cache.pending != null or snap.at > cache.capacity or snap.bytes < bytes(snap.at)) return error.Inkling2SnapshotGeometry; + if (!kept.fits(&visits(cache), state.sliding_window, snap.at)) return error.Inkling2SnapshotGeometry; + try encode(queue, cache, snap.buf, snap, "restore"); + cache.len = snap.at; +} diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig new file mode 100644 index 00000000000..7749d9b8d05 --- /dev/null +++ b/zig/src/families/inkling2/metal/state.zig @@ -0,0 +1,384 @@ +//! Forty-eight independent visit caches and the GPU buffers used by one whole-loop forward. +const std = @import("std"); +const mtl = @import("metal"); +const plan = @import("../plan.zig"); +const ap = @import("attention_plan.zig"); + +pub const window_rows = 16; +pub const batch_rows = 32; +pub const prompt_rows = 1024; +pub const max_rows = 1024; +pub const max_segments = batch_rows; +pub const max_attention_stride = 64; +pub const hidden = 2304; +pub const feature_taps = 4; +pub const feature_row_bytes = feature_taps * hidden * 2; + +pub fn captureBytes(rows: usize) usize { + return rows * feature_row_bytes; +} +pub const query_width = 3072; +pub const kv_width = 1024; +pub const rel_width = 384; +pub const experts_per_token = 8; +pub const intermediate = 1152; +pub const vocabulary = 200058; +pub const message_entries = 48; +pub const block_slots = 4; +pub const conv_states = 4; +pub const visit_slots = 48; +/// A sliding layer's span: a row reads itself and the `sliding_window - 1` rows before it. +pub const sliding_window = 1024; +pub const sliding_ring = ap.ringFor(sliding_window, max_rows); +pub const conv_widths = [conv_states]usize{ 1024, 1024, 2304, 2304 }; +pub const conv_row_values = 1024 + 1024 + 2304 + 2304; +pub const conv_bytes = visit_slots * 3 * conv_row_values * 2; +/// A cache stages a round's taps: three old rows and a window. A wider chunk stages in its scratch. +pub const stage_rows = 3 + window_rows; +pub const taps_bytes = visit_slots * stage_rows * conv_row_values * 2; +/// A scratch's staged taps for a chunk of up to `rows`; none where a cache's own staging holds them. +pub fn stageBytes(rows: usize) usize { + return if (rows > window_rows) visit_slots * (3 + rows) * conv_row_values * 2 else 0; +} + +pub fn globalSlots(capacity: usize) usize { + return std.mem.alignForward(usize, capacity, ap.tile_keys); +} + +pub fn globalStride(capacity: usize) usize { + return @max(@as(usize, ap.sliding_chunk / ap.tile_keys + 2), std.math.divCeil(usize, capacity, ap.global_chunk) catch unreachable); +} + +pub fn kvBytes(capacity: usize) usize { + const row_bytes = kv_width * 2; + return 40 * sliding_ring * 2 * row_bytes + 8 * globalSlots(capacity) * 2 * row_bytes; +} + +pub fn cacheBytes(capacity: usize) usize { + return kvBytes(capacity) + conv_bytes + taps_bytes + conv_bytes + vocabulary * 4; +} + +pub fn convWidth(state: usize) usize { + std.debug.assert(state < conv_states); + return conv_widths[state]; +} + +/// Values before a convolution state's rows in one slot's tightly sized layout. +pub fn convBase(state: usize, tap_rows: usize) usize { + var out: usize = 0; + for (0..state) |s| out += tap_rows * conv_widths[s]; + return out; +} + +pub fn convByteOffset(slot: usize, state: usize, rows_before: usize, tap_rows: usize) usize { + std.debug.assert(slot < visit_slots and rows_before <= tap_rows); + return (slot * tap_rows * conv_row_values + convBase(state, tap_rows) + rows_before * convWidth(state)) * 2; +} + +pub const Ref = @import("inkling2_metal_ref").Ref; + +/// Tap rows cover [start,start+rows); scratch rows carry a generation, unlike the prompt's stable last row. +pub const Tap = struct { buf: ?mtl.Buffer = null, off: usize = 0, start: u64 = 0, rows: usize = 0, gen: ?u64 = null }; + +/// Byte offset of a requested held feature range, rejecting stale and rejected rows. +pub fn featureOffset(t: Tap, start: u64, count: u32, generation: u64) !usize { + if (t.gen) |g| if (g != generation) return error.StaleInkling2Taps; + if (count == 0 or start < t.start) return error.Inkling2TapsNotHeld; + const delta = start - t.start; + const held: u64 = @intCast(t.rows); + if (delta >= held or count > held - delta) return error.Inkling2TapsNotHeld; + return t.off + @as(usize, @intCast(delta)) * feature_row_bytes; +} + +pub const Cache = struct { + kv: mtl.Buffer, + conv: mtl.Buffer, + taps: mtl.Buffer, + backup: mtl.Buffer, + logits: mtl.Buffer, + tap: Tap = .{}, + /// A stepped prompt chunk's rows, good until the next forward. + fill_tap: Tap = .{}, + last_tap: ?mtl.Buffer = null, + key_at: [visit_slots]usize, + value_at: [visit_slots]usize, + rings: [visit_slots]u32, + globals: [visit_slots]bool, + capacity: usize, + len: usize = 0, + pending: ?usize = null, + follow: ?mtl.ResidencySet.Follow = null, + + pub fn init(device: mtl.Device, capacity: usize, schedule: *const plan.Plan) !Cache { + if (capacity == 0 or capacity > 1048576 or schedule.n_visits != visit_slots) return error.Inkling2CacheShape; + var out: Cache = .{ + .kv = undefined, + .conv = undefined, + .taps = undefined, + .backup = undefined, + .logits = undefined, + .key_at = undefined, + .value_at = undefined, + .rings = undefined, + .globals = undefined, + .capacity = capacity, + }; + var at: usize = 0; + for (0..visit_slots) |slot| { + const global = schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global; + const ring_size = if (global) globalSlots(capacity) else sliding_ring; + out.globals[slot] = global; + out.rings[slot] = @intCast(ring_size); + out.key_at[slot] = at; + at += ring_size * kv_width * 2; + out.value_at[slot] = at; + at += ring_size * kv_width * 2; + } + std.debug.assert(at == kvBytes(capacity)); + out.kv = try device.buffer(@max(at, 16), mtl.ResourceOptions.private); + errdefer out.kv.deinit(); + out.conv = try device.buffer(conv_bytes, mtl.ResourceOptions.private); + errdefer out.conv.deinit(); + out.taps = try device.buffer(taps_bytes, mtl.ResourceOptions.private); + errdefer out.taps.deinit(); + out.backup = try device.buffer(conv_bytes, mtl.ResourceOptions.private); + errdefer out.backup.deinit(); + out.logits = try device.buffer(vocabulary * 4, mtl.ResourceOptions.shared); + errdefer out.logits.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.fill(out.conv, 0, conv_bytes, 0); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache clear: {s}", .{msg}); + return error.GpuFailed; + } + return out; + } + + pub fn setResident(c: *Cache, hook: ?mtl.ResidencySet.Follow) void { + const buffers = [_]mtl.Buffer{ c.kv, c.conv, c.taps, c.backup, c.logits }; + if (c.follow) |f| { + for (buffers) |b| f.leave(f.ctx, b); + if (c.last_tap) |b| f.leave(f.ctx, b); + } + c.follow = hook; + if (hook) |f| { + for (buffers) |b| f.join(f.ctx, b); + if (c.last_tap) |b| f.join(f.ctx, b); + } + } + + pub fn ring(c: *const Cache, slot: usize) usize { + return c.rings[slot]; + } + + pub fn keys(c: *const Cache, slot: usize) Ref { + return .{ .buf = c.kv, .off = c.key_at[slot] }; + } + + pub fn values(c: *const Cache, slot: usize) Ref { + return .{ .buf = c.kv, .off = c.value_at[slot] }; + } + + pub fn history(c: *const Cache, slot: usize, state: usize) Ref { + return .{ .buf = c.conv, .off = convByteOffset(slot, state, 0, 3) }; + } + + pub fn staged(c: *const Cache, slot: usize, state: usize, rows_before: usize) Ref { + return .{ .buf = c.taps, .off = convByteOffset(slot, state, rows_before, stage_rows) }; + } + + pub fn attentionLayer(c: *const Cache, schedule: *const plan.Plan, slot: usize, rows: usize) ap.Layer { + std.debug.assert(rows <= max_rows); + var layer = if (schedule.at(schedule.visit(@intCast(slot)).layer).kind == .global) ap.Layer.global(@intCast(c.capacity)) else ap.Layer.sliding(1024, @intCast(rows)); + layer.ring = @intCast(c.ring(slot)); + return layer; + } + + /// Save all four pre-window three-tap histories before KV/conv speculation. + pub fn begin(c: *Cache, queue: mtl.Queue, rows: usize) !void { + if (c.pending != null or rows == 0 or rows > window_rows or c.len + rows > c.capacity) return error.Inkling2CacheTransaction; + try copyGpu(queue, c.conv, 0, c.backup, 0, conv_bytes, "begin"); + c.pending = rows; + } + + /// Commit accepted rows: staged taps select the new state; rejected KV positions are overwritten on replay. + pub fn commit(c: *Cache, queue: mtl.Queue, accepted: usize) !void { + const rows = c.pending orelse return error.Inkling2NoTransaction; + if (accepted > rows) return error.Inkling2CacheTransaction; + if (accepted < rows) { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.copy(c.backup, 0, c.conv, 0, conv_bytes); + for (0..visit_slots) |slot| for (0..conv_states) |state| { + const bytes = 3 * convWidth(state) * 2; + e.copy(c.taps, convByteOffset(slot, state, accepted, stage_rows), c.conv, convByteOffset(slot, state, 0, 3), bytes); + }; + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache commit: {s}", .{msg}); + return error.GpuFailed; + } + } + const start = c.len; + c.len += accepted; + if (c.tap.buf != null and c.tap.start == start) { + c.tap.rows = accepted; + } else c.tap = .{}; + c.pending = null; + } + + pub fn rollback(c: *Cache, queue: mtl.Queue) !void { + _ = c.pending orelse return error.Inkling2NoTransaction; + try copyGpu(queue, c.backup, 0, c.conv, 0, conv_bytes, "rollback"); + c.pending = null; + c.tap = .{}; + } + + pub fn deinit(c: *Cache) void { + c.setResident(null); + c.logits.deinit(); + if (c.last_tap) |b| b.deinit(); + c.backup.deinit(); + c.taps.deinit(); + c.conv.deinit(); + c.kv.deinit(); + c.* = undefined; + } +}; + +fn copyGpu(queue: mtl.Queue, from: mtl.Buffer, from_off: usize, to: mtl.Buffer, to_off: usize, bytes: usize, comptime what: []const u8) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.copy(from, from_off, to, to_off, bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop cache {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +pub const fields = [_][]const u8{ + "ids", "pos", "seg_of", "segs", "p", "prelude", "blocks", "bank0", "bank1", "messages", + "partial", "ar", "gated", "mlp_ar", "mlp_gated", "q_norm", "k_norm", "v_norm", "q_raw", "k_raw", + "v_raw", "rel_raw", "sink", "gate", "k_conv", "v_conv", "q_prep", "rel_prep", "rel_tab", "part_o", + "part_ml", "att", "attn_dense", "mlp_normed", "route_ids", "route_weights", "gu", "down", "mlp_out", "logits_all", +}; + +fn sizes(rows: usize) [fields.len]usize { + const r = rows; + const h = hidden; + const q = query_width; + const kv = kv_width; + const bf = 2; + const fp = 4; + return .{ + r * 4, r * 4, r * 4, max_segments * @sizeOf(ap.Seg), r * h * bf, r * h * bf, r * block_slots * h * bf, + r * h * bf, r * h * bf, r * message_entries * h * fp, r * h * fp, 3 * r * h * fp, 3 * r * h * fp, r * h * fp, + r * h * fp, r * h * bf, r * h * bf, r * h * bf, r * q * bf, r * kv * bf, r * kv * bf, + r * rel_width * bf, r * 24 * bf, r * q * bf, r * kv * bf, r * kv * bf, r * q * bf, r * rel_width * bf, + r * 24 * ap.extent * bf, r * 24 * max_attention_stride * ap.head_dim * fp, r * 24 * max_attention_stride * 2 * fp, r * q * bf, r * h * bf, r * h * bf, r * experts_per_token * 4, + r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, @as(usize, @min(r, batch_rows)) * vocabulary * fp, + }; +} + +pub fn scratchBytes(rows: usize) usize { + var out: usize = 0; + for (sizes(rows)) |n| out += n; + return out + stageBytes(rows); +} + +pub const Scratch = struct { + ids: mtl.Buffer, + pos: mtl.Buffer, + seg_of: mtl.Buffer, + segs: mtl.Buffer, + p: mtl.Buffer, + prelude: mtl.Buffer, + blocks: mtl.Buffer, + bank0: mtl.Buffer, + bank1: mtl.Buffer, + messages: mtl.Buffer, + partial: mtl.Buffer, + ar: mtl.Buffer, + gated: mtl.Buffer, + mlp_ar: mtl.Buffer, + mlp_gated: mtl.Buffer, + q_norm: mtl.Buffer, + k_norm: mtl.Buffer, + v_norm: mtl.Buffer, + q_raw: mtl.Buffer, + k_raw: mtl.Buffer, + v_raw: mtl.Buffer, + rel_raw: mtl.Buffer, + sink: mtl.Buffer, + gate: mtl.Buffer, + k_conv: mtl.Buffer, + v_conv: mtl.Buffer, + q_prep: mtl.Buffer, + rel_prep: mtl.Buffer, + rel_tab: mtl.Buffer, + part_o: mtl.Buffer, + part_ml: mtl.Buffer, + att: mtl.Buffer, + attn_dense: mtl.Buffer, + mlp_normed: mtl.Buffer, + route_ids: mtl.Buffer, + route_weights: mtl.Buffer, + gu: mtl.Buffer, + down: mtl.Buffer, + mlp_out: mtl.Buffer, + logits_all: mtl.Buffer, + /// Opt-in DSpark features [row][tap][H], allocated by prepare_features. + taps: ?mtl.Buffer = null, + /// The staged convolution taps of a chunk wider than a window: this scratch then holds one stream's rows. + stage: ?mtl.Buffer = null, + rows: usize, + + pub fn init(device: mtl.Device, rows: usize) !Scratch { + @setEvalBranchQuota(10_000); + if (rows == 0 or rows > max_rows) return error.Inkling2ScratchRows; + const ns = sizes(rows); + var s: Scratch = undefined; + var made: usize = 0; + errdefer inline for (fields, 0..) |f, i| if (i < made) @field(s, f).deinit(); + inline for (fields, 0..) |f, i| { + @field(s, f) = try device.buffer(@max(ns[i], 16), mtl.ResourceOptions.shared); + made += 1; + } + s.taps = null; + s.rows = rows; + s.stage = if (stageBytes(rows) > 0) try device.buffer(stageBytes(rows), mtl.ResourceOptions.private) else null; + return s; + } + + pub fn deinit(s: *Scratch) void { + inline for (fields) |f| @field(s, f).deinit(); + if (s.taps) |b| b.deinit(); + if (s.stage) |b| b.deinit(); + s.* = undefined; + } + + pub fn staged(s: *const Scratch, slot: usize, state: usize, rows_before: usize) Ref { + return .{ .buf = s.stage.?, .off = convByteOffset(slot, state, rows_before, 3 + s.rows) }; + } +}; + +comptime { + if (sliding_ring != 2048 or conv_bytes != 1916928) @compileError("Inkling cache geometry drift"); +} diff --git a/zig/src/families/inkling2/modelopt.zig b/zig/src/families/inkling2/modelopt.zig new file mode 100644 index 00000000000..7ef444cab24 --- /dev/null +++ b/zig/src/families/inkling2/modelopt.zig @@ -0,0 +1,454 @@ +//! Inkling 2 Mini's routed experts: stored NVFP4/MXFP8 codes, bf16 activations and fp32 routing. +const std = @import("std"); +const cuda = @import("cuda"); +const experts = @import("experts.zig"); +const core = @import("core"); + +pub const Format = enum(i32) { nvfp4 = 0, mxfp8 = 1 }; +pub const max_slots = 32; +const max_experts = 512; + +pub const Projection = struct { + codes: u64, + scales: u64, + amax: u64 = 0, + denominator: u64 = 0, + n: u32, + k: u32, +}; + +/// One physical layer. Loop visits share these device pointers. +pub const Layer = struct { + format: Format, + experts: u32, + w13: Projection, + w2: Projection, +}; + +pub const Weight = extern struct { + codes: u64, + scales: u64, + amax: u64, + denominator: u64, + experts: i64, + n: i64, + k: i64, + group: i32, + format: i32, + row0: i32, + row_step: i32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + plan: cuda.Function, + decode: cuda.Function, + prompt: cuda.Function, + act: cuda.Function, + combine: cuda.Function, + resident: usize, + + pub fn load(d: *const cuda.Driver, sms: usize) !Kernels { + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_modelopt); + errdefer mod.unload(); + const decode = try mod.function("tf_ink2moe_up"); + return .{ + .mod = mod, + .plan = try mod.function("tf_ink2moe_plan"), + .decode = decode, + .prompt = try mod.function("tf_ink2moe_prompt_up"), + .act = try mod.function("tf_ink2moe_act"), + .combine = try mod.function("tf_ink2moe_combine"), + .resident = @max(1, try decode.occupancy(128, 0)) * sms, + }; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + } +}; + +fn aligned(n: usize) usize { + return (n + 255) / 256 * 256; +} + +pub const Layout = struct { + gate: u64, + up: u64, + act: u64, + down: u64, + items: u64, + item_count: u64, + members: u64, + bytes: usize, +}; + +/// Reconstructs the stable intermediate addresses inside one scratch allocation. +pub fn layout(base: u64, rows: usize, slots: usize, hidden: usize, intermediate: usize) Layout { + const pairs = rows * slots; + const items_max = (pairs + 15) / 16 + @min(pairs, max_experts); + var at = base; + const take = struct { + fn f(p: *u64, bytes: usize) u64 { + const r = p.*; + p.* = r + aligned(bytes); + return r; + } + }.f; + const gate = take(&at, pairs * intermediate * 2); + const up = take(&at, pairs * intermediate * 2); + const act = take(&at, pairs * intermediate * 2); + const down = take(&at, pairs * hidden * 2); + const items = take(&at, items_max * 12); + const item_count = take(&at, 4); + const members = take(&at, pairs * 4); + return .{ .gate = gate, .up = up, .act = act, .down = down, .items = items, .item_count = item_count, .members = members, .bytes = at - base }; +} + +/// Gate, up, activation and per-expert outputs, plus the ascending-expert group plan. +pub fn scratchBytes(rows: usize, slots: usize, hidden: usize, intermediate: usize) !usize { + if (rows == 0 or rows > 2048 or slots == 0 or slots > max_slots) return error.BadExperts; + return layout(0, rows, slots, hidden, intermediate).bytes; +} + +fn i32d(v: usize) i32 { + return @intCast(v); +} + +pub fn weight(p: Projection, l: Layer, row0: i32, row_step: i32) Weight { + return .{ + .codes = p.codes, + .scales = p.scales, + .amax = p.amax, + .denominator = p.denominator, + .experts = l.experts, + .n = p.n, + .k = p.k, + .group = if (l.format == .nvfp4) 16 else 32, + .format = @backingInt(l.format), + .row0 = row0, + .row_step = row_step, + }; +} + +fn projection(s: cuda.Stream, fn_: cuda.Function, prompt: bool, resident: usize, x: u64, x_stride: usize, slots: usize, w: Weight, items: u64, item_count: u64, members: u64, out: u64, item_bound: usize) !void { + const kg: usize = @intCast(@divExact(w.k, 32)); + const outputs: usize = @intCast(if (w.row_step == 2) @divExact(w.n, 2) else w.n); + const nb = outputs / 32; + var a: cuda.Args = .{}; + a.add(x); + a.add(i32d(x_stride)); + a.add(i32d(slots)); + a.add(w); + a.add(i32d(kg)); + a.add(i32d(nb)); + for ([_]u64{ items, item_count, members, out }) |v| a.add(v); + a.add(i32d(outputs)); + a.add(@as(i32, -1)); + const bound = item_bound * nb; + const grid = if (prompt) (bound + 3) / 4 else @min((bound + 3) / 4, resident); + if (grid == 0) return; + try cuda.launch.launch(fn_, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, s, &a); +} + +/// Run one MoE layer. `pick` is row-major int32 expert IDs; routing `weights` are fp32. +pub fn run(k: *const Kernels, s: cuda.Stream, l: Layer, caps: experts.Caps, x: u64, x_stride: usize, pick: u64, weights: u64, rows: usize, slots: usize, out: u64, scratch: u64) !void { + if (rows == 0 or rows > 2048 or slots == 0 or slots > max_slots or l.experts == 0 or l.experts > max_experts) return error.BadExperts; + if (l.w13.n % 64 != 0 or l.w13.k % 32 != 0 or l.w2.n % 32 != 0 or l.w2.k % 32 != 0) return error.BadExperts; + if (l.w13.k != l.w2.n or l.w13.n / 2 != l.w2.k or x_stride < l.w13.k) return error.BadExperts; + const hidden: usize = l.w2.n; + const intermediate: usize = l.w2.k; + const pairs = rows * slots; + const b = layout(scratch, rows, slots, hidden, intermediate); + const listed = rows >= 32; + const tile: usize = if (listed) 64 else 16; + const item_bound = (pairs + tile - 1) / tile + @min(pairs, @as(usize, l.experts)); + + var g: cuda.Args = .{}; + for ([_]u64{ pick, b.items, b.members, b.item_count }) |v| g.add(v); + for ([_]usize{ rows, slots, l.experts, tile }) |v| g.add(i32d(v)); + try cuda.launch.launch(k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, s, &g); + + const fn_ = if (listed) k.prompt else k.decode; + try projection(s, fn_, listed, k.resident, x, x_stride, slots, weight(l.w13, l, 0, 2), b.items, b.item_count, b.members, b.gate, item_bound); + try projection(s, fn_, listed, k.resident, x, x_stride, slots, weight(l.w13, l, 1, 2), b.items, b.item_count, b.members, b.up, item_bound); + + var aa: cuda.Args = .{}; + for ([_]u64{ b.gate, b.up, b.act }) |v| aa.add(v); + aa.add(i32d(pairs * intermediate)); + aa.add(caps.gate); + aa.add(caps.up); + try cuda.launch.launch(k.act, .{ .grid = .{ .x = @intCast((pairs * intermediate + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, s, &aa); + try projection(s, fn_, listed, k.resident, b.act, intermediate, 0, weight(l.w2, l, 0, 1), b.items, b.item_count, b.members, b.down, item_bound); + + var ca: cuda.Args = .{}; + for ([_]u64{ pick, weights, b.down, out }) |v| ca.add(v); + for ([_]i32{ i32d(rows), i32d(hidden), i32d(slots), i32d(l.experts) }) |v| ca.add(v); + const count = rows * hidden; + try cuda.launch.launch(k.combine, .{ .grid = .{ .x = @intCast((count + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, s, &ca); +} + +fn put(e: anytype, bytes: []const u8) !u64 { + const p = try e.alloc(bytes.len); + try e.arena.upload(p - e.arena.ptr, bytes); + return p; +} + +fn loadProjection(e: anytype, ck: *core.Checkpoint, prefix: []const u8, name: []const u8, format: Format, count: usize, n: usize, k: usize) !Projection { + var wb: [256]u8 = undefined; + var sb: [256]u8 = undefined; + const weight_name = try std.fmt.bufPrint(&wb, "{s}{s}_weight", .{ prefix, name }); + const scale_name = try std.fmt.bufPrint(&sb, "{s}{s}_weight_scale", .{ prefix, name }); + const w = switch (format) { + .nvfp4 => try ck.expect(weight_name, .u8, &.{ count, n, k / 2 }), + .mxfp8 => try ck.expect(weight_name, .f8_e4m3, &.{ count, n, k }), + }; + const scales = switch (format) { + .nvfp4 => try ck.expect(scale_name, .f8_e4m3, &.{ count, n, k / 16 }), + .mxfp8 => try ck.expect(scale_name, .u8, &.{ count, n, k / 32 }), + }; + var p: Projection = .{ .codes = try put(e, w.bytes), .scales = try put(e, scales.bytes), .n = @intCast(n), .k = @intCast(k) }; + if (format == .nvfp4) { + var ab: [256]u8 = undefined; + var db: [256]u8 = undefined; + const amax = try ck.expect(try std.fmt.bufPrint(&ab, "{s}{s}_weight_amax", .{ prefix, name }), .f32, &.{count}); + const denominator = try ck.expect(try std.fmt.bufPrint(&db, "{s}{s}_weight_outer_scale_denominator", .{ prefix, name }), .f32, &.{1}); + p.amax = try put(e, amax.bytes); + p.denominator = try put(e, denominator.bytes); + } + return p; +} + +/// Upload the checkpoint's two stored projections without a repack or an activation-quantization side input. +pub fn load(e: anytype, ck: *core.Checkpoint, prefix: []const u8, format: Format, count: usize, hidden: usize, intermediate: usize) !Layer { + if (count == 0 or count > max_experts or hidden % 32 != 0 or intermediate % 32 != 0) return error.BadExperts; + return .{ + .format = format, + .experts = @intCast(count), + .w13 = try loadProjection(e, ck, prefix, "w13", format, count, 2 * intermediate, hidden), + .w2 = try loadProjection(e, ck, prefix, "w2", format, count, hidden, intermediate), + }; +} + +test "Mini's expert scratch holds all tensor-core stages and the group plan" { + const bytes = try scratchBytes(2048, 8, 2304, 1152); + try std.testing.expectEqual(@as(usize, 72), @sizeOf(Weight)); + try std.testing.expect(bytes > 2048 * 8 * (3 * 1152 + 2304) * 2); + try std.testing.expectEqual(@as(i32, 0), @backingInt(Format.nvfp4)); + try std.testing.expectEqual(@as(i32, 1), @backingInt(Format.mxfp8)); + try std.testing.expectError(error.BadExperts, scratchBytes(0, 8, 2304, 1152)); +} + +/// One-member warp: A/B lanes explicit; exact rationals expose scalar/mma FP32 reduction diffs despite BF16 rounding. +const FragmentHostProbe = struct { + const expert_count = 2; + const hidden = 64; // two 32-column output blocks in the down projection + const intermediate = 64; // two gate/up blocks and two 32-input groups in down + const gate_cap = 4; + const up_cap = 25; + + const Matrix = struct { + codes: []const u8, + scales: []const u8, + n: usize, + k: usize, + + /// Checkpoint NVFP4 -> BF16, with outer scale one to isolate fragment addressing. + fn decoded(m: Matrix, e: usize, row: usize, col: usize) u16 { + const z = (e * m.n + row) * m.k + col; + const nib = (m.codes[z / 2] >> @as(u3, @intCast(4 * (col & 1)))) & 15; + const magnitude = ([8]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 })[nib & 7]; + const q = if ((nib & 8) != 0) -magnitude else magnitude; + const scale_code = m.scales[z / 16]; + const se = (scale_code >> 3) & 15; + const sm = scale_code & 7; + const sign: u32 = if ((scale_code & 128) != 0) 0x80000000 else 0; + const scale: f32 = if (se == 0) + @as(f32, @floatFromInt(sm)) * 0x1p-9 * (if (sign != 0) @as(f32, -1) else 1) + else + @bitCast(sign | ((@as(u32, se) + 120) << 23) | (@as(u32, sm) << 20)); + return core.bf16_round.bits(q * scale); + } + }; + + fn value(bits: u16) f32 { + return core.bf16_round.value(bits); + } + + fn fill(codes: []u8, scales: []u8, e: usize, n: usize, k: usize, one_per_row: bool) void { + const order = [16]u8{ 2, 10, 4, 13, 1, 7, 14, 0, 3, 9, 5, 12, 6, 15, 11, 8 }; + const scale_codes = [4]u8{ 0x28, 0x30, 0x2c, 0x34 }; // 1/4, 1/2, 3/8, 3/4 + for (0..n) |row| for (0..k) |col| { + const z = (e * n + row) * k + col; + const index = (7 * row + 11 * col + (row * col) % 13 + 3 * e) & 15; + var code = order[index]; + // Down's one nonzero rotates through all K positions over the two output tiles. + if (one_per_row and col != (19 * row + 7 * e) % k) code = 0; + if (one_per_row and col == (19 * row + 7 * e) % k and (code & 7) == 0) code = 2; + if ((col & 1) == 0) codes[z / 2] = code else codes[z / 2] |= code << 4; + if ((col & 15) == 0) scales[z / 16] = scale_codes[(3 * row + col / 16 + e) & 3]; + }; + } + + /// The arithmetic baseline: dequantize row-major weights and evaluate x @ W directly. + fn scalarProjection(m: Matrix, e: usize, row0: usize, row_step: usize, x: []const u16, out: []u16) void { + for (out, 0..) |*o, col| { + var sum: f32 = 0; + const row = row0 + row_step * col; + for (0..m.k) |k| sum += value(x[k]) * value(m.decoded(e, row, k)); + o.* = core.bf16_round.bits(sum); + } + } + + /// Served RT=1 (ten max): materialize uint2/uint4 A/B; m16n8k16 D gathers PTX lanes, B column 2*t+n, not lane gq. + fn fragmentProjection(m: Matrix, e: usize, row0: usize, row_step: usize, x: []const u16, out: []u16, members: usize) void { + const width = out.len / members; + for (0..width / 32) |cb| { + var acc: [32][4][4]f32 = std.mem.zeroes([32][4][4]f32); + for (0..m.k / 32) |g| { + // [lane][row half][q][uint2 member][BF16 in the member] + var a: [32][2][2][2][2]f32 = std.mem.zeroes([32][2][2][2][2]f32); + // Four ld_w uint4s: [n8 tile][lane][eight BF16 values in x,y,z,w]. + var b: [4][32][8]f32 = undefined; + for (0..32) |lane| { + const gq = lane >> 2; + const t = lane & 3; + for (0..2) |h| for (0..2) |q| for (0..2) |pair| for (0..2) |element| { + const i = gq + 8 * h; + // x = X + token*x_stride + 4*t; uint2 spans two adjacent pairs. + const col = 32 * g + 16 * q + 4 * t + 2 * pair + element; + a[lane][h][q][pair][element] = if (i < members) value(x[col]) else 0; + }; + for (0..4) |j| for (0..8) |i| { + const row = row0 + row_step * (cb * 32 + 8 * j + gq); + const col = g * 32 + 4 * t + (i & 3) + 16 * (i >> 2); + b[j][lane][i] = value(m.decoded(e, row, col)); + }; + } + for (0..2) |q| for (0..4) |j| for (0..32) |lane| { + const gq = lane >> 2; + const t = lane & 3; + for (0..2) |h| for (0..2) |n| { + const output_col = 2 * t + n; + var dot: f32 = 0; + for (0..16) |kk| { + // uint2 A/B permute mma K as 4*t+(0,1,2,3), valid only together; gather both source lanes. + const a_lane = 4 * gq + kk / 4; + const b_lane = 4 * output_col + kk / 4; + const av = a[a_lane][h][q][(kk & 3) / 2][kk & 1]; + const bv = b[j][b_lane][4 * q + (kk & 3)]; + dot += av * bv; + } + acc[lane][j][2 * h + n] += dot; + }; + }; + } + // Every valid member uses its own lane group's D row, including h=1,q=1. + for (0..32) |lane| for (0..2) |h| { + const member = (lane >> 2) + 8 * h; + if (member >= members) continue; + for (0..4) |j| for (0..2) |n| { + const col = cb * 32 + 8 * j + 2 * (lane & 3) + n; + out[member * width + col] = core.bf16_round.bits(acc[lane][j][2 * h + n]); + }; + }; + } + } + + fn reference(m13: Matrix, m2: Matrix, x: []const u16) [hidden]u16 { + var gate: [expert_count * intermediate]u16 = undefined; + var up: [expert_count * intermediate]u16 = undefined; + var act: [expert_count * intermediate]u16 = undefined; + var down: [expert_count * hidden]u16 = undefined; + var out: [hidden]u16 = undefined; + for (0..expert_count) |e| { + scalarProjection(m13, e, 0, 2, x, gate[e * intermediate ..][0..intermediate]); + scalarProjection(m13, e, 1, 2, x, up[e * intermediate ..][0..intermediate]); + for (0..intermediate) |j| { + const raw = value(gate[e * intermediate + j]); + const gc = gate_cap * @as(f32, @floatCast(std.math.tanh(raw / gate_cap))); + const uc = up_cap * @as(f32, @floatCast(std.math.tanh(value(up[e * intermediate + j]) / up_cap))); + const sigmoid: f32 = 1 / (1 + @exp(-raw)); + act[e * intermediate + j] = core.bf16_round.bits(gc * sigmoid * uc); + } + scalarProjection(m2, e, 0, 1, act[e * intermediate ..][0..intermediate], down[e * hidden ..][0..hidden]); + } + // Routing is slot 0 -> expert 1 (+3/4), slot 1 -> expert 0 (-3/8). + for (&out, 0..) |*o, col| { + var total: f32 = 0; + total += -0.375 * value(down[col]); + total += 0.75 * value(down[hidden + col]); + o.* = core.bf16_round.bits(total); + } + return out; + } + + fn model(m13: Matrix, m2: Matrix, x: []const u16) [hidden]u16 { + var gate: [expert_count * intermediate]u16 = undefined; + var up: [expert_count * intermediate]u16 = undefined; + var act: [expert_count * intermediate]u16 = undefined; + var down: [expert_count * hidden]u16 = undefined; + var out: [hidden]u16 = undefined; + for (0..expert_count) |e| { + fragmentProjection(m13, e, 0, 2, x, gate[e * intermediate ..][0..intermediate], 1); + fragmentProjection(m13, e, 1, 2, x, up[e * intermediate ..][0..intermediate], 1); + for (0..intermediate) |j| { + const raw = value(gate[e * intermediate + j]); + const gc = gate_cap * @as(f32, @floatCast(std.math.tanh(raw / gate_cap))); + const uc = up_cap * @as(f32, @floatCast(std.math.tanh(value(up[e * intermediate + j]) / up_cap))); + const sigmoid: f32 = 1 / (1 + @exp(-raw)); + act[e * intermediate + j] = core.bf16_round.bits(gc * sigmoid * uc); + } + fragmentProjection(m2, e, 0, 1, act[e * intermediate ..][0..intermediate], down[e * hidden ..][0..hidden], 1); + } + for (&out, 0..) |*o, col| { + var total: f32 = 0; + total += -0.375 * value(down[col]); + total += 0.75 * value(down[hidden + col]); + o.* = core.bf16_round.bits(total); + } + return out; + } + + fn checkMembers(m13: Matrix, x: []const u16) !void { + const members = 10; + var tensor: [members * intermediate]u16 = undefined; + var scalar: [intermediate]u16 = undefined; + scalarProjection(m13, 0, 0, 2, x, &scalar); + fragmentProjection(m13, 0, 0, 2, x, &tensor, members); + var first_difference: ?usize = null; + for (tensor, 0..) |got, i| if (got != scalar[i % intermediate]) { + first_difference = i; + break; + }; + try std.testing.expectEqual(@as(?usize, null), first_difference); + } + + fn check() !void { + var codes13: [expert_count * 2 * intermediate * hidden / 2]u8 = undefined; + var scales13: [expert_count * 2 * intermediate * hidden / 16]u8 = undefined; + var codes2: [expert_count * hidden * intermediate / 2]u8 = undefined; + var scales2: [expert_count * hidden * intermediate / 16]u8 = undefined; + for (0..expert_count) |e| { + fill(&codes13, &scales13, e, 2 * intermediate, hidden, false); + fill(&codes2, &scales2, e, hidden, intermediate, true); + } + const m13: Matrix = .{ .codes = &codes13, .scales = &scales13, .n = 2 * intermediate, .k = hidden }; + const m2: Matrix = .{ .codes = &codes2, .scales = &scales2, .n = hidden, .k = intermediate }; + var x: [hidden]u16 = undefined; + for (&x, 0..) |*v, i| v.* = core.bf16_round.bits(@as(f32, @floatFromInt(@as(i32, @intCast(i % 13)) - 6)) / 128); + const got = model(m13, m2, &x); + const want = reference(m13, m2, &x); + var first_difference: ?usize = null; + for (got, want, 0..) |g, w, i| if (g != w) { + first_difference = i; + break; + }; + try std.testing.expectEqual(@as(?usize, null), first_difference); + try checkMembers(m13, &x); + } +}; + +test "one token: m16n8k16 fragment pipeline matches independent BF16 dequantization" { + try FragmentHostProbe.check(); +} diff --git a/zig/src/families/inkling2/names.zig b/zig/src/families/inkling2/names.zig index 3c75db572bf..79890b60510 100644 --- a/zig/src/families/inkling2/names.zig +++ b/zig/src/families/inkling2/names.zig @@ -1,6 +1,6 @@ -//! Inkling 2 Small's weight map: each tensor the config implies, with dtype and shape, checked against headers. +//! Inkling 2 weight maps: each tensor the config implies, with dtype and shape, checked against headers. const std = @import("std"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const config = @import("config.zig"); const plan = @import("plan.zig"); @@ -77,6 +77,19 @@ fn experts(c: *const Text, i: u32, prec: plan.Precision, sink: anytype) !void { } } +fn controllers(c: *const Text, i: u32, sink: anytype) !void { + const loop = c.loop orelse return; + if (i < loop.core_start or i >= loop.core_end) return; + const rank: u64 = loop.gate_rank; + const h: u64 = c.hidden; + const L = .{i}; + inline for (.{ "attn", "k", "mlp", "v" }) |kind| { + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".down_weight", L, .bf16, &.{ rank, 2 * h }); + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".forget_weight", L, .bf16, &.{ h, rank }); + try put(sink, "model.llm.layers.{d}.controllers." ++ kind ++ ".gain_weight", L, .bf16, &.{ h, rank }); + } +} + fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { const h: u64 = c.hidden; try put(sink, "model.llm.embed.weight", .{}, .bf16, &.{ c.vocab, h }); @@ -84,6 +97,11 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.norm.weight", .{}, .bf16, &.{h}); try put(sink, "model.llm.unembed.weight", .{}, .bf16, &.{ c.vocab, h }); try put(sink, "model.llm.attn_res.output_query", .{}, .f32, &.{h}); + if (c.loop) |loop| { + const rows = 2 * @as(u64, loop.core_end - loop.core_start); + try put(sink, "model.llm.middle_cycle_cross_pass_queries", .{}, .f32, &.{ rows, h }); + try put(sink, "model.llm.middle_cycle_cross_pass_kv_queries", .{}, .f32, &.{ rows, h }); + } for (0..c.layers) |k| { const i: u32 = @intCast(k); try put(sink, "model.llm.attn_res.mlp_queries.{d}", .{i}, .f32, &.{h}); @@ -93,6 +111,7 @@ fn backbone(c: *const Text, prec: []const plan.Precision, sink: anytype) !void { try put(sink, "model.llm.attn_res.attn_queries.{d}", .{i}, .f32, dims); } try attention(c, i, sink); + try controllers(c, i, sink); try put(sink, "model.llm.layers.{d}.attn_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); try put(sink, "model.llm.layers.{d}.mlp_norm.weight", .{i}, .bf16, &.{h}); try put(sink, "model.llm.layers.{d}.mlp_sconv.weight", .{i}, .bf16, &.{ h, 1, config.conv_taps }); @@ -131,8 +150,8 @@ fn draft(m: config.Mtp, text: *const Text, sink: anytype) !void { const q: u64 = @as(u64, m.q_heads) * m.head_dim; const kv: u64 = @as(u64, m.kv_heads) * m.head_dim; const rank: u64 = m.rank; - // fuse_weight's six rows do not follow from the config, so any row count passes - try put(sink, "fuse_weight", .{}, .bf16, &.{ any, m.taps_n }); + // One fusion row per draft layer plus the Markov head, one column per target visit tap. + try put(sink, "fuse_weight", .{}, .bf16, &.{ m.layers + 1, m.taps_n }); try put(sink, "mask_embed", .{}, .bf16, &.{h}); try put(sink, "norm.weight", .{}, .bf16, &.{h}); try put(sink, "markov_head.dflare_norm.weight", .{}, .bf16, &.{h}); diff --git a/zig/src/families/inkling2/names_test.zig b/zig/src/families/inkling2/names_test.zig index c5eb215d86b..b194b435d28 100644 --- a/zig/src/families/inkling2/names_test.zig +++ b/zig/src/families/inkling2/names_test.zig @@ -1,14 +1,17 @@ -//! The weight map and layer plan against the tiny-random checkpoint's safetensors headers (fixtures fold them). +//! Weight maps and layer plans against safetensors headers (fixtures fold them). + const std = @import("std"); const config = @import("config.zig"); const config_test = @import("config_test.zig"); -const st = @import("safetensors"); +const st = @import("core").safetensors; const names = @import("names.zig"); const plan = @import("plan.zig"); const t = std.testing; const model_fixture = @embedFile("fixtures/tiny_model_header.txt"); const mtp_fixture = @embedFile("fixtures/tiny_mtp_header.txt"); +const mini_model_fixture = @embedFile("fixtures/mini_model_header.txt"); +const mini_mtp_fixture = @embedFile("fixtures/mini_mtp_header.txt"); fn byName(_: void, a: []const u8, b: []const u8) bool { return std.mem.lessThan(u8, a, b); @@ -78,6 +81,11 @@ fn load(a: std.mem.Allocator) !config.Config { return config.parse(a, config_test.tiny, &why); } +fn loadMini(a: std.mem.Allocator) !config.Config { + var why: config.Why = .{}; + return config.parse(a, config_test.mini, &why); +} + test "the folded fixtures unfold to the 404 and 84 tensors of tiny's two files, digests equal" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -85,6 +93,13 @@ test "the folded fixtures unfold to the 404 and 84 tensors of tiny's two files, try t.expectEqual(@as(usize, 84), (try unfold(arena.allocator(), mtp_fixture, "inkling2-tiny-mtp")).count()); } +test "Mini's folded fixtures unfold to the 1244 and 54 tensors of its two files, digests equal" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + try t.expectEqual(@as(usize, 1244), (try unfold(arena.allocator(), mini_model_fixture, "inkling2-mini-model")).count()); + try t.expectEqual(@as(usize, 54), (try unfold(arena.allocator(), mini_mtp_fixture, "inkling2-mini-mtp")).count()); +} + test "the map names exactly tiny's backbone and vision tensors, with their dtypes and shapes" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -108,6 +123,19 @@ test "the map names exactly tiny's draft head tensors" { try t.expect(r.clean()); } +test "Mini's config parses and the map names exactly its model and draft tensors" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try loadMini(a); + const model = try names.check(a, &c, try unfold(a, mini_model_fixture, "inkling2-mini-model"), .model); + try t.expectEqual(@as(usize, 1244), model.expected); + try t.expect(model.clean()); + const mtp = try names.check(a, &c, try unfold(a, mini_mtp_fixture, "inkling2-mini-mtp"), .mtp); + try t.expectEqual(@as(usize, 54), mtp.expected); + try t.expect(mtp.clean()); +} + test "a missing tensor, a wrong shape, a wrong dtype and an unknown tensor are each reported by name" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -177,6 +205,15 @@ test "expert precision follows each layer's tensors: NVFP4 on layers 0 to 5, MXF try t.expectError(error.ExpertFormat, names.precisions(bad, 12, &prec)); } +test "Mini's expert precision is NVFP4 on layers 0 to 19 and MXFP8 on 20 to 23" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const entries = try unfold(arena.allocator(), mini_model_fixture, "inkling2-mini-model"); + var prec: [24]plan.Precision = undefined; + try names.precisions(entries, 24, &prec); + for (prec, 0..) |p, i| try t.expectEqual(if (i < 20) plan.Precision.nvfp4 else plan.Precision.mxfp8, p); +} + test "the plan: global layers 5 and 11, blocks of six, three attention queries before each global layer" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -199,6 +236,38 @@ test "the plan: global layers 5 and 11, blocks of six, three attention queries b try t.expectEqual(@as(u32, 3), p.at(11).attn_sources); try t.expectEqual(@as(u32, 3), p.final_sources); try t.expectError(error.PrecisionCount, plan.build(&c.text, prec[0..11])); + try t.expectEqual(@as(u32, 12), p.n_visits); + for (0..p.n_visits) |i| { + const v = p.visit(@intCast(i)); + try t.expectEqual(@as(u32, @intCast(i)), v.layer); + try t.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try t.expect(!v.hasMessages()); + } +} + +test "Mini's visit plan repeats only the core, gives all 48 visits private state and banks the previous pass" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c = try loadMini(a); + var prec: [24]plan.Precision = undefined; + try names.precisions(try unfold(a, mini_model_fixture, "inkling2-mini-model"), 24, &prec); + const p = try plan.build(&c.text, &prec); + try t.expectEqual(@as(u32, 48), p.n_visits); + try t.expectEqual(@as(u32, 8), p.visitCount(.global)); + try t.expectEqual(@as(u32, 40), p.visitCount(.local)); + for (0..p.n_visits) |i| { + const v = p.visit(@intCast(i)); + const layer: u32 = if (i < 6) @intCast(i) else if (i < 42) 6 + @as(u32, @intCast((i - 6) % 12)) else @intCast(i - 24); + const pass: u32 = if (i >= 6 and i < 42) 1 + @as(u32, @intCast((i - 6) / 12)) else 0; + try t.expectEqual(layer, v.layer); + try t.expectEqual(pass, v.pass); + try t.expectEqual(@as(u32, @intCast(i)), v.cache_slot); + try t.expectEqual(pass >= 2, v.hasMessages()); + const previous: ?u32 = if (pass == 2) 6 else if (pass == 3) 18 else null; + try t.expectEqual(previous, v.previous_core_start); + } + try t.expectEqual(@as(u32, 5), p.final_sources); } /// A file's header through the core reader; the files may hold the header alone, so no data length is checked. diff --git a/zig/src/families/inkling2/plan.zig b/zig/src/families/inkling2/plan.zig index c2327d26bef..86effc0c4a3 100644 --- a/zig/src/families/inkling2/plan.zig +++ b/zig/src/families/inkling2/plan.zig @@ -19,27 +19,64 @@ pub const Layer = struct { precision: Precision, }; +pub const Visit = struct { + layer: u32, // physical weight layer; core layers repeat with the same weights + pass: u32, // zero outside the core, otherwise one-based loop pass + cache_slot: u32, // this visit's private KV and four short-convolution states + previous_core_start: ?u32, // previous pass's first visit; its two bank states feed this visit's messages + + pub fn hasMessages(v: Visit) bool { + return v.previous_core_start != null; + } +}; + pub const Plan = struct { layers: [config.max_layers]Layer, n: u32, + visits: [config.max_visits]Visit, + n_visits: u32, final_sources: u32, // the output query's states: every finished block and the last layer's output pub fn at(p: *const Plan, i: u32) *const Layer { return &p.layers[i]; } + pub fn visit(p: *const Plan, i: u32) *const Visit { + return &p.visits[i]; + } + pub fn count(p: *const Plan, kind: Kind) u32 { var k: u32 = 0; for (p.layers[0..p.n]) |l| k += @intFromBool(l.kind == kind); return k; } + + pub fn visitCount(p: *const Plan, kind: Kind) u32 { + var k: u32 = 0; + for (p.visits[0..p.n_visits]) |v| k += @intFromBool(p.layers[v.layer].kind == kind); + return k; + } }; /// The plan for a parsed config and each layer's expert precision (`prec` holds one entry per layer). +fn appendVisit(p: *Plan, c: *const config.Text, layer: u32, pass: u32) void { + const previous: ?u32 = if (c.loop) |core| + (if (pass >= 2) core.core_start + (pass - 2) * (core.core_end - core.core_start) else null) + else + null; + p.visits[p.n_visits] = .{ + .layer = layer, + .pass = pass, + .cache_slot = p.n_visits, + .previous_core_start = previous, + }; + p.n_visits += 1; +} pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCount}!Plan { if (prec.len != c.layers) return error.PrecisionCount; var p: Plan = undefined; p.n = c.layers; + p.n_visits = 0; for (0..c.layers) |k| { const i: u32 = @intCast(k); const boundary = i % c.block == 0; @@ -58,5 +95,12 @@ pub fn build(c: *const config.Text, prec: []const Precision) error{PrecisionCoun }; } p.final_sources = (c.layers + c.block - 1) / c.block + 1; + if (c.loop) |loop| { + for (0..loop.core_start) |i| appendVisit(&p, c, @intCast(i), 0); + for (1..loop.passes + 1) |pass| for (loop.core_start..loop.core_end) |i| appendVisit(&p, c, @intCast(i), @intCast(pass)); + for (loop.core_end..c.layers) |i| appendVisit(&p, c, @intCast(i), 0); + } else { + for (0..c.layers) |i| appendVisit(&p, c, @intCast(i), 0); + } return p; } diff --git a/zig/src/families/inkling2/vision.zig b/zig/src/families/inkling2/vision.zig new file mode 100644 index 00000000000..eced25b1697 --- /dev/null +++ b/zig/src/families/inkling2/vision.zig @@ -0,0 +1,400 @@ +//! Inkling 2's vision tower on CUDA in bf16: patch embedding, 23 ViT layers with axial rotary, the 2 x 2 projector. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const image = @import("image.zig"); + +const vit = cuda.vit; + +pub const width = 1024; +pub const heads = 16; +pub const head_dim = 64; +pub const depth = 23; +pub const mlp_inter = 4096; +pub const proj_inter = 4096; +pub const hidden = 4608; // the decoder's width +const merged = image.merge * image.merge * width; // a token's four patch rows side by side +const eps: f32 = 1e-5; +const pre = "model.visual.backbone."; +/// The checkpoint names the tower reads (source shards and the pack's vision sidecar alike). +pub const prefixes = [_][]const u8{"model.visual."}; +/// Image tokens a tower's scratch covers when the caller names no limit: 1280 x 1280 pixels. +pub const default_tokens: u32 = 1024; +const attn_smem: u32 = 2 * 2 * 64 * (head_dim / 8 + 1) * 16; + +/// The family's tower kernels (inkling2/vision.cu). +pub const Kernels = struct { + mod: cuda.Module, + attention: cuda.Function, + embed: cuda.Function, + rope: cuda.Function, + scale_add: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_vision); + errdefer mod.unload(); + const k: Kernels = .{ + .mod = mod, + .attention = try mod.function("tf_ink2v_attention"), + .embed = try mod.function("tf_ink2v_embed"), + .rope = try mod.function("tf_ink2v_rope"), + .scale_add = try mod.function("tf_ink2v_scale_add"), + }; + try k.attention.allowDynamicShared(attn_smem); + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + k.* = undefined; + } +}; + +/// The tower's tensors: a pack's vision.safetensors sidecar (as the release stores them), else the model's shards. +fn openTower(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !core.Checkpoint { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, "{s}/" ++ sidecar, .{dir}); + std.Io.Dir.cwd().access(io, path, .{}) catch return core.Checkpoint.openModelPrefixes(gpa, io, dir, &prefixes); + var ck: core.Checkpoint = .{ .gpa = gpa, .io = io }; + errdefer ck.close(); + try ck.add(dir, sidecar); + return ck; +} + +/// The file a pack carries the tower in, copied unchanged from the release's shards. +pub const sidecar = "vision.safetensors"; + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, shared: u32, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads }, .shared = shared }, s, a); +} + +const Layer = struct { ln1_w: u64, ln1_b: u64, qkv_w: u64, qkv_b: u64, out_w: u64, out_b: u64, ls1: u64, ln2_w: u64, ln2_b: u64, fc1_w: u64, fc1_b: u64, fc2_w: u64, fc2_b: u64, ls2: u64 }; + +/// What one image row of scratch costs: patch inputs, x/xn/att/y, qkv, mid, the f32 bias sums, tables. +const row_bytes: u64 = image.patch_width * 2 + 4 * width * 2 + 3 * width * 2 + mlp_inter * 2 + mlp_inter * 4 + 4 * 4 + 4 * 4 + 2 * image.pairs * 4; + +/// Scratch for pictures of up to `tokens` decoder tokens, plus cuBLASLt's workspace. +pub fn scratchBytes(tokens: u32) u64 { + const rows: u64 = @as(u64, tokens) * image.merge * image.merge + 1; + return rows * row_bytes + @as(u64, tokens) * proj_inter * 2 + (32 << 20); +} + +/// The tower's weights and scratch on one GPU. +pub const Tower = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + k: Kernels, + vk: vit.Kernels, + g: vit.Gemms, + bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, + max_tokens: u32, + patch_w: u64 = 0, // [width][1200]: a native patch's row, column, channel + table: u64 = 0, // [32 * 32][width] position rows + cls: u64 = 0, + cls_pos: u64 = 0, + pre_w: u64 = 0, + pre_b: u64 = 0, + proj_in: u64 = 0, // [4096][4096], no bias + proj_out: u64 = 0, // [hidden][4096], no bias + layers: [depth]Layer = undefined, + px: u64 = 0, // bf16 [P][1200] + x: u64 = 0, // bf16 [R][width]: the residual stream (row 0 the class token) + xn: u64 = 0, + att: u64 = 0, + y: u64 = 0, + qkv: u64 = 0, // bf16 [R][3 width] + mid: u64 = 0, // bf16 [R][mlp_inter] + acc: u64 = 0, // f32 [R][mlp_inter]: a Linear's sums when cuBLASLt cannot fuse its bias + taps: u64 = 0, // u32 [P][4] + wts: u64 = 0, // f32 [P][4] + cs: u64 = 0, // f32 [R][32] + sn: u64 = 0, + p1: u64 = 0, // bf16 [T][proj_inter] + bytes: u64 = 0, + /// Layers encode runs (a parity tool stops early to read a layer's output at `x`). + layers_run: usize = depth, + + fn alloc(t: *Tower, n: usize) !u64 { + var b = try cuda.DeviceBuffer.alloc(t.d, @max(n, 256)); + errdefer b.free(); + try t.bufs.append(t.gpa, b); + t.bytes += n; + return b.ptr; + } + + fn up(t: *Tower, bytes: []const u8) !u64 { + const p = try t.alloc(bytes.len); + try t.d.check(t.d.api.cuMemcpyHtoD_v2(p, bytes.ptr, bytes.len), "cuMemcpyHtoD"); + return p; + } + + fn get(t: *Tower, ck: *core.Checkpoint, name: []const u8, dims: []const usize) !u64 { + return t.up((try ck.expect(name, .bf16, dims)).bytes); + } + + /// The tower from the checkpoint at `dir` (its model.visual.* tensors, bf16 as released), scratch for `max_tokens`. + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, max_tokens: u32) !*Tower { + if (max_tokens == 0) return error.ImageTokens; + const t = try gpa.create(Tower); + errdefer gpa.destroy(t); + var k = try Kernels.load(d); + errdefer k.unload(); + var vk = try vit.Kernels.load(d); + errdefer vk.unload(); + t.* = .{ .gpa = gpa, .d = d, .k = k, .vk = vk, .g = try vit.Gemms.init(gpa, d), .max_tokens = max_tokens }; + errdefer { + for (t.bufs.items) |*b| b.free(); + t.bufs.deinit(gpa); + t.g.deinit(); + } + var ck = try openTower(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + t.patch_w = try t.get(&ck, pre ++ "embeddings.patch_embedding.weight", &.{ width, image.patch_width }); + t.table = try t.get(&ck, pre ++ "embeddings.position_embedding", &.{ image.grid * image.grid, width }); + t.cls = try t.get(&ck, pre ++ "embeddings.class_embedding", &.{width}); + t.cls_pos = try t.get(&ck, pre ++ "embeddings.cls_position_embedding", &.{width}); + t.pre_w = try t.get(&ck, pre ++ "ln_pre.weight", &.{width}); + t.pre_b = try t.get(&ck, pre ++ "ln_pre.bias", &.{width}); + t.proj_in = try t.get(&ck, "model.visual.proj_in.weight", &.{ proj_inter, merged }); + t.proj_out = try t.get(&ck, "model.visual.proj_out.weight", &.{ hidden, proj_inter }); + const w = try gpa.alloc(u8, 3 * width * width * 2); + defer gpa.free(w); + for (&t.layers, 0..) |*l, i| { + var nb: [128]u8 = undefined; + const at = struct { + fn f(buf: *[128]u8, li: usize, comptime rel: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, pre ++ "layers.{d}." ++ rel, .{li}); + } + }.f; + l.ln1_w = try t.get(&ck, try at(&nb, i, "ln_1.weight"), &.{width}); + l.ln1_b = try t.get(&ck, try at(&nb, i, "ln_1.bias"), &.{width}); + l.ln2_w = try t.get(&ck, try at(&nb, i, "ln_2.weight"), &.{width}); + l.ln2_b = try t.get(&ck, try at(&nb, i, "ln_2.bias"), &.{width}); + l.ls1 = try t.get(&ck, try at(&nb, i, "ls_1.gamma"), &.{width}); + l.ls2 = try t.get(&ck, try at(&nb, i, "ls_2.gamma"), &.{width}); + // q | k | v stacked by rows, their biases likewise: one Linear, heads as the attention reads them + var b: [3 * width * 2]u8 = undefined; + inline for (.{ "q", "k", "v" }, 0..) |which, j| { + const wt = try ck.expect(try at(&nb, i, "self_attn." ++ which ++ "_proj.weight"), .bf16, &.{ width, width }); + @memcpy(w[j * width * width * 2 ..][0 .. width * width * 2], wt.bytes); + const bt = try ck.expect(try at(&nb, i, "self_attn." ++ which ++ "_proj.bias"), .bf16, &.{width}); + @memcpy(b[j * width * 2 ..][0 .. width * 2], bt.bytes); + } + l.qkv_w = try t.up(w); + l.qkv_b = try t.up(&b); + l.out_w = try t.get(&ck, try at(&nb, i, "self_attn.out_proj.weight"), &.{ width, width }); + l.out_b = try t.get(&ck, try at(&nb, i, "self_attn.out_proj.bias"), &.{width}); + l.fc1_w = try t.get(&ck, try at(&nb, i, "mlp.c_fc.weight"), &.{ mlp_inter, width }); + l.fc1_b = try t.get(&ck, try at(&nb, i, "mlp.c_fc.bias"), &.{mlp_inter}); + l.fc2_w = try t.get(&ck, try at(&nb, i, "mlp.c_proj.weight"), &.{ width, mlp_inter }); + l.fc2_b = try t.get(&ck, try at(&nb, i, "mlp.c_proj.bias"), &.{width}); + } + const P: usize = @as(usize, max_tokens) * image.merge * image.merge; + const R = P + 1; + t.px = try t.alloc(P * image.patch_width * 2); + inline for (.{ "x", "xn", "att", "y" }) |f| @field(t, f) = try t.alloc(R * width * 2); + t.qkv = try t.alloc(R * 3 * width * 2); + t.mid = try t.alloc(R * mlp_inter * 2); + t.acc = try t.alloc(R * mlp_inter * 4); + t.taps = try t.alloc(P * 4 * 4); + t.wts = try t.alloc(P * 4 * 4); + t.cs = try t.alloc(R * image.pairs * 4); + t.sn = try t.alloc(R * image.pairs * 4); + t.p1 = try t.alloc(@as(usize, max_tokens) * proj_inter * 2); + return t; + } + + /// The device bytes load takes for `dir`: the tower's tensors as stored, scratch and workspace for `max_tokens`. + pub fn bytesFor(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, max_tokens: u32) !u64 { + var ck = try openTower(gpa, io, dir); + defer core.checkpoint.cache.close(&ck); + var total: u64 = scratchBytes(max_tokens); + for (ck.files.items) |*f| for (f.names.keys()) |name| { + total += f.get(name).?.bytes.len; + }; + return total; + } + + pub fn deinit(t: *Tower) void { + for (t.bufs.items) |*b| b.free(); + t.bufs.deinit(t.gpa); + t.g.deinit(); + t.vk.unload(); + t.k.unload(); + t.gpa.destroy(t); + } + + fn upload(t: *Tower, dst: u64, bytes: []const u8) !void { + try t.d.check(t.d.api.cuMemcpyHtoD_v2(dst, bytes.ptr, bytes.len), "cuMemcpyHtoD"); + } + + /// The host tables of one picture (patch rows, position taps, rotary; rotary off only for a planted control). + fn stage(t: *Tower, s: cuda.Stream, p: image.Prepared, rope: bool) !void { + const P = image.patchCount(p); + const rows = try t.gpa.alloc(u16, P * image.patch_width); + defer t.gpa.free(rows); + const taps = try t.gpa.alloc(u32, P * 4); + defer t.gpa.free(taps); + const wts = try t.gpa.alloc(f32, P * 4); + defer t.gpa.free(wts); + const cs = try t.gpa.alloc(f32, (P + 1) * image.pairs); + defer t.gpa.free(cs); + const sn = try t.gpa.alloc(f32, (P + 1) * image.pairs); + defer t.gpa.free(sn); + image.patchRows(p, rows); + image.positionTaps(p, taps, wts); + image.rotary(p, cs, sn, rope); + try s.synchronize(); // the previous picture's kernels may still read the tables + try t.upload(t.px, std.mem.sliceAsBytes(rows)); + try t.upload(t.taps, std.mem.sliceAsBytes(taps)); + try t.upload(t.wts, std.mem.sliceAsBytes(wts)); + try t.upload(t.cs, std.mem.sliceAsBytes(cs)); + try t.upload(t.sn, std.mem.sliceAsBytes(sn)); + } + + /// One picture to its tokens' rows at `out` (bf16 [tokens][hidden]): what replaces its placeholders' embeddings. + pub fn encode(t: *Tower, s: cuda.Stream, p: image.Prepared, out: u64) !void { + return t.encodeWith(s, p, out, true); + } + + pub fn encodeWith(t: *Tower, s: cuda.Stream, p: image.Prepared, out: u64, rope: bool) !void { + const T: usize = p.tokens(); + if (T == 0 or p.pixels.len != T * image.side * image.side * 3) return error.ImageGrid; + if (T > t.max_tokens) return error.ImageTooLarge; + try t.stage(s, p, rope); + const P = image.patchCount(p); + const R = P + 1; + try t.g.run(s, t.px, t.patch_w, t.y, P, width, image.patch_width, .bf16); + var a: cuda.Args = .{}; + for ([_]u64{ t.y, t.table, t.taps, t.wts, t.cls, t.cls_pos, t.xn }) |v| a.add(v); + try go(t.k.embed, s, .{ .x = @intCast(R) }, 256, 0, &a); + try t.vk.layerNorm(s, t.xn, t.pre_w, t.pre_b, t.x, R, width, eps); + for (t.layers[0..@min(t.layers_run, depth)]) |l| try t.layer(s, l, R); + if (t.layers_run < depth) return; + // the projector: each token's four patch rows (merge order, after the class row) as one 4096-wide row + try t.g.run(s, t.x + width * 2, t.proj_in, t.p1, T, proj_inter, merged, .bf16); + try t.vk.pointwise(s, t.p1, null, t.p1, T * proj_inter, .gelu); + try t.g.run(s, t.p1, t.proj_out, out, T, hidden, proj_inter, .bf16); + } + + fn layer(t: *Tower, s: cuda.Stream, l: Layer, R: usize) !void { + try t.vk.layerNorm(s, t.x, l.ln1_w, l.ln1_b, t.xn, R, width, eps); + try vit.linear(&t.g, &t.vk, s, t.acc, t.xn, l.qkv_w, l.qkv_b, t.qkv, R, 3 * width, width); + var a: cuda.Args = .{}; + for ([_]u64{ t.qkv, t.cs, t.sn }) |v| a.add(v); + try go(t.k.rope, s, .{ .x = @intCast(R) }, 256, 0, &a); + var b: cuda.Args = .{}; + b.add(t.qkv); + b.add(t.att); + b.add(@as(c_int, @intCast(R))); + b.add(@as(c_int, heads)); + b.add(@as(f32, 1.0 / @sqrt(@as(f32, head_dim)))); + try go(t.k.attention, s, .{ .x = @intCast((R + 127) / 128), .y = heads }, 256, attn_smem, &b); + try vit.linear(&t.g, &t.vk, s, t.acc, t.att, l.out_w, l.out_b, t.y, R, width, width); + try t.scaleAdd(s, l.ls1, R); + try t.vk.layerNorm(s, t.x, l.ln2_w, l.ln2_b, t.xn, R, width, eps); + try vit.linearAct(&t.g, &t.vk, s, t.acc, t.xn, l.fc1_w, l.fc1_b, t.mid, R, mlp_inter, width, null, t.mid, .gelu); + try vit.linear(&t.g, &t.vk, s, t.acc, t.mid, l.fc2_w, l.fc2_b, t.y, R, width, mlp_inter); + try t.scaleAdd(s, l.ls2, R); + } + + /// x = bf16(x + bf16(gamma y)), the layer scale of torch's `residual + lambda * h`. + fn scaleAdd(t: *Tower, s: cuda.Stream, gamma: u64, R: usize) !void { + const n = R * width; + var a: cuda.Args = .{}; + for ([_]u64{ t.x, t.y, gamma }) |v| a.add(v); + a.add(@as(i64, @intCast(n))); + try go(t.k.scale_add, s, .{ .x = @intCast((n + 255) / 256) }, 256, 0, &a); + } +}; + +/// Prompt rows [at, at + n) take image rows [row, row + n) (rows of the encoded pictures, in prompt order). +pub const Span = struct { at: u32, n: u32, row: u32 }; + +/// The placeholder runs of a prompt's ids: each maximal run of image_token is one picture's rows, in order. +pub fn spans(a: std.mem.Allocator, ids: []const u32) ![]Span { + var out: std.ArrayList(Span) = .empty; + errdefer out.deinit(a); + var row: u32 = 0; + var i: usize = 0; + while (i < ids.len) : (i += 1) { + if (ids[i] != image.image_token) continue; + const at = i; + while (i < ids.len and ids[i] == image.image_token) i += 1; + try out.append(a, .{ .at = @intCast(at), .n = @intCast(i - at), .row = row }); + row += @intCast(i - at); + } + return out.toOwnedSlice(a); +} + +/// The prompt's placeholders must equal the encoded pictures' rows, as transformers' get_placeholder_mask requires. +pub fn check(list: []const Span, pictures: []const image.Prepared) !void { + var want: usize = 0; + for (pictures) |p| want += p.tokens(); + var have: usize = 0; + for (list) |sp| have += sp.n; + if (have != want) return error.ImagePlaceholders; +} + +/// One copy into a pass: pass row `dst` on takes image rows from `src`, `n` of them. +pub const Copy = struct { dst: u32, src: u32, n: u32 }; + +/// The part of a placeholder run inside a pass over prompt positions [lo, hi), if any. +pub fn cut(sp: Span, lo: usize, hi: usize) ?Copy { + const a = @max(lo, sp.at); + const b = @min(hi, sp.at + sp.n); + if (a >= b) return null; + return .{ .dst = @intCast(a - lo), .src = @intCast(sp.row + (a - sp.at)), .n = @intCast(b - a) }; +} + +/// After the normed embedding, a pass's rows at positions [lo, hi) (bf16 at `x`) take their image rows (at `rows`). +pub fn splice(d: *const cuda.Driver, s: cuda.Stream, rows: u64, list: []const Span, lo: usize, hi: usize, x: u64) !void { + for (list) |sp| { + const c = cut(sp, lo, hi) orelse continue; + const row: u64 = hidden * 2; + try d.check(d.api.cuMemcpyDtoDAsync_v2(x + c.dst * row, rows + c.src * row, c.n * row, s.handle), "cuMemcpyDtoDAsync"); + } +} + +test "placeholder runs map to picture rows in prompt order" { + const a = std.testing.allocator; + const t = image.image_token; + const got = try spans(a, &.{ 1, t, t, t, 2, 3, t, t, 4 }); + defer a.free(got); + try std.testing.expectEqual(@as(usize, 2), got.len); + try std.testing.expectEqual(Span{ .at = 1, .n = 3, .row = 0 }, got[0]); + try std.testing.expectEqual(Span{ .at = 6, .n = 2, .row = 3 }, got[1]); + var px: [2 * image.side * image.side * 3]f32 = undefined; + const two = [_]image.Prepared{ .{ .pixels = &px, .rows = 1, .cols = 3 }, .{ .pixels = &px, .rows = 1, .cols = 2 } }; + try check(got, &two); + try std.testing.expectError(error.ImagePlaceholders, check(got, two[0..1])); +} + +test "chunked passes give every placeholder the row masked_scatter gives it" { + const a = std.testing.allocator; + const t = image.image_token; + const ids = [_]u32{ 7, t, t, t, t, t, 9, 9, t, 4, t, t, t, t, t, t, t, 3, 2 }; + const list = try spans(a, &ids); + defer a.free(list); + for ([_]usize{ 1, 2, 3, 5, 8, ids.len }) |chunk| { + var got: [ids.len]i32 = @splat(-1); + var lo: usize = 0; + while (lo < ids.len) : (lo += chunk) { + const hi = @min(ids.len, lo + chunk); + for (list) |sp| if (cut(sp, lo, hi)) |c| for (0..c.n) |i| { + got[lo + c.dst + i] = @intCast(c.src + i); + }; + } + var next: i32 = 0; // masked_scatter: the k-th placeholder in the prompt takes feature row k + for (ids, got) |id, g| { + try std.testing.expectEqual(if (id == t) next else -1, g); + if (id == t) next += 1; + } + } +} + +test "scratch for the default limit stays under 256 MiB" { + try std.testing.expect(scratchBytes(default_tokens) < 256 << 20); + try std.testing.expectEqual(@as(u32, 36864), attn_smem); +} diff --git a/zig/src/inkling2_metal_host_test.zig b/zig/src/inkling2_metal_host_test.zig new file mode 100644 index 00000000000..eb76bab6406 --- /dev/null +++ b/zig/src/inkling2_metal_host_test.zig @@ -0,0 +1,6 @@ +//! Inkling 2 Mini Metal host tests rooted with the production engine sources. + +test { + _ = @import("families/inkling2/metal/host_test.zig"); + _ = @import("inkling2_native.zig"); +} diff --git a/zig/src/inkling2_native.zig b/zig/src/inkling2_native.zig new file mode 100644 index 00000000000..9101c4a644f --- /dev/null +++ b/zig/src/inkling2_native.zig @@ -0,0 +1,3 @@ +//! Module root for the Inkling 2 Mini native backend and its zig/src family dependencies. +pub const open = @import("native/inkling2.zig").open; +pub const refusal = @import("native/inkling2.zig").refusal; diff --git a/zig/src/native/cuda_families.zig b/zig/src/native/cuda_families.zig index db2d88035e8..fd40a97d523 100644 --- a/zig/src/native/cuda_families.zig +++ b/zig/src/native/cuda_families.zig @@ -12,9 +12,10 @@ const gemma4 = @import("gemma4_cuda"); const spark25 = @import("spark25"); const dory = @import("dory"); const qwen3 = @import("qwen3_cuda"); +const inkling2 = @import("inkling2"); /// CUDA families provide metadata, open their lane backend and explain their refusals. -pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("lfm2_moe_cuda").native }; +pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("lfm2_moe_cuda").native, inkling2.native }; pub const families: []const api.Family = blk: { var out: [registry.len + 5]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats, .decision_formats = if (@hasDecl(F, "decision_formats")) F.decision_formats else &.{} }; @@ -30,8 +31,8 @@ pub const families: []const api.Family = blk: { test "every registered family and d1's decision engine are listed for capabilities" { try std.testing.expectEqual(@as(usize, registry.len + 5), families.len); try std.testing.expectEqualStrings("nemotron_h", families[0].model_type); - try std.testing.expectEqualStrings("lfm2_moe", families[registry.len - 1].model_type); - try std.testing.expectEqualStrings("lfm2_vl", families[registry.len].model_type); + try std.testing.expectEqualStrings("lfm2_moe", families[registry.len - 2].model_type); + try std.testing.expectEqualStrings("inkling2_loop", families[registry.len - 1].model_type); try std.testing.expectEqualStrings("qwen4", families[registry.len + 2].model_type); try std.testing.expectEqualStrings("qwen4_text", families[registry.len + 3].model_type); try std.testing.expectEqualStrings("qwen3", families[registry.len + 4].model_type); diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig new file mode 100644 index 00000000000..0cfa8c54758 --- /dev/null +++ b/zig/src/native/inkling2.zig @@ -0,0 +1,294 @@ +//! Text-only Inkling 2 Mini on Metal, with exact prompt reuse and budgeted stream state. +const std = @import("std"); +const mtl = @import("metal"); +const api = @import("engine_api"); +const lanes = @import("lanes"); +const Model = @import("../families/inkling2/metal/model.zig").Model; +const st = @import("../families/inkling2/metal/state.zig"); +const backend = @import("../families/inkling2/metal/backend.zig"); +const dspark = @import("../families/inkling2/metal/dspark.zig"); +const dl = @import("../families/inkling2/dspark_lanes.zig"); + +const Host = struct { + gpa: std.mem.Allocator, + io: std.Io, + model: *Model, + metal: *backend.Metal, + drafter: ?*dspark.Drafter = null, + drafted: ?lanes.drafted.Drafted = null, + warm: mtl.keepalive.Target, + clock: lanes.backend.WallClock, + config: lanes.Config = undefined, + core: lanes.Engine, + host: api.LaneHost, + cache: ?api.prompt_cache.Store = null, + cache_cap: u64 = 0, + + fn close(ctx: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + h.host.stop(); + if (h.cache) |*store| store.deinit(); + h.core.deinit(); + h.config.deinit(h.gpa); + if (h.drafted) |*d| d.deinit(); + if (h.drafter) |d| d.deinit(); + h.metal.deinit(); + h.model.deinit(); + h.gpa.destroy(h); + } +}; + +pub fn refusal(o: api.Open) ?[]const u8 { + if (o.vision != null or o.cfg_enabled or o.cfg_batched) return "inkling2_loop: this Metal engine serves text only; images and audio are unsupported"; + if (o.loops != null) return "inkling2_loop: the model has exactly three core passes; --loops cannot override them"; + if (o.mtp_drafts != null or o.mtp_confidence != null) return "inkling2_loop: use --drafter for the checkpoint's DSpark head; external draft controls remain unsupported"; + if (o.precision != null) return "inkling2_loop: the checkpoint's NVFP4, MXFP8 and BF16 arithmetic is fixed; serve without --precision"; + if (o.speed_up != null) return "inkling2_loop: this Metal engine serves one Mac; --speed-up is unsupported"; + if (o.learn != null or o.learn_conversations) return "inkling2_loop: learned disk states are not implemented; serve without --learn and --learn-conversations"; + if (o.prompt_cache_gib) |g| if (!std.math.isFinite(g) or g < 0 or g > 1024 * 1024) return "inkling2_loop: --prompt-cache-gib must be a finite, nonnegative budget"; + return null; +} + +fn drafterDirectory(o: api.Open) ?[]const u8 { + return if (o.drafts) o.drafter else null; +} + +fn contextProblem(window: i64, fits: usize) ?[]const u8 { + if (window < 1) return "inkling2_loop: --context must be at least one token, and the selected context must fit the Metal state budget"; + if (window > fits) return "inkling2_loop: --context exceeds the largest window this Mac can afford beside the checkpoint and DSpark state"; + return null; +} + +pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + if (refusal(o)) |why| { + problem.* = why; + return null; + } + if (try o.slideRefusal(a, "Macs")) |why| { + problem.* = why; + return null; + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const model = Model.load(gpa, io, o.dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "the native Inkling 2 Mini engine cannot load this checkpoint ({s})", .{@errorName(err)}); + return null; + }; + const drafter_dir = drafterDirectory(o); + errdefer model.deinit(); + const drafter = if (drafter_dir) |dir| dspark.Drafter.init(gpa, io, model.device, model, dir) catch |err| { + problem.* = try std.fmt.allocPrint(a, "--drafter: Inkling 2 Mini DSpark cannot load {s} ({s})", .{ dir, @errorName(err) }); + model.deinit(); + return null; + } else null; + errdefer if (drafter) |d| d.deinit(); + var ram: u64 = 0; + if (@import("builtin").os.tag.isDarwin()) { + var len: usize = @sizeOf(u64); + if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; + } + const scratch: u64 = st.scratchBytes(st.batch_rows) + st.scratchBytes(st.prompt_rows); + const resident = model.checkpoint.residentBytes() + scratch + if (drafter) |d| d.fixedBytes() + dl.scoreBytes(0) else 0; + const budget = cacheBudget(ram, model.device.maxWorkingSet(), @import("sys").getenv("INKLING2_LOAD_LIMIT_GB"), resident) catch { + if (drafter) |d| d.deinit(); + model.deinit(); + problem.* = "INKLING2_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 75% of RAM"; + return null; + }; + const streams: u64 = @max(o.lanes, 1); + // The shared host's fit: a drafted stream's fixed bytes, its bytes a token, and the shared scores' a token. + const draft: dl.Fit = if (drafter != null) dl.fit() else .{ .fixed = 0, .lane = 0, .shared = 0 }; + const fits = longest(budget, model.config.text.max_context, streams, draft.fixed, draft.lane, draft.shared); + const window: i64 = o.context orelse @intCast(fits); + if (contextProblem(window, fits)) |why| { + if (drafter) |d| d.deinit(); + model.deinit(); + problem.* = why; + return null; + } + std.log.info("inkling2_loop: {d:.1} GiB for stream and prompt state, context up to {d} tokens", .{ @as(f64, @floatFromInt(budget)) / (1 << 30), window }); + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + h.gpa = gpa; + h.io = io; + h.model = model; + h.drafter = drafter; + const reserved = if (drafter != null) streams * dl.laneBytes(@intCast(window)) + dl.scoreBytes(@intCast(window)) - dl.scoreBytes(0) else 0; + if (reserved > budget) return error.DSparkReservationExceeded; + h.metal = try backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = @max(o.lanes, 1), .budget = budget - reserved }); + errdefer h.metal.deinit(); + try h.metal.warm(); + h.drafted = null; + h.warm = .{ .queue = model.queue }; + if (drafter) |d| { + try d.lanes.setContext(@intCast(window)); + try d.measure(); + h.drafted = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.lanes.drafter()); + h.drafted.?.first_rows = true; + } + errdefer if (h.drafted) |*d| d.deinit(); + const facts = if (h.drafted) |*d| d.facts(h.metal.facts()) else h.metal.facts(); + h.config = try lanes.Config.init(gpa, facts, st.window_rows, st.window_rows - 1); + errdefer h.config.deinit(gpa); + h.clock = .{ .io = io }; + h.core = lanes.Engine.init(gpa, &h.config, if (h.drafted) |*d| d.backend() else h.metal.backend(), h.clock.clock()); + errdefer h.core.deinit(); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = st.prompt_rows, .decode_share = o.decode_share, .structures = true, .logprobs = true, .draft_sources = .{ .drafter = if (drafter_dir) |dir| .{ .kind = "DSpark", .name = o.drafter_name orelse dir } else null } }); + h.cache = null; + h.cache_cap = if (o.prompt_cache_gib) |g| @intFromFloat(g * (1 << 30)) else budget; + if (h.cache_cap > 0) { + const M = backend.Metal; + const rules: api.prompt_cache.Rules = .{ .lookahead = 0, .planned = true, .grid = st.prompt_rows, .min_prompt = 0 }; + h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = h.metal, .vtable = &.{ .bytes = M.snapBytes, .save = M.snapSave, .restore = M.snapRestore, .drop = M.snapDrop } }, rules, @min(h.cache_cap, budget)); + h.host.cache = &h.cache.?; + h.host.info_.prompt_cache = true; + h.metal.room = .{ .ctx = h, .fit = fitCache }; + } + errdefer if (h.cache) |*store| store.deinit(); + h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick }; + try h.host.start(); + return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; +} + +fn cacheBudget(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) error{BadLoadLimit}!u64 { + var limit: u64 = @intFromFloat(@as(f64, @floatFromInt(ram)) * 0.75); + const value = std.mem.trim(u8, text orelse "", " \t"); + if (value.len > 0) { + const gb = std.fmt.parseFloat(f64, value) catch return error.BadLoadLimit; + if (!std.math.isFinite(gb) or gb <= 0) return error.BadLoadLimit; + const cap = @min(ram, working_set); + const bytes = gb * 1e9; + limit = if (bytes >= @as(f64, @floatFromInt(cap))) cap else @intFromFloat(bytes); + } + const margin: u64 = 2 << 30; + return if (limit > resident + margin) limit - resident - margin else 0; +} + +fn longest(bytes: u64, most: u32, streams: u64, draft_fixed: u64, draft_token: u64, draft_shared_token: u64) usize { + const one: u64 = st.cacheBytes(1) + streams * (draft_fixed + draft_token) + draft_shared_token; + if (one > bytes) return 0; + var lo: usize = 1; + var hi: usize = most; + while (lo < hi) { + const mid = lo + (hi - lo + 1) / 2; + const need = st.cacheBytes(mid) + streams * (draft_fixed + draft_token * @as(u64, @intCast(mid))) + draft_shared_token * @as(u64, @intCast(mid)); + if (need <= bytes) lo = mid else hi = mid - 1; + } + return lo; +} + +fn fitCache(ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const u32) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + const store = if (h.cache) |*owned| owned else return; + store.budget = @min(h.cache_cap, bytes); + const Left = struct { + s: *const api.prompt_cache.Store, + pub fn fits(l: @This()) bool { + return l.s.held <= l.s.budget; + } + }; + _ = store.giveBack(restoring, prompt, Left{ .s = store }); +} + +test "Inkling native admission keeps DSpark opt-in and refuses learned modes" { + var o: api.Open = .{ .dir = "checkpoint", .model_type = "inkling2_loop" }; + try std.testing.expect(refusal(o) == null); + try std.testing.expect(drafterDirectory(o) == null); + o.drafter = "checkpoint"; + try std.testing.expectEqualStrings("checkpoint", drafterDirectory(o).?); + o.drafts = false; + try std.testing.expect(drafterDirectory(o) == null); + o.speed_up = "distributed"; + try std.testing.expect(refusal(o) != null); + o.speed_up = null; + o.learn = "learned"; + try std.testing.expect(refusal(o) != null); + try std.testing.expect(contextProblem(0, 10) != null); + try std.testing.expect(contextProblem(-1, 10) != null); + try std.testing.expect(contextProblem(11, 10) != null); + try std.testing.expect(contextProblem(10, 10) == null); +} + +test "Inkling native open publishes the exact admission refusal" { + var problem: []const u8 = "not published"; + const o: api.Open = .{ .dir = "unused", .model_type = "inkling2_loop", .learn_conversations = true }; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: learned disk states are not implemented; serve without --learn and --learn-conversations", problem); +} + +test "Inkling native open releases DSpark when the later context admission refuses (TF_INKLING2_METAL_DIR, TF_INKLING2_DSPARK_DIR)" { + const dir = @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse return error.SkipZigTest; + const drafter_dir = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + var problem: []const u8 = "not published"; + var o: api.Open = .{ .dir = dir, .model_type = "inkling2_loop", .context = 0, .drafter = drafter_dir }; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: --context must be at least one token, and the selected context must fit the Metal state budget", problem); + o.context = std.math.maxInt(i64); + problem = "not published"; + try std.testing.expect((try open(std.testing.allocator, std.testing.allocator, std.testing.io, o, &problem)) == null); + try std.testing.expectEqualStrings("inkling2_loop: --context exceeds the largest window this Mac can afford beside the checkpoint and DSpark state", problem); + // Null skips errdefer; omitting explicit deinit leaks allocations caught by std.testing.allocator. +} + +test "Inkling native open unwinds DSpark when the later Host allocation fails (TF_INKLING2_METAL_DIR, TF_INKLING2_DSPARK_DIR)" { + const Fault = struct { + drafter_allocated: bool = false, + host_failed: bool = false, + + fn allocator(f: *@This()) std.mem.Allocator { + return .{ .ptr = f, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const f: *@This() = @ptrCast(@alignCast(ctx)); + if (f.drafter_allocated and len == @sizeOf(Host)) { + f.host_failed = true; + return null; + } + const memory = std.testing.allocator.rawAlloc(len, alignment, ra) orelse return null; + if (len == @sizeOf(dspark.Drafter)) f.drafter_allocated = true; + return memory; + } + fn resize(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool { + return std.testing.allocator.rawResize(memory, alignment, len, ra); + } + fn remap(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 { + return std.testing.allocator.rawRemap(memory, alignment, len, ra); + } + fn free(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ra: usize) void { + std.testing.allocator.rawFree(memory, alignment, ra); + } + }; + const dir = @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse return error.SkipZigTest; + const drafter_dir = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + var fault: Fault = .{}; + var problem: []const u8 = ""; + const o: api.Open = .{ .dir = dir, .model_type = "inkling2_loop", .context = 1, .lanes = 1, .drafter = drafter_dir }; + try std.testing.expectError(error.OutOfMemory, open(std.testing.allocator, fault.allocator(), std.testing.io, o, &problem)); + try std.testing.expect(fault.drafter_allocated and fault.host_failed); + // Removing errdefer leaks DSpark and its weights in std.testing.allocator. +} + +test "Inkling native load limit clamps before integer conversion" { + const gib: u64 = 1 << 30; + try std.testing.expectEqual(8_000_000_000 - 5 * gib, try cacheBudget(16 * gib, 14 * gib, "8", 3 * gib)); + try std.testing.expectEqual(9 * gib, try cacheBudget(16 * gib, 14 * gib, "1e30", 3 * gib)); + try std.testing.expectEqual(0, try cacheBudget(4 * gib, 4 * gib, null, 3 * gib)); + for ([_][]const u8{ "0", "-1", "nan", "inf", "bad" }) |text| { + try std.testing.expectError(error.BadLoadLimit, cacheBudget(16 * gib, 14 * gib, text, 3 * gib)); + } +} + +test "Inkling native longest context accounts target, streams and shared draft scores" { + const budget = st.cacheBytes(7) + 2 * (11 + 7 * 13) + 7 * 17; + try std.testing.expectEqual(@as(usize, 7), longest(budget, 8, 2, 11, 13, 17)); + try std.testing.expectEqual(@as(usize, 0), longest(st.cacheBytes(1) - 1, 8, 1, 0, 0, 0)); + // A stream's bytes are within the ring's slack of its fixed bytes and a token's bytes a token, never under. + const fit = dl.fit(); + for ([_]usize{ 1, 127, 128, 129, 4096, 262144 }) |n| { + const bound = fit.fixed + n * fit.lane; + try std.testing.expect(bound >= dl.laneBytes(n)); + try std.testing.expect(bound - dl.laneBytes(n) <= dl.ring_slack * fit.lane); + } + // 36 GiB of state hold the model's whole window for eight drafted streams. + try std.testing.expectEqual(@as(usize, 262144), longest(36 << 30, 262144, 8, fit.fixed, fit.lane, fit.shared)); +} diff --git a/zig/src/native/inkling2_capabilities_test.zig b/zig/src/native/inkling2_capabilities_test.zig new file mode 100644 index 00000000000..5dd1c0c1403 --- /dev/null +++ b/zig/src/native/inkling2_capabilities_test.zig @@ -0,0 +1,13 @@ +//! Inkling's checkpoint-format offer in the production native Metal registry. +const std = @import("std"); +const native_metal = @import("native_metal"); + +test "Metal capabilities: inkling2_loop serves the checkpoint's ModelOpt NVFP4 weights" { + var found = false; + for (native_metal.families) |family| if (std.mem.eql(u8, family.model_type, "inkling2_loop")) { + found = true; + try std.testing.expectEqual(@as(usize, 1), family.formats.len); + try std.testing.expectEqualStrings("modelopt-nvfp4", family.formats[0]); + }; + try std.testing.expect(found); +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 499fda3bc07..13bd6c0f744 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -41,7 +41,6 @@ const affine_widths = blk: { }; /// Gemma 4's: MLX affine 2-6 or 8 bits in groups of 64, uniform or per module (oQ packs). const gemma4_widths: []const []const u8 = &.{ "mlx-q2g64", "mlx-q3g64", "mlx-q4g64", "mlx-q5g64", "mlx-q6g64", "mlx-q8g64" }; - pub const families: []const api.Family = &.{ .{ .model_type = "kimi_k3", .formats = &.{"mxfp4"} }, .{ .model_type = "kimi_k31", .formats = &.{"mxfp4"} }, @@ -62,6 +61,7 @@ pub const families: []const api.Family = &.{ .{ .model_type = "gemma4_unified", .formats = gemma4_widths }, .{ .model_type = "step5_vl", .formats = &.{"mlx-q2g128"} }, .{ .model_type = "spark2_5", .formats = &.{ "bf16", "mlx-q2g64", "mlx-q3g64", "mlx-q4g64", "mlx-q5g64", "mlx-q6g64", "mlx-q8g64" } }, + .{ .model_type = "inkling2_loop", .formats = &.{"modelopt-nvfp4"} }, .{ .model_type = "minimax_m3_vl", .formats = &.{ "mlx-q3g64", "mlx-q8g64" } }, .{ .model_type = "hy_v4_flash", .formats = &.{ "mlx-q4g64", "mlx-q8g64" } }, .{ .model_type = "qwen3", .formats = &.{"bf16"} }, @@ -69,7 +69,6 @@ pub const families: []const api.Family = &.{ .{ .model_type = "flint", .formats = &.{"mlx-q4g64"} }, .{ .model_type = "unlimited-ocr", .formats = &.{"bf16"} }, }; - /// Gemma 4 31B (gemma4) and 12B (gemma4_unified, its text model): one native family, gemma4.zig's host. fn isGemma4(model_type: []const u8) bool { return std.mem.eql(u8, model_type, "gemma4") or std.mem.eql(u8, model_type, "gemma4_unified"); @@ -166,6 +165,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c if (std.mem.eql(u8, o.model_type, "qwen3_5")) return @import("qwen35.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "step5_vl")) return @import("step5.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "spark2_5")) return @import("spark25.zig").open(a, gpa, io, o, problem); + if (std.mem.eql(u8, o.model_type, "inkling2_loop")) return @import("tensorfold").inkling2_native.open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "minimax_m3_vl")) return @import("minimax_m3.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "llama")) return @import("llama.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "flint")) return @import("flint.zig").open(a, gpa, io, o, problem); @@ -295,7 +295,7 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { if (o.kv8) return "--kv-cache fp8 keeps fp8 caches on CUDA; the Metal engines keep bf16: serve without it"; if (o.prompt_int8) return prompt_int8_refusal; if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; - if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5) and Llama (a smaller Llama on the same tokenizer)"; + if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark) and Llama (a smaller Llama on the same tokenizer)"; const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "nemotron_h_puzzle")) "Nemotron 3.5 Bolt" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.speed_up != null) if (one_mac) |name| return try std.fmt.allocPrint(a, "--speed-up joins two Macs for Flash Next, GLM-5.3-Flash and GLM-5.3 only: serve {s} without it", .{name}); if (o.recall and std.mem.eql(u8, t, "qwen4_exp")) return recall_refusal; diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 5a29cf3aef1..6391bfa51f1 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -25,12 +25,16 @@ pub const idol = @import("families/idol/idol.zig"); /// Unlimited-OCR-2 on Metal: document pages to text (its image encoder and decoder). pub const uocr = @import("families/uocr/uocr.zig"); pub const checkpoint = @import("core/checkpoint_metal.zig"); +pub const checkpoint_file_cache = @import("core/checkpoint_file_cache.zig"); pub const shard_edit = @import("core/shard_edit.zig"); pub const lora_merge = @import("core/lora_merge_dir.zig"); pub const npy = @import("core/npy.zig"); pub const picture = @import("core/picture/picture.zig"); pub const ids_json = @import("core/ids_json.zig"); pub const lanes = @import("lanes"); +pub const inkling2_native = @import("inkling2_native.zig"); +pub const inkling2_metal_host = @import("families/inkling2/metal/metal.zig"); +pub const inkling2_dspark_host = @import("families/inkling2/metal/dspark_kernels.zig"); pub const segments = @import("core/segments.zig"); pub const prompt_tail = @import("core/prompt_tail.zig"); pub const row_projection = @import("core/row_projection.zig"); diff --git a/zig/tests/contract/metal_inkling2_attention.zig b/zig/tests/contract/metal_inkling2_attention.zig new file mode 100644 index 00000000000..7516ceb19d4 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_attention.zig @@ -0,0 +1,576 @@ +//! Inkling 2 Mini Metal attention gates 1-4 with an independent float64 formula and both prompt layouts. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_inkling2_attention_controls.zig"); +const sources = @import("inkling2_metal"); +const plan = @import("tensorfold").inkling2_metal_host.attention.planning; +const c = contract.spec; +const g = contract.gates; +const Which = controls.Which; +const Mutation = controls.Mutation; +const D = 128; +const H = 24; +const KV = 8; +const R = 16; +const EXTENT = 1024; +const scale = 0.08838834764831845; + +const prep_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 9000 } }; +const prep_global_shapes = [_]c.Shape{ prep_shapes[0], prep_shapes[1], .{ .rows = 4, .n = H * D, .k = 1048576 } }; +const rel_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * EXTENT, .k = R }, .{ .rows = 1, .n = H * EXTENT, .k = R } }; +const sliding_shapes = [_]c.Shape{ .{ .rows = 7, .n = H * D, .k = 1030 }, .{ .rows = 3, .n = H * D, .k = 2049 } }; +const global_shapes = [_]c.Shape{ .{ .rows = 4, .n = H * D, .k = 1100 }, .{ .rows = 2, .n = H * D, .k = 1030 } }; +const prompt_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 80 } }; +/// A window that starts inside a tile, one that wraps the ring, and one not yet full. +const prompt_sliding_shapes = [_]c.Shape{ .{ .rows = 8, .n = H * D, .k = 1100 }, .{ .rows = 64, .n = H * D, .k = 2049 }, .{ .rows = 64, .n = H * D, .k = 80 } }; +fn depth(s: c.Shape) usize { + return D + 4 * s.k + 64; +} +fn flat(_: c.Shape) usize { + return R; +} +fn spec(w: Which) c.Spec { + const x: c.Spec = .{ .name = "", .accum = .f32, .depth = depth, .ops = 64, .mids = 8, .out = .bf16, .served = &global_shapes, .sums = .{ .f16 = 0, .bf16 = 0, .exact = true, .why = "P and outputs have required bf16 roundings" } }; + var s = x; + switch (w) { + .prep_sliding, .prep_global => { + s.name = if (w == .prep_global) "metal inkling2 attention prep global tf_ink2_prep" else "metal inkling2 attention prep sliding tf_ink2_prep"; + s.served = if (w == .prep_global) &prep_global_shapes else &prep_shapes; + s.ops = 32; + s.mids = 2; + }, + .rel_table => { + s.name = "metal inkling2 attention relative table tf_ink2_rel_table"; + s.served = &rel_shapes; + s.depth = flat; + s.ops = 4; + s.mids = 0; + }, + .decode_sliding => { + s.name = "metal inkling2 attention scalar sliding tf_ink2_attn_scalar"; + s.served = &sliding_shapes; + }, + .decode_global => { + s.name = "metal inkling2 attention scalar global tf_ink2_attn_scalar"; + s.served = &global_shapes; + }, + .prompt_m5 => { + s.name = "metal inkling2 prompt m5 tf_ink2_attn_prompt"; + s.served = &prompt_shapes; + }, + .prompt_pre_m5 => { + s.name = "metal inkling2 prompt pre-m5 tf_ink2_attn_prompt"; + s.served = &prompt_shapes; + }, + .prompt_sliding_m5 => { + s.name = "metal inkling2 prompt m5 sliding tf_ink2_attn_prompt"; + s.served = &prompt_sliding_shapes; + }, + .prompt_sliding_pre_m5 => { + s.name = "metal inkling2 prompt pre-m5 sliding tf_ink2_attn_prompt"; + s.served = &prompt_sliding_shapes; + }, + } + return s; +} +fn bf(x: u16) f64 { + return c.fromBf16(x); +} +fn rn(x: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(x))); +} +fn bits(x: f64) u16 { + return c.toBf16(@floatCast(x)); +} +fn minNum(x: f64, y: f64) f64 { + return if (std.math.isNan(x)) y else if (std.math.isNan(y)) x else @min(x, y); +} +fn maxNan(x: f64, y: f64) f64 { + return if (std.math.isNan(x) or std.math.isNan(y)) std.math.nan(f64) else @max(x, y); +} +fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} +/// Prompt P rounds to BF16 at each tile maximum; later rescaling does not round twice. The result anchors weights. +fn promptWeights(score: []const f64, weights: []f64) f64 { + const tile_keys = 64; + const sub_keys = 1024; + var top = -std.math.inf(f64); + var upper = -std.math.inf(f64); + var first: usize = 0; + while (first < score.len) { + const end = @min(first + tile_keys, score.len); + const sub_first = first - first % sub_keys; + var tile_peak = top; + for (score[first..end]) |sc| tile_peak = maxNan(tile_peak, sc); + const mu = if (tile_peak == -std.math.inf(f64)) 0 else tile_peak; + const keep = @exp(top - mu); + for (weights[sub_first..first]) |*w| w.* *= keep; + for (weights[first..end], score[first..end]) |*w, sc| w.* = rn(@exp(sc - mu)); + top = tile_peak; + if (first % sub_keys == sub_keys - tile_keys or end == score.len) { + if (top != -std.math.inf(f64)) { + const merged = maxNan(upper, top); + const old_scale = @exp(upper - merged); + const new_scale = @exp(top - merged); + for (weights[0..sub_first]) |*w| w.* *= old_scale; + for (weights[sub_first..end]) |*w| w.* *= new_scale; + upper = merged; + } + top = -std.math.inf(f64); + } + first = end; + } + return upper; +} +fn tau(pos: usize) f64 { + return 1 + 0.1 * @log(@max(@as(f64, @floatFromInt(pos + 1)) / 8192, 1)); +} +fn periodic(p: usize, col: usize) f64 { + const i = p % 1024; + if (i < 512) return @floatFromInt(129 + (i * 73 + col * 31) % 127); + const j = i - 512; + return -@as(f64, @floatFromInt(129 + ((j + 1) * 73 + col * 31) % 127)) + @as(f64, if (j < 8) 1 else 0); +} +const Sim = struct { acc: c.Accum, order: g.Order }; +fn sum(v: []const f64, sim: ?Sim) f64 { + if (sim) |s| return contract.rows.sumIn(s.acc, s.order, v); + var total: f64 = 0; + for (v) |x| total += x; + return total; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + which: Which, + mutation: Mutation, + lib: mtl.Library, + main: mtl.Pipeline, + merge_lib: ?mtl.Library = null, + merge: mtl.Pipeline = undefined, + fused: bool = false, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + fill: g.Fill = .random, + layer: plan.Layer = undefined, + q: []u16 = &.{}, + kc: []u16 = &.{}, + vc: []u16 = &.{}, + tab: []u16 = &.{}, + sink: []u16 = &.{}, + gate: []u16 = &.{}, + rel: []u16 = &.{}, + proj: []u16 = &.{}, + qs: []u16 = &.{}, + rs: []u16 = &.{}, + pos: []usize = &.{}, + refs: [10]rig_.Ref = undefined, + out: [4]rig_.Ref = undefined, + meta: [3]rig_.Ref = undefined, + po: rig_.Ref = undefined, + pml: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, w: Which, m: Mutation) !Probe { + const plain = if (controls.isPrompt(w)) (if (controls.isPre(w)) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const text = try controls.apply(a, plain, m); + defer a.free(text); + var lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + errdefer lib.deinit(); + var main = try mtl.Pipeline.init(device, lib, controls.function(w), false); + errdefer main.deinit(); + var merge_lib: ?mtl.Library = null; + errdefer if (merge_lib) |loaded| loaded.deinit(); + var merge: mtl.Pipeline = undefined; + const fused = controls.isAttention(w); + if (fused) { + if (controls.isPrompt(w)) merge_lib = try mtl.Library.fromSource(device, sources.attention, mtl.CompileOptions.mlx()); + const merge_library = if (merge_lib) |loaded| loaded else lib; + merge = try mtl.Pipeline.init(device, merge_library, "tf_ink2_merge", false); + } + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .which = w, .mutation = m, .lib = lib, .main = main, .merge_lib = merge_lib, .merge = merge, .fused = fused }; + } + fn hostFree(p: *Probe) void { + inline for (.{ "q", "kc", "vc", "tab", "sink", "gate", "rel", "proj", "qs", "rs", "pos" }) |f| { + p.a.free(@field(p, f)); + @field(p, f) = &.{}; + } + } + pub fn deinit(p: *Probe) void { + p.hostFree(); + p.rig.deinit(); + if (p.fused) p.merge.deinit(); + if (p.merge_lib) |loaded| loaded.deinit(); + p.main.deinit(); + p.lib.deinit(); + } + const vt = g.hooks(Probe); + pub fn kernel(p: *Probe) g.Kernel { + var k: g.Kernel = .{ .spec = spec(p.which), .ctx = p, .vt = &vt }; + if (p.mutation != .none) { + k.spec.name = p.mutation.name(); + k.control = p.mutation.gate(); + } + return k; + } + fn sizes(p: *const Probe) [4]usize { + const n = p.rigCache(); + return .{ p.shape.rows * H * D, p.shape.rows * H * R, n, n }; + } + fn rigCache(p: *const Probe) usize { + return KV * p.layer.ring * D; + } + pub fn count(p: *const Probe) usize { + if (p.which == .rel_table) return p.shape.rows * H * EXTENT; + if (controls.isAttention(p.which)) return p.shape.rows * H * D; + const z = p.sizes(); + return z[0] + z[1] + z[2] + z[3]; + } + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.rows == 0 or s.k < s.rows) return false; + if (p.which == .rel_table) { + if (s.n != H * EXTENT or s.k != R) return false; + } else if (s.n != H * D) return false; + p.hostFree(); + p.rig.reset(); + p.shape = s; + p.fill = fill; + const tiled = controls.isPromptSliding(p.which); + const global = p.which == .prep_global or p.which == .decode_global or (controls.isPrompt(p.which) and !tiled); + const sliding = p.which == .prep_sliding or p.which == .decode_sliding or tiled; + p.layer = .{ .window = if (sliding) 1024 else 0, .ring = 2048, .chunk = if (tiled) plan.tile_keys else if (sliding) 256 else plan.global_chunk, .tau = global }; + const rows = s.rows; + const rh = rows * H; + const cache = KV * p.layer.ring * D; + p.pos = try p.a.alloc(usize, rows); + for (p.pos, 0..) |*v, r| v.* = s.k - rows + r; + if (p.which != .rel_table) { + p.q = try p.a.alloc(u16, rh * D); + p.tab = try p.a.alloc(u16, rh * EXTENT); + @memset(p.q, 0); + @memset(p.tab, 0); + } else { + p.rel = try p.a.alloc(u16, rh * R); + p.proj = try p.a.alloc(u16, R * EXTENT); + @memset(p.rel, 0); + @memset(p.proj, 0); + } + if (!controls.isAttention(p.which) and p.which != .rel_table) p.rel = try p.a.alloc(u16, rh * R); + if (p.which != .rel_table) { + p.kc = try p.a.alloc(u16, if (controls.isAttention(p.which)) cache else rows * KV * D); + p.vc = try p.a.alloc(u16, p.kc.len); + @memset(p.kc, 0); + @memset(p.vc, 0); + } + if (controls.isAttention(p.which)) { + p.sink = try p.a.alloc(u16, rh); + p.gate = try p.a.alloc(u16, rh * D); + @memset(p.sink, 0); + @memset(p.gate, 0); + } + if (p.which == .prep_sliding or p.which == .prep_global) { + p.qs = try p.a.alloc(u16, H * D); + p.rs = try p.a.alloc(u16, H * R); + @memset(p.qs, 0); + @memset(p.rs, 0); + } + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.fillValues(rng, global); + if (fill == .nonfinite) p.plant(); + try p.bind(); + return true; + } + fn fillValues(p: *Probe, rng: std.Random, global: bool) void { + const stress = p.fill == .stress; + for (p.q) |*v| v.* = bits(if (stress and controls.isAttention(p.which)) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 511))) - 255) else rng.floatNorm(f64) * 0.3); + for (p.kc) |*v| v.* = bits(if (stress and controls.isAttention(p.which)) 0 else if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64) * 0.3); + for (p.vc, 0..) |*v, i| v.* = if (stress and controls.isAttention(p.which)) bits(periodic(i / D % p.layer.ring, i % D)) else bits(if (stress) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 255))) - 127) else rng.floatNorm(f64)); + for (p.tab) |*v| v.* = bits(if (stress) 0 else rng.floatNorm(f64) * 0.25); + for (p.sink) |*v| v.* = bits(if (stress) -std.math.inf(f64) else 2 + 4 * rng.float(f64)); + for (p.gate) |*v| v.* = bits(if (stress) 32 else rng.floatNorm(f64)); + for (p.rel, 0..) |*v, i| v.* = bits(if (stress) @floatFromInt(2 * (i % 31) + 1) else rng.floatNorm(f64)); + for (p.proj, 0..) |*v, i| v.* = bits(if (stress) @floatFromInt(1 + i % 2) else rng.floatNorm(f64) * 0.5); + for (p.qs) |*v| v.* = bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); + for (p.rs) |*v| v.* = bits(if (stress) 1 else 0.5 + 2 * rng.float(f64)); + if (global and !controls.isAttention(p.which)) { + _ = tau(p.pos[0]); + } + } + fn plant(p: *Probe) void { + const nan = bits(std.math.nan(f64)); + const inf = bits(std.math.inf(f64)); + if (p.which == .rel_table) { + p.rel[3] = nan; + if (p.rel.len > R + 5) p.rel[R + 5] = inf; + if (p.rel.len > 2 * R + 1) { + p.rel[2 * R] = inf; + p.rel[2 * R + 1] = inf | 0x8000; + } + } else if (controls.isAttention(p.which)) { + p.q[D + 5] = nan; + p.sink[2] = inf; + p.gate[3 * D] = inf; + p.gate[3 * D + 1] = inf | 0x8000; + } else { + p.q[D + 3] = nan; + p.kc[5] = inf; + p.vc[D] = inf | 0x8000; + p.rel[2] = nan; + } + } + fn bind(p: *Probe) !void { + const rows = p.shape.rows; + if (p.which == .rel_table) { + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.rel)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.proj)); + p.out[0] = try p.rig.output(p.count() * 2); + return; + } + if (controls.isAttention(p.which)) { + const arrays = [_][]u16{ p.q, p.kc, p.vc, p.tab, p.sink, p.gate }; + for (arrays, 0..) |x, i| p.refs[i] = try p.rig.input(std.mem.sliceAsBytes(x)); + } else { + const arrays = [_][]u16{ p.q, p.kc, p.vc, p.rel, p.qs, p.rs }; + for (arrays, 0..) |x, i| p.refs[i] = try p.rig.input(std.mem.sliceAsBytes(x)); + } + const pos32 = try p.a.alloc(i32, rows); + defer p.a.free(pos32); + const seg32 = try p.a.alloc(i32, rows); + defer p.a.free(seg32); + @memset(seg32, 0); + for (pos32, p.pos) |*v, x| v.* = @intCast(x); + const seg = [1]plan.Seg{.{ .row0 = 0, .n = @intCast(rows), .p0 = @intCast(p.shape.k - rows), .off = 0 }}; + p.meta[0] = try p.rig.input(std.mem.sliceAsBytes(pos32)); + p.meta[1] = try p.rig.input(std.mem.sliceAsBytes(seg32)); + p.meta[2] = try p.rig.input(std.mem.sliceAsBytes(&seg)); + if (controls.isAttention(p.which)) { + const stride = plan.slotsFor(p.layer, p.shape.k); + const parts = rows * H * stride; + p.po = try p.rig.scratch(parts * D * 4); + p.pml = try p.rig.scratch(parts * 8); + p.out[0] = try p.rig.output(p.count() * 2); + } else for (p.sizes(), 0..) |n, i| p.out[i] = try p.rig.output(n * 2); + } + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.main); + const rows: u32 = @intCast(p.shape.rows); + const ring = p.layer.ring; + if (p.which == .rel_table) { + e.setBuffer(p.refs[0].buf, p.refs[0].off, 0); + e.setBuffer(p.refs[1].buf, p.refs[1].off, 1); + e.setBuffer(p.out[0].buf, p.out[0].off, 2); + e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(256, 1, 1)); + } else if (!controls.isAttention(p.which)) { + @memset(p.rig.bytes(p.out[2], p.sizes()[2] * 2), 0); + @memset(p.rig.bytes(p.out[3], p.sizes()[3] * 2), 0); + for (p.refs[0..6], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + for (p.meta, 6..) |r, i| e.setBuffer(r.buf, r.off, i); + for (p.out, 9..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(plan.PrepArgs{ .heads = H, .kv_heads = KV, .ring = ring, .global = @intFromBool(p.layer.tau), .qk_clip = 22.627416997969522, .rel_clip = 8, .floor_pos = 8192, .alpha = 0.1, .eps = 1e-6 }, 13); + e.dispatchGroups(mtl.Size.of(rows, H + 2 * KV, 1), mtl.Size.of(32, 1, 1)); + } else { + const stride = plan.slotsFor(p.layer, p.shape.k); + for (p.refs[0..4], 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setBuffer(p.meta[2].buf, p.meta[2].off, 4); + e.setBuffer(p.po.buf, p.po.off, 5); + e.setBuffer(p.pml.buf, p.pml.off, 6); + const sc: f32 = 1.0 / @sqrt(@as(f32, D)); + if (controls.isPrompt(p.which)) { + const launch = try plan.attend(.{ .rows = @intCast(rows), .last_pos = @intCast(p.shape.k - 1), .prompt = p.layer.window > 0 }, p.layer, stride, 0); + e.setValue(plan.PromptArgs{ .heads = H, .kv_heads = KV, .ring = ring, .chunk = p.layer.chunk, .c0 = launch.c0, .chunks = stride, .scale = sc, .window = p.layer.window }, 7); + e.dispatchGroups(mtl.Size.of(launch.grid[0], launch.grid[1], launch.grid[2]), mtl.Size.of(256, 1, 1)); + } else { + e.setBuffer(p.meta[0].buf, p.meta[0].off, 7); + e.setBuffer(p.meta[1].buf, p.meta[1].off, 8); + e.setValue(plan.AttnArgs{ .heads = H, .kv_heads = KV, .ring = ring, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride, .scale = sc }, 9); + e.dispatchGroups(mtl.Size.of(rows * H, stride, 1), mtl.Size.of(32, 1, 1)); + } + e.barrier(); + e.setPipeline(p.merge); + e.setBuffer(p.po.buf, p.po.off, 0); + e.setBuffer(p.pml.buf, p.pml.off, 1); + e.setBuffer(p.refs[4].buf, p.refs[4].off, 2); + e.setBuffer(p.refs[5].buf, p.refs[5].off, 3); + e.setBuffer(p.meta[0].buf, p.meta[0].off, 4); + e.setBuffer(p.out[0].buf, p.out[0].off, 5); + e.setValue(plan.MergeArgs{ .heads = H, .window = p.layer.window, .chunk = p.layer.chunk, .c0 = 0, .chunks = stride }, 6); + e.dispatchGroups(mtl.Size.of(rows * H, 1, 1), mtl.Size.of(D, 1, 1)); + } + try p.rig.finish(pass); + } + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + if (p.which == .rel_table) return p.tableRef(null, want, mag); + if (controls.isAttention(p.which)) return p.attentionRef(null, want, mag); + return p.prepRef(null, want, mag); + } + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + const mag = try p.a.alloc(f64, out.len); + defer p.a.free(mag); + const sim: Sim = .{ .acc = acc, .order = order }; + if (p.which == .rel_table) return p.tableRef(sim, out, mag); + if (controls.isAttention(p.which)) return p.attentionRef(sim, out, mag); + return p.prepRef(sim, out, mag); + } + fn tableRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + var terms: [R]f64 = undefined; + for (want, mag, 0..) |*w, *m, o| { + const rh = o / EXTENT; + const d = o % EXTENT; + for (&terms, 0..) |*v, j| v.* = bf(p.rel[rh * R + j]) * bf(p.proj[j * EXTENT + d]); + m.* = 0; + for (terms) |x| m.* += @abs(x); + const x = sum(&terms, sim); + w.* = if (sim != null) rn(x) else x; + } + } + fn headClip(x: []const f64, threshold: f64, sim: ?Sim, t: ?f64, want: []f64, mag: []f64) void { + var sq: [D]f64 = undefined; + mZero(mag); + for (sq[0..x.len], x, 0..) |*v, y, i| { + v.* = y * y; + mag[i] = @abs(y); + } + const f = minNum(threshold / (@sqrt(sum(sq[0..x.len], sim)) + 1e-6), 1); + for (want, x, mag) |*w, v, *m| { + w.* = rn(v * f); + if (t) |tv| w.* = rn(w.* * tv); + m.* = @abs(v) + v * v; + } + } + /// prep uses independent K/V and attention uses populated ring caches; q and rel never alias either one. + fn prepRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + const z = p.sizes(); + var x: [D]f64 = undefined; + for (0..p.shape.rows) |r| { + const tv: ?f64 = if (p.layer.tau) tau(p.pos[r]) else null; + for (0..H) |h| { + for (&x, 0..) |*v, d| v.* = bf(p.q[(r * H + h) * D + d]) * bf(p.qs[h * D + d]); + headClip(&x, 22.627416997969522, sim, tv, want[(r * H + h) * D ..][0..D], mag[(r * H + h) * D ..][0..D]); + for (x[0..R], 0..) |*v, d| v.* = bf(p.rel[(r * H + h) * R + d]) * bf(p.rs[h * R + d]); + const at = z[0] + (r * H + h) * R; + headClip(x[0..R], 8, sim, tv, want[at..][0..R], mag[at..][0..R]); + } + for (0..KV) |h| { + const slot = (h * p.layer.ring + p.pos[r] % p.layer.ring) * D; + for (&x, 0..) |*v, d| v.* = bf(p.kc[(r * KV + h) * D + d]); + headClip(&x, 22.627416997969522, sim, null, want[z[0] + z[1] + slot ..][0..D], mag[z[0] + z[1] + slot ..][0..D]); + var sq: [D]f64 = undefined; + for (&x, &sq, 0..) |*v, *ss, d| { + v.* = bf(p.vc[(r * KV + h) * D + d]); + ss.* = v.* * v.*; + } + const inv = 1 / @sqrt(sum(&sq, sim) / D + 1e-6); + for (0..D) |d| { + const at = z[0] + z[1] + z[2] + slot + d; + want[at] = rn(x[d] * inv); + mag[at] = sq[d] + @abs(x[d]); + } + } + } + } + fn mZero(mag: []f64) void { + @memset(mag, 0); + } + fn attentionRef(p: *Probe, sim: ?Sim, want: []f64, mag: []f64) !void { + const most = p.shape.k; + const score = try p.a.alloc(f64, most); + defer p.a.free(score); + const weights = try p.a.alloc(f64, most); + defer p.a.free(weights); + const terms = try p.a.alloc(f64, @max(most, D)); + defer p.a.free(terms); + for (0..p.shape.rows) |r| { + for (0..H) |h| { + const rh = r * H + h; + const pos = p.pos[r]; + const lo = if (p.layer.window > 0) (pos + 1) -| p.layer.window else 0; + const n = pos + 1 - lo; + const kvh = h / (H / KV); + const z = bf(p.sink[rh]); + // Prompt P is BF16 at the keys' maximum; the sink joins in the final merge using the shared maximum. + const prompt = sim == null and controls.isPrompt(p.which); + var peak = if (prompt) -std.math.inf(f64) else z; + for (lo..pos + 1) |kp| { + const j = kp - lo; + const at = (kvh * p.layer.ring + kp % p.layer.ring) * D; + for (0..D) |d| terms[d] = bf(p.q[rh * D + d]) * bf(p.kc[at + d]); + const distance = pos - kp; + const bias = if (distance < EXTENT) bf(p.tab[rh * EXTENT + distance]) else 0; + score[j] = sum(terms[0..D], sim) * scale + bias; + peak = maxNan(peak, score[j]); + } + if (prompt) { + peak = promptWeights(score[0..n], weights[0..n]); + } else for (weights[0..n], score[0..n]) |*w, sc| w.* = @exp(sc - peak); + const merged_peak = if (prompt) maxNan(peak, z) else peak; + const rescale = if (prompt) @exp(peak - merged_peak) else 1; + const den = sum(weights[0..n], sim) * rescale + @exp(z - merged_peak); + for (0..D) |d| { + for (lo..pos + 1) |kp| { + const j = kp - lo; + const at = (kvh * p.layer.ring + kp % p.layer.ring) * D; + terms[j] = weights[j] * bf(p.vc[at + d]); + } + const num = sum(terms[0..n], sim) * rescale; + const y = num / den * sigmoid(bf(p.gate[rh * D + d])); + want[rh * D + d] = if (sim != null) rn(y) else y; + mag[rh * D + d] = (@abs(num) + den + 1) * (1 + @abs(y)); + for (terms[0..n]) |v| mag[rh * D + d] += @abs(v * rescale); + } + } + } + } +}; + +fn supported(device: mtl.Device, w: Which) bool { + return switch (w) { + .prompt_m5, .prompt_sliding_m5 => device.tensorUnits(), + .prompt_pre_m5, .prompt_sliding_pre_m5 => !device.tensorUnits(), + else => true, + }; +} +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Which)) |w| { + if (!supported(s.device, w) or (only != null and std.mem.indexOf(u8, spec(w).name, only.?) == null)) continue; + try s.add(w, .none); + } + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const w = m.which(); + if (!supported(s.device, w) or (only != null and std.mem.indexOf(u8, m.name(), only.?) == null)) continue; + try s.add(w, m); + } + } + fn add(s: *Suite, w: Which, m: Mutation) !void { + const p = try s.a.create(Probe); + errdefer s.a.destroy(p); + p.* = Probe.init(s.a, s.device, s.queue, w, m) catch |err| { + var k: g.Kernel = .{ .spec = spec(w), .ctx = undefined, .vt = undefined, .control = m.gate(), .init_error = err }; + if (m != .none) k.spec.name = m.name(); + try s.kernels.append(s.a, k); + s.a.destroy(p); + return; + }; + try s.probes.append(s.a, p); + try s.kernels.append(s.a, p.kernel()); + } + pub fn deinit(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_attention_controls.zig b/zig/tests/contract/metal_inkling2_attention_controls.zig new file mode 100644 index 00000000000..87510911e20 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_attention_controls.zig @@ -0,0 +1,175 @@ +//! Count-checked, discriminating source edits for every Inkling 2 attention shader entry point. +const std = @import("std"); +const contract = @import("contract"); + +pub const Which = enum { prep_sliding, prep_global, rel_table, decode_sliding, decode_global, prompt_m5, prompt_pre_m5, prompt_sliding_m5, prompt_sliding_pre_m5 }; +pub fn function(w: Which) []const u8 { + return switch (w) { + .prep_sliding, .prep_global => "tf_ink2_prep", + .rel_table => "tf_ink2_rel_table", + .decode_sliding, .decode_global => "tf_ink2_attn_scalar", + .prompt_m5, .prompt_pre_m5, .prompt_sliding_m5, .prompt_sliding_pre_m5 => "tf_ink2_attn_prompt", + }; +} +pub fn isPrompt(w: Which) bool { + return w == .prompt_m5 or w == .prompt_pre_m5 or isPromptSliding(w); +} +/// The prompt kernel on a sliding layer: a window of keys a row, a tile of keys a chunk. +pub fn isPromptSliding(w: Which) bool { + return w == .prompt_sliding_m5 or w == .prompt_sliding_pre_m5; +} +/// The prompt kernel built for chips before the M5. +pub fn isPre(w: Which) bool { + return w == .prompt_pre_m5 or w == .prompt_sliding_pre_m5; +} +pub fn isAttention(w: Which) bool { + return w == .decode_sliding or w == .decode_global or isPrompt(w); +} + +pub const Mutation = enum { + none, + prep_swap_kv, + prep_tau_off, + rel_late, + decode_late_bias, + merge_no_sink, + prompt_late_bias, + prompt_pre_late_bias, + prompt_wide_window, + prompt_pre_wide_window, + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .prep_swap_kv => "control: metal inkling2 attention prep sliding with gated K/V inputs exchanged tf_ink2_prep", + .prep_tau_off => "control: metal inkling2 attention global prep without tau tf_ink2_prep", + .rel_late => "control: metal inkling2 attention relative projection one column late tf_ink2_rel_table", + .decode_late_bias => "control: metal inkling2 attention sliding first key score boosted tf_ink2_attn_scalar", + .merge_no_sink => "control: metal inkling2 attention global merge without sink tf_ink2_merge", + .prompt_late_bias => "control: metal inkling2 prompt m5 first key bias boosted tf_ink2_attn_prompt", + .prompt_pre_late_bias => "control: metal inkling2 prompt pre-m5 first key bias boosted tf_ink2_attn_prompt", + .prompt_wide_window => "control: metal inkling2 prompt m5 sliding window half as long tf_ink2_attn_prompt", + .prompt_pre_wide_window => "control: metal inkling2 prompt pre-m5 sliding window half as long tf_ink2_attn_prompt", + }; + } + pub fn gate(m: Mutation) ?contract.gates.Gate { + return if (m == .none) null else .shapes; + } + pub fn which(m: Mutation) Which { + return switch (m) { + .none => unreachable, + .prep_swap_kv => .prep_sliding, + .prep_tau_off => .prep_global, + .rel_late => .rel_table, + .decode_late_bias => .decode_sliding, + .merge_no_sink => .decode_global, + .prompt_late_bias => .prompt_m5, + .prompt_pre_late_bias => .prompt_pre_m5, + .prompt_wide_window => .prompt_sliding_m5, + .prompt_pre_wide_window => .prompt_sliding_pre_m5, + }; + } + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .prep_swap_kv => .{ + .from = "const device bfloat* src = (key ? k_raw : v_raw) + (size_t(row) * a.kv_heads + h) * D;", + .to = "const device bfloat* src = (key ? v_raw : k_raw) + (size_t(row) * a.kv_heads + h) * D;", + }, + .prep_tau_off => .{ + .from = "const float tau = a.global ? 1.0f + a.alpha * precise::log(max(float(pos + 1) / a.floor_pos, 1.0f)) : 1.0f;", + .to = "const float tau = 1.0f;", + }, + .rel_late => .{ + .from = "acc += r[j] * float(proj[j * EXTENT + d]);", + .to = "acc += r[j] * float(proj[j * EXTENT + (d + 1) % EXTENT]);", + }, + .decode_late_bias => .{ + .from = "const float score = (dot_score * a.scale + bias) * LOG2E;", + .to = "const float score = (dot_score * a.scale + bias + (kp == from ? 128.0f : 0.0f)) * LOG2E;", + }, + .merge_no_sink => .{ + .from = "const float sk = float(sink[rh]) * LOG2E, mf = max(mm, sk), a0 = precise::exp2(mm - mf);", + .to = "const float sk = -INFINITY, mf = max(mm, sk), a0 = precise::exp2(mm - mf);", + }, + .prompt_late_bias, .prompt_pre_late_bias => .{ + .from = "const float bias = live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f;", + .to = "const float bias = (live && distance < EXTENT ? float(tab[prow * EXTENT + distance]) : 0.0f) + (live && kp == b_lo ? 128.0f : 0.0f);", + }, + .prompt_wide_window, .prompt_pre_wide_window => .{ + .from = "(a.window == 0u || kp + a.window > pos);", + .to = "(a.window == 0u || kp + a.window / 2u > pos);", + }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, text: []const u8, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, text); + const e = m.edit(); + if (std.mem.count(u8, text, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, text, e.from, e.to); +} + +test "Inkling 2 attention controls each hit one live statement and cannot apply twice" { + const a = std.testing.allocator; + const sources = @import("inkling2_metal"); + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const w = m.which(); + const plain = if (isPrompt(w)) (if (isPre(w)) sources.prompt_attention_pre_m5 else sources.prompt_attention) else sources.attention; + const edited = try apply(a, plain, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectError(error.ControlEditMissing, apply(a, edited, m)); + try std.testing.expectEqual(contract.gates.Gate.shapes, m.gate().?); + } + const unchanged = try apply(a, sources.attention, .none); + defer a.free(unchanged); + try std.testing.expectEqualStrings(sources.attention, unchanged); +} + +fn fp64Clip(src: []const f64, dst: []f64, threshold: f64) void { + var ss: f64 = 0; + for (src) |x| ss += x * x; + const f = @min(threshold / (@sqrt(ss) + 1e-6), 1); + for (dst, src) |*y, x| y.* = x * f; +} + +fn fp64Rms(src: []const f64, dst: []f64) void { + var ss: f64 = 0; + for (src) |x| ss += x * x; + const inv = 1 / @sqrt(ss / @as(f64, @floatFromInt(src.len)) + 1e-6); + for (dst, src) |*y, x| y.* = x * inv; +} + +test "Inkling 2 gated FP64 prep exchanges only K/V" { + const q = [4]f64{ 4, 0, 0, 0 }; + const rel = [4]f64{ 4, 0, 0, 0 }; + const k = [4]f64{ 4, 0, 0, 0 }; + const v = [4]f64{ 0, 3, 0, 0 }; + var q_base: [4]f64 = undefined; + var q_swap: [4]f64 = undefined; + var rel_base: [4]f64 = undefined; + var rel_swap: [4]f64 = undefined; + var k_base: [4]f64 = undefined; + var k_swap: [4]f64 = undefined; + var v_base: [4]f64 = undefined; + var v_swap: [4]f64 = undefined; + fp64Clip(&q, &q_base, 5); + fp64Clip(&q, &q_swap, 5); + fp64Clip(&rel, &rel_base, 5); + fp64Clip(&rel, &rel_swap, 5); + fp64Clip(&k, &k_base, 5); + fp64Clip(&v, &k_swap, 5); + fp64Rms(&v, &v_base); + fp64Rms(&k, &v_swap); + try std.testing.expectEqualSlices(f64, &q_base, &q_swap); + try std.testing.expectEqualSlices(f64, &rel_base, &rel_swap); + try std.testing.expectEqualSlices(f64, &.{ 4, 0, 0, 0 }, &k_base); + try std.testing.expectEqualSlices(f64, &.{ 0, 3, 0, 0 }, &k_swap); + const v_from_v = 3 * (1 / @sqrt(@as(f64, 9) / 4 + 1e-6)); + const v_from_k = 4 * (1 / @sqrt(@as(f64, 16) / 4 + 1e-6)); + try std.testing.expectEqualSlices(f64, &.{ 0, v_from_v, 0, 0 }, &v_base); + try std.testing.expectEqualSlices(f64, &.{ v_from_k, 0, 0, 0 }, &v_swap); +} diff --git a/zig/tests/contract/metal_inkling2_controls_host.zig b/zig/tests/contract/metal_inkling2_controls_host.zig new file mode 100644 index 00000000000..dddbd887d0b --- /dev/null +++ b/zig/tests/contract/metal_inkling2_controls_host.zig @@ -0,0 +1,13 @@ +//! Every Inkling 2 Mini source control must apply once without a Metal compiler. + +test { + _ = @import("metal_inkling2_attention_controls.zig"); + _ = @import("metal_inkling2_glue_controls.zig"); + _ = @import("metal_inkling2_experts_controls.zig"); + _ = @import("metal_inkling2_units_controls.zig"); + _ = @import("metal_inkling2_loop_controls.zig"); + _ = @import("metal_inkling2_runtime_controls.zig"); + _ = @import("metal_inkling2_dspark_controls.zig"); + _ = @import("metal_inkling2_dspark_chain_controls.zig"); + _ = @import("metal_inkling2_dspark_units_controls.zig"); +} diff --git a/zig/tests/contract/metal_inkling2_dense_units.zig b/zig/tests/contract/metal_inkling2_dense_units.zig new file mode 100644 index 00000000000..2ebf6bc0ba3 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dense_units.zig @@ -0,0 +1,181 @@ +//! Inkling 2 Mini's prompt projections on the tensor units: an FP64 dot of BF16 values, stored as BF16. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +/// The columns the kernel takes: the hidden width, and the query width `wo` reads. +const widths = [_]usize{ 2304, 3072 }; +pub const name = "metal inkling2 units tf_ink2_dense_units"; + +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(control: bool) c.Spec { + return .{ + .name = if (control) controls.Mutation.dense_store.name() else name, + .accum = .f32, + .depth = depth, + .ops = 3, + .out = .bf16, + // Rows go 16 a band and outputs 32 a tile; 24 and 90 outputs leave the last tile part full. + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{} }, + .served = &.{ .{ .rows = 1, .n = 64, .k = 2304 }, .{ .rows = 8, .n = 24, .k = 2304 }, .{ .rows = 20, .n = 90, .k = 3072 } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and one BF16 store" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + control: bool, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + refs: [3]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Probe { + const text = try controls.apply(a, if (control) .dense_store else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .control = control }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.x = &.{}; + p.w = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.control), .ctx = p, .vt = &vt, .control = if (p.control) controls.Mutation.dense_store.gate() else null }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > 40 or shape.n == 0 or shape.n > 128 or std.mem.indexOfScalar(usize, &widths, shape.k) == null) return false; + p.clear(); + p.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, shape.rows * shape.k); + p.w = try p.a.alloc(u16, shape.n * shape.k); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + for (p.w) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + if (fill == .stress) { + // Whole numbers times a power of two: every product and partial sum is exact. + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + for (p.w, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(@as(i32, @intCast(i % 7)) - 3)) * 0x1p-20); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.w)); + p.refs[2] = try p.rig.output(p.count() * 2); + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + try host.denseUnits(&p.pipes, pass.e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.n), @intCast(p.shape.k)); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * p.shape.n; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const row = at / p.shape.n; + const v = at % p.shape.n; + const k = p.shape.k; + var store: [3072]f64 = undefined; + const terms = store[0..k]; + var magnitude: f64 = 0; + for (terms, 0..) |*term, d| { + term.* = @as(f64, c.fromBf16(p.w[v * k + d])) * @as(f64, c.fromBf16(p.x[row * k + d])); + magnitude += @abs(term.*); + } + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, terms) else blk: { + var total: f64 = 0; + for (terms) |term| total += term; + break :blk total; + }; + return .{ .value = bf(sum), .magnitude = magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [2]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entry exists only where the GPU has tensor units; elsewhere a prompt's rows take the shared matvec. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for ([_]bool{ false, true }) |control| { + const label = spec(control).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + } + } +}; + +test "the dense entry resolves to its symbol in the units source" { + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, "tf_ink2_dense_units(")); +} diff --git a/zig/tests/contract/metal_inkling2_dspark.zig b/zig/tests/contract/metal_inkling2_dspark.zig new file mode 100644 index 00000000000..659d4b3305a --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark.zig @@ -0,0 +1,590 @@ +//! Mini DSpark's ten real Metal launches with guarded buffers, FP64 references and red controls. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_dspark_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_dspark_host; +const sources = @import("inkling2_metal"); + +const H = host.hidden; +const Q = host.query_width; +const KV = host.kv_width; +const RANK = host.rank; +const RNN = host.rnn_width; +const INTER = host.intermediate; + +fn depth(s: c.Shape) usize { + return s.k + 16; +} +fn bf(v: anytype) f64 { + return host.roundBf16(v); +} +fn rounded(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} +fn rms(values: []const f32, start: usize, width: usize) f32 { + var sum: f32 = 0; + for (0..width) |d| { + const x = values[start + d]; + sum += x * x; + } + return 1.0 / @sqrt(sum / @as(f32, @floatFromInt(width)) + 1e-6); +} +fn rope(d: usize, position: usize, x: f32, other: f32) f64 { + const frequency = std.math.pow(f32, 1e6, -@as(f32, @floatFromInt(d % 64)) / 64.0); + const angle = @as(f32, @floatFromInt(position)) * frequency; + const rotated: f32 = if (d < 64) x * @cos(angle) - other * @sin(angle) else other * @sin(angle) + x * @cos(angle); + return bf(rotated); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: host.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [6]c.Shape = undefined, + served_len: usize = 0, + f: [8][]f32 = @splat(&.{}), + phi: []u16 = &.{}, + refs: [8]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + score_scratch: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: host.Kind) !Probe { + return initSource(a, device, queue, kind, sources.inkling2_dspark); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: host.Kind, text: []const u8) !Probe { + var self: Probe = .{ .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .pipes = try host.Pipelines.loadSource(device, text) }; + switch (kind) { + .init_rows => self.setServed(&.{.{ .rows = 8, .n = H, .k = 0 }}), + .fuse_taps => self.setServed(&.{ .{ .rows = 5, .n = H, .k = 0 }, .{ .rows = 1, .n = H, .k = 0 }, .{ .rows = 3, .n = H, .k = 0 }, .{ .rows = 7, .n = H, .k = 0 } }), + .block_qkv => self.setServed(&.{ .{ .rows = 8, .n = Q, .k = 17 }, .{ .rows = 8, .n = Q, .k = 67 } }), + .context_kv => self.setServed(&.{ .{ .rows = 5, .n = KV, .k = 17 }, .{ .rows = 1, .n = KV, .k = 31 }, .{ .rows = 3, .n = KV, .k = 47 }, .{ .rows = 8, .n = KV, .k = 67 } }), + .attention => self.setServed(&.{ + .{ .rows = 8, .n = 0, .k = 0 }, + .{ .rows = 8, .n = 1, .k = 0 }, + .{ .rows = 8, .n = 3, .k = 0 }, + .{ .rows = 8, .n = 3, .k = 5 }, + .{ .rows = 8, .n = 1025, .k = 1 }, + .{ .rows = 8, .n = 1025, .k = 7 }, + }), + .residual_norm => self.setServed(&.{ .{ .rows = 8, .n = H, .k = 1 }, .{ .rows = 8, .n = H, .k = 0 } }), + .swiglu => self.setServed(&.{.{ .rows = 8, .n = INTER, .k = 0 }}), + .kappa => self.setServed(&.{ .{ .rows = 5, .n = RNN, .k = 0 }, .{ .rows = 1, .n = RNN, .k = 0 }, .{ .rows = 3, .n = RNN, .k = 0 }, .{ .rows = 7, .n = RNN, .k = 0 } }), + .recurrent => self.setServed(&.{.{ .rows = 8, .n = RNN, .k = 0 }}), + .base => self.setServed(&.{ .{ .rows = 5, .n = 5, .k = 0 }, .{ .rows = 1, .n = 1, .k = 0 }, .{ .rows = 3, .n = 17, .k = 0 }, .{ .rows = 7, .n = 129, .k = 0 } }), + .logits => self.setServed(&.{.{ .rows = 8, .n = host.vocab, .k = 0 }}), + } + return self; + } + fn setServed(self: *Probe, shapes: []const c.Shape) void { + @memcpy(self.served[0..shapes.len], shapes); + self.served_len = shapes.len; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + + const vt = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = &vt, .spec = .{ + .name = self.kind.label(), + .accum = .none, + .depth = depth, + .ops = 0, + .mids = 0, + .out = if (self.kind == .kappa) .f32 else .bf16, + .served = self.served[0..self.served_len], + .sums = .{ .f16 = 0, .bf16 = 0, .why = "explicit serial FP32 reference and required BF16 nodes are checked directly" }, + } }; + } + pub fn count(self: *Probe) usize { + return switch (self.kind) { + .init_rows => 8 * H, + .fuse_taps => (4 * self.shape.rows + 1) * H, + .block_qkv => 8 * (Q + 2 * KV), + .context_kv => 2 * self.shape.rows * KV, + .attention => 8 * Q, + .residual_norm => 2 * 8 * H, + .swiglu => 8 * INTER, + .kappa => self.shape.rows * RNN, + .recurrent => RNN + 2 * RANK, + .base => self.shape.rows * self.shape.n, + .logits => host.vocab, + }; + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = rng.float(f32) * 0.5 - 0.25; + return values; + } + fn input(self: *Probe, values: []const f32, is_bf: bool) !rig_.Ref { + if (!is_bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + fn output(self: *Probe, slot: usize, elements: usize, elem: c.Elem) !void { + self.outs[slot] = try self.rig.output(elements * c.size(elem)); + } + fn first(self: *const Probe) usize { + const from = self.shape.k / 2; + const local = self.shape.k % 2 != 0; + return @max(from, if (local and self.shape.n > 1024) self.shape.n - 1024 else 0); + } + + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + var admitted = false; + for (self.served[0..self.served_len]) |served| if (std.meta.eql(shape, served)) { + admitted = true; + break; + }; + if (!admitted) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + self.phi = &.{}; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const nf = fill == .nonfinite; + const rows = shape.rows; + switch (self.kind) { + .init_rows => { + self.f[0] = try self.floats(H, rng); + self.f[1] = try self.floats(H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + rounded(self.f[0]); + rounded(self.f[1]); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + try self.output(0, 8 * H, .bf16); + }, + .fuse_taps => { + self.f[0] = try self.floats(rows * 4 * H, rng); + self.f[1] = try self.floats(16, rng); + self.f[2] = try self.floats(4 * H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + @memcpy(self.f[1][0..4], &[_]f32{ 0, 0.5, -0.25, 2 }); + for (self.f[0][0 .. 4 * H]) |*v| v.* *= 400; + rounded(self.f[0]); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 4 * rows * H, .bf16); + try self.output(1, H, .bf16); + }, + .block_qkv => { + const sizes = [_]usize{ 8 * Q, 8 * KV, 8 * KV, 128, 128 }; + for (sizes, 0..) |n, j| { + self.f[j] = try self.floats(n, rng); + rounded(self.f[j]); + self.refs[j] = try self.input(self.f[j], true); + } + if (nf) { + self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + } + try self.output(0, 8 * Q, .bf16); + try self.output(1, 8 * KV, .bf16); + try self.output(2, 8 * KV, .bf16); + }, + .context_kv => { + self.f[0] = try self.floats(rows * KV, rng); + self.f[1] = try self.floats(rows * KV, rng); + self.f[2] = try self.floats(128, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, rows * KV, .bf16); + try self.output(1, rows * KV, .bf16); + }, + .attention => { + const ring = @max(shape.n, 1); + const sizes = [_]usize{ 8 * Q, 8 * KV, 8 * KV, ring * KV, ring * KV }; + for (sizes, 0..) |n, j| { + self.f[j] = try self.floats(n, rng); + rounded(self.f[j]); + self.refs[j] = try self.input(self.f[j], true); + } + if (nf) { + self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + } + self.score_scratch = try self.rig.scratch(8 * 24 * (shape.n - self.first() + 8) * 4); + self.refs[5] = self.score_scratch; + try self.output(0, 8 * Q, .bf16); + }, + .residual_norm => { + self.f[0] = try self.floats(8 * H, rng); + self.f[1] = try self.floats(8 * H, rng); + self.f[2] = try self.floats(H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + for (0..3) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 8 * H, .bf16); + try self.output(1, 8 * H, .bf16); + }, + .swiglu => { + self.f[0] = try self.floats(8 * INTER, rng); + self.f[1] = try self.floats(8 * INTER, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..2]) |values| rounded(values); + for (0..2) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, 8 * INTER, .bf16); + }, + .kappa => { + self.f[0] = try self.floats(rows * H, rng); + self.f[1] = try self.floats(H, rng); + self.f[2] = try self.floats(RNN * 5120, rng); + self.f[3] = try self.floats(RNN, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..4]) |values| rounded(values); + for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + try self.output(0, rows * RNN, .f32); + }, + .recurrent => { + self.f[0] = try self.floats(RANK, rng); + self.f[1] = try self.floats(RNN, rng); + self.f[2] = try self.floats(RNN * 5120, rng); + self.f[3] = try self.floats(2 * RANK, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..4]) |values| rounded(values); + @memset(self.f[0], 99.5); + self.f[1][0] = c.fromBf16(c.toBf16(0.6)); + self.f[1][RANK] = c.fromBf16(c.toBf16(0.8)); + self.f[1][2 * RANK] = c.fromBf16(c.toBf16(0.3)); + for ([_]usize{ 0, RANK, 2 * RANK }) |channel| @memset(self.f[2][channel * 5120 ..][0..512], 0); + if (nf) self.f[0][0] = std.math.nan(f32); + // kappa arrives as the kappa kernel wrote it, in FP32; the other three are BF16. + for (0..4) |j| self.refs[j] = try self.input(self.f[j], j != 1); + try self.output(0, RNN, .bf16); + try self.output(1, RANK, .bf16); + try self.output(2, RANK, .bf16); + }, + .logits => { + self.f[0] = try self.floats(host.vocab, rng); + self.f[1] = try self.floats(host.vocab, rng); + self.f[2] = try self.floats(RANK, rng); + for (self.f[0]) |*v| v.* = rng.float(f32) * 120 - 60; + if (nf) self.f[0][0] = std.math.nan(f32); + for (self.f[0..3]) |values| rounded(values); + self.f[0][0] = 40; + self.f[0][1] = 1000; + self.f[1][0] = 0.125; + if (nf) self.f[0][0] = std.math.nan(f32); + self.f[2][0] = c.fromBf16(c.toBf16(0.0001)); + self.phi = try self.arena.allocator().alloc(u16, host.vocab * RANK); + for (self.phi) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + @memset(self.phi[0..RANK], 0); + self.phi[0] = c.toBf16(1); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(self.phi)); + self.refs[2] = try self.input(self.f[1], true); + self.refs[3] = try self.input(self.f[2], true); + try self.output(0, host.vocab, .bf16); + }, + .base => { + self.f[0] = try self.floats(shape.n * H, rng); + self.f[1] = try self.floats(rows * H, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + rounded(self.f[0]); + rounded(self.f[1]); + if (!nf) { + @memset(self.f[0][0..H], 1); + @memset(self.f[1][0..H], 1); + } + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + try self.output(0, rows * shape.n, .bf16); + }, + } + return true; + } + + fn hostRef(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const R = self.refs; + const O = self.outs; + const p = &self.pipes; + switch (self.kind) { + .init_rows => host.initializeRows(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0])), + .fuse_taps => host.fuseTaps(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), @intCast(self.shape.rows)), + .block_qkv => host.blockQkv(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(R[4]), hostRef(O[0]), hostRef(O[1]), hostRef(O[2]), @intCast(self.shape.k)), + .context_kv => host.commitContext(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), @intCast(self.shape.k), @intCast(self.shape.rows), @intCast(self.shape.rows)), + .attention => host.attend(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(R[4]), hostRef(self.score_scratch), hostRef(O[0]), @intCast(self.shape.n), @intCast(@max(self.shape.n, 1)), self.shape.k % 2 != 0, @intCast(self.shape.k / 2)), + .residual_norm => host.residualNorm(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(O[0]), hostRef(O[1]), 8, self.shape.k != 0), + .swiglu => host.swiglu(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0]), 8 * INTER), + .kappa => host.kappa(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0]), @intCast(self.shape.rows)), + .recurrent => host.recurrentStep(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0]), hostRef(O[1]), hostRef(O[2]), 1), + .base => host.base(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(O[0]), @intCast(self.shape.rows), @intCast(self.shape.n)), + .logits => host.finalLogits(p, e, hostRef(R[0]), hostRef(R[1]), hostRef(R[2]), hostRef(R[3]), hostRef(O[0])), + } + try self.rig.finish(pass); + } + + fn fusionReference(self: *Probe, want: []f64) void { + const rows = self.shape.rows; + for (0..4) |fusion| { + var scores: [4]f32 = undefined; + var peak: f32 = -std.math.inf(f32); + for (0..4) |j| { + scores[j] = self.f[1][fusion * 4 + j]; + peak = @max(peak, scores[j]); + } + var den: f32 = 0; + for (0..4) |j| { + scores[j] = @exp(scores[j] - peak); + den += scores[j]; + } + var alpha: [4]f32 = undefined; + for (0..4) |j| alpha[j] = @floatCast(bf(scores[j] / den)); + for (0..rows) |row| { + var square: f32 = 0; + for (0..H) |d| { + var mixed: f32 = 0; + for (0..4) |j| mixed += alpha[j] * self.f[0][(row * 4 + j) * H + d]; + square += mixed * mixed; + } + const scale: f32 = 1.0 / @sqrt(square / H + 1e-6); + for (0..H) |d| { + var mixed: f32 = 0; + for (0..4) |j| mixed += alpha[j] * self.f[0][(row * 4 + j) * H + d]; + const out = bf(mixed * scale * self.f[2][fusion * H + d]); + want[(fusion * rows + row) * H + d] = out; + if (fusion == 3 and row + 1 == rows) want[4 * rows * H + d] = out; + } + } + } + } + fn qkvReference(self: *Probe, want: []f64) void { + for (0..8) |row| for (0..24) |h| for (0..128) |d| { + const at = row * Q + h * 128 + d; + const other_at = row * Q + h * 128 + (if (d < 64) d + 64 else d - 64); + const scale = rms(self.f[0], row * Q + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[0][at] * scale * self.f[3][d])); + const other: f32 = @floatCast(bf(self.f[0][other_at] * scale * self.f[3][if (d < 64) d + 64 else d - 64])); + want[at] = rope(d, self.shape.k + row, x, other); + }; + const offset = 8 * Q; + for (0..8) |row| for (0..8) |h| for (0..128) |d| { + const at = row * KV + h * 128 + d; + const other_at = row * KV + h * 128 + (if (d < 64) d + 64 else d - 64); + const scale = rms(self.f[1], row * KV + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[1][at] * scale * self.f[4][d])); + const other: f32 = @floatCast(bf(self.f[1][other_at] * scale * self.f[4][if (d < 64) d + 64 else d - 64])); + want[offset + at] = rope(d, self.shape.k + row, x, other); + want[offset + 8 * KV + at] = self.f[2][at]; + }; + } + fn contextReference(self: *Probe, want: []f64) void { + const rows = self.shape.rows; + for (0..rows) |row| for (0..8) |h| for (0..128) |d| { + const src = row * KV + h * 128 + d; + const dst = ((self.shape.k + row) % rows) * KV + h * 128 + d; + const partner = if (d < 64) d + 64 else d - 64; + const other_src = row * KV + h * 128 + partner; + const scale = rms(self.f[0], row * KV + h * 128, 128); + const x: f32 = @floatCast(bf(self.f[0][src] * scale * self.f[2][d])); + const other: f32 = @floatCast(bf(self.f[0][other_src] * scale * self.f[2][partner])); + want[dst] = rope(d, self.shape.k + row, x, other); + want[rows * KV + dst] = self.f[1][src]; + }; + } + fn attentionReference(self: *Probe, want: []f64) !void { + const committed = self.shape.n; + const first_kept = self.first(); + const retained = committed - first_kept; + const score_count = retained + 8; + const ring = @max(committed, 1); + const scores = try self.a.alloc(f32, score_count); + defer self.a.free(scores); + for (0..8) |row| for (0..24) |h| { + const kv = h / 3; + const q_at = row * Q + h * 128; + var peak: f32 = -std.math.inf(f32); + for (0..score_count) |j| { + var dot: f32 = 0; + const k_at = if (j < retained) ((first_kept + j) % ring) * KV + kv * 128 else (j - retained) * KV + kv * 128; + const keys = if (j < retained) self.f[3] else self.f[1]; + for (0..128) |d| dot += self.f[0][q_at + d] * keys[k_at + d]; + scores[j] = dot * @as(f32, 0x1.6a09e6p-4); + peak = @max(peak, scores[j]); + } + var den: f32 = 0; + for (scores) |s| den += @exp(s - peak); + for (0..128) |d| { + var sum: f32 = 0; + for (0..score_count) |j| { + const v_at = if (j < retained) ((first_kept + j) % ring) * KV + kv * 128 + d else (j - retained) * KV + kv * 128 + d; + const values = if (j < retained) self.f[4] else self.f[2]; + sum += (@exp(scores[j] - peak) / den) * values[v_at]; + } + want[q_at + d] = bf(sum); + } + }; + } + fn recurrentReference(self: *Probe, want: []f64) void { + for (0..RANK) |i| { + var z: [3]f32 = undefined; + for (0..3) |part| { + const channel = part * RANK + i; + var sum: f32 = 0; + for (0..RANK) |d| sum += self.f[0][d] * self.f[2][channel * 5120 + d]; + for (0..RANK) |d| sum += self.f[3][RANK + d] * self.f[2][channel * 5120 + 256 + d]; + sum += self.f[1][channel]; + z[part] = @floatCast(bf(sum)); + want[channel] = z[part]; + } + const gamma: f32 = @floatCast(bf(1.0 / (1.0 + @exp(-z[0])))); + const candidate: f32 = @floatCast(bf(std.math.tanh(z[1]))); + const keep: f32 = @floatCast(bf(1.0 - gamma)); + const left: f32 = @floatCast(bf(gamma * self.f[0][i])); + const right: f32 = @floatCast(bf(keep * candidate)); + want[RNN + i] = bf(left + right); + want[RNN + RANK + i] = bf(std.math.tanh(z[2])); + } + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + switch (self.kind) { + .init_rows => for (0..8) |row| { + for (0..H) |d| want[row * H + d] = self.f[if (row == 0) 0 else 1][d]; + }, + .fuse_taps => self.fusionReference(want), + .block_qkv => self.qkvReference(want), + .context_kv => self.contextReference(want), + .attention => try self.attentionReference(want), + .residual_norm => for (0..8) |row| { + var square: f32 = 0; + for (0..H) |d| { + const at = row * H + d; + const sigma: f32 = if (self.shape.k != 0) self.f[0][at] else self.f[0][at] + self.f[1][at]; + square += sigma * sigma; + } + const scale: f32 = 1.0 / @sqrt(square / H + 1e-6); + for (0..H) |d| { + const at = row * H + d; + const sigma: f32 = if (self.shape.k != 0) self.f[0][at] else self.f[0][at] + self.f[1][at]; + want[at] = bf(sigma); + want[8 * H + at] = bf(sigma * scale * self.f[2][d]); + } + }, + .swiglu => for (want, 0..) |*w, i| { + const gate = self.f[0][i]; + w.* = bf((gate / (1.0 + @exp(-gate))) * self.f[1][i]); + }, + .kappa => for (0..self.shape.rows) |row| for (0..RNN) |channel| { + var sum: f32 = 0; + for (0..H) |d| sum += self.f[0][row * H + d] * self.f[2][channel * 5120 + 512 + d]; + for (0..H) |d| sum += self.f[1][d] * self.f[2][channel * 5120 + 2816 + d]; + sum += self.f[3][channel]; + want[row * RNN + channel] = sum; + }, + .recurrent => self.recurrentReference(want), + .base => for (0..self.shape.rows) |row| for (0..self.shape.n) |id| { + var dot: f32 = 0; + for (0..H) |d| dot += self.f[0][id * H + d] * self.f[1][row * H + d]; + want[row * self.shape.n + id] = bf(dot); + }, + .logits => for (0..host.vocab) |i| { + var dot: f32 = 0; + for (0..RANK) |d| dot += c.fromBf16(self.phi[i * RANK + d]) * self.f[2][d]; + const bias: f32 = @floatCast(bf(self.f[1][i] + dot)); + const logit: f32 = @floatCast(bf(self.f[0][i] + bias)); + want[i] = bf(30.0 * std.math.tanh(logit / 30.0)); + }, + } + for (mag, want) |*m, w| m.* = 1 + @abs(w); + } + + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + if (gate != .shapes and gate != .nonfinite) return "numeric hooks must be used"; + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + const bytes = try self.rig.outputBytes(); + for (want, 0..) |w, i| { + if (self.kind == .kappa) { + const got = c.read(.f32, bytes, i); + if (gate == .nonfinite and c.classOf(got) != c.classOf(w)) return "kappa floating-point class differs"; + if (gate == .shapes and std.math.isFinite(w) and @abs(got - w) > 2e-5 * @max(1, @abs(w))) return "FP32 kappa dot or column split differs"; + } else { + const bits = std.mem.readInt(u16, bytes[2 * i ..][0..2], .little); + const expected = c.toBf16(@floatCast(w)); + if (std.math.isNan(w)) { + if (!std.math.isNan(c.fromBf16(bits))) return "BF16 NaN was not propagated"; + } else if (bits != expected) { + const relative: f64 = switch (self.kind) { + .fuse_taps, .block_qkv, .context_kv, .swiglu, .logits, .base => 0.02, + .attention => 0.03, + else => 0, + }; + const got = c.fromBf16(bits); + if (@abs(@as(f64, got) - w) > @max(1e-5, relative * @abs(w))) return "BF16 endpoint differs from the explicit FP32/FP64 reference"; + } + } + } + if (self.kind == .logits and gate == .shapes) { + if (!(want[1] <= 30 and want[1] > 29.9)) return "the planted large logit does not prove softcap saturation"; + } + if (self.kind == .base and gate == .shapes and self.f[0][0] == 1) { + if (want[0] != 2304) return "raw base projection was softened instead of rounded once"; + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: host.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(@fromBackingInt(@intCast(@backingInt(kind)))) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.inkling2_dspark, @fromBackingInt(@intCast(@backingInt(kind)))); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else probe.* = try Probe.init(s.a, s.device, s.queue, kind); + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(host.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_dspark_chain.zig b/zig/tests/contract/metal_inkling2_dspark_chain.zig new file mode 100644 index 00000000000..e3b15184e44 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_chain.zig @@ -0,0 +1,253 @@ +//! Mini DSpark's greedy chain: the step is the recurrent kernel on a token read from a buffer, the pick a first max. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_dspark_host; +const controls = @import("metal_inkling2_dspark_chain_controls.zig"); +const sources = @import("inkling2_metal"); + +const RANK = host.rank; +const RNN = host.rnn_width; + +fn noSums(_: c.Shape) usize { + return 1; +} +fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; +} + +/// The chain step against the registered recurrent kernel on the same inputs: every byte of its three outputs. +pub const Step = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + chain: host.Chain, + pipes: host.Pipelines, + control: ?g.Gate, + refs: [5]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + twin: [3]rig_.Ref = undefined, + msg: [160]u8 = undefined, + + const name = "metal inkling2 dspark chain_step tf_ink2_dspark_chain_step"; + /// The slot of the held tokens the probe's step reads, and the token there; the slot after holds another. + const step = 3; + const token = 1; + const sizes = [3]usize{ RNN * 2, RANK * 2, RANK * 2 }; + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Step { + const text = try controls.apply(a, if (control) .step_token else .none); + defer a.free(text); + var chain = try host.Chain.load(device, text); + errdefer chain.deinit(); + return .{ .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .chain = chain, .pipes = try host.Pipelines.load(device), .control = if (control) .shapes else null }; + } + pub fn deinit(t: *Step) void { + t.rig.deinit(); + t.arena.deinit(); + t.pipes.deinit(); + t.chain.deinit(); + } + pub fn kernel(t: *Step) g.Kernel { + return .{ .ctx = t, .vt = &vt, .control = t.control, .spec = .{ + .name = if (t.control != null) controls.Mutation.step_token.name() else name, + .accum = .none, + .depth = noSums, + .out = .bf16, + .nan = .{ .stated = "its bytes are tf_ink2_dspark_recurrent's on the token the buffer holds, whatever their classes" }, + .served = &.{.{ .rows = 8, .n = RNN, .k = 0 }}, + } }; + } + const vt = g.hooks(Step); + + fn bf16(t: *Step, n: usize, rng: std.Random) ![]u16 { + const bits = try t.arena.allocator().alloc(u16, n); + for (bits) |*b| b.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + return bits; + } + + pub fn prepare(t: *Step, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows != 8 or shape.n != RNN) return false; + t.rig.reset(); + _ = t.arena.reset(.retain_capacity); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const state = try t.bf16(RANK, rng); + if (fill == .nonfinite) state[0] = c.toBf16(std.math.nan(f32)); + const kappa = try t.arena.allocator().alloc(f32, RNN); + for (kappa) |*v| v.* = rng.float(f32) * 0.5 - 0.25; + // The Markov rows of tokens 0 and 1 differ, so the token read decides the outputs. + const held = [8]u32{ 0, 0, 0, token, 0, 0, 0, 0 }; + t.refs[0] = try t.rig.input(std.mem.sliceAsBytes(state)); + t.refs[1] = try t.rig.input(std.mem.sliceAsBytes(kappa)); + t.refs[2] = try t.rig.input(std.mem.sliceAsBytes(try t.bf16(RNN * 5120, rng))); + t.refs[3] = try t.rig.input(std.mem.sliceAsBytes(try t.bf16(2 * RANK, rng))); + t.refs[4] = try t.rig.input(std.mem.sliceAsBytes(&held)); + for (&t.outs, &t.twin, sizes) |*out, *twin, bytes| { + out.* = try t.rig.output(bytes); + twin.* = try t.rig.scratch(bytes); + } + return true; + } + + pub fn run(t: *Step) !void { + const pass = t.rig.begin(); + host.chainStep(&t.chain, pass.e, hr(t.refs[0]), hr(t.refs[1]), hr(t.refs[2]), hr(t.refs[3]), hr(t.outs[0]), hr(t.outs[1]), hr(t.outs[2]), hr(t.refs[4]), step); + try t.rig.finish(pass); + } + + pub fn count(_: *Step) usize { + return RNN + 2 * RANK; + } + pub fn reference(_: *Step, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + pub fn check(t: *Step, _: g.Gate) !?[]const u8 { + const pass = t.rig.begin(); + host.recurrentStep(&t.pipes, pass.e, hr(t.refs[0]), hr(t.refs[1]), hr(t.refs[2]), hr(t.refs[3]), hr(t.twin[0]), hr(t.twin[1]), hr(t.twin[2]), token); + try t.rig.finish(pass); + for (t.outs, t.twin, sizes, 0..) |out, twin, bytes, i| { + const got = t.rig.bytes(out, bytes); + const want = t.rig.bytes(twin, bytes); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&t.msg, "output {d} differs from the recurrent kernel's from byte {d}", .{ i, at }); + } + return null; + } +}; + +/// The pick against a scan of the same logits: the first of equal maxima, a NaN only at id 0, no other slot written. +pub const Pick = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + chain: host.Chain, + control: ?g.Gate, + logits: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + msg: [160]u8 = undefined, + + const name = "metal inkling2 dspark chain_pick tf_ink2_dspark_chain_pick"; + const step = 2; + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Pick { + const text = try controls.apply(a, if (control) .pick_tie else .none); + defer a.free(text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .chain = try host.Chain.load(device, text), .control = if (control) .shapes else null }; + } + pub fn deinit(t: *Pick) void { + t.a.free(t.logits); + t.rig.deinit(); + t.chain.deinit(); + } + pub fn kernel(t: *Pick) g.Kernel { + return .{ + .ctx = t, + .vt = &vt, + .control = t.control, + .spec = .{ + .name = if (t.control != null) controls.Mutation.pick_tie.name() else name, + .accum = .none, + .depth = noSums, + .out = .raw, + .nan = .{ .stated = "a NaN is never the pick unless logit 0 is one, and then the pick is id 0; else ties go to the lower id" }, + // k 1 is the same row with a NaN at id 0, where the rule picks id 0. + .served = &.{ .{ .rows = 1, .n = host.vocab, .k = 0 }, .{ .rows = 1, .n = host.vocab, .k = 1 } }, + }, + }; + } + const vt = g.hooks(Pick); + + pub fn prepare(t: *Pick, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != host.vocab or shape.k > 1) return false; + t.rig.reset(); + t.a.free(t.logits); + t.logits = try t.a.alloc(u16, host.vocab); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // Few distinct values, so the greatest is tied many times within a simdgroup and across them. + for (t.logits) |*v| v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 64))) / 4 - 8); + t.logits[host.vocab - 1] = t.logits[host.vocab - 2]; + if (fill == .nonfinite) { + // Later NaNs lose to an infinity near the end of the row. + t.logits[host.vocab / 3] = c.toBf16(std.math.nan(f32)); + t.logits[host.vocab / 2] = c.toBf16(-std.math.inf(f32)); + t.logits[host.vocab - 1] = c.toBf16(std.math.nan(f32)); + t.logits[host.vocab - 7] = c.toBf16(std.math.inf(f32)); + } + if (shape.k == 1) t.logits[0] = c.toBf16(std.math.nan(f32)); + t.in = try t.rig.input(std.mem.sliceAsBytes(t.logits)); + t.out = try t.rig.output(8 * @sizeOf(u32)); + return true; + } + + pub fn run(t: *Pick) !void { + const pass = t.rig.begin(); + host.chainPick(&t.chain, pass.e, hr(t.in), hr(t.out), step); + try t.rig.finish(pass); + } + + pub fn count(_: *Pick) usize { + return 8 * @sizeOf(u32); + } + pub fn reference(_: *Pick, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + pub fn check(t: *Pick, _: g.Gate) !?[]const u8 { + var at: u32 = 0; + if (!std.math.isNan(c.fromBf16(t.logits[0]))) { + var best = -std.math.inf(f32); + at = std.math.maxInt(u32); + for (t.logits, 0..) |bits, i| { + const v = c.fromBf16(bits); + if (!std.math.isNan(v) and (v > best or at == std.math.maxInt(u32))) { + best = v; + at = @intCast(i); + } + } + } + const held = std.mem.bytesAsSlice(u32, t.rig.bytes(t.out, 8 * @sizeOf(u32))); + for (held, 0..) |got, slot| { + const want: u32 = if (slot == step + 1) at else 0xffff_ffff; + if (got != want) return try std.fmt.bufPrint(&t.msg, "held[{d}] is {d} where the rule leaves {d}", .{ slot, got, want }); + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + steps: [2]Step = undefined, + picks: [2]Pick = undefined, + step_count: usize = 0, + pick_count: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.steps[0..s.step_count]) |*t| t.deinit(); + for (s.picks[0..s.pick_count]) |*t| t.deinit(); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]bool{ false, true }) |control| { + const step_label = if (control) controls.Mutation.step_token.name() else Step.name; + if (only == null or std.mem.indexOf(u8, step_label, only.?) != null) { + s.steps[s.step_count] = try Step.init(s.a, s.device, s.queue, control); + s.step_count += 1; + try s.kernels.append(s.a, s.steps[s.step_count - 1].kernel()); + } + const pick_label = if (control) controls.Mutation.pick_tie.name() else Pick.name; + if (only == null or std.mem.indexOf(u8, pick_label, only.?) != null) { + s.picks[s.pick_count] = try Pick.init(s.a, s.device, s.queue, control); + s.pick_count += 1; + try s.kernels.append(s.a, s.picks[s.pick_count - 1].kernel()); + } + } + } +}; diff --git a/zig/tests/contract/metal_inkling2_dspark_chain_controls.zig b/zig/tests/contract/metal_inkling2_dspark_chain_controls.zig new file mode 100644 index 00000000000..f8f8f272634 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_chain_controls.zig @@ -0,0 +1,52 @@ +//! Count-checked mutations of Mini DSpark's two chain kernels: each has a genuine control. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + step_token, + pick_tie, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .step_token => "control: metal inkling2 dspark chain_step tf_ink2_dspark_chain_step next token", + .pick_tie => "control: metal inkling2 dspark chain_pick tf_ink2_dspark_chain_pick later tie", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .step_token => .{ .from = "lambda, held[a.token], i);", .to = "lambda, held[a.token + 1u], i);" }, + .pick_tie => .{ .from = "if (ov > best || (ov == best && oi < at)) { best = ov; at = oi; }", .to = "if (ov > best || (ov == best && oi > at)) { best = ov; at = oi; }" }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.inkling2_dspark); + const change = m.edit(); + if (std.mem.count(u8, src.inkling2_dspark, change.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.inkling2_dspark, change.from, change.to); +} + +test "each chain control edits exactly its planted line" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 dspark chain_")); + } + inline for ([_][]const u8{ "tf_ink2_dspark_chain_step", "tf_ink2_dspark_chain_pick" }) |name| + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.inkling2_dspark, name ++ "(")); +} diff --git a/zig/tests/contract/metal_inkling2_dspark_controls.zig b/zig/tests/contract/metal_inkling2_dspark_controls.zig new file mode 100644 index 00000000000..5a1d605fbd8 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_controls.zig @@ -0,0 +1,56 @@ +//! One host-checkable arithmetic mutation for every Mini DSpark Metal kernel. +const std = @import("std"); + +pub const Kind = enum { init_rows, fuse_taps, block_qkv, context_kv, attention, residual_norm, swiglu, kappa, recurrent, base, logits }; +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: Kind) Edit { + return switch (kind) { + .init_rows => .{ .from = "rows[row * DSP_H + d] = src[d];", .to = "rows[row * DSP_H + d] = mask[d];" }, + .fuse_taps => .{ .from = "alpha[j] = float(bfloat(scores[j] / sum));", .to = "alpha[j] = scores[j] / sum;" }, + .block_qkv => .{ .from = "const float rotated = d < 64 ? x * cs - other * sn : other * sn + x * cs;", .to = "const float rotated = d < 64 ? x * cs - other * sn : x * sn + other * cs;" }, + .context_kv => .{ .from = "keys[at] = bfloat(d < 64 ? x * cs - other * sn : other * sn + x * cs);", .to = "keys[at] = bfloat(d < 64 ? x * cs - other * sn : x * sn + other * cs);" }, + .attention => .{ .from = "const uint first = max(a.from, a.local && a.committed > 1024 ? a.committed - 1024 : 0);", .to = "const uint first = a.from;" }, + .residual_norm => .{ .from = "normalized[at] = bfloat(sigma * scale * float(weight[d]));", .to = "normalized[at] = bfloat(float(new_residual[at]) * scale * float(weight[d]));" }, + .swiglu => .{ .from = "out[i] = bfloat((gate / (1.0f + exp(-gate))) * float(u[i]));", .to = "out[i] = bfloat(gate * float(u[i]));" }, + .kappa => .{ .from = "sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + 512 + d]);", .to = "sum += float(y[row * DSP_H + d]) * float(weight[channel * 5120 + d]);" }, + .recurrent => .{ .from = "const bfloat left = bfloat(float(gamma) * float(state[i]));", .to = "const float left = float(gamma) * float(state[i]);" }, + .base => .{ .from = "out[size_t(row) * a.vocab + id] = bfloat(sum);", .to = "out[size_t(row) * a.vocab + id] = bfloat(30.0f * tanh(sum / 30.0f));" }, + .logits => .{ .from = "const bfloat bias = bfloat(float(beta[i]) + dot);", .to = "const float bias = float(beta[i]) + dot;" }, + }; +} + +pub fn name(kind: Kind) []const u8 { + return switch (kind) { + inline else => |k| "control: metal inkling2 dspark " ++ @tagName(k), + }; +} +pub fn source(a: std.mem.Allocator, production: []const u8, kind: Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +test "every DSpark control applies once and only mutates its arithmetic anchor" { + const production = @import("inkling2_metal").inkling2_dspark; + const a = std.testing.allocator; + for (std.enums.values(Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "repeated DSpark control anchors are refused" { + const production = @import("inkling2_metal").inkling2_dspark; + const a = std.testing.allocator; + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + for (std.enums.values(Kind)) |kind| try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); +} diff --git a/zig/tests/contract/metal_inkling2_dspark_units.zig b/zig/tests/contract/metal_inkling2_dspark_units.zig new file mode 100644 index 00000000000..2453f7594c0 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_units.zig @@ -0,0 +1,321 @@ +//! Mini DSpark's tensor-unit block attention against float64: the chunk partials with their fold, and the fold alone. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_dspark_host; +const controls = @import("metal_inkling2_dspark_units_controls.zig"); + +const Q = host.query_width; +const KV = host.kv_width; +const D = 128; +const pairs = 8 * 24; +const local_ring = 1152; +const scale: f64 = @as(f32, 0x1.6a09e6p-4); +const log2e: f64 = @as(f32, 1.4426950408889634); + +pub const Kind = enum { attend, merge }; + +pub fn label(kind: Kind) []const u8 { + return switch (kind) { + .attend => "metal inkling2 dspark_units tf_ink2_dspark_attn_units", + .merge => "metal inkling2 dspark_units tf_ink2_dspark_attn_merge", + }; +} + +fn noSums(_: c.Shape) usize { + return 1; +} +fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; +} +fn bf(v: f32) f32 { + return c.fromBf16(c.toBf16(v)); +} + +// n is the committed length and k twice the first kept position, plus one on a sliding layer. +const attend_shapes = [_]c.Shape{ + .{ .rows = 8, .n = 0, .k = 0 }, + .{ .rows = 8, .n = 1, .k = 0 }, + .{ .rows = 8, .n = 3, .k = 5 }, + .{ .rows = 8, .n = 300, .k = 140 }, + .{ .rows = 8, .n = 700, .k = 0 }, + .{ .rows = 8, .n = 1025, .k = 1 }, + .{ .rows = 8, .n = 1025, .k = 7 }, + .{ .rows = 8, .n = 5000, .k = 1 }, +}; +// n is the chunks folded after the block's own keys. +const merge_shapes = [_]c.Shape{ .{ .rows = 8, .n = 0, .k = 0 }, .{ .rows = 8, .n = 1, .k = 0 }, .{ .rows = 8, .n = 5, .k = 0 } }; + +fn shapes(kind: Kind) []const c.Shape { + return if (kind == .attend) &attend_shapes else &merge_shapes; +} + +/// One entry: its launch on planted inputs, then every output against the float64 sum and its stated bound. +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + units: host.Units, + kind: Kind, + control: ?g.Gate, + shape: c.Shape = undefined, + nonfinite: bool = false, + f: [7][]f32 = @splat(&.{}), + refs: [6]rig_.Ref = undefined, + out: rig_.Ref = undefined, + msg: [200]u8 = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (control) controls.of(kind) else .none); + defer a.free(text); + return .{ .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .units = try host.Units.load(device, text), .kind = kind, .control = if (control) .shapes else null }; + } + pub fn deinit(t: *Probe) void { + t.rig.deinit(); + t.arena.deinit(); + t.units.deinit(); + } + pub fn kernel(t: *Probe) g.Kernel { + return .{ .ctx = t, .vt = &vt, .control = t.control, .spec = .{ + .name = if (t.control != null) controls.of(t.kind).name() else label(t.kind), + .accum = .none, + .depth = noSums, + .out = .bf16, + .nan = .{ .stated = "a NaN in a query makes its (row, head)'s 128 outputs NaN and no other pair's" }, + .served = shapes(t.kind), + } }; + } + const vt = g.hooks(Probe); + + fn local(t: *const Probe) bool { + return t.shape.k % 2 != 0; + } + fn ring(t: *const Probe) usize { + return if (t.local()) local_ring else std.mem.alignForward(usize, @max(t.shape.n, 1), 128); + } + fn span(t: *const Probe) struct { first: usize, chunks: usize } { + const s = host.unitsSpan(@intCast(t.shape.n), t.local(), @intCast(t.shape.k / 2)); + return .{ .first = s.first, .chunks = s.chunks }; + } + + fn floats(t: *Probe, n: usize, rng: std.Random, width: f32) ![]f32 { + const values = try t.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = bf((rng.float(f32) - 0.5) * width); + return values; + } + fn input(t: *Probe, values: []const f32) !rig_.Ref { + const bits = try t.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return t.rig.input(std.mem.sliceAsBytes(bits)); + } + /// The direction every query leans to: a key along it weighs in every pair's sum. + fn lean(d: usize) f32 { + return if ((d * 2654435761) >> 7 & 1 == 0) 1 else -1; + } + fn plant(row: []f32, weight: f32, rng: std.Random) void { + for (row, 0..) |*v, d| v.* = bf(weight * lean(d % D) + (rng.float(f32) - 0.5) * 0.02); + } + + pub fn prepare(t: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + var admitted = false; + for (shapes(t.kind)) |served| admitted = admitted or std.meta.eql(shape, served); + if (!admitted) return false; + t.rig.reset(); + _ = t.arena.reset(.retain_capacity); + t.shape = shape; + t.nonfinite = fill == .nonfinite; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // Queries are wide and lean one way: scores spread over several nats, and a planted key weighs in every sum. + t.f[0] = try t.floats(8 * Q, rng, 48); + for (t.f[0], 0..) |*v, i| v.* = bf(v.* + 16 * lean(i % D)); + if (t.nonfinite) t.f[0][0] = std.math.nan(f32); + t.f[1] = try t.floats(8 * KV, rng, 0.5); + t.f[2] = try t.floats(8 * KV, rng, 0.5); + plant(t.f[1][3 * KV ..][0..KV], 0.05, rng); + for (0..3) |j| t.refs[j] = try t.input(t.f[j]); + t.out = try t.rig.output(8 * Q * 2); + if (t.kind == .merge) { + const slots = pairs * shape.n; + t.f[3] = try t.arena.allocator().alloc(f32, slots * 2 + slots * D); + for (0..slots) |s| { + const mass = 1 + rng.float(f32) * 29; + t.f[3][2 * s] = 8 + rng.float(f32) * 10; + t.f[3][2 * s + 1] = mass; + for (t.f[3][slots * 2 + s * D ..][0..D]) |*v| v.* = (rng.float(f32) - 0.5) * 0.5 * mass; + } + t.refs[3] = try t.rig.input(std.mem.sliceAsBytes(t.f[3])); + return true; + } + const size = t.ring(); + const sp = t.span(); + t.f[3] = try t.floats(size * KV, rng, 0.5); + t.f[4] = try t.floats(size * KV, rng, 0.5); + if (shape.n > sp.first) { + // The first and last kept keys weigh in every sum; a key just outside them would swamp it if it were read. + plant(t.f[3][(sp.first % size) * KV ..][0..KV], 0.05, rng); + plant(t.f[3][((shape.n - 1) % size) * KV ..][0..KV], 0.05, rng); + const room = shape.n - sp.first < size; + if (sp.first > 0 and room) { + plant(t.f[3][((sp.first - 1) % size) * KV ..][0..KV], 0.5, rng); + @memset(t.f[4][((sp.first - 1) % size) * KV ..][0..KV], 0.25); + } + if (room) { + plant(t.f[3][(shape.n % size) * KV ..][0..KV], 0.5, rng); + @memset(t.f[4][(shape.n % size) * KV ..][0..KV], 0.25); + } + } + t.refs[3] = try t.input(t.f[3]); + t.refs[4] = try t.input(t.f[4]); + t.refs[5] = try t.rig.scratch(@max(host.unitsBytes(sp.chunks), 16)); + return true; + } + + pub fn run(t: *Probe) !void { + const pass = t.rig.begin(); + const R = t.refs; + switch (t.kind) { + .attend => host.attendUnits(&t.units, pass.e, hr(R[0]), hr(R[1]), hr(R[2]), hr(R[3]), hr(R[4]), hr(R[5]), hr(t.out), @intCast(t.shape.n), @intCast(t.ring()), t.local(), @intCast(t.shape.k / 2)), + .merge => host.mergeUnits(&t.units, pass.e, hr(R[0]), hr(R[1]), hr(R[2]), hr(R[3]), hr(t.out), .{ .committed = 0, .ring = 64, .first = 0, .chunk = host.units_chunk, .chunks = @intCast(t.shape.n) }), + } + try t.rig.finish(pass); + } + + pub fn count(_: *Probe) usize { + return 8 * Q; + } + pub fn reference(_: *Probe, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + fn score(t: *const Probe, group: usize, keys: []const f32) f64 { + var dot: f64 = 0; + for (t.f[0][group * D ..][0..D], keys[0..D]) |x, y| dot += @as(f64, x) * y; + return dot * scale; + } + + /// Softmax over the kept context and the block's eight keys, in float64 from the bf16 inputs. + fn attendReference(t: *Probe, group: usize, want: *[D]f64, mag: *[D]f64) !void { + const kv = (group % 24) / 3; + const size = t.ring(); + const first = t.span().first; + const kept = t.shape.n - first; + const scores = try t.a.alloc(f64, kept + 8); + defer t.a.free(scores); + var peak = -std.math.inf(f64); + for (scores, 0..) |*s, j| { + s.* = if (j < kept) t.score(group, t.f[3][((first + j) % size) * KV + kv * D ..]) else t.score(group, t.f[1][(j - kept) * KV + kv * D ..]); + peak = @max(peak, s.*); + } + var den: f64 = 0; + for (scores) |s| den += @exp(s - peak); + want.* = @splat(0); + mag.* = @splat(0); + for (scores, 0..) |s, j| { + const p = @exp(s - peak) / den; + const values = if (j < kept) t.f[4][((first + j) % size) * KV + kv * D ..][0..D] else t.f[2][(j - kept) * KV + kv * D ..][0..D]; + for (values, want, mag) |v, *w, *m| { + w.* += p * v; + m.* += p * @abs(v); + } + } + } + + /// The block's keys at their powers of two, then each chunk's sums at its own peak, in float64. + fn mergeReference(t: *Probe, group: usize, want: *[D]f64, mag: *[D]f64) void { + const kv = (group % 24) / 3; + const slots = pairs * t.shape.n; + var bs: [8]f64 = undefined; + var top = -std.math.inf(f64); + for (&bs, 0..) |*s, j| { + s.* = t.score(group, t.f[1][j * KV + kv * D ..]) * log2e; + top = @max(top, s.*); + } + for (0..t.shape.n) |chunk| top = @max(top, t.f[3][2 * (group * t.shape.n + chunk)]); + var den: f64 = 0; + want.* = @splat(0); + mag.* = @splat(0); + for (bs, 0..) |s, j| { + const w = std.math.pow(f64, 2, s - top); + den += w; + for (t.f[2][j * KV + kv * D ..][0..D], want, mag) |v, *o, *m| { + o.* += w * v; + m.* += w * @abs(v); + } + } + for (0..t.shape.n) |chunk| { + const at = group * t.shape.n + chunk; + const w = std.math.pow(f64, 2, @as(f64, t.f[3][2 * at]) - top); + den += w * t.f[3][2 * at + 1]; + for (t.f[3][slots * 2 + at * D ..][0..D], want, mag) |v, *o, *m| { + o.* += w * v; + m.* += w * @abs(v); + } + } + for (want, mag) |*o, *m| { + o.* /= den; + m.* /= den; + } + } + + /// A weight is a bf16, within 2^-8 of the softmax's above and below the line, and so is the output: 3 * 2^-8. + const divisor = 64; + + pub fn check(t: *Probe, _: g.Gate) !?[]const u8 { + const bytes = t.rig.bytes(t.out, 8 * Q * 2); + var want: [D]f64 = undefined; + var mag: [D]f64 = undefined; + for (0..pairs) |group| { + const poisoned = t.nonfinite and group == 0; + if (!poisoned) switch (t.kind) { + .attend => try t.attendReference(group, &want, &mag), + .merge => t.mergeReference(group, &want, &mag), + }; + for (0..D) |d| { + const i = group * D + d; + const got: f64 = c.fromBf16(std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)); + if (poisoned) { + if (!std.math.isNan(got)) return try std.fmt.bufPrint(&t.msg, "output {d} is {e} where its query holds a NaN", .{ i, got }); + continue; + } + const bound = mag[d] / divisor; + if (!(@abs(got - want[d]) <= bound)) return try std.fmt.bufPrint(&t.msg, "output {d} is {e} where float64 gives {e}: {d:.2} of its bound", .{ i, got, want[d], @abs(got - want[d]) / bound }); + } + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } + + /// The entries exist only where the GPU has tensor units; elsewhere the block attends on the scalar kernel. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for (std.enums.values(Kind)) |kind| for ([_]bool{ false, true }) |control| { + const name = if (control) controls.of(kind).name() else label(kind); + if (only) |needle| if (std.mem.indexOf(u8, name, needle) == null) continue; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + probe.* = try Probe.init(s.a, s.device, s.queue, kind, control); + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + try s.kernels.append(s.a, probe.kernel()); + }; + } +}; diff --git a/zig/tests/contract/metal_inkling2_dspark_units_controls.zig b/zig/tests/contract/metal_inkling2_dspark_units_controls.zig new file mode 100644 index 00000000000..7412fea687c --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_units_controls.zig @@ -0,0 +1,60 @@ +//! Count-checked mutations of Mini DSpark's tensor-unit attention: each of its two kernels has a genuine control. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; +const Kind = @import("metal_inkling2_dspark_units.zig").Kind; + +pub const Mutation = enum { + none, + attend_log2, + merge_keep, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .attend_log2 => "control: metal inkling2 dspark_units tf_ink2_dspark_attn_units context scores without the log2 factor", + .merge_keep => "control: metal inkling2 dspark_units tf_ink2_dspark_attn_merge earlier mass kept unscaled", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .attend_log2 => .{ .from = "score[f][e] = live ? score[f][e] * DSU_SCALE * DSU_LOG2E : -INFINITY;", .to = "score[f][e] = live ? score[f][e] * DSU_SCALE : -INFINITY;" }, + .merge_keep => .{ .from = "ll = ll * x + ml.y * y;", .to = "ll = ll + ml.y * y;" }, + }; + } +}; + +pub fn of(kind: Kind) Mutation { + return switch (kind) { + .attend => .attend_log2, + .merge => .merge_keep, + }; +} + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.inkling2_dspark_units); + const change = m.edit(); + if (std.mem.count(u8, src.inkling2_dspark_units, change.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.inkling2_dspark_units, change.from, change.to); +} + +test "each tensor-unit attention control edits exactly its planted line" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 dspark_units ")); + } + inline for ([_][]const u8{ "tf_ink2_dspark_attn_units", "tf_ink2_dspark_attn_merge" }) |name| + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.inkling2_dspark_units, name ++ "(")); +} diff --git a/zig/tests/contract/metal_inkling2_experts.zig b/zig/tests/contract/metal_inkling2_experts.zig new file mode 100644 index 00000000000..55c9a3d1c66 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_experts.zig @@ -0,0 +1,409 @@ +//! Inkling 2 Mini M3 contracts: independent FP64 decode/dot/activation and ascending-expert combine. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_experts_controls.zig"); +const src = @import("inkling2_metal"); + +pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down, nv_decode, mx_decode, combine }; + +fn symbol(k: Kind) []const u8 { + return switch (k) { + .nv_gu => "tf_ink2_nvfp4_gu", + .nv_down => "tf_ink2_nvfp4_down", + .mx_gu => "tf_ink2_mxfp8_gu", + .mx_down => "tf_ink2_mxfp8_down", + .nv_decode => "tf_ink2_nvfp4_quantize", + .mx_decode => "tf_ink2_mxfp8_quantize", + .combine => "tf_ink2_combine", + }; +} + +fn mutation(k: Kind) controls.Mutation { + return switch (k) { + .nv_gu => .nv_gu_up, + .nv_down => .nv_down_phi, + .mx_gu => .mx_gu_up, + .mx_down => .mx_down_scale, + .nv_decode => .nv_decode_nibble, + .mx_decode => .mx_decode_scale, + .combine => .combine_slot_order, + }; +} + +fn isNv(k: Kind) bool { + return k == .nv_gu or k == .nv_down or k == .nv_decode; +} +fn isGu(k: Kind) bool { + return k == .nv_gu or k == .mx_gu; +} +fn isDown(k: Kind) bool { + return k == .nv_down or k == .mx_down; +} +fn isDecode(k: Kind) bool { + return k == .nv_decode or k == .mx_decode; +} +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(k: Kind, control: bool) c.Spec { + const base = if (control) mutation(k).name() else switch (k) { + .nv_gu => "metal inkling2 experts tf_ink2_nvfp4_gu", + .nv_down => "metal inkling2 experts tf_ink2_nvfp4_down", + .mx_gu => "metal inkling2 experts tf_ink2_mxfp8_gu", + .mx_down => "metal inkling2 experts tf_ink2_mxfp8_down", + .nv_decode => "metal inkling2 experts tf_ink2_nvfp4_quantize", + .mx_decode => "metal inkling2 experts tf_ink2_mxfp8_quantize", + .combine => "metal inkling2 experts tf_ink2_combine", + }; + return .{ + .name = base, + .accum = if (isDecode(k)) .none else .f32, + .depth = depth, + .ops = if (isGu(k)) 12 else if (isDecode(k)) 1 else 3, + .mids = if (isGu(k)) 3 else 0, + .out = .bf16, + .served = switch (k) { + .nv_gu, .mx_gu => &.{ .{ .rows = 2, .n = 4, .k = 32 }, .{ .rows = 4, .n = 8, .k = 64 } }, + .nv_down, .mx_down => &.{ .{ .rows = 2, .n = 8, .k = 32 }, .{ .rows = 4, .n = 12, .k = 64 } }, + .nv_decode, .mx_decode => &.{ .{ .rows = 2, .n = 32, .k = 32 }, .{ .rows = 3, .n = 64, .k = 64 } }, + .combine => &.{ .{ .rows = 2, .n = 8, .k = 8 }, .{ .rows = 4, .n = 12, .k = 8 } }, + }, + .sums = if (k == .combine) .{ .f16 = 0, .bf16 = 100, .why = "bounded cancellation is exact in fp32 but loses its residual in bf16" } else .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and explicit BF16 nodes" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; +const Dot = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + kind: Kind, + ctl: controls.Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u8 = &.{}, + scales: []u8 = &.{}, + amax: []f32 = &.{}, + denominator: []f32 = &.{}, + ids: []i32 = &.{}, + weights: []f32 = &.{}, + refs: [7]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (control) mutation(kind) else .none); + defer a.free(text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = try host.Pipelines.loadSource(device, text), .kind = kind, .ctl = if (control) mutation(kind) else .none }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.a.free(p.scales); + p.a.free(p.amax); + p.a.free(p.denominator); + p.a.free(p.ids); + p.a.free(p.weights); + p.x = &.{}; + p.w = &.{}; + p.scales = &.{}; + p.amax = &.{}; + p.denominator = &.{}; + p.ids = &.{}; + p.weights = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.kind, p.ctl != .none), .ctx = p, .vt = if (p.kind == .combine and p.ctl == .combine_slot_order) &vt_exact else &vt, .control = p.ctl.gate() }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + const vt_exact = g.hooks(Probe); + + fn call(p: *const Probe) host.Call { + return .{ .rows = @intCast(p.shape.rows), .k = @intCast(if (p.kind == .combine) 32 else p.shape.k), .n = @intCast(p.shape.n), .experts = if (p.kind == .combine) 8 else 4, .topk = if (p.kind == .combine) 8 else 2, .format = if (isNv(p.kind)) .nvfp4 else .mxfp8 }; + } + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const k = p.kind; + if (shape.rows == 0 or shape.rows > 8) return false; + if (isGu(k) and (shape.n > 8 or shape.k > 64 or shape.k % 32 != 0)) return false; + if (isDown(k) and (shape.n > 12 or shape.k > 64 or shape.k % 32 != 0)) return false; + if (isDecode(k) and (shape.n != shape.k or shape.k > 64 or shape.k % 32 != 0)) return false; + if (k == .combine and (shape.n > 12 or shape.k != 8)) return false; + p.clear(); + p.shape = shape; + const nv = isNv(k); + const topk: usize = if (k == .combine) 8 else 2; + const routes = shape.rows * topk; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (!isDecode(k)) { + const nx = if (isGu(k)) shape.rows * shape.k else if (isDown(k)) routes * shape.k else routes * shape.n; + p.x = try p.a.alloc(u16, nx); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + } + p.ids = try p.a.alloc(i32, routes); + const combine_ids = [_]i32{ 2, 0, 1, 7, 3, 6, 4, 5 }; + // Eight distinct, unsorted routes exercise ascending-expert accumulation. + for (p.ids, 0..) |*id, i| id.* = if (k == .combine) combine_ids[i % 8] else @intCast(if (i % 2 == 0) 2 else (i / 2) % 2); + const matrices: usize = if (isGu(k)) 8 * shape.n else if (isDown(k)) 4 * shape.n else shape.rows; + if (k != .combine) { + p.w = try p.a.alloc(u8, matrices * (if (nv) shape.k / 2 else shape.k)); + p.scales = try p.a.alloc(u8, matrices * (shape.k / @as(usize, if (nv) 16 else 32))); + for (p.w) |*v| v.* = rng.int(u8); + for (p.scales, 0..) |*v, i| v.* = if (nv) @intCast(0x30 + (i % 17)) else @intCast(125 + (i % 5)); + if (!nv) for (p.w) |*v| if (v.* & 0x7f == 0x7f) { + v.* = (v.* & 0x80) | 0x7e; + }; + if (k == .mx_decode) { + p.w[0] = 0x30; + p.scales[0] = 255; // Decodes to 2^127 without first forming an overflowing 2^128. + } + } + if (nv) { + p.amax = try p.a.alloc(f32, if (isDecode(k)) 1 else 4); + for (p.amax, 0..) |*v, i| v.* = 2688.125 + @as(f32, @floatFromInt(i)) * 0.375; + p.denominator = try p.a.alloc(f32, 1); + p.denominator[0] = 2695.75; + } + if (k == .combine) p.weights = try p.a.alloc(f32, routes); + if (fill == .stress and !isDecode(k)) { + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + if (k != .combine) @memset(p.scales, if (nv) 0x38 else 127); + } + if (k == .combine) { + const values = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 }; + for (p.x, 0..) |*v, i| v.* = c.toBf16(if (fill == .stress) 1 else values[i % 8]); + if (fill == .stress) { + const terms = [_]f32{ 1024, 1, 1, 1, 1, 1, 1, -1029 }; + // Map expert indices back to route slots; the ascending sum is 1024 + six 1s - 1029. + for (0..p.shape.rows) |token| for (0..8) |expert| for (0..8) |slot| if (p.ids[token * 8 + slot] == expert) { + p.weights[token * 8 + slot] = terms[expert]; + }; + } else if (p.ctl == .combine_slot_order) { + const control_weights = [_]f32{ 0x1p127, 0x1p126, -0x1p127 / 3.0, 0.25, -0.2, 1.0 / 3.0, -2.0 / 7.0, 0.375 }; + for (p.weights, 0..) |*v, i| v.* = control_weights[i % 8]; + // Only this planted control overflows route order; ascending experts remain finite. + } else { + const ordinary_weights = [_]f32{ 0.125, -0.25, 0.375, -0.5, 0.625, -0.75, 0.875, -1 }; + for (p.weights, 0..) |*v, i| v.* = ordinary_weights[i % 8]; + } + } + if (fill == .nonfinite) { + if (!isDecode(k) and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } else if (isDecode(k) and p.scales.len > 1) { + if (nv) p.scales[0] = 0x7f else p.w[0] = 0x7f; + } + } + const out = try p.rig.output(p.count() * 2); + if (k == .combine) { + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[2] = try p.rig.input(std.mem.sliceAsBytes(p.weights)); + p.refs[3] = out; + } else if (isDecode(k)) { + p.refs[0] = try p.rig.input(p.w); + p.refs[1] = try p.rig.input(p.scales); + if (nv) { + p.refs[2] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[4] = out; + } else p.refs[2] = out; + } else { + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(p.w); + p.refs[2] = try p.rig.input(p.scales); + if (nv) { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[4] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[5] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[6] = out; + } else { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[4] = out; + } + } + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + const nv = isNv(p.kind); + if (isDecode(p.kind)) { + if (nv) try host.nvfp4Quantize(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), @intCast(p.shape.rows), @intCast(p.shape.k)) else try host.mxfp8Quantize(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.k)); + } else if (isGu(p.kind)) { + if (nv) try host.nvfp4Gu(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), hr(p.refs[5]), hr(p.refs[6]), p.call()) else try host.mxfp8Gu(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), p.call()); + } else if (isDown(p.kind)) { + if (nv) try host.nvfp4Down(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), hr(p.refs[5]), hr(p.refs[6]), p.call()) else try host.mxfp8Down(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), hr(p.refs[4]), p.call()); + } else try host.combine(&p.pipes, e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), hr(p.refs[3]), p.call()); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return if (isGu(p.kind) or isDown(p.kind)) p.shape.rows * 2 * p.shape.n else p.shape.rows * p.shape.n; + } + + fn e2(code: u8) f64 { + const v = ([_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 })[code & 7]; + return if (code & 8 != 0) -v else v; + } + fn e4(code: u8) f64 { + const exponent = (code >> 3) & 15; + const mantissa = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f64); + const v = if (exponent == 0) @as(f64, @floatFromInt(mantissa)) / 512 else std.math.ldexp(@as(f64, 8 + @as(u16, mantissa)), @as(i32, exponent) - 10); + return if (code & 0x80 != 0) -v else v; + } + fn weight(p: *const Probe, expert: usize, row: usize, col: usize) f64 { + const nv = isNv(p.kind); + const k = p.shape.k; + const rows_per_expert: usize = if (isGu(p.kind)) 2 * p.shape.n else p.shape.n; + const matrix_row = if (isDecode(p.kind)) row else expert * rows_per_expert + row; + if (!nv) { + const value = p.w[matrix_row * k + col]; + const scale = p.scales[matrix_row * (k / 32) + col / 32]; + return bf(std.math.ldexp(e4(value), @as(i32, scale) - 127)); + } + const codes = p.w[matrix_row * (k / 2) + col / 2]; + const code = if (col % 2 == 0) codes & 15 else codes >> 4; + const scale = p.scales[matrix_row * (k / 16) + col / 16]; + const factor = bf(p.amax[if (isDecode(p.kind)) 0 else expert]) / bf(p.denominator[0]); + return bf(@as(f32, @floatCast(e2(code) * e4(scale) * factor))); + } + + fn dot(p: *const Probe, expert: usize, row: usize, x: []const u16, sim: ?Sim) Dot { + var terms: [64]f64 = undefined; + var magnitude: f64 = 0; + for (0..p.shape.k) |col| { + const term = p.weight(expert, row, col) * @as(f64, c.fromBf16(x[col])); + terms[col] = term; + magnitude += @abs(term); + } + return .{ .value = if (sim) |s| rows.sumIn(s.acc, s.order, terms[0..p.shape.k]) else blk: { + var sum: f64 = 0; + for (terms[0..p.shape.k]) |term| sum += term; + break :blk sum; + }, .magnitude = magnitude }; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + if (isDecode(p.kind)) return .{ .value = p.weight(0, at / p.shape.k, at % p.shape.k), .magnitude = 0 }; + if (p.kind == .combine) { + const token = at / p.shape.n; + const col = at % p.shape.n; + var terms: [8]f64 = undefined; + var magnitude: f64 = 0; + var made: usize = 0; + for (0..8) |expert| for (0..8) |slot| if (p.ids[token * 8 + slot] == @as(i32, @intCast(expert))) { + const value = p.weights[token * 8 + slot] * @as(f64, c.fromBf16(p.x[(token * 8 + slot) * p.shape.n + col])); + terms[made] = value; + made += 1; + magnitude += @abs(value); + }; + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, terms[0..made]) else blk: { + var total: f64 = 0; + for (terms[0..made]) |term| total += term; + break :blk total; + }; + return .{ .value = bf(sum), .magnitude = magnitude }; + } + const pair = at / p.shape.n; + const n = at % p.shape.n; + const token = pair / 2; + const expert: usize = @intCast(p.ids[pair]); + const x = if (isGu(p.kind)) p.x[token * p.shape.k ..][0..p.shape.k] else p.x[pair * p.shape.k ..][0..p.shape.k]; + if (isDown(p.kind)) { + const d = p.dot(expert, n, x, sim); + return .{ .value = bf(d.value), .magnitude = d.magnitude }; + } + const gd = p.dot(expert, 2 * n, x, sim); + const ud = p.dot(expert, 2 * n + 1, x, sim); + const gate = bf(gd.value); + const up = bf(ud.value); + const left = 4 * std.math.tanh(gate / 4) * (1 / (1 + @exp(-gate))); + return .{ .value = bf(left * (25 * std.math.tanh(up / 25))), .magnitude = gd.magnitude + ud.magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } + pub fn check(p: *Probe, gate: g.Gate) !?[]const u8 { + if (gate != .shapes) return null; + const bytes = try p.rig.outputBytes(); + const want = try p.a.alloc(f64, p.count()); + defer p.a.free(want); + const mag = try p.a.alloc(f64, p.count()); + defer p.a.free(mag); + try p.reference(want, mag); + for (want, 0..) |w, i| if (c.read(.bf16, bytes, i) != w) return "route-slot output differs from the ascending-expert reference"; + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [14]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(Kind)) |kind| for ([_]bool{ false, true }) |control| { + const label = if (control) mutation(kind).name() else spec(kind, false).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, kind, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + }; + } +}; + +test "contract labels resolve to the seven shipped entries" { + for (std.enums.values(Kind)) |kind| { + const name = spec(kind, false).name; + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 experts ")); + try std.testing.expect(std.mem.indexOf(u8, src.experts, symbol(kind)) != null); + } +} diff --git a/zig/tests/contract/metal_inkling2_experts_controls.zig b/zig/tests/contract/metal_inkling2_experts_controls.zig new file mode 100644 index 00000000000..b21fc9fb14f --- /dev/null +++ b/zig/tests/contract/metal_inkling2_experts_controls.zig @@ -0,0 +1,80 @@ +//! Count-checked M3 source mutations: every shader entry has a genuine arithmetic control. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + nv_gu_up, + nv_down_phi, + mx_gu_up, + mx_down_scale, + nv_decode_nibble, + mx_decode_scale, + combine_slot_order, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .nv_gu_up => "control: metal inkling2 experts tf_ink2_nvfp4_gu up row", + .nv_down_phi => "control: metal inkling2 experts tf_ink2_nvfp4_down phi", + .mx_gu_up => "control: metal inkling2 experts tf_ink2_mxfp8_gu up row", + .mx_down_scale => "control: metal inkling2 experts tf_ink2_mxfp8_down scale", + .nv_decode_nibble => "control: metal inkling2 experts tf_ink2_nvfp4_quantize nibble", + .mx_decode_scale => "control: metal inkling2 experts tf_ink2_mxfp8_quantize scale", + .combine_slot_order => "control: metal inkling2 experts tf_ink2_combine route-slot order", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .nv_gu_up => .{ .from = "const uint gr = 2u * n, ur = gr + 1u;", .to = "const uint gr = 2u * n, ur = gr;" }, + .mx_gu_up => .{ .from = "const uint gr = 2u * n, ur = gr + 1u;", .to = "const uint gr = 2u * n, ur = gr;" }, + .nv_down_phi => .{ .from = "const float phi = ink2_phi(amax, denominator, expert);", .to = "const float phi = precise::divide(2.0f * amax[expert], denominator[0]);" }, + .nv_decode_nibble => .{ .from = "W[row * (a.k / 2u) + col / 2u], col,", .to = "W[row * (a.k / 2u) + col / 2u], col + 1u," }, + .mx_down_scale => .{ .from = "S + expert_s + ulong(n) * (a.k / 32u), X + ulong(group) * a.k, a.k, lane);", .to = "S + expert_s + ulong(n) * (a.k / 16u), X + ulong(group) * a.k, a.k, lane);" }, + .mx_decode_scale => .{ .from = "S[row * (a.k / 32u) + col / 32u]", .to = "S[row * (a.k / 32u) + col / 16u]" }, + .combine_slot_order => .{ .from = "const uint slot = order[r];", .to = "const uint slot = r;" }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.experts); + const change = m.edit(); + const expected: usize = switch (m) { + .nv_gu_up, .mx_gu_up, .nv_down_phi => 2, + else => 1, + }; + if (std.mem.count(u8, src.experts, change.from) != expected) return error.ControlEditCount; + // The same textual mutation serves both formats; a control compiles only its selected entry. + return std.mem.replaceOwned(u8, a, src.experts, change.from, change.to); +} + +test "every expert control edits exactly its planted arithmetic" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 experts ")); + } + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.experts, plain); +} + +test "expert source exports all seven entries and has no activation quantizer" { + for ([_][]const u8{ "tf_ink2_nvfp4_gu", "tf_ink2_nvfp4_down", "tf_ink2_mxfp8_gu", "tf_ink2_mxfp8_down", "tf_ink2_nvfp4_quantize", "tf_ink2_mxfp8_quantize", "tf_ink2_combine" }) |name| + try std.testing.expect(std.mem.indexOf(u8, src.experts, name) != null); + try std.testing.expect(std.mem.indexOf(u8, src.experts, "never quantize an activation") != null); + try std.testing.expect(std.mem.indexOf(u8, src.experts, "e2m1(float") == null); +} diff --git a/zig/tests/contract/metal_inkling2_glue.zig b/zig/tests/contract/metal_inkling2_glue.zig new file mode 100644 index 00000000000..b090ab0bbf5 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_glue.zig @@ -0,0 +1,380 @@ +//! Inkling 2 Mini glue under FP64 references, guarded buffers and real Metal dispatch. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_glue_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.glue; +const p = host.plan; +const sources = @import("inkling2_metal"); + +fn depth(s: c.Shape) usize { + return s.k + 40; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn fromBf(v: u16) f32 { + return c.fromBf16(v); +} + +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [3]c.Shape = undefined, + f: [4][]f32 = @splat(&.{}), + ids: []u32 = &.{}, + route_ids: rig_.Ref = undefined, + refs: [5]rig_.Ref = undefined, + out: rig_.Ref = undefined, + nonfinite: bool = false, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.glue); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .kind = kind, .pipes = try host.Pipelines.loadSource(device, text) }; + self.served = switch (kind) { + .embed_norm => .{ .{ .rows = 1, .n = p.hidden, .k = p.hidden }, .{ .rows = 5, .n = p.hidden, .k = p.hidden }, .{ .rows = 7, .n = p.hidden, .k = p.hidden } }, + .ar => .{ .{ .rows = 2, .n = p.hidden, .k = p.hidden }, .{ .rows = 4, .n = p.hidden, .k = p.hidden }, .{ .rows = 5, .n = p.hidden, .k = p.hidden } }, + .conv_static => .{ .{ .rows = 1, .n = 128, .k = 4 }, .{ .rows = 5, .n = 1024, .k = 4 }, .{ .rows = 7, .n = p.hidden, .k = 4 } }, + .conv_dynamic => .{ .{ .rows = 1, .n = 128, .k = 4 }, .{ .rows = 5, .n = 512, .k = 4 }, .{ .rows = 7, .n = 1024, .k = 4 } }, + .router => .{ .{ .rows = 1, .n = 8, .k = p.hidden }, .{ .rows = 5, .n = 8, .k = p.hidden }, .{ .rows = 7, .n = 8, .k = p.hidden } }, + .swiglu => .{ .{ .rows = 1, .n = p.intermediate, .k = 2 }, .{ .rows = 5, .n = p.intermediate, .k = 2 }, .{ .rows = 7, .n = p.intermediate, .k = 2 } }, + .logits => .{ .{ .rows = 1, .n = 128, .k = p.hidden }, .{ .rows = 5, .n = 256, .k = p.hidden }, .{ .rows = 11, .n = 128, .k = p.hidden } }, + .expert_pick => .{ .{ .rows = 1, .n = p.intermediate, .k = 8 }, .{ .rows = 5, .n = p.intermediate, .k = 8 }, .{ .rows = 7, .n = p.intermediate, .k = 8 } }, + .expert_combine => .{ .{ .rows = 1, .n = p.hidden, .k = 8 }, .{ .rows = 5, .n = p.hidden, .k = 8 }, .{ .rows = 7, .n = p.hidden, .k = 8 } }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + const vt_checked = g.hooks(Probe); + const vt_plain = blk: { + var vt = g.hooks(Probe); + vt.check = null; + break :blk vt; + }; + pub fn kernel(self: *Probe) g.Kernel { + const out: c.Elem = switch (self.kind) { + .ar, .router, .logits => .f32, + else => .bf16, + }; + return .{ + .ctx = self, + .vt = if (self.kind == .router) &vt_checked else &vt_plain, + .spec = .{ + .name = self.kind.label(), + .accum = .f32, + .depth = depth, + .ops = 96, + .mids = if (self.kind == .logits) 1 else 0, + .out = out, + .served = &self.served, + .nan = if (self.kind == .router) .{ .stated = "a NaN selected score makes the shared normalization and every selected weight NaN" } else .propagate, + // AR's integer stress terms are exact in FP32 and must discriminate FP16/BF16 by 100x. + .sums = if (self.kind == .ar) .{} else .{ .f16 = 0, .bf16 = 0, .why = "nonlinear norms, exponentials and BF16 endpoints have no uniform lower-precision separability factor" }, + }, + }; + } + pub fn count(self: *Probe) usize { + return if (self.kind == .ar) 2 * p.hidden else p.count(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const out = try self.arena.allocator().alloc(f32, n); + for (out) |*x| x.* = value(rng); + return out; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, x| b.* = c.toBf16(x); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!p.valid(self.kind, .{ .rows = shape.rows, .n = shape.n, .k = shape.k })) return false; + if (self.kind == .embed_norm and shape.n != p.hidden) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.nonfinite = fill == .nonfinite; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const r = shape.rows; + const n = shape.n; + const nf = fill == .nonfinite; + self.f = @splat(&.{}); + switch (self.kind) { + .embed_norm => { + self.f[0] = try self.floats(64 * p.hidden, rng); + self.f[1] = try self.floats(p.hidden, rng); + self.ids = try self.arena.allocator().alloc(u32, r); + for (self.ids, 0..) |*id, i| id.* = @intCast(i % 64); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.rig.input(std.mem.sliceAsBytes(self.ids)); + self.refs[1] = try self.input(self.f[0], true); + self.refs[2] = try self.input(self.f[1], true); + }, + .ar => { + self.f[0] = try self.floats((r - 1) * p.hidden, rng); + self.f[1] = try self.floats(p.hidden, rng); + self.f[2] = try self.floats(2 * p.hidden, rng); + if (fill == .stress) { + // Each 2304-term square sum is exactly 9 * 2^24 in FP32 under every order. + for (0..r) |s| { + const values = if (s + 1 == r) self.f[1] else self.f[0][s * p.hidden ..][0..p.hidden]; + @memset(values, if (s % 2 == 0) 256 else -256); + } + // Normalized mirrored queries leave +/-8; partial sums stay exact integers in FP32. + for (0..2) |query_row| { + const row = self.f[2][query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + const nudge: f32 = if (d < 8) 1 else 0; + row[d] = v; + row[p.hidden / 2 + d] = nudge - v; + } + } + } + if (nf) self.f[2][0] = std.math.inf(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], false); + self.refs[2] = try self.input(self.f[2], false); + }, + .conv_static => { + self.f[0] = try self.floats((r + 3) * n, rng); + self.f[1] = try self.floats(4 * n, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + }, + .conv_dynamic => { + self.f[0] = try self.floats((r + 3) * n, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(4 * n, rng); + self.f[3] = try self.floats(32 * p.hidden, rng); + if (nf) self.f[1][0] = std.math.nan(f32); + for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + }, + .router => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(p.expert_count * p.hidden, rng); + self.f[2] = try self.floats(p.expert_count, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + self.refs[2] = try self.input(self.f[2], false); + self.route_ids = try self.rig.scratch(r * 8 * 4); + }, + .swiglu => { + self.f[0] = try self.floats(r * n * 2, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + }, + .logits => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(n * p.hidden, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + }, + .expert_pick => { + self.f[0] = try self.floats(r * p.expert_count * n, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.ids = try self.arena.allocator().alloc(u32, r * 8); + for (self.ids, 0..) |*id, j| id.* = @intCast(j % 8 * 13 + j / 8); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(self.ids)); + }, + .expert_combine => { + self.f[0] = try self.floats(r * 8 * n, rng); + self.f[1] = try self.floats(r * 8, rng); + if (nf) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], false); + }, + } + // Every BF16 input and the FP64 oracle see exactly the same stored values. + for (self.f, 0..) |values, j| if (values.len > 0 and switch (self.kind) { + .ar => j == 0, + .router => j < 2, + .expert_combine => j == 0, + else => true, + }) round(values); + const bytes = self.count() * @as(usize, if (self.kind == .ar or self.kind == .router or self.kind == .logits) 4 else 2); + self.out = try self.rig.output(bytes); + return true; + } + fn at(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + /// A convolution's own rows: the taps after their three old rows. + fn fresh(ref: rig_.Ref, channels: usize) host.Ref { + return .{ .buf = ref.buf, .off = ref.off + 3 * channels * 2 }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const pl = &self.pipes; + const R = self.refs; + const y = at(self.out); + const r: u32 = @intCast(self.shape.rows); + const n: u32 = @intCast(self.shape.n); + switch (self.kind) { + .embed_norm => host.embedNorm(pl, e, at(R[0]), at(R[1]), at(R[2]), y, r), + .ar => host.ar(pl, e, at(R[0]), at(R[1]), at(R[2]), y, r, 2), + .conv_static => host.convStatic(pl, e, at(R[0]), fresh(R[0], n), at(R[1]), y, r, n), + .conv_dynamic => host.convDynamic(pl, e, at(R[0]), fresh(R[0], n), at(R[1]), at(R[2]), at(R[3]), y, r, n), + .router => host.router(pl, e, at(R[0]), at(R[1]), at(R[2]), at(self.route_ids), y, r), + .swiglu => host.swiglu(pl, e, at(R[0]), y, r, n), + .logits => host.logits(pl, e, at(R[0]), at(R[1]), y, r, n), + .expert_pick => host.expertPick(pl, e, at(R[0]), at(R[1]), y, r, n), + .expert_combine => host.expertCombine(pl, e, at(R[0]), at(R[1]), y, r, n), + } + try self.rig.finish(pass); + } + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + const r = self.shape.rows; + const n = self.shape.n; + for (0..r) |row| switch (self.kind) { + .embed_norm => { + const x = self.f[0][self.ids[row] * p.hidden ..][0..p.hidden]; + for (0..p.hidden) |d| want[row * p.hidden + d] = p.embedValue(x, self.f[1], d); + }, + .ar => { + var qout: [2 * p.hidden]f64 = undefined; + for (0..2) |q| p.blockResidual(self.f[0], self.f[1], self.f[2], r, q, qout[q * p.hidden ..][0..p.hidden]); + @memcpy(want, &qout); + break; + }, + .conv_static => { + for (0..n) |d| want[row * n + d] = p.staticConv(self.f[0], self.f[1], n, row, d); + }, + .conv_dynamic => { + for (0..n) |d| want[row * n + d] = p.dynamicConv(self.f[0], self.f[1], self.f[2], self.f[3], n, row, d); + }, + .router => { + const route = p.route(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], self.f[2]); + @memcpy(want[row * 8 ..][0..8], &route.weights); + }, + .swiglu => { + for (0..n) |d| want[row * n + d] = p.swiglu(self.f[0][(row * n + d) * 2], self.f[0][(row * n + d) * 2 + 1]); + }, + .logits => { + for (0..n) |v| want[row * n + v] = p.logit(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], v); + }, + .expert_pick => { + for (0..8) |j| { + for (0..n) |d| want[(row * 8 + j) * n + d] = p.pick(self.f[0], self.ids, n, row, j, d); + } + }, + .expert_combine => { + for (0..n) |d| want[row * n + d] = p.combine(self.f[0][row * 8 * n ..], self.f[1][row * 8 ..][0..8], n, d); + }, + }; + for (mag, want) |*m, w| m.* = 10 * @abs(w) + 1e-5; + } + pub fn simulate(self: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + if (self.kind == .ar) { + const sim: p.ArSum = .{ + .accum = switch (acc) { + .none => .none, + .f32 => .f32, + .f16 => .f16, + .bf16 => .bf16, + }, + .order = switch (order) { + .sequential => .sequential, + .pairwise => .pairwise, + .strided => .strided, + }, + }; + for (0..2) |q| p.blockResidualIn(self.f[0], self.f[1], self.f[2], self.shape.rows, q, sim, out[q * p.hidden ..][0..p.hidden]); + return; + } + const mag = try self.a.alloc(f64, out.len); + defer self.a.free(mag); + return self.reference(out, mag); + } + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + if (self.kind != .router) return "numeric hooks must be used"; + const bytes = try self.rig.outputBytes(); + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + if (gate == .nonfinite) { + for (want, 0..) |w, i| if (std.math.isNan(c.read(.f32, bytes, i)) != std.math.isNan(w)) return "NaN normalization rule differs"; + return null; + } + const got_ids = std.mem.bytesAsSlice(u32, self.rig.bytes(self.route_ids, self.shape.rows * 8 * 4)); + for (0..self.shape.rows) |row| { + const route = p.route(self.f[0][row * p.hidden ..][0..p.hidden], self.f[1], self.f[2]); + for (0..8) |j| { + if (got_ids[row * 8 + j] != route.ids[j]) return "selected IDs differ"; + const got = c.read(.f32, bytes, row * 8 + j); + if (@abs(got - want[row * 8 + j]) > 1e-5 * @max(1, @abs(want[row * 8 + j]))) return "router weight differs"; + } + } + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.glue, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_glue_controls.zig b/zig/tests/contract/metal_inkling2_glue_controls.zig new file mode 100644 index 00000000000..d54c3199693 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_glue_controls.zig @@ -0,0 +1,65 @@ +//! One host-checkable source-planted arithmetic fault for every Inkling 2 Mini glue kernel. +const std = @import("std"); +const p = @import("inkling2_glue_plan"); + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: p.Kind) Edit { + return switch (kind) { + .embed_norm => .{ .from = "float(weight[d]) * (float(x[d]) * inverse)", .to = "float(weight[0]) * (float(x[d]) * inverse)" }, + .ar => .{ .from = "weights[s] = dot * INKLING_AR_SCALE;", .to = "weights[s] = dot;" }, + .conv_static => .{ .from = "weight[c * 4 + tap]", .to = "weight[c * 4 + 3 - tap]" }, + .conv_dynamic => .{ .from = "static_w[lag * a.channels + c]", .to = "static_w[(3 - lag) * a.channels + c]" }, + .router => .{ .from = "keys[t] = scores[t] + bias[t];", .to = "keys[t] = scores[t];" }, + .swiglu => .{ .from = "ink_cap(u, 25.0f)", .to = "ink_cap(g, 25.0f)" }, + .logits => .{ .from = "ink_cap(float(bfloat(dot)), 30.0f)", .to = "ink_cap(dot, 30.0f)" }, + .expert_pick => .{ .from = "ids[r * 8 + j]", .to = "ids[r * 8 + 7 - j]" }, + .expert_combine => .{ .from = "acc += weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]);", .to = "acc -= weights[r * 8 + j] * float(picked[(size_t(r) * 8 + j) * a.channels + d]);" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .embed_norm => "control: metal inkling2 glue embed_norm tf_inkling2_embed_norm", + .ar => "control: metal inkling2 glue ar tf_inkling2_ar", + .conv_static => "control: metal inkling2 glue conv_static tf_inkling2_conv_static", + .conv_dynamic => "control: metal inkling2 glue conv_dynamic tf_inkling2_conv_dynamic", + .router => "control: metal inkling2 glue router tf_inkling2_router", + .swiglu => "control: metal inkling2 glue swiglu tf_inkling2_swiglu", + .logits => "control: metal inkling2 glue logits tf_inkling2_logits", + .expert_pick => "control: metal inkling2 glue expert_pick tf_inkling2_expert_pick", + .expert_combine => "control: metal inkling2 glue expert_combine tf_inkling2_expert_combine", + }; +} + +test "every glue control applies once and changes only its arithmetic anchor" { + const production = @import("inkling2_metal").glue; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated glue control anchor is ambiguous and refuses to prove a fault" { + const a = std.testing.allocator; + const production = @import("inkling2_metal").glue; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_inkling2_logits_units.zig b/zig/tests/contract/metal_inkling2_logits_units.zig new file mode 100644 index 00000000000..d88e13f7441 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_logits_units.zig @@ -0,0 +1,179 @@ +//! Inkling 2 Mini's logits on the tensor units: the glue entry's FP64 dot, BF16 round and cap of 30. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +const hidden = 2304; +pub const name = "metal inkling2 units tf_ink2_logits_units"; + +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +pub fn spec(control: bool) c.Spec { + return .{ + .name = if (control) controls.Mutation.logits_cap.name() else name, + .accum = .f32, + .depth = depth, + .ops = 8, + .mids = 1, + .out = .f32, + // Rows go 16 a band and vocabulary rows 32 a tile; 90 vocabulary rows leave the last tile part full. + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{} }, + .served = &.{ .{ .rows = 1, .n = 64, .k = hidden }, .{ .rows = 8, .n = 90, .k = hidden }, .{ .rows = 20, .n = 32, .k = hidden } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms, an explicit BF16 node and a tanh" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + control: bool, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + refs: [3]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, control: bool) !Probe { + const text = try controls.apply(a, if (control) .logits_cap else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .control = control }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.x = &.{}; + p.w = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.control), .ctx = p, .vt = &vt, .control = if (p.control) controls.Mutation.logits_cap.gate() else null }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > 40 or shape.n == 0 or shape.n > 128 or shape.k != hidden) return false; + p.clear(); + p.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, shape.rows * hidden); + p.w = try p.a.alloc(u16, shape.n * hidden); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + for (p.w) |*v| v.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + if (fill == .stress) { + // Whole numbers times a power of two: every product and partial sum is exact, and the cap stays live. + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + for (p.w, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(@as(i32, @intCast(i % 7)) - 3)) * 0x1p-20); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.w)); + p.refs[2] = try p.rig.output(p.count() * 4); + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + try host.logitsUnits(&p.pipes, pass.e, hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), @intCast(p.shape.rows), @intCast(p.shape.n)); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * p.shape.n; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const row = at / p.shape.n; + const v = at % p.shape.n; + var terms: [hidden]f64 = undefined; + var magnitude: f64 = 0; + for (&terms, 0..) |*term, d| { + term.* = @as(f64, c.fromBf16(p.w[v * hidden + d])) * @as(f64, c.fromBf16(p.x[row * hidden + d])); + magnitude += @abs(term.*); + } + const sum = if (sim) |s| rows.sumIn(s.acc, s.order, &terms) else blk: { + var total: f64 = 0; + for (terms) |term| total += term; + break :blk total; + }; + return .{ .value = 30 * std.math.tanh(bf(sum) / 30), .magnitude = magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [2]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entry exists only where the GPU has tensor units; elsewhere the glue's kernel serves every width. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for ([_]bool{ false, true }) |control| { + const label = spec(control).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + } + } +}; + +test "the logits entry resolves to its symbol in the units source" { + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, "tf_ink2_logits_units(")); +} diff --git a/zig/tests/contract/metal_inkling2_loop.zig b/zig/tests/contract/metal_inkling2_loop.zig new file mode 100644 index 00000000000..f597983003e --- /dev/null +++ b/zig/tests/contract/metal_inkling2_loop.zig @@ -0,0 +1,327 @@ +//! Mini cross-pass messages and rank-64 gates under FP64 oracles and mutation controls. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_loop_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.loop; +const p = host.plan; +const sources = @import("inkling2_metal"); + +fn depth(s: c.Shape) usize { + return if (s.n == p.message_entries * p.hidden) 2 * s.k + 16 else 2 * p.hidden + s.k + 16; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipes: host.Pipelines, + shape: c.Shape = undefined, + served: [3]c.Shape = undefined, + f: [6][]f32 = @splat(&.{}), + refs: [6]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.loop); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ + .a = a, + .arena = .init(a), + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = kind, + .pipes = try host.Pipelines.loadSource(device, text), + }; + self.served = switch (kind) { + .messages => .{ + .{ .rows = 1, .n = p.message_entries * p.hidden, .k = p.hidden }, + .{ .rows = 5, .n = p.message_entries * p.hidden, .k = p.hidden }, + .{ .rows = 7, .n = p.message_entries * p.hidden, .k = p.hidden }, + }, + .gates => .{ + .{ .rows = 1, .n = p.hidden, .k = p.rank }, + .{ .rows = 5, .n = p.hidden, .k = p.rank }, + .{ .rows = 7, .n = p.hidden, .k = p.rank }, + }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.rig.deinit(); + self.arena.deinit(); + self.pipes.deinit(); + } + + const vt = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = &vt, .spec = .{ + .name = self.kind.label(), + .accum = .f32, + .depth = depth, + .ops = if (self.kind == .messages) 32 else 64, + .mids = if (self.kind == .gates) 2 else 0, + .out = .f32, + .served = &self.served, + .sums = .{}, + } }; + } + pub fn count(self: *Probe) usize { + return p.count(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = value(rng); + return values; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const call = p.Call{ .rows = shape.rows, .n = shape.n, .k = shape.k }; + if (!p.valid(self.kind, call)) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const r = shape.rows; + switch (self.kind) { + .messages => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(2 * p.core_layers * p.hidden, rng); + self.f[3] = try self.floats(2 * p.core_layers * p.hidden, rng); + if (fill == .stress) { + // rho(+256) = +1 and rho(-256) = -1 in FP32: their square sum is 9 * 2^24. + @memset(self.f[0], 256); + @memset(self.f[1], -256); + // Mirrored integer queries leave 8, while every partial sum stays below 2^24. + for ([_][]f32{ self.f[2], self.f[3] }) |queries| for (0..2 * p.core_layers) |query_row| { + const row = queries[query_row * p.hidden ..][0..p.hidden]; + for (0..p.hidden / 2) |d| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + const nudge: f32 = if (d < 8) 1 else 0; + row[d] = v; + row[p.hidden / 2 + d] = nudge - v; + } + }; + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + round(self.f[0]); + round(self.f[1]); + self.refs[0] = try self.input(self.f[0], true); + self.refs[1] = try self.input(self.f[1], true); + self.refs[2] = try self.input(self.f[2], false); + self.refs[3] = try self.input(self.f[3], false); + }, + .gates => { + self.f[0] = try self.floats(r * p.hidden, rng); + self.f[1] = try self.floats(r * p.hidden, rng); + self.f[2] = try self.floats(p.rank * 2 * p.hidden, rng); + self.f[3] = try self.floats(p.hidden * p.rank, rng); + self.f[4] = try self.floats(p.hidden * p.rank, rng); + if (fill == .stress) { + @memset(self.f[0], 256); + @memset(self.f[1], -256); + // D sees [+1; -1]: mirrored integer rows leave zeta = 1, with exact FP32 partials. + for (0..p.rank) |rank| for (0..p.hidden) |d| { + const w: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 64)); + self.f[2][rank * 2 * p.hidden + d] = w; + self.f[2][rank * 2 * p.hidden + p.hidden + d] = if (d == 0) w - 1 else w; + }; + // With zeta = 1, mirrored F/Gamma rows leave one, also exactly in every FP32 order. + for ([_][]f32{ self.f[3], self.f[4] }) |weights| for (0..p.hidden) |d| for (0..p.rank / 2) |rank| { + const w: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 7)); + weights[d * p.rank + rank] = w; + weights[d * p.rank + rank + p.rank / 2] = if (rank == 0) 1 - w else -w; + }; + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + round(self.f[2]); + round(self.f[3]); + round(self.f[4]); + self.refs[0] = try self.input(self.f[0], false); + self.refs[1] = try self.input(self.f[1], false); + self.refs[2] = try self.input(self.f[2], true); + self.refs[3] = try self.input(self.f[3], true); + self.refs[4] = try self.input(self.f[4], true); + }, + } + self.out = try self.rig.output(self.count() * @sizeOf(f32)); + return true; + } + + fn at(ref: rig_.Ref) host.Ref { + return .{ .buf = ref.buf, .off = ref.off }; + } + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + const rows: u32 = @intCast(self.shape.rows); + switch (self.kind) { + .messages => host.crossPassMessageAttention(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.out), rows), + .gates => host.gates(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.refs[4]), at(self.out), rows), + } + try self.rig.finish(pass); + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + switch (self.kind) { + .messages => for (0..self.shape.rows) |row| { + const b0 = self.f[0][row * p.hidden ..][0..p.hidden]; + const b1 = self.f[1][row * p.hidden ..][0..p.hidden]; + for (0..p.message_entries) |entry| { + const role: p.Role = @fromBackingInt(@intCast(entry % p.roles)); + const dst = want[(row * p.message_entries + entry) * p.hidden ..][0..p.hidden]; + p.message(b0, b1, self.f[2], self.f[3], entry / p.roles, role, dst); + } + }, + .gates => for (0..self.shape.rows) |row| { + const h = self.f[0][row * p.hidden ..][0..p.hidden]; + const m = self.f[1][row * p.hidden ..][0..p.hidden]; + p.gate(h, m, self.f[2], self.f[3], self.f[4], want[row * p.hidden ..][0..p.hidden]); + }, + } + for (mag, want) |*m, w| m.* = if (self.kind == .messages) + 10 * @abs(w) + 1e-3 + else + 32 * @abs(w) + 8; + } + fn simRms(x: []const f32, acc: c.Accum, order: g.Order, terms: []f64) f64 { + for (x, 0..) |v, d| terms[d] = @as(f64, v) * v; + const ss = contract.rows.sumIn(acc, order, terms[0..p.hidden]); + return 1 / @sqrt(ss / @as(f64, @floatFromInt(p.hidden)) + p.eps); + } + + fn simMessage(bank0: []const f32, bank1: []const f32, q_mlp: []const f32, kv: []const f32, layer: usize, role: p.Role, inverse: [2]f64, acc: c.Accum, order: g.Order, terms: []f64, out: []f64) void { + const queries = if (p.usesQueryMessageTensor(role)) q_mlp else kv; + const query = queries[p.queryRow(role, layer) * p.hidden ..][0..p.hidden]; + var logits: [2]f64 = undefined; + var peak = -std.math.inf(f64); + inline for (0..2) |s| { + const bank = if (s == 0) bank0 else bank1; + for (0..p.hidden) |d| terms[d] = @as(f64, query[d]) * (@as(f64, bank[d]) * inverse[s]); + logits[s] = contract.rows.sumIn(acc, order, terms[0..p.hidden]) * p.message_scale; + peak = @max(peak, logits[s]); + } + var weights: [2]f64 = undefined; + var den: f64 = 0; + for (0..2) |s| { + weights[s] = @exp(logits[s] - peak); + den += weights[s]; + } + for (0..p.hidden) |d| out[d] = weights[0] / den * (@as(f64, bank0[d]) * inverse[0]) + weights[1] / den * (@as(f64, bank1[d]) * inverse[1]); + } + + fn simGate(h: []const f32, m: []const f32, down: []const f32, forget: []const f32, gain: []const f32, inverse: [2]f64, acc: c.Accum, order: g.Order, terms: []f64, normalized: *[2 * p.hidden]f64, zeta: *[p.rank]f64, out: []f64) void { + for (0..p.hidden) |d| { + normalized[d] = p.roundBf16(@as(f64, h[d]) * inverse[0]); + normalized[p.hidden + d] = p.roundBf16(@as(f64, m[d]) * inverse[1]); + } + for (0..p.rank) |r| { + for (0..2 * p.hidden) |d| terms[d] = @as(f64, down[r * 2 * p.hidden + d]) * normalized[d]; + zeta[r] = p.roundBf16(contract.rows.sumIn(acc, order, terms)); + } + for (0..p.hidden) |d| { + for (0..p.rank) |r| terms[r] = @as(f64, forget[d * p.rank + r]) * zeta[r]; + const fdot = contract.rows.sumIn(acc, order, terms[0..p.rank]); + for (0..p.rank) |r| terms[r] = @as(f64, gain[d * p.rank + r]) * zeta[r]; + const gdot = contract.rows.sumIn(acc, order, terms[0..p.rank]); + out[d] = p.blend(std.math.tanh(fdot), std.math.tanh(gdot), h[d], m[d]); + } + } + + pub fn simulate(self: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + const terms = try self.a.alloc(f64, 2 * p.hidden); + defer self.a.free(terms); + switch (self.kind) { + .messages => for (0..self.shape.rows) |row| { + const banks = [2][]const f32{ + self.f[0][row * p.hidden ..][0..p.hidden], + self.f[1][row * p.hidden ..][0..p.hidden], + }; + var inverse: [2]f64 = undefined; + inline for (0..2) |s| inverse[s] = simRms(banks[s], acc, order, terms); + for (0..p.message_entries) |entry| { + const role: p.Role = @fromBackingInt(@intCast(entry % p.roles)); + const dst = out[(row * p.message_entries + entry) * p.hidden ..][0..p.hidden]; + simMessage(banks[0], banks[1], self.f[2], self.f[3], entry / p.roles, role, inverse, acc, order, terms, dst); + } + }, + .gates => { + var normalized: [2 * p.hidden]f64 = undefined; + var zeta: [p.rank]f64 = undefined; + for (0..self.shape.rows) |row| { + const h = self.f[0][row * p.hidden ..][0..p.hidden]; + const m = self.f[1][row * p.hidden ..][0..p.hidden]; + var inverse: [2]f64 = undefined; + inverse[0] = simRms(h, acc, order, terms); + inverse[1] = simRms(m, acc, order, terms); + simGate(h, m, self.f[2], self.f[3], self.f[4], inverse, acc, order, terms, &normalized, &zeta, out[row * p.hidden ..][0..p.hidden]); + } + }, + } + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.loop, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_loop_controls.zig b/zig/tests/contract/metal_inkling2_loop_controls.zig new file mode 100644 index 00000000000..0e7c0600010 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_loop_controls.zig @@ -0,0 +1,53 @@ +//! One host-checkable arithmetic mutation for each Inkling 2 Mini loop kernel. +const std = @import("std"); +const p = @import("inkling2_loop_plan"); + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: p.Kind) Edit { + return switch (kind) { + // Drops the required post-dot binary32(1/48) scale. + .messages => .{ .from = "weights[s] = dot * INKLING_LOOP_SCALE;", .to = "weights[s] = dot;" }, + // Drops the model-dtype rounding between D accumulation and F/Gamma. + .gates => .{ .from = "zeta[row * INKLING_LOOP_RANK + r] = bfloat(sum);", .to = "zeta[row * INKLING_LOOP_RANK + r] = bfloat(2.0f * sum);" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .messages => "control: metal inkling2 loop messages tf_inkling2_loop_messages", + .gates => "control: metal inkling2 loop gates tf_inkling2_loop_gates", + }; +} + +test "every loop control applies once and changes only its arithmetic anchor" { + const production = @import("inkling2_metal").loop; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated loop control anchor is ambiguous and refuses to prove a fault" { + const a = std.testing.allocator; + const production = @import("inkling2_metal").loop; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig new file mode 100644 index 00000000000..557538723e2 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -0,0 +1,61 @@ +//! Inkling 2 Mini Metal suites and the lifetimes of their contract probes. +const std = @import("std"); +const mtl = @import("metal"); +const g = @import("contract").gates; + +pub const Suites = struct { + attention: @import("metal_inkling2_attention.zig").Suite, + glue: @import("metal_inkling2_glue.zig").Suite, + experts: @import("metal_inkling2_experts.zig").Suite, + units: @import("metal_inkling2_units.zig").Suite, + logits_units: @import("metal_inkling2_logits_units.zig").Suite, + dense_units: @import("metal_inkling2_dense_units.zig").Suite, + loop: @import("metal_inkling2_loop.zig").Suite, + runtime: @import("metal_inkling2_runtime.zig").Suite, + dspark: @import("metal_inkling2_dspark.zig").Suite, + chain: @import("metal_inkling2_dspark_chain.zig").Suite, + dspark_units: @import("metal_inkling2_dspark_units.zig").Suite, + + /// Built where it will live: each kernel's context points at a probe inside these suites. + pub fn init(s: *Suites, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + s.* = .{ + .attention = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .glue = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .experts = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .logits_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .dense_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .loop = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .runtime = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .dspark = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .chain = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .dspark_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + }; + errdefer s.deinit(); + try s.attention.collect(only); + try s.glue.collect(only); + try s.experts.collect(only); + try s.units.collect(only); + try s.logits_units.collect(only); + try s.dense_units.collect(only); + try s.loop.collect(only); + try s.runtime.collect(only); + try s.dspark.collect(only); + try s.chain.collect(only); + try s.dspark_units.collect(only); + } + + pub fn deinit(s: *Suites) void { + s.attention.deinit(); + s.glue.deinit(); + s.experts.deinit(); + s.units.deinit(); + s.logits_units.deinit(); + s.dense_units.deinit(); + s.loop.deinit(); + s.runtime.deinit(); + s.dspark.deinit(); + s.chain.deinit(); + s.dspark_units.deinit(); + } +}; diff --git a/zig/tests/contract/metal_inkling2_runtime.zig b/zig/tests/contract/metal_inkling2_runtime.zig new file mode 100644 index 00000000000..94f555aecdf --- /dev/null +++ b/zig/tests/contract/metal_inkling2_runtime.zig @@ -0,0 +1,319 @@ +//! Inkling 2 Mini runtime helpers under FP64 references, guarded buffers and exact ABI launches. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_runtime_controls.zig"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const p = @import("inkling2_runtime_plan"); +const sources = @import("inkling2_metal"); + +fn depth(_: c.Shape) usize { + return 1; +} +fn value(rng: std.Random) f32 { + return rng.float(f32) * 0.5 - 0.25; +} +fn round(values: []f32) void { + for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); +} + +pub const Probe = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: p.Kind, + pipe: mtl.Pipeline, + shape: c.Shape = undefined, + served: [5]c.Shape = undefined, + f: [2][]f32 = @splat(&.{}), + refs: [2]rig_.Ref = undefined, + blocks: rig_.Ref = undefined, + blocks_before: []u16 = &.{}, + out: rig_.Ref = undefined, + /// A partial's convolution: taps [3 + rows][H], weight [H][4], and the widened p the MLP partial also writes. + taps: rig_.Ref = undefined, + weight: rig_.Ref = undefined, + wide: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { + return initSource(a, device, queue, kind, sources.runtime); + } + pub fn initSource(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind, text: []const u8) !Probe { + var self: Probe = .{ + .a = a, + .arena = .init(a), + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = kind, + .pipe = undefined, + }; + errdefer self.arena.deinit(); + self.pipe = try rig_.pipeline(device, text, kind.symbol()); + self.served = switch (kind) { + .attention_partial => .{ + .{ .rows = 1, .n = p.hidden, .k = 0 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 3, .n = p.hidden, .k = 2 }, + .{ .rows = 2, .n = p.hidden, .k = 3 }, + .{ .rows = 7, .n = p.hidden, .k = 4 }, + }, + .copy_bf16, .copy_f32 => .{ + .{ .rows = 1, .n = p.hidden, .k = 1 }, + .{ .rows = 5, .n = 1024, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 1 }, + .{ .rows = 16, .n = 1024, .k = 1 }, + .{ .rows = 32, .n = p.hidden, .k = 1 }, + }, + .capture_tap => .{ + .{ .rows = 1, .n = p.hidden, .k = 0 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 2 }, + .{ .rows = 16, .n = p.hidden, .k = 3 }, + .{ .rows = 32, .n = p.hidden, .k = 3 }, + }, + else => .{ + .{ .rows = 1, .n = p.hidden, .k = 1 }, + .{ .rows = 5, .n = p.hidden, .k = 1 }, + .{ .rows = 7, .n = p.hidden, .k = 1 }, + .{ .rows = 16, .n = p.hidden, .k = 1 }, + .{ .rows = 32, .n = p.hidden, .k = 1 }, + }, + }; + return self; + } + pub fn deinit(self: *Probe) void { + self.pipe.deinit(); + self.rig.deinit(); + self.arena.deinit(); + } + + const vt_plain = blk: { + var vt = g.hooks(Probe); + vt.check = null; + break :blk vt; + }; + const vt_checked = g.hooks(Probe); + pub fn kernel(self: *Probe) g.Kernel { + return .{ .ctx = self, .vt = if (self.kind == .attention_partial or self.kind == .mlp_partial) &vt_checked else &vt_plain, .spec = .{ + .name = self.kind.label(), + .accum = .none, + .depth = depth, + .ops = if (self.kind == .attention_partial or self.kind == .mlp_partial) 1 else 0, + .out = switch (self.kind) { + .copy_bf16, .mlp_partial, .capture_tap => .bf16, + .copy_f32, .widen, .attention_partial => .f32, + }, + .served = &self.served, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "pointwise moves and single additions have no reduction accumulator to discriminate" }, + } }; + } + pub fn count(self: *Probe) usize { + return p.outputCount(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }); + } + + fn floats(self: *Probe, n: usize, rng: std.Random) ![]f32 { + const values = try self.arena.allocator().alloc(f32, n); + for (values) |*v| v.* = value(rng); + return values; + } + fn input(self: *Probe, values: []const f32, bf: bool) !rig_.Ref { + if (!bf) return self.rig.input(std.mem.sliceAsBytes(values)); + const bits = try self.arena.allocator().alloc(u16, values.len); + for (bits, values) |*b, v| b.* = c.toBf16(v); + return self.rig.input(std.mem.sliceAsBytes(bits)); + } + /// f[1] becomes the convolution of fresh taps and a weight, both bound for the kernel to take it itself. + fn convolved(self: *Probe, rng: std.Random) !void { + const rows = self.shape.rows; + const taps = try self.floats((rows + 3) * p.hidden, rng); + const weight = try self.floats(4 * p.hidden, rng); + round(taps); + round(weight); + self.f[1] = try self.arena.allocator().alloc(f32, rows * p.hidden); + for (self.f[1], 0..) |*y, i| y.* = p.conv(taps, weight, i / p.hidden, i % p.hidden); + self.taps = try self.input(taps, true); + self.weight = try self.input(weight, true); + } + pub fn prepare(self: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const call = p.Call{ .rows = shape.rows, .n = shape.n, .k = shape.k }; + if (!p.valid(self.kind, call)) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + self.f = @splat(&.{}); + self.blocks_before = &.{}; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = shape.rows * shape.n; + self.f[0] = try self.floats(n, rng); + switch (self.kind) { + .copy_bf16, .widen, .capture_tap => round(self.f[0]), + .attention_partial => { + try self.convolved(rng); + round(self.f[0]); + const blocks = try self.arena.allocator().alloc(u16, shape.rows * p.block_slots * p.hidden); + for (blocks) |*b| b.* = c.toBf16(value(rng)); + self.blocks_before = blocks; + self.blocks = try self.rig.scratch(std.mem.sliceAsBytes(blocks).len); + @memcpy(self.rig.bytes(self.blocks, std.mem.sliceAsBytes(blocks).len), std.mem.sliceAsBytes(blocks)); + }, + .mlp_partial => { + try self.convolved(rng); + self.wide = try self.rig.scratch(n * 4); + }, + .copy_f32 => {}, + } + if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + self.refs[0] = try self.input(self.f[0], self.kind == .copy_bf16 or self.kind == .widen or self.kind == .attention_partial or self.kind == .capture_tap); + const elem: c.Elem = switch (self.kind) { + .copy_bf16, .mlp_partial, .capture_tap => .bf16, + .copy_f32, .widen, .attention_partial => .f32, + }; + self.out = try self.rig.output(self.count() * c.size(elem)); + if (self.kind == .capture_tap) { + const untouched = std.mem.bytesAsSlice(u16, self.rig.bytes(self.out, self.count() * 2)); + @memset(untouched, c.toBf16(1)); + } + return true; + } + + pub fn run(self: *Probe) !void { + const pass = self.rig.begin(); + const e = pass.e; + e.setPipeline(self.pipe); + e.setBuffer(self.refs[0].buf, self.refs[0].off, 0); + switch (self.kind) { + .copy_bf16, .copy_f32, .widen, .capture_tap => { + e.setBuffer(self.out.buf, self.out.off, 1); + e.setValue(p.args(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }), 2); + }, + .attention_partial, .mlp_partial => { + // The taps' first three rows are the old ones; the launch's own follow them. + e.setBuffer(self.taps.buf, self.taps.off, 1); + e.setBuffer(self.taps.buf, self.taps.off + 3 * p.hidden * 2, 2); + e.setBuffer(self.weight.buf, self.weight.off, 3); + const second = if (self.kind == .attention_partial) self.blocks else self.wide; + if (self.kind == .attention_partial) { + e.setBuffer(second.buf, second.off, 4); + e.setBuffer(self.out.buf, self.out.off, 5); + } else { + e.setBuffer(self.out.buf, self.out.off, 4); + e.setBuffer(second.buf, second.off, 5); + } + e.setValue(p.args(self.kind, .{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }), 6); + }, + } + e.dispatchThreads(mtl.Size.of(p.geometry(.{ .rows = self.shape.rows, .n = self.shape.n, .k = self.shape.k }).count, 1, 1), mtl.Size.of(p.threads, 1, 1)); + try self.rig.finish(pass); + } + + pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { + if (self.kind == .capture_tap) { + for (want, mag, 0..) |*w, *m, i| { + const row = i / (p.tap_channels * p.hidden); + const channel = (i / p.hidden) % p.tap_channels; + const x = self.f[0][row * p.hidden + i % p.hidden]; + w.* = if (channel == self.shape.k) x else 1; + m.* = @abs(@as(f64, x)); + } + return; + } + for (want, mag, 0..) |*w, *m, i| { + const x = self.f[0][i]; + const y = if (self.f[1].len == 0) 0 else self.f[1][i]; + w.* = switch (self.kind) { + .copy_bf16, .copy_f32, .widen, .capture_tap => x, + .attention_partial => p.attentionPartial(x, y, self.shape.k), + .mlp_partial => p.mlpPartial(x, y), + }; + m.* = @abs(@as(f64, x)) + @abs(@as(f64, y)); + } + } + + pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { + const mlp = self.kind == .mlp_partial; + if ((self.kind != .attention_partial and !mlp) or (gate != .shapes and gate != .nonfinite)) return "numeric hooks must be used"; + const want = try self.a.alloc(f64, self.count()); + defer self.a.free(want); + const mag = try self.a.alloc(f64, self.count()); + defer self.a.free(mag); + try self.reference(want, mag); + const bytes = try self.rig.outputBytes(); + var planted: usize = 0; + for (want, 0..) |w, i| { + const got = c.read(if (mlp) .bf16 else .f32, bytes, i); + if (c.classOf(got) != c.classOf(w)) return "partial's floating-point class differs"; + if (c.classOf(w) != .finite) planted += 1; + if (gate == .shapes and std.math.isFinite(w) and got != w) return "partial differs from the FP64 reference's explicit rounding"; + } + if (gate == .nonfinite and (planted == 0 or planted == want.len)) return "the planted NaN does not discriminate finite and non-finite partials"; + if (mlp) { + // The second output is p as stored, widened: the next visit's partial source. + const wide = self.rig.bytes(self.wide, want.len * 4); + for (0..want.len) |i| { + const stored = c.read(.bf16, bytes, i); + const widened = c.read(.f32, wide, i); + if (c.classOf(stored) != c.classOf(widened)) return "the widened p's floating-point class differs from p"; + if (std.math.isFinite(stored) and stored != widened) return "the widened p differs from the p it stored"; + } + return null; + } + const block_bytes = self.rig.bytes(self.blocks, std.mem.sliceAsBytes(self.blocks_before).len); + const got_blocks = std.mem.bytesAsSlice(u16, block_bytes); + for (0..self.shape.rows) |row| for (0..p.block_slots) |slot| for (0..p.hidden) |d| { + const at = (row * p.block_slots + slot) * p.hidden + d; + const expected = if (self.shape.k != 0 and slot == self.shape.k - 1) + c.toBf16(self.f[0][row * p.hidden + d]) + else + self.blocks_before[at]; + if (got_blocks[at] != expected) return "completed-block row/slot layout differs"; + }; + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + if (control) { + const text = try controls.source(s.a, sources.runtime, kind); + defer s.a.free(text); + probe.* = try Probe.initSource(s.a, s.device, s.queue, kind, text); + } else { + probe.* = try Probe.init(s.a, s.device, s.queue, kind); + } + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_runtime_controls.zig b/zig/tests/contract/metal_inkling2_runtime_controls.zig new file mode 100644 index 00000000000..0be4d82aa02 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_runtime_controls.zig @@ -0,0 +1,65 @@ +//! One host-checkable arithmetic or layout mutation for each Inkling 2 Mini runtime helper. +const std = @import("std"); +const p = @import("inkling2_runtime_plan"); + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(kind: p.Kind) Edit { + return switch (kind) { + .copy_bf16 => .{ + .from = "kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = x[i];", + .to = "kernel void tf_ink2_copy_bf16(const device bfloat* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = bfloat(0);", + }, + .copy_f32 => .{ + .from = "kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = x[i];", + .to = "kernel void tf_ink2_copy_f32(const device float* x [[buffer(0)]], device float* y [[buffer(1)]], constant InkRuntimeArgs& a [[buffer(2)]], uint i [[thread_position_in_grid]]) {\n if (i < a.count) y[i] = 0.0f;", + }, + .widen => .{ .from = "if (i < a.count) y[i] = float(x[i]);", .to = "if (i < a.count) y[i] = 2.0f * float(x[i]);" }, + .attention_partial => .{ .from = "blocks[row * 4 * 2304 + (a.boundary - 1) * 2304 + d] = p[i];", .to = "blocks[row * 2304 + (a.boundary - 1) * 2304 + d] = p[i];" }, + .mlp_partial => .{ .from = "bfloat(t[i] + float(ink2_conv(", .to = "bfloat(t[i] - float(ink2_conv(" }, + .capture_tap => .{ .from = "y[row * 4 * 2304 + a.boundary * 2304 + d] = x[i];", .to = "y[row * 4 * 2304 + ((a.boundary + 1) % 4) * 2304 + d] = x[i];" }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: p.Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(kind: p.Kind) []const u8 { + return switch (kind) { + .copy_bf16 => "control: metal inkling2 runtime copy_bf16 tf_ink2_copy_bf16", + .copy_f32 => "control: metal inkling2 runtime copy_f32 tf_ink2_copy_f32", + .widen => "control: metal inkling2 runtime widen tf_ink2_widen", + .attention_partial => "control: metal inkling2 runtime attention_partial tf_ink2_attention_partial", + .mlp_partial => "control: metal inkling2 runtime mlp_partial tf_ink2_mlp_partial", + .capture_tap => "control: metal inkling2 runtime capture_tap tf_ink2_capture_tap", + }; +} + +test "every runtime control applies once and changes only its discriminating anchor" { + const production = @import("inkling2_metal").runtime; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, kind)); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated runtime control anchor is ambiguous and refuses to prove a fault" { + const production = @import("inkling2_metal").runtime; + const a = std.testing.allocator; + for (std.enums.values(p.Kind)) |kind| { + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); + } +} diff --git a/zig/tests/contract/metal_inkling2_units.zig b/zig/tests/contract/metal_inkling2_units.zig new file mode 100644 index 00000000000..d5b3b186440 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_units.zig @@ -0,0 +1,336 @@ +//! Inkling 2 Mini's routed experts on the tensor units: the same FP64 decode, dot and activation as the M3 entries. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const bf = contract.bf16_round.bf16; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_metal_host.experts; +const controls = @import("metal_inkling2_units_controls.zig"); +const src = @import("inkling2_metal"); + +pub const Kind = enum { nv_gu, nv_down, mx_gu, mx_down, nv_gu_t, nv_down_t, mx_gu_t, mx_down_t }; + +/// The columns the kernels fix for each product, and the experts `group` lists. +const gu_k = 2304; +const down_k = 1152; +const experts = 128; +const topk = 2; + +fn symbol(k: Kind) []const u8 { + return switch (k) { + .nv_gu => "tf_ink2_nvfp4_gu_units", + .nv_down => "tf_ink2_nvfp4_down_units", + .mx_gu => "tf_ink2_mxfp8_gu_units", + .mx_down => "tf_ink2_mxfp8_down_units", + .nv_gu_t => "tf_ink2_nvfp4_gu_units_t", + .nv_down_t => "tf_ink2_nvfp4_down_units_t", + .mx_gu_t => "tf_ink2_mxfp8_gu_units_t", + .mx_down_t => "tf_ink2_mxfp8_down_units_t", + }; +} + +fn mutation(k: Kind) controls.Mutation { + return switch (k) { + .nv_gu => .nv_gu_phi, + .nv_down => .nv_down_phi, + .mx_gu => .mx_gu_scale, + .mx_down => .mx_down_scale, + .nv_gu_t => .nv_gu_t_phi, + .nv_down_t => .nv_down_t_phi, + .mx_gu_t => .mx_gu_t_scale, + .mx_down_t => .mx_down_t_scale, + }; +} + +fn isNv(k: Kind) bool { + return k == .nv_gu or k == .nv_down or k == .nv_gu_t or k == .nv_down_t; +} +fn isGu(k: Kind) bool { + return k == .nv_gu or k == .mx_gu or k == .nv_gu_t or k == .mx_gu_t; +} +/// The turned tiles: 16 weight rows by 32 of an expert's pairs an op. +fn isTurned(k: Kind) bool { + return k == .nv_gu_t or k == .nv_down_t or k == .mx_gu_t or k == .mx_down_t; +} +fn depth(s: c.Shape) usize { + return s.k + 3; +} + +const gu_shapes = [_]c.Shape{ .{ .rows = 2, .n = 16, .k = gu_k }, .{ .rows = 5, .n = 32, .k = gu_k }, .{ .rows = 20, .n = 16, .k = gu_k } }; +const gu_turned_shapes = [_]c.Shape{ .{ .rows = 2, .n = 16, .k = gu_k }, .{ .rows = 5, .n = 32, .k = gu_k }, .{ .rows = 40, .n = 16, .k = gu_k } }; +const down_shapes = [_]c.Shape{ .{ .rows = 2, .n = 32, .k = down_k }, .{ .rows = 5, .n = 64, .k = down_k }, .{ .rows = 20, .n = 32, .k = down_k } }; +const down_turned_shapes = [_]c.Shape{ .{ .rows = 2, .n = 32, .k = down_k }, .{ .rows = 5, .n = 64, .k = down_k }, .{ .rows = 40, .n = 32, .k = down_k } }; + +pub fn spec(k: Kind, control: bool) c.Spec { + const base = if (control) mutation(k).name() else switch (k) { + .nv_gu => "metal inkling2 units tf_ink2_nvfp4_gu_units", + .nv_down => "metal inkling2 units tf_ink2_nvfp4_down_units", + .mx_gu => "metal inkling2 units tf_ink2_mxfp8_gu_units", + .mx_down => "metal inkling2 units tf_ink2_mxfp8_down_units", + .nv_gu_t => "metal inkling2 units tf_ink2_nvfp4_gu_units_t", + .nv_down_t => "metal inkling2 units tf_ink2_nvfp4_down_units_t", + .mx_gu_t => "metal inkling2 units tf_ink2_mxfp8_gu_units_t", + .mx_down_t => "metal inkling2 units tf_ink2_mxfp8_down_units_t", + }; + return .{ + .name = base, + .accum = .f32, + .depth = depth, + .ops = if (isGu(k)) 12 else 3, + .mids = if (isGu(k)) 3 else 0, + .out = .bf16, + // One expert takes every row here, so 20 rows cross a 16-pair band and 40 a turned tile's 32. + .tiles = .{ .{ .size = if (isTurned(k)) 32 else 16 }, .{}, .{} }, + .served = if (isGu(k)) (if (isTurned(k)) &gu_turned_shapes else &gu_shapes) else if (isTurned(k)) &down_turned_shapes else &down_shapes, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "independent FP64 terms and explicit BF16 nodes" }, + }; +} + +const Sim = struct { acc: c.Accum, order: g.Order }; +const Sample = struct { value: f64, magnitude: f64 }; +const Dot = struct { value: f64, magnitude: f64 }; + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipes: host.Pipelines, + kind: Kind, + ctl: controls.Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u8 = &.{}, + scales: []u8 = &.{}, + amax: []f32 = &.{}, + denominator: []f32 = &.{}, + ids: []i32 = &.{}, + refs: [7]rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (control) mutation(kind) else .none); + defer a.free(text); + var pipes = try host.Pipelines.loadSource(device, src.experts); + errdefer pipes.deinit(); + try pipes.loadUnits(device, text); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipes = pipes, .kind = kind, .ctl = if (control) mutation(kind) else .none }; + } + + fn clear(p: *Probe) void { + p.a.free(p.x); + p.a.free(p.w); + p.a.free(p.scales); + p.a.free(p.amax); + p.a.free(p.denominator); + p.a.free(p.ids); + p.x = &.{}; + p.w = &.{}; + p.scales = &.{}; + p.amax = &.{}; + p.denominator = &.{}; + p.ids = &.{}; + p.rig.reset(); + } + + pub fn deinit(p: *Probe) void { + p.clear(); + p.pipes.deinit(); + p.rig.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.kind, p.ctl != .none), .ctx = p, .vt = &vt, .control = p.ctl.gate() }; + } + const vt = blk: { + var table = g.hooks(Probe); + table.check = null; + break :blk table; + }; + + fn call(p: *const Probe) host.Call { + return .{ .rows = @intCast(p.shape.rows), .k = @intCast(p.shape.k), .n = @intCast(p.shape.n), .experts = experts, .topk = topk, .format = if (isNv(p.kind)) .nvfp4 else .mxfp8 }; + } + + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const k = p.kind; + if (shape.rows == 0 or shape.rows > 40) return false; + if (isGu(k) and (shape.k != gu_k or shape.n == 0 or shape.n > 32 or shape.n % 16 != 0)) return false; + if (!isGu(k) and (shape.k != down_k or shape.n == 0 or shape.n > 64 or shape.n % 32 != 0)) return false; + p.clear(); + p.shape = shape; + const nv = isNv(k); + const routes = shape.rows * topk; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + p.x = try p.a.alloc(u16, if (isGu(k)) shape.rows * shape.k else routes * shape.k); + for (p.x, 0..) |*v, i| v.* = c.toBf16((rng.float(f32) * 2 - 1) * (if (i % 7 == 0) @as(f32, 3) else 1)); + p.ids = try p.a.alloc(i32, routes); + // Expert 2 takes a pair of every row and experts 0 and 1 share the other, so one expert's pairs pass 16. + for (p.ids, 0..) |*id, i| id.* = @intCast(if (i % 2 == 0) 2 else (i / 2) % 2); + const matrices: usize = experts * (if (isGu(k)) 2 * shape.n else shape.n); + p.w = try p.a.alloc(u8, matrices * (if (nv) shape.k / 2 else shape.k)); + p.scales = try p.a.alloc(u8, matrices * (shape.k / @as(usize, if (nv) 16 else 32))); + for (p.w) |*v| v.* = rng.int(u8); + // Weights small enough that the gate and up sums stay in the activation's live range. + for (p.scales, 0..) |*v, i| v.* = if (nv) @intCast(0x30 + (i % 17)) else @intCast(112 + (i % 5)); + if (!nv) for (p.w) |*v| if (v.* & 0x7f == 0x7f) { + v.* = (v.* & 0x80) | 0x7e; + }; + if (nv) { + p.amax = try p.a.alloc(f32, experts); + for (p.amax, 0..) |*v, i| v.* = 2688.125 + @as(f32, @floatFromInt(i % 4)) * 0.375; + p.denominator = try p.a.alloc(f32, 1); + p.denominator[0] = 2695.75 * 64; + } + if (fill == .stress) { + for (p.x, 0..) |*v, i| v.* = c.toBf16(@as(f32, @floatFromInt(128 * (1 + i % 13))) * (if (i >= p.x.len / 2) @as(f32, -1) else 1)); + @memset(p.scales, if (nv) 0x38 else 127); + } + if (fill == .nonfinite and p.x.len >= 3) { + p.x[0] = c.toBf16(std.math.nan(f32)); + p.x[p.x.len / 2] = c.toBf16(std.math.inf(f32)); + p.x[p.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + const out = try p.rig.output(p.count() * 2); + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.x)); + p.refs[1] = try p.rig.input(p.w); + p.refs[2] = try p.rig.input(p.scales); + if (nv) { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.amax)); + p.refs[4] = try p.rig.input(std.mem.sliceAsBytes(p.denominator)); + p.refs[5] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[6] = out; + } else { + p.refs[3] = try p.rig.input(std.mem.sliceAsBytes(p.ids)); + p.refs[4] = out; + } + return true; + } + + fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + const nv = isNv(p.kind); + const ids = hr(p.refs[if (nv) 5 else 3]); + const out = hr(p.refs[if (nv) 6 else 4]); + try host.group(&p.pipes, e, ids, p.call()); + e.barrier(); + const launch = if (isTurned(p.kind)) &host.unitsTurned else &host.units; + try launch(&p.pipes, e, !isGu(p.kind), hr(p.refs[0]), hr(p.refs[1]), hr(p.refs[2]), if (nv) .{ .amax = hr(p.refs[3]), .denominator = hr(p.refs[4]) } else null, out, p.call()); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.shape.rows * topk * p.shape.n; + } + + fn e2(code: u8) f64 { + const v = ([_]f64{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 })[code & 7]; + return if (code & 8 != 0) -v else v; + } + fn e4(code: u8) f64 { + const exponent = (code >> 3) & 15; + const mantissa = code & 7; + if (exponent == 15 and mantissa == 7) return std.math.nan(f64); + const v = if (exponent == 0) @as(f64, @floatFromInt(mantissa)) / 512 else std.math.ldexp(@as(f64, 8 + @as(u16, mantissa)), @as(i32, exponent) - 10); + return if (code & 0x80 != 0) -v else v; + } + fn weight(p: *const Probe, expert: usize, row: usize, col: usize) f64 { + const k = p.shape.k; + const rows_per_expert: usize = if (isGu(p.kind)) 2 * p.shape.n else p.shape.n; + const matrix_row = expert * rows_per_expert + row; + if (!isNv(p.kind)) { + const value = p.w[matrix_row * k + col]; + const scale = p.scales[matrix_row * (k / 32) + col / 32]; + return bf(std.math.ldexp(e4(value), @as(i32, scale) - 127)); + } + const codes = p.w[matrix_row * (k / 2) + col / 2]; + const code = if (col % 2 == 0) codes & 15 else codes >> 4; + const scale = p.scales[matrix_row * (k / 16) + col / 16]; + const factor = bf(p.amax[expert]) / bf(p.denominator[0]); + return bf(@as(f32, @floatCast(e2(code) * e4(scale) * factor))); + } + + fn dot(p: *const Probe, expert: usize, row: usize, x: []const u16, sim: ?Sim) Dot { + var terms: [gu_k]f64 = undefined; + var magnitude: f64 = 0; + for (0..p.shape.k) |col| { + const term = p.weight(expert, row, col) * @as(f64, c.fromBf16(x[col])); + terms[col] = term; + magnitude += @abs(term); + } + return .{ .value = if (sim) |s| rows.sumIn(s.acc, s.order, terms[0..p.shape.k]) else blk: { + var sum: f64 = 0; + for (terms[0..p.shape.k]) |term| sum += term; + break :blk sum; + }, .magnitude = magnitude }; + } + + fn evaluate(p: *const Probe, at: usize, sim: ?Sim) Sample { + const pair = at / p.shape.n; + const n = at % p.shape.n; + const token = pair / topk; + const expert: usize = @intCast(p.ids[pair]); + const x = if (isGu(p.kind)) p.x[token * p.shape.k ..][0..p.shape.k] else p.x[pair * p.shape.k ..][0..p.shape.k]; + if (!isGu(p.kind)) { + const d = p.dot(expert, n, x, sim); + return .{ .value = bf(d.value), .magnitude = d.magnitude }; + } + const gd = p.dot(expert, 2 * n, x, sim); + const ud = p.dot(expert, 2 * n + 1, x, sim); + const gate = bf(gd.value); + const up = bf(ud.value); + const left = 4 * std.math.tanh(gate / 4) * (1 / (1 + @exp(-gate))); + return .{ .value = bf(left * (25 * std.math.tanh(up / 25))), .magnitude = gd.magnitude + ud.magnitude }; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (want, mag, 0..) |*v, *m, i| { + const sample = p.evaluate(i, null); + v.* = sample.value; + m.* = sample.magnitude; + } + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + for (out, 0..) |*v, i| v.* = p.evaluate(i, .{ .acc = acc, .order = order }).value; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [16]Probe = undefined, + made: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.made]) |*probe| probe.deinit(); + } + + /// The entries exist only where the GPU has tensor units; elsewhere the M3 kernels serve every width. + pub fn collect(s: *Suite, only: ?[]const u8) !void { + if (!s.device.tensorUnits()) return; + for (std.enums.values(Kind)) |kind| for ([_]bool{ false, true }) |control| { + const label = if (control) mutation(kind).name() else spec(kind, false).name; + if (only) |needle| if (std.mem.indexOf(u8, label, needle) == null) continue; + s.probes[s.made] = try Probe.init(s.a, s.device, s.queue, kind, control); + s.made += 1; + try s.kernels.append(s.a, s.probes[s.made - 1].kernel()); + }; + } +}; + +test "contract labels resolve to the units entries" { + for (std.enums.values(Kind)) |kind| { + const name = spec(kind, false).name; + try std.testing.expect(std.mem.startsWith(u8, name, "metal inkling2 units ")); + try std.testing.expect(std.mem.indexOf(u8, src.experts_units, symbol(kind)) != null); + } +} diff --git a/zig/tests/contract/metal_inkling2_units_controls.zig b/zig/tests/contract/metal_inkling2_units_controls.zig new file mode 100644 index 00000000000..6026c52a2b2 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_units_controls.zig @@ -0,0 +1,81 @@ +//! Count-checked mutations of the tensor-unit kernels: every entry has a genuine arithmetic control. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + nv_gu_phi, + nv_down_phi, + mx_gu_scale, + mx_down_scale, + nv_gu_t_phi, + nv_down_t_phi, + mx_gu_t_scale, + mx_down_t_scale, + logits_cap, + dense_store, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .nv_gu_phi => "control: metal inkling2 units tf_ink2_nvfp4_gu_units phi", + .nv_down_phi => "control: metal inkling2 units tf_ink2_nvfp4_down_units phi", + .mx_gu_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units scale", + .mx_down_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units scale", + .nv_gu_t_phi => "control: metal inkling2 units tf_ink2_nvfp4_gu_units_t phi", + .nv_down_t_phi => "control: metal inkling2 units tf_ink2_nvfp4_down_units_t phi", + .mx_gu_t_scale => "control: metal inkling2 units tf_ink2_mxfp8_gu_units_t scale", + .mx_down_t_scale => "control: metal inkling2 units tf_ink2_mxfp8_down_units_t scale", + .logits_cap => "control: metal inkling2 units tf_ink2_logits_units cap", + .dense_store => "control: metal inkling2 units tf_ink2_dense_units store", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .nv_gu_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .nv_down_phi => .{ .from = "ink2_units(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + // Both MXFP8 entries decode through one helper; a control compiles only its selected entry. + .nv_gu_t_phi => .{ .from = "ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units_t(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .nv_down_t_phi => .{ .from = "ink2_units_t(X, W, S, ink2_phi(amax, denominator, tg.y),", .to = "ink2_units_t(X, W, S, 2.0f * ink2_phi(amax, denominator, tg.y)," }, + .mx_gu_scale, .mx_down_scale, .mx_gu_t_scale, .mx_down_t_scale => .{ .from = "const int shift = int(scales[b / 2u]) - 127;", .to = "const int shift = int(scales[b / 2u]) - 126;" }, + .logits_cap => .{ .from = "precise::divide(float(bfloat(dot)), 30.0f)", .to = "precise::divide(float(bfloat(dot)), 15.0f)" }, + .dense_store => .{ .from = "Y[row * a.n + v] = bfloat(dot);", .to = "Y[row * a.n + v] = bfloat(2.0f * dot);" }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.experts_units); + const change = m.edit(); + if (std.mem.count(u8, src.experts_units, change.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.experts_units, change.from, change.to); +} + +test "every units control edits exactly its planted arithmetic" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 units ")); + } + const plain = try apply(a, .none); + defer a.free(plain); + try std.testing.expectEqualStrings(src.experts_units, plain); +} + +test "units source exports all four entries after the decode helpers" { + inline for ([_][]const u8{ "tf_ink2_nvfp4_gu_units", "tf_ink2_nvfp4_down_units", "tf_ink2_mxfp8_gu_units", "tf_ink2_mxfp8_down_units" }) |name| + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.experts_units, name ++ "(")); + try std.testing.expect(std.mem.indexOf(u8, src.experts_units, "never quantize an activation") != null); +} diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 790b720bb0f..7c4499163be 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -34,7 +34,7 @@ fn boltSource(name: []const u8) ![]const u8 { } /// Each registration's function is its label's last word; the label's words say which source it compiles. -fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !Launch { +pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !Launch { return resolve(a, device, d, true); } @@ -209,6 +209,29 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp const t = try @import("metal_flint.zig").limitsText(a, device, d.name); return .{ .decl = d, .function = fun, .here = t.here, .pre_m5 = t.pre_m5 }; } + if (std.mem.startsWith(u8, d.name, "metal inkling2 ")) { + if (!assemble) return undefined; + const body = if (std.mem.startsWith(u8, d.name, "metal inkling2 dspark ")) + @import("inkling2_metal").inkling2_dspark + else if (std.mem.startsWith(u8, d.name, "metal inkling2 dspark_units ")) + @import("inkling2_metal").inkling2_dspark_units + else if (std.mem.startsWith(u8, d.name, "metal inkling2 runtime ")) + @import("inkling2_metal").runtime + else if (std.mem.startsWith(u8, d.name, "metal inkling2 loop ")) + @import("inkling2_metal").loop + else if (std.mem.startsWith(u8, d.name, "metal inkling2 experts ")) + @import("inkling2_metal").experts + else if (std.mem.startsWith(u8, d.name, "metal inkling2 units ")) + @import("inkling2_metal").experts_units + else if (std.mem.startsWith(u8, d.name, "metal inkling2 glue ")) + @import("inkling2_metal").glue + else if (std.mem.startsWith(u8, d.name, "metal inkling2 prompt ")) + @import("inkling2_metal").prompt_attention + else + @import("inkling2_metal").attention; + const pre_m5 = if (std.mem.startsWith(u8, d.name, "metal inkling2 prompt ")) @import("inkling2_metal").prompt_attention_pre_m5 else body; + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = pre_m5 }; + } if (std.mem.startsWith(u8, d.name, "lfm2 masked prompt ")) { if (!assemble) return undefined; const body = try tf.lfm2_moe.source.prompt(device, a, true); diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index eb44a76eab1..784f7aea7a8 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -359,6 +359,9 @@ pub fn main(init: std.process.Init) !u8 { var ling_mla_set = ling_mla.Suite{ .a = a, .device = device, .queue = queue }; defer ling_mla_set.deinit(); try ling_mla_set.collect(&kernels, o.only); + var inkling2_suites: @import("metal_inkling2_main.zig").Suites = undefined; + try inkling2_suites.init(a, device, queue, &kernels, o.only); + defer inkling2_suites.deinit(); for ([_][]const Reg{ &common, if (tensor) &m5_only else &.{} }) |list| for (list) |v| { if (!wanted(o, v.name)) continue; const p = try a.create(affine_k.Proj); diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index aedf4e04e08..1b5291d9dda 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -15,6 +15,16 @@ test "Metal launch map: every registered launch and control has a resolver branc try std.testing.expectEqual(@as(usize, 0), missing); } +test "Metal launch map: every DSpark limit pipeline has a resolver branch" { + var count: usize = 0; + for (registry.all_metal) |d| { + if (!std.mem.startsWith(u8, d.name, "metal inkling2 dspark ")) continue; + try launches.requireMapped(d); + count += 1; + } + try std.testing.expectEqual(@as(usize, 13), count); +} + test "Metal launch map: unknown registrations stay errors on every chip" { try std.testing.expectError(error.UnknownLaunch, launches.requireMapped(.{ .name = "unregistered family missing_kernel", .threads = 32, .tg_memory = 0 })); } diff --git a/zig/tests/cuda/contract_inkling2.zig b/zig/tests/cuda/contract_inkling2.zig index fccf522af06..1ab486edf31 100644 --- a/zig/tests/cuda/contract_inkling2.zig +++ b/zig/tests/cuda/contract_inkling2.zig @@ -1,4 +1,4 @@ -//! Inkling 2's CUDA kernels under the contract: attention, glue, drafter, experts and tower, each with controls. +//! Inkling 2's CUDA kernels under the contract: attention, glue, experts and tower, each with controls. const std = @import("std"); const cuda = @import("cuda"); const check = @import("check.zig"); @@ -9,6 +9,8 @@ pub const Set = struct { gpa: std.mem.Allocator, attn: @import("contract_inkling2_attn.zig").Set = .{}, ops: @import("contract_inkling2_ops.zig").Set = .{}, + experts: @import("contract_inkling2_experts.zig").Set = .{}, + loop_math: @import("contract_inkling2_loop_math_extra.zig").Set = .{}, /// The set, its kernels appended to `list`. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { @@ -18,10 +20,16 @@ pub const Set = struct { try set.attn.init(gpu, s, a, list); errdefer set.attn.deinit(); try set.ops.init(gpu, s, a, list); + errdefer set.ops.deinit(); + try set.experts.init(gpu, s, a, list); + errdefer set.experts.deinit(); + try set.loop_math.init(gpu, s, a, list); return set; } pub fn deinit(set: *Set) void { + set.loop_math.deinit(); + set.experts.deinit(); set.ops.deinit(); set.attn.deinit(); set.gpa.destroy(set); diff --git a/zig/tests/cuda/contract_inkling2_experts.zig b/zig/tests/cuda/contract_inkling2_experts.zig new file mode 100644 index 00000000000..73f89cff366 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts.zig @@ -0,0 +1,88 @@ +//! Inkling 2's grouped experts and vision tower (inkling2/experts.cu, vision.cu) under the contract, with controls. +const std = @import("std"); +const cuda = @import("cuda"); +const ink = @import("inkling2"); +const check = @import("check.zig"); +const g = @import("core").contract.gates; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); +const grouped = @import("contract_inkling2_experts_grouped.zig"); +const vision = @import("contract_inkling2_experts_vision.zig"); +const modelopt = @import("contract_inkling2_modelopt.zig"); +const Attention = @import("contract_inkling2_experts_attn.zig").Attention; + +/// Every registration, each control after the kernel it breaks; the gates point at these fields. +pub const Set = struct { + live: bool = false, + ek: ink.experts.Kernels = undefined, + vk: ink.vision.Kernels = undefined, + mk: ink.modelopt.Kernels = undefined, + groups: [2]grouped.Group = undefined, + projections: [4]grouped.Grouped = undefined, + moe: [11]modelopt.ModelOpt = undefined, + embeds: [2]ref.Gated(vision.Embed) = undefined, + ropes: [2]ref.Gated(vision.Rope) = undefined, + adds: [2]ref.Gated(vision.ScaleAdd) = undefined, + attns: [2]Attention = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.ek = try ink.experts.Kernels.load(gpu.d); + errdefer set.ek.unload(); + set.vk = try ink.vision.Kernels.load(gpu.d); + errdefer set.vk.unload(); + const sms: usize = @intCast(try gpu.ctx.attribute(.multiprocessor_count)); + set.mk = try ink.modelopt.Kernels.load(gpu.d, sms); + errdefer set.mk.unload(); + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&set.groups, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.ek, .wrong_run = i == 1 }; + const forms = [4]@import("contract_inkling2_experts_ref.zig").Form{ .rows, .rows, .wide, .wide }; + for (&set.projections, forms, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = &set.ek, .form = f, .fault = if (i == 1) .short else if (i == 3) .swapped else .none }; + const prompt = [11]bool{ false, true, false, true, false, true, false, false, false, true, false }; + for (&set.moe, 0..) |*x, i| x.* = .{ + .rig = rig, + .k = &set.mk, + .format = if (i < 4) .nvfp4 else .mxfp8, + .phase = if (prompt[i]) .prompt else .decode, + .fault = switch (i) { + 0, 1, 4, 5 => .none, + 2, 6 => .wrong_combine, + 3, 9 => .wrong_prompt_up, + 7 => .wrong_plan, + 8 => .wrong_up, + 10 => .wrong_act, + else => unreachable, + }, + }; + for (&set.embeds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .late = i == 1 } }; + for (&set.ropes, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .swapped = i == 1 } }; + for (&set.adds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .late = i == 1 } }; + for (&set.attns, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.vk, .wide = i == 1 }; + set.live = true; + for (&set.groups) |*x| try list.append(a, x.kernel()); + for (&set.projections) |*x| try list.append(a, x.kernel()); + for (&set.moe) |*x| try list.append(a, x.kernel()); + for (&set.embeds) |*x| try list.append(a, x.kernel()); + for (&set.ropes) |*x| try list.append(a, x.kernel()); + for (&set.adds) |*x| try list.append(a, x.kernel()); + for (&set.attns) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + if (!set.live) return; + for (&set.attns) |*x| x.deinit(); + for (&set.adds) |*x| x.deinit(); + for (&set.ropes) |*x| x.deinit(); + for (&set.embeds) |*x| x.deinit(); + for (&set.moe) |*x| x.deinit(); + for (&set.projections) |*x| x.deinit(); + for (&set.groups) |*x| x.deinit(); + set.mk.unload(); + set.vk.unload(); + set.ek.unload(); + set.live = false; + } +}; + +test { + _ = @import("contract_inkling2_experts_ref.zig"); +} diff --git a/zig/tests/cuda/contract_inkling2_experts_attn.zig b/zig/tests/cuda/contract_inkling2_experts_attn.zig new file mode 100644 index 00000000000..e914309ae75 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_attn.zig @@ -0,0 +1,282 @@ +//! tf_ink2v_attention under the contract: the tower's full attention over one picture's rows, head dim 64. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const aref = core.attention_ref; +const threads = core.contract.reference_threads; + +const D = ink.vision.head_dim; +const smem: u32 = 2 * 2 * 64 * (D / 8 + 1) * 16; // vision.zig's attn_smem + +/// The P x V chain of a row: every key, a 64-key tile at a time. +fn keyChain(s: c.Shape) usize { + return s.k + 64; +} + +fn scale(wide: bool) f32 { + return 1.0 / @sqrt(@as(f32, if (wide) 128 else D)); +} + +/// Shape: heads (rows), head dim (n), sequence rows W (k): 16 heads at 1, 4 and 32 tokens, two at 256 to 4,096. +fn spec(wide: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 2, .n = D, .k = 1025 }, .{ .rows = 16, .n = D, .k = 5 }, .{ .rows = 16, .n = D, .k = 17 }, .{ .rows = 16, .n = D, .k = 129 }, .{ .rows = 2, .n = D, .k = 4097 }, .{ .rows = 2, .n = D, .k = 16385 } }; + const name = if (wide) "inkling2 experts control: tf_ink2v_attention scaled for head dim 128" else "inkling2 experts vision tf_ink2v_attention (full attention, head dim 64)"; + return .{ .name = name, .accum = .f32, .depth = keyChain, .ops = 1, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 128 } }, .served = served, .sums = .{ .why = attn.why } }; +} + +/// Gate 4's values: odd integers, every other one times 4, the second half cancelling the first (fp32 exact at 16K). +fn mirrored(rng: std.Random, out: []f32) void { + const h = out.len / 2; + for (0..h) |i| { + const v: f32 = @floatFromInt((1 + 2 * rng.uintLessThan(u32, 128)) * @as(u32, if (i % 2 == 1) 4 else 1)); + out[i] = v; + out[h + i] = (if (i < 8) @as(f32, 1) else 0) - v; + } + if (out.len % 2 == 1) out[out.len - 1] = 0; +} + +pub const Attention = struct { + rig: rig_.Rig, + k: *const ink.vision.Kernels, + wide: bool = false, // control: the score scale of head dim 128 + shape: c.Shape = undefined, + qkv: []u16 = &.{}, // [W][3 heads 64]: q heads, then k, then v + f: []f64 = &.{}, // [3][heads][W][64]: the same in float64 + keys: []usize = &.{}, + stressed: bool = false, + dev: u64 = 0, + out: u64 = 0, + msg: [240]u8 = undefined, + + pub fn deinit(self: *Attention) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Attention) void { + const a = self.rig.gpu.gpa; + a.free(self.qkv); + a.free(self.f); + a.free(self.keys); + self.qkv = &.{}; + self.f = &.{}; + self.keys = &.{}; + } + + pub fn kernel(self: *Attention) g.Kernel { + return .{ .spec = spec(self.wide), .ctx = self, .vt = &vt, .control = if (self.wide) .shapes else null }; + } + + const vt = g.hooks(Attention); + + fn heads(self: *const Attention) usize { + return self.shape.rows; + } + + fn at(self: *const Attention, row: usize, which: usize, head: usize) []u16 { + return self.qkv[row * 3 * self.heads() * D + (which * self.heads() + head) * D ..][0..D]; + } + + /// Float64 rows of q, k or v for one head: [W][64]. + fn rows(self: *const Attention, which: usize, head: usize) []const f64 { + const w = self.shape.k; + return self.f[(which * self.heads() + head) * w * D ..][0 .. w * D]; + } + + pub fn prepare(self: *Attention, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.n != D or shape.rows == 0 or shape.k == 0) return false; + const a = self.rig.gpu.gpa; + self.free(); + self.shape = shape; + self.stressed = fill == .stress; + const W = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.qkv = try a.alloc(u16, W * 3 * shape.rows * D); + for (self.qkv) |*e| e.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => try self.stress(rng), + } + self.f = try a.alloc(f64, self.qkv.len); + for (0..W) |j| for (0..3) |which| for (0..shape.rows) |h| { + for (self.f[((which * shape.rows + h) * W + j) * D ..][0..D], self.at(j, which, h)) |*y, x| y.* = c.fromBf16(x); + }; + self.keys = try a.alloc(usize, W); + for (self.keys, 0..) |*k, i| k.* = i; + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); + self.out = try self.rig.output(W * shape.rows * D * 2); + return true; + } + + /// Head 0: NaN in row 0's query, +inf and -inf in values, both in one column; head 1: NaN in one key. + fn plant(self: *Attention) void { + const L = self.shape.k; + self.at(0, 0, 0)[3] = c.toBf16(std.math.nan(f32)); + self.at(L - 1, 2, 0)[7] = c.toBf16(std.math.inf(f32)); + self.at(L / 2, 2, 0)[9] = c.toBf16(-std.math.inf(f32)); + if (L >= 3) { + self.at(1, 2, 0)[11] = c.toBf16(std.math.inf(f32)); + self.at(2, 2, 0)[11] = c.toBf16(-std.math.inf(f32)); + } + if (self.heads() > 1) self.at(L / 3, 1, 1)[5] = c.toBf16(std.math.nan(f32)); + } + + /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. + fn stress(self: *Attention, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const L = self.shape.k; + var key: [D]u16 = undefined; + for (&key) |*e| e.* = attn.normal(rng); + const col = try a.alloc(f32, L); + defer a.free(col); + for (0..self.heads()) |h| { + for (0..L) |j| @memcpy(self.at(j, 1, h), &key); + for (0..D) |e| { + mirrored(rng, col); + for (col, 0..) |y, j| self.at(j, 2, h)[e] = c.toBf16(y); + } + } + } + + pub fn run(self: *Attention) !void { + var a: cuda.Args = .{}; + a.add(self.dev); + a.add(self.out); + a.add(@as(c_int, @intCast(self.shape.k))); + a.add(@as(c_int, @intCast(self.heads()))); + a.add(scale(self.wide)); + try cuda.launch.launch(self.k.attention, .{ .grid = .{ .x = @intCast((self.shape.k + 127) / 128), .y = @intCast(self.heads()) }, .block = .{ .x = 256 }, .shared = smem }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Attention) usize { + return self.shape.k * self.heads() * D; + } + + /// Output rows [lo, hi) (row-major over sequence row and head) checked against attention_ref on one thread. + const Job = struct { + t: *const Attention, + out: []const u8, + lo: usize, + hi: usize, + gate: g.Gate, + planted: usize = 0, + bad: ?usize = null, // first failing output + ratio: f64 = 0, + + pub fn run(j: *Job) void { + var want: [D]f64 = undefined; + var tol: [D]f64 = undefined; + const t = j.t; + const s: f64 = scale(false); + for (j.lo..j.hi) |i| { + const row = i / t.heads(); + const head = i % t.heads(); + aref.head(t.rows(0, head)[row * D ..][0..D], t.rows(1, head), t.rows(2, head), t.keys, D, s, &want, &tol); + for (want, tol, 0..) |w, tl, e| { + const got = c.read(.bf16, j.out, i * D + e); + if (c.classOf(w) != .finite) j.planted += 1; + const off = c.classOf(got) != c.classOf(w) or (j.gate != .nonfinite and std.math.isFinite(w) and !(@abs(got - w) <= tl)); + if (off and j.bad == null) { + j.bad = i * D + e; + j.ratio = @abs(got - w) / tl; + } + } + if (j.bad != null) return; + } + } + }; + + /// Gates 1 and 3: every output's class equals float64's, and a finite one is within attention_ref's bound. + pub fn check(self: *Attention, gate: g.Gate) !?[]const u8 { + const out = try self.rig.outputBytes(); + const n = self.shape.k * self.heads(); + var jobs: [threads.maximum]Job = undefined; + const parts = threads.count(threads.maximum, n); + for (jobs[0..parts], 0..) |*j, p| j.* = .{ .t = self, .out = out, .lo = n * p / parts, .hi = n * (p + 1) / parts, .gate = gate }; + threads.run(Job, jobs[0..parts], .normal); + var planted: usize = 0; + for (jobs[0..parts]) |j| { + planted += j.planted; + if (j.bad) |b| { + const got = c.read(.bf16, out, b); + return try std.fmt.bufPrint(&self.msg, "output {d} (row {d}, head {d}, dim {d}) is {e:.6}: {t}, {d:.2} of attention_ref's bound", .{ b, b / D / self.heads(), b / D % self.heads(), b % D, got, c.classOf(got), j.ratio }); + } + } + if (gate == .nonfinite and (planted == 0 or planted == n * D)) return try std.fmt.bufPrint(&self.msg, "the planted values make {d} of {d} reference outputs non-finite: no proof", .{ planted, n * D }); + return null; + } + + /// Float64 softmax(s q.k) v of one output row, and its terms' magnitude sum p |v| / sum p. + fn one(self: *const Attention, i: usize, p: []f64, want: []f64, mag: []f64) void { + const row = i / self.heads(); + const head = i % self.heads(); + const q = self.rows(0, head)[row * D ..][0..D]; + const k = self.rows(1, head); + const v = self.rows(2, head); + var m: f64 = -std.math.inf(f64); + for (p, 0..) |*x, j| { + var s: f64 = 0; + for (0..D) |e| s += q[e] * k[j * D + e]; + x.* = s * scale(false); + m = @max(m, x.*); + } + var l: f64 = 0; + for (p) |*x| { + x.* = @exp(x.* - m); + l += x.*; + } + for (0..D) |e| { + var s: f64 = 0; + var abs: f64 = 0; + for (p, 0..) |x, j| { + s += x * v[j * D + e]; + abs += x * @abs(v[j * D + e]); + } + want[i * D + e] = s / l; + mag[i * D + e] = abs / l; + } + } + + /// Gate 4 reads these; under its stress every key scores alike, so a head's rows share one output row. + pub fn reference(self: *Attention, want: []f64, mag: []f64) !void { + const a = self.rig.gpu.gpa; + const p = try a.alloc(f64, self.shape.k); + defer a.free(p); + const n = self.shape.k * self.heads(); + for (0..n) |i| { + if (self.stressed and i >= self.heads()) { + @memcpy(want[i * D ..][0..D], want[(i % self.heads()) * D ..][0..D]); + @memcpy(mag[i * D ..][0..D], mag[(i % self.heads()) * D ..][0..D]); + } else self.one(i, p, want, mag); + } + } + + /// Gate 4's sums in an accumulator: its keys score alike, so every p is 1 and the sums are V's terms and l's ones. + pub fn simulate(self: *Attention, acc: c.Accum, order: g.Order, out: []f64) !void { + if (!self.stressed) return error.SumsNeedStress; + const a = self.rig.gpu.gpa; + const L = self.shape.k; + const terms = try a.alloc(f64, L); + defer a.free(terms); + const ones = try a.alloc(f64, L); + defer a.free(ones); + @memset(ones, 1); + const l = core.contract.rows.sumIn(acc, order, ones); + for (0..self.heads()) |h| for (0..D) |e| { + const v = self.rows(2, h); + for (terms, 0..) |*x, j| x.* = v[j * D + e]; + out[h * D + e] = core.contract.rows.sumIn(acc, order, terms) / l; + }; + for (self.heads()..L * self.heads()) |i| @memcpy(out[i * D ..][0..D], out[(i % self.heads()) * D ..][0..D]); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_experts_grouped.zig b/zig/tests/cuda/contract_inkling2_experts_grouped.zig new file mode 100644 index 00000000000..1d82f7c6a2f --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_grouped.zig @@ -0,0 +1,296 @@ +//! tf_ink2x_rows, tf_ink2x_wide and tf_ink2x_group under the contract: each bit-equal to the main kernel it replaces. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_experts_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +fn i32s(v: usize) i32 { + return @intCast(v); +} + +/// One projection as experts.run launches it, on the lists tf_exl3_group writes; the baseline runs tf_exl3_grouped_2. +pub const Grouped = struct { + rig: rig_.Rig, + k: *const ink.experts.Kernels, + form: ref.Form, + fault: ref.Fault = .none, + fix: ?ref.Fixture = null, + tp: [2]u64 = .{ 0, 0 }, + k2: [2]u64 = .{ 0, 0 }, + x: [2]u64 = .{ 0, 0 }, + uids: u64 = 0, + ucount: u64 = 0, + members: u64 = 0, + items: u64 = 0, + nitems: u64 = 0, + out: u64 = 0, + base: u64 = 0, + msg: [160]u8 = undefined, + + pub fn deinit(self: *Grouped) void { + self.drop(); + self.rig.deinit(); + } + + fn drop(self: *Grouped) void { + if (self.fix) |*f| f.deinit(); + self.fix = null; + self.rig.reset(); + } + + pub fn kernel(self: *Grouped) g.Kernel { + return .{ .spec = ref.spec(self.form, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + } + + const vt = g.hooks(Grouped); + + fn put(self: *Grouped, x: anytype) !u64 { + return self.rig.input(std.mem.sliceAsBytes(x)); + } + + pub fn prepare(self: *Grouped, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!ref.Fixture.valid(shape)) return false; + self.drop(); + const a = self.rig.gpu.gpa; + self.fix = try ref.Fixture.init(a, shape, fill, seed); + const f = &self.fix.?; + var pool: [f.trellis.len]u64 = undefined; + for (&pool, f.trellis) |*p, t| p.* = try self.put(t); + const m = ref.mats(shape); + for (0..2) |mat| { + var tp: [ref.experts]u64 = undefined; + var k2: [ref.experts]i32 = undefined; + for (&tp, &k2, 0..) |*t, *h, e| { + const i = ref.Fixture.entry(e, @min(mat, m - 1)); + t.* = pool[i]; + h.* = ref.halves(i); + } + self.tp[mat] = try self.put(&tp); + self.k2[mat] = try self.put(&k2); + } + const p = f.pairs(); + const xs = p * shape.k; + self.x[0] = try self.put(f.x[0..xs]); + self.x[1] = if (m == 2) try self.put(f.x[xs..]) else self.x[0]; + var l = try ref.Lists.init(a, f.pick, shape.rows); + defer l.deinit(a); + self.uids = try self.put(l.uids); + self.ucount = try self.put(&[1]i32{l.count}); + self.members = try self.put(l.members); + const items = try a.alloc(i32, 3 * ref.maxItems(p)); + defer a.free(items); + const n = l.items(shape.rows, ref.per(self.form), items); + self.items = try self.put(items); + const listed = ref.listed(self.form, shape.rows); + const short: i32 = @intFromBool(self.fault == .short); + self.nitems = try self.put(&[1]i32{(if (listed) n else l.count) - short}); + self.out = try self.rig.output(f.outputs() * 4); + self.base = try self.rig.scratch(f.outputs() * 4); + return true; + } + + /// experts.zig's launch: WideArgs in its add order, items and their count (rows kernel below 17 rows: the groups). + fn launch(self: *Grouped) !void { + const sh = self.fix.?.shape; + const p = self.fix.?.pairs(); + const sk = self.fix.?.sk; + const listed = ref.listed(self.form, sh.rows); + const per = ref.per(self.form); + const x0 = if (self.fault == .swapped) self.x[1] else self.x[0]; + var a: cuda.Args = .{}; + for ([_]u64{ x0, self.x[1], self.tp[0], self.tp[1], self.k2[0], self.k2[1], self.uids, if (listed) self.items else 0, self.nitems, self.members, self.out }) |v| a.add(v); + for ([_]usize{ sh.k, sh.n, p, sk, sh.rows, ref.slots }) |v| a.add(i32s(v)); + const maxu = @min(p, ref.experts); + const gy = if (listed) (p + per - 1) / per + maxu else maxu; + const cols: usize = if (self.form == .wide) 64 else 128; + const f = if (self.form == .wide) self.k.wide else self.k.rows; + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(sh.n / cols), .y = @intCast(gy), .z = @intCast(ref.mats(sh) * sk) }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + pub fn run(self: *Grouped) !void { + try self.launch(); + try self.rig.s.synchronize(); + } + + /// exl3_experts.Experts.run's grouped launch on the same lists: GroupedArgs, one member tile a grid z step. + pub fn replaced(self: *Grouped) ![]const u8 { + const sh = self.fix.?.shape; + const p = self.fix.?.pairs(); + const sk = self.fix.?.sk; + const maxu = @min(p, ref.experts); + const m = ref.mats(sh); + var a: cuda.Args = .{}; + for ([_]u64{ self.x[0], self.x[1], self.tp[0], self.tp[1], self.k2[0], self.k2[1], self.uids, self.ucount, self.members, self.base }) |v| a.add(v); + for ([_]usize{ sh.k, sh.n, p, sk, sh.rows, ref.slots, maxu, m, 0, 0 }) |v| a.add(i32s(v)); + a.add(@as(i32, -1)); + const mt = (sh.rows + 15) / 16; + try cuda.launch.launch(self.k.main.grouped[2], .{ .grid = .{ .x = @intCast(maxu), .y = @intCast(sh.n / 128), .z = @intCast(m * sk * mt) }, .block = .{ .x = 128 } }, self.rig.s, &a); + return self.rig.bytes(self.base, self.outputs() * 4); + } + + /// Gate 1: tf_exl3_grouped_2's bytes, and some output non-finite: the planted values. + pub fn check(self: *Grouped, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + const want = try self.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&self.msg, "byte {d} of {d} differs from tf_exl3_grouped_2's", .{ at, got.len }); + for (0..got.len / 4) |i| if (c.classOf(c.read(.f32, got, i)) != .finite) return null; + return try std.fmt.bufPrint(&self.msg, "no output is non-finite: the planted values prove nothing", .{}); + } + + fn outputs(self: *Grouped) usize { + return self.fix.?.outputs(); + } + + pub fn count(self: *Grouped) usize { + return self.outputs(); + } + + pub fn reference(self: *Grouped, want: []f64, mag: []f64) !void { + return self.fix.?.reference(want, mag); + } + + pub fn simulate(self: *Grouped, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.fix.?.simulate(acc, order, out); + } +}; + +/// Shape: token rows x slots (8) x experts (384); short calls pad members with -1, longer ones list item runs. +fn groupSpec(control: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 8, .n = ref.slots, .k = ref.experts }, .{ .rows = 1, .n = ref.slots, .k = ref.experts }, .{ .rows = 15, .n = ref.slots, .k = ref.experts }, .{ .rows = 16, .n = ref.slots, .k = ref.experts }, .{ .rows = 17, .n = ref.slots, .k = ref.experts }, .{ .rows = 128, .n = ref.slots, .k = ref.experts }, .{ .rows = 511, .n = ref.slots, .k = ref.experts }, .{ .rows = 512, .n = ref.slots, .k = ref.experts }, .{ .rows = 2048, .n = ref.slots, .k = ref.experts } }; + const name = if (control) "inkling2 experts control: tf_ink2x_group listing 16-member runs for the prompt kernel" else "inkling2 experts tf_ink2x_group (tf_exl3_group's lists, then item runs)"; + return .{ .name = name, .accum = .none, .depth = noSums, .out = .raw, .replaces = "tf_exl3_group (main's grouping), the runs its counts give", .nan = .{ .stated = "picks outside [0, experts) are left out, as tf_exl3_group leaves them" }, .tiles = .{ .{ .size = 16 }, .{}, .{} }, .served = served }; +} + +fn noSums(_: c.Shape) usize { + return 0; +} + +/// tf_ink2x_group as experts.run launches it; the baseline runs tf_exl3_group and adds the runs on the host. +pub const Group = struct { + rig: rig_.Rig, + k: *const ink.experts.Kernels, + wrong_run: bool = false, + shape: c.Shape = undefined, + pick: []i32 = &.{}, + dev: u64 = 0, + outs: [5]u64 = @splat(0), // uids, count, members, items, item count + base: [3]u64 = @splat(0), + want: std.ArrayList(u8) = .empty, + msg: [160]u8 = undefined, + + pub fn deinit(self: *Group) void { + const a = self.rig.gpu.gpa; + a.free(self.pick); + self.want.deinit(a); + self.rig.deinit(); + } + + pub fn kernel(self: *Group) g.Kernel { + return .{ .spec = groupSpec(self.wrong_run), .ctx = self, .vt = &vt, .control = if (self.wrong_run) .shapes else null }; + } + + const vt = g.hooks(Group); + + fn maxu(self: *const Group) usize { + return @min(self.shape.rows * ref.slots, ref.experts); + } + + fn sizes(self: *const Group) [5]usize { + const p = self.shape.rows * ref.slots; + return .{ self.maxu() * 4, 4, self.maxu() * self.shape.rows * 4, 3 * ref.maxItems(p) * 4, 4 }; + } + + pub fn prepare(self: *Group, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != ref.slots or shape.k != ref.experts or shape.rows * shape.n * 4 > 64 * 1024) return false; + self.rig.reset(); + const a = self.rig.gpu.gpa; + self.shape = shape; + a.free(self.pick); + self.pick = &.{}; + self.pick = try a.alloc(i32, shape.rows * ref.slots); + var prng = std.Random.DefaultPrng.init(seed); + ref.picks(prng.random(), self.pick); + if (fill == .nonfinite) { + const put = [_]i32{ -1, ref.experts, 1 << 20 }; + for (put, 0..) |v, i| self.pick[(i * 5 + 1) % self.pick.len] = v; + } + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.pick)); + for (&self.outs, self.sizes()) |*o, n| o.* = try self.rig.output(n); + for (&self.base, self.sizes()[0..3]) |*o, n| o.* = try self.rig.scratch(n); + return true; + } + + pub fn run(self: *Group) !void { + const rows = self.shape.rows; + const listed = rows >= ink.experts.listed_from; + const run_: usize = if (rows >= ink.experts.wide_from and !self.wrong_run) 32 else 16; + var b: cuda.Args = .{}; + for ([_]u64{ self.dev, self.outs[0], self.outs[1], self.outs[2], self.outs[3], self.outs[4] }) |v| b.add(v); + for ([_]usize{ rows, ref.slots, ref.experts, rows, if (listed) run_ else 0, @intFromBool(!listed) }) |v| b.add(i32s(v)); + const shared: u32 = @intCast(ref.experts * (32 * 2 + 2 * 4)); + try cuda.launch.launch(self.k.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = shared }, self.rig.s, &b); + try self.rig.s.synchronize(); + } + + /// tf_exl3_group's lists as written, words no launch writes as the rig poisons them, and the runs from its counts. + pub fn replaced(self: *Group) ![]const u8 { + const a = self.rig.gpu.gpa; + const rows = self.shape.rows; + var m: cuda.Args = .{}; + for ([_]u64{ self.dev, self.base[0], self.base[1], self.base[2] }) |v| m.add(v); + for ([_]usize{ rows, ref.slots, ref.experts, rows }) |v| m.add(i32s(v)); + try cuda.launch.launch(self.k.main.group, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 }, .shared = @intCast(rows * ref.slots * 4) }, self.rig.s, &m); + const sz = self.sizes(); + self.want.clearRetainingCapacity(); + try self.want.appendNTimes(a, 0xff, sz[0] + sz[1] + sz[2] + sz[3] + sz[4]); + const w = self.want.items; + const cnt = std.mem.readInt(i32, (try self.rig.bytes(self.base[1], 4))[0..4], .little); + if (cnt < 0 or @as(usize, @intCast(cnt)) > self.maxu()) return error.BadBaselineCount; + const used: usize = @intCast(cnt); + @memcpy(w[0 .. used * 4], (try self.rig.bytes(self.base[0], sz[0]))[0 .. used * 4]); + std.mem.writeInt(i32, w[sz[0]..][0..4], cnt, .little); + const mem = w[sz[0] + 4 ..][0..sz[2]]; + @memcpy(mem[0 .. used * rows * 4], (try self.rig.bytes(self.base[2], sz[2]))[0 .. used * rows * 4]); + if (rows >= ink.experts.listed_from) { + const members = try a.alloc(i32, sz[2] / 4); + defer a.free(members); + @memcpy(std.mem.sliceAsBytes(members), mem); + const l: ref.Lists = .{ .uids = &.{}, .count = cnt, .members = members }; + const items = try a.alloc(i32, sz[3] / 4); + defer a.free(items); + const n = l.items(rows, if (rows >= ink.experts.wide_from) 32 else 16, items); + const start = sz[0] + 4 + sz[2]; + for (items, 0..) |v, i| if (v >= 0) std.mem.writeInt(i32, w[start + 4 * i ..][0..4], v, .little); + std.mem.writeInt(i32, w[start + sz[3] ..][0..4], n, .little); + } + return w; + } + + /// Gate 1: the baseline's bytes with picks outside the experts planted. + pub fn check(self: *Group, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + const want = try self.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&self.msg, "byte {d} of {d} differs from tf_exl3_group's lists and their runs", .{ at, got.len }); + return null; + } + + pub fn count(self: *Group) usize { + var n: usize = 0; + for (self.sizes()) |s| n += s; + return n; + } + + pub fn reference(_: *Group, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_experts_ref.zig b/zig/tests/cuda/contract_inkling2_experts_ref.zig new file mode 100644 index 00000000000..9549c2b112e --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_ref.zig @@ -0,0 +1,293 @@ +//! Inkling 2's grouped experts on the host: specs, Inkling's routing and trellises, float64 sums, replays. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); + +const fmt = core.exl3_format; +const c = core.contract.spec; +const rows_ = core.contract.rows; + +pub const experts = 384; +pub const slots = 8; // top 8 +pub const hidden = 4608; +pub const width = 1152; // a rank's intermediate at TP=2: 2304 cut in 128-column blocks +const pool = 16; // distinct trellises a shape: expert e's gate takes pool[e % 16], its up pool[(7e + 3) % 16] +const warps = 4; // wide_body's W +const step: f32 = 256; // gate 4's x: multiples of 256 to 8,192, so fp16 sums of the products overflow + +/// The served kernels: decode rows and short windows (128 columns, 16 members), prompt chunks (64 columns, 32). +pub const Form = enum { rows, wide }; +/// Gate 3's planted faults, both launch arguments: the call's last item dropped, the up rows read as gate rows. +pub const Fault = enum { none, short, swapped }; + +/// Half-bits a value of pool entry i: the release's 2- and 3-bit trellises in turn. +pub fn halves(i: usize) u16 { + return if (i % 2 == 0) 4 else 6; +} + +/// exl3_experts.plan's K splits as experts.run takes them: gate and up where K > N, down otherwise. +pub fn split(s: c.Shape) usize { + return cuda.exl3_experts.plan(s.k, s.n, s.k > s.n) catch 1; +} + +/// Gate and up (two matrices, K > N), or down (one). +pub fn mats(s: c.Shape) usize { + return if (s.k > s.n) 2 else 1; +} + +/// Whether a call takes an item list: the prompt kernel always, the rows kernel from experts.listed_from rows. +pub fn listed(form: Form, rows: usize) bool { + return form == .wide or rows >= ink.experts.listed_from; +} + +/// Members a run: the prompt kernel's 32, the rows kernel's 16. +pub fn per(form: Form) usize { + return if (form == .wide) 32 else 16; +} + +/// Items experts.zig makes room for: runs of 16 members, plus one partial run a distinct expert. +pub fn maxItems(p: usize) usize { + return (p + 15) / 16 + @min(p, experts); +} + +/// A split's 16-input mma steps, the 16 products inside one, then the 4 warps' partials added in warp order. +fn depth(s: c.Shape) usize { + return s.k / split(s) / 16 + 16 + warps; +} + +fn served(rows: []const usize, comptime n: usize) [2 * n]c.Shape { + var out: [2 * n]c.Shape = undefined; + for (rows[0..n], 0..) |r, i| { + out[2 * i] = .{ .rows = r, .n = width, .k = hidden }; + out[2 * i + 1] = .{ .rows = r, .n = hidden, .k = width }; + } + return out; +} + +const rows_served = served(&.{ 8, 1, 15, 16, 17, 128, 511 }, 7); +const wide_served = served(&.{ 512, 513, 2048 }, 3); +const rule = "as tf_exl3_grouped_2 gives them: NaN and infinite inputs"; + +pub fn spec(form: Form, fault: Fault) c.Spec { + const name = switch (fault) { + .none => if (form == .rows) "inkling2 experts tf_ink2x_rows (decode rows to 511, 128 columns by 16 members)" else "inkling2 experts tf_ink2x_wide (prompt chunks from 512, 64 columns by 32 members)", + .short => "inkling2 experts control: tf_ink2x_rows launched one item short", + .swapped => "inkling2 experts control: tf_ink2x_wide reading the up rows as gate rows", + }; + const edge: c.Tile = if (form == .rows) .{ .size = 16 } else .{ .size = ink.experts.wide_from, .min = ink.experts.wide_from }; + const tiles = [3]c.Tile{ edge, .{ .size = 128, .step = 128, .min = 128 }, .{ .size = 256, .step = 64, .min = 64 } }; + const list: []const c.Shape = if (form == .rows) &rows_served else &wide_served; + return .{ .name = name, .accum = .f32, .depth = depth, .out = .f32, .replaces = "tf_exl3_grouped_2 (main's grouped experts, mul1)", .nan = .{ .stated = rule }, .tiles = tiles, .served = list, .sums = .{ .exact = false } }; +} + +/// Each row's 8 distinct experts: expert 0 in every row (long runs and a partial one), the rest at random. +pub fn picks(rng: std.Random, out: []i32) void { + for (0..out.len / slots) |r| { + const row = out[r * slots ..][0..slots]; + row[0] = 0; + var i: usize = 1; + while (i < slots) { + const e: i32 = @intCast(rng.uintLessThan(u32, experts)); + if (std.mem.indexOfScalar(i32, row[0..i], e) != null) continue; + row[i] = e; + i += 1; + } + } +} + +/// One projection's host side: the pool's trellises, the pairs' fp16 rows per matrix, each pair's expert. +pub const Fixture = struct { + a: std.mem.Allocator, + shape: c.Shape, + sk: usize, + trellis: [pool][]i16, + x: []u16, // fp16 bits [mats][pairs][k], the rotated rows + pick: []i32, // [pairs]: pair p = row * slots + slot + w: [pool][]f16 = @splat(@as([]f16, &.{})), // each entry's W_q [k][n], decoded on first use + + /// false: a shape the kernels are not built for (plan() finds no split, N not a whole number of 128s). + pub fn valid(s: c.Shape) bool { + if (s.rows == 0 or s.n == 0 or s.k == 0 or s.n % 128 != 0) return false; + _ = cuda.exl3_experts.plan(s.k, s.n, s.k > s.n) catch return false; + return true; + } + + pub fn init(a: std.mem.Allocator, s: c.Shape, fill: rows_.Fill, seed: u64) !Fixture { + var f: Fixture = .{ .a = a, .shape = s, .sk = split(s), .trellis = @splat(@as([]i16, &.{})), .x = &.{}, .pick = &.{} }; + errdefer f.deinit(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (&f.trellis, 0..) |*t, i| { + t.* = try a.alloc(i16, s.k / 16 * (s.n / 16) * @as(usize, halves(i)) * 8); + for (t.*) |*v| v.* = rng.int(i16); + } + const p = f.pairs(); + f.pick = try a.alloc(i32, p); + picks(rng, f.pick); + f.x = try a.alloc(u16, mats(s) * p * s.k); + for (f.x) |*v| v.* = bits(rng.float(f32) * 4 - 2); + switch (fill) { + .random => {}, + .nonfinite => { + const k = s.k; + const at = [_][2]usize{ .{ 0, k / 3 }, .{ 1, k / 2 }, .{ 2, k - 1 }, .{ 3, 0 }, .{ 3, k - 1 } }; + const put = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32), std.math.inf(f32), -std.math.inf(f32) }; + for (at, put) |q, v| if (q[0] < p) { + f.x[q[0] * k + q[1]] = bits(v); + }; + }, + .stress => for (f.x) |*v| { + v.* = bits(step * @as(f32, @floatFromInt(1 + rng.uintLessThan(u32, 32)))); + }, + } + return f; + } + + pub fn deinit(f: *Fixture) void { + for (f.trellis) |t| f.a.free(t); + for (f.w) |w| f.a.free(w); + f.a.free(f.x); + f.a.free(f.pick); + f.* = undefined; + } + + pub fn pairs(f: *const Fixture) usize { + return f.shape.rows * slots; + } + + pub fn outputs(f: *const Fixture) usize { + return mats(f.shape) * f.sk * f.pairs() * f.shape.n; + } + + /// The pool entry matrix `mat` of expert e reads. + pub fn entry(e: usize, mat: usize) usize { + return if (mat == 0) e % pool else (7 * e + 3) % pool; + } + + fn weights(f: *Fixture, i: usize) ![]const f16 { + if (f.w[i].len > 0) return f.w[i]; + const s = f.shape; + f.w[i] = try f.a.alloc(f16, s.k * s.n); + fmt.unpack(.{ .halves = halves(i) }, .mul1, f.trellis[i], s.k / 16, s.n / 16, f.w[i]); + return f.w[i]; + } + + /// The terms output (mat, split, pair, column) sums: x times W_q over the split's K range, in K order. + fn terms(f: *Fixture, mat: usize, sp: usize, p: usize, j: usize, t: []f64) !void { + const s = f.shape; + const e: usize = @intCast(f.pick[p]); + const w = try f.weights(entry(e, mat)); + const per_split = s.k / f.sk; + const x = f.x[(mat * f.pairs() + p) * s.k ..]; + for (t, sp * per_split..) |*o, i| o.* = value(x[i]) * @as(f64, w[i * s.n + j]); + } + + fn each(f: *Fixture, ctx: anytype, comptime body: fn (@TypeOf(ctx), usize, []const f64) void) !void { + const t = try f.a.alloc(f64, f.shape.k / f.sk); + defer f.a.free(t); + for (0..mats(f.shape)) |mat| for (0..f.sk) |sp| for (0..f.pairs()) |p| for (0..f.shape.n) |j| { + try f.terms(mat, sp, p, j, t); + body(ctx, (((mat * f.sk) + sp) * f.pairs() + p) * f.shape.n + j, t); + }; + } + + pub fn reference(f: *Fixture, want: []f64, mag: []f64) !void { + const Ctx = struct { want: []f64, mag: []f64 }; + try f.each(Ctx{ .want = want, .mag = mag }, struct { + fn body(x: Ctx, o: usize, t: []const f64) void { + var sum: f64 = 0; + var abs: f64 = 0; + for (t) |v| { + sum += v; + abs += @abs(v); + } + x.want[o] = sum; + x.mag[o] = abs; + } + }.body); + } + + pub fn simulate(f: *Fixture, acc: c.Accum, order: rows_.Order, out: []f64) !void { + const Ctx = struct { acc: c.Accum, order: rows_.Order, out: []f64 }; + try f.each(Ctx{ .acc = acc, .order = order, .out = out }, struct { + fn body(x: Ctx, o: usize, t: []const f64) void { + x.out[o] = rows_.sumIn(x.acc, x.order, t); + } + }.body); + } +}; + +/// The lists tf_exl3_group writes for `pick`: distinct experts in id order, members row * 32 + slot, -1 after them. +pub const Lists = struct { + uids: []i32, + count: i32, + members: []i32, // [min(pairs, experts)][rows] + + pub fn init(a: std.mem.Allocator, pick: []const i32, rows: usize) !Lists { + const maxu = @min(pick.len, experts); + const uids = try a.alloc(i32, maxu); + errdefer a.free(uids); + const members = try a.alloc(i32, maxu * rows); + @memset(members, -1); + var used: usize = 0; + for (0..experts) |e| { + var m: usize = 0; + for (pick, 0..) |pe, p| if (pe == e) { + members[used * rows + m] = @intCast(p / slots * 32 + p % slots); + m += 1; + }; + if (m == 0) continue; + uids[used] = @intCast(e); + used += 1; + } + return .{ .uids = uids, .count = @intCast(used), .members = members }; + } + + pub fn deinit(l: *Lists, a: std.mem.Allocator) void { + a.free(l.uids); + a.free(l.members); + } + + /// tf_ink2x_group's items for runs of `run` members: (u, first, count) in expert order, -1 words after them. + pub fn items(l: Lists, rows: usize, run: usize, out: []i32) i32 { + @memset(out, -1); + var n: usize = 0; + for (0..@intCast(l.count)) |u| { + const m = l.members[u * rows ..][0..rows]; + const cnt = std.mem.indexOfScalar(i32, m, -1) orelse rows; + var first: usize = 0; + while (first < cnt) : (first += run) { + out[3 * n ..][0..3].* = .{ @intCast(u), @intCast(first), @intCast(@min(run, cnt - first)) }; + n += 1; + } + } + return @intCast(n); + } +}; + +fn bits(v: f32) u16 { + return @bitCast(@as(f16, @floatCast(v))); +} + +fn value(h: u16) f64 { + return @as(f16, @bitCast(h)); +} + +test "inkling2 experts contract: every served shape has a split, items fit experts.zig's room" { + for (rows_served ++ wide_served) |s| { + try std.testing.expect(Fixture.valid(s)); + try std.testing.expectEqual(@as(usize, 0), s.k % (split(s) * 16 * warps)); + } + try std.testing.expectEqual(@as(usize, 4), split(rows_served[0])); + var prng = std.Random.DefaultPrng.init(1); + const pick = try std.testing.allocator.alloc(i32, 2048 * slots); + defer std.testing.allocator.free(pick); + picks(prng.random(), pick); + var l = try Lists.init(std.testing.allocator, pick, 2048); + defer l.deinit(std.testing.allocator); + const out = try std.testing.allocator.alloc(i32, 3 * maxItems(pick.len)); + defer std.testing.allocator.free(out); + try std.testing.expect(l.items(2048, 16, out) <= maxItems(pick.len)); + try std.testing.expectEqual(@as(i32, 0), l.uids[0]); +} diff --git a/zig/tests/cuda/contract_inkling2_experts_vision.zig b/zig/tests/cuda/contract_inkling2_experts_vision.zig new file mode 100644 index 00000000000..976a8ce7448 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_experts_vision.zig @@ -0,0 +1,275 @@ +//! Inkling 2's tower glue (vision.cu) under the contract: patch rows to the sequence, axial rotary, layer-scaled adds. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; +const Kernels = ink.vision.Kernels; + +const width = ink.vision.width; +const qkv_width = 3 * width; +const pairs = ink.vision.head_dim / 2; +const grid = 1024; // the position table's rows (32 x 32) + +/// Sequence rows R = 4 T + 1 (the class row, then four patches a token): 1, 4, 256, 1,024 and 4,096 tokens. +fn tower(comptime n: usize, comptime k: usize) [5]c.Shape { + var out: [5]c.Shape = undefined; + for (&out, [_]usize{ 17, 5, 1025, 4097, 16385 }) |*s, r| s.* = .{ .rows = r, .n = n, .k = k }; + return out; +} + +const embed_served = tower(width, 4); +const rope_served = tower(qkv_width, 1); +const add_served = tower(width, 1); + +fn four(_: c.Shape) usize { + return 4; +} + +fn launch(f: cuda.Function, s: cuda.Stream, blocks: usize, args: []const u64, tail: ?i64) !void { + var a: cuda.Args = .{}; + for (args) |v| a.add(v); + if (tail) |t| a.add(t); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(blocks) }, .block = .{ .x = 256 } }, s, &a); +} + +/// Row 0 bf16(cls + cls_pos); row r bf16(pe + bf16(sum of four table rows times their bilinear weights, in fp32)). +pub const Embed = struct { + kern: *const Kernels, + late: bool = false, // control: each weight read one tap late + shape: c.Shape = undefined, + pe: []u16 = &.{}, + table: []u16 = &.{}, + taps: []u32 = &.{}, + wts: []f32 = &.{}, + cls: []u16 = &.{}, + pos: []u16 = &.{}, + dev: [6]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Embed) c.Spec { + const name = if (self.late) "inkling2 experts control: tf_ink2v_embed reading each weight one tap late" else "inkling2 experts vision tf_ink2v_embed (class row, patches plus resampled positions)"; + return .{ .name = name, .accum = .f32, .depth = four, .out = .bf16, .served = &embed_served, .sums = .{ .f16 = 0, .bf16 = 0, .why = "four taps a value, rounded to bf16: no sum long enough to tell fp32 from half" } }; + } + + pub fn control(self: *const Embed) ?g.Gate { + return if (self.late) .shapes else null; + } + + pub fn free(self: *Embed, a: std.mem.Allocator) void { + inline for (.{ "pe", "table", "taps", "wts", "cls", "pos" }) |f| { + a.free(@field(self, f)); + @field(self, f) = &.{}; + } + } + + pub fn prepare(self: *Embed, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows < 2 or shape.n != width or shape.k != 4) return false; + self.free(a); + self.shape = shape; + const p = shape.rows - 1; + const stress = fill == .stress; + self.pe = try ref.bfs(a, rng, p * width, -2, 2); + self.table = try ref.bfs(a, rng, grid * width, -1, 1); + self.cls = try ref.bfs(a, rng, width, -1, 1); + self.pos = try ref.bfs(a, rng, width, -1, 1); + self.taps = try a.alloc(u32, p * 4); + self.wts = try a.alloc(f32, p * 4); + for (0..p) |i| { + const x = rng.float(f32); + const y = rng.float(f32); + self.wts[4 * i ..][0..4].* = if (stress) .{ ref.int(rng, 0, 3), ref.int(rng, 0, 3), ref.int(rng, 0, 3), ref.int(rng, 0, 3) } else .{ (1 - x) * (1 - y), x * (1 - y), (1 - x) * y, x * y }; + for (self.taps[4 * i ..][0..4]) |*t| t.* = rng.uintLessThan(u32, grid); + } + if (stress) for ([_][]u16{ self.pe, self.table, self.cls, self.pos }) |v| { + for (v) |*e| e.* = c.toBf16(ref.int(rng, -8, 8)); + }; + if (fill == .nonfinite) { + self.pe[3] = c.toBf16(ref.nan); // patch 0 + self.table[self.taps[4] * width + 5] = c.toBf16(ref.inf); // every patch that taps patch 1's first row + self.cls[7] = c.toBf16(-ref.inf); + if (p > 2) self.pe[2 * width + 9] = c.toBf16(-ref.inf); + } + self.dev = .{ try ref.input(rig, self.pe), try ref.input(rig, self.table), try ref.input(rig, self.taps), try ref.input(rig, self.wts), try ref.input(rig, self.cls), try ref.input(rig, self.pos) }; + self.out = try rig.output(shape.rows * width * 2); + return true; + } + + pub fn run(self: *Embed, rig: *rig_.Rig) !void { + const d = self.dev; + try launch(self.kern.embed, rig.s, self.shape.rows, &.{ d[0], d[1], d[2], d[3] + @as(u64, if (self.late) 4 else 0), d[4], d[5], self.out }, null); + } + + pub fn count(self: *const Embed) usize { + return self.shape.rows * width; + } + + pub fn solve(self: *const Embed, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + var terms: [4]Iv = undefined; + var scratch: [4]f64 = undefined; + for (0..width) |e| out[e] = Iv.of(ref.bf(self.cls[e])).add(Iv.of(ref.bf(self.pos[e]))).bf(); + for (1..self.shape.rows) |r| for (0..width) |e| { + const p = r - 1; + for (&terms, 0..) |*t, i| t.* = Iv.of(ref.bf(self.table[self.taps[4 * p + i] * width + e])).mul(Iv.of(self.wts[4 * p + i])); + const pos = s.sum(&terms, 4, &scratch).bf(); + out[r * width + e] = Iv.of(ref.bf(self.pe[p * width + e])).add(pos).bf(); + }; + } +}; + +/// q and k heads of qkv [R, 3 x 1024] turned in place, pair (2j, 2j + 1) of each head by fp32 cos and sin of row r. +pub const Rope = struct { + kern: *const Kernels, + swapped: bool = false, // control: cos and sin swapped + shape: c.Shape = undefined, + qkv: []u16 = &.{}, + cs: []f32 = &.{}, + sn: []f32 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Rope) c.Spec { + const name = if (self.swapped) "inkling2 experts control: tf_ink2v_rope with cos and sin swapped" else "inkling2 experts vision tf_ink2v_rope (2D rotary of q and k, in place)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .in_place = true, .served = &rope_served }; + } + + pub fn control(self: *const Rope) ?g.Gate { + return if (self.swapped) .shapes else null; + } + + pub fn free(self: *Rope, a: std.mem.Allocator) void { + a.free(self.qkv); + a.free(self.cs); + a.free(self.sn); + self.qkv = &.{}; + self.cs = &.{}; + self.sn = &.{}; + } + + pub fn prepare(self: *Rope, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != qkv_width) return false; + self.free(a); + self.shape = shape; + const r = shape.rows; + self.qkv = try ref.bfs(a, rng, r * qkv_width, -3, 3); + self.cs = try a.alloc(f32, r * pairs); + self.sn = try a.alloc(f32, r * pairs); + for (self.cs, self.sn) |*x, *y| { + const angle = rng.float(f32) * 64; + x.* = @cos(angle); + y.* = @sin(angle); + } + if (fill == .nonfinite) { + self.qkv[3] = c.toBf16(ref.nan); // row 0, q head 0, pair 1's second value + self.qkv[qkv_width + width + 64 + 10] = c.toBf16(ref.inf); // row 1, k head 1 + self.qkv[2 * qkv_width + 2 * width + 5] = c.toBf16(-ref.inf); // row 2, v: as it is + if (r > 3) self.qkv[3 * qkv_width + 63] = c.toBf16(-ref.inf); + } + self.dev = .{ try ref.input(rig, self.cs), try ref.input(rig, self.sn) }; + self.out = try rig.output(self.qkv.len * 2); + return true; + } + + pub fn run(self: *Rope, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.qkv)); // in place: every run from the same rows + const cs = if (self.swapped) self.dev[1] else self.dev[0]; + const sn = if (self.swapped) self.dev[0] else self.dev[1]; + try launch(self.kern.rope, rig.s, self.shape.rows, &.{ self.out, cs, sn }, null); + } + + pub fn count(self: *const Rope) usize { + return self.qkv.len; + } + + pub fn solve(self: *const Rope, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.qkv, 0..) |*o, x, at| { + const col = at % qkv_width; + if (col >= 2 * width) { + o.* = Iv.of(ref.bf(x)); + continue; + } + const d = col % 64; + const first = at - d % 2; + const r = at / qkv_width; + const cv = Iv.of(self.cs[r * pairs + d / 2]); + const sv = Iv.of(self.sn[r * pairs + d / 2]); + const av = Iv.of(ref.bf(self.qkv[first])); + const bv = Iv.of(ref.bf(self.qkv[first + 1])); + o.* = (if (d % 2 == 0) av.mul(cv).add(bv.neg().mul(sv)) else bv.mul(cv).add(av.mul(sv))).bf(); + } + } +}; + +/// x = bf16(x + bf16(gamma[i % 1024] y)) over [R, 1024] in place: torch's `residual + lambda * h` in bf16. +pub const ScaleAdd = struct { + kern: *const Kernels, + late: bool = false, // control: gamma read one column late + shape: c.Shape = undefined, + x: []u16 = &.{}, + y: []u16 = &.{}, + gamma: []u16 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const ScaleAdd) c.Spec { + const name = if (self.late) "inkling2 experts control: tf_ink2v_scale_add reading gamma one column late" else "inkling2 experts vision tf_ink2v_scale_add (layer-scaled residual add, in place)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .in_place = true, .served = &add_served }; + } + + pub fn control(self: *const ScaleAdd) ?g.Gate { + return if (self.late) .shapes else null; + } + + pub fn free(self: *ScaleAdd, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.y); + a.free(self.gamma); + self.x = &.{}; + self.y = &.{}; + self.gamma = &.{}; + } + + pub fn prepare(self: *ScaleAdd, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != width) return false; + self.free(a); + self.shape = shape; + const n = shape.rows * width; + self.x = try ref.bfs(a, rng, n, -4, 4); + self.y = try ref.bfs(a, rng, n, -4, 4); + self.gamma = try ref.bfs(a, rng, width, -0.5, 0.5); + if (fill == .nonfinite) { + self.x[0] = c.toBf16(ref.nan); + self.y[1] = c.toBf16(ref.inf); + self.gamma[2] = c.toBf16(-ref.inf); // column 2 of every row + self.x[width + 3] = c.toBf16(ref.inf); + } + self.dev = .{ try ref.input(rig, self.y), try ref.input(rig, self.gamma) }; + self.out = try rig.output(n * 2); + return true; + } + + pub fn run(self: *ScaleAdd, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.x)); + const n = self.count(); + try launch(self.kern.scale_add, rig.s, (n + 255) / 256, &.{ self.out, self.dev[0], self.dev[1] + @as(u64, if (self.late) 2 else 0) }, @intCast(n)); + } + + pub fn count(self: *const ScaleAdd) usize { + return self.shape.rows * width; + } + + pub fn solve(self: *const ScaleAdd, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + for (out, self.x, self.y, 0..) |*o, x, y, i| { + const scaled = Iv.of(ref.bf(self.gamma[i % width])).mul(Iv.of(ref.bf(y))).bf(); + o.* = Iv.of(ref.bf(x)).add(scaled).bf(); + } + } +}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math.zig b/zig/tests/cuda/contract_inkling2_loop_math.zig new file mode 100644 index 00000000000..bef2f7d69ef --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_loop_math.zig @@ -0,0 +1,479 @@ +//! Mini loop math under the contract, with independent host arithmetic and planted single-fault controls. +const std = @import("std"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_ops_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const lm = ink.loop_math_cuda; +pub const eps = ref.eps; +pub const mini_h = 2304; + +/// Exact raw-output checks, with interval references and accumulator simulations for gate 4. +pub fn Checked(comptime T: type) type { + return struct { + const Self = @This(); + inner: ref.Gated(T), + rig: *rig_.Rig = undefined, + msg: [200]u8 = undefined, + + pub fn deinit(self: *Self) void { + self.inner.deinit(); + } + + pub fn kernel(self: *Self) g.Kernel { + self.rig = &self.inner.rig; + return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; + } + + const vt = g.hooks(Self); + + pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + return self.inner.prepare(shape, fill, seed); + } + + pub fn run(self: *Self) !void { + try self.inner.run(); + } + + pub fn count(self: *Self) usize { + return self.inner.count(); + } + + pub fn reference(self: *Self, want: []f64, mag: []f64) !void { + try self.inner.reference(want, mag); + } + + pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { + try self.inner.bounds(want, mag, allow); + } + + pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.inner.simulate(acc, order, out); + } + + pub fn check(self: *Self, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + return self.inner.k.check(a, got, &self.msg); + } + }; +} + +pub fn queryScale(cols: usize) ref.Iv { + return if (cols == mini_h) ref.Iv.of(scale(cols)) else ref.Iv.of(@floatFromInt(cols)).rsqrt(); +} + +pub fn softmax(logits: []ref.Iv) void { + var m = logits[0]; + for (logits[1..]) |v| m = .{ .m = @max(m.m, v.m), .lo = @max(m.lo, v.lo), .hi = @max(m.hi, v.hi) }; + var den = ref.Iv.of(0); + for (logits) |*v| { + v.* = v.sub(m).exp(); + den = den.add(v.*); + } + for (logits) |*v| v.* = v.div(den); +} + +/// Irregular integer squares stay exact in FP32 for gate 4, but overflow FP16 and round in every BF16 order. +fn stressBank(i: usize) f32 { + return if ((i * 37 + i / 7) % 5 == 0) 384 else 256; +} + +/// Messages nearly cancel two normalized banks; the unmatched first tap keeps FP16 normalization overflow visible. +fn messageStressBank(bank: usize, col: usize, cols: usize) f32 { + if (bank == 0) return stressBank(col); + if (col == 0) return 0; + return -stressBank((col + 1) % cols); +} + +/// AR cyclically assigns [x, -x, 0] over its sources so zero-query outputs expose RMS-sum differences. +pub fn arStressSource(source: usize, col: usize) f32 { + if (source == 0 and col == 0) return 0; + const value = stressBank(col - col % 3); + return switch ((col + 2 * source) % 3) { + 0 => value, + 1 => -value, + 2 => 0, + else => unreachable, + }; +} + +pub fn close(got: f32, want: f32) bool { + if (std.math.isNan(want)) return std.math.isNan(got); + if (!std.math.isFinite(want)) return got == want; + if (!std.math.isFinite(got)) return false; + const tolerance = 1e-4 * (1.0 + @abs(want)); + return @abs(got - want) <= tolerance; +} + +pub fn bf(x: u16) f32 { + return @floatCast(ref.bf(x)); +} + +pub fn bfRound(x: f32) f32 { + return bf(c.toBf16(x)); +} +pub fn cudaMax(a: f32, b: f32) f32 { + if (std.math.isNan(a)) return b; + if (std.math.isNan(b)) return a; + return @max(a, b); +} + +pub fn sameBf(got: u16, want: u16) bool { + if ((want & 0x7fff) > 0x7f80) return (got & 0x7fff) > 0x7f80; // NaN payload is not part of the math rule + return got == want; +} + +pub fn scale(cols: usize) f32 { + return if (cols == mini_h) 1.0 / 48.0 else 1.0 / @sqrt(@as(f32, @floatFromInt(cols))); +} + +fn warp(v: *[32]f32) f32 { + var offset: usize = 16; + while (offset != 0) : (offset >>= 1) { + const old = v.*; + for (0..32) |lane| v.*[lane] = old[lane] + old[lane ^ offset]; + } + return v.*[0]; +} + +/// The exact lane chains and butterfly tree of loop_math.cu. Terms are fused into each lane's accumulator. +pub fn reduce(a: []const f32, b: []const f32, threads: usize) f32 { + var partial: [32]f32 = @splat(0); + for (0..threads / 32) |w| { + var lanes: [32]f32 = undefined; + for (0..32) |lane| { + const tid = w * 32 + lane; + var sum: f32 = 0; + var i = tid; + while (i < a.len) : (i += threads) sum = @mulAdd(f32, a[i], b[i], sum); + lanes[lane] = sum; + } + partial[w] = warp(&lanes); + } + return warp(&partial); +} + +pub fn fail(msg: []u8, comptime fmt: []const u8, args: anytype) !?[]const u8 { + return try std.fmt.bufPrint(msg, fmt, args); +} + +const message_shapes = [_]c.Shape{ + .{ .rows = 1, .n = 4 * 12 * mini_h, .k = mini_h }, + .{ .rows = 16, .n = 4 * 128, .k = 128 }, + .{ .rows = 2048, .n = 4 * 128, .k = 128 }, +}; + +/// Two normalized banks and the checkpoint's even/odd q,mlp and k,v queries, compared element by element. +pub const Messages = struct { + kern: *const lm.Kernels, + aliased: bool = false, + shape: c.Shape = undefined, + banks: [2][]u16 = .{ &.{}, &.{} }, + queries: [2][]f32 = .{ &.{}, &.{} }, + dev: [5]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Messages) c.Spec { + return .{ .name = if (self.aliased) "control: inkling2 loop messages with both previous-pass inputs wired to bank zero" else "inkling2 loop tf_ink2_loop_messages (two normalized banks, post-dot 1/48, four roles)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.aliased) message_shapes[0..2] else &message_shapes }; + } + + fn depth(s: c.Shape) usize { + return 2 * ((s.k + 255) / 256 + 10); + } + + pub fn control(self: *const Messages) ?g.Gate { + return if (self.aliased) .shapes else null; + } + + pub fn free(self: *Messages, a: std.mem.Allocator) void { + for (&self.banks) |*x| a.free(x.*); + for (&self.queries) |*x| a.free(x.*); + self.banks = .{ &.{}, &.{} }; + self.queries = .{ &.{}, &.{} }; + } + + pub fn prepare(self: *Messages, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.k == 0 or shape.n % (4 * shape.k) != 0) return false; + self.free(a); + self.shape = shape; + const cols = shape.k; + const layers = shape.n / (4 * cols); + for (&self.banks, 0..) |*x, bank| { + x.* = try a.alloc(u16, shape.rows * cols); + if (fill == .stress) { + for (x.*, 0..) |*v, i| v.* = c.toBf16(messageStressBank(bank, i % cols, cols)); + } else for (x.*) |*v| v.* = c.toBf16(rng.float(f32) * 2 - 1); + } + for (&self.queries) |*x| { + x.* = try ref.f32s(a, rng, 2 * layers * cols, -0.25, 0.25); + if (fill == .stress) @memset(x.*, 0); + } + if (fill == .nonfinite) { + ref.plant(u16, self.banks[0], shape.rows, cols, ref.asBf); + ref.plant(u16, self.banks[1], shape.rows, cols, ref.asBf); + } + for (self.banks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + for (self.queries, 0..) |x, i| self.dev[2 + i] = try ref.input(rig, x); + self.out = try rig.output(shape.rows * shape.n * 4); + return true; + } + + pub fn run(self: *Messages, rig: *rig_.Rig) !void { + const b1 = if (self.aliased) self.dev[0] else self.dev[1]; + const layers = self.shape.n / (4 * self.shape.k); + try lm.messages(self.kern, rig.s, self.dev[0], b1, self.dev[2], self.dev[3], self.out, self.shape.rows, layers, self.shape.k, eps); + } + + pub fn count(self: *const Messages) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Messages, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.k; + const layers = self.shape.n / (4 * cols); + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + const later = ref.later(s); + for (0..self.shape.rows) |row| { + var inv: [2]ref.Iv = undefined; + for (0..2) |b| { + for (terms, self.banks[b][row * cols ..][0..cols]) |*t, v| { + const x = ref.Iv.of(ref.bf(v)); + t.* = x.mul(x); + } + inv[b] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); + } + for (0..layers) |j| for (0..4) |role| { + const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; + var logits: [2]ref.Iv = undefined; + for (0..2) |b| { + for (terms, query, self.banks[b][row * cols ..][0..cols]) |*t, q, v| t.* = ref.Iv.of(q).mul(ref.Iv.of(ref.bf(v)).mul(inv[b])); + logits[b] = later.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); + } + softmax(&logits); + for (0..cols) |i| { + var value = ref.Iv.of(0); + for (0..2) |b| { + const beta = ref.Iv.of(ref.bf(self.banks[b][row * cols + i])).mul(inv[b]); + value = value.add(logits[b].mul(beta)); + } + const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; + out[at] = value; + } + }; + } + } + + pub fn check(self: *const Messages, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.k; + const layers = self.shape.n / (4 * cols); + const raw0 = try a.alloc(f32, cols); + defer a.free(raw0); + const raw1 = try a.alloc(f32, cols); + defer a.free(raw1); + const beta0 = try a.alloc(f32, cols); + defer a.free(beta0); + const beta1 = try a.alloc(f32, cols); + defer a.free(beta1); + for (0..self.shape.rows) |row| { + for (raw0, self.banks[0][row * cols ..][0..cols]) |*x, v| x.* = bf(v); + for (raw1, self.banks[1][row * cols ..][0..cols]) |*x, v| x.* = bf(v); + const inv0 = 1.0 / @sqrt(reduce(raw0, raw0, 256) / @as(f32, @floatFromInt(cols)) + eps); + const inv1 = 1.0 / @sqrt(reduce(raw1, raw1, 256) / @as(f32, @floatFromInt(cols)) + eps); + for (beta0, raw0) |*x, v| x.* = v * inv0; + for (beta1, raw1) |*x, v| x.* = v * inv1; + for (0..layers) |j| for (0..4) |role| { + const query = self.queries[if (role == 0 or role == 3) 0 else 1][(2 * j + @intFromBool(role >= 2)) * cols ..][0..cols]; + const l0 = reduce(query, beta0, 256) * scale(cols); + const l1 = reduce(query, beta1, 256) * scale(cols); + const m = cudaMax(l0, l1); + const e0 = @exp(l0 - m); + const e1 = @exp(l1 - m); + const den = e0 + e1; + const w0 = e0 / den; + const w1 = e1 / den; + for (0..cols) |i| { + const want = w0 * beta0[i] + w1 * beta1[i]; + const at = ((j * 4 + role) * self.shape.rows + row) * cols + i; + const value = ref.readF32(got, at); + if (!close(value, want)) return fail(msg, "row {d} core {d} role {d} col {d}: {e} where {e} is due", .{ row, j, role, i, value, want }); + } + }; + } + return null; + } +}; + +const gate_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 2 * mini_h }, + .{ .rows = 16, .n = mini_h, .k = 2 * mini_h }, + .{ .rows = 2048, .n = 128, .k = 256 }, +}; + +/// Host reference preserves BF16 n/zeta and all four FP32 output steps; control substitutes F for Gain. +pub const Gate = struct { + kern: *const lm.Kernels, + wrong_gain: bool = false, + shape: c.Shape = undefined, + h: []f32 = &.{}, + m: []f32 = &.{}, + d: []u16 = &.{}, + f: []u16 = &.{}, + gain: []u16 = &.{}, + dev: [5]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Gate) c.Spec { + return .{ .name = if (self.wrong_gain) "control: inkling2 loop rank-64 gate with forget weights again instead of gain" else "inkling2 loop tf_ink2_loop_gate (BF16 down input/result, FP32 F/G tanh and four output steps)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.wrong_gain) gate_shapes[0..2] else &gate_shapes }; + } + + fn depth(s: c.Shape) usize { + return (s.k + 255) / 256 + 10 + lm.rank; + } + + pub fn control(self: *const Gate) ?g.Gate { + return if (self.wrong_gain) .shapes else null; + } + + pub fn free(self: *Gate, a: std.mem.Allocator) void { + a.free(self.h); + a.free(self.m); + a.free(self.d); + a.free(self.f); + a.free(self.gain); + self.h = &.{}; + self.m = &.{}; + self.d = &.{}; + self.f = &.{}; + self.gain = &.{}; + } + + pub fn prepare(self: *Gate, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k != 2 * shape.n) return false; + self.free(a); + self.shape = shape; + const cols = shape.n; + self.h = try ref.f32s(a, rng, shape.rows * cols, -1, 1); + self.m = try ref.f32s(a, rng, shape.rows * cols, -1, 1); + self.d = try ref.bfs(a, rng, lm.rank * 2 * cols, -0.1, 0.1); + self.f = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); + self.gain = try ref.bfs(a, rng, cols * lm.rank, -0.2, 0.2); + if (fill == .stress) { + for (self.h, 0..) |*v, i| v.* = stressBank(i % cols); + for (self.m, 0..) |*v, i| v.* = stressBank(i % cols); + for (self.d) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.f) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.gain) |*v| v.* = c.toBf16(ref.int(rng, -8, 8)); + } + if (fill == .nonfinite) { + ref.plant(f32, self.h, shape.rows, cols, ref.asF32); + ref.plant(f32, self.m, shape.rows, cols, ref.asF32); + } + self.dev = .{ try ref.input(rig, self.h), try ref.input(rig, self.m), try ref.input(rig, self.d), try ref.input(rig, self.f), try ref.input(rig, self.gain) }; + self.out = try rig.output(shape.rows * cols * 4); + return true; + } + + pub fn run(self: *Gate, rig: *rig_.Rig) !void { + try lm.gate(self.kern, rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], if (self.wrong_gain) self.dev[3] else self.dev[4], self.out, self.shape.rows, self.shape.n, eps); + } + + pub fn count(self: *const Gate) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Gate, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.n; + const n = try a.alloc(ref.Iv, 2 * cols); + defer a.free(n); + const terms = try a.alloc(ref.Iv, 2 * cols); + defer a.free(terms); + const scratch = try a.alloc(f64, 2 * cols); + defer a.free(scratch); + const zeta = try a.alloc(ref.Iv, lm.rank); + defer a.free(zeta); + const later = ref.later(s); + const zeta_depth = (2 * cols + 31) / 32 + 5; + for (0..self.shape.rows) |row| { + const h = self.h[row * cols ..][0..cols]; + const m = self.m[row * cols ..][0..cols]; + var inv: [2]ref.Iv = undefined; + for (0..2) |b| { + const x = if (b == 0) h else m; + for (terms[0..cols], x) |*t, v| { + const e = ref.Iv.of(v); + t.* = e.mul(e); + } + inv[b] = ref.rms(s.sum(terms[0..cols], depth(self.shape), scratch), cols, eps); + } + for (n[0..cols], h) |*v, x| v.* = ref.Iv.of(x).mul(inv[0]).bf(); + for (n[cols..], m) |*v, x| v.* = ref.Iv.of(x).mul(inv[1]).bf(); + for (0..lm.rank) |r| { + for (terms, n, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(w)).mul(x); + zeta[r] = later.sum(terms, zeta_depth, scratch).bf(); + } + for (0..cols) |i| { + for (terms[0..lm.rank], zeta, self.f[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const forget = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); + for (terms[0..lm.rank], zeta, self.gain[i * lm.rank ..][0..lm.rank]) |*t, z, w| t.* = ref.Iv.of(ref.bf(w)).mul(z); + const gain = ref.tanh(later.sum(terms[0..lm.rank], lm.rank, scratch)); + const keep = ref.Iv.of(1).sub(forget); + const old = keep.mul(ref.Iv.of(h[i])); + const added = gain.mul(ref.Iv.of(m[i])); + out[row * cols + i] = old.add(added); + } + } + } + + pub fn check(self: *const Gate, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.n; + const n = try a.alloc(f32, 2 * cols); + defer a.free(n); + const weights = try a.alloc(f32, 2 * cols); + defer a.free(weights); + const zeta = try a.alloc(f32, lm.rank); + defer a.free(zeta); + const zf = try a.alloc(f32, lm.rank); + defer a.free(zf); + const zg = try a.alloc(f32, lm.rank); + defer a.free(zg); + for (0..self.shape.rows) |row| { + const h = self.h[row * cols ..][0..cols]; + const m = self.m[row * cols ..][0..cols]; + const ih = 1.0 / @sqrt(reduce(h, h, 256) / @as(f32, @floatFromInt(cols)) + eps); + const im = 1.0 / @sqrt(reduce(m, m, 256) / @as(f32, @floatFromInt(cols)) + eps); + for (n[0..cols], h) |*v, x| v.* = bfRound(x * ih); + for (n[cols..], m) |*v, x| v.* = bfRound(x * im); + for (0..lm.rank) |r| { + for (weights, self.d[r * 2 * cols ..][0 .. 2 * cols]) |*v, w| v.* = bf(w); + zeta[r] = bfRound(reduce(weights, n, 256)); + } + for (0..cols) |i| { + for (zf, self.f[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); + for (zg, self.gain[i * lm.rank ..][0..lm.rank]) |*v, w| v.* = bf(w); + var sf: f32 = 0; + var sg: f32 = 0; + for (0..lm.rank) |r| { + sf = @mulAdd(f32, zf[r], zeta[r], sf); + sg = @mulAdd(f32, zg[r], zeta[r], sg); + } + const forget = std.math.tanh(sf); + const gain = std.math.tanh(sg); + const keep: f32 = 1.0 - forget; + const old: f32 = keep * h[i]; + const added: f32 = gain * m[i]; + const want: f32 = old + added; + const value = ref.readF32(got, row * cols + i); + if (!close(value, want)) return fail(msg, "row {d} col {d}: {e} where {e} is due", .{ row, i, value, want }); + } + } + return null; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig new file mode 100644 index 00000000000..49bd3ae650e --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig @@ -0,0 +1,426 @@ +//! Mini QKV projection, raw AR and BF16 tap rounding, with the loop suites' shared registration. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_inkling2_ops_ref.zig"); +const base = @import("contract_inkling2_loop_math.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const lm = ink.loop_math_cuda; +const K = base.Checked; +const eps = base.eps; +const mini_h = base.mini_h; +const queryScale = base.queryScale; +const softmax = base.softmax; +const arStressSource = base.arStressSource; +const close = base.close; +const bf = base.bf; +const bfRound = base.bfRound; +const cudaMax = base.cudaMax; +const sameBf = base.sameBf; +const scale = base.scale; +const reduce = base.reduce; +const fail = base.fail; +const Messages = base.Messages; +const Gate = base.Gate; +const qkv_shapes = [_]c.Shape{ + .{ .rows = 1, .n = 3072, .k = mini_h }, + .{ .rows = 16, .n = 384, .k = 128 }, + .{ .rows = 2048, .n = 384, .k = 128 }, +}; + +/// Distinct q/k/v rows, with the Small single-input aliasing bug planted as the control. +pub const ProjectQkv = struct { + kern: *const lm.Kernels, + shared_input: bool = false, + shape: c.Shape = undefined, + u: [3][]u16 = .{ &.{}, &.{}, &.{} }, + w: [3][]u16 = .{ &.{}, &.{}, &.{} }, + dev: [6]u64 = @splat(0), + out: [3]u64 = @splat(0), + + pub fn spec(self: *const ProjectQkv) c.Spec { + return .{ .name = if (self.shared_input) "control: Mini split QKV projection using Small's one normalized input for all roles" else "inkling2 loop tf_ink2_loop_project_qkv (distinct normalized q/k/v inputs, unchanged raw layouts)", .accum = .f32, .depth = depth, .out = .bf16, .served = if (self.shared_input) qkv_shapes[0..2] else &qkv_shapes }; + } + + fn depth(s: c.Shape) usize { + return s.k; + } + + pub fn control(self: *const ProjectQkv) ?g.Gate { + return if (self.shared_input) .shapes else null; + } + + pub fn free(self: *ProjectQkv, a: std.mem.Allocator) void { + for (&self.u) |*x| a.free(x.*); + for (&self.w) |*x| a.free(x.*); + self.u = .{ &.{}, &.{}, &.{} }; + self.w = .{ &.{}, &.{}, &.{} }; + } + + pub fn prepare(self: *ProjectQkv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 3 != 0 or shape.k == 0) return false; + self.free(a); + self.shape = shape; + for (&self.u) |*x| x.* = try ref.bfs(a, rng, shape.rows * shape.k, -1, 1); + for (&self.w, 0..) |*x, role| x.* = try ref.bfs(a, rng, (if (role == 0) shape.n else shape.n / 3) * shape.k, -0.1, 0.1); + if (fill == .stress) { + // Mirrored products cancel to eight small FP32 terms; lower precisions lose their large partials. + const half = shape.k / 2; + for (self.u) |bank| for (0..shape.rows) |row| { + const values = bank[row * shape.k ..][0..shape.k]; + for (0..half) |i| { + values[i] = c.toBf16(ref.int(rng, 8, 16)); + values[half + i] = values[i]; + } + if (shape.k % 2 != 0) values[shape.k - 1] = 0; + }; + for (self.w) |bank| for (0..bank.len / shape.k) |row| { + const values = bank[row * shape.k ..][0..shape.k]; + for (0..half) |i| { + const v = ref.int(rng, 8, 16); + values[i] = c.toBf16(v); + values[half + i] = c.toBf16(-v); + } + for (0..@min(8, half)) |i| values[half + i] = c.toBf16(1 - bf(values[i])); + if (shape.k % 2 != 0) values[shape.k - 1] = 0; + }; + } + if (fill == .nonfinite) for (&self.u) |*x| ref.plant(u16, x.*, shape.rows, shape.k, ref.asBf); + for (self.u, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + for (self.w, 0..) |x, i| self.dev[3 + i] = try ref.input(rig, x); + for (0..3) |role| self.out[role] = try rig.output(shape.rows * (if (role == 0) shape.n else shape.n / 3) * 2); + return true; + } + + pub fn run(self: *ProjectQkv, rig: *rig_.Rig) !void { + const k = if (self.shared_input) self.dev[0] else self.dev[1]; + const v = if (self.shared_input) self.dev[0] else self.dev[2]; + try lm.projectQkv(self.kern, rig.s, self.dev[0], k, v, self.dev[3], self.dev[4], self.dev[5], self.out[0], self.out[1], self.out[2], self.shape.rows, self.shape.k, self.shape.n, self.shape.n / 3); + } + + pub fn count(self: *const ProjectQkv) usize { + return self.shape.rows * self.shape.n * 5 / 3; + } + + pub fn solve(self: *const ProjectQkv, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.k; + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + var offset: usize = 0; + for (0..3) |role| { + const width = if (role == 0) self.shape.n else self.shape.n / 3; + for (0..self.shape.rows) |row| for (0..width) |j| { + for (terms, self.u[role][row * cols ..][0..cols], self.w[role][j * cols ..][0..cols]) |*t, x, w| t.* = ref.Iv.of(ref.bf(x) * ref.bf(w)); + out[offset + row * width + j] = s.sum(terms, depth(self.shape), scratch).bf(); + }; + offset += self.shape.rows * width; + } + } + + pub fn check(self: *const ProjectQkv, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.k; + const x = try a.alloc(f32, cols); + defer a.free(x); + const w = try a.alloc(f32, cols); + defer a.free(w); + var byte_at: usize = 0; + for (0..3) |role| { + const width = if (role == 0) self.shape.n else self.shape.n / 3; + for (0..self.shape.rows) |row| for (0..width) |j| { + for (x, self.u[role][row * cols ..][0..cols]) |*v, u| v.* = bf(u); + for (w, self.w[role][j * cols ..][0..cols]) |*v, u| v.* = bf(u); + var sum: f32 = 0; + for (0..cols) |i| sum = @mulAdd(f32, x[i], w[i], sum); + const want = c.toBf16(sum); + const at = byte_at + (row * width + j) * 2; + const value = std.mem.readInt(u16, got[at..][0..2], .little); + if (!sameBf(value, want)) return fail(msg, "role {d} row {d} output {d}: {x} where {x} is due", .{ role, row, j, value, want }); + }; + byte_at += self.shape.rows * width * 2; + } + return null; + } +}; + +const ar_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 1 }, + .{ .rows = 16, .n = 128, .k = 3 }, + .{ .rows = 2048, .n = 128, .k = 3 }, +}; + +/// Raw AR before controllers. Two completed blocks plus a partial; control omits the second completed block. +pub const Ar = struct { + kern: *const lm.Kernels, + partial_bf16: bool, + short: bool = false, + shape: c.Shape = undefined, + blocks: [2][]u16 = .{ &.{}, &.{} }, + partial32: []f32 = &.{}, + partial16: []u16 = &.{}, + query: []f32 = &.{}, + dev: [4]u64 = @splat(0), // two blocks, partial, query + out: u64 = 0, + + pub fn spec(self: *const Ar) c.Spec { + return .{ .name = if (self.short) "control: inkling2 loop raw AR omitting its second completed block" else if (self.partial_bf16) "inkling2 loop tf_ink2_loop_ar (BF16 partial, FP32 unnormalized output)" else "inkling2 loop tf_ink2_loop_ar (FP32 partial, FP32 unnormalized output)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.short) ar_shapes[1..2] else &ar_shapes }; + } + + fn depth(s: c.Shape) usize { + return (s.n + 511) / 512 + 10 + 3; + } + + pub fn control(self: *const Ar) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *Ar, a: std.mem.Allocator) void { + for (&self.blocks) |*x| a.free(x.*); + a.free(self.partial32); + a.free(self.partial16); + a.free(self.query); + self.blocks = .{ &.{}, &.{} }; + self.partial32 = &.{}; + self.partial16 = &.{}; + self.query = &.{}; + } + + pub fn prepare(self: *Ar, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0 or shape.k > lm.max_queries) return false; + self.free(a); + self.shape = shape; + for (&self.blocks, 0..) |*x, source| { + x.* = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (x.*, 0..) |*v, i| v.* = c.toBf16(arStressSource(source, i % shape.n)); + } + } + if (self.partial_bf16) { + self.partial16 = try ref.bfs(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (self.partial16, 0..) |*v, i| v.* = c.toBf16(arStressSource(2, i % shape.n)); + } + self.dev[2] = try ref.input(rig, self.partial16); + } else { + self.partial32 = try ref.f32s(a, rng, shape.rows * shape.n, -1, 1); + if (fill == .stress) { + for (self.partial32, 0..) |*v, i| v.* = arStressSource(2, i % shape.n); + } + self.dev[2] = try ref.input(rig, self.partial32); + } + self.query = try ref.f32s(a, rng, shape.k * shape.n, -0.25, 0.25); + if (fill == .stress) @memset(self.query, 0); + if (fill == .nonfinite) for (&self.blocks) |*x| ref.plant(u16, x.*, shape.rows, shape.n, ref.asBf); + for (self.blocks, 0..) |x, i| self.dev[i] = try ref.input(rig, x); + self.dev[3] = try ref.input(rig, self.query); + self.out = try rig.output(shape.rows * shape.n * shape.k * 4); + return true; + } + + pub fn run(self: *Ar, rig: *rig_.Rig) !void { + var args: lm.ArArgs = .{ .partial = self.dev[2], .query = self.dev[3], .out = self.out, .n_blocks = if (self.short) 1 else 2, .partial_bf16 = @intFromBool(self.partial_bf16), .nq = @intCast(self.shape.k), .rows = @intCast(self.shape.rows), .c = @intCast(self.shape.n), .eps = eps }; + args.blocks[0] = self.dev[0]; + args.blocks[1] = self.dev[1]; + try lm.ar(self.kern, rig.s, args); + } + + pub fn count(self: *const Ar) usize { + return self.shape.rows * self.shape.n * self.shape.k; + } + + fn entry(self: *const Ar, source: usize, row: usize, col: usize) f32 { + const at = row * self.shape.n + col; + return if (source < 2) bf(self.blocks[source][at]) else if (self.partial_bf16) bf(self.partial16[at]) else self.partial32[at]; + } + + pub fn solve(self: *const Ar, a: std.mem.Allocator, s: ref.Sums, out: []ref.Iv) !void { + const cols = self.shape.n; + const terms = try a.alloc(ref.Iv, cols); + defer a.free(terms); + const scratch = try a.alloc(f64, cols); + defer a.free(scratch); + for (0..self.shape.rows) |row| { + var inv: [3]ref.Iv = undefined; + for (0..3) |j| { + for (terms, 0..) |*t, i| { + const x = ref.Iv.of(self.entry(j, row, i)); + t.* = x.mul(x); + } + inv[j] = ref.rms(s.sum(terms, depth(self.shape), scratch), cols, eps); + } + for (0..self.shape.k) |q| { + var logits: [3]ref.Iv = undefined; + for (0..3) |j| { + for (terms, 0..) |*t, i| t.* = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]).mul(ref.Iv.of(self.query[q * cols + i])); + logits[j] = s.sum(terms, depth(self.shape), scratch).mul(queryScale(cols)); + } + softmax(&logits); + for (0..cols) |i| { + var value = ref.Iv.of(0); + for (0..3) |j| { + const beta = ref.Iv.of(self.entry(j, row, i)).mul(inv[j]); + value = value.add(logits[j].mul(beta)); + } + out[(q * self.shape.rows + row) * cols + i] = value; + } + } + } + } + + pub fn check(self: *const Ar, a: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const cols = self.shape.n; + const sources = 3; + const raw = try a.alloc(f32, cols); + defer a.free(raw); + const beta = try a.alloc(f32, sources * cols); + defer a.free(beta); + const weights = try a.alloc(f32, sources); + defer a.free(weights); + for (0..self.shape.rows) |row| { + var invs: [3]f32 = undefined; + for (0..sources) |j| { + for (raw, 0..) |*v, i| v.* = self.entry(j, row, i); + invs[j] = 1.0 / @sqrt(reduce(raw, raw, 512) / @as(f32, @floatFromInt(cols)) + eps); + for (beta[j * cols ..][0..cols], raw) |*v, x| v.* = x * invs[j]; + } + for (0..self.shape.k) |q| { + var logits: [3]f32 = undefined; + var m = -std.math.inf(f32); + for (0..sources) |j| { + const query = self.query[q * cols ..][0..cols]; + logits[j] = reduce(query, beta[j * cols ..][0..cols], 512) * scale(cols); + m = cudaMax(m, logits[j]); + } + var den: f32 = 0; + for (0..sources) |j| { + weights[j] = @exp(logits[j] - m); + den += weights[j]; + } + for (0..sources) |j| weights[j] /= den; + for (0..cols) |i| { + var want: f32 = 0; + for (0..sources) |j| want = @mulAdd(f32, weights[j], beta[j * cols + i], want); + const at = (q * self.shape.rows + row) * cols + i; + const value = ref.readF32(got, at); + if (!close(value, want)) return fail(msg, "query {d} row {d} col {d}: {e} where {e} is due", .{ q, row, i, value, want }); + } + } + } + return null; + } +}; + +test "AR normalizes each FP32 query term before reduction and scales after its dot" { + const source = [_]f32{ + @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), + @bitCast(@as(u32, 0x40400001)), 0, + }; + const query = [_]f32{ + @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), + @bitCast(@as(u32, 0xc0000001)), 0, + }; + const inv: f32 = @bitCast(@as(u32, 0x3f800001)); + var normalized: [4]f32 = undefined; + for (&normalized, source) |*v, x| v.* = x * inv; + const dot = reduce(&query, &normalized, 512); + const old = reduce(&query, &source, 512) * inv * scale(source.len); + const scaled = dot * scale(source.len); + try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); + try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); +} + +const round_shapes = [_]c.Shape{ + .{ .rows = 1, .n = mini_h, .k = 1 }, + .{ .rows = 2048, .n = 32, .k = 1 }, +}; + +/// Dynamic taps' required BF16 storage rounding, followed by exact widening for the FP32 convolution. +pub const RoundBf16 = struct { + kern: *const lm.Kernels, + short: bool = false, + shape: c.Shape = undefined, + x: []f32 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn spec(self: *const RoundBf16) c.Spec { + return .{ .name = if (self.short) "control: inkling2 loop dynamic taps leave the final value unrounded" else "inkling2 loop tf_ink2_loop_round_bf16 (global dynamic taps, BF16 then FP32)", .accum = .none, .depth = ref.noSums, .out = .f32, .served = if (self.short) round_shapes[0..1] else &round_shapes }; + } + + pub fn control(self: *const RoundBf16) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *RoundBf16, a: std.mem.Allocator) void { + a.free(self.x); + self.x = &.{}; + } + + pub fn prepare(self: *RoundBf16, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + self.x = try ref.f32s(a, rng, shape.rows * shape.n, -32, 32); + if (fill == .nonfinite) ref.plant(f32, self.x, shape.rows, shape.n, ref.asF32); + self.dev = try ref.input(rig, self.x); + self.out = try rig.output(self.x.len * 4); + return true; + } + + pub fn run(self: *RoundBf16, rig: *rig_.Rig) !void { + try lm.roundBf16(self.kern, rig.s, self.dev, self.out, self.x.len - @intFromBool(self.short)); + } + + pub fn count(self: *const RoundBf16) usize { + return self.x.len; + } + + pub fn solve(self: *const RoundBf16, _: std.mem.Allocator, _: ref.Sums, out: []ref.Iv) !void { + for (out, self.x) |*o, x| o.* = ref.Iv.of(x).bf(); + } + + pub fn check(self: *const RoundBf16, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + for (self.x, 0..) |x, i| { + const want = bfRound(x); + const value = ref.readF32(got, i); + if (!ref.sameF32(value, want)) return fail(msg, "tap {d}: {e} where {e} is due", .{ i, value, want }); + } + return null; + } +}; + +pub const Set = struct { + k: lm.Kernels = undefined, + loaded: bool = false, + messages: [2]K(Messages) = undefined, + gates: [2]K(Gate) = undefined, + qkvs: [2]K(ProjectQkv) = undefined, + ars: [3]K(Ar) = undefined, + rounds: [2]K(RoundBf16) = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.k = try lm.Kernels.load(gpu.d); + set.loaded = true; + const k = &set.k; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + for (&set.messages, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .aliased = i == 1 } } }; + for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .wrong_gain = i == 1 } } }; + for (&set.qkvs, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .shared_input = i == 1 } } }; + for (&set.ars, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .partial_bf16 = i == 1, .short = i == 2 } } }; + for (&set.rounds, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } } }; + inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + if (!set.loaded) return; + inline for (.{ "messages", "gates", "qkvs", "ars", "rounds" }) |f| for (&@field(set, f)) |*x| x.deinit(); + set.k.unload(); + set.loaded = false; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_modelopt.zig b/zig/tests/cuda/contract_inkling2_modelopt.zig new file mode 100644 index 00000000000..5052173fd2a --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_modelopt.zig @@ -0,0 +1,590 @@ +//! Mini's packed NVFP4/MXFP8 expert pipeline on BF16 activations, with bit-exact and float64 references. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const ink = @import("inkling2"); +const rig_ = @import("contract_rig.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const mo = ink.modelopt; +const experts = 8; +const slots = 8; + +const CombineArgs = extern struct { + experts: u64, + pick: u64, + weights: u64, + out: u64, + rows: i32, + h: i32, + slots: i32, +}; + +const TensorActArgs = extern struct { + gateup: u64, + out: u64, + n: i32, +}; + +const Baseline = struct { + mod: cuda.Module, + tensor_mod: cuda.Module, + pack: cuda.Function, + project: cuda.Function, + act: cuda.Function, + combine: cuda.Function, +}; + +fn bf(x: f32) f32 { + return c.fromBf16(c.toBf16(x)); +} + +fn e2m1(n: u8) f32 { + const table = [8]f32{ 0, 0.5, 1, 1.5, 2, 3, 4, 6 }; + const v = table[n & 7]; + return if ((n & 8) != 0) -v else v; +} + +fn e4m3(n: u8) f32 { + const e = (n >> 3) & 15; + const m: f32 = @floatFromInt(n & 7); + var v: f32 = undefined; + if (e == 0) { + v = m * 0x1p-9; + } else if (e == 15 and n & 7 == 7) { + v = std.math.nan(f32); + } else { + v = std.math.pow(f32, 2, @as(f32, @floatFromInt(e)) - 7) * (1 + m / 8); + } + return if ((n & 128) != 0) -v else v; +} + +fn route(slot: usize) u32 { + const ids = [8]u32{ 7, 7, 2, 5, 0, 6, 3, 4 }; + return ids[slot]; +} + +fn routeWeight(token: usize, slot: usize) f32 { + _ = token; + // Route order loses the unit between opposite large terms; expert order keeps it. + return switch (slot) { + 0 => 0x1p24, + 1 => 1, + 2 => -0x1p24, + else => 0, + }; +} + +const test_amax: f32 = 1.0039; // bf16: 1 +const test_den: f32 = 2696.001; // bf16: 2704 + +fn nvfp4Weight(code: u8, scale: u8) u16 { + const factor = bf(test_amax) / bf(test_den); + return c.toBf16(e2m1(code) * e4m3(scale) * factor); +} + +fn ue8m0(n: u8) f32 { + return std.math.pow(f32, 2, @as(f32, @floatFromInt(@as(i32, n) - 127))); +} + +fn mxfp8Weight(code: u8, scale: u8) u16 { + return c.toBf16(e4m3(code) * ue8m0(scale)); +} + +const Phase = enum { decode, prompt }; +const Fault = enum { none, wrong_combine, wrong_plan, wrong_up, wrong_prompt_up, wrong_act }; +fn rawSpec(format: mo.Format, phase: Phase, fault: Fault) c.Spec { + const served = &[_]c.Shape{ + .{ .rows = 1, .n = 2304, .k = 1152 }, + .{ .rows = 16, .n = 2304, .k = 1152 }, + .{ .rows = 31, .n = 2304, .k = 1152 }, + .{ .rows = 32, .n = 2304, .k = 1152 }, + .{ .rows = 2048, .n = 2304, .k = 1152 }, + }; + const name = switch (fault) { + .none => if (format == .nvfp4) + (if (phase == .decode) "inkling2 Mini NVFP4 decode w13/w2 tensor-core experts" else "inkling2 Mini NVFP4 prompt w13/w2 tensor-core experts") + else + (if (phase == .decode) "inkling2 Mini MXFP8 decode w13/w2 tensor-core experts" else "inkling2 Mini MXFP8 prompt w13/w2 tensor-core experts"), + .wrong_combine => if (format == .nvfp4) "control: inkling2 Mini NVFP4 int32 route IDs reinterpreted as FP32 weights" else "control: inkling2 Mini MXFP8 int32 route IDs reinterpreted as FP32 weights", + .wrong_plan => "control: inkling2 Mini MXFP8 plan routes to the next expert IDs", + .wrong_up => "control: inkling2 Mini MXFP8 decode up projection clears the planted up-row code", + .wrong_prompt_up => if (format == .nvfp4) "control: inkling2 Mini NVFP4 prompt up projection clears the planted up-row code" else "control: inkling2 Mini MXFP8 prompt up projection clears the planted up-row code", + .wrong_act => "control: inkling2 Mini MXFP8 activation uses gate cap eight", + }; + const shapes = if (fault == .wrong_prompt_up or (fault == .none and phase == .prompt)) + served[3..] + else if (fault == .none) + served[0..3] + else + served[0..2]; + return .{ + .name = name, + .accum = .f32, + .depth = depth, + .ops = 8, + .mids = 4, + .out = .bf16, + .replaces = "host-dequantized BF16 tensor projections, softcapped SwiGLU, ascending FP32 routing", + .nan = .{ .stated = "a non-finite BF16 input row propagates through its selected experts" }, + .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{ .size = 32 } }, + .served = shapes, + .sums = .{ .f16 = 30, .bf16 = 30 }, + }; +} +fn depth(s: c.Shape) usize { + return s.n + s.k + 2 * core.attention_range.mma_step + slots; +} +pub const ModelOpt = struct { + rig: rig_.Rig, + k: *const mo.Kernels, + format: mo.Format, + phase: Phase, + shape: c.Shape = undefined, + fault: Fault = .none, + arena: ?std.heap.ArenaAllocator = null, + x: []const u16 = &.{}, + w13: []const u16 = &.{}, + w2: []const u16 = &.{}, + l: mo.Layer = undefined, + dev_x: u64 = 0, + pick: u64 = 0, + weights: u64 = 0, + out: u64 = 0, + stress: bool = false, + scratch: u64 = 0, + base_pick: u64 = 0, + base_w13: u64 = 0, + base_w2: u64 = 0, + base_pack13: u64 = 0, + base_pack2: u64 = 0, + base_gateup: u64 = 0, + base_act: u64 = 0, + base_down: u64 = 0, + base_out: u64 = 0, + baseline: ?Baseline = null, + + pub fn kernel(self: *ModelOpt) g.Kernel { + return .{ .spec = rawSpec(self.format, self.phase, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + } + + const vt = g.hooks(ModelOpt); + + pub fn deinit(self: *ModelOpt) void { + self.drop(); + if (self.baseline) |*b| { + b.tensor_mod.unload(); + b.mod.unload(); + } + self.baseline = null; + self.rig.deinit(); + } + + fn drop(self: *ModelOpt) void { + if (self.arena) |*a| a.deinit(); + self.arena = null; + self.rig.reset(); + } + + fn projectionRef(a: std.mem.Allocator, format: mo.Format, nexperts: usize, n: usize, k: usize, gate_up: bool, fill: g.Fill) !struct { codes: []u8, scales: []u8, amax: []f32, den: [1]f32, ref: []u16 } { + const values = nexperts * n * k; + const raw = try a.alloc(u8, if (format == .nvfp4) values / 2 else values); + const ref = try a.alloc(u16, values); + const group: usize = if (format == .nvfp4) 16 else 32; + const scales = try a.alloc(u8, values / group); + const amax = try a.alloc(f32, if (format == .nvfp4) nexperts else 0); + if (format == .nvfp4) @memset(amax, if (fill == .stress) bf(test_den) else test_amax); + const codes = [16]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + const fp8 = [16]u8{ 0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x80, 0x88, 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8 }; + const nv_scales = [4]u8{ 0x38, 0x30, 0x40, 0x34 }; + // General controls stay finite; the dedicated scale-255 test covers +inf without masking faults as shared NaNs. + const mx_scales = [4]u8{ 127, 128, 126, 129 }; + if (fill == .stress) { + for (0..nexperts) |e| for (0..n) |row| { + const base = (e * n + row) * k; + const scale_base = (e * n + row) * (k / group); + @memset(scales[scale_base..][0 .. k / group], if (format == .nvfp4) 0x38 else 127); + for (0..k) |col| { + // Mirrored +/-1 terms cancel to small integers; eight up rows retain a down-projection nudge. + const zero = gate_up and (row & 1) == 1 and row / 2 < 8 and col == k / 2 + 8; + const code: u8 = if (zero) 0 else if (format == .nvfp4) (if (col < k / 2) 2 else 10) else (if (col < k / 2) 0x38 else 0xb8); + if (format == .nvfp4) { + if ((col & 1) == 0) raw[base / 2 + col / 2] = code else raw[base / 2 + col / 2] |= code << 4; + } else raw[base + col] = code; + ref[base + col] = c.toBf16(if (zero) 0 else if (col < k / 2) 1 else -1); + } + }; + return .{ .codes = raw, .scales = scales, .amax = amax, .den = .{test_den}, .ref = ref }; + } + for (0..nexperts) |e| for (0..n) |row| { + const base = (e * n + row) * k; + const scale_base = (e * n + row) * (k / group); + if (format == .nvfp4) { + for (0..k / 2) |cb| { + var n0 = codes[(2 * (base / 2 + cb) * 5 + 3) & 15]; + const n1 = if (cb == 0) 0 else codes[(2 * (base / 2 + cb) * 5 + 7) & 15]; + if (cb == 0) n0 = if (!gate_up or row < 2) (if (gate_up) 2 else 7) else 0; + raw[base / 2 + cb] = n0 | (n1 << 4); + const gi = cb / 8; + scales[scale_base + gi] = if (gi == 0) 0x38 else nv_scales[(scale_base + gi) & 3]; + const scale = scales[scale_base + gi]; + ref[base + 2 * cb] = nvfp4Weight(n0, scale); + ref[base + 2 * cb + 1] = nvfp4Weight(n1, scale); + } + } else { + for (0..k) |col| { + var code = fp8[((base + col) * 5 + 3) & 15]; + // Gate six makes caps four and eight differ deterministically on the one-token control. + if (col == 0) code = if (!gate_up) 0x40 else if (row == 0) 0x4c else if (row == 1) 0x38 else 0; + raw[base + col] = code; + const gi = col / 32; + scales[scale_base + gi] = if (gi == 0) 127 else mx_scales[(scale_base + gi) % mx_scales.len]; + ref[base + col] = mxfp8Weight(code, scales[scale_base + gi]); + } + } + }; + return .{ .codes = raw, .scales = scales, .amax = amax, .den = .{test_den}, .ref = ref }; + } + + pub fn prepare(self: *ModelOpt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + _ = seed; + if (self.phase == .prompt and shape.rows < 32 and fill != .stress and fill != .nonfinite) return false; + if (shape.n != 2304 or shape.k != 1152 or shape.rows == 0 or shape.rows > 2048) return false; + self.drop(); + self.shape = shape; + self.stress = fill == .stress; + self.arena = std.heap.ArenaAllocator.init(self.rig.gpu.gpa); + const a = self.arena.?.allocator(); + const h = shape.n; + const m = shape.k; + const pairs = shape.rows * slots; + const x = try a.alloc(u16, shape.rows * h); + for (x, 0..) |*v, i| { + const q: f32 = @as(f32, @floatFromInt(@as(i32, @intCast(i % 17)) - 8)) / 64; + v.* = c.toBf16(q); + } + @memset(x[0..h], 0); + x[0] = c.toBf16(1); // One gate/up activation and one down product make token zero a decode probe. + if (fill == .nonfinite) x[0] = 0x7fc0; + if (fill == .stress) for (0..shape.rows) |row| for (0..h) |col| { + const v: f32 = 4 * @as(f32, @floatFromInt(1 + col % 64)); + x[row * h + col] = c.toBf16(v + @as(f32, if (col >= h / 2 and col < h / 2 + 8) 4 else 0)); + }; + self.x = x; + const p13 = try projectionRef(a, self.format, experts, 2 * m, h, true, fill); + const p2 = try projectionRef(a, self.format, experts, h, m, false, fill); + self.w13 = p13.ref; + self.w2 = p2.ref; + self.dev_x = try self.rig.input(std.mem.sliceAsBytes(x)); + const dev13 = if (self.fault == .wrong_up or self.fault == .wrong_prompt_up) blk: { + const wrong = try a.dupe(u8, p13.codes); + for (0..experts) |e| { + const code_stride: usize = if (self.format == .nvfp4) 2 else 1; + const z = (e * 2 * m + 1) * h / code_stride; + if (self.format == .nvfp4) wrong[z] &= 0xf0 else wrong[z] = 0; + } + break :blk try self.rig.input(wrong); + } else try self.rig.input(p13.codes); + const dev13s = try self.rig.input(p13.scales); + const dev2 = try self.rig.input(p2.codes); + const dev2s = try self.rig.input(p2.scales); + var amax13: u64 = 0; + var amax2: u64 = 0; + var den13: u64 = 0; + var den2: u64 = 0; + if (self.format == .nvfp4) { + amax13 = try self.rig.input(std.mem.sliceAsBytes(p13.amax)); + amax2 = try self.rig.input(std.mem.sliceAsBytes(p2.amax)); + den13 = try self.rig.input(std.mem.asBytes(&p13.den)); + den2 = try self.rig.input(std.mem.asBytes(&p2.den)); + } + self.l = .{ + .format = self.format, + .experts = experts, + .w13 = .{ .codes = dev13, .scales = dev13s, .amax = amax13, .denominator = den13, .n = @intCast(2 * m), .k = @intCast(h) }, + .w2 = .{ .codes = dev2, .scales = dev2s, .amax = amax2, .denominator = den2, .n = @intCast(h), .k = @intCast(m) }, + }; + const picks = try a.alloc(i32, pairs); + const weights = try a.alloc(f32, pairs); + for (picks, weights, 0..) |*p, *w, i| { + const slot = i % slots; + const id = if (self.fault == .wrong_plan) (route(slot) + 1) % experts else route(slot); + p.* = @intCast(id); + w.* = routeWeight(i / slots, slot); + } + const base_picks = try a.alloc(i32, pairs); + for (base_picks, 0..) |*p, i| p.* = @intCast(route(i % slots)); + self.pick = try self.rig.input(std.mem.sliceAsBytes(picks)); + self.weights = try self.rig.input(std.mem.sliceAsBytes(weights)); + self.out = try self.rig.output(shape.rows * h * 2); + self.scratch = try self.rig.scratch(try mo.scratchBytes(shape.rows, slots, h, m)); + self.base_pick = try self.rig.input(std.mem.sliceAsBytes(base_picks)); + self.base_w13 = try self.rig.input(std.mem.sliceAsBytes(p13.ref)); + self.base_w2 = try self.rig.input(std.mem.sliceAsBytes(p2.ref)); + self.base_pack13 = try self.rig.scratch(experts * 2 * m * h * 2); + self.base_pack2 = try self.rig.scratch(experts * h * m * 2); + self.base_gateup = try self.rig.scratch(pairs * 2 * m * 2); + self.base_act = try self.rig.scratch(pairs * m * 2); + self.base_down = try self.rig.scratch(pairs * h * 2); + self.base_out = try self.rig.scratch(shape.rows * h * 2); + return true; + } + + pub fn run(self: *ModelOpt) !void { + const route_weights = if (self.fault == .wrong_combine) self.pick else self.weights; + const caps = if (self.fault == .wrong_act) ink.experts.Caps{ .gate = 8, .up = 25 } else ink.experts.Caps{ .gate = 4, .up = 25 }; + if (self.phase == .prompt and self.shape.rows < 32) return self.runPrompt(caps); + try mo.run(self.k, self.rig.s, self.l, caps, self.dev_x, self.shape.n, self.pick, route_weights, self.shape.rows, slots, self.out, self.scratch); + } + + fn pack(self: *ModelOpt, b: *const Baseline, src: u64, n: usize, k: usize, dst: u64) !void { + var a: cuda.Args = .{}; + a.add(src); + a.add(@as(i64, @intCast(n * k))); + a.add(@as(i32, @intCast(k))); + for ([_]i32{ 0, 0, 0 }) |v| a.add(v); + a.add(@as(i32, @intCast(n))); + a.add(@as(i32, @intCast(k))); + a.add(dst); + const q = (n / 32) * (k / 32) * 128; + try cuda.launch.launch(b.pack, .{ .grid = .{ .x = @intCast((q + 255) / 256), .y = experts, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); + } + + fn tensorProjection(self: *ModelOpt, b: *const Baseline, x: u64, x_stride: usize, slot_count: usize, w: u64, n: usize, k: usize, plan: mo.Layout, out: u64, item_bound: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i32, @intCast(x_stride))); + a.add(@as(i32, @intCast(slot_count))); + a.add(w); + a.add(@as(i32, @intCast(k / 32))); + a.add(@as(i32, @intCast(n / 32))); + for ([_]u64{ plan.items, plan.item_count, plan.members, out }) |v| a.add(v); + a.add(@as(i32, @intCast(n))); + a.add(@as(i32, -1)); + const nb = n / 32; + const grid = (item_bound * nb + 3) / 4; + try cuda.launch.launch(b.project, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + /// Tensor projections over host-dequantized weights, the baseline epilogue and the original ascending combine. + pub fn replaced(self: *ModelOpt) ![]const u8 { + if (self.baseline == null) { + var mod = try cuda.Module.load(self.rig.gpu.d, cuda.kernels.inkling2_experts); + errdefer mod.unload(); + var tensor_mod = try cuda.Module.load(self.rig.gpu.d, cuda.kernels.experts_bf16); + errdefer tensor_mod.unload(); + self.baseline = .{ + .mod = mod, + .tensor_mod = tensor_mod, + .pack = try tensor_mod.function("tf_bf16_experts_pack"), + .project = try tensor_mod.function("tf_bf16_experts_down_bf16"), + .act = try mod.function("tf_ink2moe_tensor_act"), + .combine = try mod.function("tf_ink2moe_combine"), + }; + } + const b = &self.baseline.?; + const pairs = self.shape.rows * slots; + const h = self.shape.n; + const m = self.shape.k; + const plan = mo.layout(self.scratch, self.shape.rows, slots, h, m); + const tile: usize = if (self.shape.rows < 32) 16 else 64; + const item_bound = (pairs + tile - 1) / tile + @min(pairs, experts); + var pa: cuda.Args = .{}; + for ([_]u64{ self.base_pick, plan.items, plan.members, plan.item_count }) |v| pa.add(v); + for ([_]i32{ @intCast(self.shape.rows), slots, experts, @intCast(tile) }) |v| pa.add(v); + try cuda.launch.launch(self.k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, self.rig.s, &pa); + try self.pack(b, self.base_w13, 2 * m, h, self.base_pack13); + try self.pack(b, self.base_w2, h, m, self.base_pack2); + try self.tensorProjection(b, self.dev_x, h, slots, self.base_pack13, 2 * m, h, plan, self.base_gateup, item_bound); + var aa: cuda.Args = .{}; + aa.add(TensorActArgs{ .gateup = self.base_gateup, .out = self.base_act, .n = @intCast(pairs * m) }); + try cuda.launch.launch(b.act, .{ .grid = .{ .x = @intCast((pairs * m + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &aa); + try self.tensorProjection(b, self.base_act, m, 0, self.base_pack2, h, m, plan, self.base_down, item_bound); + var ca: cuda.Args = .{}; + ca.add(CombineArgs{ .experts = self.base_down, .pick = self.base_pick, .weights = self.weights, .out = self.base_out, .rows = @intCast(self.shape.rows), .h = @intCast(h), .slots = slots }); + const outputs = self.shape.rows * h; + try cuda.launch.launch(b.combine, .{ .grid = .{ .x = @intCast((outputs + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &ca); + return self.rig.bytes(self.base_out, 2 * self.count()); + } + + fn promptProjection(self: *ModelOpt, x: u64, stride: usize, pair_slots: usize, p: mo.Projection, row0: i32, step: i32, plan: mo.Layout, out: u64, bound: usize) !void { + const outputs: usize = @intCast(if (step == 2) p.n / 2 else p.n); + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i32, @intCast(stride))); + a.add(@as(i32, @intCast(pair_slots))); + a.add(mo.weight(p, self.l, row0, step)); + a.add(@as(i32, @intCast(p.k / 32))); + a.add(@as(i32, @intCast(outputs / 32))); + for ([_]u64{ plan.items, plan.item_count, plan.members, out }) |v| a.add(v); + a.add(@as(i32, @intCast(outputs))); + a.add(@as(i32, -1)); + const grid = (bound * outputs / 32 + 3) / 4; + try cuda.launch.launch(self.k.prompt, .{ .grid = .{ .x = @intCast(grid), .y = 1, .z = 1 }, .block = .{ .x = 128 } }, self.rig.s, &a); + } + + fn runPrompt(self: *ModelOpt, caps: ink.experts.Caps) !void { + const pairs = self.shape.rows * slots; + const b = mo.layout(self.scratch, self.shape.rows, slots, self.shape.n, self.shape.k); + const bound = (pairs + 63) / 64 + @min(pairs, experts); + var plan_args: cuda.Args = .{}; + for ([_]u64{ self.pick, b.items, b.members, b.item_count }) |v| plan_args.add(v); + for ([_]i32{ @intCast(self.shape.rows), slots, experts, 64 }) |v| plan_args.add(v); + try cuda.launch.launch(self.k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, self.rig.s, &plan_args); + try self.promptProjection(self.dev_x, self.shape.n, slots, self.l.w13, 0, 2, b, b.gate, bound); + try self.promptProjection(self.dev_x, self.shape.n, slots, self.l.w13, 1, 2, b, b.up, bound); + var aa: cuda.Args = .{}; + for ([_]u64{ b.gate, b.up, b.act }) |v| aa.add(v); + aa.add(@as(i32, @intCast(pairs * self.shape.k))); + aa.add(caps.gate); + aa.add(caps.up); + try cuda.launch.launch(self.k.act, .{ .grid = .{ .x = @intCast((pairs * self.shape.k + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &aa); + try self.promptProjection(b.act, self.shape.k, 0, self.l.w2, 0, 1, b, b.down, bound); + var ca: cuda.Args = .{}; + for ([_]u64{ self.pick, self.weights, b.down, self.out }) |v| ca.add(v); + for ([_]i32{ @intCast(self.shape.rows), @intCast(self.shape.n), slots, experts }) |v| ca.add(v); + const output_count = self.shape.rows * self.shape.n; + try cuda.launch.launch(self.k.combine, .{ .grid = .{ .x = @intCast((output_count + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &ca); + } + + pub fn count(self: *const ModelOpt) usize { + return self.shape.rows * self.shape.n; + } + + fn roundTo(acc: c.Accum, v: f64) f64 { + return switch (acc) { + .f32 => @as(f32, @floatCast(v)), + .f16 => @as(f16, @floatCast(v)), + .bf16 => c.fromBf16(c.toBf16(@floatCast(v))), + .none => v, + }; + } + fn rounded(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); + } + fn activate(gate: f64, up: f64) f64 { + const gate_f32: f32 = @floatCast(gate); + const up_f32: f32 = @floatCast(up); + const gc = 4 * @as(f32, @floatCast(std.math.tanh(gate_f32 / 4))); + const uc = 25 * @as(f32, @floatCast(std.math.tanh(up_f32 / 25))); + const sigmoid: f32 = 1 / (1 + @exp(-gate_f32)); + return rounded(gc * sigmoid * uc); + } + + fn evaluate(self: *const ModelOpt, acc: c.Accum, order: g.Order, out: []f64, mag: ?[]f64) !void { + const a = self.rig.gpu.gpa; + const pairs = self.shape.rows * slots; + const h = self.shape.n; + const m = self.shape.k; + const t = try a.alloc(f64, h); + defer a.free(t); + const act = try a.alloc(f64, pairs * m); + defer a.free(act); + const upstream = try a.alloc(f64, pairs * m); + defer a.free(upstream); + const down = try a.alloc(f64, pairs * h); + defer a.free(down); + const down_mag = try a.alloc(f64, pairs * h); + defer a.free(down_mag); + for (0..if (self.stress) 1 else pairs) |p| { + const token = p / slots; + const e = route(p % slots); + const x = self.x[token * h ..][0..h]; + const w = self.w13[e * 2 * m * h ..]; + for (0..m) |j| { + var gabs: f64 = 0; + var uabs: f64 = 0; + for (0..h) |i| { + const xv = c.fromBf16(x[i]); + t[i] = xv * c.fromBf16(w[(2 * j) * h + i]); + gabs += @abs(t[i]); + } + const gate = rounded(core.contract.rows.sumIn(acc, order, t)); + for (0..h) |i| { + t[i] = c.fromBf16(x[i]) * c.fromBf16(w[(2 * j + 1) * h + i]); + uabs += @abs(t[i]); + } + const up = rounded(core.contract.rows.sumIn(acc, order, t)); + act[p * m + j] = activate(gate, up); + upstream[p * m + j] = 32 * gabs + 8 * uabs; + } + } + if (self.stress) for (1..pairs) |p| { + @memcpy(act[p * m ..][0..m], act[0..m]); + @memcpy(upstream[p * m ..][0..m], upstream[0..m]); + }; + for (0..if (self.stress) 1 else pairs) |p| for (0..if (self.stress) 1 else h) |col| { + const w = self.w2[route(p % slots) * h * m + col * m ..][0..m]; + var abs: f64 = 0; + for (0..m) |j| { + t[j] = act[p * m + j] * c.fromBf16(w[j]); + abs += @abs(t[j]) + @abs(c.fromBf16(w[j])) * upstream[p * m + j]; + } + down[p * h + col] = rounded(core.contract.rows.sumIn(acc, order, t[0..m])); + down_mag[p * h + col] = abs; + }; + if (self.stress) { + @memset(down, down[0]); + @memset(down_mag, down_mag[0]); + } + for (0..self.shape.rows) |token| for (0..h) |col| { + var total: f64 = 0; + var abs: f64 = 0; + for (0..experts) |e| for (0..slots) |slot| { + if (route(slot) != e) continue; + const p = token * slots + slot; + const weight = routeWeight(token, slot); + total = roundTo(acc, total + roundTo(acc, weight * down[p * h + col])); + abs += @abs(weight) * down_mag[p * h + col]; + }; + out[token * h + col] = rounded(total); + if (mag) |v| v[token * h + col] = abs; + }; + } + + pub fn reference(self: *ModelOpt, want: []f64, mag: []f64) !void { + if (self.x[0] == 0x7fc0) { + @memset(want, 0); + @memset(mag, 0); + @memset(want[0..self.shape.n], std.math.nan(f64)); + return; + } + return self.evaluate(.none, .sequential, want, mag); + } + + pub fn simulate(self: *ModelOpt, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.evaluate(acc, order, out, null); + } +}; + +test "A2: amax and denominator are BF16 before the FP32 quotient" { + // code=6, scale=1: rounded sources give 0x3b11; f32 sources give 0x3b12. + try std.testing.expectEqual(@as(u16, 0x3b11), nvfp4Weight(7, 0x38)); + const factor = bf(test_amax) / bf(test_den); + try std.testing.expectEqual(@as(f32, 1) / 2704, factor); + const unrounded = c.toBf16(e2m1(7) * e4m3(0x38) * (test_amax / test_den)); + try std.testing.expectEqual(@as(u16, 0x3b12), unrounded); +} + +test "MXFP8 UE8M0 scale 255 decodes to positive infinity" { + try std.testing.expectEqual(std.math.inf(f32), ue8m0(255)); + try std.testing.expectEqual(@as(u16, 0x7f80), mxfp8Weight(0x38, 255)); +} + +test "A12: ascending experts retain the unit cancelled in route order" { + var route_sum: f32 = 0; + for (0..slots) |slot| route_sum += routeWeight(0, slot); + try std.testing.expectEqual(@as(f32, 0), route_sum); + var expert_sum: f32 = 0; + for (0..experts) |e| for (0..slots) |slot| { + if (route(slot) == e) expert_sum += routeWeight(0, slot); + }; + try std.testing.expectEqual(@as(f32, 1), expert_sum); +} + +test "the independent baseline's CUDA structs match experts.cu" { + try std.testing.expectEqual(@as(usize, 48), @sizeOf(CombineArgs)); + try std.testing.expectEqual(@as(usize, 24), @sizeOf(TensorActArgs)); + try std.testing.expectEqual(@as(usize, 16), @offsetOf(TensorActArgs, "n")); +} diff --git a/zig/tests/cuda/contract_inkling2_ops_mix.zig b/zig/tests/cuda/contract_inkling2_ops_mix.zig index 22fc073bf40..b837c657b8b 100644 --- a/zig/tests/cuda/contract_inkling2_ops_mix.zig +++ b/zig/tests/cuda/contract_inkling2_ops_mix.zig @@ -10,7 +10,8 @@ const g = core.contract.gates; const Iv = ref.Iv; const Sums = ref.Sums; const ops = ref.ops; -const C = ref.hidden; +const small_hidden = ref.hidden; +const mini_hidden = 2304; /// forward.zig's mixes: attention's (q, k and v queries, bf16 stream), the MLP's (fp32 residual), layer 0's (no query). pub const Form = enum { attn, mlp, first }; @@ -23,16 +24,16 @@ fn nq(f: Form) usize { } /// A thread's columns 512 apart, then the block's two shuffle stages. -fn depth(_: c.Shape) usize { - return ref.blockDepth(C, 512); +fn depth(s: c.Shape) usize { + return ref.blockDepth(s.n, 512); } /// Rows x hidden x blocks (completed blocks + the partial): mix_rows takes calls of more than 16 rows, mix the rest. pub fn mixSpec(f: Form, narrow: bool, fault: Fault) c.Spec { - const wide = &[_]c.Shape{ .{ .rows = 17, .n = C, .k = 9 }, .{ .rows = 64, .n = C, .k = 5 }, .{ .rows = 2048, .n = C, .k = 9 }, .{ .rows = 128, .n = C, .k = 1 }, .{ .rows = 32, .n = C, .k = 2 } }; - const decode = &[_]c.Shape{ .{ .rows = 1, .n = C, .k = 9 }, .{ .rows = 16, .n = C, .k = 9 }, .{ .rows = 8, .n = C, .k = 5 }, .{ .rows = 2, .n = C, .k = 1 }, .{ .rows = 4, .n = C, .k = 2 } }; - const one = &[_]c.Shape{ .{ .rows = 17, .n = C, .k = 1 }, .{ .rows = 2048, .n = C, .k = 1 }, .{ .rows = 64, .n = C, .k = 1 } }; - const one_decode = &[_]c.Shape{ .{ .rows = 1, .n = C, .k = 1 }, .{ .rows = 16, .n = C, .k = 1 }, .{ .rows = 5, .n = C, .k = 1 } }; + const wide = &[_]c.Shape{ .{ .rows = 17, .n = small_hidden, .k = 9 }, .{ .rows = 64, .n = small_hidden, .k = 5 }, .{ .rows = 2048, .n = small_hidden, .k = 9 }, .{ .rows = 128, .n = small_hidden, .k = 1 }, .{ .rows = 32, .n = small_hidden, .k = 2 }, .{ .rows = 17, .n = mini_hidden, .k = 5 }, .{ .rows = 64, .n = mini_hidden, .k = 3 }, .{ .rows = 2048, .n = mini_hidden, .k = 5 }, .{ .rows = 128, .n = mini_hidden, .k = 1 }, .{ .rows = 32, .n = mini_hidden, .k = 2 } }; + const decode = &[_]c.Shape{ .{ .rows = 1, .n = small_hidden, .k = 9 }, .{ .rows = 16, .n = small_hidden, .k = 9 }, .{ .rows = 8, .n = small_hidden, .k = 5 }, .{ .rows = 2, .n = small_hidden, .k = 1 }, .{ .rows = 4, .n = small_hidden, .k = 2 }, .{ .rows = 1, .n = mini_hidden, .k = 5 }, .{ .rows = 16, .n = mini_hidden, .k = 5 }, .{ .rows = 8, .n = mini_hidden, .k = 3 }, .{ .rows = 2, .n = mini_hidden, .k = 1 }, .{ .rows = 4, .n = mini_hidden, .k = 2 } }; + const one = &[_]c.Shape{ .{ .rows = 17, .n = small_hidden, .k = 1 }, .{ .rows = 2048, .n = small_hidden, .k = 1 }, .{ .rows = 64, .n = small_hidden, .k = 1 }, .{ .rows = 17, .n = mini_hidden, .k = 1 }, .{ .rows = 2048, .n = mini_hidden, .k = 1 }, .{ .rows = 64, .n = mini_hidden, .k = 1 } }; + const one_decode = &[_]c.Shape{ .{ .rows = 1, .n = small_hidden, .k = 1 }, .{ .rows = 16, .n = small_hidden, .k = 1 }, .{ .rows = 5, .n = small_hidden, .k = 1 }, .{ .rows = 1, .n = mini_hidden, .k = 1 }, .{ .rows = 16, .n = mini_hidden, .k = 1 }, .{ .rows = 5, .n = mini_hidden, .k = 1 } }; const names = [2][3][]const u8{ .{ "inkling2 ops tf_ink2_mix_rows attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix_rows MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix_rows layer 0 (no query)" }, .{ "inkling2 ops tf_ink2_mix attention (3 queries, bf16 stream)", "inkling2 ops tf_ink2_mix MLP (1 query, fp32 residual)", "inkling2 ops tf_ink2_mix layer 0 (no query)" }, @@ -93,10 +94,11 @@ pub const Mix = struct { /// Values in [-2, 2) with one in 61 eight times larger, queries in [-1, 1); stress: integers in [-16, 16]. pub fn prepare(self: *Mix, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { - if (shape.rows == 0 or shape.n != C or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; + if (shape.rows == 0 or (shape.n != small_hidden and shape.n != mini_hidden) or shape.k < 1 or shape.k > ops.max_blocks + 1) return false; self.free(a); self.shape = shape; - const rows = shape.rows; + const C = self.shape.n; + const rows = self.shape.rows; const nb = shape.k - 1; const q = nq(self.form); const stress = fill == .stress; @@ -116,7 +118,7 @@ pub const Mix = struct { if (nb == 0) ref.plant(f32, self.part, 1, C, ref.asF32); if (rows > 1) ref.plant(f32, self.part[C..], @min(rows - 1, 3), C, ref.asF32); } - var m: ops.MixArgs = .{ .partial = 0, .query = 0, .out = 0, .n_blocks = @intCast(nb), .partial_bf16 = @intFromBool(self.bf16Part()), .nq = @intCast(q), .rows = @intCast(rows), .c = C, .eps = ref.eps }; + var m: ops.MixArgs = .{ .partial = 0, .query = 0, .out = 0, .n_blocks = @intCast(nb), .partial_bf16 = @intFromBool(self.bf16Part()), .nq = @intCast(q), .rows = @intCast(rows), .c = @intCast(C), .eps = ref.eps }; for (0..nb) |j| m.blocks[j] = try ref.input(rig, self.blocks[j * rows * C ..][0 .. rows * C]); if (self.bf16Part()) { const h = try a.alloc(u16, rows * C); @@ -153,16 +155,19 @@ pub const Mix = struct { } pub fn count(self: *const Mix) usize { + const C = self.shape.n; return nq(self.form) * self.shape.rows * C; } fn at(self: *const Mix, j: usize, r: usize, col: usize) f64 { + const C = self.shape.n; const nb = self.shape.k - 1; return if (j < nb) ref.bf(self.blocks[(j * self.shape.rows + r) * C + col]) else self.part[r * C + col]; } /// Each row as the kernels compute it: every block's RMS and query dots, a softmax a query, the mix, its norm. pub fn solve(self: *const Mix, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const C = self.shape.n; const rows = self.shape.rows; const n = self.shape.k; const q = nq(self.form); @@ -173,7 +178,7 @@ pub const Mix = struct { const h = try a.alloc(Iv, q * C); defer a.free(h); const d = depth(self.shape); - const root = Iv.of(C).rsqrt(); + const root = Iv.of(@as(f64, @floatFromInt(C))).rsqrt(); for (0..rows) |r| { var rr: [ops.max_blocks + 1]Iv = undefined; var w: [ops.max_queries][ops.max_blocks + 1]Iv = undefined; @@ -182,8 +187,8 @@ pub const Mix = struct { for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(Iv.of(self.at(j, r, col))); rr[j] = ref.rms(s.sum(terms, d, scratch), C, 1e-6); for (0..q) |qi| { - for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(Iv.of(self.query[qi * C + col])); - w[qi][j] = s.sum(terms, d, scratch).mul(rr[j]).mul(root); + for (terms, 0..) |*t, col| t.* = Iv.of(self.at(j, r, col)).mul(rr[j]).mul(Iv.of(self.query[qi * C + col])); + w[qi][j] = s.sum(terms, d, scratch).mul(root); } } for (0..q) |qi| softmax(w[qi][0..n]); @@ -220,3 +225,26 @@ fn softmax(l: []Iv) void { } for (l, 0..) |*v, j| v.* = e[j].div(t); } + +test "mix normalizes each FP32 query term before reduction and scales after its dot" { + const source = [_]f32{ + @bitCast(@as(u32, 0x3f800008)), @bitCast(@as(u32, 0x3f800001)), + @bitCast(@as(u32, 0x40400001)), 0, + }; + const query = [_]f32{ + @bitCast(@as(u32, 0x3f800010)), @bitCast(@as(u32, 0x3fffffff)), + @bitCast(@as(u32, 0xc0000001)), 0, + }; + const inv: f32 = @bitCast(@as(u32, 0x3f800001)); + var dot: f32 = 0; + var raw_dot: f32 = 0; + for (source, query) |x, q| { + dot = @mulAdd(f32, q, x * inv, dot); + raw_dot = @mulAdd(f32, q, x, raw_dot); + } + const inverse_root_h: f32 = 0.5; + const scaled = dot * inverse_root_h; + const old = raw_dot * inv * inverse_root_h; + try std.testing.expectEqual(@as(u32, 0xbfbffffb), @as(u32, @bitCast(scaled))); + try std.testing.expectEqual(@as(u32, 0xbfbffffa), @as(u32, @bitCast(old))); +} diff --git a/zig/tests/cuda/contract_inkling2_ops_route.zig b/zig/tests/cuda/contract_inkling2_ops_route.zig index c17be9c5860..8e04891dab9 100644 --- a/zig/tests/cuda/contract_inkling2_ops_route.zig +++ b/zig/tests/cuda/contract_inkling2_ops_route.zig @@ -21,7 +21,7 @@ const topk_rule = "the 8 largest score + bias, the lower id on ties, a NaN never /// Rows x experts x picks: every row of a call, a block each. pub fn topkSpec(unbiased: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = experts, .k = top }, .{ .rows = 1, .n = experts, .k = top }, .{ .rows = 128, .n = experts, .k = top }, .{ .rows = 2048, .n = experts, .k = top } }; + const served = &[_]c.Shape{ .{ .rows = 16, .n = experts, .k = top }, .{ .rows = 1, .n = experts, .k = top }, .{ .rows = 128, .n = experts, .k = top }, .{ .rows = 2048, .n = experts, .k = top }, .{ .rows = 16, .n = 128, .k = top }, .{ .rows = 1, .n = 128, .k = top }, .{ .rows = 128, .n = 128, .k = top }, .{ .rows = 2048, .n = 128, .k = top } }; const name = if (unbiased) "control: inkling2 ops tf_ink2_topk without the selection bias" else "inkling2 ops tf_ink2_topk (sigmoid scores, bias, route scale 8)"; return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = topk_rule }, .served = if (unbiased) served[0..2] else served }; } @@ -122,7 +122,7 @@ pub const Topk = struct { const had: f64 = @as(f32, 0.08838834764831845); // exl3_decode.cuh's HAD_SCALE, as fp32 holds it const gate_cap: f32 = 4; const up_cap: f32 = 25; -const width = 1152; // a rank's 2,304-wide expert intermediate at TP=2 +const width = 1152; // Small's width at TP=2; Mini runs one rank with the same full width. const fixture_experts = 8; /// fwht128 and tf_exl3_fwht alike: butterflies (lo + hi, lo - hi) at strides 1, 2, ..., 64 of the 128 values. @@ -142,7 +142,7 @@ fn gateDepth(s: c.Shape) usize { /// (row, slot) pairs x a rank's width x the gate/up's K splits: 1 row, 16, a 128-row window, a 2,048-row window. pub fn gateupSpec(swapped: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 8, .n = width, .k = 4 }, .{ .rows = 128, .n = width, .k = 4 }, .{ .rows = 1024, .n = width, .k = 4 }, .{ .rows = 16384, .n = width, .k = 4 } }; + const served = &[_]c.Shape{ .{ .rows = 8, .n = width, .k = 4 }, .{ .rows = 128, .n = width, .k = 4 }, .{ .rows = 1024, .n = width, .k = 4 }, .{ .rows = 16384, .n = width, .k = 4 }, .{ .rows = 8, .n = width, .k = 2 }, .{ .rows = 128, .n = width, .k = 2 }, .{ .rows = 1024, .n = width, .k = 2 }, .{ .rows = 16384, .n = width, .k = 2 } }; const name = if (swapped) "control: inkling2 ops tf_ink2_gateup with the caps swapped" else "inkling2 ops tf_ink2_gateup (softcapped SwiGLU, gate cap 4, up cap 25)"; return .{ .name = name, .accum = .f32, .depth = gateDepth, .out = .f16, .tiles = .{ .{}, .{ .size = 128, .step = 128, .min = 128 }, .{} }, .served = if (swapped) served[0..2] else served }; } diff --git a/zig/tests/cuda/contract_inkling2_ops_rows.zig b/zig/tests/cuda/contract_inkling2_ops_rows.zig index cb17ac6cbe0..953f54fb68a 100644 --- a/zig/tests/cuda/contract_inkling2_ops_rows.zig +++ b/zig/tests/cuda/contract_inkling2_ops_rows.zig @@ -21,7 +21,7 @@ fn embedDepth(s: c.Shape) usize { /// Rows x hidden x hidden: a prompt chunk, a verify window, one decode row (the drafter's anchor embeds one too). pub fn embedSpec(shifted: bool) c.Spec { - const served = &[_]c.Shape{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C } }; + const served = &[_]c.Shape{ .{ .rows = 16, .n = C, .k = C }, .{ .rows = 1, .n = C, .k = C }, .{ .rows = 128, .n = C, .k = C }, .{ .rows = 2048, .n = C, .k = C }, .{ .rows = 16, .n = 2304, .k = 2304 }, .{ .rows = 1, .n = 2304, .k = 2304 }, .{ .rows = 128, .n = 2304, .k = 2304 }, .{ .rows = 2048, .n = 2304, .k = 2304 } }; if (shifted) return .{ .name = "control: inkling2 ops tf_ink2_embed gathering the next row", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served[0..2] }; return .{ .name = "inkling2 ops tf_ink2_embed (embed_norm, rounded once)", .accum = .f32, .depth = embedDepth, .out = .bf16, .served = served }; } @@ -114,14 +114,14 @@ fn dotDepth(s: c.Shape) usize { /// Rows x outputs x hidden; tiles: calls of 32 rows or more with fp32 out (router, taps), bit-equal to tf_ink2_rowdot. pub fn dotSpec(d: Dot, tiles: bool, short: bool) c.Spec { const plain: []const c.Shape = switch (d) { // comptime arrays: a spec outlives this call - .router => &.{ .{ .rows = 16, .n = 384, .k = C }, .{ .rows = 1, .n = 384, .k = C }, .{ .rows = 31, .n = 384, .k = C }, .{ .rows = 7, .n = 384, .k = C } }, - .sink => &.{ .{ .rows = 16, .n = 24, .k = C }, .{ .rows = 1, .n = 24, .k = C }, .{ .rows = 128, .n = 24, .k = C }, .{ .rows = 2048, .n = 24, .k = C } }, - .taps => &.{ .{ .rows = 16, .n = 16, .k = C }, .{ .rows = 1, .n = 16, .k = C }, .{ .rows = 31, .n = 16, .k = C } }, + .router => &.{ .{ .rows = 16, .n = 384, .k = C }, .{ .rows = 1, .n = 384, .k = C }, .{ .rows = 31, .n = 384, .k = C }, .{ .rows = 7, .n = 384, .k = C }, .{ .rows = 16, .n = 128, .k = 2304 }, .{ .rows = 1, .n = 128, .k = 2304 }, .{ .rows = 31, .n = 128, .k = 2304 }, .{ .rows = 7, .n = 128, .k = 2304 } }, + .sink => &.{ .{ .rows = 16, .n = 24, .k = C }, .{ .rows = 1, .n = 24, .k = C }, .{ .rows = 128, .n = 24, .k = C }, .{ .rows = 2048, .n = 24, .k = C }, .{ .rows = 16, .n = 24, .k = 2304 }, .{ .rows = 1, .n = 24, .k = 2304 }, .{ .rows = 128, .n = 24, .k = 2304 }, .{ .rows = 2048, .n = 24, .k = 2304 } }, + .taps => &.{ .{ .rows = 16, .n = 16, .k = C }, .{ .rows = 1, .n = 16, .k = C }, .{ .rows = 31, .n = 16, .k = C }, .{ .rows = 16, .n = 16, .k = 2304 }, .{ .rows = 1, .n = 16, .k = 2304 }, .{ .rows = 31, .n = 16, .k = 2304 } }, }; const wide: []const c.Shape = if (d == .router) - &.{ .{ .rows = 64, .n = 384, .k = C }, .{ .rows = 32, .n = 384, .k = C }, .{ .rows = 100, .n = 384, .k = C }, .{ .rows = 2048, .n = 384, .k = C } } + &.{ .{ .rows = 64, .n = 384, .k = C }, .{ .rows = 32, .n = 384, .k = C }, .{ .rows = 100, .n = 384, .k = C }, .{ .rows = 2048, .n = 384, .k = C }, .{ .rows = 64, .n = 128, .k = 2304 }, .{ .rows = 32, .n = 128, .k = 2304 }, .{ .rows = 100, .n = 128, .k = 2304 }, .{ .rows = 2048, .n = 128, .k = 2304 } } else - &.{ .{ .rows = 64, .n = 16, .k = C }, .{ .rows = 32, .n = 16, .k = C }, .{ .rows = 100, .n = 16, .k = C }, .{ .rows = 2048, .n = 16, .k = C } }; + &.{ .{ .rows = 64, .n = 16, .k = C }, .{ .rows = 32, .n = 16, .k = C }, .{ .rows = 100, .n = 16, .k = C }, .{ .rows = 2048, .n = 16, .k = C }, .{ .rows = 64, .n = 16, .k = 2304 }, .{ .rows = 32, .n = 16, .k = 2304 }, .{ .rows = 100, .n = 16, .k = 2304 }, .{ .rows = 2048, .n = 16, .k = 2304 } }; const names = [3][2][]const u8{ .{ "inkling2 ops tf_ink2_rowdot router (fp32 sigmoid scores)", "inkling2 ops tf_ink2_rowdot_tiles router (fp32 sigmoid scores)" }, .{ "inkling2 ops tf_ink2_rowdot attention sinks (bf16 sigmoid)", "" }, diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 9198c30174a..acbb9b75998 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -32,7 +32,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; } diff --git a/zig/tests/cuda/inkling2_serving_tests.zig b/zig/tests/cuda/inkling2_serving_tests.zig new file mode 100644 index 00000000000..b393c3099c9 --- /dev/null +++ b/zig/tests/cuda/inkling2_serving_tests.zig @@ -0,0 +1,489 @@ +//! Real Inkling 2 Mini CUDA serving: device draws against host selection, snapshots, admission and copied drafts. +const std = @import("std"); +const lanes = @import("lanes"); +const mini = @import("inkling2"); +const cuda = @import("cuda"); +const check = @import("check.zig"); + +const native = mini.native; +const Backend = @TypeOf(@as(native.Owned, undefined).backend); +const Gpu = check.Gpu; +const sampled: lanes.Sampling = .{ .seed = 37, .temperature = 0.8, .top_k = 64, .top_p = 0.95 }; + +const Trace = struct { + ids: []u32, + logits: []f32, + cached: u32, + failed: bool, + + fn deinit(t: *Trace, gpa: std.mem.Allocator) void { + gpa.free(t.ids); + gpa.free(t.logits); + } +}; + +fn target(loaded: *native.Loaded) *Backend { + return &loaded.target.backend; +} + +fn download(b: *Backend, src: u64, out: []f32) !void { + try b.s.synchronize(); + try cuda.memory.download(b.d, src, std.mem.sliceAsBytes(out)); +} + +/// A real target pass with either CUDA's draws or host selection over its downloaded fp32 logits. +fn trace(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, n: usize, host: bool, reuse: lanes.stream.Reuse) !Trace { + const t = target(loaded); + const v = t.m.w.c.text.unpadded_vocab; + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-trace", .prompt = prompt, .max_new = @intCast(n), .sampling = sampling, .reuse = reuse }); + defer s.deinit(gpu.gpa); + const b = loaded.backend; + defer b.release(&s); + const ids = try gpu.gpa.alloc(u32, n); + errdefer gpu.gpa.free(ids); + const logits = try gpu.gpa.alloc(f32, n * v); + errdefer gpu.gpa.free(logits); + try b.prefill(&s); + try download(t, try t.lastOf(&s), logits[0..v]); + var handle: ?u64 = try b.first(&s, prompt.len); + for (0..n) |i| { + ids[i] = if (host) try lanes.gpu_full.draw(gpu.gpa, logits[i * v ..][0..v], sampling, @intCast(prompt.len + i), null) else try b.read(handle.?); + if (i + 1 < n) { + handle = try b.queue(&s, .{ .value = ids[i] }, prompt.len + i + 1); + try download(t, t.m.s.logits, logits[(i + 1) * v ..][0..v]); + } + } + return .{ .ids = ids, .logits = logits, .cached = s.cached, .failed = s.reuse_failed }; +} + +fn sameTrace(a: *const Trace, b: *const Trace) !void { + if (!std.mem.eql(u32, a.ids, b.ids)) return error.MiniServingTokenMismatch; + if (!std.mem.eql(u8, std.mem.sliceAsBytes(a.logits), std.mem.sliceAsBytes(b.logits))) return error.MiniServingLogitMismatch; +} + +fn hostReference(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }, 0..) |sampling, case| { + var device = try trace(gpu, loaded, prompt, sampling, 12, false, .{}); + defer device.deinit(gpu.gpa); + var host = try trace(gpu, loaded, prompt, sampling, 12, true, .{}); + defer host.deinit(gpu.gpa); + sameTrace(&device, &host) catch |err| { + std.debug.print("RESULT mini-serving host-reference case={d} mismatch={s}\n", .{ case, @errorName(err) }); + return err; + }; + } +} + +/// Save one complete state at `cut`, restore it through the genuine prompt-reuse hook and rerun the suffix. +fn resumedAt(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, cut: u32, sampling: ?lanes.Sampling, fresh: *const Trace) !void { + const Saved = @TypeOf(loaded.target.model).Saved; + const Keeper = struct { + b: *Backend, + saved: ?*Saved = null, + fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.saved = k.b.saveState(s, mark) catch null; + } + }; + const t = target(loaded); + const saved = snapshot: { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-snapshot", .prompt = prompt, .max_new = 1, .reuse = .{ .marks = &.{cut} } }); + defer s.deinit(gpu.gpa); + const b = loaded.backend; + defer b.release(&s); + var keeper: Keeper = .{ .b = t }; + s.reuse.hook = .{ .ptr = &keeper, .at = Keeper.at }; + try b.prefill(&s); + break :snapshot keeper.saved orelse return error.MiniSnapshotNotSaved; + }; + defer t.dropState(saved); + var resumed = try trace(gpu, loaded, prompt, sampling, fresh.ids.len, false, .{ .saved = saved, .at = cut }); + defer resumed.deinit(gpu.gpa); + if (resumed.cached != cut or resumed.failed) return error.MiniSnapshotNotRestored; + try sameTrace(fresh, &resumed); +} + +/// A keeps states at 14 and 39; B resumes A's 14, keeps its 39 and decodes; A resumed at 39 must equal fresh A. +fn crossPrompt(gpu: Gpu, loaded: *native.Loaded, ids: []const u32) !void { + const Saved = @TypeOf(loaded.target.model).Saved; + const Keeper = struct { + b: *Backend, + saved: [2]?*Saved = .{ null, null }, + fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.saved[@intFromBool(mark != 14)] = k.b.saveState(s, mark) catch null; + } + }; + const t = target(loaded); + const b = loaded.backend; + const a = ids[0..40]; + var other: [40]u32 = undefined; + @memcpy(other[0..14], ids[0..14]); + @memcpy(other[14..], ids[500..526]); + var fresh = try trace(gpu, loaded, a, null, 8, false, .{}); + defer fresh.deinit(gpu.gpa); + var ka: Keeper = .{ .b = t }; + defer for (ka.saved) |x| if (x) |y| t.dropState(y); + { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-a", .prompt = a, .max_new = 1, .reuse = .{ .marks = &.{ 14, 39 } } }); + defer s.deinit(gpu.gpa); + defer b.release(&s); + s.reuse.hook = .{ .ptr = &ka, .at = Keeper.at }; + try b.prefill(&s); + } + var kb: Keeper = .{ .b = t }; + defer for (kb.saved) |x| if (x) |y| t.dropState(y); + { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-b", .prompt = &other, .max_new = 8, .reuse = .{ .saved = ka.saved[0] orelse return error.MiniSnapshotNotSaved, .at = 14, .marks = &.{39} } }); + defer s.deinit(gpu.gpa); + defer b.release(&s); + s.reuse.hook = .{ .ptr = &kb, .at = Keeper.at }; + try b.prefill(&s); + if (s.cached != 14 or kb.saved[1] == null) return error.MiniSnapshotNotRestored; + var h = try b.first(&s, other.len); + for (0..6) |i| h = try b.queue(&s, .{ .handle = h }, other.len + i + 1); + } + var resumed = try trace(gpu, loaded, a, null, 8, false, .{ .saved = ka.saved[1] orelse return error.MiniSnapshotNotSaved, .at = 39 }); + defer resumed.deinit(gpu.gpa); + if (resumed.cached != 39 or resumed.failed) return error.MiniSnapshotNotRestored; + sameTrace(&fresh, &resumed) catch |err| { + std.debug.print("RESULT mini-serving cross-prompt resume mismatch={s} fresh={any} resumed={any}\n", .{ @errorName(err), fresh.ids, resumed.ids }); + return err; + }; +} + +/// A history on the chunk grid is kept at its end and decoded on; after another prompt, its next turn resumed == fresh. +fn turnAfterHistory(gpu: Gpu, loaded: *native.Loaded, ids: []const u32) !void { + const Saved = @TypeOf(loaded.target.model).Saved; + const Keeper = struct { + b: *Backend, + saved: ?*Saved = null, + fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.saved = k.b.saveState(s, mark) catch null; + } + }; + const t = target(loaded); + const b = loaded.backend; + const history = native.prompt_rows; + var turn: [history + 16]u32 = undefined; + @memcpy(turn[0..history], ids[0..history]); + @memcpy(turn[history..], ids[6000..6016]); + var keeper: Keeper = .{ .b = t }; + defer if (keeper.saved) |x| t.dropState(x); + { + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-history", .prompt = ids[0..history], .max_new = 24, .reuse = .{ .marks = &.{history} } }); + defer s.deinit(gpu.gpa); + defer b.release(&s); + s.reuse.hook = .{ .ptr = &keeper, .at = Keeper.at }; + try b.prefill(&s); + if (keeper.saved == null) return error.MiniSnapshotNotSaved; + var h = try b.first(&s, history); + for (0..23) |i| h = try b.queue(&s, .{ .handle = h }, history + i + 1); + } + for ([_]?lanes.Sampling{ null, sampled }, 0..) |sampling, case| { + var other = try trace(gpu, loaded, ids[3000 .. 3000 + history + 100], null, 2, false, .{}); + other.deinit(gpu.gpa); + var resumed = try trace(gpu, loaded, &turn, sampling, 24, false, .{ .saved = keeper.saved.?, .at = history }); + defer resumed.deinit(gpu.gpa); + if (resumed.cached != history or resumed.failed) return error.MiniSnapshotNotRestored; + var fresh = try trace(gpu, loaded, &turn, sampling, 24, false, .{}); + defer fresh.deinit(gpu.gpa); + if (fresh.cached != 0) return error.MiniFreshTurnCached; + sameTrace(&fresh, &resumed) catch |err| { + std.debug.print("RESULT mini-serving turn after history case={d} mismatch={s}\n", .{ case, @errorName(err) }); + return err; + }; + } +} + +/// A state saved from one capacity restores into a cache of another: each head's kept rows land at their positions. +fn otherCapacity(gpu: Gpu, loaded: *native.Loaded) !void { + const Model = @TypeOf(loaded.target.model); + const ks = mini.kept_state; + const a = &loaded.target.model; + const s = loaded.target.stream; + a.slot = 0; + const window = a.w.c.text.window; + const from = try gpu.gpa.alloc(u8, a.layout.bytes); + defer gpu.gpa.free(from); + // At context 3500 B's sliding rings are A's and wrap by 3300, its global ones shorter; at 1500 all are shorter. + for ([_][2]u32{ .{ 3500, 3300 }, .{ 1500, 1400 } }) |case| { + var b = try Model.init(gpu.gpa, a.d, s, a.w, case[0]); + defer b.deinit(); + const to = try gpu.gpa.alloc(u8, b.layout.bytes); + defer gpu.gpa.free(to); + var prng = std.Random.DefaultPrng.init(case[0]); + prng.random().bytes(from); + prng.random().bytes(to); + try cuda.copy_source.enqueue(a.d, a.slots[0].cache.ptr, from, s); + try cuda.copy_source.enqueue(a.d, b.slots[0].cache.ptr, to, s); + const saved = try a.save(s, case[1]); + defer a.drop(s, saved); + try b.restore(s, saved); + try s.synchronize(); + try cuda.memory.download(a.d, b.slots[0].cache.ptr, to); + var va: [a.w.p.visits.len]ks.Visit = undefined; + var vb: [a.w.p.visits.len]ks.Visit = undefined; + const at = case[1]; + for (a.keptVisits(&va), b.keptVisits(&vb), 0..) |x, y, visit| for (0..2) |side| for (0..x.heads) |h| { + for (at - ks.kept(x.global, window, at)..at) |p| { + const ra = (if (side == 0) x.k else x.v) - a.slots[0].cache.ptr + (h * x.ring + p % x.ring) * x.row; + const rb = (if (side == 0) y.k else y.v) - b.slots[0].cache.ptr + (h * y.ring + p % y.ring) * y.row; + if (!std.mem.eql(u8, from[ra..][0..x.row], to[rb..][0..y.row])) { + std.debug.print("RESULT mini-serving other capacity {d}: visit {d} side {d} head {d} position {d} moved\n", .{ case[0], visit, side, h, p }); + return error.MiniKeptRowMoved; + } + } + }; + if (!std.mem.eql(u8, from[a.layout.at(0).conv_offset..], to[b.layout.at(0).conv_offset..])) return error.MiniKeptConvMoved; + } +} + +fn freshAndResumed(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }, 0..) |sampling, case| { + var fresh = try trace(gpu, loaded, prompt, sampling, 8, false, .{}); + defer fresh.deinit(gpu.gpa); + const cuts: []const u32 = if (case == 0) &.{ 17, 2048 } else &.{ 2049, @intCast(prompt.len - 1) }; + for (cuts) |cut| try resumedAt(gpu, loaded, prompt, cut, sampling, &fresh); + } +} + +fn serve(gpu: Gpu, loaded: *native.Loaded, s: *lanes.Stream, proposer: ?lanes.proposer.Proposer) !void { + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + defer cfg.deinit(gpu.gpa); + cfg.timed = false; + var clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); + defer e.deinit(); + if (proposer) |p| s.proposer = p; + try e.addStream(s); + while (!s.finished) try e.step(); + if (s.reason != .length) return error.MiniServingDidNotFinish; +} + +fn admission(gpu: Gpu, loaded: *native.Loaded, a: []const u32, b: []const u32) !void { + var plain_a = try trace(gpu, loaded, a, null, 10, false, .{}); + defer plain_a.deinit(gpu.gpa); + var plain_b = try trace(gpu, loaded, b, sampled, 10, false, .{}); + defer plain_b.deinit(gpu.gpa); + var first = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-first", .prompt = a, .max_new = 10 }); + defer first.deinit(gpu.gpa); + var second = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-second", .prompt = b, .max_new = 10, .sampling = sampled }); + defer second.deinit(gpu.gpa); + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + defer cfg.deinit(gpu.gpa); + cfg.timed = false; + var clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); + defer e.deinit(); + if (!native.fits(loaded.ctx, @intCast(a.len), first.max_new)) return error.MiniUnexpectedFreeSlot; + try e.addStream(&first); + if (native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniBusyAdmissionRefused; + try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&second)); + while (!first.finished) try e.step(); + try std.testing.expectEqual(lanes.stream.Reason.length, first.reason); + if (!std.mem.eql(u32, first.emitted(), plain_a.ids)) return error.MiniAdmissionChangedFirst; + if (!native.fits(loaded.ctx, @intCast(b.len), second.max_new)) return error.MiniSlotNotReleased; + try e.addStream(&second); + while (!second.finished) try e.step(); + try std.testing.expectEqual(lanes.stream.Reason.length, second.reason); + if (!std.mem.eql(u32, second.emitted(), plain_b.ids)) return error.MiniAdmissionChangedSecond; +} + +/// Four slots: interleaved greedy and seeded streams equal solo; a fifth is refused before anything is queued. +fn concurrent(gpu: Gpu, loaded: *native.Loaded, ids: []const u32) !void { + const n = 4; + const cuts = [n][2]usize{ .{ 0, 257 }, .{ 17, 1042 }, .{ 300, 2400 }, .{ 5, 70 } }; + var solo: [n]Trace = undefined; + var done: usize = 0; + defer for (solo[0..done]) |*x| x.deinit(gpu.gpa); + for (cuts, 0..) |c, i| { + solo[i] = try trace(gpu, loaded, ids[c[0]..c[1]], if (i % 2 == 0) null else sampled, 10, false, .{}); + done += 1; + } + try loaded.reserve(loaded.ctx, n); + { + var busy: [n]lanes.Stream = undefined; + var opened: usize = 0; + defer for (busy[0..opened]) |*x| { + loaded.backend.release(x); + x.deinit(gpu.gpa); + }; + for (&busy, 0..) |*x, i| { + x.* = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-busy", .prompt = ids[i .. i + 8], .max_new = 1 }); + opened += 1; + if (!native.fits(loaded.ctx, 8, 1)) return error.MiniSlotMissing; + try loaded.backend.prefill(x); + } + if (native.fits(loaded.ctx, 8, 1)) return error.MiniFifthAdmitted; + var fifth = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-fifth", .prompt = ids[0..8], .max_new = 1 }); + defer fifth.deinit(gpu.gpa); + try std.testing.expectError(error.NoFreeSlot, loaded.backend.prefill(&fifth)); + if (fifth.fill_at.load(.monotonic) != 0) return error.MiniFifthQueued; + } + var streams: [n]lanes.Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*x| x.deinit(gpu.gpa); + for (cuts, 0..) |c, i| { + streams[i] = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-concurrent", .prompt = ids[c[0]..c[1]], .max_new = 10, .sampling = if (i % 2 == 0) null else sampled }); + made += 1; + } + var cfg = try lanes.Config.init(gpu.gpa, loaded.facts, native.prompt_rows, native.window_rows); + defer cfg.deinit(gpu.gpa); + cfg.timed = false; + var clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpu.gpa, &cfg, loaded.backend, clock.clock()); + defer e.deinit(); + for (&streams) |*x| try e.addStream(x); + var live = true; + while (live) { + try e.step(); + live = false; + for (&streams) |*x| live = live or !x.finished; + } + for (&streams, solo) |*x, want| { + if (x.reason != .length) return error.MiniServingDidNotFinish; + if (!std.mem.eql(u32, x.emitted(), want.ids)) return error.MiniConcurrentChangedTokens; + } +} + +/// Priced copies deliberately alternate whole matches, first-row rejection and a prefix match. +const Copier = struct { + prompt_len: usize, + plain: []const u32, + out: [4]u32 = undefined, + calls: usize = 0, + rejected: bool = false, + partial: bool = false, + continued: bool = false, + full: bool = false, + was_rejected: bool = false, + + fn propose(ptr: *anyopaque, context: []const u32, most: i64) anyerror![]const u32 { + const c: *@This() = @ptrCast(@alignCast(ptr)); + const n = context.len - c.prompt_len; + if (n >= c.plain.len or most < 2) return &.{}; + if (c.was_rejected) c.continued = true; + const count = @min(c.out.len, @min(c.plain.len - n, @as(usize, @intCast(most)))); + for (c.out[0..count], 0..) |*token, i| token.* = c.plain[n + i]; + const mode = c.calls % 3; + c.was_rejected = false; + if (mode == 0 and count >= 2) { + c.full = true; + } else if (mode == 1 and count >= 2) { + c.out[0] = if (c.out[0] == 0) 1 else 0; + c.rejected = true; + c.was_rejected = true; + } else if (count >= 2) { + c.out[1] = if (c.out[1] == 0) 1 else 0; + c.partial = true; + } + c.calls += 1; + return c.out[0..count]; + } + + fn proposer(c: *Copier) lanes.proposer.Proposer { + return .{ .ptr = c, .vtable = &.{ + .propose = propose, + .last_match = struct { + fn f(_: *anyopaque) i64 { + return 1; + } + }.f, + .priced = true, + } }; + } +}; + +/// Rewind a rejected, partially accepted or fully accepted window, then compare continuation bits with serial decode. +fn rollback(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32, sampling: ?lanes.Sampling, plain: []const u32, accepted: usize) !void { + const t = target(loaded); + const v = t.m.w.c.text.unpadded_vocab; + const next = accepted + 1; + const ref = try gpu.gpa.alloc(f32, v); + defer gpu.gpa.free(ref); + var serial = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-serial", .prompt = prompt, .max_new = 12, .sampling = sampling }); + defer serial.deinit(gpu.gpa); + const b = loaded.backend; + try b.prefill(&serial); + for (plain[0 .. next + 1], 0..) |token, i| _ = try b.queue(&serial, .{ .value = token }, prompt.len + i + 1); + try download(t, t.m.s.logits, ref); + b.release(&serial); + + var drafted = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-drafted", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); + defer drafted.deinit(gpu.gpa); + defer b.release(&drafted); + try b.prefill(&drafted); + const pending = plain[0]; + var tokens: [4]u32 = undefined; + for (&tokens, 0..) |*token, i| token.* = plain[i + 1]; + if (accepted < tokens.len) tokens[accepted] = if (tokens[accepted] == 0) 1 else 0; + var positions: [5]u64 = undefined; + for (&positions, 0..) |*p, i| p.* = prompt.len + i + 1; + const window: lanes.backend.Window = .{ .stream = &drafted, .tokens = &tokens, .parents = null, .positions = &positions, .pending = pending, .held = 0 }; + var picks: [5]u32 = undefined; + var drafts: [4]u32 = undefined; + var out = [1]lanes.backend.Verified{.{ .sampled = &picks, .drafts = &drafts }}; + try b.verify(&.{window}, &out); + if (picks[accepted] != plain[next]) return error.MiniWrongCorrection; + var path: [5]u32 = undefined; + for (path[0..next], 0..) |*p, i| p.* = @intCast(i); + try b.keep(&.{window}, &.{path[0..next]}); + const handle = try b.queue(&drafted, .{ .value = plain[next] }, prompt.len + next + 1); + const after = try gpu.gpa.alloc(f32, v); + defer gpu.gpa.free(after); + try download(t, t.m.s.logits, after); + if (!std.mem.eql(u8, std.mem.sliceAsBytes(ref), std.mem.sliceAsBytes(after))) return error.MiniRollbackChangedLogits; + if (try b.read(handle) != plain[next + 1]) return error.MiniPostRejectionTokenChanged; +} + +fn copiedDrafts(gpu: Gpu, loaded: *native.Loaded, prompt: []const u32) !void { + for ([_]?lanes.Sampling{ null, sampled }) |sampling| { + var plain = try trace(gpu, loaded, prompt, sampling, 12, false, .{}); + defer plain.deinit(gpu.gpa); + var copier: Copier = .{ .prompt_len = prompt.len, .plain = plain.ids }; + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "mini-copied", .prompt = prompt, .max_new = 12, .sampling = sampling, .drafts = true }); + defer s.deinit(gpu.gpa); + try serve(gpu, loaded, &s, copier.proposer()); + if (!std.mem.eql(u32, s.emitted(), plain.ids)) return error.MiniCopiesChangedTarget; + if (s.drafted == 0 or s.accepted == 0 or s.accepted == s.drafted) return error.MiniCopyCoverageMissing; + if (!(copier.full and copier.rejected and copier.partial and copier.continued)) return error.MiniCopyCaseMissing; + for ([_]usize{ 0, 1, 4 }) |accepted| try rollback(gpu, loaded, prompt, sampling, plain.ids, accepted); + } +} + +fn readIds(gpu: Gpu, path: []const u8) ![]u32 { + const text = try std.Io.Dir.cwd().readFileAlloc(gpu.io, path, gpu.gpa, .limited(1 << 26)); + defer gpu.gpa.free(text); + var out: std.ArrayList(u32) = .empty; + errdefer out.deinit(gpu.gpa); + var it = std.mem.tokenizeAny(u8, text, ", \n\r\t[]"); + while (it.next()) |t| try out.append(gpu.gpa, try std.fmt.parseInt(u32, t, 10)); + return out.toOwnedSlice(gpu.gpa); +} + +pub fn run(gpu: Gpu, model: []const u8, ids_path: []const u8) !void { + const ids = try readIds(gpu, ids_path); + defer gpu.gpa.free(ids); + if (ids.len < 4096) return error.MiniServingPromptTooShort; + const context = ids.len + 64; + var loaded = try native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = context, .drafts = true }); + defer loaded.deinit(loaded.ctx); + try hostReference(gpu, &loaded, ids[0..4096]); + check.pass("Mini CUDA serving matches the host reference token for token", .{}); + try freshAndResumed(gpu, &loaded, ids[0..2309]); + check.pass("Mini CUDA fresh and resumed prompts produce identical logits and tokens", .{}); + try crossPrompt(gpu, &loaded, ids); + check.pass("Mini CUDA a state resumed after another prompt resumed its prefix equals the fresh prompt", .{}); + try turnAfterHistory(gpu, &loaded, ids); + check.pass("Mini CUDA a turn after a history kept at the chunk grid resumes equal to fresh, after another prompt", .{}); + try admission(gpu, &loaded, ids[0..257], ids[17..1042]); + check.pass("Mini CUDA one-slot admission serializes concurrent requests without changing tokens", .{}); + try concurrent(gpu, &loaded, ids); + check.pass("Mini CUDA four slots: concurrent greedy and seeded replies equal solo, a fifth is refused", .{}); + try copiedDrafts(gpu, &loaded, ids[0..64]); + check.pass("Mini CUDA opt-in copy drafting preserves target tokens and rolls back exactly", .{}); + try otherCapacity(gpu, &loaded); + check.pass("Mini CUDA a kept state restores each head's rows into a cache of another capacity", .{}); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 3b20c3dbacc..972160f0062 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -145,6 +145,33 @@ fn arg(rest: []const [:0]const u8, i: usize) ![]const u8 { return rest[i]; } +fn compileInkling2Contracts() !void { + const shape: @import("core").contract.spec.Shape = .{ .rows = 1, .n = 2304, .k = 2 }; + const a: std.mem.Allocator = undefined; + const gpu: check.Gpu = undefined; + const stream: cuda.Stream = undefined; + var list: std.ArrayList(@import("core").contract.gates.Kernel) = .empty; + const set = try @import("contract_inkling2.zig").Set.init(gpu, stream, a, &list); + set.deinit(); + var rig: @import("contract_rig.zig").Rig = undefined; + const rng: std.Random = undefined; + var mix: @import("contract_inkling2_ops_mix.zig").Mix = undefined; + _ = try mix.prepare(a, &rig, shape, .random, rng); + try mix.run(&rig); + _ = try mix.replaced(&rig); + const sums: @import("contract_inkling2_ops_ref.zig").Sums = undefined; + const solved: []@import("contract_inkling2_ops_ref.zig").Iv = undefined; + try mix.solve(a, sums, solved); + var modelopt: @import("contract_inkling2_modelopt.zig").ModelOpt = undefined; + _ = try modelopt.prepare(shape, .random, 0); + try modelopt.run(); + _ = modelopt.kernel(); + _ = modelopt.count(); + const want: []f64 = undefined; + const mag: []f64 = undefined; + try modelopt.reference(want, mag); +} + fn compileContractGlue() !void { // the contract glue's device path, built with the runner: prepare through the vtable const cores = std.Thread.getCpuCount() catch 1; if (cores != 0) return; @@ -152,6 +179,7 @@ fn compileContractGlue() !void { // the contract glue's device path, built with g.kind = .chain; const kernels = [_]@import("core").contract.gates.Kernel{g.kernel()}; for (kernels) |k| _ = try k.vt.prepare(k.ctx, .{ .rows = 0, .n = 0, .k = 0 }, .random, 0); + try compileInkling2Contracts(); } fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { @@ -376,6 +404,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "kolibri-reference")) return kolibri_layer_tests.reference(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-layers")) return kolibri_layer_tests.layers(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-full")) return kolibri_tests.full(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); + if (std.mem.eql(u8, cmd, "inkling2-serving")) return @import("inkling2_serving_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-pages")) return @import("kolibri_pages_tests.zig").pages(gpu, rest); if (std.mem.eql(u8, cmd, "kolibri-greedy")) return kolibri_tests.greedy(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "kolibri-logits")) return kolibri_tests.logits(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), if (rest.len > 3) rest[3] else null); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 817792de607..687f4f28d77 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -3,6 +3,7 @@ pub const usage = \\usage: tf-cuda-test \\ qwen4 synthetic native Qwen4: binary64 logits/tokens, state seams, lanes and copied drafts + \\ inkling2-serving MODEL IDS_FILE Mini CUDA host-reference, resume, admission and copy-rollback serving equivalence \\ qwen-draft-frames MODEL DRAFTER IDS OUT native 27B DFlash frames: raw bytes equal across partitions, controls red \\ experts-rows experts_rows.cu's windows and chunks against the decode kernel's one-row launches \\ route-rows route_rows.cu's router logits and softmax top-k against float64 (synthetic rows) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index ac9b6b9dd82..38b6f21e94f 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 8bfc2f15a742cceba87dd7eb8e80f3f1b4e3f7eb323b557eb1bb4bf zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 0303722961597dd1d155363059dbac5ba88ccf42094deed894a81e33706b10c9 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #1858: the idol_decoder image registered +zig/src/cuda/kernels.zig 883d432ebce183cc554d6f0d61944a4d87df845f3eae3174d6f6307fed7e7612 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw