Skip to content
Merged
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
48 changes: 33 additions & 15 deletions models/mlx/resin_models_mlx/inkling2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ four-tap convolutions over independent 16-token tiles, depth mixes, RMS norms,
expert routing, the capped SwiGLU
with its output scale, the route combine and the BF16 vocabulary projection
with FP32 output. Decode also compiles small FP32 helpers with `mx.compile`;
their shapes depend only on the batch size. Prefill runs uncompiled, and chunks
of 512 or more tokens run one dense FP32 GEMM per expert segment over exactly
dequantized weights; shorter chunks keep the gathered quantized GEMM. At 2,048 tokens (16K routes) that is 2.3× (NVFP4) to 3.5× (MXFP8)
faster than MLX's gathered quantized GEMM, dequantization included.
their shapes depend only on the batch size. Prefill runs uncompiled. Experts
run as one sorted `gather_qmm` per projection over rows gathered into route
order. MLX ignores `sorted_indices` when given `lhs_indices`, so passing the row
map that way keeps prefill off its grouped kernel.

## Validation

Expand All @@ -82,15 +82,18 @@ tests' independent NVFP4/MXFP8 arithmetic.
- On a tiny looped checkpoint with both expert formats, every visit's mixing,
attention and experts match the reference within about one BF16 rounding step
over a prefill and six decode steps, including prefill chunks large enough for
the per-expert GEMMs (teacher-forced: random tiny models with FP4 activations
MLX's grouped expert GEMM (teacher-forced: random tiny models with FP4 activations
amplify one rounding step into different logits).
- On the real checkpoint, the opt-in test (a 24-token prompt from the model
card, then three greedy decode steps) finds each visit's attention and
experts within 0.53% relative, teacher-forced logits within about 1×10⁻⁵, and
the same top-1 token at every step. Ad hoc runs of the same comparison on
16-, 1,100- and 2,100-token prompts with four decode steps each also agreed on
all 15 top-1 tokens; mean absolute logit differences were 0.25–1.05 (logits
are capped at ±30). Moving 40 values by one BF16 step at the first visit moves
- On the real checkpoint, the opt-in test (an 80-token prompt from the model
card, long enough for MLX's grouped expert GEMM, then three greedy decode
steps) finds each visit's attention within 0.56% relative and experts within
0.31%, teacher-forced logits within about 5×10⁻⁵, and the same top-1 token at
every step. Three of the 3,840 token visits route through an FP32 tie (eighth
and ninth biased scores within 10⁻⁵) and are excluded from the expert bound;
one picks a different expert than the reference. Ad hoc runs of the same
comparison on 16-, 1,100- and 2,100-token prompts with four decode steps each
also agreed on all 15 top-1 tokens; mean absolute logit differences were
0.21–0.91 (logits are capped at ±30). Moving 40 values by one BF16 step at the first visit moves
the reference's own logits by a mean of 0.64. The same amplification means greedy output can change with
the prefill chunk size or the batch a request runs in, whose different GEMM
shapes round differently; it is reproducible for a fixed configuration.
Expand Down Expand Up @@ -124,7 +127,7 @@ unqualified.
uv run pytest models/mlx/tests/test_inkling2_model.py \
models/mlx/tests/test_inkling2_engine.py models/mlx/tests/test_inkling2_attention.py \
models/mlx/tests/test_inkling2_vision.py tests/test_deploy_models.py
# Real checkpoint against the CPU reference (about 50 GB of memory, under a minute):
# Real checkpoint against the CPU reference (about 50 GB of memory, about a minute):
RESIN_TEST_CHECKPOINT="$INKLING_CHECKPOINT" \
uv run pytest models/mlx/tests/test_inkling2_checkpoint.py
```
Expand Down Expand Up @@ -161,6 +164,21 @@ kernel matched the prototype bit for bit. Compared with the dense reference,
the maximum absolute error was 3.34 × 10⁻⁶ for the output and 2.86 × 10⁻⁶
for log-sum-exp.

### Full-model throughput on M4 Max

Measured on November 23, 2026 on the same laptop, MLX 0.32.4 and prompt
artifact as the historical table below, with the shared benchmark command shown
there.

| Complete prefill | 4K prompt | 8K prompt | 16K prompt | 32K prompt |
| ---------------- | --------: | --------: | ---------: | ---------: |
| Seconds | 4.66 | 10.28 | 22.13 | 52.48 |
| Input tokens/s | 880 | 797 | 740 | 624 |

Runs of the same code differ by up to about 10% as the laptop heats; 32K
prefill ranged from 624 to 703 tokens/s. Same-session decode at batch 1–8 was
within 4% of the previous expert path.

### Historical full-model throughput on M4 Max

The original runner (`e2f020b`) was benchmarked on November 22, 2026 on a
Expand Down Expand Up @@ -233,8 +251,8 @@ remaining gap is the dispatch of many small per-visit operations.
own cache groups, block verification and rollback, and is left for a
follow-up, so the speculative-decoding step of the model checklist is open.
- One GPU; no tensor or expert parallelism.
- Prefill expert GEMMs reach about 7.8 TFLOPS (versus 13.5 for one dense GEMM)
because each expert sees about 128 rows per 2,048 tokens.
- With 4,096 tokens routed uniformly, the gate/up NVFP4 expert projection
reaches about 11 TFLOPS, versus 12–13 for FP32 dense GEMMs of the same size.
- Prompt logprobs project 128 prompt rows in about 60 ms (four rows per GEMV
launch), adding about 4 seconds per 8,192-token chunk when requested.

Expand Down
78 changes: 17 additions & 61 deletions models/mlx/resin_models_mlx/inkling2/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@

from dataclasses import dataclass
from functools import update_wrapper
from itertools import pairwise
from typing import Protocol

import mlx.core as mx
import numpy as np

from resin.models.inkling2.config import Inkling2Config
from resin_models_mlx.fused_norm import rms_norm
Expand Down Expand Up @@ -191,79 +189,43 @@ def log_scaling_tau(positions: mx.array, n_floor: int, alpha: float) -> mx.array
return 1.0 + alpha * mx.log(mx.maximum(effective / float(n_floor), 1.0))


# From this many routes (512 tokens), prefill runs one dense FP32 GEMM per
# expert over its sorted segment of exactly dequantized weights. On an M4 Max
# the two paths tie at 512 tokens; at 2,048 tokens (16K routes) the segments are
# 2.3x (NVFP4) to 3.5x (MXFP8) faster, dequantization included. Below the
# threshold, dequantizing every expert costs more than the gathered GEMM saves.
SEGMENTED_ROUTES = 4096


def _expert_matmul(
x: mx.array,
weight: mx.array,
scales: mx.array,
experts: Experts,
rows: mx.array | None,
ids: mx.array,
segments: list[tuple[int, int, int]] | None = None,
) -> tuple[mx.array, mx.array | None]:
"""Quantize activations as the checkpoint requires, then run the packed GEMM.

Returns the FP32 product of dequantized codes, one row per route in ``ids``
order (sorted by expert), and the NVFP4 activation amax per row of ``x``;
the output scale is applied with the next rounding. ``rows`` maps each route
to its row of ``x``; ``None`` means one row per route. ``segments`` lists
``(expert, start, stop)`` route ranges; given, each expert's weights are
dequantized to FP32 (exactly) for a dense GEMM.
to its row of ``x``; ``None`` means one row per route. Rows are gathered
before the GEMM because MLX ignores ``sorted_indices`` when given
``lhs_indices``, which keeps prefill off its grouped kernel.
"""
values, activation_amax = quantize_activations(x, experts.mode)
if segments is None:
output = mx.gather_qmm(
values[:, None, :],
weight,
scales,
None,
lhs_indices=rows,
rhs_indices=ids,
transpose=True,
group_size=experts.group_size,
bits=experts.bits,
mode=experts.mode,
sorted_indices=True,
)[:, 0, :]
else:
routed = values if rows is None else values[rows]
parts = []
for expert, start, stop in segments:
dense = mx.dequantize(
weight[expert],
scales[expert],
None,
group_size=experts.group_size,
bits=experts.bits,
mode=experts.mode,
dtype=F32,
)
parts.append(routed[start:stop] @ dense.T)
output = mx.concatenate(parts) if len(parts) > 1 else parts[0]
routed = values if rows is None else values[rows]
output = mx.gather_qmm(
routed[:, None, :],
weight,
scales,
None,
rhs_indices=ids,
transpose=True,
group_size=experts.group_size,
bits=experts.bits,
mode=experts.mode,
sorted_indices=True,
)[:, 0, :]
if activation_amax is not None and activation_amax.size < 8:
# Keep the Metal device-array binding even at batch one.
activation_amax = mx.pad(activation_amax, (0, 8 - activation_amax.size))
return output, activation_amax


def _segments(sorted_ids: mx.array, experts: int) -> list[tuple[int, int, int]]:
"""Route ranges per expert; reading the routing back waits for the router."""
ids = np.asarray(sorted_ids)
bounds = np.searchsorted(ids, np.arange(experts + 1, dtype=ids.dtype)).tolist()
return [
(expert, start, stop)
for expert, (start, stop) in enumerate(pairwise(bounds))
if start < stop
]


@_decode_compiled
def _sort_routes(ids, weights, top_k: int):
"""Order routes by expert; ``ids``/``weights`` are ``[B, T, top_k]``."""
Expand All @@ -287,19 +249,13 @@ def sparse_mlp(x: mx.array, layer: Layer, config: Inkling2Config) -> mx.array:
)
experts = layer.experts
nvfp4 = experts.mode == "nvfp4"
segments = (
_segments(sorted_ids, experts.w13.shape[0])
if sorted_ids.size >= SEGMENTED_ROUTES
else None
)
gate_up, gate_up_amax = _expert_matmul(
flat,
experts.w13,
experts.w13_scales,
experts,
source_rows,
sorted_ids,
segments,
)
activated = expert_activation(
gate_up,
Expand All @@ -313,7 +269,7 @@ def sparse_mlp(x: mx.array, layer: Layer, config: Inkling2Config) -> mx.array:
experts.w13_denominator,
)
down, down_amax = _expert_matmul(
activated, experts.w2, experts.w2_scales, experts, None, sorted_ids, segments
activated, experts.w2, experts.w2_scales, experts, None, sorted_ids
)
return expert_combine(
down,
Expand Down
2 changes: 0 additions & 2 deletions models/mlx/resin_models_mlx/inkling2/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,6 @@ def __init__(
self.benchmark_metadata = {
"quant": "checkpoint-nvfp4-mxfp8-experts",
"weight_source": "prequantized_checkpoint",
# Prefill chunks of 512 or more tokens instead run exactly
# dequantized FP32 GEMMs per expert segment (model.SEGMENTED_ROUTES).
"expert_backend": "mlx-gather-qmm",
"graphs": {"prefill": "disabled", "decode": "disabled"},
}
Expand Down
38 changes: 29 additions & 9 deletions models/mlx/tests/test_inkling2_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Set ``RESIN_TEST_CHECKPOINT`` to a local thinkingmachines/Inkling-2-Mini
snapshot (revision ed40e7da625f594fc9c4990f5f66be24873c22d7). Both models load
(about 50 GB of memory); the run takes under a minute on an M4 Max.
(about 50 GB of memory); the run takes about a minute on an M4 Max.
"""

from __future__ import annotations
Expand Down Expand Up @@ -104,7 +104,8 @@ def test_real_checkpoint_matches_cpu_reference(monkeypatch):
)
model = Inkling2Model(config, weights)
text = (root / "README.md").read_text()
prompt = Tokenizer.from_file(str(root / "tokenizer.json")).encode(text).ids[:24]
# 80 tokens (640 routes, five per expert) take MLX's grouped expert GEMM.
prompt = Tokenizer.from_file(str(root / "tokenizer.json")).encode(text).ids[:80]

# Teacher-forced: each visit's attention and experts from the reference's inputs.
records = _record(target)
Expand All @@ -123,14 +124,29 @@ def forced_attention(self, layer, sources, state, tau, visit, slot, store):
errors["attention"] = max(errors["attention"], _relative(output, expected))
return _to_mlx(expected), k_history, v_history

route_ties = []

def forced_mlp(x, layer, config):
index = cursor["mlp"]
cursor["mlp"] += 1
output = sparse(
_to_mlx(records["mlp_input"][index]).reshape(x.shape), layer, config
)
forced = _to_mlx(records["mlp_input"][index]).reshape(x.shape)
output = sparse(forced, layer, config)
expected = records["mlp"][index]
errors["mlp"] = max(errors["mlp"], _relative(output, expected))
# A token whose eighth and ninth biased router scores tie in FP32 may
# pick the other expert under a different summation order.
rows = forced.reshape(-1, x.shape[-1]).astype(mx.float32)
scores = np.array(mx.sigmoid(rows @ layer.router.T) + layer.router_bias)
ranked = -np.sort(-scores, axis=-1)
top_k = config.experts_per_token
tied = ranked[:, top_k - 1] - ranked[:, top_k] < 1e-5
route_ties.extend((index, int(row)) for row in np.flatnonzero(tied))
keep = np.flatnonzero(~tied)
width = expected.shape[-1]
kept = _relative(
output.reshape(-1, width)[mx.array(keep)],
expected.reshape(-1, width)[torch.from_numpy(keep)],
)
errors["mlp"] = max(errors["mlp"], kept)
return _to_mlx(expected).reshape(x.shape)

tokens = torch.tensor([prompt])
Expand All @@ -142,7 +158,7 @@ def forced_mlp(x, layer, config):
expected, _, _, _ = target(
tokens,
positions,
ReferenceCache(config, 1, 64),
ReferenceCache(config, 1, 128),
state,
positions[:, -1] + 1,
len(prompt),
Expand All @@ -152,7 +168,7 @@ def forced_mlp(x, layer, config):
with monkeypatch.context() as patch:
patch.setattr(Inkling2Model, "_attention", forced_attention)
patch.setattr(mlx_model, "sparse_mlp", forced_mlp)
store = DenseStore(config, 1, 64)
store = DenseStore(config, 1, 128)
store.positions = mx.array(positions.numpy())
actual, _ = model(
mx.array(tokens.numpy()),
Expand All @@ -163,10 +179,14 @@ def forced_mlp(x, layer, config):
)
# Real-checkpoint visits agree within about one BF16 step (2^-8 relative).
assert errors["attention"] < 1e-2 and errors["mlp"] < 1e-2, errors
# Three of the 3,840 token visits tie at this prompt.
assert len(route_ties) <= 0.002 * len(prompt) * config.execution_layer_count, (
route_ties
)
assert _relative(actual, expected) < 1e-3

# Free-running: prefill and three greedy decode steps choose the same tokens.
cache, store = ReferenceCache(config, 1, 64), DenseStore(config, 1, 64)
cache, store = ReferenceCache(config, 1, 128), DenseStore(config, 1, 128)
reference_state = state
mlx_state = model.initial_state(1)
current, start = tokens, 0
Expand Down
5 changes: 0 additions & 5 deletions models/mlx/tests/test_inkling2_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,8 +410,6 @@ def _to_mlx(value) -> mx.array:
return mx.array(value.float().numpy()).astype(mx.bfloat16)


# At 40 tokens (640 routes) the threshold is lowered so the segmented prefill
# experts run; the shorter prompts keep the gathered quantized GEMM.
@pytest.mark.parametrize("prompt_length", [5, 20, 40])
def test_tiny_model_matches_cuda_reference(tmp_path, monkeypatch, prompt_length):
"""Teacher-forced: each visit's mixing, attention and experts against the reference.
Expand All @@ -425,9 +423,6 @@ def test_tiny_model_matches_cuda_reference(tmp_path, monkeypatch, prompt_length)
"""
from resin_models_mlx.inkling2 import model as mlx_model

if prompt_length == 40:
monkeypatch.setattr(mlx_model, "SEGMENTED_ROUTES", 512)

config = tiny_config()
write_checkpoint(tmp_path, config)
target = reference_target(tmp_path, config, monkeypatch)
Expand Down
Loading