Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
44 changes: 44 additions & 0 deletions docs/lfm2.5-24b-a2b.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <LiquidAI/LFM2.5-24B-A2B checkpoint> --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).
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
15 changes: 15 additions & 0 deletions engine/methods/hostcopy.py
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion engine/models/lfm2_moe/arch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
46 changes: 46 additions & 0 deletions engine/models/lfm2_moe/csrc/mlx_kernels/convgate.metal
Original file line number Diff line number Diff line change
@@ -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<T>(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<T>(float(row_r[h]) * float(row_r[2 * H + h]));
}
}
const T prod = static_cast<T>(float(val) * float(cw[(size_t)h * KT + t]));
acc = (t == 0) ? float(prod) : float(static_cast<T>(acc + float(prod)));
}
cy[(size_t)m * H + h] = static_cast<T>(Cm * acc);
141 changes: 141 additions & 0 deletions engine/models/lfm2_moe/csrc/mlx_kernels/dense_prefill_swiz.metal
Original file line number Diff line number Diff line change
@@ -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<int32_t, 2>;
using strides_t = metal::array<int32_t, 2>;
using tg_t = metal::tensor<threadgroup T, extents_t, metal::tensor_inline>;

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<desc, metal::execution_simdgroup> 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<tg_t, tg_t, float>();
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<OT>(static_cast<T>(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<float, 8, 8> acc[4][4];
for (int fm = 0; fm < 4; fm++)
for (int fn = 0; fn < 4; fn++)
acc[fm][fn] = simdgroup_matrix<float, 8, 8>(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<T, 8, 8> 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<OT>(static_cast<T>(acc[fm][fn].thread_elements()[0]));
y[(size_t)row * N + col + 1] = static_cast<OT>(static_cast<T>(acc[fm][fn].thread_elements()[1]));
}
}
}
}
#endif
15 changes: 15 additions & 0 deletions engine/models/lfm2_moe/csrc/mlx_kernels/embed_swiz.metal
Original file line number Diff line number Diff line change
@@ -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];
Loading
Loading