diff --git a/CHANGELOG.md b/CHANGELOG.md index 954b8ca91..b31a8f7b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ Releases of TandemEngine, TandemLLM's inference engine (TandemLLM up to 0.15.4; ## Unreleased +### Apple silicon + +- LFM2.5-24B-A2B runs on a Mac's GPU through MLX, in BF16, one request at a time, with the lookup drafter and StairCut (`engine/models/lfm2_moe/mlx_board.py`, `mlx_serving.py`, `tools/gpu/apple.py`). On an M5 Max: 94 tok/s plain through the server, 315 on an edit ask and 320 on a copy ask with the lookup (medians of 3 runs), every lookup text equal to the plain one. The prefix, session and disk caches, the KV pool, side slots and joint passes are off there. Numbers and checks: `docs/lfm2.5-24b-a2b.md`, "Apple silicon". +- A verify row has the decode step's bits on the Mac too. MLX's own matmul and attention round by the number of rows, so the board runs its own Metal kernels, which compute every row in an order fixed by the weight's shape (`engine/models/lfm2_moe/csrc/mlx_kernels/`). The self-check at load compares 101 rows byte for byte (chains of 2 to 32 rows, a tree, a 300-token prompt) and one differing byte turns speculation off; `tools/mlx_lfm_exact.py` checks the real checkpoint's verify rows against sequential decode (36 rows bit for bit). +- Dense projections of 3 rows and more run on the 8x8 matrix units and those of 1 or 2 rows on a scalar kernel that writes the same bits. The weights are repacked at load into the order the kernels read. +- `ops/prices/lfm2.5-24b-a2b/lfm25-bf16.apple-m5-max.json`: StairCut's prices for the M5 Max (`tools/mlx_lfm_prices.py`). +- Apple silicon is a `tools/gpu` adapter (`apple.py`), and `GpuProfile.backend()` says which array library a device's models run on; the LFM2 family's server builder picks its engine by it. Every family's cache fingerprint moves with the adapter's files, with no change to a CUDA row: a CUDA box rebuilds its disk caches once. + ### Fixes - The 27B no longer stops answering after a short chat follows a long one (SRV-885). The end of a request could lower the draft window's floor and leave the rows between the new floor and the old one unmapped. The next save of that conversation to the disk read them, the GPU faulted (an illegal memory access) and every request after it was a 503 `engine_failed` until a restart. A lowered floor now leaves those rows on the window's shared page until they are mapped again, and a trim drops only what lies past the rows it keeps. diff --git a/docs/lfm2.5-24b-a2b.md b/docs/lfm2.5-24b-a2b.md index cdf3ae19d..d2849c050 100644 --- a/docs/lfm2.5-24b-a2b.md +++ b/docs/lfm2.5-24b-a2b.md @@ -159,6 +159,50 @@ Then run `~/TandemLLM/bin/tandem restart`. Check that it took: `curl -s localhos Quality and speed against the exact cache: not measured. +## Apple silicon (M5 Max, MLX) + +BF16 only, one request at a time. Measured on an M5 Max with 128 GB, MLX 0.32.4, 2026-11-20; peak memory 51.3 GB in the bench run. + +- Board: `engine/models/lfm2_moe/mlx_board.py` computes in MLX; the server's loop stays in PyTorch on the CPU (`mlx_serving.py`). `tools/gpu/apple.py` is the device's adapter: it names the chip, keys the price file by it, and answers `backend()` with "mlx", which the family's server builder (`dispatch.py`) picks the engine by. +- Row kernels: MLX's own matmul and attention choose their kernel by the number of rows, so a verify row and the decode step's row of the same token round differently (an fp32 matmul of 2 rows or more runs at about TF32 precision). The board's Metal kernels (`engine/models/lfm2_moe/csrc/mlx_kernels/`, wrapped by `mlx_kernels.py`) compute every row in an order fixed by the weight's shape, never by the row count. A verify row has the decode step's bits. +- Dense projections: up to 2 rows run a scalar kernel (`rowchain_swiz.metal`), more run the 8x8 matrix units (`rowmma_swiz.metal`). On this GPU `simdgroup_multiply_accumulate` on 8x8 float matrices equals a sequential `fma` chain over k = 0..7 bit for bit (2.4 million elements, 0 differences), so the two kernels write the same bits for the same split of K. This is measured on one chip, not guaranteed by Metal: the self-check at load is the gate. +- Weight layout: at load the projection and expert weights are repacked into the tile order the kernels read (`swizzle_dense`, `swizzle_moe_w13`, `swizzle_moe_w2`; the same values in another order). A shape the layout cannot take (a width that is not a multiple of 64) runs on the plain-layout kernels with the same row contract. +- Self-check at load: 101 verify rows compared with the decode step byte for byte: a 24-row greedy chain, then chains of 2, 3, 4, 5, 9, 16 and 32 rows and a 6-row tree after a 300-token prompt (each size is a kernel variant of its own; the long prompt takes the attention's chunk-then-reduce path). One differing byte turns speculation off. +- Off: the prefix, session and disk caches, the KV pool, side slots and joint passes. + +Start: `python server/app.py --model --drafter mtp` (`--drafter none` for plain decode). The price file is found by the chip's name. + +One greedy request a cell through the server, 512 tokens, thinking off, plain / lookup, tok/s (`tools/fn_lookup_ab.py`, the server's own `timings`): the median of 3 runs, plain and lookup servers started in turn (plain, lookup, plain, lookup, ...), with the range of the runs. Every lookup text equals every plain text in all runs. + +| `lfm25-bf16`, M5 Max | prose | chat | code | edit | copy | +|-|-|-|-|-|-| +| plain | 94.4 (92.5 to 95.0) | 94.7 (91.7 to 94.8) | 94.6 (93.1 to 94.9) | 94.1 (90.4 to 94.7) | 94.5 (92.0 to 94.6) | +| lookup | 93.2 (91.6 to 93.5) | 93.1 (90.6 to 93.2) | 96.3 (96.0 to 98.3) | 315.2 (305.1 to 316.8) | 320.1 (319.9 to 321.0) | + +The same servers through `python -m tools.measure run --rows decode.c1.short,decode.c1.1k` (256 tokens out, the client's clock: `(completion_tokens - 1) / (end to end - time to first token)`): 85.5 tok/s plain (83.3 to 86.6 over 30 rounds), 85.0 with the lookup (83.4 to 85.8). The tool marks these rows INVALID: it asks `/health` for the slots decoding at once, which the server reports from its slot pool, and this serving has one slot and no pool. The gate's measurement suites therefore do not run against the Mac yet. + +The decode loop alone, without the server: 99.1 tok/s; a 512-token prompt prefills at 3,444 tok/s (`tools/mlx_lfm_bench.py`). + +Verify staircase, chain blocks, median of 7, ms (`tools/mlx_lfm_prices.py`, the price file `ops/prices/lfm2.5-24b-a2b/lfm25-bf16.apple-m5-max.json`): + +| rows | plain step | 1 | 2 | 4 | 8 | 12 | 16 | +|-|-|-|-|-|-|-|-| +| 512 tokens of context | 10.26 | 10.20 | 13.81 | 17.47 | 25.12 | 31.10 | 34.63 | +| 16,384 tokens of context | 10.97 | 10.94 | 14.59 | 18.17 | 26.62 | 33.54 | 36.95 | + +| check | where | result | +|-|-|-| +| verify rows against sequential decode, real checkpoint: a 12-row tree, chains of 16, 5 and 3 rows | `tools/mlx_lfm_exact.py` | 36 rows bit for bit | +| verify rows against decode steps | load-time self-check | 101 rows byte for byte | +| kernels against fp32 references; every row kernel's block against its rows alone at every size from 1 to 33; the served attention shape through the board up to 64 rows; the self-check refusing one unit in one row; the serving's state after an in-place ask; the dispatch by the adapter's `backend()` | `tests/test_lfm2_moe_mlx.py` | 26 pass | +| lookup against plain through the server, 5 asks x 512 tokens, 3 runs each | `tools/fn_lookup_ab.py --compare` | every text equal | +| last-row logits against mlx-lm's `lfm2_moe` in BF16, the bench's chat prompt | `tools/mlx_lfm_bench.py --check` | top token equal, top 5 equal, largest difference 0.94 on logits up to 24.8 | +| logits against mlx-lm over 85 positions of 3 prompts (21, 600 and 1,500 tokens), token by token | one-off script, not in the tree | top token equal at 74 of 85; mean difference 0.20 to 0.22 | + +mlx-lm in BF16 rounds in its own order, so it is a noisy reference. On an earlier build three attention kernels (the softmax weights in BF16, in fp32, and an all-fp32 kernel) sat at the same distance from it (mean 0.15 to 0.25) and from each other (0.16 to 0.19): that distance is the BF16 noise floor, not an error of one kernel. A comparison against an fp32 copy of the model is not done. + +Greedy text from this build can differ from an earlier build's at a near tie: a kernel that sums in another order moves the logits by that noise floor. Within one build the lookup's text is the plain text. + ## Not supported yet - A draft head (none published for this model). diff --git a/docs/reference/variables.md b/docs/reference/variables.md index 179c065d0..5e69c8566 100644 --- a/docs/reference/variables.md +++ b/docs/reference/variables.md @@ -695,7 +695,7 @@ TandemEngine reads four families of settings. Engine switches are `QWEN38_*` var | `QSE_USAGE_DEFAULT` | `server/app.py` | | `QSE_USAGE_LEDGER` | `install.sh, ops/engines.sh, ops/serve.env` and 4 more | | `QSE_VISION_ASKED` | `ops/serve.env, ops/start.sh, server/remote/overlay.py` | -| `QSE_WEIGHTS` | `engine/models/flashnext/corrector.py, engine/models/flashnext/coupled.py, engine/models/flashnext/serving.py` and 20 more | +| `QSE_WEIGHTS` | `engine/models/flashnext/corrector.py, engine/models/flashnext/coupled.py, engine/models/flashnext/serving.py` and 21 more | | `QSE_WEIGHTS_ALSO` | `ops/profiles/_flashnext.env, ops/use-profile.sh` | | `QSE_WEIGHTS_DIR` | `engine/models/nemotron_h/community.py, engine/models/qwen3_5/community.py, ops/profiles/_exl3.env` and 12 more | | `QSE_WEIGHTS_FILES` | `engine/models/nemotron_h/community.py, engine/models/qwen3_5/community.py, ops/profiles/_exl3.env` and 9 more | diff --git a/engine/methods/hostcopy.py b/engine/methods/hostcopy.py new file mode 100644 index 000000000..c0fe9936c --- /dev/null +++ b/engine/methods/hostcopy.py @@ -0,0 +1,15 @@ +"""`h2d` for the server's generation loop on a machine without Triton (Apple silicon, +engine/models/lfm2_moe/mlx_serving.py): engine/model.py owns `h2d` and `HOST_ASYNC` and cannot be imported +there. Off CUDA the copy is the plain one engine/model.py's `h2d` makes; on CUDA it is engine/model.py's.""" + +from __future__ import annotations + +import torch + + +def h2d(values, dtype: torch.dtype, device) -> torch.Tensor: + """A Python list as a device tensor (engine/model.py `h2d`; its pinned path is CUDA's alone).""" + if torch.device(device).type != "cuda": + return torch.tensor(values, dtype=dtype).to(device) + from engine.model import h2d as on_cuda + return on_cuda(values, dtype, device) diff --git a/engine/models/lfm2_moe/arch.py b/engine/models/lfm2_moe/arch.py index 49a8d4055..1c5c5b544 100644 --- a/engine/models/lfm2_moe/arch.py +++ b/engine/models/lfm2_moe/arch.py @@ -10,7 +10,7 @@ config="engine.models.lfm2_moe.config:load_lfm2_moe_config", engine="engine.models.lfm2_moe.engine:Lfm2MoeEngine", package="models/lfm2_moe", - serve="engine.models.lfm2_moe.serving:serve", + serve="engine.models.lfm2_moe.dispatch:serve", manifest="engine.models.lfm2_moe.serving:manifest", rank=3, spec=ServeSpec(tool_format="pythonic"), # LFM2's Pythonic call lists diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/convgate.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/convgate.metal new file mode 100644 index 000000000..2c65a996b --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/convgate.metal @@ -0,0 +1,46 @@ +// Fused row-invariant double-gated short convolution (no mx.concatenate copy!). +// Computes bx[m, h] = B[m, h] * x[m, h] and cy[m, h] = C[m, h] * sum_{t=0..KT-1} win[m, t, h] * cw[h, t] +// in exact ascending tap order 0..KT-1 (identical for M=1 decode, chain blocks, and arbitrary trees). +// When NEXT_STATE == 1 (M == 1 decode step), writes next_state [S, H] directly, eliminating 30 mx.concatenate calls! +// Grid: (H, M, 1), Threadgroup: (min(256, H), 1, 1). +const int h = (int)thread_position_in_grid.x; +const int m = (int)threadgroup_position_in_grid.y; +if (h >= H) return; +const int S = KT - 1; +const device T* row_m = bcx + (size_t)m * (3 * H); +const float Bm = float(row_m[h]); +const float Cm = float(row_m[H + h]); +const float xm = float(row_m[2 * H + h]); +const T bxm = static_cast(Bm * xm); +#if NEXT_STATE +for (int t = 0; t < S - 1; t++) { + next_state[(size_t)t * H + h] = state[(size_t)(t + 1) * H + h]; +} +next_state[(size_t)(S - 1) * H + h] = bxm; +#else +bx[(size_t)m * H + h] = bxm; +#endif + +float acc = 0.0f; +for (int t = 0; t < KT; t++) { +#if HAS_TAPS + const int pos = taps[(size_t)m * KT + t]; +#else + const int pos = m + t; +#endif + T val; + if (pos < S) { + val = state[(size_t)pos * H + h]; + } else { + const int rr = pos - S; + if (rr == m) { + val = bxm; + } else { + const device T* row_r = bcx + (size_t)rr * (3 * H); + val = static_cast(float(row_r[h]) * float(row_r[2 * H + h])); + } + } + const T prod = static_cast(float(val) * float(cw[(size_t)h * KT + t])); + acc = (t == 0) ? float(prod) : float(static_cast(acc + float(prod))); +} +cy[(size_t)m * H + h] = static_cast(Cm * acc); diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/dense_prefill_swiz.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/dense_prefill_swiz.metal new file mode 100644 index 000000000..2ae66a177 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/dense_prefill_swiz.metal @@ -0,0 +1,141 @@ +// High-throughput batched prefill GEMM directly on 512B-coalesced w_swiz (zero unswizzle copy!). +// Layout w_swiz: [N // 16, K // 64, B8=2, TN=2, cg_sg=8, KS=4, 8]. +// Uses Metal 4 MPP matmul2d (M5 Neural Accelerators) when __METAL_VERSION__ >= 400, else simdgroup_matrix. +// Tile: BM=64, BN=64, BK=64, TG=128 (4 simdgroups: 2 M-tiles of 32 x 2 N-tiles of 32). +const uint tid = thread_position_in_threadgroup.x; +const uint sg = simdgroup_index_in_threadgroup; +const int M = x_shape[0]; +// Threadgroups go along M first so concurrent TGs share w_swiz in L2 +const int m0 = (int)threadgroup_position_in_grid.x * 64; +const int tile_n0 = (int)threadgroup_position_in_grid.y * 4; +const int n0 = tile_n0 * 16; + +constexpr int KSTEPS = K / 64; +constexpr int NTILES_TOTAL = N / 16; + +const device ulong2* wbase = (const device ulong2*)w_swiz; +const int b_i = (int)(tid >> 6); +const int c_i = (int)((tid >> 5) & 1); +const int cg_sg = (int)((tid >> 2) & 7); +const int s_i = (int)(tid & 3); +const int w_row_base = cg_sg * 2 + c_i; +const int w_kk = s_i * 16 + b_i * 8; + +#if defined(__METAL_VERSION__) && __METAL_VERSION__ >= 400 +using extents_t = metal::dextents; +using strides_t = metal::array; +using tg_t = metal::tensor; + +constexpr int STRIDE = 64; +threadgroup T xs[64][STRIDE]; +threadgroup T ws[64][STRIDE]; + +const int sg_m = (int)(sg >> 1); // 0..1 (32 rows each) +const int sg_n = (int)(sg & 1); // 0..1 (32 cols each) + +constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + 32, 32, 64, false, true, true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); +mpp::tensor_ops::matmul2d op; + +tg_t tA(&xs[sg_m * 32][0], extents_t(64, 32), strides_t{1, STRIDE}); +tg_t tB(&ws[sg_n * 32][0], extents_t(64, 32), strides_t{1, STRIDE}); +auto Dacc = op.template get_destination_cooperative_tensor(); +for (uint16_t i = 0; i < Dacc.get_capacity(); i++) Dacc[i] = 0.0f; + +for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * 64; + for (int p = 0; p < 4; p++) { + const int v = p * 128 + (int)tid; + const int r = v >> 3; + const int kk = (v & 7) << 3; + if (m0 + r < M) { + *((threadgroup ulong2*)&xs[r][kk]) = *((const device ulong2*)(x + (size_t)(m0 + r) * K + k0 + kk)); + } else { + *((threadgroup ulong2*)&xs[r][kk]) = ulong2(0); + } + } + for (int st = 0; st < 4; st++) { + const int tn = tile_n0 + st; + const int w_row = st * 16 + w_row_base; + if (tn < NTILES_TOTAL) { + *((threadgroup ulong2*)&ws[w_row][w_kk]) = wbase[((size_t)tn * KSTEPS + ks_i) * 128 + tid]; + } else { + *((threadgroup ulong2*)&ws[w_row][w_kk]) = ulong2(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + op.run(tA, tB, Dacc); + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +for (uint16_t i = 0; i < Dacc.get_capacity(); i++) { + auto idx = Dacc.get_multidimensional_index(i); + const int r = m0 + sg_m * 32 + idx[1]; + const int c = n0 + sg_n * 32 + idx[0]; + if (r < M && c < N) { + y[(size_t)r * N + c] = static_cast(static_cast(Dacc[i])); + } +} +#else +const uint lane = thread_index_in_simdgroup; +constexpr int STRIDE = 72; +threadgroup T xs[64][STRIDE]; +threadgroup T ws[64][STRIDE]; + +const uint sg_m = sg >> 1; +const uint sg_n = sg & 1; + +simdgroup_matrix acc[4][4]; +for (int fm = 0; fm < 4; fm++) + for (int fn = 0; fn < 4; fn++) + acc[fm][fn] = simdgroup_matrix(0.0f); + +for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * 64; + for (int p = 0; p < 4; p++) { + const int v = p * 128 + (int)tid; + const int r = v >> 3; + const int kk = (v & 7) << 3; + if (m0 + r < M) { + *((threadgroup ulong2*)&xs[r][kk]) = *((const device ulong2*)(x + (size_t)(m0 + r) * K + k0 + kk)); + } else { + *((threadgroup ulong2*)&xs[r][kk]) = ulong2(0); + } + } + for (int st = 0; st < 4; st++) { + const int tn = tile_n0 + st; + const int w_row = st * 16 + w_row_base; + if (tn < NTILES_TOTAL) { + *((threadgroup ulong2*)&ws[w_row][w_kk]) = wbase[((size_t)tn * KSTEPS + ks_i) * 128 + tid]; + } else { + *((threadgroup ulong2*)&ws[w_row][w_kk]) = ulong2(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int kk = 0; kk < 64; kk += 8) { + simdgroup_matrix a[4], b[4]; + for (int fm = 0; fm < 4; fm++) simdgroup_load(a[fm], &xs[sg_m * 32 + fm * 8][kk], STRIDE); + for (int fn = 0; fn < 4; fn++) simdgroup_load(b[fn], &ws[sg_n * 32 + fn * 8][kk], STRIDE, ulong2(0, 0), true); + for (int fm = 0; fm < 4; fm++) + for (int fn = 0; fn < 4; fn++) + simdgroup_multiply_accumulate(acc[fm][fn], a[fm], b[fn], acc[fm][fn]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +const int my_r = (int)(((lane & 16) >> 2) | ((lane & 6) >> 1)); +const int my_c0 = (int)(((lane & 8) >> 1) | ((lane & 1) << 1)); +for (int fm = 0; fm < 4; fm++) { + const int row = m0 + (int)sg_m * 32 + fm * 8 + my_r; + if (row < M) { + for (int fn = 0; fn < 4; fn++) { + const int col = n0 + (int)sg_n * 32 + fn * 8 + my_c0; + if (col + 1 < N) { + y[(size_t)row * N + col] = static_cast(static_cast(acc[fm][fn].thread_elements()[0])); + y[(size_t)row * N + col + 1] = static_cast(static_cast(acc[fm][fn].thread_elements()[1])); + } + } + } +} +#endif diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/embed_swiz.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/embed_swiz.metal new file mode 100644 index 000000000..349aaacf8 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/embed_swiz.metal @@ -0,0 +1,15 @@ +// Gather rows from 512B-coalesced swizzled [V, K] embedding table (zero extra bytes when lm_head is tied). +// Layout w_swiz: [V // 16, K // 64, B8=2, TN=2, cg_sg=8, KS=4, 8]. +// Grid: (K / 8, M, 1), Threadgroup: (min(256, K / 8), 1, 1). +const uint k8 = thread_position_in_grid.x; +const uint m = threadgroup_position_in_grid.y; +if (k8 >= (uint)(K / 8)) return; +const int n = tokens[m]; +const int tile_n = n >> 4; +const int cg_sg = (n >> 1) & 7; +const int c_i = n & 1; +const int ks_i = (int)(k8 >> 3); +const int s_i = (int)((k8 >> 1) & 3); +const int b_i = (int)(k8 & 1); +const size_t src = ((size_t)tile_n * (K / 64) + ks_i) * 128 + b_i * 64 + c_i * 32 + cg_sg * 4 + s_i; +((device ulong2*)out)[(size_t)m * (K / 8) + k8] = ((const device ulong2*)w_swiz)[src]; diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moegate.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moegate.metal new file mode 100644 index 000000000..155a66165 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moegate.metal @@ -0,0 +1,161 @@ +// Row-invariant 2-simdgroup MoE router gate projection with optional fused RMSNorm (FUSE_RMS) +// and optional normalized hidden state output (WRITE_NORM: threadgroup e==0 writes n_out [M, K]). +// Grid: (E * 64, 1, 1), Threadgroup: (64, 1, 1): 2 simdgroups collaborate on each expert row (4 iters for K=2048). +// For R == 1 (M == 1), loads x, w, nw in a single overlapped pass into registers (zero second x load!). +// For R > 1, uses the exact same (sg, p, lane) summation order so M=1 and M=2..64 match bit for bit. +const uint e = threadgroup_position_in_grid.x; +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; +const int M = x_shape[0]; +const device T* wr = w + (size_t)e * K; +constexpr int NP = (K + 511) / 512; + +threadgroup float sh_acc[2][R]; +#if FUSE_RMS +threadgroup float sh_ss[2][R]; +#endif + +for (int m0 = 0; m0 < M; m0 += R) { + const int nr = min(R, M - m0); +#if FUSE_RMS + if (R == 1) { + ulong2 xr_reg[NP], wr_reg[NP], nr_reg[NP]; + float ss_loc = 0.0f; + const device T* xr = x + (size_t)m0 * K; + for (int p = 0; p < NP; p++) { + const int k = (p * 2 + (int)sg) * 256 + (int)lane * 8; + if (k < K) { + const ulong2 xraw = *((const device ulong2*)(xr + k)); + wr_reg[p] = *((const device ulong2*)(wr + k)); + nr_reg[p] = *((const device ulong2*)(nw + k)); + xr_reg[p] = xraw; + const vec xa = as_type>(xraw.x), xb = as_type>(xraw.y); + ss_loc = fma(float(xa[0]), float(xa[0]), ss_loc); ss_loc = fma(float(xa[1]), float(xa[1]), ss_loc); + ss_loc = fma(float(xa[2]), float(xa[2]), ss_loc); ss_loc = fma(float(xa[3]), float(xa[3]), ss_loc); + ss_loc = fma(float(xb[0]), float(xb[0]), ss_loc); ss_loc = fma(float(xb[1]), float(xb[1]), ss_loc); + ss_loc = fma(float(xb[2]), float(xb[2]), ss_loc); ss_loc = fma(float(xb[3]), float(xb[3]), ss_loc); + } + } + const float ss_sg = simd_sum(ss_loc); + if (lane == 0) sh_ss[sg][0] = ss_sg; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float inv = rsqrt((sh_ss[0][0] + sh_ss[1][0]) / (float)K + eps[0]); + float acc = 0.0f; + for (int p = 0; p < NP; p++) { + const int k = (p * 2 + (int)sg) * 256 + (int)lane * 8; + if (k < K) { + const vec wa = as_type>(wr_reg[p].x), wb = as_type>(wr_reg[p].y); + const vec na = as_type>(nr_reg[p].x), nb4 = as_type>(nr_reg[p].y); + const vec xa = as_type>(xr_reg[p].x), xb = as_type>(xr_reg[p].y); + vec oa, ob; + oa[0] = static_cast(float(xa[0]) * inv * float(na[0])); + oa[1] = static_cast(float(xa[1]) * inv * float(na[1])); + oa[2] = static_cast(float(xa[2]) * inv * float(na[2])); + oa[3] = static_cast(float(xa[3]) * inv * float(na[3])); + ob[0] = static_cast(float(xb[0]) * inv * float(nb4[0])); + ob[1] = static_cast(float(xb[1]) * inv * float(nb4[1])); + ob[2] = static_cast(float(xb[2]) * inv * float(nb4[2])); + ob[3] = static_cast(float(xb[3]) * inv * float(nb4[3])); +#if WRITE_NORM + if (e == 0) { + *((device ulong2*)(n_out + (size_t)m0 * K + k)) = ulong2(as_type(oa), as_type(ob)); + } +#endif + acc = fma(float(oa[0]), float(wa[0]), acc); acc = fma(float(oa[1]), float(wa[1]), acc); + acc = fma(float(oa[2]), float(wa[2]), acc); acc = fma(float(oa[3]), float(wa[3]), acc); + acc = fma(float(ob[0]), float(wb[0]), acc); acc = fma(float(ob[1]), float(wb[1]), acc); + acc = fma(float(ob[2]), float(wb[2]), acc); acc = fma(float(ob[3]), float(wb[3]), acc); + } + } + const float a_sg = simd_sum(acc); + if (lane == 0) sh_acc[sg][0] = a_sg; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0 && lane == 0) out[(size_t)m0 * E + e] = static_cast(sh_acc[0][0] + sh_acc[1][0]); + continue; + } + for (int r = 0; r < R; r++) { + float ss_loc = 0.0f; + if (r < nr) { + const device T* xr = x + (size_t)(m0 + r) * K; + for (int p = 0; p < NP; p++) { + const int k = (p * 2 + (int)sg) * 256 + (int)lane * 8; + if (k < K) { + const ulong2 xraw = *((const device ulong2*)(xr + k)); + const vec xa = as_type>(xraw.x), xb = as_type>(xraw.y); + ss_loc = fma(float(xa[0]), float(xa[0]), ss_loc); ss_loc = fma(float(xa[1]), float(xa[1]), ss_loc); + ss_loc = fma(float(xa[2]), float(xa[2]), ss_loc); ss_loc = fma(float(xa[3]), float(xa[3]), ss_loc); + ss_loc = fma(float(xb[0]), float(xb[0]), ss_loc); ss_loc = fma(float(xb[1]), float(xb[1]), ss_loc); + ss_loc = fma(float(xb[2]), float(xb[2]), ss_loc); ss_loc = fma(float(xb[3]), float(xb[3]), ss_loc); + } + } + } + const float ss_sg = simd_sum(ss_loc); + if (lane == 0) sh_ss[sg][r] = ss_sg; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float inv_r[R]; + for (int r = 0; r < R; r++) inv_r[r] = rsqrt((sh_ss[0][r] + sh_ss[1][r]) / (float)K + eps[0]); +#endif + float acc[R]; + for (int r = 0; r < R; r++) acc[r] = 0.0f; + for (int p = 0; p < NP; p++) { + const int k = (p * 2 + (int)sg) * 256 + (int)lane * 8; + if (k < K) { + const ulong2 wraw = *((const device ulong2*)(wr + k)); + const vec wa = as_type>(wraw.x), wb = as_type>(wraw.y); + const float w0 = float(wa[0]), w1 = float(wa[1]), w2 = float(wa[2]), w3 = float(wa[3]); + const float w4 = float(wb[0]), w5 = float(wb[1]), w6 = float(wb[2]), w7 = float(wb[3]); +#if FUSE_RMS + const ulong2 nwraw = *((const device ulong2*)(nw + k)); + const vec na = as_type>(nwraw.x), nb4 = as_type>(nwraw.y); + const float n0f = float(na[0]), n1f = float(na[1]), n2f = float(na[2]), n3f = float(na[3]); + const float n4f = float(nb4[0]), n5f = float(nb4[1]), n6f = float(nb4[2]), n7f = float(nb4[3]); +#endif + for (int r = 0; r < R; r++) { + if (r < nr) { + const ulong2 xraw = *((const device ulong2*)(x + (size_t)(m0 + r) * K + k)); + const vec xa = as_type>(xraw.x), xb = as_type>(xraw.y); + float t = acc[r]; +#if FUSE_RMS + const float inv = inv_r[r]; + vec oa, ob; + oa[0] = static_cast(float(xa[0]) * inv * n0f); + oa[1] = static_cast(float(xa[1]) * inv * n1f); + oa[2] = static_cast(float(xa[2]) * inv * n2f); + oa[3] = static_cast(float(xa[3]) * inv * n3f); + ob[0] = static_cast(float(xb[0]) * inv * n4f); + ob[1] = static_cast(float(xb[1]) * inv * n5f); + ob[2] = static_cast(float(xb[2]) * inv * n6f); + ob[3] = static_cast(float(xb[3]) * inv * n7f); +#if WRITE_NORM + if (e == 0) { + *((device ulong2*)(n_out + (size_t)(m0 + r) * K + k)) = ulong2(as_type(oa), as_type(ob)); + } +#endif + t = fma(float(oa[0]), w0, t); t = fma(float(oa[1]), w1, t); + t = fma(float(oa[2]), w2, t); t = fma(float(oa[3]), w3, t); + t = fma(float(ob[0]), w4, t); t = fma(float(ob[1]), w5, t); + t = fma(float(ob[2]), w6, t); t = fma(float(ob[3]), w7, t); +#else + t = fma(float(xa[0]), w0, t); t = fma(float(xa[1]), w1, t); + t = fma(float(xa[2]), w2, t); t = fma(float(xa[3]), w3, t); + t = fma(float(xb[0]), w4, t); t = fma(float(xb[1]), w5, t); + t = fma(float(xb[2]), w6, t); t = fma(float(xb[3]), w7, t); +#endif + acc[r] = t; + } + } + } + } + for (int r = 0; r < R; r++) { + const float a_sg = simd_sum(acc[r]); + if (lane == 0) sh_acc[sg][r] = a_sg; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0 && lane == 0) { + for (int r = 0; r < R; r++) { + if (r < nr) out[(size_t)(m0 + r) * E + e] = static_cast(sh_acc[0][r] + sh_acc[1][r]); + } + } + if (m0 + R < M) threadgroup_barrier(mem_flags::mem_threadgroup); +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_hyb.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_hyb.metal new file mode 100644 index 000000000..9e8d07140 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_hyb.metal @@ -0,0 +1,269 @@ +// Row-invariant M>1 hybrid MoE projection (scalar chain for ns<=2, 8x8 bfloat simdgroup_matrix MMA for ns>=3). +// Reads LPT-ordered pre-grouped (elist, eoff, ecnt, sel) from moeroute.metal (O(1) startup, zero pair scan). +// Uses union-aliased threadgroup memory and FM_MAX template (1 for M<=8, 2 for M>8 -> half the registers and +// half the xs shared memory for M=3..8, while M=9..16 still reads every expert's weights once for up to 16 rows). +// Exact bit-for-bit twin of moemm_r1.metal (same (BK, KS) FMA chain). Optional fused SwiGLU for w13. +const int u = (int)threadgroup_position_in_grid.y; +const int e = elist[u]; +if (e < 0) return; + +const int ns = ecnt[u]; +const int start = eoff[u]; +const uint tid = thread_position_in_threadgroup.x; +const uint sg = simdgroup_index_in_threadgroup; +constexpr int CG = 4 / KS; +constexpr int N_TILE = CG * FN * 8; +const int nb = (int)threadgroup_position_in_grid.x * N_TILE; +if (nb >= NOUT) return; + +const device T* we = w + (size_t)e * (SWIGLU ? (2 * NOUT) : NOUT) * K; + +if (ns <= 2) { + const int s = (int)tid % KS; + const int col = (int)tid / KS; + if (col >= N_TILE) return; + const int n = nb + col; + const int p0 = sel[start]; + const int p1 = (ns == 2) ? sel[start + 1] : p0; + const int xr0 = PROW_IDENTITY ? p0 : (p0 / TOPK); + const int xr1 = PROW_IDENTITY ? p1 : (p1 / TOPK); + const device T* xp0 = x + (size_t)xr0 * K; + const device T* xp1 = x + (size_t)xr1 * K; + const device T* wp1 = we + (size_t)min(n, NOUT - 1) * K; + const device T* wp3 = SWIGLU ? (we + (size_t)(NOUT + min(n, NOUT - 1)) * K) : wp1; + + float a0 = 0.0f, a1 = 0.0f, b0 = 0.0f, b1 = 0.0f; + if (n < NOUT) { + if (ns == 1) { + for (int k0 = s * BK; k0 < K; k0 += KS * BK) { + for (int kk = 0; kk < BK; kk += 8) { + const int k = k0 + kk; + const device vec* xv = (const device vec*)(xp0 + k); + const vec xa = xv[0], xb = xv[1]; + const float x0 = float(xa[0]), x1 = float(xa[1]), x2 = float(xa[2]), x3 = float(xa[3]); + const float x4 = float(xb[0]), x5 = float(xb[1]), x6 = float(xb[2]), x7 = float(xb[3]); + { + const device vec* wv = (const device vec*)(wp1 + k); + const vec wa = wv[0], wb = wv[1]; + a0 = fma(x0, float(wa[0]), a0); a0 = fma(x1, float(wa[1]), a0); + a0 = fma(x2, float(wa[2]), a0); a0 = fma(x3, float(wa[3]), a0); + a0 = fma(x4, float(wb[0]), a0); a0 = fma(x5, float(wb[1]), a0); + a0 = fma(x6, float(wb[2]), a0); a0 = fma(x7, float(wb[3]), a0); + } + if (SWIGLU) { + const device vec* wv = (const device vec*)(wp3 + k); + const vec wa = wv[0], wb = wv[1]; + b0 = fma(x0, float(wa[0]), b0); b0 = fma(x1, float(wa[1]), b0); + b0 = fma(x2, float(wa[2]), b0); b0 = fma(x3, float(wa[3]), b0); + b0 = fma(x4, float(wb[0]), b0); b0 = fma(x5, float(wb[1]), b0); + b0 = fma(x6, float(wb[2]), b0); b0 = fma(x7, float(wb[3]), b0); + } + } + } + } else { + for (int k0 = s * BK; k0 < K; k0 += KS * BK) { + for (int kk = 0; kk < BK; kk += 8) { + const int k = k0 + kk; + const device vec* xv0 = (const device vec*)(xp0 + k); + const device vec* xv1 = (const device vec*)(xp1 + k); + const vec x0a = xv0[0], x0b = xv0[1]; + const vec x1a = xv1[0], x1b = xv1[1]; + { + const device vec* wv = (const device vec*)(wp1 + k); + const vec wa = wv[0], wb = wv[1]; + const float w0 = float(wa[0]), w1 = float(wa[1]), w2 = float(wa[2]), w3 = float(wa[3]); + const float w4 = float(wb[0]), w5 = float(wb[1]), w6 = float(wb[2]), w7 = float(wb[3]); + a0 = fma(float(x0a[0]), w0, a0); a0 = fma(float(x0a[1]), w1, a0); + a0 = fma(float(x0a[2]), w2, a0); a0 = fma(float(x0a[3]), w3, a0); + a0 = fma(float(x0b[0]), w4, a0); a0 = fma(float(x0b[1]), w5, a0); + a0 = fma(float(x0b[2]), w6, a0); a0 = fma(float(x0b[3]), w7, a0); + a1 = fma(float(x1a[0]), w0, a1); a1 = fma(float(x1a[1]), w1, a1); + a1 = fma(float(x1a[2]), w2, a1); a1 = fma(float(x1a[3]), w3, a1); + a1 = fma(float(x1b[0]), w4, a1); a1 = fma(float(x1b[1]), w5, a1); + a1 = fma(float(x1b[2]), w6, a1); a1 = fma(float(x1b[3]), w7, a1); + } + if (SWIGLU) { + const device vec* wv = (const device vec*)(wp3 + k); + const vec wa = wv[0], wb = wv[1]; + const float w0 = float(wa[0]), w1 = float(wa[1]), w2 = float(wa[2]), w3 = float(wa[3]); + const float w4 = float(wb[0]), w5 = float(wb[1]), w6 = float(wb[2]), w7 = float(wb[3]); + b0 = fma(float(x0a[0]), w0, b0); b0 = fma(float(x0a[1]), w1, b0); + b0 = fma(float(x0a[2]), w2, b0); b0 = fma(float(x0a[3]), w3, b0); + b0 = fma(float(x0b[0]), w4, b0); b0 = fma(float(x0b[1]), w5, b0); + b0 = fma(float(x0b[2]), w6, b0); b0 = fma(float(x0b[3]), w7, b0); + b1 = fma(float(x1a[0]), w0, b1); b1 = fma(float(x1a[1]), w1, b1); + b1 = fma(float(x1a[2]), w2, b1); b1 = fma(float(x1a[3]), w3, b1); + b1 = fma(float(x1b[0]), w4, b1); b1 = fma(float(x1b[1]), w5, b1); + b1 = fma(float(x1b[2]), w6, b1); b1 = fma(float(x1b[3]), w7, b1); + } + } + } + } + } + if (KS == 2) { + a0 = a0 + simd_shuffle_down(a0, 1); + if (ns == 2) a1 = a1 + simd_shuffle_down(a1, 1); + if (SWIGLU) { + b0 = b0 + simd_shuffle_down(b0, 1); + if (ns == 2) b1 = b1 + simd_shuffle_down(b1, 1); + } + } else if (KS == 4) { + a0 = ((a0 + simd_shuffle_down(a0, 1)) + simd_shuffle_down(a0, 2)) + simd_shuffle_down(a0, 3); + if (ns == 2) a1 = ((a1 + simd_shuffle_down(a1, 1)) + simd_shuffle_down(a1, 2)) + simd_shuffle_down(a1, 3); + if (SWIGLU) { + b0 = ((b0 + simd_shuffle_down(b0, 1)) + simd_shuffle_down(b0, 2)) + simd_shuffle_down(b0, 3); + if (ns == 2) b1 = ((b1 + simd_shuffle_down(b1, 1)) + simd_shuffle_down(b1, 2)) + simd_shuffle_down(b1, 3); + } + } + if (s == 0 && n < NOUT) { + if (SWIGLU) { + const float ga0 = float(static_cast(a0)), ub0 = float(static_cast(b0)); + y[(size_t)p0 * NOUT + n] = static_cast((1.0f / (1.0f + exp(-ga0))) * ga0 * ub0); + if (ns == 2) { + const float ga1 = float(static_cast(a1)), ub1 = float(static_cast(b1)); + y[(size_t)p1 * NOUT + n] = static_cast((1.0f / (1.0f + exp(-ga1))) * ga1 * ub1); + } + } else { + y[(size_t)p0 * NOUT + n] = static_cast(a0); + if (ns == 2) y[(size_t)p1 * NOUT + n] = static_cast(a1); + } + } + return; +} + +constexpr int KSTEP = KS * BK; +constexpr int KVECS = KSTEP / 8; +constexpr int STRIDE = KSTEP + 8; +constexpr int RPASS = FM_MAX * 8; +struct StageMem { + T xs[RPASS][STRIDE]; + T ws[N_TILE][STRIDE]; +}; +struct EpiMem { + float os1[KS][8][N_TILE]; + float os3[SWIGLU ? KS : 1][SWIGLU ? 8 : 1][SWIGLU ? N_TILE : 1]; +}; +union ShMem { + StageMem st; + EpiMem ep; +}; +threadgroup ShMem sm; + +const int split = (int)sg % KS; +const int cg = (int)sg / KS; + +for (int c0 = 0; c0 < ns; c0 += RPASS) { + const int nr = min(RPASS, ns - c0); + const int fm_max = (FM_MAX == 2 && nr > 8) ? 2 : 1; + const int mr = fm_max * 8; + + simdgroup_matrix acc1[FM_MAX][FN]; + simdgroup_matrix acc3[SWIGLU ? FM_MAX : 1][SWIGLU ? FN : 1]; + for (int fm = 0; fm < FM_MAX; fm++) { + for (int f = 0; f < FN; f++) { + acc1[fm][f] = simdgroup_matrix(0.0f); + if (SWIGLU) acc3[fm][f] = simdgroup_matrix(0.0f); + } + } + + for (int k0 = 0; k0 < K; k0 += KSTEP) { + for (int v = (int)tid; v < mr * KVECS; v += 128) { + const int r = v / KVECS; + const int kk = (v % KVECS) * 8; + if (r < nr) { + const int p = sel[start + c0 + r]; + const int xr = PROW_IDENTITY ? p : (p / TOPK); + const device vec* xp = (const device vec*)(x + (size_t)xr * K + k0 + kk); + *((threadgroup vec*)&sm.st.xs[r][kk]) = xp[0]; + *((threadgroup vec*)&sm.st.xs[r][kk + 4]) = xp[1]; + } else { + *((threadgroup vec*)&sm.st.xs[r][kk]) = vec(0); + *((threadgroup vec*)&sm.st.xs[r][kk + 4]) = vec(0); + } + } + for (int v = (int)tid; v < N_TILE * KVECS; v += 128) { + const int c = v / KVECS; + const int kk = (v % KVECS) * 8; + const int n = nb + c; + if (n < NOUT) { + const device vec* wp = (const device vec*)(we + (size_t)n * K + k0 + kk); + *((threadgroup vec*)&sm.st.ws[c][kk]) = wp[0]; + *((threadgroup vec*)&sm.st.ws[c][kk + 4]) = wp[1]; + } else { + *((threadgroup vec*)&sm.st.ws[c][kk]) = vec(0); + *((threadgroup vec*)&sm.st.ws[c][kk + 4]) = vec(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int kk = split * BK; kk < (split + 1) * BK; kk += 8) { + simdgroup_matrix a[FM_MAX]; + simdgroup_load(a[0], &sm.st.xs[0][kk], STRIDE); + if (FM_MAX == 2 && fm_max == 2) simdgroup_load(a[1], &sm.st.xs[8][kk], STRIDE); + for (int f = 0; f < FN; f++) { + simdgroup_matrix b; + simdgroup_load(b, &sm.st.ws[(cg * FN + f) * 8][kk], STRIDE, ulong2(0, 0), true); + simdgroup_multiply_accumulate(acc1[0][f], a[0], b, acc1[0][f]); + if (FM_MAX == 2 && fm_max == 2) simdgroup_multiply_accumulate(acc1[1][f], a[1], b, acc1[1][f]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (SWIGLU) { + for (int v = (int)tid; v < N_TILE * KVECS; v += 128) { + const int c = v / KVECS; + const int kk = (v % KVECS) * 8; + const int n = nb + c; + if (n < NOUT) { + const device vec* wp = (const device vec*)(we + (size_t)(NOUT + n) * K + k0 + kk); + *((threadgroup vec*)&sm.st.ws[c][kk]) = wp[0]; + *((threadgroup vec*)&sm.st.ws[c][kk + 4]) = wp[1]; + } else { + *((threadgroup vec*)&sm.st.ws[c][kk]) = vec(0); + *((threadgroup vec*)&sm.st.ws[c][kk + 4]) = vec(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int kk = split * BK; kk < (split + 1) * BK; kk += 8) { + simdgroup_matrix a[FM_MAX]; + simdgroup_load(a[0], &sm.st.xs[0][kk], STRIDE); + if (FM_MAX == 2 && fm_max == 2) simdgroup_load(a[1], &sm.st.xs[8][kk], STRIDE); + for (int f = 0; f < FN; f++) { + simdgroup_matrix b; + simdgroup_load(b, &sm.st.ws[(cg * FN + f) * 8][kk], STRIDE, ulong2(0, 0), true); + simdgroup_multiply_accumulate(acc3[0][f], a[0], b, acc3[0][f]); + if (FM_MAX == 2 && fm_max == 2) simdgroup_multiply_accumulate(acc3[1][f], a[1], b, acc3[1][f]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + for (int fm = 0; fm < fm_max; fm++) { + for (int f = 0; f < FN; f++) { + simdgroup_store(acc1[fm][f], &sm.ep.os1[split][0][(cg * FN + f) * 8], N_TILE); + if (SWIGLU) simdgroup_store(acc3[fm][f], &sm.ep.os3[split][0][(cg * FN + f) * 8], N_TILE); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int v = (int)tid; v < 8 * N_TILE; v += 128) { + const int lr = v / N_TILE; + const int c = v % N_TILE; + const int r = fm * 8 + lr; + const int n = nb + c; + if (r < nr && n < NOUT) { + const int p = sel[start + c0 + r]; + float s1 = sm.ep.os1[0][lr][c]; + for (int sp = 1; sp < KS; sp++) s1 += sm.ep.os1[sp][lr][c]; + if (SWIGLU) { + float s3 = sm.ep.os3[0][lr][c]; + for (int sp = 1; sp < KS; sp++) s3 += sm.ep.os3[sp][lr][c]; + const float a = float(static_cast(s1)); + const float b = float(static_cast(s3)); + y[(size_t)p * NOUT + n] = static_cast((1.0f / (1.0f + exp(-a))) * a * b); + } else { + y[(size_t)p * NOUT + n] = static_cast(s1); + } + } + } + if (fm + 1 < fm_max || c0 + RPASS < ns) threadgroup_barrier(mem_flags::mem_threadgroup); + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_hyb_swiz.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_hyb_swiz.metal new file mode 100644 index 000000000..359517550 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_hyb_swiz.metal @@ -0,0 +1,221 @@ +// Row-invariant M>1 512B-coalesced swizzled hybrid MoE projection (scalar for ns<=2, 8x8 bfloat MMA for ns>=3). +// Shares the exact same swizzled weights as moemm_r1_swiz.metal & moemm_w2add_swiz.metal (zero duplication). +// Stages w1 and w3 together in 6.9 KB shared mem (only 2 barriers/KSTEP, reuses A tiles in registers!). +const int u = (int)threadgroup_position_in_grid.y; +const int e = elist[u]; +if (e < 0) return; + +const int ns = ecnt[u]; +const int start = eoff[u]; +const uint tid = thread_position_in_threadgroup.x; +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; +const int tile_n = (int)threadgroup_position_in_grid.x; +const int nb = tile_n * 16; +if (nb >= NOUT) return; + +constexpr int KSTEP = 64; +constexpr int KSTEPS = K / KSTEP; +constexpr size_t TILE_U2 = (size_t)KSTEPS * (SWIGLU ? 256 : 128); +constexpr size_t EXP_U2 = (size_t)(NOUT / 16) * TILE_U2; +const device ulong2* wtile = (const device ulong2*)w_swiz + (size_t)e * EXP_U2 + (size_t)tile_n * TILE_U2; + +if (ns <= 2) { + if (sg != 0) return; + const int s = (int)(lane & 3); + const int cg_sg = (int)(lane >> 2); + const int n0 = nb + cg_sg * 2; + const int p0 = sel[start]; + const int p1 = (ns == 2) ? sel[start + 1] : p0; + const device T* xp0 = x + (size_t)(PROW_IDENTITY ? p0 : (p0 / TOPK)) * K; + const device T* xp1 = x + (size_t)(PROW_IDENTITY ? p1 : (p1 / TOPK)) * K; + + float a0[2] = {0.0f, 0.0f}, a1[2] = {0.0f, 0.0f}; + float b0[2] = {0.0f, 0.0f}, b1[2] = {0.0f, 0.0f}; + + for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * 64 + s * 16; + const device ulong2* w1p = wtile + ks_i * (SWIGLU ? 256 : 128) + lane; + const device ulong2* w3p = w1p + 128; + for (int b_i = 0; b_i < 2; b_i++) { + const int k = k0 + b_i * 8; + const ulong2 x0r = *((const device ulong2*)(xp0 + k)); + const vec x0a = as_type>(x0r.x), x0b = as_type>(x0r.y); + const float u0 = float(x0a[0]), u1 = float(x0a[1]), u2 = float(x0a[2]), u3 = float(x0a[3]); + const float u4 = float(x0b[0]), u5 = float(x0b[1]), u6 = float(x0b[2]), u7 = float(x0b[3]); + float v0=0,v1=0,v2=0,v3=0,v4=0,v5=0,v6=0,v7=0; + if (ns == 2) { + const ulong2 x1r = *((const device ulong2*)(xp1 + k)); + const vec x1a = as_type>(x1r.x), x1b = as_type>(x1r.y); + v0 = float(x1a[0]); v1 = float(x1a[1]); v2 = float(x1a[2]); v3 = float(x1a[3]); + v4 = float(x1b[0]); v5 = float(x1b[1]); v6 = float(x1b[2]); v7 = float(x1b[3]); + } + for (int c = 0; c < 2; c++) { + const ulong2 r1 = w1p[(b_i * 2 + c) * 32]; + const vec wa = as_type>(r1.x), wb = as_type>(r1.y); + const float w0 = float(wa[0]), w1 = float(wa[1]), w2 = float(wa[2]), w3 = float(wa[3]); + const float w4 = float(wb[0]), w5 = float(wb[1]), w6 = float(wb[2]), w7 = float(wb[3]); + float t0 = a0[c]; + t0 = fma(u0, w0, t0); t0 = fma(u1, w1, t0); t0 = fma(u2, w2, t0); t0 = fma(u3, w3, t0); + t0 = fma(u4, w4, t0); t0 = fma(u5, w5, t0); t0 = fma(u6, w6, t0); t0 = fma(u7, w7, t0); + a0[c] = t0; + if (ns == 2) { + float t1 = a1[c]; + t1 = fma(v0, w0, t1); t1 = fma(v1, w1, t1); t1 = fma(v2, w2, t1); t1 = fma(v3, w3, t1); + t1 = fma(v4, w4, t1); t1 = fma(v5, w5, t1); t1 = fma(v6, w6, t1); t1 = fma(v7, w7, t1); + a1[c] = t1; + } + if (SWIGLU) { + const ulong2 r3 = w3p[(b_i * 2 + c) * 32]; + const vec qa = as_type>(r3.x), qb = as_type>(r3.y); + const float q0 = float(qa[0]), q1 = float(qa[1]), q2 = float(qa[2]), q3 = float(qa[3]); + const float q4 = float(qb[0]), q5 = float(qb[1]), q6 = float(qb[2]), q7 = float(qb[3]); + float p0t = b0[c]; + p0t = fma(u0, q0, p0t); p0t = fma(u1, q1, p0t); p0t = fma(u2, q2, p0t); p0t = fma(u3, q3, p0t); + p0t = fma(u4, q4, p0t); p0t = fma(u5, q5, p0t); p0t = fma(u6, q6, p0t); p0t = fma(u7, q7, p0t); + b0[c] = p0t; + if (ns == 2) { + float p1t = b1[c]; + p1t = fma(v0, q0, p1t); p1t = fma(v1, q1, p1t); p1t = fma(v2, q2, p1t); p1t = fma(v3, q3, p1t); + p1t = fma(v4, q4, p1t); p1t = fma(v5, q5, p1t); p1t = fma(v6, q6, p1t); p1t = fma(v7, q7, p1t); + b1[c] = p1t; + } + } + } + } + } + for (int c = 0; c < 2; c++) { + const float r0 = ((a0[c] + simd_shuffle_down(a0[c], 1)) + simd_shuffle_down(a0[c], 2)) + simd_shuffle_down(a0[c], 3); + const float r1 = (ns == 2) ? (((a1[c] + simd_shuffle_down(a1[c], 1)) + simd_shuffle_down(a1[c], 2)) + simd_shuffle_down(a1[c], 3)) : 0.0f; + if (SWIGLU) { + const float g0 = ((b0[c] + simd_shuffle_down(b0[c], 1)) + simd_shuffle_down(b0[c], 2)) + simd_shuffle_down(b0[c], 3); + const float g1 = (ns == 2) ? (((b1[c] + simd_shuffle_down(b1[c], 1)) + simd_shuffle_down(b1[c], 2)) + simd_shuffle_down(b1[c], 3)) : 0.0f; + if (s == 0 && n0 + c < NOUT) { + const float fa0 = float(static_cast(r0)), fb0 = float(static_cast(g0)); + y[(size_t)p0 * NOUT + n0 + c] = static_cast((1.0f / (1.0f + exp(-fa0))) * fa0 * fb0); + if (ns == 2) { + const float fa1 = float(static_cast(r1)), fb1 = float(static_cast(g1)); + y[(size_t)p1 * NOUT + n0 + c] = static_cast((1.0f / (1.0f + exp(-fa1))) * fa1 * fb1); + } + } + } else if (s == 0 && n0 + c < NOUT) { + y[(size_t)p0 * NOUT + n0 + c] = static_cast(r0); + if (ns == 2) y[(size_t)p1 * NOUT + n0 + c] = static_cast(r1); + } + } + return; +} + +constexpr int STRIDE = KSTEP + 8; +constexpr int RPASS = FM_MAX * 8; +struct StageMem { + T xs[RPASS][STRIDE]; + T ws1[16][STRIDE]; + T ws3[SWIGLU ? 16 : 1][SWIGLU ? STRIDE : 1]; +}; +struct EpiMem { + float os1[4][8][16]; + float os3[SWIGLU ? 4 : 1][SWIGLU ? 8 : 1][SWIGLU ? 16 : 1]; +}; +union ShMem { + StageMem st; + EpiMem ep; +}; +threadgroup ShMem sm; + +const int split = (int)sg; +const int b_i = (int)(tid >> 6); +const int c_i = (int)((tid >> 5) & 1); +const int cg_sg = (int)((tid >> 2) & 7); +const int s_i = (int)(tid & 3); +const int w_row = cg_sg * 2 + c_i; +const int w_kk = s_i * 16 + b_i * 8; + +for (int c0 = 0; c0 < ns; c0 += RPASS) { + const int nr = min(RPASS, ns - c0); + const int fm_max = (FM_MAX == 2 && nr > 8) ? 2 : 1; + const int mr = fm_max * 8; + + simdgroup_matrix acc1[FM_MAX][2]; + simdgroup_matrix acc3[SWIGLU ? FM_MAX : 1][SWIGLU ? 2 : 1]; + for (int fm = 0; fm < FM_MAX; fm++) { + for (int f = 0; f < 2; f++) { + acc1[fm][f] = simdgroup_matrix(0.0f); + if (SWIGLU) acc3[fm][f] = simdgroup_matrix(0.0f); + } + } + + for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * KSTEP; + for (int v = (int)tid; v < mr * 8; v += 128) { + const int r = v / 8; + const int kk = (v % 8) * 8; + if (r < nr) { + const int p = sel[start + c0 + r]; + const int xr_i = PROW_IDENTITY ? p : (p / TOPK); + *((threadgroup ulong2*)&sm.st.xs[r][kk]) = *((const device ulong2*)(x + (size_t)xr_i * K + k0 + kk)); + } else { + *((threadgroup ulong2*)&sm.st.xs[r][kk]) = ulong2(0); + } + } + const device ulong2* wk = wtile + ks_i * (SWIGLU ? 256 : 128); + *((threadgroup ulong2*)&sm.st.ws1[w_row][w_kk]) = wk[tid]; + if (SWIGLU) { + *((threadgroup ulong2*)&sm.st.ws3[w_row][w_kk]) = wk[128 + tid]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int kk = split * 16; kk < (split + 1) * 16; kk += 8) { + simdgroup_matrix a0, a1; + simdgroup_load(a0, &sm.st.xs[0][kk], STRIDE); + if (FM_MAX == 2 && fm_max == 2) simdgroup_load(a1, &sm.st.xs[8][kk], STRIDE); + simdgroup_matrix b0, b1; + simdgroup_load(b0, &sm.st.ws1[0][kk], STRIDE, ulong2(0, 0), true); + simdgroup_load(b1, &sm.st.ws1[8][kk], STRIDE, ulong2(0, 0), true); + simdgroup_multiply_accumulate(acc1[0][0], a0, b0, acc1[0][0]); + simdgroup_multiply_accumulate(acc1[0][1], a0, b1, acc1[0][1]); + if (FM_MAX == 2 && fm_max == 2) { + simdgroup_multiply_accumulate(acc1[1][0], a1, b0, acc1[1][0]); + simdgroup_multiply_accumulate(acc1[1][1], a1, b1, acc1[1][1]); + } + if (SWIGLU) { + simdgroup_load(b0, &sm.st.ws3[0][kk], STRIDE, ulong2(0, 0), true); + simdgroup_load(b1, &sm.st.ws3[8][kk], STRIDE, ulong2(0, 0), true); + simdgroup_multiply_accumulate(acc3[0][0], a0, b0, acc3[0][0]); + simdgroup_multiply_accumulate(acc3[0][1], a0, b1, acc3[0][1]); + if (FM_MAX == 2 && fm_max == 2) { + simdgroup_multiply_accumulate(acc3[1][0], a1, b0, acc3[1][0]); + simdgroup_multiply_accumulate(acc3[1][1], a1, b1, acc3[1][1]); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + for (int fm = 0; fm < fm_max; fm++) { + simdgroup_store(acc1[fm][0], &sm.ep.os1[split][0][0], 16); + simdgroup_store(acc1[fm][1], &sm.ep.os1[split][0][8], 16); + if (SWIGLU) { + simdgroup_store(acc3[fm][0], &sm.ep.os3[split][0][0], 16); + simdgroup_store(acc3[fm][1], &sm.ep.os3[split][0][8], 16); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int v = (int)tid; v < 128; v += 128) { + const int lr = v / 16, c = v % 16; + const int r = fm * 8 + lr; + const int n = nb + c; + if (r < nr && n < NOUT) { + const int p = sel[start + c0 + r]; + float s1 = ((sm.ep.os1[0][lr][c] + sm.ep.os1[1][lr][c]) + sm.ep.os1[2][lr][c]) + sm.ep.os1[3][lr][c]; + if (SWIGLU) { + float s3 = ((sm.ep.os3[0][lr][c] + sm.ep.os3[1][lr][c]) + sm.ep.os3[2][lr][c]) + sm.ep.os3[3][lr][c]; + const float a = float(static_cast(s1)), b = float(static_cast(s3)); + y[(size_t)p * NOUT + n] = static_cast((1.0f / (1.0f + exp(-a))) * a * b); + } else { + y[(size_t)p * NOUT + n] = static_cast(s1); + } + } + } + if (fm + 1 < fm_max || c0 + RPASS < ns) threadgroup_barrier(mem_flags::mem_threadgroup); + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_prefill_swiz.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_prefill_swiz.metal new file mode 100644 index 000000000..6cb162a0b --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_prefill_swiz.metal @@ -0,0 +1,201 @@ +// High-throughput batched prefill MoE GEMM directly on 512B-coalesced w13_swiz / w2_swiz (zero unswizzle copy!). +// Uses flat (tile_e, tile_off, tile_nr) work-queue along grid.x so same-expert M-tiles run concurrently and +// share weights in L2 with zero hot-expert stragglers. Uses Metal 4 MPP matmul2d (M5 NAX) when available. +// Fuses w1 + w3 + SwiGLU when SWIGLU == 1, scattering directly to y[sel[r], n] with zero reorder copy. +const int t_idx = (int)threadgroup_position_in_grid.x; +const int e = tile_e[t_idx]; +if (e < 0) return; + +const int start = tile_off[t_idx]; +const int nr = tile_nr[t_idx]; +const uint tid = thread_position_in_threadgroup.x; +const uint sg = simdgroup_index_in_threadgroup; +const int tile_n0 = (int)threadgroup_position_in_grid.y * (BN / 16); +const int n0 = tile_n0 * 16; + +constexpr int KSTEPS = K / 64; +constexpr int NTILES_TOTAL = NOUT / 16; +constexpr size_t TILE_U2 = (size_t)KSTEPS * (SWIGLU ? 256 : 128); +constexpr size_t EXP_U2 = (size_t)NTILES_TOTAL * TILE_U2; + +const device ulong2* wexp = (const device ulong2*)w_swiz + (size_t)e * EXP_U2; +const int b_i = (int)(tid >> 6); +const int c_i = (int)((tid >> 5) & 1); +const int cg_sg = (int)((tid >> 2) & 7); +const int s_i = (int)(tid & 3); +const int w_row_base = cg_sg * 2 + c_i; +const int w_kk = s_i * 16 + b_i * 8; + +#if defined(__METAL_VERSION__) && __METAL_VERSION__ >= 400 +using extents_t = metal::dextents; +using strides_t = metal::array; +using tg_t = metal::tensor; + +constexpr int STRIDE = 64; +constexpr int TSM = BM / 2; +constexpr int TSN = BN / 2; +threadgroup T xs[BM][STRIDE]; +threadgroup T ws1[BN][STRIDE]; +threadgroup T ws3[SWIGLU ? BN : 1][SWIGLU ? STRIDE : 1]; + +const int sg_m = (int)(sg >> 1); +const int sg_n = (int)(sg & 1); + +constexpr auto desc = mpp::tensor_ops::matmul2d_descriptor( + TSM, TSN, 64, false, true, true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate); +mpp::tensor_ops::matmul2d op; + +tg_t tA(&xs[sg_m * TSM][0], extents_t(64, TSM), strides_t{1, STRIDE}); +tg_t tB1(&ws1[sg_n * TSN][0], extents_t(64, TSN), strides_t{1, STRIDE}); +tg_t tB3(&ws3[SWIGLU ? sg_n * TSN : 0][0], extents_t(64, TSN), strides_t{1, STRIDE}); + +auto Areg = op.template get_left_input_cooperative_tensor(); +auto Dacc1 = op.template get_destination_cooperative_tensor(); +auto Dacc3 = op.template get_destination_cooperative_tensor(); +for (uint16_t i = 0; i < Dacc1.get_capacity(); i++) { + Dacc1[i] = 0.0f; + if (SWIGLU) Dacc3[i] = 0.0f; +} + +for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * 64; + for (int v = (int)tid; v < BM * 8; v += 128) { + const int r = v >> 3; + const int kk = (v & 7) << 3; + if (r < nr) { + const int p = sel[start + r]; + const int xr_i = PROW_IDENTITY ? p : (p / TOPK); + *((threadgroup ulong2*)&xs[r][kk]) = *((const device ulong2*)(x + (size_t)xr_i * K + k0 + kk)); + } else { + *((threadgroup ulong2*)&xs[r][kk]) = ulong2(0); + } + } + for (int st = 0; st < BN / 16; st++) { + const int tn = tile_n0 + st; + const int w_row = st * 16 + w_row_base; + if (tn < NTILES_TOTAL) { + const device ulong2* wk = wexp + (size_t)tn * TILE_U2 + (size_t)ks_i * (SWIGLU ? 256 : 128); + *((threadgroup ulong2*)&ws1[w_row][w_kk]) = wk[tid]; + if (SWIGLU) *((threadgroup ulong2*)&ws3[w_row][w_kk]) = wk[128 + tid]; + } else { + *((threadgroup ulong2*)&ws1[w_row][w_kk]) = ulong2(0); + if (SWIGLU) *((threadgroup ulong2*)&ws3[w_row][w_kk]) = ulong2(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (SWIGLU) { + Areg.load(tA); + op.run(Areg, tB1, Dacc1); + op.run(Areg, tB3, Dacc3); + } else { + op.run(tA, tB1, Dacc1); + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +for (uint16_t i = 0; i < Dacc1.get_capacity(); i++) { + auto idx = Dacc1.get_multidimensional_index(i); + const int r = sg_m * TSM + idx[1]; + const int c = n0 + sg_n * TSN + idx[0]; + if (r < nr && c < NOUT) { + const int p = sel[start + r]; + if (SWIGLU) { + const float a = float(static_cast(Dacc1[i])); + const float b = float(static_cast(Dacc3[i])); + y[(size_t)p * NOUT + c] = static_cast((1.0f / (1.0f + exp(-a))) * a * b); + } else { + y[(size_t)p * NOUT + c] = static_cast(Dacc1[i]); + } + } +} +#else +const uint lane = thread_index_in_simdgroup; +constexpr int STRIDE = 72; +constexpr int FM = BM / 16; +constexpr int FN = BN / 16; +threadgroup T xs[BM][STRIDE]; +threadgroup T ws1[BN][STRIDE]; +threadgroup T ws3[SWIGLU ? BN : 1][SWIGLU ? STRIDE : 1]; + +const uint sg_m = sg >> 1; +const uint sg_n = sg & 1; + +simdgroup_matrix acc1[FM][FN]; +simdgroup_matrix acc3[SWIGLU ? FM : 1][SWIGLU ? FN : 1]; +for (int fm = 0; fm < FM; fm++) { + for (int fn = 0; fn < FN; fn++) { + acc1[fm][fn] = simdgroup_matrix(0.0f); + if (SWIGLU) acc3[fm][fn] = simdgroup_matrix(0.0f); + } +} + +for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * 64; + for (int v = (int)tid; v < BM * 8; v += 128) { + const int r = v >> 3; + const int kk = (v & 7) << 3; + if (r < nr) { + const int p = sel[start + r]; + const int xr_i = PROW_IDENTITY ? p : (p / TOPK); + *((threadgroup ulong2*)&xs[r][kk]) = *((const device ulong2*)(x + (size_t)xr_i * K + k0 + kk)); + } else { + *((threadgroup ulong2*)&xs[r][kk]) = ulong2(0); + } + } + for (int st = 0; st < BN / 16; st++) { + const int tn = tile_n0 + st; + const int w_row = st * 16 + w_row_base; + if (tn < NTILES_TOTAL) { + const device ulong2* wk = wexp + (size_t)tn * TILE_U2 + (size_t)ks_i * (SWIGLU ? 256 : 128); + *((threadgroup ulong2*)&ws1[w_row][w_kk]) = wk[tid]; + if (SWIGLU) *((threadgroup ulong2*)&ws3[w_row][w_kk]) = wk[128 + tid]; + } else { + *((threadgroup ulong2*)&ws1[w_row][w_kk]) = ulong2(0); + if (SWIGLU) *((threadgroup ulong2*)&ws3[w_row][w_kk]) = ulong2(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int kk = 0; kk < 64; kk += 8) { + simdgroup_matrix a[FM], b[FN]; + for (int fm = 0; fm < FM; fm++) simdgroup_load(a[fm], &xs[sg_m * (BM / 2) + fm * 8][kk], STRIDE); + for (int fn = 0; fn < FN; fn++) simdgroup_load(b[fn], &ws1[sg_n * (BN / 2) + fn * 8][kk], STRIDE, ulong2(0, 0), true); + for (int fm = 0; fm < FM; fm++) + for (int fn = 0; fn < FN; fn++) + simdgroup_multiply_accumulate(acc1[fm][fn], a[fm], b[fn], acc1[fm][fn]); + if (SWIGLU) { + for (int fn = 0; fn < FN; fn++) simdgroup_load(b[fn], &ws3[sg_n * (BN / 2) + fn * 8][kk], STRIDE, ulong2(0, 0), true); + for (int fm = 0; fm < FM; fm++) + for (int fn = 0; fn < FN; fn++) + simdgroup_multiply_accumulate(acc3[fm][fn], a[fm], b[fn], acc3[fm][fn]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +const int my_r = (int)(((lane & 16) >> 2) | ((lane & 6) >> 1)); +const int my_c0 = (int)(((lane & 8) >> 1) | ((lane & 1) << 1)); +for (int fm = 0; fm < FM; fm++) { + const int r = (int)sg_m * (BM / 2) + fm * 8 + my_r; + if (r < nr) { + const int p = sel[start + r]; + for (int fn = 0; fn < FN; fn++) { + const int col = n0 + (int)sg_n * (BN / 2) + fn * 8 + my_c0; + if (col + 1 < NOUT) { + device T* yp = y + (size_t)p * NOUT + col; + if (SWIGLU) { + const float a0 = float(static_cast(acc1[fm][fn].thread_elements()[0])); + const float b0 = float(static_cast(acc3[fm][fn].thread_elements()[0])); + const float a1 = float(static_cast(acc1[fm][fn].thread_elements()[1])); + const float b1 = float(static_cast(acc3[fm][fn].thread_elements()[1])); + yp[0] = static_cast((1.0f / (1.0f + exp(-a0))) * a0 * b0); + yp[1] = static_cast((1.0f / (1.0f + exp(-a1))) * a1 * b1); + } else { + yp[0] = static_cast(acc1[fm][fn].thread_elements()[0]); + yp[1] = static_cast(acc1[fm][fn].thread_elements()[1]); + } + } + } + } +} +#endif diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_r1.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_r1.metal new file mode 100644 index 000000000..9231271ee --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_r1.metal @@ -0,0 +1,80 @@ +// Dedicated M=1 row-invariant MoE projection (zero shared memory, zero barriers, max occupancy). +// Exact bit-for-bit twin of moemm_hyb.metal (same (BK, KS) FMA chain, ordered simd_shuffle_down). +// When SWIGLU == 1: w is [E, 2 * NOUT, K], computes gate (0..NOUT-1) and up (NOUT..2*NOUT-1) and fuses silu(a) * b. +const int u = (int)threadgroup_position_in_grid.y; +const int e = pexp[u]; +const uint tid = thread_position_in_threadgroup.x; +const int s = (int)tid % KS; +const int cgi = (int)tid / KS; +const int nb = (int)threadgroup_position_in_grid.x * (TG / KS) * TN; +const int n0 = nb + cgi * TN; +if (n0 >= NOUT) return; + +const int xr0 = PROW_IDENTITY ? u : 0; +const device T* xp = x + (size_t)xr0 * K; +const device T* we = w + (size_t)e * (SWIGLU ? (2 * NOUT) : NOUT) * K; +const device T* wb1 = we + (size_t)n0 * K; +const device T* wb3 = SWIGLU ? (we + (size_t)(NOUT + n0) * K) : wb1; + +float acc1[TN]; +float acc3[TN]; +for (int c = 0; c < TN; c++) { acc1[c] = 0.0f; acc3[c] = 0.0f; } + +for (int k0 = s * BK; k0 < K; k0 += KS * BK) { + for (int kk = 0; kk < BK; kk += 8) { + const int k = k0 + kk; + const device vec* xv = (const device vec*)(xp + k); + const vec xa = xv[0], xb = xv[1]; + const float x0 = float(xa[0]), x1 = float(xa[1]), x2 = float(xa[2]), x3 = float(xa[3]); + const float x4 = float(xb[0]), x5 = float(xb[1]), x6 = float(xb[2]), x7 = float(xb[3]); + for (int c = 0; c < TN; c++) { + const int cl = (n0 + c < NOUT) ? c : 0; + { + const device vec* wv = (const device vec*)(wb1 + (size_t)cl * K + k); + const vec wa = wv[0], wb = wv[1]; + float t = acc1[c]; + t = fma(x0, float(wa[0]), t); t = fma(x1, float(wa[1]), t); + t = fma(x2, float(wa[2]), t); t = fma(x3, float(wa[3]), t); + t = fma(x4, float(wb[0]), t); t = fma(x5, float(wb[1]), t); + t = fma(x6, float(wb[2]), t); t = fma(x7, float(wb[3]), t); + acc1[c] = t; + } + if (SWIGLU) { + const device vec* wv = (const device vec*)(wb3 + (size_t)cl * K + k); + const vec wa = wv[0], wb = wv[1]; + float t = acc3[c]; + t = fma(x0, float(wa[0]), t); t = fma(x1, float(wa[1]), t); + t = fma(x2, float(wa[2]), t); t = fma(x3, float(wa[3]), t); + t = fma(x4, float(wb[0]), t); t = fma(x5, float(wb[1]), t); + t = fma(x6, float(wb[2]), t); t = fma(x7, float(wb[3]), t); + acc3[c] = t; + } + } + } +} + +for (int c = 0; c < TN; c++) { + float t1 = acc1[c]; + if (KS == 2) { + t1 = t1 + simd_shuffle_down(t1, 1); + } else if (KS == 4) { + t1 = ((t1 + simd_shuffle_down(t1, 1)) + simd_shuffle_down(t1, 2)) + simd_shuffle_down(t1, 3); + } + if (SWIGLU) { + float t3 = acc3[c]; + if (KS == 2) { + t3 = t3 + simd_shuffle_down(t3, 1); + } else if (KS == 4) { + t3 = ((t3 + simd_shuffle_down(t3, 1)) + simd_shuffle_down(t3, 2)) + simd_shuffle_down(t3, 3); + } + if (s == 0 && n0 + c < NOUT) { + const float a = float(static_cast(t1)); + const float b = float(static_cast(t3)); + y[(size_t)u * NOUT + n0 + c] = static_cast((1.0f / (1.0f + exp(-a))) * a * b); + } + } else { + if (s == 0 && n0 + c < NOUT) { + y[(size_t)u * NOUT + n0 + c] = static_cast(t1); + } + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_r1_swiz.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_r1_swiz.metal new file mode 100644 index 000000000..083d4c593 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_r1_swiz.metal @@ -0,0 +1,124 @@ +// Dedicated M=1 512B-coalesced swizzled MoE w13+SwiGLU kernel. +// Layout w_swiz: [E, NOUT // 16, K // 64, 2 (w1/w3), B8=2, TN=2, cg_sg=8, KS=4, 8] -> w1 & w3 are 2 KB apart. +// When FUSE_ROUTE == 1, computes exact deterministic top-TOPK in-register (~25ns, zero shared mem, zero barrier) +// directly from (logits, bias), eliminating all 38 standalone moeroute_m1 kernel launches! +// Exact bit-for-bit twin of moemm_hyb_swiz.metal + moeroute.metal. +const int u = (int)threadgroup_position_in_grid.y; +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; +const int s = (int)(lane & 3); +const int cgi_sg = (int)(lane >> 2); +constexpr int N_SG = 16; +const int sg_id = (int)threadgroup_position_in_grid.x * (TG / 32) + (int)sg; +const int n0 = sg_id * N_SG + cgi_sg * 2; +if (sg_id * N_SG >= NOUT) return; + +#if FUSE_ROUTE +constexpr int E_PER = (E + 31) / 32; +float loc_c[E_PER]; +for (int i = 0; i < E_PER; i++) { + const int ek = (int)lane + i * 32; + if (ek < E) { + const float lv = float(logits[ek]); + const float sv = float(static_cast(1.0f / (1.0f + exp(-lv)))); + loc_c[i] = USE_BIAS ? (sv + bias[ek]) : sv; + } else { + loc_c[i] = -INFINITY; + } +} +int top_i[TOPK]; +for (int j = 0; j < TOPK; j++) { + float bc = -INFINITY; + int be = 1000000; + for (int i = 0; i < E_PER; i++) { + const int ek = (int)lane + i * 32; + if (loc_c[i] > bc || (loc_c[i] == bc && ek < be)) { bc = loc_c[i]; be = ek; } + } + const float gmax = simd_max(bc); + const int win_e = simd_min((bc == gmax) ? be : 1000000); + top_i[j] = win_e; + for (int i = 0; i < E_PER; i++) { + if ((int)lane + i * 32 == win_e) loc_c[i] = -INFINITY; + } +} +for (int i = 1; i < TOPK; i++) { + const int ki = top_i[i]; + int j = i - 1; + while (j >= 0 && top_i[j] > ki) { top_i[j + 1] = top_i[j]; j--; } + top_i[j + 1] = ki; +} +const int e = top_i[u]; +#else +const int e = pexp[u]; +#endif + +float acc1[2] = {0.0f, 0.0f}; +float acc3[2] = {0.0f, 0.0f}; + +constexpr int KSTEPS = K / 64; +constexpr size_t TILE_U2 = (size_t)KSTEPS * 256; +constexpr size_t EXP_U2 = (size_t)(NOUT / 16) * TILE_U2; +const device ulong2* wtile = (const device ulong2*)w_swiz + (size_t)e * EXP_U2 + (size_t)sg_id * TILE_U2; + +for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * 64 + s * 16; + const device ulong2* w1p = wtile + ks_i * 256 + lane; + const device ulong2* w3p = w1p + 128; + for (int b_i = 0; b_i < 2; b_i++) { + const int k = k0 + b_i * 8; + const ulong2 xraw = *((const device ulong2*)(x + k)); + const vec xa = as_type>(xraw.x), xb = as_type>(xraw.y); + const float x0 = float(xa[0]), x1 = float(xa[1]), x2 = float(xa[2]), x3 = float(xa[3]); + const float x4 = float(xb[0]), x5 = float(xb[1]), x6 = float(xb[2]), x7 = float(xb[3]); + const ulong2 r1_0 = w1p[(b_i * 2 + 0) * 32]; + const ulong2 r1_1 = w1p[(b_i * 2 + 1) * 32]; + const ulong2 r3_0 = w3p[(b_i * 2 + 0) * 32]; + const ulong2 r3_1 = w3p[(b_i * 2 + 1) * 32]; + { + const vec wa = as_type>(r1_0.x), wb = as_type>(r1_0.y); + float t = acc1[0]; + t = fma(x0, float(wa[0]), t); t = fma(x1, float(wa[1]), t); + t = fma(x2, float(wa[2]), t); t = fma(x3, float(wa[3]), t); + t = fma(x4, float(wb[0]), t); t = fma(x5, float(wb[1]), t); + t = fma(x6, float(wb[2]), t); t = fma(x7, float(wb[3]), t); + acc1[0] = t; + } + { + const vec wa = as_type>(r1_1.x), wb = as_type>(r1_1.y); + float t = acc1[1]; + t = fma(x0, float(wa[0]), t); t = fma(x1, float(wa[1]), t); + t = fma(x2, float(wa[2]), t); t = fma(x3, float(wa[3]), t); + t = fma(x4, float(wb[0]), t); t = fma(x5, float(wb[1]), t); + t = fma(x6, float(wb[2]), t); t = fma(x7, float(wb[3]), t); + acc1[1] = t; + } + { + const vec wa = as_type>(r3_0.x), wb = as_type>(r3_0.y); + float t = acc3[0]; + t = fma(x0, float(wa[0]), t); t = fma(x1, float(wa[1]), t); + t = fma(x2, float(wa[2]), t); t = fma(x3, float(wa[3]), t); + t = fma(x4, float(wb[0]), t); t = fma(x5, float(wb[1]), t); + t = fma(x6, float(wb[2]), t); t = fma(x7, float(wb[3]), t); + acc3[0] = t; + } + { + const vec wa = as_type>(r3_1.x), wb = as_type>(r3_1.y); + float t = acc3[1]; + t = fma(x0, float(wa[0]), t); t = fma(x1, float(wa[1]), t); + t = fma(x2, float(wa[2]), t); t = fma(x3, float(wa[3]), t); + t = fma(x4, float(wb[0]), t); t = fma(x5, float(wb[1]), t); + t = fma(x6, float(wb[2]), t); t = fma(x7, float(wb[3]), t); + acc3[1] = t; + } + } +} + +for (int c = 0; c < 2; c++) { + const float t1 = ((acc1[c] + simd_shuffle_down(acc1[c], 1)) + simd_shuffle_down(acc1[c], 2)) + simd_shuffle_down(acc1[c], 3); + const float t3 = ((acc3[c] + simd_shuffle_down(acc3[c], 1)) + simd_shuffle_down(acc3[c], 2)) + simd_shuffle_down(acc3[c], 3); + if (s == 0 && n0 + c < NOUT) { + const float a = float(static_cast(t1)); + const float b = float(static_cast(t3)); + y[(size_t)u * NOUT + n0 + c] = static_cast((1.0f / (1.0f + exp(-a))) * a * b); + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_w2add_swiz.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_w2add_swiz.metal new file mode 100644 index 000000000..87f046172 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moemm_w2add_swiz.metal @@ -0,0 +1,136 @@ +// Dedicated M=1 512B-coalesced swizzled MoE w2 + ascending weighted sum + residual add. +// Uses 4-load upfront ulong2 prefetching (2 KB coalesced per simdgroup per KSTEP=64). +// When FUSE_ROUTE == 1, computes exact deterministic top-TOPK + wts in-register from (logits, bias, scale), +// eliminating all 38 standalone moeroute_m1 AND all 38 moewsum launches! +// Exact bit-for-bit twin of moeroute.metal + moemm_hyb_swiz.metal + moewsum.metal. +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; +const int s = (int)(lane & 3); +const int cgi_sg = (int)(lane >> 2); +constexpr int N_SG = 16; +const int sg_id = (int)threadgroup_position_in_grid.x * (TG / 32) + (int)sg; +const int n0 = sg_id * N_SG + cgi_sg * 2; +if (sg_id * N_SG >= NOUT) return; + +#if FUSE_ROUTE +constexpr int E_PER = (E + 31) / 32; +float loc_c[E_PER], loc_s[E_PER]; +for (int i = 0; i < E_PER; i++) { + const int ek = (int)lane + i * 32; + if (ek < E) { + const float lv = float(logits[ek]); + const float sv = float(static_cast(1.0f / (1.0f + exp(-lv)))); + loc_s[i] = sv; + loc_c[i] = USE_BIAS ? (sv + bias[ek]) : sv; + } else { + loc_s[i] = 0.0f; + loc_c[i] = -INFINITY; + } +} +int top_i[TOPK]; +float top_s[TOPK]; +for (int j = 0; j < TOPK; j++) { + float bc = -INFINITY, bs = 0.0f; + int be = 1000000; + for (int i = 0; i < E_PER; i++) { + const int ek = (int)lane + i * 32; + if (loc_c[i] > bc || (loc_c[i] == bc && ek < be)) { bc = loc_c[i]; bs = loc_s[i]; be = ek; } + } + const float gmax = simd_max(bc); + const int win_e = simd_min((bc == gmax) ? be : 1000000); + const float win_s = simd_broadcast(bs, (ushort)(win_e & 31)); + top_i[j] = win_e; + top_s[j] = win_s; + for (int i = 0; i < E_PER; i++) { + if ((int)lane + i * 32 == win_e) loc_c[i] = -INFINITY; + } +} +for (int i = 1; i < TOPK; i++) { + const int ki = top_i[i]; + const float ks = top_s[i]; + int j = i - 1; + while (j >= 0 && top_i[j] > ki) { top_i[j + 1] = top_i[j]; top_s[j + 1] = top_s[j]; j--; } + top_i[j + 1] = ki; + top_s[j + 1] = ks; +} +float tot = top_s[0]; +for (int j = 1; j < TOPK; j++) tot = tot + top_s[j]; +const float denom = tot + 1e-6f; +const float sc = scale[0]; +float top_w[TOPK]; +for (int j = 0; j < TOPK; j++) top_w[j] = float(static_cast((top_s[j] / denom) * sc)); +#endif + +constexpr int KSTEPS = K / 64; +constexpr size_t TILE_U2 = (size_t)KSTEPS * 128; +constexpr size_t EXP_U2 = (size_t)(NOUT / 16) * TILE_U2; + +float out_sum[2] = {0.0f, 0.0f}; + +for (int j = 0; j < TOPK; j++) { +#if FUSE_ROUTE + const int e = top_i[j]; + const float wj = top_w[j]; +#else + const int e = pexp[j]; + const float wj = float(wts[j]); +#endif + const device T* xp = x + (size_t)j * K; + const device ulong2* wtile = (const device ulong2*)w_swiz + (size_t)e * EXP_U2 + (size_t)sg_id * TILE_U2; + float t0 = 0.0f, t1 = 0.0f; + for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * 64 + s * 16; + const device ulong2* wp = wtile + ks_i * 128 + lane; + const ulong2 w00 = wp[0]; + const ulong2 w01 = wp[32]; + const ulong2 w10 = wp[64]; + const ulong2 w11 = wp[96]; + const device ulong2* xpu = (const device ulong2*)(xp + k0); + const ulong2 xr0 = xpu[0]; + const ulong2 xr1 = xpu[1]; + const vec x0a = as_type>(xr0.x), x0b = as_type>(xr0.y); + const vec x1a = as_type>(xr1.x), x1b = as_type>(xr1.y); + { + const vec wa = as_type>(w00.x), wb = as_type>(w00.y); + t0 = fma(float(x0a[0]), float(wa[0]), t0); t0 = fma(float(x0a[1]), float(wa[1]), t0); + t0 = fma(float(x0a[2]), float(wa[2]), t0); t0 = fma(float(x0a[3]), float(wa[3]), t0); + t0 = fma(float(x0b[0]), float(wb[0]), t0); t0 = fma(float(x0b[1]), float(wb[1]), t0); + t0 = fma(float(x0b[2]), float(wb[2]), t0); t0 = fma(float(x0b[3]), float(wb[3]), t0); + } + { + const vec wa = as_type>(w01.x), wb = as_type>(w01.y); + t1 = fma(float(x0a[0]), float(wa[0]), t1); t1 = fma(float(x0a[1]), float(wa[1]), t1); + t1 = fma(float(x0a[2]), float(wa[2]), t1); t1 = fma(float(x0a[3]), float(wa[3]), t1); + t1 = fma(float(x0b[0]), float(wb[0]), t1); t1 = fma(float(x0b[1]), float(wb[1]), t1); + t1 = fma(float(x0b[2]), float(wb[2]), t1); t1 = fma(float(x0b[3]), float(wb[3]), t1); + } + { + const vec wa = as_type>(w10.x), wb = as_type>(w10.y); + t0 = fma(float(x1a[0]), float(wa[0]), t0); t0 = fma(float(x1a[1]), float(wa[1]), t0); + t0 = fma(float(x1a[2]), float(wa[2]), t0); t0 = fma(float(x1a[3]), float(wa[3]), t0); + t0 = fma(float(x1b[0]), float(wb[0]), t0); t0 = fma(float(x1b[1]), float(wb[1]), t0); + t0 = fma(float(x1b[2]), float(wb[2]), t0); t0 = fma(float(x1b[3]), float(wb[3]), t0); + } + { + const vec wa = as_type>(w11.x), wb = as_type>(w11.y); + t1 = fma(float(x1a[0]), float(wa[0]), t1); t1 = fma(float(x1a[1]), float(wa[1]), t1); + t1 = fma(float(x1a[2]), float(wa[2]), t1); t1 = fma(float(x1a[3]), float(wa[3]), t1); + t1 = fma(float(x1b[0]), float(wb[0]), t1); t1 = fma(float(x1b[1]), float(wb[1]), t1); + t1 = fma(float(x1b[2]), float(wb[2]), t1); t1 = fma(float(x1b[3]), float(wb[3]), t1); + } + } + const float r0 = ((t0 + simd_shuffle_down(t0, 1)) + simd_shuffle_down(t0, 2)) + simd_shuffle_down(t0, 3); + const float r1 = ((t1 + simd_shuffle_down(t1, 1)) + simd_shuffle_down(t1, 2)) + simd_shuffle_down(t1, 3); + if (s == 0 && n0 < NOUT) { + const float term0 = float(static_cast(float(static_cast(r0)) * wj)); + out_sum[0] = (j == 0) ? term0 : float(static_cast(out_sum[0] + term0)); + } + if (s == 0 && n0 + 1 < NOUT) { + const float term1 = float(static_cast(float(static_cast(r1)) * wj)); + out_sum[1] = (j == 0) ? term1 : float(static_cast(out_sum[1] + term1)); + } +} +if (s == 0) { + if (n0 < NOUT) out[n0] = static_cast(float(h[n0]) + out_sum[0]); + if (n0 + 1 < NOUT) out[n0 + 1] = static_cast(float(h[n0 + 1]) + out_sum[1]); +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moeprefill_grp.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moeprefill_grp.metal new file mode 100644 index 000000000..9a3b22fd0 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moeprefill_grp.metal @@ -0,0 +1,45 @@ +// Single-TG GPU expert grouping + flat BM-tile work-queue for batched prefill (zero skewed-expert stragglers!). +// Emits (tile_e[MAXT], tile_off[MAXT], tile_nr[MAXT]) splitting hot experts across parallel threadgroups, plus sel[P]. +// Grid: (256, 1, 1), Threadgroup: (256, 1, 1). +const uint tid = thread_position_in_threadgroup.x; +const int P = pexp_shape[0]; + +threadgroup atomic_uint tg_cnt[E]; +threadgroup atomic_uint tg_pos[E]; + +if ((int)tid < E) atomic_store_explicit(&tg_cnt[tid], 0u, memory_order_relaxed); +threadgroup_barrier(mem_flags::mem_threadgroup); + +for (int p = (int)tid; p < P; p += 256) { + atomic_fetch_add_explicit(&tg_cnt[pexp[p]], 1u, memory_order_relaxed); +} +threadgroup_barrier(mem_flags::mem_threadgroup); + +if (tid == 0) { + uint off = 0; + int t = 0; + for (int e = 0; e < E; e++) { + const uint c = atomic_load_explicit(&tg_cnt[e], memory_order_relaxed); + atomic_store_explicit(&tg_pos[e], off, memory_order_relaxed); + for (int c0 = 0; c0 < (int)c; c0 += BM) { + if (t < MAXT) { + tile_e[t] = e; + tile_off[t] = (int)off + c0; + tile_nr[t] = min(BM, (int)c - c0); + t++; + } + } + off += c; + } + for (; t < MAXT; t++) { + tile_e[t] = -1; + tile_off[t] = 0; + tile_nr[t] = 0; + } +} +threadgroup_barrier(mem_flags::mem_threadgroup); + +for (int p = (int)tid; p < P; p += 256) { + const uint pos = atomic_fetch_add_explicit(&tg_pos[pexp[p]], 1u, memory_order_relaxed); + sel[pos] = p; +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moeroute.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moeroute.metal new file mode 100644 index 000000000..8870a6c87 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moeroute.metal @@ -0,0 +1,146 @@ +// Fused MoE router top-k + ascending sort + ordered renorm + LPT compact expert grouping (1 threadgroup). +// - When M == 1 (GROUP == 0): all E threads compute sigmoid+bias in parallel (1 exp() per thread!), +// and 2 simdgroups find the top-TOPK in parallel, skipping unused elist/eoff/ecnt/sel grouping. +// - When M > 1 (GROUP == 1): thread m processes row m's E logits independently with deterministic tie-breaking, +// then outputs LPT-ordered (ns>=3 heavy MMA experts first, then ns==2, then ns==1) compact (elist, eoff, ecnt, sel). +// 100% bit-for-bit row-invariant across M=1..64. +const uint tid = thread_position_in_threadgroup.x; +const int M = logits_shape[0]; +const int P = M * TOPK; + +#if !GROUP +// M == 1 fast path: parallel sigmoid+bias across all E threads (no 64x serial exp() loop on thread 0!) +threadgroup float tg_s[E]; +threadgroup float tg_c[E]; +if ((int)tid < E) { + const float lv = float(logits[tid]); + const float sv = float(static_cast(1.0f / (1.0f + exp(-lv)))); + tg_s[tid] = sv; + tg_c[tid] = USE_BIAS ? (sv + bias[tid]) : sv; +} +threadgroup_barrier(mem_flags::mem_threadgroup); +if (tid == 0) { + float top_c[TOPK], top_s[TOPK]; + int top_i[TOPK]; + for (int j = 0; j < TOPK; j++) { top_c[j] = -INFINITY; top_s[j] = 0.0f; top_i[j] = -1; } + for (int e = 0; e < E; e++) { + const float cv = tg_c[e]; + const float sv = tg_s[e]; + int min_j = 0; + for (int j = 1; j < TOPK; j++) { + if (top_c[j] < top_c[min_j] || (top_c[j] == top_c[min_j] && top_i[j] > top_i[min_j])) min_j = j; + } + if (cv > top_c[min_j]) { top_c[min_j] = cv; top_s[min_j] = sv; top_i[min_j] = e; } + } + for (int i = 1; i < TOPK; i++) { + const int ki = top_i[i]; + const float ks = top_s[i]; + int j = i - 1; + while (j >= 0 && top_i[j] > ki) { top_i[j + 1] = top_i[j]; top_s[j + 1] = top_s[j]; j--; } + top_i[j + 1] = ki; + top_s[j + 1] = ks; + } + float tot = top_s[0]; + for (int j = 1; j < TOPK; j++) tot = tot + top_s[j]; + const float denom = tot + 1e-6f; + const float sc = scale[0]; + for (int j = 0; j < TOPK; j++) { + pexp[j] = top_i[j]; + wts[j] = static_cast((top_s[j] / denom) * sc); + } +} +#else +threadgroup int tg_pexp[MAXP]; +threadgroup int tg_cnt[E]; +threadgroup int tg_uoff[E]; + +if ((int)tid < M) { + const int m = (int)tid; + const device T* row = logits + (size_t)m * E; + float top_c[TOPK]; + float top_s[TOPK]; + int top_i[TOPK]; + for (int j = 0; j < TOPK; j++) { top_c[j] = -INFINITY; top_s[j] = 0.0f; top_i[j] = -1; } + for (int e = 0; e < E; e++) { + const float lv = float(row[e]); + const float sv = float(static_cast(1.0f / (1.0f + exp(-lv)))); + const float cv = USE_BIAS ? (sv + bias[e]) : sv; + int min_j = 0; + for (int j = 1; j < TOPK; j++) { + if (top_c[j] < top_c[min_j] || (top_c[j] == top_c[min_j] && top_i[j] > top_i[min_j])) min_j = j; + } + if (cv > top_c[min_j]) { + top_c[min_j] = cv; + top_s[min_j] = sv; + top_i[min_j] = e; + } + } + for (int i = 1; i < TOPK; i++) { + const int ki = top_i[i]; + const float ks = top_s[i]; + int j = i - 1; + while (j >= 0 && top_i[j] > ki) { + top_i[j + 1] = top_i[j]; + top_s[j + 1] = top_s[j]; + j--; + } + top_i[j + 1] = ki; + top_s[j + 1] = ks; + } + float tot = top_s[0]; + for (int j = 1; j < TOPK; j++) tot = tot + top_s[j]; + const float denom = tot + 1e-6f; + const float sc = scale[0]; + for (int j = 0; j < TOPK; j++) { + tg_pexp[m * TOPK + j] = top_i[j]; + pexp[m * TOPK + j] = top_i[j]; + wts[m * TOPK + j] = static_cast((top_s[j] / denom) * sc); + } +} +threadgroup_barrier(mem_flags::mem_threadgroup); + +if ((int)tid < E) { + int c = 0; + for (int p = 0; p < P; p++) { + if (tg_pexp[p] == (int)tid) c++; + } + tg_cnt[tid] = c; +} +threadgroup_barrier(mem_flags::mem_threadgroup); + +// LPT ordering: heavy MMA experts (ns >= 3) first, then ns == 2, then ns == 1 (minimizes GPU wave tail!) +if (tid == 0) { + int u = 0; + int off = 0; + for (int e = 0; e < E; e++) tg_uoff[e] = -1; + for (int e = 0; e < E; e++) { + const int c = tg_cnt[e]; + if (c >= 3) { elist[u] = e; eoff[u] = off; ecnt[u] = c; tg_uoff[e] = off; off += c; u++; } + } + for (int e = 0; e < E; e++) { + const int c = tg_cnt[e]; + if (c == 2) { elist[u] = e; eoff[u] = off; ecnt[u] = c; tg_uoff[e] = off; off += c; u++; } + } + for (int e = 0; e < E; e++) { + const int c = tg_cnt[e]; + if (c == 1) { elist[u] = e; eoff[u] = off; ecnt[u] = c; tg_uoff[e] = off; off += c; u++; } + } + for (; u < EMAX; u++) { + elist[u] = -1; + eoff[u] = 0; + ecnt[u] = 0; + } +} +threadgroup_barrier(mem_flags::mem_threadgroup); + +if ((int)tid < E) { + int pos = tg_uoff[tid]; + if (pos >= 0) { + for (int p = 0; p < P; p++) { + if (tg_pexp[p] == (int)tid) { + sel[pos++] = p; + } + } + } +} +#endif diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/moewsum.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/moewsum.metal new file mode 100644 index 000000000..3fbde07a8 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/moewsum.metal @@ -0,0 +1,31 @@ +// Fused MoE weighted expert sum + residual add in ascending expert slot order: +// out[m, n] = h[m, n] + sum_{j=0..TOPK-1} (y[m * TOPK + j, n] * wts[m, j]) +const uint tid = thread_position_in_grid.x; +const int m = (int)threadgroup_position_in_grid.y; +const int n4 = (int)tid * 4; +if (n4 >= N) return; +const device vec* hp = (const device vec*)(h + (size_t)m * N + n4); +const vec hv = *hp; +float s0 = 0.0f, s1 = 0.0f, s2 = 0.0f, s3 = 0.0f; +for (int j = 0; j < TOPK; j++) { + const float wj = float(wts[(size_t)m * TOPK + j]); + const device vec* yp = (const device vec*)(y + (size_t)(m * TOPK + j) * N + n4); + const vec yv = *yp; + if (j == 0) { + s0 = float(static_cast(float(yv[0]) * wj)); + s1 = float(static_cast(float(yv[1]) * wj)); + s2 = float(static_cast(float(yv[2]) * wj)); + s3 = float(static_cast(float(yv[3]) * wj)); + } else { + s0 = float(static_cast(s0 + float(static_cast(float(yv[0]) * wj)))); + s1 = float(static_cast(s1 + float(static_cast(float(yv[1]) * wj)))); + s2 = float(static_cast(s2 + float(static_cast(float(yv[2]) * wj)))); + s3 = float(static_cast(s3 + float(static_cast(float(yv[3]) * wj)))); + } +} +vec res; +res[0] = static_cast(float(hv[0]) + s0); +res[1] = static_cast(float(hv[1]) + s1); +res[2] = static_cast(float(hv[2]) + s2); +res[3] = static_cast(float(hv[3]) + s3); +*((device vec*)(out + (size_t)m * N + n4)) = res; diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn.metal new file mode 100644 index 000000000..aa0d8acaa --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn.metal @@ -0,0 +1,59 @@ +// Row-invariant attention of a block's rows (engine/models/lfm2_moe/mlx_kernels.py). A threadgroup is one +// (query head h, row r). The row's keys in logical order are the cache's slots 0..L-1, then its path in the +// block (slots L + anc[r][0..d-1], root first): what the same row sees when it is decoded alone, in the same +// order. Thread t takes logical keys t, t + NT, ... (an online softmax of its own), the lanes are combined by +// simd reductions and the simdgroups in order 0..NT/32-1: every step depends on the row's keys alone. +uint h = threadgroup_position_in_grid.x; +uint r = threadgroup_position_in_grid.y; +uint tid = thread_position_in_threadgroup.x; +uint sg = simdgroup_index_in_threadgroup; +uint lane = thread_index_in_simdgroup; +const int Hq = q_shape[1]; +const int cap = kc_shape[1]; +const int A = anc_shape[1]; +const int L = lb[0]; +const int n = L + dl[r]; +const uint hk = h / GQA; +const float scale = rsqrt((float)D); +float qv[D]; +for (int i = 0; i < D; i++) qv[i] = float(q[((size_t)r * Hq + h) * D + i]); +float m = -INFINITY, l = 0.0f; +float acc[D]; +for (int i = 0; i < D; i++) acc[i] = 0.0f; +for (int j = (int)tid; j < n; j += NT) { + const int slot = j < L ? j : L + anc[(size_t)r * A + (j - L)]; + const device T* kp = kc + ((size_t)hk * cap + slot) * D; + const device T* vp = vc + ((size_t)hk * cap + slot) * D; + float s = 0.0f; + for (int i = 0; i < D; i++) s = fma(qv[i], float(kp[i]), s); + s *= scale; + const float mn = max(m, s); + const float c = exp(m - mn); + const float p = exp(s - mn); + l = l * c + p; + for (int i = 0; i < D; i++) acc[i] = acc[i] * c + p * float(vp[i]); + m = mn; +} +threadgroup float tM[NT / 32]; +threadgroup float tL[NT / 32]; +threadgroup float tA[NT / 32][D]; +const float Ms = simd_max(m); +const float f = (m == -INFINITY) ? 0.0f : exp(m - Ms); +const float ls = simd_sum(l * f); +for (int i = 0; i < D; i++) { + const float a = simd_sum(acc[i] * f); + if (lane == 0) tA[sg][i] = a; +} +if (lane == 0) { tM[sg] = Ms; tL[sg] = ls; } +threadgroup_barrier(mem_flags::mem_threadgroup); +if (tid < (uint)D) { + float Mx = -INFINITY; + for (int g = 0; g < NT / 32; g++) Mx = max(Mx, tM[g]); + float L2 = 0.0f, A2 = 0.0f; + for (int g = 0; g < NT / 32; g++) { + const float wg = (tM[g] == -INFINITY) ? 0.0f : exp(tM[g] - Mx); + L2 += tL[g] * wg; + A2 += tA[g][tid] * wg; + } + o[((size_t)r * Hq + h) * D + tid] = static_cast(A2 / L2); +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_flash.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_flash.metal new file mode 100644 index 000000000..b292646b5 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_flash.metal @@ -0,0 +1,285 @@ +// Row-invariant FlashAttention-2 Split-K on 8x8 bfloat simdgroup_matrix units (D == 64, GQA == 4). +// Each logical key chunk [ch * BK, (ch + 1) * BK) is processed in fixed BT=32 tiles using 8x8 simdgroup MMA, +// in-register online softmax (simd_shuffle_xor(1) / simd_shuffle_xor(8)), and in-register O rescale. +// A threadgroup shares a single 4.6 KB bfloat kv[BT][D+8] buffer across all GQA=4 heads and BM rows +// (BM=2/NSG=1 for M<=2, BM=4/NSG=2 for M<=4, BM=8/NSG=4 for M<=8, BM=16/NSG=8 for M>8 -> QT_PER_SG=1 always). +// 100% bit-for-bit row-invariant across M=1..64, arbitrary trees, and any L/dlen split. +const uint hk = threadgroup_position_in_grid.x; +const uint ch = threadgroup_position_in_grid.y; +const uint rb = threadgroup_position_in_grid.z; +const uint tid = thread_position_in_threadgroup.x; +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; + +const int M = q_shape[0]; +const int Hq = q_shape[1]; +const int cap = kc_shape[1]; +const int A = anc_shape[1]; +const int L = lb[0]; +const int nchunks = (int)threadgroups_per_grid.y; +const int r0 = (int)rb * BM; +const float scale = rsqrt((float)D) * 1.4426950408889634f; // log2(e) / sqrt(D) + +const int j_start = (int)ch * BK; +const int j_end_cap = j_start + BK; + +constexpr int NTHREADS = NSG * 32; +constexpr int NQT = (BM * GQA + 7) / 8; +constexpr int BT = 32; +constexpr int NT_BLOCKS = BT / 8; +constexpr int ND_BLOCKS = D / 8; +constexpr int KV_STRIDE = D + 8; + +// Apple Silicon 8x8 simdgroup_matrix lane -> (row, col0) mapping +const int my_qr = (int)(((lane & 16) >> 2) | ((lane & 6) >> 1)); +const int my_c0 = (int)(((lane & 8) >> 1) | ((lane & 1) << 1)); + +threadgroup T kv[BT][KV_STRIDE]; + +// Load Q into registers (1 Q-tile = 2 rows x GQA(4) heads per simdgroup) via kv scratch +simdgroup_matrix Qm[ND_BLOCKS]; +simdgroup_matrix O[ND_BLOCKS]; +float m_cur = -INFINITY; +float l_cur = 0.0f; +const int qt = (int)sg; + +for (int sg_batch = 0; sg_batch < NSG; sg_batch += 4) { + if ((int)sg >= sg_batch && (int)sg < sg_batch + 4) { + const int sg_loc = (int)sg - sg_batch; + for (int idx = (int)lane; idx < 8 * (D / 4); idx += 32) { + const int lr = idx / (D / 4); + const int d4 = (idx % (D / 4)) * 4; + const int gr = r0 + qt * 2 + (lr / GQA); + const int gh = (int)hk * GQA + (lr % GQA); + if (qt < NQT && gr < M) { + const device vec* qp = (const device vec*)(q + ((size_t)gr * Hq + gh) * D + d4); + *((threadgroup vec*)&kv[sg_loc * 8 + lr][d4]) = *qp; + } else { + *((threadgroup vec*)&kv[sg_loc * 8 + lr][d4]) = vec(0); + } + } + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int db = 0; db < ND_BLOCKS; db++) { + simdgroup_load(Qm[db], &kv[sg_loc * 8][db * 8], KV_STRIDE); + O[db] = simdgroup_matrix(0.0f); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +const device T* kbase = kc + (size_t)hk * cap * D; +const device T* vbase = vc + (size_t)hk * cap * D; + +const int full_prefix_end = (j_end_cap <= L) + ? j_end_cap + : (j_start + ((max(0, min(j_end_cap, L) - j_start)) / BT) * BT); + +// Shared prefix blocks: ALL rows and GQA heads share the exact same K and V loads! +for (int jb = j_start; jb < full_prefix_end; jb += BT) { + for (int v = (int)tid; v < BT * (D / 8); v += NTHREADS) { + const int t = v / (D / 8); + const int d8 = (v % (D / 8)) * 8; + const device vec* kp = (const device vec*)(kbase + (size_t)(jb + t) * D + d8); + *((threadgroup vec*)&kv[t][d8]) = kp[0]; + *((threadgroup vec*)&kv[t][d8 + 4]) = kp[1]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + simdgroup_matrix Pm[NT_BLOCKS]; + float cf = 1.0f; + if (qt < NQT) { + simdgroup_matrix S[NT_BLOCKS]; + for (int tb = 0; tb < NT_BLOCKS; tb++) S[tb] = simdgroup_matrix(0.0f); + for (int db = 0; db < ND_BLOCKS; db++) { + for (int tb = 0; tb < NT_BLOCKS; tb++) { + simdgroup_matrix km; + simdgroup_load(km, &kv[tb * 8][db * 8], KV_STRIDE, ulong2(0, 0), true); + simdgroup_multiply_accumulate(S[tb], Qm[db], km, S[tb]); + } + } + float mt = -INFINITY; + for (int tb = 0; tb < NT_BLOCKS; tb++) { + S[tb].thread_elements()[0] *= scale; + S[tb].thread_elements()[1] *= scale; + mt = max(mt, max(S[tb].thread_elements()[0], S[tb].thread_elements()[1])); + } + mt = max(mt, simd_shuffle_xor(mt, 1)); + mt = max(mt, simd_shuffle_xor(mt, 8)); + + const float mo = m_cur; + const float mn = max(mo, mt); + cf = (mo == -INFINITY) ? 0.0f : exp2(mo - mn); + float ls = 0.0f; + for (int tb = 0; tb < NT_BLOCKS; tb++) { + const float p0 = exp2(S[tb].thread_elements()[0] - mn); + const float p1 = exp2(S[tb].thread_elements()[1] - mn); + ls += p0 + p1; + Pm[tb].thread_elements()[0] = static_cast(p0); + Pm[tb].thread_elements()[1] = static_cast(p1); + } + ls = ls + simd_shuffle_xor(ls, 1); + ls = ls + simd_shuffle_xor(ls, 8); + l_cur = l_cur * cf + ls; + m_cur = mn; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int v = (int)tid; v < BT * (D / 8); v += NTHREADS) { + const int t = v / (D / 8); + const int d8 = (v % (D / 8)) * 8; + const device vec* vp = (const device vec*)(vbase + (size_t)(jb + t) * D + d8); + *((threadgroup vec*)&kv[t][d8]) = vp[0]; + *((threadgroup vec*)&kv[t][d8 + 4]) = vp[1]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (qt < NQT) { + for (int db = 0; db < ND_BLOCKS; db++) { + if (jb > j_start) { + O[db].thread_elements()[0] *= cf; + O[db].thread_elements()[1] *= cf; + } + for (int tb = 0; tb < NT_BLOCKS; tb++) { + simdgroup_matrix vm; + simdgroup_load(vm, &kv[tb * 8][db * 8], KV_STRIDE); + simdgroup_multiply_accumulate(O[db], Pm[tb], vm, O[db]); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +// Tail blocks crossing L: each row uses its own path anc[gr] with the exact same 8x8 MMA math +if (full_prefix_end < j_end_cap) { + const int nr = min(BM, M - r0); + for (int lr = 0; lr < nr; lr++) { + const int gr = r0 + lr; + const int n_r = L + dl[gr]; + const int target_sg = lr / 2; + const int row_off = (lr % 2) * 4; + for (int jb = full_prefix_end; jb < j_end_cap; jb += BT) { + if (jb >= n_r) break; + for (int v = (int)tid; v < BT * (D / 8); v += NTHREADS) { + const int t = v / (D / 8); + const int d8 = (v % (D / 8)) * 8; + const int j = jb + t; + if (j < n_r) { + const int slot = (j < L) ? j : (L + anc[(size_t)gr * A + (j - L)]); + const device vec* kp = (const device vec*)(kbase + (size_t)slot * D + d8); + *((threadgroup vec*)&kv[t][d8]) = kp[0]; + *((threadgroup vec*)&kv[t][d8 + 4]) = kp[1]; + } else { + *((threadgroup vec*)&kv[t][d8]) = vec(0); + *((threadgroup vec*)&kv[t][d8 + 4]) = vec(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + simdgroup_matrix Pm_tail[NT_BLOCKS]; + float cf_tail = 1.0f; + if ((int)sg == target_sg) { + simdgroup_matrix S[NT_BLOCKS]; + for (int tb = 0; tb < NT_BLOCKS; tb++) S[tb] = simdgroup_matrix(0.0f); + for (int db = 0; db < ND_BLOCKS; db++) { + for (int tb = 0; tb < NT_BLOCKS; tb++) { + simdgroup_matrix km; + simdgroup_load(km, &kv[tb * 8][db * 8], KV_STRIDE, ulong2(0, 0), true); + simdgroup_multiply_accumulate(S[tb], Qm[db], km, S[tb]); + } + } + const bool active_row = (my_qr >= row_off && my_qr < row_off + 4); + if (active_row) { + float mt = -INFINITY; + for (int tb = 0; tb < NT_BLOCKS; tb++) { + const int t0 = jb + tb * 8 + my_c0; + const float s0 = (t0 < n_r) ? (S[tb].thread_elements()[0] * scale) : -INFINITY; + const float s1 = (t0 + 1 < n_r) ? (S[tb].thread_elements()[1] * scale) : -INFINITY; + S[tb].thread_elements()[0] = s0; + S[tb].thread_elements()[1] = s1; + mt = max(mt, max(s0, s1)); + } + mt = max(mt, simd_shuffle_xor(mt, 1)); + mt = max(mt, simd_shuffle_xor(mt, 8)); + const float mo = m_cur; + const float mn = max(mo, mt); + cf_tail = (mo == -INFINITY) ? 0.0f : exp2(mo - mn); + float ls = 0.0f; + for (int tb = 0; tb < NT_BLOCKS; tb++) { + const int t0 = jb + tb * 8 + my_c0; + const float p0 = (t0 < n_r) ? exp2(S[tb].thread_elements()[0] - mn) : 0.0f; + const float p1 = (t0 + 1 < n_r) ? exp2(S[tb].thread_elements()[1] - mn) : 0.0f; + ls += p0 + p1; + Pm_tail[tb].thread_elements()[0] = static_cast(p0); + Pm_tail[tb].thread_elements()[1] = static_cast(p1); + } + ls = ls + simd_shuffle_xor(ls, 1); + ls = ls + simd_shuffle_xor(ls, 8); + l_cur = l_cur * cf_tail + ls; + m_cur = mn; + } else { + for (int tb = 0; tb < NT_BLOCKS; tb++) { + Pm_tail[tb].thread_elements()[0] = T(0); + Pm_tail[tb].thread_elements()[1] = T(0); + } + cf_tail = 1.0f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int v = (int)tid; v < BT * (D / 8); v += NTHREADS) { + const int t = v / (D / 8); + const int d8 = (v % (D / 8)) * 8; + const int j = jb + t; + if (j < n_r) { + const int slot = (j < L) ? j : (L + anc[(size_t)gr * A + (j - L)]); + const device vec* vp = (const device vec*)(vbase + (size_t)slot * D + d8); + *((threadgroup vec*)&kv[t][d8]) = vp[0]; + *((threadgroup vec*)&kv[t][d8 + 4]) = vp[1]; + } else { + *((threadgroup vec*)&kv[t][d8]) = vec(0); + *((threadgroup vec*)&kv[t][d8 + 4]) = vec(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if ((int)sg == target_sg) { + for (int db = 0; db < ND_BLOCKS; db++) { + O[db].thread_elements()[0] *= cf_tail; + O[db].thread_elements()[1] *= cf_tail; + for (int tb = 0; tb < NT_BLOCKS; tb++) { + simdgroup_matrix vm; + simdgroup_load(vm, &kv[tb * 8][db * 8], KV_STRIDE); + simdgroup_multiply_accumulate(O[db], Pm_tail[tb], vm, O[db]); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } +} + +if (qt < NQT) { + const int gr = r0 + qt * 2 + (my_qr / GQA); + const int gh = (int)hk * GQA + (my_qr % GQA); + if (gr < M) { +#if SINGLE_CHUNK + const float invl = 1.0f / l_cur; + device T* op = o + ((size_t)gr * Hq + gh) * D + my_c0; + for (int db = 0; db < ND_BLOCKS; db++) { + op[db * 8] = static_cast(O[db].thread_elements()[0] * invl); + op[db * 8 + 1] = static_cast(O[db].thread_elements()[1] * invl); + } +#else + const size_t base = ((size_t)gr * Hq + gh) * nchunks + ch; + if (my_c0 == 0) { + pm[base] = m_cur; + pl[base] = l_cur; + } + device float* pap = pa + base * D + my_c0; + for (int db = 0; db < ND_BLOCKS; db++) { + pap[db * 8] = O[db].thread_elements()[0]; + pap[db * 8 + 1] = O[db].thread_elements()[1]; + } +#endif + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_flash_m2.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_flash_m2.metal new file mode 100644 index 000000000..d29d37e28 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_flash_m2.metal @@ -0,0 +1,244 @@ +// Row-invariant 4-simdgroup cooperative FlashAttention-2 Split-K for M <= 2 (D == 64, GQA == 4). +// Exact bit-for-bit twin of pathattn_flash.metal (M >= 3): same ATTN_BK=256, BT=32, 8x8 bfloat MMA, +// and exact same softmax reduction order. Uses 128 threads/TG (4 simdgroups) to load K/V 4x faster, +// parallelize Q@K^T across tb=0..3 and P@V across db=0..7, with only 3 barriers per BT=32 tile. +const uint hk = threadgroup_position_in_grid.x; +const uint ch = threadgroup_position_in_grid.y; +const uint rb = threadgroup_position_in_grid.z; +const uint tid = thread_position_in_threadgroup.x; +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; + +const int M = q_shape[0]; +const int Hq = q_shape[1]; +const int cap = kc_shape[1]; +const int A = anc_shape[1]; +const int L = lb[0]; +const int nchunks = (int)threadgroups_per_grid.y; +const int r0 = (int)rb * BM; +const float scale = rsqrt((float)D) * 1.4426950408889634f; // log2(e) / sqrt(D) + +const int j_start = (int)ch * BK; +const int j_end_cap = j_start + BK; + +constexpr int NTHREADS = 128; +constexpr int BT = 32; +constexpr int ND_BLOCKS = D / 8; // 8 +constexpr int KV_STRIDE = D + 8; + +const int my_qr = (int)(((lane & 16) >> 2) | ((lane & 6) >> 1)); +const int my_c0 = (int)(((lane & 8) >> 1) | ((lane & 1) << 1)); + +threadgroup T kv_k[BT][KV_STRIDE]; +threadgroup T kv_v[BT][KV_STRIDE]; +threadgroup float sm_mt[4][8]; +threadgroup float sm_ls[4][32]; +threadgroup T sm_pm[8][32]; + +// Load Q [8, 64] into kv_k[0..7] collaboratively with 128 threads +for (int idx = (int)tid; idx < 8 * (D / 4); idx += NTHREADS) { + const int lr = idx / (D / 4); + const int d4 = (idx % (D / 4)) * 4; + const int gr = r0 + (lr / GQA); + const int gh = (int)hk * GQA + (lr % GQA); + if (gr < M) { + const device vec* qp = (const device vec*)(q + ((size_t)gr * Hq + gh) * D + d4); + *((threadgroup vec*)&kv_k[lr][d4]) = *qp; + } else { + *((threadgroup vec*)&kv_k[lr][d4]) = vec(0); + } +} +threadgroup_barrier(mem_flags::mem_threadgroup); + +simdgroup_matrix Qm[ND_BLOCKS]; +for (int db = 0; db < ND_BLOCKS; db++) simdgroup_load(Qm[db], &kv_k[0][db * 8], KV_STRIDE); + +// Each simdgroup owns 2 of the 8 D-blocks of O (d_base = sg * 16) +simdgroup_matrix O0 = simdgroup_matrix(0.0f); +simdgroup_matrix O1 = simdgroup_matrix(0.0f); +float m_cur = -INFINITY; +float l_cur = 0.0f; +threadgroup_barrier(mem_flags::mem_threadgroup); + +const device T* kbase = kc + (size_t)hk * cap * D; +const device T* vbase = vc + (size_t)hk * cap * D; + +const int full_prefix_end = (j_end_cap <= L) + ? j_end_cap + : (j_start + ((max(0, min(j_end_cap, L) - j_start)) / BT) * BT); + +// Shared prefix blocks: 3 barriers per BT=32 tile (kv_k and kv_v ping-pong hazard-free) +for (int jb = j_start; jb < full_prefix_end; jb += BT) { + for (int v = (int)tid; v < BT * (D / 8); v += NTHREADS) { + const int t = v / (D / 8); + const int d8 = (v % (D / 8)) * 8; + *((threadgroup ulong2*)&kv_k[t][d8]) = *((const device ulong2*)(kbase + (size_t)(jb + t) * D + d8)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); // B1: kv_k ready + + simdgroup_matrix St = simdgroup_matrix(0.0f); + for (int db = 0; db < ND_BLOCKS; db++) { + simdgroup_matrix km; + simdgroup_load(km, &kv_k[sg * 8][db * 8], KV_STRIDE, ulong2(0, 0), true); + simdgroup_multiply_accumulate(St, Qm[db], km, St); + } + const float s0 = St.thread_elements()[0] * scale; + const float s1 = St.thread_elements()[1] * scale; + float mt_loc = max(s0, s1); + mt_loc = max(mt_loc, simd_shuffle_xor(mt_loc, 1)); + mt_loc = max(mt_loc, simd_shuffle_xor(mt_loc, 8)); + if (my_c0 == 0) sm_mt[sg][my_qr] = mt_loc; + threadgroup_barrier(mem_flags::mem_threadgroup); // B2: sm_mt ready, kv_k & prev kv_v idle + + const float mt = max(max(sm_mt[0][my_qr], sm_mt[1][my_qr]), max(sm_mt[2][my_qr], sm_mt[3][my_qr])); + const float mo = m_cur; + const float mn = max(mo, mt); + const float cf = (mo == -INFINITY) ? 0.0f : exp2(mo - mn); + const float p0 = exp2(s0 - mn); + const float p1 = exp2(s1 - mn); + sm_ls[sg][lane] = p0 + p1; + sm_pm[my_qr][sg * 8 + my_c0] = static_cast(p0); + sm_pm[my_qr][sg * 8 + my_c0 + 1] = static_cast(p1); + + for (int v = (int)tid; v < BT * (D / 8); v += NTHREADS) { + const int t = v / (D / 8); + const int d8 = (v % (D / 8)) * 8; + *((threadgroup ulong2*)&kv_v[t][d8]) = *((const device ulong2*)(vbase + (size_t)(jb + t) * D + d8)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); // B3: sm_ls, sm_pm, kv_v ready + + float ls = (((0.0f + sm_ls[0][lane]) + sm_ls[1][lane]) + sm_ls[2][lane]) + sm_ls[3][lane]; + ls = ls + simd_shuffle_xor(ls, 1); + ls = ls + simd_shuffle_xor(ls, 8); + l_cur = l_cur * cf + ls; + m_cur = mn; + + if (jb > j_start) { + O0.thread_elements()[0] *= cf; O0.thread_elements()[1] *= cf; + O1.thread_elements()[0] *= cf; O1.thread_elements()[1] *= cf; + } + const int d_base = (int)sg * 16; + for (int tb = 0; tb < 4; tb++) { + simdgroup_matrix pm, vm0, vm1; + simdgroup_load(pm, &sm_pm[0][tb * 8], 32); + simdgroup_load(vm0, &kv_v[tb * 8][d_base], KV_STRIDE); + simdgroup_load(vm1, &kv_v[tb * 8][d_base + 8], KV_STRIDE); + simdgroup_multiply_accumulate(O0, pm, vm0, O0); + simdgroup_multiply_accumulate(O1, pm, vm1, O1); + } +} + +// Tail blocks crossing L: each row uses its own path anc[gr] with the exact same 8x8 MMA math +if (full_prefix_end < j_end_cap) { + threadgroup_barrier(mem_flags::mem_threadgroup); + const int nr = min(BM, M - r0); + for (int lr = 0; lr < nr; lr++) { + const int gr = r0 + lr; + const int n_r = L + dl[gr]; + const int row_off = lr * 4; + for (int jb = full_prefix_end; jb < j_end_cap; jb += BT) { + if (jb >= n_r) break; + for (int v = (int)tid; v < BT * (D / 8); v += NTHREADS) { + const int t = v / (D / 8); + const int d8 = (v % (D / 8)) * 8; + const int j = jb + t; + if (j < n_r) { + const int slot = (j < L) ? j : (L + anc[(size_t)gr * A + (j - L)]); + *((threadgroup ulong2*)&kv_k[t][d8]) = *((const device ulong2*)(kbase + (size_t)slot * D + d8)); + } else { + *((threadgroup ulong2*)&kv_k[t][d8]) = ulong2(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + simdgroup_matrix St = simdgroup_matrix(0.0f); + for (int db = 0; db < ND_BLOCKS; db++) { + simdgroup_matrix km; + simdgroup_load(km, &kv_k[sg * 8][db * 8], KV_STRIDE, ulong2(0, 0), true); + simdgroup_multiply_accumulate(St, Qm[db], km, St); + } + const bool active_row = (my_qr >= row_off && my_qr < row_off + 4); + const int t0 = jb + (int)sg * 8 + my_c0; + const float s0 = (active_row && t0 < n_r) ? (St.thread_elements()[0] * scale) : -INFINITY; + const float s1 = (active_row && t0 + 1 < n_r) ? (St.thread_elements()[1] * scale) : -INFINITY; + float mt_loc = max(s0, s1); + mt_loc = max(mt_loc, simd_shuffle_xor(mt_loc, 1)); + mt_loc = max(mt_loc, simd_shuffle_xor(mt_loc, 8)); + if (my_c0 == 0) sm_mt[sg][my_qr] = mt_loc; + threadgroup_barrier(mem_flags::mem_threadgroup); + + float cf_tail = 1.0f; + if (active_row) { + const float mt = max(max(sm_mt[0][my_qr], sm_mt[1][my_qr]), max(sm_mt[2][my_qr], sm_mt[3][my_qr])); + const float mo = m_cur; + const float mn = max(mo, mt); + cf_tail = (mo == -INFINITY) ? 0.0f : exp2(mo - mn); + const float p0 = (t0 < n_r) ? exp2(s0 - mn) : 0.0f; + const float p1 = (t0 + 1 < n_r) ? exp2(s1 - mn) : 0.0f; + sm_ls[sg][lane] = p0 + p1; + sm_pm[my_qr][sg * 8 + my_c0] = static_cast(p0); + sm_pm[my_qr][sg * 8 + my_c0 + 1] = static_cast(p1); + m_cur = mn; + } else { + sm_ls[sg][lane] = 0.0f; + sm_pm[my_qr][sg * 8 + my_c0] = T(0); + sm_pm[my_qr][sg * 8 + my_c0 + 1] = T(0); + } + for (int v = (int)tid; v < BT * (D / 8); v += NTHREADS) { + const int t = v / (D / 8); + const int d8 = (v % (D / 8)) * 8; + const int j = jb + t; + if (j < n_r) { + const int slot = (j < L) ? j : (L + anc[(size_t)gr * A + (j - L)]); + *((threadgroup ulong2*)&kv_v[t][d8]) = *((const device ulong2*)(vbase + (size_t)slot * D + d8)); + } else { + *((threadgroup ulong2*)&kv_v[t][d8]) = ulong2(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (active_row) { + float ls = (((0.0f + sm_ls[0][lane]) + sm_ls[1][lane]) + sm_ls[2][lane]) + sm_ls[3][lane]; + ls = ls + simd_shuffle_xor(ls, 1); + ls = ls + simd_shuffle_xor(ls, 8); + l_cur = l_cur * cf_tail + ls; + } + O0.thread_elements()[0] *= cf_tail; O0.thread_elements()[1] *= cf_tail; + O1.thread_elements()[0] *= cf_tail; O1.thread_elements()[1] *= cf_tail; + const int d_base = (int)sg * 16; + for (int tb = 0; tb < 4; tb++) { + simdgroup_matrix pm, vm0, vm1; + simdgroup_load(pm, &sm_pm[0][tb * 8], 32); + simdgroup_load(vm0, &kv_v[tb * 8][d_base], KV_STRIDE); + simdgroup_load(vm1, &kv_v[tb * 8][d_base + 8], KV_STRIDE); + simdgroup_multiply_accumulate(O0, pm, vm0, O0); + simdgroup_multiply_accumulate(O1, pm, vm1, O1); + } + } + } +} + +const int gr = r0 + (my_qr / GQA); +const int gh = (int)hk * GQA + (my_qr % GQA); +if (gr < M) { + const int d_base = (int)sg * 16; +#if SINGLE_CHUNK + const float invl = 1.0f / l_cur; + device T* op = o + ((size_t)gr * Hq + gh) * D + d_base + my_c0; + op[0] = static_cast(O0.thread_elements()[0] * invl); + op[1] = static_cast(O0.thread_elements()[1] * invl); + op[8] = static_cast(O1.thread_elements()[0] * invl); + op[9] = static_cast(O1.thread_elements()[1] * invl); +#else + const size_t base = ((size_t)gr * Hq + gh) * nchunks + ch; + if (sg == 0 && my_c0 == 0) { + pm[base] = m_cur; + pl[base] = l_cur; + } + device float* pap = pa + base * D + d_base + my_c0; + pap[0] = O0.thread_elements()[0]; + pap[1] = O0.thread_elements()[1]; + pap[8] = O1.thread_elements()[0]; + pap[9] = O1.thread_elements()[1]; +#endif +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_reduce.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_reduce.metal new file mode 100644 index 000000000..39abe5afa --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/pathattn_reduce.metal @@ -0,0 +1,25 @@ +// Stage 2 of Split-K pathattn_flash: combines chunks 0..nc-1 in exact logical order for each (row, head). +const uint h = threadgroup_position_in_grid.x; +const uint r = threadgroup_position_in_grid.y; +const uint lane = thread_index_in_simdgroup; +const int Hq = pm_shape[1]; +const int nchunks = pm_shape[2]; +const int n = lb[0] + dl[r]; +const int nc = (n + BK - 1) / BK; +const int d0 = (int)lane * 2; +const size_t base = ((size_t)r * Hq + h) * nchunks; + +float Mx = -INFINITY; +for (int c = 0; c < nc; c++) Mx = max(Mx, pm[base + c]); +float L2 = 0.0f, A0 = 0.0f, A1 = 0.0f; +for (int c = 0; c < nc; c++) { + const float mc = pm[base + c]; + const float wg = (mc == -INFINITY) ? 0.0f : exp2(mc - Mx); + L2 += pl[base + c] * wg; + A0 += pa[(base + c) * D + d0] * wg; + A1 += pa[(base + c) * D + d0 + 1] * wg; +} +const float invl = 1.0f / L2; +device T* op = o + ((size_t)r * Hq + h) * D + d0; +op[0] = static_cast(A0 * invl); +op[1] = static_cast(A1 * invl); diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/qkv_rope.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/qkv_rope.metal new file mode 100644 index 000000000..cf3671d7e --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/qkv_rope.metal @@ -0,0 +1,65 @@ +// Fused Q/K per-head RMSNorm + RoPE + K/V transpose for attention layers. +// Inputs: qkv [M, (Hq + 2*Hk) * D], qn [D], kn [D], cos [M, D], sin [M, D], eps [1] +// Outputs: q_out [M, Hq, D], k_out [Hk, M, D], v_out [Hk, M, D] +// Grid: ((Hq + 2*Hk) * 32, M, 1), Threadgroup: (32, 1, 1). Works for any even D <= 64 (each lane handles d and d + D/2). +const int blk = (int)threadgroup_position_in_grid.x; +const int m = (int)threadgroup_position_in_grid.y; +const int lane = (int)thread_index_in_simdgroup; +const int M = qkv_shape[0]; +const int halfD = D / 2; +const int qkv_stride = (Hq + 2 * Hk) * D; +const device T* row = qkv + (size_t)m * qkv_stride; + +if (blk < Hq) { + // Query head h = blk: RMSNorm + RoPE -> q_out[m, h, d] + const device T* qp = row + (size_t)blk * D; + float x0 = 0.0f, x1 = 0.0f; + if (lane < halfD) { + x0 = float(qp[lane]); + x1 = float(qp[lane + halfD]); + } + const float ss = simd_sum(x0 * x0 + x1 * x1); + const float inv = rsqrt(ss / (float)D + eps[0]); + if (lane < halfD) { + const float n0 = float(static_cast(x0 * inv * float(qn[lane]))); + const float n1 = float(static_cast(x1 * inv * float(qn[lane + halfD]))); + const float c0 = float(cos[(size_t)m * D + lane]); + const float s0 = float(sin[(size_t)m * D + lane]); + const float c1 = float(cos[(size_t)m * D + lane + halfD]); + const float s1 = float(sin[(size_t)m * D + lane + halfD]); + device T* op = q_out + ((size_t)m * Hq + blk) * D; + op[lane] = static_cast(float(static_cast(n0 * c0)) + float(static_cast((-n1) * s0))); + op[lane + halfD] = static_cast(float(static_cast(n1 * c1)) + float(static_cast(n0 * s1))); + } +} else if (blk < Hq + Hk) { + // Key head hk = blk - Hq: RMSNorm + RoPE + transpose -> k_out[hk, m, d] + const int hk = blk - Hq; + const device T* kp = row + (size_t)(Hq + hk) * D; + float x0 = 0.0f, x1 = 0.0f; + if (lane < halfD) { + x0 = float(kp[lane]); + x1 = float(kp[lane + halfD]); + } + const float ss = simd_sum(x0 * x0 + x1 * x1); + const float inv = rsqrt(ss / (float)D + eps[0]); + if (lane < halfD) { + const float n0 = float(static_cast(x0 * inv * float(kn[lane]))); + const float n1 = float(static_cast(x1 * inv * float(kn[lane + halfD]))); + const float c0 = float(cos[(size_t)m * D + lane]); + const float s0 = float(sin[(size_t)m * D + lane]); + const float c1 = float(cos[(size_t)m * D + lane + halfD]); + const float s1 = float(sin[(size_t)m * D + lane + halfD]); + device T* op = k_out + ((size_t)hk * M + m) * D; + op[lane] = static_cast(float(static_cast(n0 * c0)) + float(static_cast((-n1) * s0))); + op[lane + halfD] = static_cast(float(static_cast(n1 * c1)) + float(static_cast(n0 * s1))); + } +} else { + // Value head hk = blk - Hq - Hk: transpose -> v_out[hk, m, d] + const int hk = blk - Hq - Hk; + if (lane < halfD) { + const device T* vp = row + (size_t)(Hq + Hk + hk) * D; + device T* op = v_out + ((size_t)hk * M + m) * D; + op[lane] = vp[lane]; + op[lane + halfD] = vp[lane + halfD]; + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/rowchain.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/rowchain.metal new file mode 100644 index 000000000..e48e7c138 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/rowchain.metal @@ -0,0 +1,97 @@ +// Row-invariant dense projection, the scalar twin of rowmma.metal (engine/models/lfm2_moe/mlx_kernels.py `dense`). +// y[m, n] = sum_k x[m, k] w[n, k] (+ res[m, n] when ADD_RES == 1). +// A thread is (TN output columns, one of the KS K-splits, R rows); a threadgroup is TG / KS column groups x KS splits. +// Split s takes [s BK, (s + 1) BK) of each KS BK step of K, as rowmma's does, and sums it in one sequential chain of +// fused multiply-adds from 0, k ascending; the KS adjacent lanes in the same simdgroup reduce in split order via +// simd_shuffle_down (zero threadgroup memory, zero barriers). Loads x once per 8-wide step and streams w per column +// to keep register pressure minimal. K is a multiple of KS BK and BK of 8 (`dense` checks). +const uint tid = thread_position_in_threadgroup.x; +const int M = x_shape[0]; +const int s = (int)tid % KS; +const int cgi = (int)tid / KS; +const int nb = (int)threadgroup_position_in_grid.x * (TG / KS) * TN; +const int n0 = nb + cgi * TN; +const int m0 = (int)threadgroup_position_in_grid.y * R; +float acc[R][TN]; +for (int r = 0; r < R; r++) for (int c = 0; c < TN; c++) acc[r][c] = 0.0f; +const device T* wb = w + (size_t)min(n0, N - 1) * K; +if (n0 < N) { + for (int k0 = s * BK; k0 < K; k0 += KS * BK) { + for (int kk = 0; kk < BK; kk += 8) { + const int k = k0 + kk; + if (R == 1) { + const device vec* xv = (const device vec*)(x + (size_t)m0 * K + k); + const vec xa = xv[0], xb = xv[1]; + const float x0 = float(xa[0]), x1 = float(xa[1]), x2 = float(xa[2]), x3 = float(xa[3]); + const float x4 = float(xb[0]), x5 = float(xb[1]), x6 = float(xb[2]), x7 = float(xb[3]); + for (int c = 0; c < TN; c++) { + const device vec* wv = (const device vec*)(wb + (size_t)(n0 + c < N ? c : 0) * K + k); + const vec wa = wv[0], wb4 = wv[1]; + float t = acc[0][c]; + t = fma(x0, float(wa[0]), t); t = fma(x1, float(wa[1]), t); + t = fma(x2, float(wa[2]), t); t = fma(x3, float(wa[3]), t); + t = fma(x4, float(wb4[0]), t); t = fma(x5, float(wb4[1]), t); + t = fma(x6, float(wb4[2]), t); t = fma(x7, float(wb4[3]), t); + acc[0][c] = t; + } + } else { + float xv[R][8]; + for (int r = 0; r < R; r++) { + if (m0 + r < M) { + const device vec* xp = (const device vec*)(x + (size_t)(m0 + r) * K + k); + const vec xa = xp[0], xb = xp[1]; + xv[r][0] = float(xa[0]); xv[r][1] = float(xa[1]); xv[r][2] = float(xa[2]); xv[r][3] = float(xa[3]); + xv[r][4] = float(xb[0]); xv[r][5] = float(xb[1]); xv[r][6] = float(xb[2]); xv[r][7] = float(xb[3]); + } + } + for (int c = 0; c < TN; c++) { + const device vec* wv = (const device vec*)(wb + (size_t)(n0 + c < N ? c : 0) * K + k); + const vec wa = wv[0], wb4 = wv[1]; + const float w0 = float(wa[0]), w1 = float(wa[1]), w2 = float(wa[2]), w3 = float(wa[3]); + const float w4 = float(wb4[0]), w5 = float(wb4[1]), w6 = float(wb4[2]), w7 = float(wb4[3]); + for (int r = 0; r < R; r++) { + if (m0 + r < M) { + float t = acc[r][c]; + t = fma(xv[r][0], w0, t); t = fma(xv[r][1], w1, t); + t = fma(xv[r][2], w2, t); t = fma(xv[r][3], w3, t); + t = fma(xv[r][4], w4, t); t = fma(xv[r][5], w5, t); + t = fma(xv[r][6], w6, t); t = fma(xv[r][7], w7, t); + acc[r][c] = t; + } + } + } + } + } + } +} +// Exact ordered reduction across KS adjacent lanes in the same simdgroup (KS in {1, 2, 4, 8}) +for (int r = 0; r < R; r++) { + for (int c = 0; c < TN; c++) { + float t = acc[r][c]; + if (KS == 2) { + t = t + simd_shuffle_down(t, 1); + } else if (KS == 4) { + const float s1 = simd_shuffle_down(t, 1); + const float s2 = simd_shuffle_down(t, 2); + const float s3 = simd_shuffle_down(t, 3); + t = ((t + s1) + s2) + s3; + } else if (KS == 8) { + const float s1 = simd_shuffle_down(t, 1); + const float s2 = simd_shuffle_down(t, 2); + const float s3 = simd_shuffle_down(t, 3); + const float s4 = simd_shuffle_down(t, 4); + const float s5 = simd_shuffle_down(t, 5); + const float s6 = simd_shuffle_down(t, 6); + const float s7 = simd_shuffle_down(t, 7); + t = ((((((t + s1) + s2) + s3) + s4) + s5) + s6) + s7; + } + if (s == 0 && m0 + r < M && n0 + c < N) { + const size_t idx = (size_t)(m0 + r) * N + n0 + c; +#if ADD_RES + y[idx] = static_cast(float(res[idx]) + float(static_cast(t))); +#else + y[idx] = static_cast(static_cast(t)); +#endif + } + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/rowchain_swiz.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/rowchain_swiz.metal new file mode 100644 index 000000000..6a8bd68ea --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/rowchain_swiz.metal @@ -0,0 +1,131 @@ +// 512B-coalesced swizzled scalar dense projection (M <= 2), bit-for-bit twin of rowmma_swiz.metal. +// Weight layout w_swiz: [N // 16, K // 64, B8=2, TN=2, cg_sg=8, KS=4, 8] (BK=16, KS=4, TN=2 -> N_SG=16). +// Issues 4 upfront 16-byte ulong2 loads (2 KB contiguous per simdgroup) per KSTEP=64. +// Supports optional on-the-fly 32-lane simd_sum RMSNorm (FUSE_RMS) and fused residual add (ADD_RES). +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; +const int M = x_shape[0]; +const int m0 = (int)threadgroup_position_in_grid.y * R; +const int s = (int)(lane & 3); +const int cgi_sg = (int)(lane >> 2); +constexpr int N_SG = 16; // (32 / 4) * 2 +const int sg_id = (int)threadgroup_position_in_grid.x * (TG / 32) + (int)sg; +const int n0 = sg_id * N_SG + cgi_sg * 2; +if (sg_id * N_SG >= N) return; + +#if FUSE_RMS +float inv_r[R]; +for (int r = 0; r < R; r++) { + float ss_loc = 0.0f; + if (m0 + r < M) { + const device T* xr = x + (size_t)(m0 + r) * K; + for (int k = (int)lane * 8; k < K; k += 256) { + const ulong2 xraw = *((const device ulong2*)(xr + k)); + const vec ha = as_type>(xraw.x), hb = as_type>(xraw.y); + ss_loc = fma(float(ha[0]), float(ha[0]), ss_loc); ss_loc = fma(float(ha[1]), float(ha[1]), ss_loc); + ss_loc = fma(float(ha[2]), float(ha[2]), ss_loc); ss_loc = fma(float(ha[3]), float(ha[3]), ss_loc); + ss_loc = fma(float(hb[0]), float(hb[0]), ss_loc); ss_loc = fma(float(hb[1]), float(hb[1]), ss_loc); + ss_loc = fma(float(hb[2]), float(hb[2]), ss_loc); ss_loc = fma(float(hb[3]), float(hb[3]), ss_loc); + } + } + inv_r[r] = rsqrt(simd_sum(ss_loc) / (float)K + eps[0]); +} +#endif + +float acc[R][2]; +for (int r = 0; r < R; r++) { acc[r][0] = 0.0f; acc[r][1] = 0.0f; } + +constexpr int KSTEPS = K / 64; +const device ulong2* wbase = (const device ulong2*)w_swiz + (size_t)sg_id * KSTEPS * 128; + +for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * 64 + s * 16; + const device ulong2* wp = wbase + ks_i * 128 + lane; + const ulong2 w00 = wp[0]; + const ulong2 w01 = wp[32]; + const ulong2 w10 = wp[64]; + const ulong2 w11 = wp[96]; +#if FUSE_RMS + const device ulong2* nwp = (const device ulong2*)(nw + k0); + const ulong2 nr0 = nwp[0], nr1 = nwp[1]; + const vec n0a = as_type>(nr0.x), n0b = as_type>(nr0.y); + const vec n1a = as_type>(nr1.x), n1b = as_type>(nr1.y); +#endif + for (int r = 0; r < R; r++) { + if (m0 + r < M) { + const device ulong2* xp = (const device ulong2*)(x + (size_t)(m0 + r) * K + k0); + const ulong2 xr0 = xp[0], xr1 = xp[1]; + const vec x0a = as_type>(xr0.x), x0b = as_type>(xr0.y); + const vec x1a = as_type>(xr1.x), x1b = as_type>(xr1.y); +#if FUSE_RMS + const float inv = inv_r[r]; + const float a0 = float(static_cast(float(x0a[0]) * inv * float(n0a[0]))); + const float a1 = float(static_cast(float(x0a[1]) * inv * float(n0a[1]))); + const float a2 = float(static_cast(float(x0a[2]) * inv * float(n0a[2]))); + const float a3 = float(static_cast(float(x0a[3]) * inv * float(n0a[3]))); + const float a4 = float(static_cast(float(x0b[0]) * inv * float(n0b[0]))); + const float a5 = float(static_cast(float(x0b[1]) * inv * float(n0b[1]))); + const float a6 = float(static_cast(float(x0b[2]) * inv * float(n0b[2]))); + const float a7 = float(static_cast(float(x0b[3]) * inv * float(n0b[3]))); + const float b0 = float(static_cast(float(x1a[0]) * inv * float(n1a[0]))); + const float b1 = float(static_cast(float(x1a[1]) * inv * float(n1a[1]))); + const float b2 = float(static_cast(float(x1a[2]) * inv * float(n1a[2]))); + const float b3 = float(static_cast(float(x1a[3]) * inv * float(n1a[3]))); + const float b4 = float(static_cast(float(x1b[0]) * inv * float(n1b[0]))); + const float b5 = float(static_cast(float(x1b[1]) * inv * float(n1b[1]))); + const float b6 = float(static_cast(float(x1b[2]) * inv * float(n1b[2]))); + const float b7 = float(static_cast(float(x1b[3]) * inv * float(n1b[3]))); +#else + const float a0 = float(x0a[0]), a1 = float(x0a[1]), a2 = float(x0a[2]), a3 = float(x0a[3]); + const float a4 = float(x0b[0]), a5 = float(x0b[1]), a6 = float(x0b[2]), a7 = float(x0b[3]); + const float b0 = float(x1a[0]), b1 = float(x1a[1]), b2 = float(x1a[2]), b3 = float(x1a[3]); + const float b4 = float(x1b[0]), b5 = float(x1b[1]), b6 = float(x1b[2]), b7 = float(x1b[3]); +#endif + float t0 = acc[r][0], t1 = acc[r][1]; + { + const vec wa = as_type>(w00.x), wb = as_type>(w00.y); + t0 = fma(a0, float(wa[0]), t0); t0 = fma(a1, float(wa[1]), t0); + t0 = fma(a2, float(wa[2]), t0); t0 = fma(a3, float(wa[3]), t0); + t0 = fma(a4, float(wb[0]), t0); t0 = fma(a5, float(wb[1]), t0); + t0 = fma(a6, float(wb[2]), t0); t0 = fma(a7, float(wb[3]), t0); + } + { + const vec wa = as_type>(w01.x), wb = as_type>(w01.y); + t1 = fma(a0, float(wa[0]), t1); t1 = fma(a1, float(wa[1]), t1); + t1 = fma(a2, float(wa[2]), t1); t1 = fma(a3, float(wa[3]), t1); + t1 = fma(a4, float(wb[0]), t1); t1 = fma(a5, float(wb[1]), t1); + t1 = fma(a6, float(wb[2]), t1); t1 = fma(a7, float(wb[3]), t1); + } + { + const vec wa = as_type>(w10.x), wb = as_type>(w10.y); + t0 = fma(b0, float(wa[0]), t0); t0 = fma(b1, float(wa[1]), t0); + t0 = fma(b2, float(wa[2]), t0); t0 = fma(b3, float(wa[3]), t0); + t0 = fma(b4, float(wb[0]), t0); t0 = fma(b5, float(wb[1]), t0); + t0 = fma(b6, float(wb[2]), t0); t0 = fma(b7, float(wb[3]), t0); + } + { + const vec wa = as_type>(w11.x), wb = as_type>(w11.y); + t1 = fma(b0, float(wa[0]), t1); t1 = fma(b1, float(wa[1]), t1); + t1 = fma(b2, float(wa[2]), t1); t1 = fma(b3, float(wa[3]), t1); + t1 = fma(b4, float(wb[0]), t1); t1 = fma(b5, float(wb[1]), t1); + t1 = fma(b6, float(wb[2]), t1); t1 = fma(b7, float(wb[3]), t1); + } + acc[r][0] = t0; acc[r][1] = t1; + } + } +} + +for (int r = 0; r < R; r++) { + for (int c = 0; c < 2; c++) { + float t = acc[r][c]; + t = ((t + simd_shuffle_down(t, 1)) + simd_shuffle_down(t, 2)) + simd_shuffle_down(t, 3); + if (s == 0 && m0 + r < M && n0 + c < N) { + const size_t idx = (size_t)(m0 + r) * N + n0 + c; +#if ADD_RES + y[idx] = static_cast(float(res[idx]) + float(static_cast(t))); +#else + y[idx] = static_cast(static_cast(t)); +#endif + } + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/rowmm.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/rowmm.metal new file mode 100644 index 000000000..31eae7c26 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/rowmm.metal @@ -0,0 +1,115 @@ +// Row-invariant y[p, n] = sum_k x[prow[p], k] * w[pexp[p], n, k] (engine/models/lfm2_moe/mlx_kernels.py) +// General fallback for shapes not served by rowchain/rowmma or moemm (tiny test shapes, non-aligned K, etc.). +const int e = elist[threadgroup_position_in_grid.y]; +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; +const uint tid = thread_position_in_threadgroup.x; +const int split = (int)sg % KS; +const int cg = (int)sg / KS; +const int P = prow_shape[0]; +threadgroup int sel[MAXP]; +threadgroup int nsel; +threadgroup T xs[KS][R > 1 ? R : 1][R > 1 ? 256 : 4]; +threadgroup float part[KS > 1 ? KS : 1][KS > 1 ? R : 1][KS > 1 ? (TN * (4 / KS)) : 1]; +if (e < 0) return; +if (tid == 0) { + int c = 0; + for (int p = 0; p < P; p++) { + if (pexp[p] == e) { sel[c] = p; c++; } + } + nsel = c; +} +threadgroup_barrier(mem_flags::mem_threadgroup); +const int ns = nsel; +const int n0 = ((int)threadgroup_position_in_grid.x * (4 / KS) + cg) * TN; +const device T* wb = w + ((size_t)e * N + (size_t)min(n0, N - 1)) * K; +const int nchunk = (K + 255) / 256; +for (int c0 = 0; c0 < ns; c0 += R) { + const int nr = min(R, ns - c0); + float acc[R][TN]; + for (int r = 0; r < R; r++) for (int c = 0; c < TN; c++) acc[r][c] = 0.0f; + for (int ch0 = 0; ch0 < nchunk; ch0 += KS) { + if (R > 1) { + for (int v = (int)tid; v < KS * R * 64; v += 128) { + const int s = v / (R * 64), r = (v / 64) % R, kk = (v % 64) * 4; + const int kb = (ch0 + s) * 256 + kk; + vec xv4 = vec(0); + if (r < nr && kb < K) { + const device T* xr = x + (size_t)prow[sel[c0 + r]] * K + kb; + if (kb + 4 <= K) { + xv4 = *((const device vec*)xr); + } else { + for (int i = 0; i < 4; i++) xv4[i] = (kb + i < K) ? xr[i] : T(0); + } + } + *((threadgroup vec*)&xs[s][r][kk]) = xv4; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const int k = (ch0 + split) * 256 + (int)lane * 8; + if (n0 < N && ch0 + split < nchunk) { + float wv[TN][8]; + for (int c = 0; c < TN; c++) { + const device T* wp = wb + (size_t)c * K + k; + if (n0 + c < N && k + 8 <= K) { + const vec a = *((const device vec*)wp); + const vec b = *((const device vec*)(wp + 4)); + for (int i = 0; i < 4; i++) { wv[c][i] = float(a[i]); wv[c][4 + i] = float(b[i]); } + } else { + for (int i = 0; i < 8; i++) wv[c][i] = (n0 + c < N && k + i < K) ? float(wp[i]) : 0.0f; + } + } + for (int r = 0; r < R; r++) { + if (r < nr) { + float xv[8]; + if (R > 1) { + for (int i = 0; i < 8; i++) xv[i] = float(xs[split][r][lane * 8 + i]); + } else { + const device T* xr = x + (size_t)prow[sel[c0 + r]] * K + k; + if (k + 8 <= K) { + const vec a = *((const device vec*)xr); + const vec b = *((const device vec*)(xr + 4)); + for (int i = 0; i < 4; i++) { xv[i] = float(a[i]); xv[4 + i] = float(b[i]); } + } else { + for (int i = 0; i < 8; i++) xv[i] = (k + i < K) ? float(xr[i]) : 0.0f; + } + } + for (int c = 0; c < TN; c++) { + float s = acc[r][c]; + for (int i = 0; i < 8; i++) s = fma(xv[i], wv[c][i], s); + acc[r][c] = s; + } + } + } + } + if (R > 1) threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (KS == 1) { + for (int r = 0; r < nr; r++) { + for (int c = 0; c < TN; c++) { + const float s = simd_sum(acc[r][c]); + if (lane == 0 && n0 + c < N) { + y[(size_t)sel[c0 + r] * N + n0 + c] = static_cast(s); + } + } + } + } else { + for (int r = 0; r < nr; r++) { + for (int c = 0; c < TN; c++) { + const float s = simd_sum(acc[r][c]); + if (lane == 0) part[split][r][cg * TN + c] = s; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int v = (int)tid; v < nr * TN * (4 / KS); v += 128) { + const int r = v / (TN * (4 / KS)), col = v % (TN * (4 / KS)); + const int n = (int)threadgroup_position_in_grid.x * (4 / KS) * TN + col; + if (n < N) { + float s = part[0][r][col]; + for (int sp = 1; sp < KS; sp++) s += part[sp][r][col]; + y[(size_t)sel[c0 + r] * N + n] = static_cast(s); + } + } + if (c0 + R < ns) threadgroup_barrier(mem_flags::mem_threadgroup); + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/rowmma.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/rowmma.metal new file mode 100644 index 000000000..5048a5cdd --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/rowmma.metal @@ -0,0 +1,103 @@ +// Row-invariant dense projection on the 8x8 matrix units (engine/models/lfm2_moe/mlx_kernels.py `dense`). +// Its scalar twin for few rows is rowchain.metal: the same sums, bit for bit. +// y[m, n] = sum_k x[m, k] w[n, k] (+ res[m, n] when ADD_RES == 1). +// Uses simdgroup_matrix (bfloat inputs -> float accumulator, measured bit-for-bit identical to +// rowchain on M5 Max), coalesced 16-byte bfloat staging into union-aliased threadgroup memory, and FM 8-row +// tiles per threadgroup (FM=1 for M<=8, FM=2 for M>8 so weights are read once for up to 16 rows). +const uint sg = simdgroup_index_in_threadgroup; +const uint tid = thread_position_in_threadgroup.x; +const int CG = 4 / KS; +const int split = (int)sg % KS; +const int cg = (int)sg / KS; +const int M = x_shape[0]; +const int m0 = (int)threadgroup_position_in_grid.y * (FM * 8); +const int nb = (int)threadgroup_position_in_grid.x * (CG * FN * 8); + +constexpr int KSTEP = KS * BK; +constexpr int NC = CG * FN * 8; +constexpr int MR = FM * 8; +constexpr int STRIDE = KSTEP + 8; +constexpr int KVECS = KSTEP / 8; + +struct StageMem { + T xs[MR][STRIDE]; + T ws[NC][STRIDE]; +}; +struct EpiMem { + float os[KS][MR][NC]; +}; +union ShMem { + StageMem st; + EpiMem ep; +}; +threadgroup ShMem sm; + +simdgroup_matrix acc[FM][FN]; +for (int fm = 0; fm < FM; fm++) + for (int f = 0; f < FN; f++) + acc[fm][f] = simdgroup_matrix(0.0f); + +for (int k0 = 0; k0 < K; k0 += KSTEP) { + for (int v = (int)tid; v < MR * KVECS; v += 128) { + const int r = v / KVECS; + const int kk = (v % KVECS) * 8; + if (m0 + r < M) { + const device vec* xp = (const device vec*)(x + (size_t)(m0 + r) * K + k0 + kk); + *((threadgroup vec*)&sm.st.xs[r][kk]) = xp[0]; + *((threadgroup vec*)&sm.st.xs[r][kk + 4]) = xp[1]; + } else { + *((threadgroup vec*)&sm.st.xs[r][kk]) = vec(0); + *((threadgroup vec*)&sm.st.xs[r][kk + 4]) = vec(0); + } + } + for (int v = (int)tid; v < NC * KVECS; v += 128) { + const int c = v / KVECS; + const int kk = (v % KVECS) * 8; + const int n = nb + c; + if (n < N) { + const device vec* wp = (const device vec*)(w + (size_t)n * K + k0 + kk); + *((threadgroup vec*)&sm.st.ws[c][kk]) = wp[0]; + *((threadgroup vec*)&sm.st.ws[c][kk + 4]) = wp[1]; + } else { + *((threadgroup vec*)&sm.st.ws[c][kk]) = vec(0); + *((threadgroup vec*)&sm.st.ws[c][kk + 4]) = vec(0); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int kk = split * BK; kk < (split + 1) * BK; kk += 8) { + simdgroup_matrix a[FM]; + for (int fm = 0; fm < FM; fm++) { + simdgroup_load(a[fm], &sm.st.xs[fm * 8][kk], STRIDE); + } + for (int f = 0; f < FN; f++) { + simdgroup_matrix b; + simdgroup_load(b, &sm.st.ws[(cg * FN + f) * 8][kk], STRIDE, ulong2(0, 0), true); + for (int fm = 0; fm < FM; fm++) { + simdgroup_multiply_accumulate(acc[fm][f], a[fm], b, acc[fm][f]); + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +for (int fm = 0; fm < FM; fm++) { + for (int f = 0; f < FN; f++) { + simdgroup_store(acc[fm][f], &sm.ep.os[split][fm * 8][(cg * FN + f) * 8], NC); + } +} +threadgroup_barrier(mem_flags::mem_threadgroup); +for (int v = (int)tid; v < MR * NC; v += 128) { + const int r = v / NC; + const int c = v % NC; + const int n = nb + c; + if (m0 + r < M && n < N) { + float s = sm.ep.os[0][r][c]; + for (int sp = 1; sp < KS; sp++) s += sm.ep.os[sp][r][c]; + const size_t idx = (size_t)(m0 + r) * N + n; +#if ADD_RES + y[idx] = static_cast(float(res[idx]) + float(static_cast(s))); +#else + y[idx] = static_cast(static_cast(s)); +#endif + } +} diff --git a/engine/models/lfm2_moe/csrc/mlx_kernels/rowmma_swiz.metal b/engine/models/lfm2_moe/csrc/mlx_kernels/rowmma_swiz.metal new file mode 100644 index 000000000..36ec86873 --- /dev/null +++ b/engine/models/lfm2_moe/csrc/mlx_kernels/rowmma_swiz.metal @@ -0,0 +1,133 @@ +// 512B-coalesced swizzled 8x8 bfloat simdgroup_matrix dense projection (M >= 3), +// bit-for-bit twin of rowchain_swiz.metal on the exact same w_swiz buffer (BK=16, KS=4, FN=2 -> N_TILE=16). +// Each thread loads ONE 16-byte ulong2 from w_swiz per KSTEP=64. Supports FUSE_RMS and ADD_RES. +const uint sg = simdgroup_index_in_threadgroup; +const uint lane = thread_index_in_simdgroup; +const uint tid = thread_position_in_threadgroup.x; +const int split = (int)sg; +const int M = x_shape[0]; +const int m0 = (int)threadgroup_position_in_grid.y * (FM * 8); +const int tile_n = (int)threadgroup_position_in_grid.x; +const int nb = tile_n * 16; + +constexpr int KSTEP = 64; +constexpr int NC = 16; +constexpr int MR = FM * 8; +constexpr int STRIDE = KSTEP + 8; +constexpr int KSTEPS = K / KSTEP; + +struct StageMem { + T xs[MR][STRIDE]; + T ws[NC][STRIDE]; +}; +struct EpiMem { + float os[4][MR][NC]; +}; +union ShMem { + StageMem st; + EpiMem ep; +}; +threadgroup ShMem sm; + +#if FUSE_RMS +// Compute exact same 32-lane simd_sum RMSNorm inv per row as rowchain_swiz.metal! +threadgroup float inv_tg[MR]; +for (int r = (int)sg; r < MR; r += 4) { + float ss_loc = 0.0f; + if (m0 + r < M) { + const device T* xr = x + (size_t)(m0 + r) * K; + for (int k = (int)lane * 8; k < K; k += 256) { + const ulong2 xraw = *((const device ulong2*)(xr + k)); + const vec ha = as_type>(xraw.x), hb = as_type>(xraw.y); + ss_loc = fma(float(ha[0]), float(ha[0]), ss_loc); ss_loc = fma(float(ha[1]), float(ha[1]), ss_loc); + ss_loc = fma(float(ha[2]), float(ha[2]), ss_loc); ss_loc = fma(float(ha[3]), float(ha[3]), ss_loc); + ss_loc = fma(float(hb[0]), float(hb[0]), ss_loc); ss_loc = fma(float(hb[1]), float(hb[1]), ss_loc); + ss_loc = fma(float(hb[2]), float(hb[2]), ss_loc); ss_loc = fma(float(hb[3]), float(hb[3]), ss_loc); + } + } + const float inv = rsqrt(simd_sum(ss_loc) / (float)K + eps[0]); + if (lane == 0) inv_tg[r] = inv; +} +threadgroup_barrier(mem_flags::mem_threadgroup); +#endif + +simdgroup_matrix acc[FM][2]; +for (int fm = 0; fm < FM; fm++) { + acc[fm][0] = simdgroup_matrix(0.0f); + acc[fm][1] = simdgroup_matrix(0.0f); +} + +const int b_i = (int)(tid >> 6); +const int c_i = (int)((tid >> 5) & 1); +const int cg_sg = (int)((tid >> 2) & 7); +const int s_i = (int)(tid & 3); +const int w_row = cg_sg * 2 + c_i; +const int w_kk = s_i * 16 + b_i * 8; + +const device ulong2* wtile = (const device ulong2*)w_swiz + (size_t)tile_n * KSTEPS * 128; + +for (int ks_i = 0; ks_i < KSTEPS; ks_i++) { + const int k0 = ks_i * KSTEP; + for (int v = (int)tid; v < MR * 8; v += 128) { + const int r = v / 8; + const int kk = (v % 8) * 8; + if (m0 + r < M) { +#if FUSE_RMS + const ulong2 xr = *((const device ulong2*)(x + (size_t)(m0 + r) * K + k0 + kk)); + const ulong2 nr = *((const device ulong2*)(nw + k0 + kk)); + const vec xa = as_type>(xr.x), xb = as_type>(xr.y); + const vec na = as_type>(nr.x), nb4 = as_type>(nr.y); + const float inv = inv_tg[r]; + vec oa, ob; + oa[0] = static_cast(float(xa[0]) * inv * float(na[0])); + oa[1] = static_cast(float(xa[1]) * inv * float(na[1])); + oa[2] = static_cast(float(xa[2]) * inv * float(na[2])); + oa[3] = static_cast(float(xa[3]) * inv * float(na[3])); + ob[0] = static_cast(float(xb[0]) * inv * float(nb4[0])); + ob[1] = static_cast(float(xb[1]) * inv * float(nb4[1])); + ob[2] = static_cast(float(xb[2]) * inv * float(nb4[2])); + ob[3] = static_cast(float(xb[3]) * inv * float(nb4[3])); + *((threadgroup vec*)&sm.st.xs[r][kk]) = oa; + *((threadgroup vec*)&sm.st.xs[r][kk + 4]) = ob; +#else + *((threadgroup ulong2*)&sm.st.xs[r][kk]) = *((const device ulong2*)(x + (size_t)(m0 + r) * K + k0 + kk)); +#endif + } else { + *((threadgroup ulong2*)&sm.st.xs[r][kk]) = ulong2(0); + } + } + *((threadgroup ulong2*)&sm.st.ws[w_row][w_kk]) = wtile[ks_i * 128 + tid]; + + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int kk = split * 16; kk < (split + 1) * 16; kk += 8) { + simdgroup_matrix a[FM]; + for (int fm = 0; fm < FM; fm++) simdgroup_load(a[fm], &sm.st.xs[fm * 8][kk], STRIDE); + simdgroup_matrix b0, b1; + simdgroup_load(b0, &sm.st.ws[0][kk], STRIDE, ulong2(0, 0), true); + simdgroup_load(b1, &sm.st.ws[8][kk], STRIDE, ulong2(0, 0), true); + for (int fm = 0; fm < FM; fm++) { + simdgroup_multiply_accumulate(acc[fm][0], a[fm], b0, acc[fm][0]); + simdgroup_multiply_accumulate(acc[fm][1], a[fm], b1, acc[fm][1]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); +} + +for (int fm = 0; fm < FM; fm++) { + simdgroup_store(acc[fm][0], &sm.ep.os[split][fm * 8][0], NC); + simdgroup_store(acc[fm][1], &sm.ep.os[split][fm * 8][8], NC); +} +threadgroup_barrier(mem_flags::mem_threadgroup); +for (int v = (int)tid; v < MR * NC; v += 128) { + const int r = v / NC, c = v % NC; + const int n = nb + c; + if (m0 + r < M && n < N) { + float s = ((sm.ep.os[0][r][c] + sm.ep.os[1][r][c]) + sm.ep.os[2][r][c]) + sm.ep.os[3][r][c]; + const size_t idx = (size_t)(m0 + r) * N + n; +#if ADD_RES + y[idx] = static_cast(float(res[idx]) + float(static_cast(s))); +#else + y[idx] = static_cast(static_cast(s)); +#endif + } +} diff --git a/engine/models/lfm2_moe/dispatch.py b/engine/models/lfm2_moe/dispatch.py new file mode 100644 index 000000000..7ce54288a --- /dev/null +++ b/engine/models/lfm2_moe/dispatch.py @@ -0,0 +1,16 @@ +"""The lfm2_moe family's server builder: the MLX serving where the device's adapter says the models run on +MLX (tools/gpu `backend()`: Apple silicon, mlx_serving.py), the CUDA one elsewhere (serving.py). The CUDA +serving is not imported for a Mac's build beyond its module (mlx_serving.py reads the family's conductor fit +from it, which loads engine.py and kernels.py; they import without Triton and build nothing until used), and +MLX is never imported off Apple silicon.""" + +from __future__ import annotations + + +def serve(a, ctx) -> dict: + from tools import gpu as _gpu + if _gpu.profile().backend() == "mlx": + from engine.models.lfm2_moe import mlx_serving + return mlx_serving.serve(a, ctx) + from engine.models.lfm2_moe import serving + return serving.serve(a, ctx) diff --git a/engine/models/lfm2_moe/mlx_board.py b/engine/models/lfm2_moe/mlx_board.py new file mode 100644 index 000000000..490381131 --- /dev/null +++ b/engine/models/lfm2_moe/mlx_board.py @@ -0,0 +1,660 @@ +"""LFM2 MoE on Apple silicon: the reference forward (ref.py) in MLX, on the Mac's GPU. + +`Lfm2MoeMLX` keeps `Lfm2MoeRef`'s block algebra and API (`new_state`, `rows(tokens, parents, st)`, +`commit(st, path)`, `prefill`, `decode`), so the drafting and verify loop above it is unchanged. Where +the reference loops over rows, this runs a block as one step, on one of two paths (`Geo`): + + row-invariant the decode step and every block of up to mlx_kernels.ROWS_MAX rows (a draft tree in DFS + pre-order): projections and experts on the row kernels of mlx_kernels.py, attention on + `mlx_kernels.path_attention` (each row against the cache and its own path), the short + conv's window gathered by the row's path (`conv_taps`), the rest elementwise. A verified + row is the decode step's row bit for bit, so greedy speculation writes the plain greedy + text, as on the CUDA board (ENG-287) + batched a longer prompt chunk (a chain): batched kernels whose rows are not the row path's bits; + decode and verify both continue from the state it leaves + +The weights are a dict of the reference's canonical names as `mx.array`, plus each MoE layer's experts +stacked as `experts.L.w13` [E, 2 I, H] and `experts.L.w2` [E, H, I] (`from_torch`, `load_checkpoint`); on +the GPU in BF16 they are repacked into the kernels' tile order (`fuse`). + +What is not here yet: quantised weights, EXL3, the KV pool's pages. +""" + +from __future__ import annotations + +import glob +import json +import os +from dataclasses import dataclass, field + +import mlx.core as mx +import numpy as np + +from engine.models.lfm2_moe import mlx_kernels as K +from engine.models.lfm2_moe.ref import chain, tree_paths + + + +@dataclass +class MlxState: + """One sequence: conv state per conv layer [S, H], K and V per attention layer [kv heads, cap, D].""" + cap: int + length: int = 0 + conv: dict = field(default_factory=dict) + k: dict = field(default_factory=dict) + v: dict = field(default_factory=dict) + + def reset_inplace(self) -> None: + self.length = 0 + for li in self.conv: + self.conv[li] = mx.zeros_like(self.conv[li]) + + +@dataclass +class Geo: + """A block's geometry for `_forward`: `inv` the row-invariant path (with each row's conv taps, path, + path length and rotary), else the batched chain path.""" + inv: bool + paths: list + taps: object = None + anc: object = None + dlen: object = None + rope: object = None + + +def conv_taps(paths: list[list[int]], S: int) -> np.ndarray: + """[M, S + 1] indices into concat(state [S rows], block rows [M]) of each row's conv window, oldest + first: the last S + 1 entries of state followed by the block rows on the row's path.""" + M = len(paths) + out = np.empty((M, S + 1), dtype=np.int32) + for i, pa in enumerate(paths): + d = len(pa) + for t in range(S + 1): + j = S - t # steps back from the row itself + pos = S + d - 1 - j # its place in concat(state, path rows) + out[i, t] = S + pa[pos - S] if pos >= S else pos + return out + + +class Lfm2MoeMLX: + def __init__(self, cfg, W: dict, dtype=mx.bfloat16): + self.cfg, self.W, self.dtype = cfg, W, dtype + self._cc = None + self._attn_cc: dict = {} + self.fuse() + D = cfg.head_dim + self.inv_freq = 1.0 / (cfg.rope_theta ** (mx.arange(0, D, 2, dtype=mx.float32) / D)) + self._anc1 = mx.array([[0]], dtype=mx.int32) + self._dlen1 = mx.array([1], dtype=mx.int32) + mx.eval(self.inv_freq, self._anc1, self._dlen1) + self.rec: dict = {} + self._block = None + self.hidden = None + + @staticmethod + def _can_swiz(c, dtype) -> bool: + if dtype != mx.bfloat16: + return False + if mx.default_device().type != mx.DeviceType.gpu: + return False + H, I, E = c.hidden_size, c.moe_intermediate_size, c.num_experts + q_dim = c.num_attention_heads * c.head_dim + qkv_dim = (c.num_attention_heads + 2 * c.num_key_value_heads) * c.head_dim + return (H % 64 == 0 and I % 64 == 0 and E <= 128 and qkv_dim % 16 == 0 and q_dim % 64 == 0 + and c.intermediate_size % 64 == 0 and c.vocab_size % 16 == 0) + + # ------------------------------------------------------------------------ weights in + @classmethod + def from_torch(cls, cfg, W: dict, dtype=mx.float32): + """From the reference's torch dict (tests: the same random weights on both sides).""" + def a(t): + return mx.array(t.detach().float().cpu().numpy()).astype(dtype) + M: dict = {} + for name, t in W.items(): + if ".experts." in name: + continue + M[name] = a(t) if not name.endswith("expert_bias") else mx.array(t.float().numpy()) + for li in cfg.moe_layers: + f = f"layers.{li}.feed_forward.experts." + E = cfg.num_experts + M[f"experts.{li}.w13"] = mx.stack([mx.concatenate([a(W[f + f"{e}.w1.weight"]), a(W[f + f"{e}.w3.weight"])]) + for e in range(E)]) + M[f"experts.{li}.w2"] = mx.stack([a(W[f + f"{e}.w2.weight"]) for e in range(E)]) + return cls(cfg, M, dtype) + + @classmethod + def load_checkpoint(cls, cfg, path: str, dtype=mx.bfloat16, log=print): + """From a HF safetensors checkpoint (LiquidAI/LFM2.5-24B-A2B): per-expert w1/w3/w2 or stacked + gate_up_proj/down_proj, `model.` prefix dropped.""" + raw: dict = {} + for f in sorted(glob.glob(os.path.join(path, "*.safetensors"))): + raw.update(mx.load(f)) + raw = {k[len("model."):] if k.startswith("model.") else k: v for k, v in raw.items()} + M: dict = {} + I = cfg.moe_intermediate_size + swiz = cls._can_swiz(cfg, dtype) + for name, t in raw.items(): + if ".experts." in name: + continue + M[name] = t.astype(mx.float32) if name.endswith("expert_bias") else t.astype(dtype) + for li in cfg.moe_layers: + f = f"layers.{li}.feed_forward.experts." + if f + "gate_up_proj" in raw: + w13 = raw[f + "gate_up_proj"].astype(dtype) + w2 = raw[f + "down_proj"].astype(dtype) + else: + E = cfg.num_experts + w13 = mx.stack([mx.concatenate([raw[f + f"{e}.w1.weight"], raw[f + f"{e}.w3.weight"]]) + for e in range(E)]).astype(dtype) + w2 = mx.stack([raw[f + f"{e}.w2.weight"] for e in range(E)]).astype(dtype) + assert w13.shape[1] == 2 * I + if swiz: + M[f"experts.{li}.w13"] = K.swizzle_moe_w13(w13) + M[f"experts.{li}.w2"] = K.swizzle_moe_w2(w2) + mx.eval(M[f"experts.{li}.w13"], M[f"experts.{li}.w2"]) + else: + M[f"experts.{li}.w13"] = w13 + M[f"experts.{li}.w2"] = w2 + mx.eval(M[f"experts.{li}.w13"], M[f"experts.{li}.w2"]) + for e in range(cfg.num_experts): # free the per-expert copies as we go + for w in ("w1", "w3", "w2"): + raw.pop(f + f"{e}.{w}.weight", None) + raw.pop(f + "gate_up_proj", None) + raw.pop(f + "down_proj", None) + mx.eval(M) + board = cls(cfg, M, dtype) + if log: + log(f"[lfm-mlx] {path}: {sum(v.nbytes for v in board.W.values()) / 1e9:.2f} GB on the GPU") + return board + + def fuse(self) -> None: + """The row-invariant path's stacked weights: an attention layer's q, k, v (`qkv`), a dense MLP's w1, w3 + (`w13`), plus the 512B-coalesced weight swizzle on GPU bf16 models.""" + c = self.cfg + self._swiz = self._can_swiz(c, self.dtype) + for li in range(c.num_hidden_layers): + p = f"layers.{li}." + if c.is_attention(li): + a = p + "self_attn." + qkv = mx.concatenate([self.W[a + f"{x}_proj.weight"] for x in ("q", "k", "v")]) + self.W[a + "qkv"] = K.swizzle_dense(qkv) if self._swiz else qkv + if self._swiz: + self.W[a + "out_proj.weight"] = K.swizzle_dense(self.W[a + "out_proj.weight"]) + if not c.is_moe(li): + f = p + "feed_forward." + w13 = mx.concatenate([self.W[f + "w1.weight"], self.W[f + "w3.weight"]]) + self.W[f + "w13"] = K.swizzle_moe_w13(w13[None]) if self._swiz else w13 + if self._swiz: + self.W[f + "w2.weight"] = K.swizzle_dense(self.W[f + "w2.weight"]) + elif self._swiz and self.W[f"experts.{li}.w13"].ndim == 3: + self.W[f"experts.{li}.w13"] = K.swizzle_moe_w13(self.W[f"experts.{li}.w13"]) + self.W[f"experts.{li}.w2"] = K.swizzle_moe_w2(self.W[f"experts.{li}.w2"]) + mx.eval(self.W[f"experts.{li}.w13"], self.W[f"experts.{li}.w2"]) + if not c.is_attention(li): + cv = p + "conv." + self.W[cv + "conv2d"] = self.W[cv + "conv.weight"].reshape(c.hidden_size, -1) # [H, taps] + if self._swiz: + self.W[cv + "in_proj.weight"] = K.swizzle_dense(self.W[cv + "in_proj.weight"]) + self.W[cv + "out_proj.weight"] = K.swizzle_dense(self.W[cv + "out_proj.weight"]) + if self._swiz: + self.W["embed_tokens.weight"] = K.swizzle_dense(self.W["embed_tokens.weight"]) + if "lm_head.weight" in self.W: + self.W["lm_head.weight"] = K.swizzle_dense(self.W["lm_head.weight"]) + mx.eval(self.W) + + # ------------------------------------------------------------------------ helpers + def head_weight(self): + return self.W.get("lm_head.weight", self.W["embed_tokens.weight"]) + + def rms(self, x, w): + # fused; normalises in fp32 like the reference, but multiplies by w before the cast back + return mx.fast.rms_norm(x, w, self.cfg.rms_norm_eps) + + def rope(self, positions): + f = positions.astype(mx.float32)[:, None] * self.inv_freq[None, :] + emb = mx.concatenate([f, f], axis=-1) + return mx.cos(emb).astype(self.dtype), mx.sin(emb).astype(self.dtype) + + @staticmethod + def rotate_half(x): + h = x.shape[-1] // 2 + return mx.concatenate([-x[..., h:], x[..., :h]], axis=-1) + + def new_state(self, cap: int) -> MlxState: + c = self.cfg + st = MlxState(cap=cap) + for li in range(c.num_hidden_layers): + if c.is_attention(li): + st.k[li] = mx.zeros((c.num_key_value_heads, cap, c.head_dim), dtype=self.dtype) + st.v[li] = mx.zeros_like(st.k[li]) + else: + st.conv[li] = mx.zeros((c.conv_state_len, c.hidden_size), dtype=self.dtype) + return st + + # ------------------------------------------------------------------------ the layers + # The batched path: a prompt chunk of more than ROWS_MAX rows (a chain), on batched kernels and MLX's own + # matmul and attention. Its rows are not the row path's bits; decode and verify both continue from the + # state it leaves. The row-invariant path (the decode step and every verify block) is `_forward_inv`. + def _lin(self, x, w, N: int, Kd: int, out_dtype=None): + if self._swiz: + return K.dense_prefill_swiz(x, w, N, Kd, out_dtype=out_dtype) + out = x @ w.T + return out.astype(out_dtype) if out_dtype is not None and out.dtype != out_dtype else out + + def conv(self, h, li: int, st: MlxState): + c = self.cfg + p = f"layers.{li}.conv." + H = c.hidden_size + bcx = self._lin(h, self.W[p + "in_proj.weight"], 3 * H, H) + B, C, x = bcx[:, :H], bcx[:, H:2 * H], bcx[:, 2 * H:] + bx = B * x + self.rec[li] = bx + wc = self.W[p + "conv.weight"].reshape(H, -1) # [H, K] + src = mx.concatenate([st.conv[li], bx], axis=0) # [S + M, H] + M, Kt = h.shape[0], wc.shape[1] + win = [src[t:t + M] for t in range(Kt)] # a chain: each tap's window is a slice + y = win[0] * wc[:, 0] + for t in range(1, Kt): + y = y + win[t] * wc[:, t] + return self._lin(C * y.astype(h.dtype), self.W[p + "out_proj.weight"], H, H) + + def attention(self, h, li: int, st: MlxState): + c = self.cfg + p = f"layers.{li}.self_attn." + M, D, Hq, Hk = h.shape[0], c.head_dim, c.num_attention_heads, c.num_key_value_heads + L = st.length + q, k, v = (h @ self.W[p + f"{x}_proj.weight"].T for x in ("q", "k", "v")) + q = self.rms(q.reshape(M, Hq, D), self.W[p + "q_layernorm.weight"]) + k = self.rms(k.reshape(M, Hk, D), self.W[p + "k_layernorm.weight"]) + v = v.reshape(M, Hk, D) + q, k = q.transpose(1, 0, 2)[None], k.transpose(1, 0, 2) # [1, Hq, M, D], [Hk, M, D] + q = mx.fast.rope(q, D, traditional=False, base=c.rope_theta, scale=1.0, offset=L) + k = mx.fast.rope(k[None], D, traditional=False, base=c.rope_theta, scale=1.0, offset=L)[0] + st.k[li][:, L:L + M] = k + st.v[li][:, L:L + M] = v.transpose(1, 0, 2) + ks, vs = st.k[li][None, :, :L + M], st.v[li][None, :, :L + M] # [1, Hk, L + M, D] + o = mx.fast.scaled_dot_product_attention(q, ks, vs, scale=D ** -0.5, mask="causal" if M > 1 else None) + return self._lin(o[0].transpose(1, 0, 2).reshape(M, Hq * D), self.W[p + "out_proj.weight"], + c.hidden_size, Hq * D) + + def mlp(self, h, li: int): + c = self.cfg + p = f"layers.{li}.feed_forward." + a, b = h @ self.W[p + "w1.weight"].T, h @ self.W[p + "w3.weight"].T + return self._lin(mx.sigmoid(a) * a * b, self.W[p + "w2.weight"], c.hidden_size, c.intermediate_size) + + def route(self, h, li: int): + """(ids [M, k] ascending, weights [M, k]): the top k by score + bias, renormalised by explicit + adds in slot order (no reduction kernel whose order could follow the row count).""" + c = self.cfg + p = f"layers.{li}.feed_forward." + logits = h @ self.W[p + "gate.weight"].T + s = mx.sigmoid(logits) + k = c.num_experts_per_tok + choose = s + self.W[p + "expert_bias"] if c.use_expert_bias else s + ids = mx.sort(mx.argpartition(-choose.astype(mx.float32), kth=k - 1, axis=-1)[:, :k], axis=-1) + wts = mx.take_along_axis(s, ids, axis=-1) + tot = wts[:, 0:1] + for j in range(1, k): + tot = tot + wts[:, j:j + 1] + return ids.astype(mx.int32), wts / (tot + 1e-6) * c.routed_scaling_factor + + def moe(self, h, li: int): + c = self.cfg + ids, wts = self.route(h, li) # [M, k] + w13, w2 = self.W[f"experts.{li}.w13"], self.W[f"experts.{li}.w2"] + I, M, k = c.moe_intermediate_size, h.shape[0], c.num_experts_per_tok + if self._swiz: + return K.moe_prefill_swiz(h, ids, wts, w13, w2, c.num_experts, I, k) + # a prompt chunk: the (row, expert) pairs sorted by expert, so each expert is one matrix product + # over its rows (`sorted_indices`), not a matrix-vector product a pair (800 tok/s against 7,000) + flat = ids.reshape(-1) + order = mx.argsort(flat) + inv = mx.argsort(order) + xs = h[order // k][:, None, :] # [M k, 1, H] + es = flat[order] + gu = mx.gather_mm(xs, w13.swapaxes(-1, -2), rhs_indices=es, sorted_indices=True) + a, b = gu[..., :I], gu[..., I:] + y = mx.gather_mm(mx.sigmoid(a) * a * b, w2.swapaxes(-1, -2), rhs_indices=es, sorted_indices=True) + y = y[inv][:, 0, :].reshape(M, k, -1) + wt = wts.astype(y.dtype) + out = y[:, 0] * wt[:, 0:1] # the experts added in ascending id + for j in range(1, k): + out = out + y[:, j] * wt[:, j:j + 1] + return out.astype(h.dtype) + + # ------------------------------------------------------------------------ a block + def _geo(self, parents: list[int], L: int, M: int) -> "Geo": + """The block's geometry: the row-invariant path for up to ROWS_MAX rows (any tree), else the batched + path (a chain only).""" + paths = tree_paths(parents) + if M > K.ROWS_MAX: + if list(parents) != chain(M): + raise ValueError(f"a draft tree of {M} rows exceeds {K.ROWS_MAX}") + return Geo(inv=False, paths=paths) + A = max(len(pa) for pa in paths) + anc = np.zeros((M, A), dtype=np.int32) + for i, pa in enumerate(paths): + anc[i, :len(pa)] = pa + cos, sin = self.rope(mx.array([L + len(pa) - 1 for pa in paths], dtype=mx.int32)) + # a chain's conv windows are slices (the same values a gather would move, so the same bits) + taps = None if list(parents) == chain(M) else mx.array(conv_taps(paths, self.cfg.conv_state_len)) + return Geo(inv=True, paths=paths, taps=taps, + anc=mx.array(anc), dlen=mx.array([len(pa) for pa in paths], dtype=mx.int32), + rope=(cos[:, None, :], sin[:, None, :])) + + def rows(self, tokens, parents: list[int], st: MlxState, last_only: bool = False): + """Logits [M, vocab] (or [1, vocab] with `last_only`) fp32 of a block at the state's length.""" + tokens = mx.array(np.asarray(tokens, dtype=np.int32).reshape(-1)) + M = tokens.size + L = st.length + if L + M > st.cap: + raise ValueError(f"{L + M} rows exceed the state's capacity {st.cap}") + g = self._geo(list(parents), L, M) + self._block = (list(parents), g.paths) + out = self._forward(tokens, st, g, last_only=last_only) + mx.eval(out, *st.k.values(), *st.v.values(), *self.rec.values()) + return out + + def step(self, token, st: MlxState): + """One decode token (an int32 `mx.array` of shape [1], possibly still lazy) committed at once: + lazy logits [1, vocab], nothing evaluated, so the caller can queue the next step while this one + runs (`mx.async_eval`). The row-invariant path: the row a verify block computes for this token.""" + L = st.length + cc = self._compiled() + lb = mx.array([L], dtype=mx.int32) + cos, sin = cc["rope1"](lb) + g = Geo(inv=True, paths=[[0]], taps=None, anc=self._anc1, dlen=self._dlen1, rope=(cos, sin)) + out = self._forward_inv(token, st, g, commit_conv=True, lb=lb) + st.length = L + 1 + self.rec, self._block = {}, None + return out + + # ------------------------------------------------------------------------ the compiled row-invariant layers + def _compiled(self) -> dict: + """The row-invariant path's layer parts as `mx.compile`d functions (traced once a row count and kind, + then replayed: a decode step built ~400 ops in Python, 1.6 ms a token the server waited for). The + decode step and every verify block call the same functions, so their rows stay bit for bit equal; + the compiler's fused elementwise kernels compute each element alone.""" + if self._cc is not None: + return self._cc + c = self.cfg + eps, k, E, I = c.rms_norm_eps, c.num_experts_per_tok, c.num_experts, c.moe_intermediate_size + H, Hq, Hk, D = c.hidden_size, c.num_attention_heads, c.num_key_value_heads, c.head_dim + rot = self.rotate_half + + swiz = self._swiz + use_fast_moe = (self.dtype == mx.bfloat16 and H % 64 == 0 and I % 64 == 0 and E <= 128) + use_fast_qkv = (D <= 64 and D % 2 == 0 and self.dtype == mx.bfloat16) + use_fast_conv = (self.dtype == mx.bfloat16) + + def moe_res(h, nw, gw, bias, w13, w2): + if swiz: + return K.moe_fast_swiz(h, nw, gw, bias, w13, w2, I, eps, k, c.routed_scaling_factor, c.use_expert_bias) + if use_fast_moe: + return K.moe_fast(h, nw, gw, bias, w13, w2, eps, k, c.routed_scaling_factor, c.use_expert_bias) + n = mx.fast.rms_norm(h, nw, eps) + s = mx.sigmoid(K.dense(n, gw)) + choose = s + bias if c.use_expert_bias else s + ids = mx.sort(mx.argpartition(-choose.astype(mx.float32), kth=k - 1, axis=-1)[:, :k], axis=-1) + ids = ids.astype(mx.int32) + wts = mx.take_along_axis(s, ids, axis=-1) + tot = wts[:, 0:1] + for j in range(1, k): + tot = tot + wts[:, j:j + 1] + wts = wts / (tot + 1e-6) * c.routed_scaling_factor + M = n.shape[0] + pexp = ids.reshape(-1) + el = pexp if M == 1 else K.experts_used(pexp, E) + gu = K.rowmm(n, w13, K.pair_rows(M, k), pexp, rows=M, elist=el) + a, b = gu[:, :I], gu[:, I:] + y = K.rowmm(mx.sigmoid(a) * a * b, w2, K._index(M * k)[0], pexp, rows=M, elist=el).reshape(M, k, -1) + wt = wts.astype(y.dtype) + out = y[:, 0] * wt[:, 0:1] + for j in range(1, k): + out = out + y[:, j] * wt[:, j:j + 1] + return h + out.astype(h.dtype) + + def mlp_res(h, nw, w13, w2): + n = mx.fast.rms_norm(h, nw, eps) + if swiz: + act = K.dense_swiglu_swiz(n, w13, c.intermediate_size, H) + return K.dense_swiz(act, w2, H, c.intermediate_size, res=h) + ab = K.dense(n, w13) + a, b = ab[:, :ab.shape[1] // 2], ab[:, ab.shape[1] // 2:] + return K.dense(mx.sigmoid(a) * a * b, w2, res=h) + + def conv_res(h, nw, inw, cw, outw, state, taps=None): + if swiz: + bcx = K.dense_swiz(h, inw, 3 * H, H, nw=nw, eps=eps) + cy, bx = K.conv_gate(bcx, state, cw, taps) + return K.dense_swiz(cy, outw, H, H, res=h), bx + n = mx.fast.rms_norm(h, nw, eps) + bcx = K.dense(n, inw) + if use_fast_conv: + cy, bx = K.conv_gate(bcx, state, cw, taps) + return K.dense(cy, outw, res=h), bx + B, C, x = bcx[:, :H], bcx[:, H:2 * H], bcx[:, 2 * H:] + bx = B * x + src = mx.concatenate([state, bx], axis=0) + M, Kt = n.shape[0], cw.shape[1] + win = [src[t:t + M] for t in range(Kt)] if taps is None else [src[taps[:, t]] for t in range(Kt)] + y = win[0] * cw[:, 0] + for t in range(1, Kt): + y = y + win[t] * cw[:, t] + return K.dense(C * y.astype(n.dtype), outw, res=h), bx + + def conv_step(h, nw, inw, cw, outw, state): + if swiz: + bcx = K.dense_swiz(h, inw, 3 * H, H, nw=nw, eps=eps) + cy, nxt_st = K.conv_gate(bcx, state, cw, None, next_state=True) + return K.dense_swiz(cy, outw, H, H, res=h), nxt_st + n = mx.fast.rms_norm(h, nw, eps) + bcx = K.dense(n, inw) + if use_fast_conv: + cy, nxt_st = K.conv_gate(bcx, state, cw, None, next_state=True) + return K.dense(cy, outw, res=h), nxt_st + B, C, x = bcx[:, :H], bcx[:, H:2 * H], bcx[:, 2 * H:] + bx = B * x + src = mx.concatenate([state, bx], axis=0) + Kt = cw.shape[1] + y = src[0:1] * cw[:, 0] + for t in range(1, Kt): + y = y + src[t:t + 1] * cw[:, t] + return K.dense(C * y.astype(n.dtype), outw, res=h), src[-(Kt - 1):] + + def qkv_prep(h, nw, qkvw, qn, kn, cos, sin): + if swiz: + qkv = K.dense_swiz(h, qkvw, (Hq + 2 * Hk) * D, H, nw=nw, eps=eps) + else: + n = mx.fast.rms_norm(h, nw, eps) + qkv = K.dense(n, qkvw) + if use_fast_qkv: + return K.qkv_norm_rope(qkv, qn, kn, cos, sin, Hq, Hk, D, eps) + M = h.shape[0] + q = mx.fast.rms_norm(qkv[:, :Hq * D].reshape(M, Hq, D), qn, eps) + kk = mx.fast.rms_norm(qkv[:, Hq * D:(Hq + Hk) * D].reshape(M, Hk, D), kn, eps) + v = qkv[:, (Hq + Hk) * D:].reshape(M, Hk, D) + q = q * cos + rot(q) * sin + kk = kk * cos + rot(kk) * sin + return q, kk.transpose(1, 0, 2), v.transpose(1, 0, 2) + + def attn_out(h, o, ow): + if swiz: + return K.dense_swiz(o.reshape(o.shape[0], -1), ow, H, Hq * D, res=h) + return K.dense(o.reshape(o.shape[0], -1), ow, res=h) + + def head(h, nw, hw): + n = mx.fast.rms_norm(h, nw, eps) + if swiz: + return n, K.dense_swiz(n, hw, c.vocab_size, H, out_dtype=mx.float32) + return n, K.dense(n, hw, out_dtype=mx.float32) + + inv_freq = self.inv_freq + dt = self.dtype + + def rope1(pos): + f = pos.astype(mx.float32)[:, None] * inv_freq[None, :] + emb = mx.concatenate([f, f], axis=-1) + return mx.cos(emb).astype(dt)[:, None, :], mx.sin(emb).astype(dt)[:, None, :] + + self._raw = {"qkv": qkv_prep, "attn_out": attn_out} + self._cc = {name: mx.compile(f) for name, f in (("moe", moe_res), ("mlp", mlp_res), ("conv", conv_res), + ("conv_step", conv_step), ("qkv", qkv_prep), + ("attn_out", attn_out), ("head", head), ("rope1", rope1))} + return self._cc + + def _compiled_attn(self, nchunks: int): + fn = self._attn_cc.get(nchunks) + if fn is not None: + return fn + c = self.cfg + self._compiled() + qkv_fn, out_fn = self._raw["qkv"], self._raw["attn_out"] + gqa = c.gqa + + def attn_full(h, nw, qkvw, qn, kn, ow, kc, vc, cos, sin, anc, dlen, lb): + q, k, v = qkv_fn(h, nw, qkvw, qn, kn, cos, sin) + kc = mx.slice_update(kc, k, lb, axes=[1]) + vc = mx.slice_update(vc, v, lb, axes=[1]) + o = K.path_attention(q, kc, vc, anc, dlen, 0, gqa, lb=lb, nchunks=nchunks) + return out_fn(h, o, ow), kc, vc + + fn = self._attn_cc[nchunks] = mx.compile(attn_full) + return fn + + def _forward_inv(self, tokens, st: MlxState, g, commit_conv: bool = False, lb=None): + """The row-invariant path through the compiled parts (`_compiled`).""" + c, W, cc = self.cfg, self.W, self._compiled() + L = st.length + if lb is None: + lb = mx.array([L], dtype=mx.int32) + nchunks = (L + g.anc.shape[1] + K.ATTN_BK - 1) // K.ATTN_BK + attn_fn = self._compiled_attn(nchunks) if (c.head_dim == 64 and c.gqa == 4 and self.dtype == mx.bfloat16) else None + self.rec = {} + h = (K.embed_swiz(tokens, W["embed_tokens.weight"], c.hidden_size) if self._swiz + else W["embed_tokens.weight"][tokens].astype(self.dtype)) + for li in range(c.num_hidden_layers): + p = f"layers.{li}." + if c.is_attention(li): + a = p + "self_attn." + if attn_fn is not None: + h, st.k[li], st.v[li] = attn_fn( + h, W[p + "operator_norm.weight"], W[a + "qkv"], W[a + "q_layernorm.weight"], + W[a + "k_layernorm.weight"], W[a + "out_proj.weight"], st.k[li], st.v[li], + *g.rope, g.anc, g.dlen, lb) + else: + q, k, v = cc["qkv"](h, W[p + "operator_norm.weight"], W[a + "qkv"], W[a + "q_layernorm.weight"], + W[a + "k_layernorm.weight"], *g.rope) + M = q.shape[0] + st.k[li][:, L:L + M] = k + st.v[li][:, L:L + M] = v + o = K.path_attention(q, st.k[li], st.v[li], g.anc, g.dlen, L, c.gqa, lb=lb) + h = cc["attn_out"](h, o, W[a + "out_proj.weight"]) + else: + cv = p + "conv." + args = (h, W[p + "operator_norm.weight"], W[cv + "in_proj.weight"], W[cv + "conv2d"], + W[cv + "out_proj.weight"], st.conv[li]) + if commit_conv: + h, st.conv[li] = cc["conv_step"](*args) + else: + h, self.rec[li] = cc["conv"](*args) if g.taps is None else cc["conv"](*args, g.taps) + f = p + "feed_forward." + if c.is_moe(li): + h = cc["moe"](h, W[p + "ffn_norm.weight"], W[f + "gate.weight"], W[f + "expert_bias"], + W[f"experts.{li}.w13"], W[f"experts.{li}.w2"]) + else: + h = cc["mlp"](h, W[p + "ffn_norm.weight"], W[f + "w13"], W[f + "w2.weight"]) + self.hidden, out = cc["head"](h, W["embedding_norm.weight"], self.head_weight()) + return out + + def _forward(self, tokens, st: MlxState, g, last_only: bool = False): + if g.inv: + out = self._forward_inv(tokens, st, g) + return out[-1:] if last_only else out + c = self.cfg + self.rec = {} + h = (K.embed_swiz(tokens, self.W["embed_tokens.weight"], c.hidden_size) if self._swiz + else self.W["embed_tokens.weight"][tokens].astype(self.dtype)) + for li in range(c.num_hidden_layers): + p = f"layers.{li}." + n = self.rms(h, self.W[p + "operator_norm.weight"]) + h = h + (self.attention(n, li, st) if c.is_attention(li) else self.conv(n, li, st)) + n = self.rms(h, self.W[p + "ffn_norm.weight"]) + h = h + (self.moe(n, li) if c.is_moe(li) else self.mlp(n, li)) + h = self.rms(h, self.W["embedding_norm.weight"]) + self.hidden = h # the rows' final normed states [M, H] (a draft head reads them) + if last_only: + if self._swiz: + return K.dense_swiz(h[-1:], self.head_weight(), c.vocab_size, c.hidden_size, out_dtype=mx.float32) + return (h[-1:] @ self.head_weight().T).astype(mx.float32) + return self._lin(h, self.head_weight(), c.vocab_size, c.hidden_size, out_dtype=mx.float32) + + def commit(self, st: MlxState, path: list[int]) -> None: + parents, _ = self._block + if path and (path[0] != 0 or any(parents[b] != a for a, b in zip(path, path[1:]))): + raise ValueError(f"{path} is not a root path of the last block") + L, n = st.length, len(path) + idx = mx.array(path, dtype=mx.int32) + S = self.cfg.conv_state_len + for li, bx in self.rec.items(): + st.conv[li] = mx.concatenate([st.conv[li], bx[idx]], axis=0)[-S:] + if any(r != j for j, r in enumerate(path)): + for li in st.k: + st.k[li][:, L:L + n] = st.k[li][:, L + idx] + st.v[li][:, L:L + n] = st.v[li][:, L + idx] + st.length = L + n + mx.eval(*st.conv.values(), *st.k.values(), *st.v.values()) + self._block, self.rec = None, {} + + def prefill(self, tokens, st: MlxState, chunk: int = 2048, last_only: bool = False): + """A prompt in chunks of `chunk` rows: logits [T, vocab] of every row, or [1, vocab] of the + last with `last_only` (a long prompt's logits would not fit).""" + toks = np.asarray(tokens, dtype=np.int32).reshape(-1) + outs, hid = [], [] + for s in range(0, len(toks), chunk): + part = toks[s:s + chunk] + lg = self.rows(part, chain(len(part)), st, last_only=last_only) + outs.append(lg[-1:] if last_only else lg) + hid.append(self.hidden) + self.commit(st, list(range(len(part)))) + # every prompt row's final normed state [T, H] (the drafter syncs on them) + self.prompt_hidden = hid[0] if len(hid) == 1 else mx.concatenate(hid, axis=0) + return outs[-1] if last_only else mx.concatenate(outs, axis=0) + + def decode(self, token: int, st: MlxState): + if st.length + 1 > st.cap: + raise ValueError(f"{st.length + 1} rows exceed the state's capacity {st.cap}") + out = self.step(mx.array([int(token)], dtype=mx.int32), st) + mx.eval(out, *st.conv.values(), *st.k.values(), *st.v.values()) + return out + + def generate(self, token: int, st: MlxState, n: int, stop=()): + """Greedy tokens after `token`, up to `n`, one step queued ahead of the one read (the plain + decode loop, no drafting). Yields ints.""" + y = mx.array([int(token)], dtype=mx.int32) + nxt = mx.argmax(self.step(y, st), axis=-1).astype(mx.int32) + mx.async_eval(nxt) + for _ in range(n): + cur = nxt + if st.length < st.cap: + nxt = mx.argmax(self.step(cur, st), axis=-1).astype(mx.int32) + mx.async_eval(nxt) + t = int(cur.item()) + yield t + if t in stop or st.length >= st.cap: + return + + +def load(path: str, dtype=mx.bfloat16, log=print): + """(cfg, board) of an HF LFM2 MoE checkpoint directory.""" + from engine.models.lfm2_moe.config import config_from_dict + with open(os.path.join(path, "config.json")) as f: + raw = json.load(f) + gen = None + gp = os.path.join(path, "generation_config.json") + if os.path.isfile(gp): + with open(gp) as f: + gen = json.load(f) + cfg = config_from_dict(raw, path, gen) + return cfg, Lfm2MoeMLX.load_checkpoint(cfg, path, dtype, log) diff --git a/engine/models/lfm2_moe/mlx_kernels.py b/engine/models/lfm2_moe/mlx_kernels.py new file mode 100644 index 000000000..b22c9f641 --- /dev/null +++ b/engine/models/lfm2_moe/mlx_kernels.py @@ -0,0 +1,597 @@ +"""Row-invariant Metal kernels for LFM2 MoE on Apple silicon (the MLX board's block path, mlx_board.py). + +MLX's own matmul and attention pick their kernel and tiling by the number of rows, so a draft block's row +and the decode step's row of the same token round differently and a greedy speculative run drifts from the +plain greedy text at near ties (measured: prose, code and chat parted 8 to 56 % into a 512-token answer). +These kernels compute every row from its own inputs in an order fixed by the shapes of the weights and the +row's own keys, never by the row count, so a verified row is the decode step's row bit for bit: + + dense(x, w, res, out_dtype) y = x @ w.T (+ res): scalar chain kernel (few rows) or 8x8 bfloat matrix units + dense_swiz(...) 512B-coalesced ulong2 swizzled dense projection (`rowchain_swiz` / `rowmma_swiz`) + with optional fused 32-lane simd_sum RMSNorm and fused residual add + moe_fast_swiz(...) 512B-coalesced swizzled MoE pipeline: fused RMSNorm+gate (`moegate`), single-TG + router+LPT grouping (`moeroute`), dedicated M=1 w13+SwiGLU+RMSNorm (`moemm_r1_swiz`) + and fused w2+wsum+residual (`moemm_w2add_swiz`), or M>1 hybrid (`moemm_hyb_swiz`) + moe_fast(...) unswizzled MoE fast path (for tests/unswizzled checkpoints) + conv_gate(bcx, state, cw, taps) + fused double-gated short convolution without mx.concatenate + qkv_norm_rope(...) fused per-head Q/K RMSNorm + RoPE + K/V transpose + path_attention(q, kc, vc, anc, dlen, L, gqa) + register-resident FlashAttention-2 Split-K on 8x8 bfloat matrix units (D=64, + GQA=4, bf16), sharing K/V across GQA heads and up to 16 rows; `pathattn` fallback + rowmm(x, w, prow, pexp) general row-invariant expert/dense projection fallback + +Sources are in csrc/mlx_kernels/ (engine/native_build.py's layout). The CUDA board's counterpart is its row +kernels (ENG-287); like them these serve up to `ROWS_MAX` rows, and a longer prompt chunk takes MLX's own +batched kernels (the next token agrees, the bits need not). +""" + +from __future__ import annotations + + +import mlx.core as mx + +from engine import native_build as nb + +#: rows a block may have on these kernels (the verify width and more; `rowmm` takes pairs up to MAXP) +ROWS_MAX = 64 +#: output columns a simdgroup computes, rows a pass reads its weights for, pairs a call may route +TN, R, MAXP = 4, 8, 512 +#: rows a dense projection's pass takes (one expert: a block of up to 16 rows reads each weight once) +R_DENSE = 8 +#: threads of the fallback attention threadgroup (keys are dealt by logical index modulo NT) +NT = 128 +#: logical key chunk size for Split-K FlashAttention path_attention (fixed constant for row invariance) +ATTN_BK = 256 + +_K: dict = {} + + +#: every kernel source, by file name: read when its kernel is first built. Literal names, so that +#: tests/test_native_sources.py holds this table to the folder's contents. +_SRC = { + "convgate": lambda: nb.source(__file__, "convgate.metal"), + "dense_prefill_swiz": lambda: nb.source(__file__, "dense_prefill_swiz.metal"), + "embed_swiz": lambda: nb.source(__file__, "embed_swiz.metal"), + "moegate": lambda: nb.source(__file__, "moegate.metal"), + "moemm_hyb": lambda: nb.source(__file__, "moemm_hyb.metal"), + "moemm_hyb_swiz": lambda: nb.source(__file__, "moemm_hyb_swiz.metal"), + "moemm_prefill_swiz": lambda: nb.source(__file__, "moemm_prefill_swiz.metal"), + "moemm_r1": lambda: nb.source(__file__, "moemm_r1.metal"), + "moemm_r1_swiz": lambda: nb.source(__file__, "moemm_r1_swiz.metal"), + "moemm_w2add_swiz": lambda: nb.source(__file__, "moemm_w2add_swiz.metal"), + "moeprefill_grp": lambda: nb.source(__file__, "moeprefill_grp.metal"), + "moeroute": lambda: nb.source(__file__, "moeroute.metal"), + "moewsum": lambda: nb.source(__file__, "moewsum.metal"), + "pathattn": lambda: nb.source(__file__, "pathattn.metal"), + "pathattn_flash": lambda: nb.source(__file__, "pathattn_flash.metal"), + "pathattn_flash_m2": lambda: nb.source(__file__, "pathattn_flash_m2.metal"), + "pathattn_reduce": lambda: nb.source(__file__, "pathattn_reduce.metal"), + "qkv_rope": lambda: nb.source(__file__, "qkv_rope.metal"), + "rowchain": lambda: nb.source(__file__, "rowchain.metal"), + "rowchain_swiz": lambda: nb.source(__file__, "rowchain_swiz.metal"), + "rowmm": lambda: nb.source(__file__, "rowmm.metal"), + "rowmma": lambda: nb.source(__file__, "rowmma.metal"), + "rowmma_swiz": lambda: nb.source(__file__, "rowmma_swiz.metal"), +} + + +def _kernel(name: str, inputs: list, outputs: list, file: str | None = None, header: str = ""): + k = _K.get(name) + if k is None: + src = _SRC[file or name]() + k = _K[name] = mx.fast.metal_kernel(name=f"lfm2_{name}", input_names=inputs, output_names=outputs, + source=src, header=header) + return k + + +# --- 512B-coalesced weight swizzle helpers (BK=16, KS=4, TN=2 -> N_TILE=16, zero extra bytes) --- +def swizzle_dense(w: mx.array) -> mx.array: + """Repack [N, K] (N % 16 == 0, K % 64 == 0) into 512B-coalesced tile layout [N//16, K//64, 2, 2, 8, 4, 8].""" + N, Kd = w.shape + return w.reshape(N // 16, 8, 2, Kd // 64, 4, 2, 8).transpose(0, 3, 5, 2, 1, 4, 6).reshape(-1) + + +def unswizzle_dense(ws: mx.array, N: int, Kd: int) -> mx.array: + """Inverse of `swizzle_dense`: [N, K] back (the tests hold the round trip).""" + return ws.reshape(N // 16, Kd // 64, 2, 2, 8, 4, 8).transpose(0, 4, 3, 1, 5, 2, 6).reshape(N, Kd) + + +def swizzle_moe_w13(w13: mx.array) -> mx.array: + """Repack [E, 2*I, K] (I % 16 == 0, K % 64 == 0) with w1 & w3 interleaved inside each 4 KB tile.""" + E, N2, Kd = w13.shape + I = N2 // 2 + return w13.reshape(E, 2, I // 16, 8, 2, Kd // 64, 4, 2, 8).transpose(0, 2, 5, 1, 7, 4, 3, 6, 8).reshape(-1) + + +def unswizzle_moe_w13(ws: mx.array, E: int, I: int, Kd: int) -> mx.array: + """Inverse of `swizzle_moe_w13`: [E, 2*I, K] back (the tests hold the round trip).""" + return ws.reshape(E, I // 16, Kd // 64, 2, 2, 2, 8, 4, 8).transpose(0, 3, 1, 6, 5, 2, 7, 4, 8).reshape(E, 2 * I, Kd) + + +def swizzle_moe_w2(w2: mx.array) -> mx.array: + """Repack [E, H, I] (H % 16 == 0, I % 64 == 0) into 512B-coalesced tile layout.""" + E, H, I = w2.shape + return w2.reshape(E, H // 16, 8, 2, I // 64, 4, 2, 8).transpose(0, 1, 4, 6, 3, 2, 5, 7).reshape(-1) + + +def unswizzle_moe_w2(ws: mx.array, E: int, H: int, I: int) -> mx.array: + """Inverse of `swizzle_moe_w2`: [E, H, I] back (the tests hold the round trip).""" + return ws.reshape(E, H // 16, I // 64, 2, 2, 8, 4, 8).transpose(0, 1, 5, 4, 2, 6, 3, 7).reshape(E, H, I) + + +def embed_swiz(tokens: mx.array, w_swiz: mx.array, Kd: int) -> mx.array: + """Gather rows [M, K] from a 512B-coalesced swizzled [V, K] embedding table.""" + M = tokens.shape[0] + k8 = Kd // 8 + return _kernel("embed_swiz", ["tokens", "w_swiz"], ["out"])( + inputs=[tokens, w_swiz], template=[("K", Kd)], + grid=(k8, M, 1), threadgroup=(min(256, k8), 1, 1), + output_shapes=[(M, Kd)], output_dtypes=[w_swiz.dtype])[0] + + +def ksplit(N: int, K: int) -> int: + """How many ways a threadgroup splits K (1, 2 or 4): by the weight's shape alone, so a row's summation + order never follows the row count. Narrow outputs split more, to fill the GPU.""" + ks = 4 if N <= 512 else 1 if N <= 2048 else 2 + while ks > 1 and -(-K // 256) < ks: + ks //= 2 + return ks + + +def experts_used(pexp: mx.array, E: int) -> mx.array: + """The experts the pairs use, first, -1 past them ([min(E, P)] int32, on the GPU: no host sync).""" + used = mx.zeros((E,), dtype=mx.int32).at[pexp].add(1) > 0 + order = mx.argsort(mx.where(used, 0, 1))[:min(E, pexp.shape[0])].astype(mx.int32) + return mx.where(used[order], order, -1) + + +def rowmm(x: mx.array, w: mx.array, prow: mx.array, pexp: mx.array, rows: int | None = None, + elist: mx.array | None = None) -> mx.array: + """[P, N] in x's dtype: pair p is row prow[p] of x [rows, K] times expert pexp[p] of w [E, N, K].""" + E, N, K = w.shape + P = prow.shape[0] + if P > (MAXP if E > 1 else ROWS_MAX): + # the kernel's pair list is MAXP long for experts and ROWS_MAX long for one weight (its template) + raise ValueError(f"rowmm: {P} pairs exceed {MAXP if E > 1 else ROWS_MAX}") + if elist is None: + elist = _index(1)[2] if E == 1 else experts_used(pexp, E) + ks = ksplit(N, K) + tiles = -(-N // ((4 // ks) * TN)) + want = P if rows is None else rows + rmax = (R_DENSE if ks <= 2 else 8) if E == 1 else R + Rn = next(r for r in (1, 2, 4, 8, 16, 32) if r >= min(want, rmax)) + return _kernel("rowmm", ["x", "w", "prow", "pexp", "elist"], ["y"])( + inputs=[x, w, prow, pexp, elist], + template=[("T", x.dtype), ("OT", x.dtype), ("K", K), ("N", N), ("TN", TN), ("R", Rn), ("MAXP", MAXP if E > 1 else ROWS_MAX), ("KS", ks)], + grid=(tiles * 128, elist.shape[0], 1), threadgroup=(128, 1, 1), + output_shapes=[(P, N)], output_dtypes=[x.dtype])[0] + + +_IDX: dict = {} + + +def _index(M: int) -> tuple: + """(rows 0..M-1, zeros [M], the one-expert list [0]) as int32 arrays, made once a row count.""" + got = _IDX.get(M) + if got is None: + got = _IDX[M] = (mx.arange(M, dtype=mx.int32), mx.zeros((M,), dtype=mx.int32), mx.zeros((1,), dtype=mx.int32)) + mx.eval(*got) + return got + + +def _scalar_f32(val: float) -> mx.array: + key = ("f32", float(val)) + got = _IDX.get(key) + if got is None: + got = _IDX[key] = mx.array([float(val)], dtype=mx.float32) + mx.eval(got) + return got + + +def pair_rows(M: int, k: int) -> mx.array: + """[M k] int32: the row of each (row, slot) pair, made once a shape.""" + key = ("pairs", M, k) + got = _IDX.get(key) + if got is None: + got = _IDX[key] = mx.repeat(mx.arange(M, dtype=mx.int32), k) + mx.eval(got) + return got + + +#: (FN, BK, KS, TN, TG) of an unswizzled dense projection by its shape (N, K). +MMA = { + (6144, 2048): (2, 16, 4, 4, 128), # conv in_proj + (2048, 2048): (2, 16, 4, 4, 128), # conv and attention out_proj + (3072, 2048): (2, 16, 4, 4, 128), # q, k, v + (23552, 2048): (2, 32, 2, 4, 64), # dense MLP w1 and w3 + (2048, 11776): (2, 16, 4, 4, 128), # dense MLP w2 + (128000, 2048): (2, 32, 2, 4, 64), # head +} +#: rows a block may have on the scalar kernel; more take the matrix units +CHAIN_ROWS = 2 + + +def mma(x: mx.array, w: mx.array, FN: int, BK: int, KS: int, res: mx.array | None = None, + out_dtype=None) -> mx.array: + """x [M, K] @ w [N, K].T (+ res) on 8x8 bfloat simdgroup matrices.""" + M, Kd = x.shape + N = w.shape[0] + FM = 1 if M <= 8 else 2 + od = out_dtype or x.dtype + if res is not None: + k = _kernel("rowmma_add", ["x", "w", "res"], ["y"], file="rowmma", header="#define ADD_RES 1\n") + inps = [x, w, res] + else: + k = _kernel("rowmma", ["x", "w"], ["y"], file="rowmma", header="#define ADD_RES 0\n") + inps = [x, w] + return k( + inputs=inps, + template=[("T", x.dtype), ("OT", od), ("K", Kd), ("N", N), ("FM", FM), ("FN", FN), ("BK", BK), ("KS", KS)], + grid=(-(-N // ((4 // KS) * 8 * FN)) * 128, -(-M // (FM * 8)), 1), threadgroup=(128, 1, 1), + output_shapes=[(M, N)], output_dtypes=[od])[0] + + +def chain(x: mx.array, w: mx.array, BK: int, KS: int, TN: int, TG: int, res: mx.array | None = None, + out_dtype=None) -> mx.array: + """x [M, K] @ w [N, K].T (+ res) on the scalar kernel: `mma`'s rows for the same (BK, KS), bit for bit.""" + M, Kd = x.shape + N = w.shape[0] + R = next(r for r in (1, 2, 4, 8) if r >= min(M, CHAIN_ROWS)) + od = out_dtype or x.dtype + if res is not None: + k = _kernel("rowchain_add", ["x", "w", "res"], ["y"], file="rowchain", header="#define ADD_RES 1\n") + inps = [x, w, res] + else: + k = _kernel("rowchain", ["x", "w"], ["y"], file="rowchain", header="#define ADD_RES 0\n") + inps = [x, w] + return k( + inputs=inps, + template=[("T", x.dtype), ("OT", od), ("K", Kd), ("N", N), ("TN", TN), ("R", R), ("KS", KS), ("BK", BK), ("TG", TG)], + grid=(-(-N // ((TG // KS) * TN)) * TG, -(-M // R), 1), threadgroup=(TG, 1, 1), + output_shapes=[(M, N)], output_dtypes=[od])[0] + + +def dense(x: mx.array, w: mx.array, res: mx.array | None = None, out_dtype=None) -> mx.array: + """x [M, K] @ w [N, K].T (+ res), row-invariant.""" + cfg = MMA.get((w.shape[0], w.shape[1])) + if cfg is not None and w.shape[1] % (cfg[1] * cfg[2]) == 0 and cfg[1] % 8 == 0 and cfg[4] % cfg[2] == 0: + FN, BK, KS, TN, TG = cfg + return (chain(x, w, BK, KS, TN, TG, res=res, out_dtype=out_dtype) if x.shape[0] <= CHAIN_ROWS + else mma(x, w, FN, BK, KS, res=res, out_dtype=out_dtype)) + rows, zero, one = _index(x.shape[0]) + out = rowmm(x, w[None], rows, zero, elist=one) + if res is not None: + out = res + out + if out_dtype is not None and out.dtype != out_dtype: + out = out.astype(out_dtype) + return out + + +def dense_swiz(x: mx.array, w_swiz: mx.array, N: int, Kd: int, nw: mx.array | None = None, + eps: float = 1e-5, res: mx.array | None = None, out_dtype=None) -> mx.array: + """512B-coalesced swizzled row-invariant dense projection (`rowchain_swiz` for M<=2, `rowmma_swiz` for M>=3), + with optional fused 32-lane simd_sum RMSNorm (`nw`) and optional fused residual add (`res`).""" + M = x.shape[0] + od = out_dtype or x.dtype + has_rms = nw is not None + has_res = res is not None + tag = f"{'_rms' if has_rms else ''}{'_add' if has_res else ''}" + hdr = f"#define FUSE_RMS {int(has_rms)}\n#define ADD_RES {int(has_res)}\n" + in_names = ["x", "w_swiz"] + (["nw", "eps"] if has_rms else []) + (["res"] if has_res else []) + inps = [x, w_swiz] + ([nw, _scalar_f32(eps)] if has_rms else []) + ([res] if has_res else []) + if M <= CHAIN_ROWS: + R_n = 1 if M == 1 else 2 + TG = 128 + ntg = -(-N // ((TG // 32) * 16)) + k = _kernel(f"rowchain_swiz{tag}", in_names, ["y"], file="rowchain_swiz", header=hdr) + return k(inputs=inps, + template=[("T", x.dtype), ("OT", od), ("K", Kd), ("N", N), ("R", R_n), ("TG", TG)], + grid=(ntg * TG, -(-M // R_n), 1), threadgroup=(TG, 1, 1), + output_shapes=[(M, N)], output_dtypes=[od])[0] + FM = 1 if M <= 8 else 2 + k = _kernel(f"rowmma_swiz{tag}", in_names, ["y"], file="rowmma_swiz", header=hdr) + return k(inputs=inps, + template=[("T", x.dtype), ("OT", od), ("K", Kd), ("N", N), ("FM", FM)], + grid=((N // 16) * 128, -(-M // (FM * 8)), 1), threadgroup=(128, 1, 1), + output_shapes=[(M, N)], output_dtypes=[od])[0] + + +_NAX_HDR = ( + "#if defined(__METAL_VERSION__) && __METAL_VERSION__ >= 400\n" + "#include \n" + "#include \n" + "#endif\n" +) + + +def dense_prefill_swiz(x: mx.array, w_swiz: mx.array, N: int, Kd: int, out_dtype=None) -> mx.array: + """High-throughput batched prefill GEMM directly on 512B-coalesced w_swiz (M5 NAX / Metal 4 MPP, zero unswizzle!).""" + M = x.shape[0] + od = out_dtype or x.dtype + return _kernel("dense_prefill_swiz", ["x", "w_swiz"], ["y"], header=_NAX_HDR)( + inputs=[x, w_swiz], + template=[("T", x.dtype), ("OT", od), ("K", Kd), ("N", N)], + grid=(-(-M // 64) * 128, -(-N // 64), 1), threadgroup=(128, 1, 1), + output_shapes=[(M, N)], output_dtypes=[od])[0] + + +def moe_prefill_swiz(h: mx.array, ids: mx.array, wts: mx.array, w13_swiz: mx.array, w2_swiz: mx.array, + E: int, I: int, topk: int) -> mx.array: + """High-throughput batched prefill MoE directly on 512B-coalesced w13_swiz & w2_swiz (M5 NAX, zero unswizzle!).""" + M, H = h.shape + P = M * topk + pexp = ids.reshape(-1) + bm = 32 + maxt = P // bm + E + tile_e, tile_off, tile_nr, sel = _kernel("moeprefill_grp", ["pexp"], ["tile_e", "tile_off", "tile_nr", "sel"])( + inputs=[pexp], template=[("E", E), ("BM", bm), ("MAXT", maxt)], + grid=(256, 1, 1), threadgroup=(256, 1, 1), + output_shapes=[(maxt,), (maxt,), (maxt,), (P,)], output_dtypes=[mx.int32, mx.int32, mx.int32, mx.int32]) + bn13, bn2 = 64, 64 + act = _kernel("moemm_prefill_swiz", ["x", "w_swiz", "tile_e", "tile_off", "tile_nr", "sel"], ["y"], header=_NAX_HDR)( + inputs=[h, w13_swiz, tile_e, tile_off, tile_nr, sel], + template=[("T", h.dtype), ("K", H), ("NOUT", I), ("BM", bm), ("BN", bn13), ("TOPK", topk), ("SWIGLU", 1), ("PROW_IDENTITY", 0)], + grid=(maxt * 128, -(-I // bn13), 1), threadgroup=(128, 1, 1), + output_shapes=[(P, I)], output_dtypes=[h.dtype])[0] + y = _kernel("moemm_prefill_swiz", ["x", "w_swiz", "tile_e", "tile_off", "tile_nr", "sel"], ["y"], header=_NAX_HDR)( + inputs=[act, w2_swiz, tile_e, tile_off, tile_nr, sel], + template=[("T", h.dtype), ("K", I), ("NOUT", H), ("BM", bm), ("BN", bn2), ("TOPK", topk), ("SWIGLU", 0), ("PROW_IDENTITY", 1)], + grid=(maxt * 128, -(-H // bn2), 1), threadgroup=(128, 1, 1), + output_shapes=[(P, H)], output_dtypes=[h.dtype])[0].reshape(M, topk, H) + wt = wts.astype(y.dtype) + out = y[:, 0] * wt[:, 0:1] + for j in range(1, topk): + out = out + y[:, j] * wt[:, j:j + 1] + return out.astype(h.dtype) + + +def dense_swiglu_swiz(x: mx.array, w13_swiz: mx.array, I: int, Kd: int) -> mx.array: + """512B-coalesced swizzled fused SwiGLU dense MLP projection (w13_swiz = swizzle_moe_w13(w13[None])). + Reuses moemm_r1_swiz (M==1) and moemm_hyb_swiz (M>1) for bit-exact row invariance and 560+ GB/s BW.""" + M = x.shape[0] + if M == 1: + tg13 = 64 + _, _, one = _index(1) + return _kernel("moemm_r1_swiz_pexp", ["x", "w_swiz", "pexp"], ["y"], + file="moemm_r1_swiz", header="#define FUSE_ROUTE 0\n")( + inputs=[x, w13_swiz, one], + template=[("T", x.dtype), ("K", Kd), ("NOUT", I), ("TG", tg13)], + grid=(-(-I // ((tg13 // 32) * 16)) * tg13, 1, 1), threadgroup=(tg13, 1, 1), + output_shapes=[(1, I)], output_dtypes=[x.dtype])[0] + rows, _, one = _index(M) + eoff = one + ecnt_key = ("ecnt", M) + ecnt = _IDX.get(ecnt_key) + if ecnt is None: + ecnt = _IDX[ecnt_key] = mx.array([M], dtype=mx.int32) + mx.eval(ecnt) + fm_max = 1 if M <= 8 else 2 + return _kernel("moemm_hyb_swiz", ["x", "w_swiz", "elist", "eoff", "ecnt", "sel"], ["y"])( + inputs=[x, w13_swiz, one, eoff, ecnt, rows], + template=[("T", x.dtype), ("K", Kd), ("NOUT", I), ("FM_MAX", fm_max), ("TOPK", 1), ("SWIGLU", 1), ("PROW_IDENTITY", 1)], + grid=((I // 16) * 128, 1, 1), threadgroup=(128, 1, 1), + output_shapes=[(M, I)], output_dtypes=[x.dtype])[0] + + +def moe_fast_swiz(h: mx.array, nw: mx.array, gw: mx.array, bias: mx.array, w13_swiz: mx.array, w2_swiz: mx.array, + I: int, eps: float, topk: int, scale: float, use_bias: bool) -> mx.array: + """512B-coalesced swizzled MoE block (ONLY 3 launches per layer at M=1!): + M == 1: moegate_rms_out (gate+RMSNorm->n) -> moemm_r1_swiz_rt (route+w13+SwiGLU) -> moemm_w2add_swiz_rt (route+w2+wsum+res) + M > 1: moegate_rms_out (gate+RMSNorm->n) -> moeroute_grp -> moemm_hyb_swiz (w13+SwiGLU) -> moemm_hyb_swiz (w2) -> moewsum""" + M, H = h.shape + E = gw.shape[0] + P = M * topk + emax = min(E, P) + eps_arr = _scalar_f32(eps) + sc_arr = _scalar_f32(scale) + Rg = min(8, next(r for r in (1, 2, 4, 8) if r >= min(M, 8))) + logits, n = _kernel("moegate_rms_out", ["x", "w", "nw", "eps"], ["out", "n_out"], + file="moegate", header="#define FUSE_RMS 1\n#define WRITE_NORM 1\n")( + inputs=[h, gw, nw, eps_arr], template=[("T", h.dtype), ("K", H), ("E", E), ("R", Rg)], + grid=(E * 64, 1, 1), threadgroup=(64, 1, 1), + output_shapes=[(M, E), (M, H)], output_dtypes=[h.dtype, h.dtype]) + if M == 1: + # In-register exact top-TOPK + 512B-coalesced w13+SwiGLU (zero rms_norm, zero moeroute launch!) + tg13 = 32 + act = _kernel("moemm_r1_swiz_rt", ["x", "w_swiz", "logits", "bias"], ["y"], + file="moemm_r1_swiz", header="#define FUSE_ROUTE 1\n")( + inputs=[n, w13_swiz, logits, bias], + template=[("T", h.dtype), ("K", H), ("NOUT", I), ("TG", tg13), ("E", E), ("TOPK", topk), ("USE_BIAS", int(use_bias))], + grid=(-(-I // ((tg13 // 32) * 16)) * tg13, topk, 1), threadgroup=(tg13, 1, 1), + output_shapes=[(P, I)], output_dtypes=[h.dtype])[0] + # In-register exact top-TOPK + 4-load 512B-coalesced w2 + ascending wsum + residual add (zero moewsum launch!) + tg2 = 32 + return _kernel("moemm_w2add_swiz_rt", ["x", "w_swiz", "logits", "bias", "scale", "h"], ["out"], + file="moemm_w2add_swiz", header="#define FUSE_ROUTE 1\n")( + inputs=[act, w2_swiz, logits, bias, sc_arr, h], + template=[("T", h.dtype), ("K", I), ("NOUT", H), ("TG", tg2), ("E", E), ("TOPK", topk), ("USE_BIAS", int(use_bias))], + grid=(-(-H // ((tg2 // 32) * 16)) * tg2, 1, 1), threadgroup=(tg2, 1, 1), + output_shapes=[(M, H)], output_dtypes=[h.dtype])[0] + tg_route = 64 if max(M, E) <= 64 else 128 + pexp, wts, elist, eoff, ecnt, sel = _kernel( + "moeroute_grp", ["logits", "bias", "scale"], ["pexp", "wts", "elist", "eoff", "ecnt", "sel"], + file="moeroute", header="#define GROUP 1\n")( + inputs=[logits, bias, sc_arr], + template=[("T", h.dtype), ("E", E), ("TOPK", topk), ("MAXP", max(P, 64)), ("EMAX", emax), ("USE_BIAS", int(use_bias))], + grid=(tg_route, 1, 1), threadgroup=(tg_route, 1, 1), + output_shapes=[(P,), (M, topk), (emax,), (emax,), (emax,), (P,)], + output_dtypes=[mx.int32, h.dtype, mx.int32, mx.int32, mx.int32, mx.int32]) + fm_max = 1 if M <= 8 else 2 + act = _kernel("moemm_hyb_swiz", ["x", "w_swiz", "elist", "eoff", "ecnt", "sel"], ["y"])( + inputs=[n, w13_swiz, elist, eoff, ecnt, sel], + template=[("T", h.dtype), ("K", H), ("NOUT", I), ("FM_MAX", fm_max), ("TOPK", topk), ("SWIGLU", 1), ("PROW_IDENTITY", 0)], + grid=((I // 16) * 128, emax, 1), threadgroup=(128, 1, 1), + output_shapes=[(P, I)], output_dtypes=[h.dtype])[0] + y = _kernel("moemm_hyb_swiz", ["x", "w_swiz", "elist", "eoff", "ecnt", "sel"], ["y"])( + inputs=[act, w2_swiz, elist, eoff, ecnt, sel], + template=[("T", h.dtype), ("K", I), ("NOUT", H), ("FM_MAX", fm_max), ("TOPK", topk), ("SWIGLU", 0), ("PROW_IDENTITY", 1)], + grid=((H // 16) * 128, emax, 1), threadgroup=(128, 1, 1), + output_shapes=[(P, H)], output_dtypes=[h.dtype])[0] + return _kernel("moewsum", ["h", "y", "wts"], ["out"])( + inputs=[h, y, wts], template=[("T", h.dtype), ("N", H), ("TOPK", topk)], + grid=(H // 4, M, 1), threadgroup=(min(256, H // 4), 1, 1), + output_shapes=[(M, H)], output_dtypes=[h.dtype])[0] + + +def moe_fast(h: mx.array, nw: mx.array, gw: mx.array, bias: mx.array, w13: mx.array, w2: mx.array, + eps: float, topk: int, scale: float, use_bias: bool) -> mx.array: + """Unswizzled fused row-invariant MoE block (bfloat16, K % 64 == 0, E <= 128).""" + M, H = h.shape + E = gw.shape[0] + I = w2.shape[2] + P = M * topk + emax = min(E, P) + n = mx.fast.rms_norm(h, nw, eps) + Rg = min(8, next(r for r in (1, 2, 4, 8) if r >= min(M, 8))) + logits = _kernel("moegate", ["x", "w"], ["out"], file="moegate", header="#define FUSE_RMS 0\n#define WRITE_NORM 0\n")( + inputs=[n, gw], template=[("T", n.dtype), ("K", H), ("E", E), ("R", Rg)], + grid=(E * 64, 1, 1), threadgroup=(64, 1, 1), + output_shapes=[(M, E)], output_dtypes=[n.dtype])[0] + tg_route = 64 if max(M, E) <= 64 else 128 + BK, KS = 16, 4 + if M == 1: + pexp, wts = _kernel("moeroute_m1", ["logits", "bias", "scale"], ["pexp", "wts"], + file="moeroute", header="#define GROUP 0\n")( + inputs=[logits, bias, _scalar_f32(scale)], + template=[("T", n.dtype), ("E", E), ("TOPK", topk), ("USE_BIAS", int(use_bias))], + grid=(tg_route, 1, 1), threadgroup=(tg_route, 1, 1), + output_shapes=[(P,), (M, topk)], + output_dtypes=[mx.int32, n.dtype]) + act = _kernel("moemm_r1", ["x", "w", "pexp"], ["y"])( + inputs=[n, w13, pexp], + template=[("T", n.dtype), ("K", H), ("NOUT", I), ("BK", BK), ("KS", KS), ("TN", 1), ("TG", 128), ("SWIGLU", 1), ("PROW_IDENTITY", 0)], + grid=(-(-I // 32) * 128, topk, 1), threadgroup=(128, 1, 1), + output_shapes=[(P, I)], output_dtypes=[n.dtype])[0] + y = _kernel("moemm_r1", ["x", "w", "pexp"], ["y"])( + inputs=[act, w2, pexp], + template=[("T", n.dtype), ("K", I), ("NOUT", H), ("BK", BK), ("KS", KS), ("TN", 4), ("TG", 64), ("SWIGLU", 0), ("PROW_IDENTITY", 1)], + grid=(-(-H // 64) * 64, topk, 1), threadgroup=(64, 1, 1), + output_shapes=[(P, H)], output_dtypes=[n.dtype])[0] + else: + pexp, wts, elist, eoff, ecnt, sel = _kernel( + "moeroute_grp", ["logits", "bias", "scale"], ["pexp", "wts", "elist", "eoff", "ecnt", "sel"], + file="moeroute", header="#define GROUP 1\n")( + inputs=[logits, bias, _scalar_f32(scale)], + template=[("T", n.dtype), ("E", E), ("TOPK", topk), ("MAXP", max(P, 64)), ("EMAX", emax), ("USE_BIAS", int(use_bias))], + grid=(tg_route, 1, 1), threadgroup=(tg_route, 1, 1), + output_shapes=[(P,), (M, topk), (emax,), (emax,), (emax,), (P,)], + output_dtypes=[mx.int32, n.dtype, mx.int32, mx.int32, mx.int32, mx.int32]) + fn, fm_max = 2, (1 if M <= 8 else 2) + ntile = (4 // KS) * fn * 8 + act = _kernel("moemm_hyb", ["x", "w", "elist", "eoff", "ecnt", "sel"], ["y"])( + inputs=[n, w13, elist, eoff, ecnt, sel], + template=[("T", n.dtype), ("K", H), ("NOUT", I), ("BK", BK), ("KS", KS), ("FN", fn), ("FM_MAX", fm_max), ("TOPK", topk), ("SWIGLU", 1), ("PROW_IDENTITY", 0)], + grid=(-(-I // ntile) * 128, emax, 1), threadgroup=(128, 1, 1), + output_shapes=[(P, I)], output_dtypes=[n.dtype])[0] + y = _kernel("moemm_hyb", ["x", "w", "elist", "eoff", "ecnt", "sel"], ["y"])( + inputs=[act, w2, elist, eoff, ecnt, sel], + template=[("T", n.dtype), ("K", I), ("NOUT", H), ("BK", BK), ("KS", KS), ("FN", fn), ("FM_MAX", fm_max), ("TOPK", topk), ("SWIGLU", 0), ("PROW_IDENTITY", 1)], + grid=(-(-H // ntile) * 128, emax, 1), threadgroup=(128, 1, 1), + output_shapes=[(P, H)], output_dtypes=[n.dtype])[0] + return _kernel("moewsum", ["h", "y", "wts"], ["out"])( + inputs=[h, y, wts], template=[("T", n.dtype), ("N", H), ("TOPK", topk)], + grid=(H // 4, M, 1), threadgroup=(min(256, H // 4), 1, 1), + output_shapes=[(M, H)], output_dtypes=[n.dtype])[0] + + +def conv_gate(bcx: mx.array, state: mx.array, cw: mx.array, taps: mx.array | None = None, + next_state: bool = False) -> tuple[mx.array, mx.array]: + """Fused double-gated short convolution: returns (C * y, B * x) or (C * y, next_state) in ascending tap order.""" + M = bcx.shape[0] + H, Kt = cw.shape + tg = min(256, H) + if next_state: + k = _kernel("convgate_step", ["bcx", "state", "cw"], ["cy", "next_state"], + file="convgate", header="#define HAS_TAPS 0\n#define NEXT_STATE 1\n") + return k(inputs=[bcx, state, cw], template=[("T", bcx.dtype), ("H", H), ("KT", Kt)], + grid=(H, M, 1), threadgroup=(tg, 1, 1), + output_shapes=[(M, H), (Kt - 1, H)], output_dtypes=[bcx.dtype, bcx.dtype]) + if taps is not None: + k = _kernel("convgate_taps", ["bcx", "state", "cw", "taps"], ["cy", "bx"], + file="convgate", header="#define HAS_TAPS 1\n#define NEXT_STATE 0\n") + inps = [bcx, state, cw, taps] + else: + k = _kernel("convgate_chain", ["bcx", "state", "cw"], ["cy", "bx"], + file="convgate", header="#define HAS_TAPS 0\n#define NEXT_STATE 0\n") + inps = [bcx, state, cw] + cy, bx = k(inputs=inps, template=[("T", bcx.dtype), ("H", H), ("KT", Kt)], + grid=(H, M, 1), threadgroup=(tg, 1, 1), + output_shapes=[(M, H), (M, H)], output_dtypes=[bcx.dtype, bcx.dtype]) + return cy, bx + + +def qkv_norm_rope(qkv: mx.array, qn: mx.array, kn: mx.array, cos: mx.array, sin: mx.array, + Hq: int, Hk: int, D: int, eps: float) -> tuple[mx.array, mx.array, mx.array]: + """Fused per-head Q/K RMSNorm + RoPE + K/V transpose: returns (q [M, Hq, D], k [Hk, M, D], v [Hk, M, D]).""" + M = qkv.shape[0] + q, k, v = _kernel("qkv_rope", ["qkv", "qn", "kn", "cos", "sin", "eps"], ["q_out", "k_out", "v_out"])( + inputs=[qkv, qn, kn, cos, sin, _scalar_f32(eps)], + template=[("T", qkv.dtype), ("Hq", Hq), ("Hk", Hk), ("D", D)], + grid=((Hq + 2 * Hk) * 32, M, 1), threadgroup=(32, 1, 1), + output_shapes=[(M, Hq, D), (Hk, M, D), (Hk, M, D)], + output_dtypes=[qkv.dtype, qkv.dtype, qkv.dtype]) + return q, k, v + + +def path_attention(q: mx.array, kc: mx.array, vc: mx.array, anc: mx.array, dlen: mx.array, L: int, + gqa: int, lb: mx.array | None = None, nchunks: int | None = None) -> mx.array: + """q [M, Hq, D] (rotated), the caches [Hk, cap, D] holding the block's rows at L.., anc [M, A] int32 each + row's path (block rows, root first, padded), dlen [M] its length: out [M, Hq, D].""" + M, Hq, D = q.shape + if lb is None: + lb = mx.array([L], dtype=mx.int32) + if D == 64 and gqa == 4 and q.dtype == mx.bfloat16: + Hk = Hq // gqa + if nchunks is None: + nchunks = (L + anc.shape[1] + ATTN_BK - 1) // ATTN_BK + if M <= 2: + if nchunks == 1: + return _kernel("pathattn_flash_m2_single", ["q", "kc", "vc", "anc", "dl", "lb"], ["o"], + file="pathattn_flash_m2", header="#define SINGLE_CHUNK 1\n")( + inputs=[q, kc, vc, anc, dlen, lb], + template=[("T", q.dtype), ("D", D), ("GQA", gqa), ("BK", ATTN_BK), ("BM", 2)], + grid=(Hk * 128, 1, 1), threadgroup=(128, 1, 1), + output_shapes=[(M, Hq, D)], output_dtypes=[q.dtype])[0] + pm, pl, pa = _kernel("pathattn_flash_m2_chunk", ["q", "kc", "vc", "anc", "dl", "lb"], ["pm", "pl", "pa"], + file="pathattn_flash_m2", header="#define SINGLE_CHUNK 0\n")( + inputs=[q, kc, vc, anc, dlen, lb], + template=[("T", q.dtype), ("D", D), ("GQA", gqa), ("BK", ATTN_BK), ("BM", 2)], + grid=(Hk * 128, nchunks, 1), threadgroup=(128, 1, 1), + output_shapes=[(M, Hq, nchunks), (M, Hq, nchunks), (M, Hq, nchunks, D)], + output_dtypes=[mx.float32, mx.float32, mx.float32]) + return _kernel("pathattn_reduce", ["pm", "pl", "pa", "dl", "lb"], ["o"])( + inputs=[pm, pl, pa, dlen, lb], + template=[("T", q.dtype), ("D", D), ("BK", ATTN_BK)], + grid=(Hq * 32, M, 1), threadgroup=(32, 1, 1), + output_shapes=[(M, Hq, D)], output_dtypes=[q.dtype])[0] + if M <= 4: + bm, nsg = 4, 2 + elif M <= 8: + bm, nsg = 8, 4 + else: + bm, nsg = 16, 8 + if nchunks == 1: + return _kernel("pathattn_flash_single", ["q", "kc", "vc", "anc", "dl", "lb"], ["o"], + file="pathattn_flash", header="#define SINGLE_CHUNK 1\n")( + inputs=[q, kc, vc, anc, dlen, lb], + template=[("T", q.dtype), ("D", D), ("GQA", gqa), ("BK", ATTN_BK), ("BM", bm), ("NSG", nsg)], + grid=(Hk * nsg * 32, 1, -(-M // bm)), threadgroup=(nsg * 32, 1, 1), + output_shapes=[(M, Hq, D)], output_dtypes=[q.dtype])[0] + pm, pl, pa = _kernel("pathattn_flash_chunk", ["q", "kc", "vc", "anc", "dl", "lb"], ["pm", "pl", "pa"], + file="pathattn_flash", header="#define SINGLE_CHUNK 0\n")( + inputs=[q, kc, vc, anc, dlen, lb], + template=[("T", q.dtype), ("D", D), ("GQA", gqa), ("BK", ATTN_BK), ("BM", bm), ("NSG", nsg)], + grid=(Hk * nsg * 32, nchunks, -(-M // bm)), threadgroup=(nsg * 32, 1, 1), + output_shapes=[(M, Hq, nchunks), (M, Hq, nchunks), (M, Hq, nchunks, D)], + output_dtypes=[mx.float32, mx.float32, mx.float32]) + return _kernel("pathattn_reduce", ["pm", "pl", "pa", "dl", "lb"], ["o"])( + inputs=[pm, pl, pa, dlen, lb], + template=[("T", q.dtype), ("D", D), ("BK", ATTN_BK)], + grid=(Hq * 32, M, 1), threadgroup=(32, 1, 1), + output_shapes=[(M, Hq, D)], output_dtypes=[q.dtype])[0] + return _kernel("pathattn", ["q", "kc", "vc", "anc", "dl", "lb"], ["o"])( + inputs=[q, kc, vc, anc, dlen, lb], + template=[("T", q.dtype), ("D", D), ("GQA", gqa), ("NT", NT)], + grid=(Hq * NT, M, 1), threadgroup=(NT, 1, 1), + output_shapes=[(M, Hq, D)], output_dtypes=[q.dtype])[0] diff --git a/engine/models/lfm2_moe/mlx_serving.py b/engine/models/lfm2_moe/mlx_serving.py new file mode 100644 index 000000000..a8b144aa9 --- /dev/null +++ b/engine/models/lfm2_moe/mlx_serving.py @@ -0,0 +1,422 @@ +"""LFM2 MoE behind the server's generation loop on Apple silicon: `Lfm2MoeMLX` (mlx_board.py) in the +interface `server/app.py` drives every model through (the CUDA adapter's, serving.py). + + forward, one token `Lfm2MoeMLX.decode` + forward, more tokens `Lfm2MoeMLX.prefill` (chain blocks of PREFILL_CHUNK rows) + forward_tree `Lfm2MoeMLX.rows`: logits [M, vocab], the greedy picks + commit_tree `Lfm2MoeMLX.commit` + forward_block a chain verify whose commit waits for `rollback_to` or the next call + +Logits, picks and hidden rows cross to the server as torch tensors on the CPU (the device the server is +given), copied out of MLX's unified memory once a call. + +Exactness: a verified row is the decode step's row bit for bit, as on the CUDA board. MLX's own matmuls +round by row count (tools/gpu/apple.py), so the board computes every row with its own Metal kernels +(mlx_kernels.py), in an order fixed by the weight's shape. The load-time check (`self_check`) compares +verified rows with the decode steps' (a greedy chain, then chains and a tree after a longer prompt); +speculation runs only when every row has the decode step's bits. `exact` in the weights info says so. + +Off for now (`caps`): the prefix, session and disk caches, the KV pool, side slots, joint passes. +""" + +from __future__ import annotations + +import os +import time + +import numpy as np +import torch + +from engine.methods.manifest import Manifest +from engine.models.adapter import Capabilities, CostModel +from engine.models.lfm2_moe.serving import CONDUCTOR_FIT +from engine.models.state import SectionState + +PREFILL_CHUNK = 4096 # measured on the M5 Max: 4,096 rows a chunk prefill fastest (7.2k tok/s at 16k) +MODEL_ID = "lfm2.5-24b-a2b" +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) +MODULES = ("engine/models/lfm2_moe/config.py", "engine/models/lfm2_moe/ref.py", + "engine/models/lfm2_moe/mlx_board.py", "engine/models/lfm2_moe/mlx_kernels.py", + "engine/models/lfm2_moe/mlx_serving.py") + + +def manifest() -> Manifest: + # MLX rows are not the CUDA board's: their own arch, so no cache entry crosses between the two + return Manifest(arch="lfm2_moe-mlx", modules=MODULES) + + +def _t(a) -> torch.Tensor: + import mlx.core as mx + return torch.from_numpy(np.array(a.astype(mx.float32) if a.dtype != mx.float32 else a)) + + +class _KV: + """The `kv` the server reads: the length once pending work commits, the capacity.""" + + pages = None + + def __init__(self, s: "Lfm2MoeMLXServing"): + self._s = s + + @property + def length(self) -> int: + return self._s.st.length + (self._s._chain or 0) + + @length.setter + def length(self, v: int) -> None: + v = int(v) + if v == 0: + self._s.restart() + return + if v != self._s.st.length: + # the conv states are not indexed by row: a length alone cannot move them (`resume_at`) + raise ValueError(f"the LFM2 (MLX) state holds {self._s.st.length} rows and cannot be set to {v}") + + @property + def max_len(self) -> int: + return self._s.max_len + + +class Lfm2MoeMLXServing: + caps = Capabilities(caches=False, side_slots=False, anchor_grid=None, shadow=False, joint_verify=False, + side_lane=False, joint_plain=False, conductor=CONDUCTOR_FIT) + + def __init__(self, board, max_len: int): + self.fn, self.cfg, self.max_len = board, board.cfg, max_len + self.st = board.new_state(max_len) + self.kv = _KV(self) + self.picks = None + self.tap = None + self.mm = None + self.pos_delta = 0 + self._hidden = None + self._chain = None + self._mark = None # (length, conv states) at the last `settle` + self.commit_ms = 0.0 + self.captured = False + self.plain_captured = False + self.heads: dict = {} + self.stats = {"prefill_rows": 0, "decode_steps": 0, "verify_blocks": 0, "verify_rows": 0} + + # --- the loop's interface ------------------------------------------------------------------- + @property + def hidden_post_norm(self) -> torch.Tensor: + return self._hidden + + def price_class(self, n: int) -> int: + """The prices' context class: 2,048 keys, doubling (the CUDA board's classes).""" + c, n = 2048, max(1, int(n)) + while c < n and c < self.max_len: + c *= 2 + return c + + def last_streams(self) -> torch.Tensor: + return self._hidden[0, -1:] if self._hidden is not None else torch.zeros(1, self.cfg.hidden_size) + + def cost(self) -> CostModel: + c = self.cfg + sec = c.conv_state_bytes(2) + return CostModel(section_bytes=sec, view_bytes_per_token=c.kv_bytes_per_token(2), + parts={"recurrent": 0, "conv": sec}) + + def manifest(self) -> Manifest: + return manifest() + + def precapture(self, drafter) -> int | None: + self.kv.length = 0 + return None + + def draft_heads(self) -> dict: + return self.heads + + def settle(self) -> None: + """Pending work in, and this point kept: `resume_at` can come back to it (the server's in-place + ask, `_ask_in_place`: its `cache_state` snapshot is empty here, the conv states are MLX arrays).""" + self._settle_chain() + self._mark = (self.st.length, dict(self.st.conv)) + + def cache_state(self): + return SectionState({}) + + def resume_at(self, n: int) -> None: + """Back at `n` rows: where the state is, empty, or the point `settle` last kept (its conv states + put back; the KV rows above `n` are written over by the next forward). Any other `n` is refused: + the conv states of an arbitrary row are not kept.""" + self.discard_pending() + n = int(n) + if n == self.st.length and (self._mark is None or self._mark[0] != n): + return + if n == 0: + self.restart() + elif self._mark is not None and self._mark[0] == n: + self.st.length, self.st.conv = n, dict(self._mark[1]) + else: + raise ValueError(f"the LFM2 (MLX) state holds {self.st.length} rows and kept no point at {n}") + + def memory_parts(self) -> dict: + w = sum(int(a.nbytes) for a in self.fn.W.values()) + st = self.st + kv = sum(int(a.nbytes) for d in (st.k, st.v) for a in d.values()) + return {"weights": w, "kv_pool": kv, "drafter_kv": 0, "gdn_state": sum(int(a.nbytes) for a in st.conv.values())} + + def resident_files(self) -> list: + return [] + + def discard_pending(self) -> None: + self._chain = None + self.picks = None + + def trim_pending(self, n: int) -> bool: + n, L = int(n), self.st.length + if self._chain is None: + return n == L + if not L <= n <= L + self._chain: + return False + self._chain = None + if n > L: + self.commit_tree(list(range(n - L))) + return True + + def window_ok(self, i: int) -> bool: + return False + + def reset(self) -> None: + self.restart() + + def restart(self) -> None: + self._chain = None + self._mark = None + self.picks = None + self.st.reset_inplace() + + def tree_batchable(self, parents) -> bool: + return False + + @torch.no_grad() + def forward(self, ids: torch.Tensor, start: int, last_only: bool = True) -> torch.Tensor: + """Rows `ids` at positions start..: logits [1, 1, vocab] of the last row (fp32).""" + self._settle_chain() + ids = ids.view(-1) + self._at(start) + T = ids.numel() + if self.st.length + T > self.max_len: + raise ValueError(f"{self.st.length + T} rows exceed the window {self.max_len}") + if T == 1: + lg = self.fn.decode(int(ids[0]), self.st) + self.stats["decode_steps"] += 1 + else: + lg = self.fn.prefill(ids.tolist(), self.st, chunk=PREFILL_CHUNK, last_only=True) + self.stats["prefill_rows"] += T + self._hidden = _t(self.fn.prompt_hidden).unsqueeze(0) # [1, T, H] + return _t(lg[-1:]).view(1, 1, -1) + self._hidden = _t(self.fn.hidden[-1:]).view(1, 1, -1) + return _t(lg[-1:]).view(1, 1, -1) + + @torch.no_grad() + def forward_tree(self, block: torch.Tensor, parents: list[int], start: int) -> torch.Tensor: + """A draft block in DFS pre-order (row 0 the anchor at `start`): every row's logits [M, vocab] + fp32, its greedy pick in `picks`; nothing but the block's KV rows written until `commit_tree`.""" + self._settle_chain() + self._at(start) + toks = [int(t) for t in block.view(-1).tolist()] + M = len(toks) + if self.st.length + M > self.max_len: + raise ValueError(f"{self.st.length + M} rows exceed the window {self.max_len}") + from engine.models.lfm2_moe.mlx_kernels import ROWS_MAX + if M > ROWS_MAX: + # past it the board batches a chain on MLX's own matmul, whose rows are not the decode step's + raise ValueError(f"a verify block of {M} rows exceeds the row kernels' {ROWS_MAX}") + lg = self.fn.rows(toks, [int(p) for p in parents], self.st) + out = _t(lg) + self.picks = out.argmax(-1) + self._hidden = _t(self.fn.hidden).unsqueeze(0) + self.stats["verify_blocks"] += 1 + self.stats["verify_rows"] += M + return out + + @torch.no_grad() + def commit_tree(self, path: list[int]) -> None: + t0 = time.perf_counter() + self.fn.commit(self.st, [int(p) for p in path]) + self.commit_ms = (time.perf_counter() - t0) * 1e3 + + @torch.no_grad() + def forward_block(self, block: torch.Tensor, start: int) -> torch.Tensor: + n = block.numel() + lg = self.forward_tree(block, list(range(-1, n - 1)), start) + self._chain = n + return lg + + @torch.no_grad() + def rollback_to(self, keep: int) -> None: + self._chain = None + self.commit_tree(list(range(int(keep)))) + + # --- internals ------------------------------------------------------------------------------- + def _settle_chain(self) -> None: + if self._chain is not None: + n, self._chain = self._chain, None + self.commit_tree(list(range(n))) + + def _at(self, start: int) -> None: + if int(start) != self.st.length: + raise ValueError(f"LFM2 forward at {start}, the state holds {self.st.length} rows") + + +#: the self-check's chain blocks after its long prompt. Each size is a kernel variant of its own on the served +#: shapes: 2 rows the scalar dense kernel and the 2-row attention; 3 and 4 the 4-row attention groups and +#: router; 5 and 9 one and two tiles of the matrix units; 16 and 32 the widths the cut verifies most and last +CHECK_CHAINS = (2, 3, 4, 5, 9, 16, 32) +#: and a tree: rows that share ancestors, so the conv's windows and the attention's paths are gathered +CHECK_TREE = ([7, 19, 23, 44, 31, 60], [-1, 0, 1, 1, 0, 4]) +#: its long prompt: past the attention kernel's 256-token chunk, so a row's attention is reduced over chunks +CHECK_LONG = 300 + + +def self_check(board, prompt: list[int], steps: int = 24, log=print) -> dict: + """The load-time check of the verify path, bit for bit against the decode step. + + 1. After `prompt`: `steps` greedy tokens decoded one at a time, then verified as one chain block. + 2. After a `CHECK_LONG`-token prompt (`prompt` repeated): chains of `CHECK_CHAINS` rows and the tree + `CHECK_TREE`, each row against the decode of its path. + + `ok` when every row's logits are the decode step's, byte for byte: the row kernels hold that by + construction on the chip they were measured on (mlx_kernels.py), and a chip, macOS or MLX that rounds + one of them another way must not draft. On a failure `first_diff` is the first differing row (in the + order above), `max_diff` the largest logit gap and `picks` whether the greedy picks at least agreed.""" + import mlx.core as mx + + def at(tokens): + st = board.new_state(len(tokens) + max(steps, *CHECK_CHAINS) + 8) + lg = board.prefill(tokens, st, last_only=True) + return st, lg, st.length, dict(st.conv) + + def back(st, L, conv): + st.length, st.conv = L, dict(conv) + + seen = {"rows": 0, "first": None, "max": 0.0, "picks": True} + + def hold(got, want): + if got.tobytes() != want.tobytes(): + if seen["first"] is None: + seen["first"] = seen["rows"] + seen["max"] = max(seen["max"], float(np.abs(got.astype(np.float64) - want.astype(np.float64)).max())) + seen["picks"] = seen["picks"] and int(got.argmax()) == int(want.argmax()) + seen["rows"] += 1 + + def greedy(st, first: int, n: int): + toks, rows = [first], [] + for _ in range(n): + rows.append(np.array(board.decode(toks[-1], st)[0])) + toks.append(int(rows[-1].argmax())) + return toks[:n], rows + + # 1: the greedy chain after the chat prompt + st, lg, L, conv = at(prompt) + toks, want = greedy(st, int(mx.argmax(lg[-1]).item()), steps) + back(st, L, conv) + got = np.array(board.rows(toks, list(range(-1, steps - 1)), st)) + for i in range(steps): + hold(got[i], want[i]) + # 2: the blocks the cut serves, after a prompt of more than one attention chunk + long_prompt = (list(prompt) * (CHECK_LONG // max(1, len(prompt)) + 1))[:CHECK_LONG] + st, lg, L, conv = at(long_prompt) + toks, want = greedy(st, int(mx.argmax(lg[-1]).item()), max(CHECK_CHAINS)) + for m in CHECK_CHAINS: + back(st, L, conv) + got = np.array(board.rows(toks[:m], list(range(-1, m - 1)), st)) + for i in range(m): + hold(got[i], want[i]) + t_toks, t_par = CHECK_TREE + back(st, L, conv) + got = np.array(board.rows(t_toks, t_par, st)) + for row in range(len(t_toks)): + path, r = [], row + while r >= 0: + path.append(r) + r = t_par[r] + back(st, L, conv) + for r in reversed(path): + out = np.array(board.decode(t_toks[r], st)[0]) + hold(got[row], out) + ok = seen["first"] is None + res = {"ok": ok, "bitwise": ok, "rows": seen["rows"], "first_diff": seen["first"], "max_diff": seen["max"], + "picks": seen["picks"]} + if log: + log(f"[lfm-mlx-selfcheck] {'PASS' if ok else 'FAIL: speculation stays off'}: {res}") + return res + + +#: the one profile this serving has: the checkpoint as it is, in BF16 +PROFILE = "lfm25-bf16" + + +def profile_of(path: str) -> str: + """The weights profile the price file is named by: QSE_WEIGHTS when a launcher set it, else BF16's.""" + return os.environ.get("QSE_WEIGHTS") or PROFILE + + +def prices(path: str, log=print): + """StairCut's prior on this chip (ops/prices/lfm2.5-24b-a2b/..json); none yet: + the cut learns online.""" + from engine.methods.device import device_id + from engine.methods.staircut import PriceModel + return PriceModel.load(os.path.join(ROOT, "ops", "prices", MODEL_ID, f"{profile_of(path)}.{device_id()}.json"), + log=log) + + +def lookup_drafter(srv, path: str, corpus: str | None, log=print): + """The lookup cut by StairCut, as on the CUDA board (serving.lookup_drafter).""" + from engine.drafters.ngram import NgramDrafter + from engine.methods.mtp_drafter import MTPTreeDrafter, NoHead + from engine.methods.staircut import StairCut + from engine.tokfp import fingerprint + ng = NgramDrafter(corpus_path=corpus or "", tokenizer_sha=fingerprint(path), min_order=3, max_depth=16, + min_corpus_order=8) + log(f"[server] LFM2 (MLX) lookup drafter: corpus {(corpus or 'none') if ng.corpus is not None else 'none'}") + return MTPTreeDrafter(srv, NoHead(), StairCut(prices(path, log), siblings=False), ng) + + +def serve(a, ctx) -> dict: + """LFM2 MoE from a BF16 checkpoint on the Mac's GPU (the registry's `serve` on Apple silicon, + dispatch.py). `--drafter` other than none: the lookup cut by StairCut, gated by `self_check`.""" + from transformers import AutoTokenizer + + from engine.models.lfm2_moe import mlx_board + from engine.spec import Relax + ctx.keys(a.model, [a.model]) + if a.drafter not in ("none", "mtp"): + ctx.log(f"[server] LFM2 MoE drafts with the lookup: --drafter {a.drafter} taken as the lookup") + if getattr(a, "kv_pool", "off") == "on": + ctx.log("[server] LFM2 (MLX): no KV pool on Apple silicon yet; the window is allocated whole") + tok = AutoTokenizer.from_pretrained(a.model) + t0 = time.time() + _, board = mlx_board.load(a.model, log=ctx.log) + load_s = round(time.time() - t0, 2) + ctx.mark("weights") + srv = Lfm2MoeMLXServing(board, a.max_len) + ctx.mark("engine") + text = tok.apply_chat_template([{"role": "user", "content": "Count from one to twenty in words."}], + tokenize=False, add_generation_prompt=True) + res = self_check(board, tok(text, add_special_tokens=False)["input_ids"], log=ctx.log) + drafter = None + if a.drafter != "none": + if res["ok"]: + drafter = lookup_drafter(srv, a.model, a.corpus, ctx.log) + a.k = max(int(a.k or 0), drafter.cut.max_rows - 1) + else: + ctx.log("[server] LFM2 (MLX) self-check FAILED: speculation off, plain decode only") + ctx.mark("drafters") + describe = (f"LFM2 MoE {a.model} (bf16, MLX on {_chip()}): load {load_s} s, drafter " + f"{'lookup + StairCut' if drafter is not None else 'none'}, max_len {a.max_len:,},") + return {"engine": srv, "tok": tok, "drafter": drafter, "path": a.model, "device": "cpu", + "cfg": None, "w": None, "describe": describe, + "serving": {"tree": drafter is not None, "sampled_tree": "det", "relax": Relax(1.0, 1), + "weights_info": {"format": "bf16", "weights": a.model, "backend": "mlx", + "drafters": "lookup (no draft head)" if drafter is not None else None, + "load_s": load_s, "self_check": res, "exact": res["bitwise"]}}} + + +def _chip() -> str: + from tools.gpu.apple import chip_name + return chip_name() or "Apple silicon" diff --git a/ops/prices/lfm2.5-24b-a2b/lfm25-bf16.apple-m5-max.json b/ops/prices/lfm2.5-24b-a2b/lfm25-bf16.apple-m5-max.json new file mode 100644 index 000000000..b430c7369 --- /dev/null +++ b/ops/prices/lfm2.5-24b-a2b/lfm25-bf16.apple-m5-max.json @@ -0,0 +1,50 @@ +{ + "0": { + "chain": { + "1": 10.203, + "2": 13.808, + "3": 15.855, + "4": 17.474, + "5": 20.435, + "6": 22.303, + "7": 23.837, + "8": 25.122, + "9": 27.922, + "10": 28.966, + "11": 29.963, + "12": 31.104, + "13": 32.276, + "14": 32.822, + "15": 33.336, + "16": 34.625 + }, + "plain": { + "1": 10.261 + } + }, + "16384": { + "chain": { + "1": 10.942, + "2": 14.591, + "3": 16.958, + "4": 18.171, + "5": 22.192, + "6": 23.665, + "7": 25.206, + "8": 26.617, + "9": 30.438, + "10": 31.678, + "11": 32.642, + "12": 33.541, + "13": 34.578, + "14": 35.239, + "15": 36.003, + "16": 36.947 + }, + "plain": { + "1": 10.969 + } + }, + "step_ms": 1.188, + "measured": "tools/mlx_lfm_prices.py: chain = `Lfm2MoeMLX.rows` of 1..16 chain rows with its eval (host wall clock, the median of 7), at a 512-token prompt (class 0) and a 16,384-token one; plain = the decode step's ms a token over 32 tokens. No spec or prime prior: the cut drafts and learns them online." +} diff --git a/server/app.py b/server/app.py index 6c49dc67e..654daa3a9 100644 --- a/server/app.py +++ b/server/app.py @@ -760,7 +760,7 @@ def _slot_disk(): def _lane_run(job) -> None: """One side-lane job on the engine (server/preempt.py `decode`), with the engine held: an open disk-tier write that has not copied the rows the guest writes stops first.""" - from engine.model import h2d + from engine.methods.hostcopy import h2d disk = STATE.get("disk_cache") if disk is not None: try: @@ -2314,7 +2314,7 @@ def _run_round(meet) -> None: at most `max_rows` rows through `forward_tree_multi`, the others (and a pass of one) through the lone `forward_tree` with its graphs.""" from engine.model import forward_tree_multi - from engine.model import h2d + from engine.methods.hostcopy import h2d with meet.cv: groups = meet.batches() meet.pending.clear() @@ -2973,7 +2973,7 @@ def _generate_stream(prompt: torch.Tensor, max_new: int, eos: set[int], think=No (`_par_prefilled`, by the record `on_prefill` carries: `Handler._prefill_watch`), and the record gets the rows it forwarded for its `[req]` line (`rec.fwd`). """ - from engine.model import h2d # not at import: the fake engine's server has no triton + from engine.methods.hostcopy import h2d # not at import: the fake engine's server has no triton eng = STATE["engine"] eng.mm = mm eng.pos_delta = mm.delta if mm is not None else int(pos_delta) @@ -3732,7 +3732,7 @@ def _ask_in_place(eng, pos: int, device, ids: list[int], letters: list[int]) -> where it was: the recurrent state copied back, the KV's length reset (the rows above it are written over by the next forward). The drafter, `ctx` and the client never see it. Under the engine lock, as the request is.""" - from engine.model import h2d + from engine.methods.hostcopy import h2d if pos + len(ids) >= eng.max_len: raise ext_mod.NoRoom("no_room") eng.settle() # as `cache.capture`: a walked state that is not in yet @@ -3769,7 +3769,7 @@ def _force_close(eng, drafter, think, ctx, pos, device, pen=None, pstop=None, sa # it. The forced pass has to carry it, or the closing phrase would be written over its position. # After a dropped end token the KV already holds all of `ctx` (`pos == len(ctx)`) and the # forced pass is the action's tokens alone: `ctx[pos:]` is what the KV does not hold yet. - from engine.model import h2d + from engine.methods.hostcopy import h2d _release_held(sup) # SP2's line, after the block's tokens before the end while True: if act is not None and act.detail.get("ask"): @@ -14270,7 +14270,9 @@ def _warm_prefill(gen, tok, res=None) -> None: words = tok("warm up the kernels ", add_special_tokens=False).input_ids ids = (words * (n // max(1, len(words)) + 1))[:n] t0 = time.time() - list(gen(torch.tensor(ids, dtype=torch.long).cuda(), 2, set())) + # the served model's device (`_serving_state`): "cuda" on a CUDA box, "cpu" for the MLX engine on a Mac, + # whose own arrays live on the GPU (a hard `.cuda()` skipped the warm-up there) + list(gen(torch.tensor(ids, dtype=torch.long, device=STATE.get("device") or "cuda"), 2, set())) if res is not None: res.clear() # the warm-up's rows are nobody's conversation print(f"[server] warm-up prefill of {n} tokens in {time.time() - t0:.1f}s", flush=True) diff --git a/tests/test_gpu_adapters.py b/tests/test_gpu_adapters.py index 10f7024ed..fc9c2462c 100644 --- a/tests/test_gpu_adapters.py +++ b/tests/test_gpu_adapters.py @@ -51,7 +51,7 @@ def test_each_adapter_is_picked_by_its_capability(): for cap, name in OTHERS: assert gpu.profile_for(cap, name).id == "base", (cap, name) assert gpu.profile_for(*GB10) is gpu.profile_for(*GB10), "one profile a (capability, name)" - assert [a.id for a in gpu.ADAPTERS] == ["gb10", "ada"] + assert [a.id for a in gpu.ADAPTERS] == ["gb10", "ada", "apple"] assert gpu.parse_cc("12.1") == (12, 1) and gpu.parse_cc(None) is None and gpu.parse_cc("x") is None return "sm_121 -> gb10, sm_89 -> ada, sm_90 / sm_120 / sm_75 / the CPU -> base" @@ -136,6 +136,36 @@ def test_an_unknown_gpu_and_the_cpu_get_the_base(): return "no inline build, no skinny rows, no PDL; bf16 from sm_80; the name as the device key" +def test_apple_silicon_is_picked_by_name_and_builds_nothing(): + p = gpu.by_name("Apple M5 Max") + assert p.id == "apple" and p.unified_memory and p.bf16() and p.backend() == "mlx" + assert gpu.profile_for(None, None).backend() == "torch" + assert p.device_key() == "apple-m5-max" + assert gpu.profile_for((12, 1), "Apple M5 Max").id == "gb10", "a CUDA capability is never Apple's" + for kind in INLINE: + assert not p.inline(kind), kind + return "by name only; key from the chip; no inline build" + + +def test_the_mac_is_the_current_device_where_there_is_no_cuda_and_the_cpu_stays_the_base(): + """`profile()` without a CUDA device: the Mac's adapter by the chip's name for the current device or an + index, the base for the CPU and for a machine that is not a Mac.""" + import tools.gpu as g + kept, name = dict(g._BY_DEV), g.chip_name + try: + for chip, want in (("Apple M5 Max", "apple"), (None, "base")): + g._BY_DEV.clear() + g.chip_name = lambda chip=chip: chip + if g._index(None) is None: # this machine has no CUDA device + assert g.profile().id == want and g.profile(0).id == want, chip + assert g.profile("cpu").id == "base", chip + finally: + g.chip_name = name + g._BY_DEV.clear() + g._BY_DEV.update(kept) + return "the current device and an index: Apple on a Mac, the base elsewhere; the CPU: the base" + + def test_ada_answers_like_the_base_on_main(): p = gpu.profile_for(*ADA) _base_like(p) diff --git a/tests/test_lfm2_moe_mlx.py b/tests/test_lfm2_moe_mlx.py new file mode 100644 index 000000000..34a25a521 --- /dev/null +++ b/tests/test_lfm2_moe_mlx.py @@ -0,0 +1,620 @@ +"""LFM2 MoE on Apple silicon: the MLX board (engine/models/lfm2_moe/mlx_board.py) against the torch reference. + +The tiny random model of tests/test_lfm2_moe_ref.py runs on both. Held: prefill and decode logits equal +the reference's in fp32 within BOUND; a verify tree's rows equal the sequential decode of each row's +path; a commit of a path that leaves the chain continues as the plain decode; bf16 greedy decode picks +the reference's tokens. Skipped where MLX is not installed (any machine but a Mac). +""" + +from __future__ import annotations + +import functools +import os +import sys + +import numpy as np +import torch + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +try: + import mlx.core as mx +except ImportError: # not a Mac + mx = None + +from tests.test_lfm2_moe_ref import PROMPT, tiny # noqa: E402 + +# fp32 against fp32 torch on the CPU: summation order over 6 layers +BOUND = 1e-4 +#: the block sizes a row kernel is held at, bit for bit against its rows alone: every one from the decode +#: step to 32 rows (docs/kernels.md, "Verify twins"), and one past it +ROWS = tuple(range(1, 34)) +#: 33 rows of 5 distinct inputs: rows that share an input pick the same experts +SHARED = [0] * 10 + [1, 1, 2, 2, 3, 4] + [0, 1, 2, 3, 4, 4, 3, 2, 1, 0, 0, 2, 4, 1, 3, 0, 4] + + +def _skip(why: str): + try: + import pytest + except ImportError: # the box's suite: script mode, no pytest + from scriptmode import Skip + raise Skip(why) from None + pytest.skip(why) + + +def on(device: str): + """A test on MLX's `device`, skipped where MLX is not installed, its random draws seeded. The algebra + tests run on "cpu": on the GPU an fp32 matmul of 2 rows or more is computed at about TF32 precision + (measured on an M5 Max, MLX 0.32.4: 9e-3 off float64 on a 32-wide product whose one-row form is 1e-6 + off), which a 1e-4 bound cannot hold; the "gpu" tests are the bit-for-bit ones.""" + def deco(fn): + @functools.wraps(fn) + def test(): + if mx is None: + _skip("MLX is not installed (Apple silicon only)") + old = mx.default_device() + mx.set_default_device(getattr(mx, device)) + mx.random.seed(0) + try: + return fn() + finally: + mx.set_default_device(old) + return test + return deco + + +def board(dtype=None): + from engine.models.lfm2_moe.mlx_board import Lfm2MoeMLX + cfg, W, ref = tiny() + return cfg, ref, Lfm2MoeMLX.from_torch(cfg, W, dtype or mx.float32) + + +def np_(a) -> np.ndarray: + return np.array(a.astype(mx.float32)) + + +@on("cpu") +def test_conv_taps_follow_the_path(): + from engine.models.lfm2_moe.mlx_board import conv_taps + from engine.models.lfm2_moe.ref import tree_paths + # S = 2: state rows 0, 1; block rows at 2.. ; tree 0 -> {1 -> 2, 3} + t = conv_taps(tree_paths([-1, 0, 1, 0]), 2) + assert t.tolist() == [[0, 1, 2], [1, 2, 3], [2, 3, 4], [1, 2, 5]], t.tolist() + + +@on("cpu") +def test_prefill_and_decode_match_reference(): + cfg, ref, b = board() + st, sm = ref.new_state(64), b.new_state(64) + want, got = ref.prefill(PROMPT, st), np_(b.prefill(PROMPT.numpy(), sm)) + worst = np.abs(got - want.numpy()).max() + assert worst < BOUND, worst + for tok in (11, 50, 3): + d = np.abs(np_(b.decode(tok, sm)) - ref.decode(tok, st).numpy()).max() + assert d < BOUND, d + worst = max(worst, d) + assert sm.length == st.length + + +@on("cpu") +def test_chunked_prefill_equals_one_block(): + cfg, ref, b = board() + s1, s2 = b.new_state(64), b.new_state(64) + a = np_(b.prefill(PROMPT.numpy(), s1)) + c = np_(b.prefill(PROMPT.numpy(), s2, chunk=5)) + assert np.abs(a - c).max() < BOUND + + +@on("cpu") +def test_verify_tree_equals_sequential_decode(): + import copy + cfg, ref, b = board() + st = b.new_state(64) + b.prefill(PROMPT.numpy(), st) + tokens = [7, 19, 23, 44, 31, 60] + parents = [-1, 0, 1, 1, 0, 4] + snap = copy.copy(st) + snap.conv, snap.k, snap.v = dict(st.conv), dict(st.k), dict(st.v) + lg = np_(b.rows(tokens, parents, st)) + assert st.length == snap.length + paths = {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 3], 4: [0, 4], 5: [0, 4, 5]} + for row, path in paths.items(): + s2 = b.new_state(64) + b.prefill(PROMPT.numpy(), s2) + for r in path: + want = np_(b.decode(tokens[r], s2)) + d = np.abs(lg[row] - want[0]).max() + assert d < BOUND, (row, d) + + +@on("cpu") +def test_commit_of_a_path_continues_exactly(): + cfg, ref, b = board() + st, alone = b.new_state(64), b.new_state(64) + b.prefill(PROMPT.numpy(), st) + b.prefill(PROMPT.numpy(), alone) + b.rows([7, 19, 23, 44, 31], [-1, 0, 1, 1, 0], st) + b.commit(st, [0, 1, 3]) + for t in (7, 19, 44): + b.decode(t, alone) + assert st.length == alone.length + d = np.abs(np_(b.decode(5, st)) - np_(b.decode(5, alone))).max() + assert d < BOUND, d + + +@on("cpu") +def test_commit_refuses_a_non_path(): + cfg, ref, b = board() + st = b.new_state(64) + b.prefill(PROMPT.numpy(), st) + b.rows([7, 19, 23], [-1, 0, 0], st) + try: + b.commit(st, [0, 1, 2]) + except ValueError as e: + assert "not a root path" in str(e), e + else: + raise AssertionError("a commit of rows that are no root path went through") + + +@on("gpu") +def test_bf16_greedy_follows_reference(): + """bf16 on the Mac against the fp32 reference, both fed the reference's greedy tokens for 16 steps: + the same argmax wherever the reference's top two are more than TIE apart (bf16 moves this model's + logits, up to 17, by up to about 0.8; a free-running comparison forks at the first near tie).""" + TIE = 1.0 + cfg, ref, b = board(mx.bfloat16) + st, sm = ref.new_state(64), b.new_state(64) + r, m = ref.prefill(PROMPT, st)[-1].numpy(), np_(b.prefill(PROMPT.numpy(), sm))[-1] + for i in range(16): + top2 = np.sort(r)[-2:] + assert r.argmax() == m.argmax() or top2[1] - top2[0] < TIE, (i, top2) + t = int(r.argmax()) + r, m = ref.decode(t, st)[0].numpy(), np_(b.decode(t, sm))[0] + + +@on("cpu") +def test_generate_equals_decode_loop(): + """The pipelined greedy loop writes what one `decode` at a time writes.""" + cfg, ref, b = board() + s1, s2 = b.new_state(64), b.new_state(64) + t0 = int(np_(b.prefill(PROMPT.numpy(), s1))[-1].argmax()) + b.prefill(PROMPT.numpy(), s2) + want, t = [], t0 + for _ in range(10): + t = int(np_(b.decode(t, s1))[0].argmax()) + want.append(t) + assert list(b.generate(t0, s2, 10)) == want + assert s2.length == s1.length + 1 # generate queued one step past the last token read + + +@on("gpu") +def test_gpu_verify_tree_rows_are_the_decode_rows_bit_for_bit(): + """On the GPU in bf16 each row of a draft tree is the sequential decode of its path, bit for bit (the + row-invariant kernels, mlx_kernels.py): greedy speculation writes the plain greedy text.""" + cfg, ref, b = board(mx.bfloat16) + tokens, parents = [7, 19, 23, 44, 31, 60], [-1, 0, 1, 1, 0, 4] + st = b.new_state(64) + b.prefill(PROMPT.numpy(), st) + lg = np_(b.rows(tokens, parents, st)) + paths = {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 3], 4: [0, 4], 5: [0, 4, 5]} + for row, path in paths.items(): + s2 = b.new_state(64) + b.prefill(PROMPT.numpy(), s2) + for r in path: + want = np_(b.decode(tokens[r], s2)) + assert np.array_equal(lg[row], want[0]), (row, np.abs(lg[row] - want[0]).max()) + + +@on("gpu") +def test_gpu_commit_then_decode_is_bit_exact(): + """A tree's path kept, then decoding on: the plain decode's logits bit for bit (conv state and KV rows + moved by the commit are the decode's own).""" + cfg, ref, b = board(mx.bfloat16) + st, alone = b.new_state(64), b.new_state(64) + b.prefill(PROMPT.numpy(), st) + b.prefill(PROMPT.numpy(), alone) + b.rows([7, 19, 23, 44, 31], [-1, 0, 1, 1, 0], st) + b.commit(st, [0, 1, 3]) + for t in (7, 19, 44): + b.decode(t, alone) + for t in (5, 9, 13): + assert np.array_equal(np_(b.decode(t, st)), np_(b.decode(t, alone))), t + + +@on("gpu") +def test_gpu_dense_block_rows_are_its_rows_alone_bit_for_bit(): + """Every tabled projection shape (mlx_kernels.MMA): a block's rows on the scalar chain kernel (few rows) and + on the matrix units (more) are the rows computed one at a time, bit for bit, and close to the fp32 product.""" + from engine.models.lfm2_moe import mlx_kernels as K + for (N, Kd) in K.MMA: + if N * Kd > 5e7: + continue # the head: 0.5 GB of weights a case + w = (mx.random.normal((N, Kd)) * 0.02).astype(mx.bfloat16) + for M in ROWS: + x = mx.random.normal((M, Kd)).astype(mx.bfloat16) + y = K.dense(x, w) + alone = mx.concatenate([K.dense(x[r:r + 1], w) for r in range(M)]) + assert mx.array_equal(y, alone).item(), (N, Kd, M) + ref = x.astype(mx.float32) @ w.astype(mx.float32).T + assert float(mx.abs(y.astype(mx.float32) - ref).max()) < 2e-2 * float(mx.abs(ref).max()), (N, Kd, M) + + +@on("gpu") +def test_gpu_dense_fused_residual_and_fp32_out_are_bit_exact(): + """Fused residual add and direct fp32 output in rowchain/rowmma are bit-for-bit row-invariant.""" + from engine.models.lfm2_moe import mlx_kernels as K + w = (mx.random.normal((2048, 2048)) * 0.02).astype(mx.bfloat16) + for M in ROWS: + x = mx.random.normal((M, 2048)).astype(mx.bfloat16) + res = mx.random.normal((M, 2048)).astype(mx.bfloat16) + y = K.dense(x, w, res=res) + alone = mx.concatenate([K.dense(x[r:r + 1], w, res=res[r:r + 1]) for r in range(M)]) + assert mx.array_equal(y, alone).item(), ("res", M) + y32 = K.dense(x, w, out_dtype=mx.float32) + alone32 = mx.concatenate([K.dense(x[r:r + 1], w, out_dtype=mx.float32) for r in range(M)]) + assert mx.array_equal(y32, alone32).item(), ("fp32", M) + + +@on("gpu") +def test_gpu_flash_path_attention_is_bit_exact(): + """Split-K FlashAttention-2 path_attention (D=64, GQA=4, bf16) is bit-for-bit identical between + a 16-node branching tree and single-row sequential decode across BT=32 and BK=256 boundaries.""" + from engine.models.lfm2_moe import mlx_kernels as K + from engine.models.lfm2_moe.ref import tree_paths + Hk, Hq, D, gqa = 8, 32, 64, 4 + parents = [-1, 0, 1, 2, 1, 4, 0, 6, 7, 8, 6, 0, 11, 12, 2, 14] + paths = tree_paths(parents) + M, A = len(parents), max(len(p) for p in paths) + anc_np = np.zeros((M, A), dtype=np.int32) + for i, pa in enumerate(paths): + anc_np[i, :len(pa)] = pa + anc = mx.array(anc_np) + dlen = mx.array([len(p) for p in paths], dtype=mx.int32) + for L in (0, 30, 254, 513): + cap = L + M + 8 + kc = mx.random.normal((Hk, cap, D)).astype(mx.bfloat16) + vc = mx.random.normal((Hk, cap, D)).astype(mx.bfloat16) + q = mx.random.normal((M, Hq, D)).astype(mx.bfloat16) + out_tree = K.path_attention(q, kc, vc, anc, dlen, L, gqa) + for r, pa in enumerate(paths): + k_seq = mx.concatenate([kc[:, :L], kc[:, L + mx.array(pa, dtype=mx.int32)]], axis=1) + v_seq = mx.concatenate([vc[:, :L], vc[:, L + mx.array(pa, dtype=mx.int32)]], axis=1) + out_dec = K.path_attention(q[r:r + 1], k_seq, v_seq, mx.array([[0]], dtype=mx.int32), + mx.array([1], dtype=mx.int32), L + len(pa) - 1, gqa) + assert mx.array_equal(out_tree[r:r + 1], out_dec).item(), (L, r, pa) + + +@on("gpu") +def test_gpu_path_attention_rows_are_its_rows_alone_at_every_block_size(): + """A chain block of every size in ROWS: each row's attention is the one-row call at its own position, bit + for bit, at context lengths on both sides of the 256-token chunk (one chunk, the chunk-then-reduce path).""" + from engine.models.lfm2_moe import mlx_kernels as K + Hk, Hq, D, gqa = 8, 32, 64, 4 + one, d1 = mx.array([[0]], dtype=mx.int32), mx.array([1], dtype=mx.int32) + for L in (0, 250, 600): + cap = L + max(ROWS) + 8 + kc = mx.random.normal((Hk, cap, D)).astype(mx.bfloat16) + vc = mx.random.normal((Hk, cap, D)).astype(mx.bfloat16) + qs = mx.random.normal((max(ROWS), Hq, D)).astype(mx.bfloat16) + alone = mx.concatenate([K.path_attention(qs[r:r + 1], kc, vc, one, d1, L + r, gqa) for r in range(max(ROWS))]) + for M in ROWS: + anc = mx.array(np.tril(np.tile(np.arange(M, dtype=np.int32), (M, 1)))) + dlen = mx.arange(1, M + 1, dtype=mx.int32) + out = K.path_attention(qs[:M], kc, vc, anc, dlen, L, gqa) + assert mx.array_equal(out, alone[:M]).item(), (L, M) + + +@on("gpu") +def test_gpu_conv_gate_rows_are_the_decode_steps_at_every_block_size(): + """The short conv of a chain block of every size in ROWS: each row is the decode step's (`next_state`), + walked one row at a time from the same state, bit for bit.""" + from engine.models.lfm2_moe import mlx_kernels as K + H, Kt = 256, 3 + cw = (mx.random.normal((H, Kt)) * 0.3).astype(mx.bfloat16) + state0 = mx.random.normal((Kt - 1, H)).astype(mx.bfloat16) + bcx = mx.random.normal((max(ROWS), 3 * H)).astype(mx.bfloat16) + steps, st = [], state0 + for r in range(max(ROWS)): + cy, st = K.conv_gate(bcx[r:r + 1], st, cw, None, next_state=True) + mx.eval(cy, st) + steps.append(cy) + steps = mx.concatenate(steps) + for M in ROWS: + cy, _ = K.conv_gate(bcx[:M], state0, cw) + assert mx.array_equal(cy, steps[:M]).item(), M + + +@on("gpu") +def test_gpu_qkv_norm_rope_rows_are_its_rows_alone_at_every_block_size(): + """The fused q/k norm and rotary of a block of every size in ROWS: each row is the one-row call's, bit for + bit (q, k and v).""" + from engine.models.lfm2_moe import mlx_kernels as K + Hq, Hk, D = 32, 8, 64 + n = max(ROWS) + qkv = mx.random.normal((n, (Hq + 2 * Hk) * D)).astype(mx.bfloat16) + qn = (mx.random.normal((D,)) * 0.2 + 1.0).astype(mx.bfloat16) + kn = (mx.random.normal((D,)) * 0.2 + 1.0).astype(mx.bfloat16) + cos = mx.random.normal((n, 1, D)).astype(mx.bfloat16) + sin = mx.random.normal((n, 1, D)).astype(mx.bfloat16) + alone = [K.qkv_norm_rope(qkv[r:r + 1], qn, kn, cos[r:r + 1], sin[r:r + 1], Hq, Hk, D, 1e-5) for r in range(n)] + q1 = mx.concatenate([a[0] for a in alone]) + k1 = mx.concatenate([a[1] for a in alone], axis=1) + v1 = mx.concatenate([a[2] for a in alone], axis=1) + for M in ROWS: + q, k, v = K.qkv_norm_rope(qkv[:M], qn, kn, cos[:M], sin[:M], Hq, Hk, D, 1e-5) + assert mx.array_equal(q, q1[:M]).item() and mx.array_equal(k, k1[:, :M]).item() \ + and mx.array_equal(v, v1[:, :M]).item(), M + + +@on("gpu") +def test_gpu_moe_fast_is_bit_exact(): + """Fused MoE fast path (moegate + moeroute + moemm_r1/moemm_hyb + moewsum) is bit-for-bit row-invariant + across ns=1, ns=2, and ns>=3..10 (MMA) simultaneously.""" + from engine.models.lfm2_moe import mlx_kernels as K + H, E, I = 256, 16, 128 + nw = mx.ones((H,), dtype=mx.bfloat16) + gw = (mx.random.normal((E, H)) * 0.1).astype(mx.bfloat16) + bias = (mx.random.normal((E,)) * 0.1).astype(mx.float32) + w13 = (mx.random.normal((E, 2 * I, H)) * 0.05).astype(mx.bfloat16) + w2 = (mx.random.normal((E, H, I)) * 0.05).astype(mx.bfloat16) + base = mx.random.normal((5, H)).astype(mx.bfloat16) + h32 = base[mx.array(SHARED, dtype=mx.int32)] + for M in ROWS[1:]: + hm = h32[:M] + ym = K.moe_fast(hm, nw, gw, bias, w13, w2, 1e-5, 4, 1.0, True) + alone = mx.concatenate([K.moe_fast(hm[r:r + 1], nw, gw, bias, w13, w2, 1e-5, 4, 1.0, True) for r in range(M)]) + assert mx.array_equal(ym, alone).item(), M + + +@on("gpu") +def test_gpu_swizzle_roundtrip_and_dense_swiz_bit_exact(): + """512B-coalesced weight swizzle roundtrips exactly, and dense_swiz (plain, FUSE_RMS, ADD_RES) + is bit-for-bit identical between rowchain_swiz (M<=2) and rowmma_swiz (M>=3).""" + from engine.models.lfm2_moe import mlx_kernels as K + for N, Kd in ((64, 128), (128, 256), (384, 128)): + w = (mx.random.normal((N, Kd)) * 0.02).astype(mx.bfloat16) + ws = K.swizzle_dense(w) + assert mx.array_equal(K.unswizzle_dense(ws, N, Kd), w).item(), (N, Kd) + nw = (mx.random.normal((Kd,)) * 0.2 + 1.0).astype(mx.bfloat16) + for M in ROWS: + x = mx.random.normal((M, Kd)).astype(mx.bfloat16) + res = mx.random.normal((M, N)).astype(mx.bfloat16) + # Plain + y = K.dense_swiz(x, ws, N, Kd) + alone = mx.concatenate([K.dense_swiz(x[r:r + 1], ws, N, Kd) for r in range(M)]) + assert mx.array_equal(y, alone).item(), ("plain", N, Kd, M) + ref = x.astype(mx.float32) @ w.astype(mx.float32).T + assert float(mx.abs(y.astype(mx.float32) - ref).max()) < 2e-2 * float(mx.abs(ref).max()) + # Fused RMSNorm + yr = K.dense_swiz(x, ws, N, Kd, nw=nw, eps=1e-5) + aloner = mx.concatenate([K.dense_swiz(x[r:r + 1], ws, N, Kd, nw=nw, eps=1e-5) for r in range(M)]) + assert mx.array_equal(yr, aloner).item(), ("rms", N, Kd, M) + # Fused residual add + ya = K.dense_swiz(x, ws, N, Kd, res=res) + alonea = mx.concatenate([K.dense_swiz(x[r:r + 1], ws, N, Kd, res=res[r:r + 1]) for r in range(M)]) + assert mx.array_equal(ya, alonea).item(), ("add", N, Kd, M) + + +@on("gpu") +def test_gpu_moe_fast_swiz_is_bit_exact(): + """512B-coalesced swizzled MoE pipeline (moegate_rms + moeroute + moemm_r1_swiz/moemm_w2add_swiz vs + moemm_hyb_swiz + moewsum) roundtrips weights and is bit-for-bit row-invariant at every block size in ROWS.""" + from engine.models.lfm2_moe import mlx_kernels as K + H, E, I = 256, 16, 128 + nw = (mx.random.normal((H,)) * 0.2 + 1.0).astype(mx.bfloat16) + gw = (mx.random.normal((E, H)) * 0.1).astype(mx.bfloat16) + bias = (mx.random.normal((E,)) * 0.1).astype(mx.float32) + w13 = (mx.random.normal((E, 2 * I, H)) * 0.05).astype(mx.bfloat16) + w2 = (mx.random.normal((E, H, I)) * 0.05).astype(mx.bfloat16) + w13s = K.swizzle_moe_w13(w13) + w2s = K.swizzle_moe_w2(w2) + assert mx.array_equal(K.unswizzle_moe_w13(w13s, E, I, H), w13).item() + assert mx.array_equal(K.unswizzle_moe_w2(w2s, E, H, I), w2).item() + base = mx.random.normal((5, H)).astype(mx.bfloat16) + h32 = base[mx.array(SHARED, dtype=mx.int32)] + for M in ROWS[1:]: + hm = h32[:M] + ym = K.moe_fast_swiz(hm, nw, gw, bias, w13s, w2s, I, 1e-5, 4, 1.0, True) + alone = mx.concatenate([K.moe_fast_swiz(hm[r:r + 1], nw, gw, bias, w13s, w2s, I, 1e-5, 4, 1.0, True) + for r in range(M)]) + assert mx.array_equal(ym, alone).item(), M + ref = K.moe_fast(hm, nw, gw, bias, w13, w2, 1e-5, 4, 1.0, True) + assert float(mx.abs(ym.astype(mx.float32) - ref.astype(mx.float32)).max()) < 0.05 * float(mx.abs(ref.astype(mx.float32)).max()) + + +def _swiz_board(**over): + """A tiny random BF16 board whose shapes take the swizzled row kernels (the served layout). `over` + changes the config: head_dim=64 with 8 query and 2 key heads is the served attention shape (GQA 4).""" + from engine.models.lfm2_moe.config import config_from_dict + from engine.models.lfm2_moe.mlx_board import Lfm2MoeMLX + from tests.test_lfm2_moe_ref import TINY, _random_weights + raw = dict(TINY, vocab_size=64, hidden_size=128, intermediate_size=128, moe_intermediate_size=64, + num_hidden_layers=4, num_attention_heads=4, num_key_value_heads=2, head_dim=32, + layer_types=["conv", "full_attention", "conv", "full_attention"], + num_dense_layers=1, num_experts=8, num_experts_per_tok=4) + raw.update(over) + cfg = config_from_dict(raw) + b = Lfm2MoeMLX.from_torch(cfg, _random_weights(cfg, seed=7), mx.bfloat16) + assert b._swiz is True + return b + + +def _served_board(): + return _swiz_board(hidden_size=256, num_attention_heads=8, num_key_value_heads=2, head_dim=64) + + +@on("gpu") +def test_gpu_swizzled_board_verify_tree_and_batched_prefill(): + """End to end on the swizzled board: a verify tree's rows are the sequential decode's, bit for bit; a + prompt past ROWS_MAX takes the batched path and gives finite logits of the right shape.""" + b = _swiz_board() + # 1. Verify tree matches sequential decode bit for bit + prompt = np.array([1, 5, 9, 13, 17], dtype=np.int32) + tokens, parents = [7, 19, 23, 44, 31, 60], [-1, 0, 1, 1, 0, 4] + st = b.new_state(128) + b.prefill(prompt, st) + lg = np_(b.rows(tokens, parents, st)) + paths = {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 3], 4: [0, 4], 5: [0, 4, 5]} + for row, path in paths.items(): + s2 = b.new_state(128) + b.prefill(prompt, s2) + for r in path: + want = np_(b.decode(tokens[r], s2)) + assert np.array_equal(lg[row], want[0]), (row, np.abs(lg[row] - want[0]).max()) + # 2. a prompt of 70 rows (past ROWS_MAX): the batched kernels + long_prompt = np.arange(70, dtype=np.int32) % 64 + sb = b.new_state(128) + lg_batched = np_(b.prefill(long_prompt, sb)) + assert lg_batched.shape == (70, 64) and np.isfinite(lg_batched).all() + + +@on("gpu") +def test_gpu_self_check_holds_bits_on_chains_a_tree_and_a_long_prompt(): + """The load-time gate (mlx_serving.self_check): `ok` is `bitwise`, over the greedy chain, the chains of + CHECK_CHAINS rows and the tree after a prompt longer than one attention chunk.""" + from engine.models.lfm2_moe import mlx_serving as S + res = S.self_check(_swiz_board(), [int(t) for t in np.arange(20) % 64], steps=24, log=None) + assert res["ok"] and res["bitwise"] and res["picks"] and res["max_diff"] == 0.0, res + assert res["rows"] == 24 + sum(S.CHECK_CHAINS) + len(S.CHECK_TREE[0]) and res["first_diff"] is None, res + assert {3, 4, 32} <= set(S.CHECK_CHAINS), "the 4-row attention and router variants, and the cut's widest block" + + +@on("gpu") +def test_gpu_self_check_refuses_one_unit_in_one_row(): + """The gate itself: a verify row that differs from the decode step's in one logit's last place, with the + same greedy pick, fails the check and names the row.""" + from engine.models.lfm2_moe import mlx_serving as S + b = _swiz_board() + real, calls = b.rows, [] + + def rows(tokens, parents, st, last_only=False): + out = np.array(real(tokens, parents, st, last_only=last_only)) + calls.append(len(tokens)) + if len(calls) == 2 and not last_only: # call 1 is the prompt's prefill + j = int(np.argmin(out[3])) # not the pick + out[3, j] = np.nextafter(out[3, j], np.float32(np.inf)) + return mx.array(out) + + b.rows = rows + res = S.self_check(b, [int(t) for t in np.arange(20) % 64], steps=24, log=None) + assert res["ok"] is False and res["bitwise"] is False and res["first_diff"] == 3, res + assert res["max_diff"] > 0.0 and res["picks"] is True, res + + +@on("gpu") +def test_gpu_served_attention_shape_rows_are_the_decode_steps(): + """The served attention shape (head_dim 64, GQA 4: the compiled flash path, `_compiled_attn`) through + the whole board, after a prompt past the 256-token chunk: chains up to ROWS_MAX rows and a tree are the + sequential decode's rows, bit for bit.""" + from engine.models.lfm2_moe import mlx_kernels as K + b = _served_board() + prompt = [int(t) for t in (np.arange(300) * 7) % 64] + st = b.new_state(300 + K.ROWS_MAX + 8) + lg = b.prefill(prompt, st, last_only=True) + L, conv = st.length, dict(st.conv) + toks, want = [int(mx.argmax(lg[-1]).item())], [] + for _ in range(K.ROWS_MAX): + want.append(np.array(b.decode(toks[-1], st)[0])) + toks.append(int(want[-1].argmax())) + for M in (1, 2, 3, 4, 5, 8, 9, 16, 17, 32, 33, K.ROWS_MAX): + st.length, st.conv = L, dict(conv) + got = np.array(b.rows(toks[:M], list(range(-1, M - 1)), st)) + for r in range(M): + assert got[r].tobytes() == want[r].tobytes(), (M, r) + assert b._attn_cc, "the compiled flash attention never ran: the board took the fallback kernel" + tokens, parents = [7, 19, 23, 44, 31, 60], [-1, 0, 1, 1, 0, 4] + st.length, st.conv = L, dict(conv) + got = np.array(b.rows(tokens, parents, st)) + for row, path in {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 3], 4: [0, 4], 5: [0, 4, 5]}.items(): + st.length, st.conv = L, dict(conv) + for r in path: + out = np.array(b.decode(tokens[r], st)[0]) + assert got[row].tobytes() == out.tobytes(), row + + +@on("gpu") +def test_gpu_dense_swiglu_and_embed_rows_are_their_rows_alone_at_every_block_size(): + """The dense MLP's fused gate and up projection and the embedding lookup on the swizzled layout: a block + of every size in ROWS is its rows one at a time, bit for bit.""" + from engine.models.lfm2_moe import mlx_kernels as K + H, I, n = 128, 192, max(ROWS) + w13 = K.swizzle_moe_w13((mx.random.normal((1, 2 * I, H)) * 0.05).astype(mx.bfloat16)) + x = mx.random.normal((5, H)).astype(mx.bfloat16)[mx.array(SHARED, dtype=mx.int32)] + alone = mx.concatenate([K.dense_swiglu_swiz(x[r:r + 1], w13, I, H) for r in range(n)]) + emb = (mx.random.normal((64, H))).astype(mx.bfloat16) + ws = K.swizzle_dense(emb) + toks = mx.array([(7 * i) % 64 for i in range(n)], dtype=mx.int32) + for M in ROWS: + assert mx.array_equal(K.dense_swiglu_swiz(x[:M], w13, I, H), alone[:M]).item(), ("swiglu", M) + assert mx.array_equal(K.embed_swiz(toks[:M], ws, H), emb[toks[:M]]).item(), ("embed", M) + + +@on("gpu") +def test_gpu_serving_comes_back_from_an_in_place_ask(): + """The server's in-place ask (server/app.py `_ask_in_place`): settle, forward a hidden question, + `resume_at` the kept length. The next step is the one a serving that was never asked makes, bit for + bit: the conv states come back, not only the length. A length nothing kept is refused.""" + from engine.models.lfm2_moe.mlx_serving import Lfm2MoeMLXServing + prompt = torch.tensor([int(t) for t in np.arange(20) % 64]) + asked, plain = Lfm2MoeMLXServing(_swiz_board(), 128), Lfm2MoeMLXServing(_swiz_board(), 128) + for srv in (asked, plain): + srv.forward(prompt, start=0) + asked.settle() + n = asked.kv.length + asked.forward(torch.tensor([5, 9, 11, 3]), start=n) + asked.resume_at(n) + assert asked.kv.length == n + a, b = asked.forward(torch.tensor([7]), start=n), plain.forward(torch.tensor([7]), start=n) + assert torch.equal(a, b), float((a - b).abs().max()) + for bad in (lambda: asked.resume_at(n - 3), lambda: setattr(asked.kv, "length", n - 3)): + try: + bad() + except ValueError: + continue + raise AssertionError("a length nothing kept went through") + block = torch.arange(65) % 64 + try: + asked.forward_tree(block, list(range(-1, 64)), start=asked.kv.length) + except ValueError as e: + assert "exceeds the row kernels" in str(e), e + else: + raise AssertionError("a verify block past ROWS_MAX went through") + + +def test_the_lfm2_family_picks_its_serving_by_the_adapters_backend(): + """engine/models/lfm2_moe/dispatch.py: the MLX serving where the device's adapter answers "mlx", the + CUDA serving for "torch"; neither module is imported for the other's device.""" + import types + import tools.gpu as g + from engine.models.lfm2_moe import dispatch + names = ("engine.models.lfm2_moe.mlx_serving", "engine.models.lfm2_moe.serving") + kept, real, pkg = {n: sys.modules.get(n) for n in names}, g.profile, sys.modules["engine.models.lfm2_moe"] + attrs = {n: getattr(pkg, n.rsplit(".", 1)[1], None) for n in names} + try: + for n in names: + short = n.rsplit(".", 1)[1] + m = types.ModuleType(n) + m.serve = lambda a, ctx, short=short: {"by": short} + sys.modules[n] = m + setattr(pkg, short, m) + for backend, want in (("mlx", "mlx_serving"), ("torch", "serving")): + g.profile = lambda device=None, backend=backend: types.SimpleNamespace(backend=lambda: backend) + assert dispatch.serve(None, None) == {"by": want}, backend + finally: + g.profile = real + for n in names: + short = n.rsplit(".", 1)[1] + if kept[n] is None: + sys.modules.pop(n, None) + else: + sys.modules[n] = kept[n] + if attrs[n] is None: + if hasattr(pkg, short): + delattr(pkg, short) + else: + setattr(pkg, short, attrs[n]) + + +if __name__ == "__main__": + from scriptmode import run + run(globals()) diff --git a/tools/gpu/README.md b/tools/gpu/README.md index 8f8e97a68..9a6b1a773 100644 --- a/tools/gpu/README.md +++ b/tools/gpu/README.md @@ -10,6 +10,7 @@ tools/gpu/ base.py GpuProfile: every question, answered for a GPU without an adapter and for the CPU gb10.py sm_121a (DGX Spark): the reference GPU, every inline extension ada.py sm_89: the base's answers until its kernels land; the place an Ada port fills in + apple.py Apple silicon (Metal through MLX): no CUDA and no Triton; the models that have an MLX board ``` ## How it works @@ -31,6 +32,10 @@ The base builds no inline CUDA extension. A module whose only path is one raises its first build, and the error names the GPU. `profile_for(cap, name)` gives the same adapters without torch. +A machine without CUDA has no capability to read. There `profile()` asks for the chip's name +(`apple.chip_name`, a `sysctl` read once a process, on macOS only): an Apple silicon Mac gets `apple.py` +for its current device, and the CPU or any other machine gets the base, as before. + The CUDA sources keep their per-architecture code. The adapter picks the extension, its arch flags and its launch shape. @@ -50,6 +55,7 @@ its launch shape. | `exl3_probe(device, kb)`, `exl3_rot_ok`, `exl3_decode_ok`, `exl3_gemv_ok` | the Triton EXL3 kernels' load probes and verdicts (`tools/exl3_ada.py`) | -- | none / raise unprobed | | `moe_probe(device)`, `moe_ok(device)` | the Triton MoE kernels' load probe and verdict (`tools/moe_ada.py`) | -- | none / False unprobed | | `device_key()` | per-device files (`engine/methods/device.py`, price tables) | `dgx-spark` | the GPU's name with dashes, `cpu` | +| `backend()` | a family's server builder that has more than one engine (`engine/models/lfm2_moe/dispatch.py`) | `torch` | `torch` (`apple.py`: `mlx`) | | `unified_memory` | readers of the memory model | yes | no | `key_matches(key, name)` tells the setup page whether a preset measured under `key` belongs to a GPU of @@ -88,6 +94,7 @@ Moved: each now asks the profile. | `tools/nvfp4_skinny.py` `use_skinny`, `tools/iq2_linear.py` `NVFP4Linear.matmul` | the NVFP4 register-fed kernel's rows | | `engine/decision/laya/model.py` | BF16 or FP16 autocast | | `engine/methods/device.py` `device_id` | the key of per-device files | +| `engine/models/lfm2_moe/dispatch.py` `serve` | the array library the family's engine runs on (the MLX board on Apple silicon) | | `server/setup/device.py` `preset` | whether a measured preset belongs to this GPU | | `tools/gate/hw` (and `tools/release_report`, which reads it) | which sizing profile a box gets, and the torch probe | | `install.sh` | the skinny kernel's switch off the Spark, now the adapter's answer | diff --git a/tools/gpu/__init__.py b/tools/gpu/__init__.py index 006788bfa..d91d6ecca 100644 --- a/tools/gpu/__init__.py +++ b/tools/gpu/__init__.py @@ -13,6 +13,7 @@ from __future__ import annotations from tools.gpu.ada import Ada +from tools.gpu.apple import AppleSilicon, chip_name from tools.gpu.base import INLINE, GpuProfile, NoInlineBuild from tools.gpu.gb10 import GB10 @@ -20,7 +21,7 @@ "by_name", "capability", "key_matches", "parse_cc", "profile", "profile_for"] #: adapters in the order they are asked; the base answers for any GPU none claims, and for the CPU -ADAPTERS: tuple[type[GpuProfile], ...] = (GB10, Ada) +ADAPTERS: tuple[type[GpuProfile], ...] = (GB10, Ada, AppleSilicon) #: what a box's GPU is, printed as JSON by the engine's interpreter (tools/gate/hw `detect`) PROBE = ( @@ -96,14 +97,18 @@ def capability(device=None) -> tuple | None: def profile(device=None) -> GpuProfile: - """The adapter for `device`, picked once and kept (the current device's when None).""" + """The adapter for `device`, picked once and kept (the current device's when None). Without a CUDA device: + Apple silicon's for the current device or an index on a Mac (by the chip's name), the base for the CPU and + everywhere else.""" try: return _BY_DEV[device] except (KeyError, TypeError): pass idx = _index(device) if idx is None: - got = profile_for(None, None) + # no CUDA device: asked for the current device or a device index, the Mac's GPU where there is + # one (tools/gpu/apple.py); asked for the CPU, or no Mac, the base + got = profile_for(None, chip_name() if device is None or isinstance(device, int) else None) else: import torch got = profile_for(capability(idx), torch.cuda.get_device_name(idx)) diff --git a/tools/gpu/apple.py b/tools/gpu/apple.py new file mode 100644 index 000000000..a980b0f48 --- /dev/null +++ b/tools/gpu/apple.py @@ -0,0 +1,54 @@ +"""Apple silicon (M-series, Metal through MLX): unified memory, no CUDA, no Triton. + +The Mac runs the models that have an MLX board (engine/models/lfm2_moe/mlx_board.py) and nothing that +needs an inline CUDA extension or a Triton kernel: every `INLINE` kind raises `NoInlineBuild`, as on the +base. Claimed by name ("Apple M5 Max", from `chip_name`), never by a CUDA capability, so it is picked only +where torch has no CUDA device. Per-device files are keyed by the chip's name ("apple-m5-max"): a price +table measured on one chip is not another's. + +Measured on an M5 Max (MLX 0.32.4): an fp32 matmul of 2 rows or more runs at about TF32 precision on the +GPU (one row is exact), so MLX's own matmul rounds a verify row and a decode row of the same token +differently. The board therefore runs its own Metal kernels, whose rows do not depend on the row count +(engine/models/lfm2_moe/mlx_kernels.py); the tests hold a block's rows to its rows alone, bit for bit +(tests/test_lfm2_moe_mlx.py). +""" + +from __future__ import annotations + +import functools +import platform +import subprocess + +from tools.gpu.base import GpuProfile + + +def is_apple_silicon() -> bool: + return platform.system() == "Darwin" and platform.machine() == "arm64" + + +@functools.lru_cache(maxsize=None) +def chip_name() -> str | None: + """"Apple M5 Max" on Apple silicon, None elsewhere (sysctl, no torch or MLX import).""" + if not is_apple_silicon(): + return None + try: + return subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True, + timeout=5).stdout.strip() or "Apple silicon" + except (OSError, subprocess.SubprocessError): + return "Apple silicon" + + +class AppleSilicon(GpuProfile): + id = "apple" + about = "Apple silicon (Metal via MLX): unified memory, MLX boards only, no inline CUDA or Triton" + names = ("APPLE",) + unified_memory = True + + def label(self) -> str: + return self.name or "Apple silicon" + + def backend(self) -> str: + return "mlx" + + def bf16(self) -> bool: + return True diff --git a/tools/gpu/base.py b/tools/gpu/base.py index 9093ef91e..2ba226b87 100644 --- a/tools/gpu/base.py +++ b/tools/gpu/base.py @@ -17,6 +17,7 @@ fp8_rows(N, K, bn) (N tile, K tile, warps, stages) of the FP8 row kernel fp8_row_tile(M) rows one program of the FP8 row kernel covers device_key() the key of the per-device files measured on this GPU (price tables) + backend() the array library the models run on here: "torch" (CUDA or the CPU) or "mlx" unified_memory the GPU shares the host's memory """ @@ -70,6 +71,11 @@ def device_key(self) -> str: return "cpu" return re.sub(r"[^a-z0-9]+", "-", self.name.lower()).strip("-") + def backend(self) -> str: + """The array library a model's engine runs on with this device: "torch" (CUDA, the CPU), or + "mlx" (Apple silicon, tools/gpu/apple.py). A family's server builder picks its engine by it.""" + return "torch" + # -- builds ----------------------------------------------------------------------------- def arch_flags(self, kind: str) -> list[str]: """The nvcc arch flags inline extension `kind` builds with here.""" diff --git a/tools/mlx_lfm_bench.py b/tools/mlx_lfm_bench.py new file mode 100644 index 000000000..894a5c140 --- /dev/null +++ b/tools/mlx_lfm_bench.py @@ -0,0 +1,84 @@ +"""LFM2.5 on the Mac's GPU (engine/models/lfm2_moe/mlx_board.py): greedy text, speed, and the logits against +mlx-lm's own lfm2_moe. + + .venv-mac/bin/python tools/mlx_lfm_bench.py [--tokens 256] [--prompt-len 512] [--check] + +Prints the greedy continuation of a chat prompt, the prefill rate of a `--prompt-len` prompt and the decode +rate of `--tokens` greedy tokens (one request, plain decode, no drafting). `--check` also loads mlx-lm's +model on the same checkpoint and compares the last-row logits of a prompt (max |diff|, top-1, top-5 overlap). +""" + +from __future__ import annotations + +import argparse +import gc +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import mlx.core as mx # noqa: E402 +import numpy as np # noqa: E402 + +from engine.models.lfm2_moe import mlx_board # noqa: E402 + +CHAT = [{"role": "user", "content": "Explain in three short paragraphs why the sky is blue."}] + + +def greedy(board, cfg, ids: list[int], n: int, cap: int): + """(tokens, prefill seconds, decode seconds) of a greedy run on the pipelined loop.""" + st = board.new_state(cap) + t0 = time.perf_counter() + lg = board.prefill(ids, st, last_only=True) + first = int(mx.argmax(lg[-1]).item()) + t1 = time.perf_counter() + out = [first] + if first not in cfg.eos_token_ids: + out += list(board.generate(first, st, n - 1, stop=set(cfg.eos_token_ids))) + return out, t1 - t0, time.perf_counter() - t1 + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("path") + ap.add_argument("--tokens", type=int, default=256) + ap.add_argument("--prompt-len", type=int, default=512) + ap.add_argument("--check", action="store_true") + a = ap.parse_args() + + from transformers import AutoTokenizer + tok = AutoTokenizer.from_pretrained(a.path) + t0 = time.perf_counter() + cfg, board = mlx_board.load(a.path) + print(f"load {time.perf_counter() - t0:.1f} s, peak {mx.get_peak_memory() / 1e9:.1f} GB") + + text = tok.apply_chat_template(CHAT, add_generation_prompt=True, tokenize=False) + ids = tok.encode(text, add_special_tokens=False) + greedy(board, cfg, ids, 4, 4096) # warm-up: kernels compiled + out, _, dt = greedy(board, cfg, ids, a.tokens, 4096) + print("---\n" + tok.decode(out) + "\n---") + print(f"decode: {len(out) - 1} tokens in {dt:.2f} s = {(len(out) - 1) / dt:.1f} tok/s") + + long_ids = (tok.encode(open(__file__).read()) * 64)[:a.prompt_len] + _, pf, _ = greedy(board, cfg, long_ids, 1, a.prompt_len + 64) + print(f"prefill: {a.prompt_len} tokens in {pf:.2f} s = {a.prompt_len / pf:.0f} tok/s") + print(f"peak memory {mx.get_peak_memory() / 1e9:.1f} GB") + + if a.check: + st = board.new_state(len(ids) + 8) + mine = np.array(board.prefill(ids, st, last_only=True)[-1]) + del board, st + gc.collect() + mx.clear_cache() + from mlx_lm import load as lm_load + model, _ = lm_load(a.path) + theirs = np.array(model(mx.array([ids]))[0, -1].astype(mx.float32)) + t5m, t5t = set(np.argsort(-mine)[:5]), set(np.argsort(-theirs)[:5]) + print(f"vs mlx-lm: max |diff| {np.abs(mine - theirs).max():.3f} (logits up to {np.abs(theirs).max():.1f}), " + f"top-1 {'same' if mine.argmax() == theirs.argmax() else 'DIFFERENT'}, top-5 overlap {len(t5m & t5t)}/5") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mlx_lfm_exact.py b/tools/mlx_lfm_exact.py new file mode 100644 index 000000000..deda9a7b5 --- /dev/null +++ b/tools/mlx_lfm_exact.py @@ -0,0 +1,64 @@ +"""LFM2.5 on the Mac's GPU (engine/models/lfm2_moe/mlx_board.py): its verify rows against the decode step on the +real checkpoint, bit for bit. + + .venv-mac/bin/python tools/mlx_lfm_exact.py + +A 12-row tree and chains of 16, 5 and 3 rows are verified as one block each after a 300-token prompt; every row +is then recomputed by decoding its path one token at a time from a fresh state, and the two logit rows are +compared with `array_equal`. Exit code 1 when a row differs. +""" + +from __future__ import annotations + +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import numpy as np # noqa: E402 + +from engine.models.lfm2_moe import mlx_board # noqa: E402 +from engine.models.lfm2_moe.ref import chain # noqa: E402 + +BLOCKS = [([7, 19, 23, 44, 31, 60, 88, 91, 5, 17, 300, 4000], [-1, 0, 1, 1, 0, 4, 5, 5, 2, 8, 9, 3]), + (list(range(50, 66)), chain(16)), (list(range(200, 205)), chain(5)), ([9, 8, 7], chain(3))] + + +def exact(board) -> tuple[int, int]: + """(rows compared, rows that differ in any bit) of `BLOCKS` against sequential decode.""" + prompt = list(range(1000, 1300)) + + def fresh(): + st = board.new_state(400) + board.prefill(prompt, st, last_only=True) + return st + + n = bad = 0 + for tokens, parents in BLOCKS: + lg = np.array(board.rows(tokens, parents, fresh())) + for row in range(len(tokens)): + path, r = [], row + while r >= 0: + path.append(r) + r = parents[r] + st = fresh() + for r in reversed(path): + want = np.array(board.decode(tokens[r], st)) + n += 1 + bad += not np.array_equal(lg[row], want[0]) + return n, bad + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("path") + a = ap.parse_args() + _, board = mlx_board.load(a.path, log=None) + n, bad = exact(board) + print(f"verify rows against sequential decode: {n} rows, {bad} differ in any bit") + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mlx_lfm_prices.py b/tools/mlx_lfm_prices.py new file mode 100644 index 000000000..3a0d1da34 --- /dev/null +++ b/tools/mlx_lfm_prices.py @@ -0,0 +1,91 @@ +"""StairCut's price file for LFM2.5 on Apple silicon (engine/models/lfm2_moe/mlx_board.py), in the format of +ops/prices/lfm2.5-24b-a2b/.dgx-spark.json: + + .venv-mac/bin/python tools/mlx_lfm_prices.py [--profile lfm25-bf16] [--write] + +At each context class (0: a 512-token prompt; 16384: a prompt of 16,384 tokens) it times a chain verify of +1..16 rows (`rows` + the eval, the median of `--reps`, the state put back between reps) and the plain decode +step (`decode`, ms a token over 32 tokens). `--write` saves ops/prices/lfm2.5-24b-a2b/..json +(the key from tools/gpu, "apple-m5-max"); without it the table is printed. + +Why a file at all: with none, the cut learns verify prices of 2+ rows online but never the 1-row price, which +stays at its 1 ms placeholder, so every drafted round looks 15x dearer than the plain step and the lookup +never drafts (measured on the M5 Max: 495 of 499 rounds cut to the anchor on a copy ask). +""" + +from __future__ import annotations + +import argparse +import json +import os +import statistics +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import mlx.core as mx # noqa: E402 + +from engine.models.lfm2_moe import mlx_board # noqa: E402 +from engine.models.lfm2_moe.ref import chain # noqa: E402 + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +CLASSES = {0: 512, 16384: 16384} +ROWS = range(1, 17) + + +def time_class(board, ctx: int, reps: int) -> dict: + st = board.new_state(ctx + 64) + board.prefill(list(range(1000, 1000 + ctx)), st, last_only=True) + L, conv = st.length, dict(st.conv) + chain_ms = {} + for n in ROWS: + toks = [5 + i for i in range(n)] + board.rows(toks, chain(n), st) # warm the shapes + ts = [] + for _ in range(reps): + t0 = time.perf_counter() + board.rows(toks, chain(n), st) + ts.append((time.perf_counter() - t0) * 1e3) + chain_ms[str(n)] = round(statistics.median(ts), 3) + st.length, st.conv = L, conv + board.decode(5, st) + t0 = time.perf_counter() + for _ in range(32): + board.decode(5, st) + plain = (time.perf_counter() - t0) * 1e3 / 32 + return {"chain": chain_ms, "plain": {"1": round(plain, 3)}} + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("path") + ap.add_argument("--profile", default="lfm25-bf16") + ap.add_argument("--reps", type=int, default=7) + ap.add_argument("--write", action="store_true") + a = ap.parse_args() + _, board = mlx_board.load(a.path, log=None) + doc = {} + for cls, ctx in CLASSES.items(): + doc[str(cls)] = time_class(board, ctx, a.reps) + print(f"class {cls}: plain {doc[str(cls)]['plain']['1']} ms, chain {doc[str(cls)]['chain']}", flush=True) + c0 = doc["0"]["chain"] + doc["step_ms"] = round((c0["16"] - c0["8"]) / 8, 3) + doc["measured"] = ("tools/mlx_lfm_prices.py: chain = `Lfm2MoeMLX.rows` of 1..16 chain rows with its eval " + f"(host wall clock, the median of {a.reps}), at a 512-token prompt (class 0) and a 16,384-token " + "one; plain = the decode step's ms a token over 32 tokens. No spec or prime prior: the cut " + "drafts and learns them online.") + if a.write: + from engine.methods.device import device_id + out = os.path.join(ROOT, "ops", "prices", "lfm2.5-24b-a2b", f"{a.profile}.{device_id()}.json") + with open(out, "w") as f: + json.dump(doc, f, indent=1) + f.write("\n") + print(f"wrote {out}") + else: + print(json.dumps(doc, indent=1)) + return 0 + + +if __name__ == "__main__": + sys.exit(main())