diff --git a/NOTICE b/NOTICE index 85e69d66..ccdddf7e 100644 --- a/NOTICE +++ b/NOTICE @@ -217,6 +217,22 @@ MLX is licensed under the MIT License. The notice is retained in the model directory's LICENSE. The adaptation preserves FP32 product/reduction boundaries and BF16 output rounding. +The Inkling 2 MLX runner in models/mlx/resin_models_mlx/inkling2 follows the +arithmetic of models/cuda/resin_models_cuda/inkling2. Its NVFP4/MXFP8 activation +quantizer (quantization.py) adapts SGLang's Apache-2.0 Inkling 2 activation +quantization, as that CUDA module does: + + https://github.com/sgl-project/sglang/tree/e62ac6279646c686d3b328f58d9b5c2c2d5927dc + +Its fused routing and expert-activation kernels (kernels.py) reuse MLX v0.32.4's +sigmoid formula from mlx/backend/metal/kernels/unary_ops.h: + + Copyright 2023-2024 Apple Inc. + https://github.com/ml-explore/mlx/tree/v0.32.4/mlx/backend/metal/kernels + +MLX is licensed under the MIT License. The notice is retained in that model +directory's LICENSE. + The Qwen3.5 MLX vision adapter in models/mlx/resin_models_mlx/qwen3_5/vision.py reuses MLX-VLM 0.7.11's Qwen3.5 and Qwen3-VL vision modules, including their geometry and encoder blocks: diff --git a/README.md b/README.md index d27ebd5d..44125af7 100644 --- a/README.md +++ b/README.md @@ -250,6 +250,7 @@ hardware, and serving limits. Model runners are not tied to CUDA. `resin_models_mlx` runs [dense and MoE Qwen3.5 models](models/mlx/resin_models_mlx/qwen3_5/README.md) +and [Inkling 2 Mini text](models/mlx/resin_models_mlx/inkling2/README.md) on Apple Silicon with MLX, on the same core engine. For a small local model: ```bash diff --git a/crates/resin-recipe/src/inkling2.rs b/crates/resin-recipe/src/inkling2.rs index 33844846..8c454366 100644 --- a/crates/resin-recipe/src/inkling2.rs +++ b/crates/resin-recipe/src/inkling2.rs @@ -138,6 +138,9 @@ impl Grammar for Inkling2Grammar { pub struct Inkling2Recipe { pub add_generation_prompt: Option, pub reasoning_effort: Option, + /// Rejects media for runners that serve only the language model. + #[serde(skip_serializing)] + pub text_only: bool, #[serde(skip_serializing, deserialize_with = "crate::recipe::default_if_null")] pub media_config: media::Config, } diff --git a/crates/resin-recipe/src/inkling2/media.rs b/crates/resin-recipe/src/inkling2/media.rs index 422fb125..97d2cebc 100644 --- a/crates/resin-recipe/src/inkling2/media.rs +++ b/crates/resin-recipe/src/inkling2/media.rs @@ -168,6 +168,21 @@ mod tests { ); } #[test] + fn text_only_recipe_refuses_media() { + use crate::{Recipe, inkling2::Inkling2Recipe}; + + assert!( + Inkling2Recipe::default() + .prepare_media(vec![], &Encoder) + .is_ok() + ); + let text_only = Inkling2Recipe { + text_only: true, + ..Default::default() + }; + assert!(text_only.prepare_media(vec![], &Encoder).is_err()); + } + #[test] fn padding_is_negative_one_on_the_byte_scale() { let config = Config { size: Size { diff --git a/crates/resin-recipe/src/inkling2/render.rs b/crates/resin-recipe/src/inkling2/render.rs index d20bfe3e..ded44ca4 100644 --- a/crates/resin-recipe/src/inkling2/render.rs +++ b/crates/resin-recipe/src/inkling2/render.rs @@ -235,13 +235,20 @@ impl crate::Recipe for Inkling2Recipe { Ok(vec![encoder.special_id("<|content_model_end_sampling|>")?]) } fn input_modalities(&self) -> &'static [&'static str] { - &["text", "image"] + if self.text_only { + &["text"] + } else { + &["text", "image"] + } } fn prepare_media( &self, sources: Vec, encoder: &dyn crate::Encoder, ) -> Result { + if self.text_only { + return Err(Error::new("this recipe does not support media")); + } self.media_config.prepare(sources, encoder) } } diff --git a/crates/resin-recipe/tests/inkling2.rs b/crates/resin-recipe/tests/inkling2.rs index 19a5d0fd..3c445650 100644 --- a/crates/resin-recipe/tests/inkling2.rs +++ b/crates/resin-recipe/tests/inkling2.rs @@ -338,3 +338,18 @@ fn pinned_inkling2_template_handles_named_headers_images_and_empty_content() { assert!(Inkling2Recipe::default().render(&request).is_err()); } } + +#[test] +fn text_only_recipe_rejects_media() { + use resin_recipe::{Recipe, inkling2::Inkling2Recipe}; + + assert_eq!( + (&Inkling2Recipe::default() as &dyn Recipe).input_modalities(), + &["text", "image"] + ); + let recipe = Inkling2Recipe { + text_only: true, + ..Default::default() + }; + assert_eq!((&recipe as &dyn Recipe).input_modalities(), &["text"]); +} diff --git a/deploy/models.py b/deploy/models.py index bbacdc06..48e133d8 100644 --- a/deploy/models.py +++ b/deploy/models.py @@ -349,6 +349,31 @@ def assistant_path(self) -> Path | None: recipe="ornith", text_only=True, ), + "inkling2-mini-mlx": ModelSpec( + name="inkling2-mini-mlx", + family="inkling2", + checkpoint=Checkpoint( + repo_id="thinkingmachines/Inkling-2-Mini", + revision="ed40e7da625f594fc9c4990f5f66be24873c22d7", + directory="", + required_files=( + "config.json", + "model.safetensors.index.json", + "hf_quant_config.json", + "tokenizer.json", + "processor_config.json", + ), + ), + # Target-only text on Apple Silicon; experts stay NVFP4/MXFP8. + backend="mlx", + gpu="Apple-Silicon", + label="inkling2-mini-mlx", + expert_backend="mlx-gather-qmm", + context_length=32_768, + max_batch_size=8, + gpu_memory_utilization=0.70, + text_only=True, + ), "inkling2-small": ModelSpec( name="inkling2-small", family="inkling2", @@ -659,17 +684,27 @@ def create_runner( if spec.backend == "mlx": if draft_tokens: raise ValueError( - "this MLX Qwen3.5 runner does not support draft decoding; " + f"the MLX {spec.family} runner does not support draft decoding; " "use draft_tokens=0" ) - from resin_models_mlx.qwen3_5 import Qwen35MlxRunner - if groups is not None: raise ValueError("the MLX runner executes on one Apple Silicon device") if expert_backend not in (None, spec.expert_backend): raise ValueError(f"{spec.name} uses expert_backend={spec.expert_backend!r}") # MLX has no CUDA graphs or graph batch catalog; graph options and # decode_batch_sizes do not apply. The batch limit sizes live state. + if spec.family == "inkling2": + from resin_models_mlx.inkling2 import Inkling2MlxRunner + + return Inkling2MlxRunner( + checkpoint, + memory_utilization=memory, + max_seq_len=context_length, + max_batch_size=max_batch_size, + prefill_chunk_size=prefill_chunk_size, + ) + from resin_models_mlx.qwen3_5 import Qwen35MlxRunner + return Qwen35MlxRunner( checkpoint, memory_utilization=memory, @@ -815,10 +850,12 @@ def create_recipe( # The native recipe takes the checkpoint's image settings directly. processor_config = path / "processor_config.json" - options = {} + options: dict[str, Any] = {} if processor_config.is_file(): config = json.loads(processor_config.read_text()) options["media_config"] = config["image_processor"] + if spec.text_only: + options["text_only"] = True return get_native_recipe( spec.family, Tokenizer.from_file(str(path / "tokenizer.json")), diff --git a/models/mlx/pyproject.toml b/models/mlx/pyproject.toml index 7b2df3a1..d9ed7434 100644 --- a/models/mlx/pyproject.toml +++ b/models/mlx/pyproject.toml @@ -42,4 +42,6 @@ resin_models_mlx = [ "_native/LICENSE*", "qwen3_5/README.md", "qwen3_5/LICENSE", + "inkling2/README.md", + "inkling2/LICENSE", ] diff --git a/models/mlx/resin_models_mlx/inkling2/LICENSE b/models/mlx/resin_models_mlx/inkling2/LICENSE new file mode 100644 index 00000000..98ff47b9 --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2023 Apple Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/models/mlx/resin_models_mlx/inkling2/README.md b/models/mlx/resin_models_mlx/inkling2/README.md new file mode 100644 index 00000000..f8b32cbc --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/README.md @@ -0,0 +1,215 @@ +# Inkling 2 Mini on Apple Silicon + +`Inkling2MlxRunner` serves **Inkling 2 Mini** text through Resin's Engine on one +Apple Silicon GPU. It supports paged global and sliding-window attention, chunked +prefill, prefix reuse and overlapped decode. DSpark speculative decoding and +image input are not supported yet; image requests are rejected by the recipe. + +## Run locally + +The `inkling2-mini-mlx` preset pins +[`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini/tree/ed40e7da625f594fc9c4990f5f66be24873c22d7) +at revision `ed40e7da625f594fc9c4990f5f66be24873c22d7`: + +```bash +INKLING_CHECKPOINT="$(uv run hf download thinkingmachines/Inkling-2-Mini \ + --revision ed40e7da625f594fc9c4990f5f66be24873c22d7 --quiet)" +uv run scripts/mlx_serve.py --model inkling2-mini-mlx --checkpoint "$INKLING_CHECKPOINT" +``` + +The 18.2 GiB target file loads as stored; `mtp.safetensors` (DSpark) and the +vision tower are not loaded. The preset uses a 32,768-token context, at most +eight requests and 8,192-token prefill chunks; `--context-length` and +`--max-batch-size` override those limits. + +## Precision + +Experts stay packed in the checkpoint's formats: NVFP4 in layers 0–19 and MXFP8 +in layers 20–23. Their bytes are viewed directly as MLX `nvfp4` and `mxfp8` +weights; dequantized values match the CUDA reference bit for bit on the real +checkpoint. The NVFP4 output scale, activation amax times the expert's weight +amax over `1536 · denominator`, is applied to the FP32 GEMM output as the CUDA +kernel does, rather than through MLX's global scale. + +The checkpoint requires quantized expert activations. A Metal kernel reproduces +the CUDA quantizer bit for bit (NVFP4's four-or-six block scale chosen by summed +reconstruction error; MXFP8's power-of-two scale) and emits the dequantized +codes, which are exact in BF16. The one exception is an MXFP8 block whose +largest value is below 448 · 2⁻¹²⁷, which becomes zero where CUDA keeps +denormals. The packed GEMM therefore forms the same products as CUDA's +W4A4/W8A8 MMA, up to FP32 summation order. Attention and dense projection +weights, convolution history and KV are BF16; attention scores, softmax and +outputs are FP32. Depth mixes, controller gates, routing and logits are FP32, +and BF16 rounding points follow the CUDA runner (`resin_models_cuda/inkling2`). + +## Execution + +Mini runs 48 layer visits over 24 stored layers: layers 0–5, layers 6–17 three +times, then layers 18–23. Each pass restarts from the prelude's residual blocks +and receives the previous pass through four message controllers per layer. +Every visit has its own KV cache and convolution history. + +The Engine owns three cache groups, mirroring the CUDA runner without DSpark: + +- global KV for the 8 global visits (full history); +- local KV for the 40 sliding-window visits, retaining the 1,024 readable + tokens plus one prefill chunk of writes; +- convolution history (`48 × 3 × 6656` BF16) for prefix snapshots. + +Live convolution history stays on the GPU between steps; prefix hits restore a +snapshot. Decode reads KV pages in place with a flash-decoding kernel that adds +Inkling's relative bias, applies each row's window bound and returns the +log-sum-exp for the attention sink. Context lengths, bounds and page-table +widths are runtime data. Prefill gathers retained history per visit, attends in +query blocks, reads only each block's window band or causal prefix, and skips +bias work for global keys more than 1,024 positions back. + +Decode overlaps through the Engine's enqueue contract. Fused Metal kernels cover +short convolutions, 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. + +## Validation + +No independent MLX or Transformers implementation of Inkling 2 exists, so the +reference is the CUDA package's `Inkling2Target` on CPU PyTorch, with only its +GPU kernels replaced: dense attention, and packed experts computed by the CUDA +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 + 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 + 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. +- Engine tests check that every arena history read is byte-identical to what + was written across page, chunk and window boundaries and prefix restores; + that every runner attention call matches an unsliced dense reference, + including windows and bias extents spanning several pages; that a + cached continuation equals a fresh one; and that overlapped decode equals + synchronous decode. +- `scripts/check_server.py --stress` passes chat, logprobs, concurrency, prefix + reuse, stress, robustness and recovery, and context checks up to 2,048 tokens. + The 8,192-token check exceeds its default 10-second TTFT limit (15 seconds at + this prefill rate). Image requests are rejected at admission. +- On 100 MMLU questions (`cais/mmlu` revision `c30699e8`, 50 subjects × 2, + seed 1017; default reasoning, 4,096-token cap, eight concurrent), 86 answers + are correct. Of the 14 others, 4 are wrong, 2 reached the token cap and 8 + exceeded the checker's 180-second client timeout while still reasoning. + +After warmup over batch sizes 1–8 and both sampling paths, unseen prompt +lengths (up to 9,000 tokens), contexts, chunk lengths and sampling values create +no new custom Metal kernel variants and no new `mx.compile` traces on the real +checkpoint. An Engine test repeats the custom-kernel check on the tiny model. +MLX's own kernel JIT (GEMMs) is not observable this way and remains +unqualified. + +```bash +uv run pytest models/mlx/tests/test_inkling2_model.py \ + models/mlx/tests/test_inkling2_engine.py models/mlx/tests/test_inkling2_attention.py \ + tests/test_deploy_models.py +# Real checkpoint against the CPU reference (about 50 GB of memory, under a minute): +RESIN_TEST_CHECKPOINT="$INKLING_CHECKPOINT" \ + uv run pytest models/mlx/tests/test_inkling2_checkpoint.py +``` + +## Measured performance + +November 22, 2026, 14-inch MacBook Pro with M4 Max and 128 GiB, MLX 0.32.4, +ShareGPT prompts tokenized for Inkling and greedy sampling. Prefill figures are +medians of three cohorts; decode figures are medians of 20 overlapped steps after +five warmup steps. This laptop throttles under sustained load. + +| Decode at 8K context | Batch 1 | Batch 2 | Batch 4 | Batch 8 | Batch 16 | +| -------------------- | ------: | ------: | ------: | ------: | -------: | +| Output tokens/s | 35.6 | 60.6 | 97.6 | 129.6 | 140.1 | +| Tokens/s per request | 35.6 | 30.3 | 24.4 | 16.2 | 8.8 | + +Every measured decode step overlapped with the next through `enqueue`. Batch 16 +was measured in a separate run after a change that left decode code untouched. At batch +eight, step times rose from 56 to 66 ms across the window. + +| Complete prefill | 4K prompt | 8K prompt | 16K prompt | 32K prompt | +| ---------------- | --------: | --------: | ---------: | ---------: | +| Seconds | 7.60 | 15.48 | 38.79 | 103.63 | +| Input tokens/s | 539 | 529 | 422 | 316 | + +Prefill runs in 8,192-token chunks and includes the whole prompt. Reproduce +with the shared benchmark (raw JSONL, plots and Perfetto traces for both phases): + +```bash +uv run python -m resin.bench_prompts prepare \ + --corpus ShareGPT_V3_unfiltered_cleaned_split.json --source-metadata source.json \ + --tokenizer "$INKLING_CHECKPOINT" --revision ed40e7da625f594fc9c4990f5f66be24873c22d7 \ + --contexts 4096,8192,16384,32768 --context-counts 4096:16,8192:16,16384:8,32768:8 \ + --output inkling2-mini-32k.resinprompts +uv run scripts/bench.py --model inkling2-mini-mlx --backend local \ + --checkpoint "$INKLING_CHECKPOINT" --prompt-source saved \ + --prompt-corpus inkling2-mini-32k.resinprompts \ + --prefill-context-lengths 4096,8192,16384,32768 --decode-context-lengths 8192 \ + --decode-batch-sizes 1,2,4,8 --output artifacts/inkling2-mini-mlx-bench.jsonl \ + --trace-dir artifacts/inkling2-mini-mlx-traces --plot +``` + +For comparison, llama.cpp at commit `8d60873dfb8619f2b5ed31adfbab07cccb40db5c` +on the same machine, with a Q4_K_M GGUF (16.3 GiB) converted from the same +checkpoint by its own `convert_hf_to_gguf.py` and `llama-quantize` (Unsloth's +published GGUFs use a different tensor layout that upstream llama.cpp does not +load). Metal offload and flash attention are enabled. Q4_K_M stores most +weights, attention included, in about 4.5 bits, where Resin keeps BF16 attention +and the checkpoint's NVFP4/MXFP8 experts. + +| llama.cpp, 8K context | Batch 1 | Batch 2 | Batch 4 | Batch 8 | +| -------------------------- | ------: | ------: | ------: | ------: | +| Output tokens/s | 32.2 | 47.1 | 64.8 | 81.9 | +| Resin speedup | ~1.1× | 1.29× | 1.51× | 1.58× | + +`llama-batched-bench -npp 8192 -ntg 64` measured those rates; `llama-bench` +(`tg128 @ d8192`) reports 28.0 tokens/s at batch one. Resin's rates are median +steps; its batch-one window average was 30.9 tokens/s because of one slow +step, so batch one is roughly parity to 1.1×. llama.cpp's prefill +reaches 404 tokens/s for a 4K prompt and 318 for 8K (`llama-bench`), and +332–356 tokens/s per 8K prompt when batched. These are single sessions on a +laptop that throttles; they compare implementations, not precision. + +Batch-one decode reads about 2.6 GB of BF16 attention weights, 1.8 GB of expert +weights and 0.9 GB of vocabulary projection per token, about 5.3 GB. At the +330–410 GB/s chained GEMVs reach here, that bounds it near 62–77 tokens/s. The +remaining gap is the dispatch of many small per-visit operations. + +## Limits + +- No DSpark speculative decoding (the CUDA preset uses seven proposals). This + PR is scoped to the target model; speculation needs the bundled draft model's + 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. +- No image input. +- 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. Prefill attention + uses FP32 MLX matmuls rather than a flash kernel, so long prompts slow down: + 316 tokens/s at 32K. +- 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. + +## Source references + +- The CUDA runner `models/cuda/resin_models_cuda/inkling2`, which follows + [SGLang's Inkling 2 integration](https://github.com/sgl-project/sglang/tree/e62ac6279646c686d3b328f58d9b5c2c2d5927dc), + defines the arithmetic and supplies the CPU reference. The activation + quantizer adapts SGLang's Apache-2.0 kernel. +- The routing and activation kernels reuse MLX v0.32.4's sigmoid formula + (MIT; notice in this directory's LICENSE). diff --git a/models/mlx/resin_models_mlx/inkling2/__init__.py b/models/mlx/resin_models_mlx/inkling2/__init__.py new file mode 100644 index 00000000..1f34071b --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/__init__.py @@ -0,0 +1,5 @@ +"""Inkling 2 target-only text runner for Apple Silicon.""" + +from resin_models_mlx.inkling2.runner import Inkling2MlxRunner + +__all__ = ["Inkling2MlxRunner"] diff --git a/models/mlx/resin_models_mlx/inkling2/attention.py b/models/mlx/resin_models_mlx/inkling2/attention.py new file mode 100644 index 00000000..489f9fcd --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/attention.py @@ -0,0 +1,118 @@ +"""Inkling 2 attention over gathered history, with relative bias and a window. + +Logits are ``q·k / sqrt(d) + bias[q_pos - k_pos]`` in FP32, where the bias +applies only within its extent. Local visits additionally drop keys more than +``window - 1`` positions back. The softmax output and its log-sum-exp stay +FP32 for the sink and gate. +""" + +from __future__ import annotations + +import mlx.core as mx + +F32 = mx.float32 +# Bound each block's FP32 logits (and gathered bias) to about this many bytes. +_BLOCK_BYTES = 256 * 1024**2 +# Query block size for banded windows: each reads window + block keys. +_BAND_QUERIES = 512 + + +def dense_attention( + q: mx.array, + keys: mx.array, + values: mx.array, + key_positions: mx.array, + key_valid: mx.array, + positions: mx.array, + bias: mx.array, + scale: float, + window: int | None, + contiguous: tuple[int, int] | None = None, +) -> tuple[mx.array, mx.array]: + """Attend ``q [B, T, H, D]`` to ``keys/values [B, L, KV, D]``. + + ``key_positions``/``key_valid`` are ``[B, L]``; ``positions`` is ``[B, T]``; + ``bias`` is ``[B, T, H, E]``. Returns FP32 ``[B, T, H, D]`` and ``[B, T, H]``. + + ``contiguous = (first key position, first query position)`` states that + key ``i`` is at position ``first + i`` and query ``t`` at the second plus + ``t`` in every row. Each query block then reads only keys it can see: its + causal prefix, and for a window only the band behind it. + """ + batch, tokens, heads, dim = q.shape + length, kv_heads = keys.shape[1], keys.shape[2] + groups = heads // kv_heads + extent = bias.shape[-1] + k32 = keys.astype(F32) + # Masked probabilities are zero, but zero times a stale NaN is still NaN. + v32 = mx.where(key_valid[:, :, None, None], values, 0).astype(F32) + span_keys = ( + length if window is None or contiguous is None else window + _BAND_QUERIES + ) + block = max(1, min(tokens, _BLOCK_BYTES // max(1, 4 * batch * heads * span_keys))) + if window is not None and contiguous is not None: + block = min(block, _BAND_QUERIES) + outputs, statistics = [], [] + for start in range(0, tokens, block): + stop = min(tokens, start + block) + span = stop - start + lo, hi = 0, length + if contiguous is not None: + first_key, first_query = contiguous + hi = min(length, first_query + stop - first_key) + if window is not None: + lo = max(0, first_query + start - (window - 1) - first_key) + # Contiguous global keys more than ``extent`` behind every query of the + # block carry no bias and are all visible: score them with a plain dot + # product, and gather bias and masks only for the recent remainder. + split = lo + if contiguous is not None and window is None: + first_key, first_query = contiguous + split = min(hi, max(lo, first_query + start - (extent - 1) - first_key)) + values_block = v32[:, lo:hi] + query = q[:, start:stop].astype(F32).reshape(batch, span, kv_heads, groups, dim) + parts = [] + if split > lo: + distant = mx.einsum("btkgd,blkd->btkgl", query, k32[:, lo:split]) + parts.append(distant.reshape(batch, span, heads, split - lo) * scale) + recent_keys = k32[:, split:hi] + block_positions, block_valid = ( + key_positions[:, split:hi], + key_valid[:, split:hi], + ) + width = hi - split + logits = mx.einsum("btkgd,blkd->btkgl", query, recent_keys).reshape( + batch, span, heads, width + ) + logits = logits * scale + distance = positions[:, start:stop, None] - block_positions[:, None, :] + index = mx.clip(distance, 0, extent - 1) + gathered = mx.take_along_axis( + bias[:, start:stop].astype(F32), + mx.broadcast_to(index[:, :, None, :], (batch, span, heads, width)), + axis=-1, + ) + inside = (distance >= 0) & (distance < extent) + logits = logits + mx.where(inside[:, :, None, :], gathered, 0.0) + mask = block_valid[:, None, :] & (distance >= 0) + if window is not None: + mask = mask & (distance <= window - 1) + logits = mx.where(mask[:, :, None, :], logits, -mx.inf) + if parts: + logits = mx.concatenate([*parts, logits], axis=-1) + width = hi - lo + lse = mx.logsumexp(logits, axis=-1) + probabilities = mx.exp(logits - lse[..., None]) + output = mx.einsum( + "btkgl,blkd->btkgd", + probabilities.reshape(batch, span, kv_heads, groups, width), + values_block, + ).reshape(batch, span, heads, dim) + outputs.append(output) + statistics.append(lse) + if len(outputs) == 1: + return outputs[0], statistics[0] + return mx.concatenate(outputs, axis=1), mx.concatenate(statistics, axis=1) + + +__all__ = ["dense_attention"] diff --git a/models/mlx/resin_models_mlx/inkling2/cache.py b/models/mlx/resin_models_mlx/inkling2/cache.py new file mode 100644 index 00000000..0c321103 --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/cache.py @@ -0,0 +1,343 @@ +"""Inkling 2 global KV, sliding-window KV and convolution history in one MLX arena. + +The arena is one BF16 array of *units* shaped ``[units, 2 * page, kv_width]``. +A unit holds the keys, then the values, of one 128-token page of one layer +visit. A slab belongs to one cache group at a time. Within a KV slab, units are +arranged as ``[layers, blocks_per_slab]``: a visit's pages are consecutive, and +the visits of one logical block are ``blocks_per_slab`` units apart. A STATE +block holds every visit's raw convolution history, ``[visits, 3, width]``, +padded to whole units. + +The layout mirrors the CUDA runner without its DSpark groups: GLOBAL keeps full +history, LOCAL keeps a window large enough for its 1,024 readable tokens plus +one prefill chunk of writes, and STATE publishes prefix snapshots. +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from dataclasses import dataclass + +import mlx.core as mx +import numpy as np + +from resin import CacheGroupFamily, CacheGroupLayout, CacheLayout, CacheRetention +from resin.backend.plans import PagedCachePlan +from resin.backend.resources import CachePoolBinding +from resin.models.inkling2.config import Inkling2Config +from resin_models_mlx.cache_packing import pack_key_values + +PAGE_TOKENS = 128 +GLOBAL_GROUP, LOCAL_GROUP, STATE_GROUP = 0, 1, 2 +BF16_BYTES = 2 + + +@dataclass(frozen=True, slots=True) +class CacheGeometry: + global_layers: int + local_layers: int + kv_heads: int + head_dim: int + state_shape: tuple[int, int, int] + window_tokens: int + prefill_chunk_size: int + + @classmethod + def from_config( + cls, config: Inkling2Config, prefill_chunk_size: int + ) -> CacheGeometry: + if prefill_chunk_size <= 0 or prefill_chunk_size % PAGE_TOKENS: + raise ValueError( + "Inkling 2 prefill chunks must be positive multiples of 128" + ) + return cls( + global_layers=config.execution_global_layer_count, + local_layers=config.execution_local_layer_count, + kv_heads=config.num_key_value_heads, + head_dim=config.head_dim, + state_shape=( + config.execution_layer_count, + config.sconv_kernel_size - 1, + config.state_width(), + ), + window_tokens=config.sliding_window_size, + prefill_chunk_size=prefill_chunk_size, + ) + + @property + def kv_width(self) -> int: + return self.kv_heads * self.head_dim + + @property + def page_tokens(self) -> int: + return PAGE_TOKENS + + @property + def unit_elements(self) -> int: + return 2 * PAGE_TOKENS * self.kv_width + + @property + def state_elements(self) -> int: + return math.prod(self.state_shape) + + @property + def state_units(self) -> int: + return math.ceil(self.state_elements / self.unit_elements) + + @property + def slab_units(self) -> int: + # The smallest slab holding whole blocks of every group. + return math.lcm(self.global_layers, self.local_layers, self.state_units) + + @property + def slab_bytes(self) -> int: + return self.slab_units * self.unit_elements * BF16_BYTES + + @property + def state_bytes(self) -> int: + return self.state_units * self.unit_elements * BF16_BYTES + + def layers(self, group: int) -> int: + return self.global_layers if group == GLOBAL_GROUP else self.local_layers + + def blocks_per_slab(self, group: int) -> int: + if group == STATE_GROUP: + return self.slab_units // self.state_units + return self.slab_units // self.layers(group) + + @property + def local_retained_tokens(self) -> int: + return self.window_tokens + self.prefill_chunk_size - 1 + + def sequence_slabs(self, context: int) -> int: + """Slabs one request needs at ``context`` tokens, excluding snapshots.""" + global_blocks = math.ceil(context / PAGE_TOKENS) + local_blocks = min( + global_blocks, math.ceil(self.local_retained_tokens / PAGE_TOKENS) + 1 + ) + return ( + math.ceil(global_blocks / self.blocks_per_slab(GLOBAL_GROUP)) + + math.ceil(local_blocks / self.blocks_per_slab(LOCAL_GROUP)) + + 1 + ) + + def layout(self, slab_capacity: int) -> CacheLayout: + return CacheLayout( + parent_capacity=slab_capacity, + groups=[ + CacheGroupLayout( + PAGE_TOKENS, blocks_per_slab=self.blocks_per_slab(GLOBAL_GROUP) + ), + CacheGroupLayout( + PAGE_TOKENS, + blocks_per_slab=self.blocks_per_slab(LOCAL_GROUP), + retention=CacheRetention.WINDOW, + window_tokens=self.local_retained_tokens, + read_window_tokens=self.window_tokens, + ), + CacheGroupLayout( + PAGE_TOKENS, + blocks_per_slab=self.blocks_per_slab(STATE_GROUP), + family=CacheGroupFamily.STATE, + ), + ], + ) + + +@dataclass(frozen=True, slots=True) +class History: + """One group's retained earlier tokens for a set of rows. + + ``bases[r, j]`` is the visit-zero unit of row ``r``'s ``j``th retained block, + whose first token is at ``(starts[r] + j) * 128``. ``lengths[r]`` is the + row's context; entries at or beyond it are not history. + """ + + units: mx.array + bases: np.ndarray + starts: np.ndarray + lengths: np.ndarray + layer_stride: int + kv_heads: int + + def gather(self, layer: int) -> tuple[mx.array, mx.array, mx.array, mx.array]: + """Keys, values ``[R, L, KV, D]``, absolute positions and validity ``[R, L]``.""" + rows, width = self.bases.shape + pages = mx.take( + self.units, + mx.array((self.bases + layer * self.layer_stride).reshape(-1)), + axis=0, + ) + pages = pages.reshape(rows, width, 2, PAGE_TOKENS, self.kv_heads, -1) + keys = pages[:, :, 0].reshape(rows, width * PAGE_TOKENS, self.kv_heads, -1) + values = pages[:, :, 1].reshape(rows, width * PAGE_TOKENS, self.kv_heads, -1) + positions = (self.starts[:, None] * PAGE_TOKENS) + np.arange( + width * PAGE_TOKENS + )[None] + counts = self.lengths - self.starts * PAGE_TOKENS + offsets = mx.arange(width * PAGE_TOKENS)[None] + valid = offsets < mx.array(counts.astype(np.int32))[:, None] + return keys, values, mx.array(positions.astype(np.int32)), valid + + +class CacheArena: + """Engine-addressed mutable storage, ordered by an MLX dependency epoch.""" + + def __init__(self, layout: CacheLayout, geometry: CacheGeometry) -> None: + self.layout = layout + self.geometry = geometry + self.binding = CachePoolBinding(layout, resource="Inkling 2 MLX cache") + self.slabs = layout.parent_capacity + 1 + from resin_models_mlx._native import CacheStorage + + self._storage = CacheStorage( + [self.slabs * geometry.slab_units, 2 * PAGE_TOKENS, geometry.kv_width], + mx.bfloat16, + ) + self._epoch = self._storage.initial_epoch() + self._readers: list[mx.array] = [] + mx.eval(self._epoch) + + @property + def nbytes(self) -> int: + return self._storage.nbytes + + @property + def epoch(self) -> mx.array: + return self._epoch + + def order_after(self, reads: Sequence[mx.array]) -> None: + """Queue later mutation after every consumer of the preceding view.""" + self._readers.extend(reads) + + def _read(self) -> mx.array: + return self._storage.read_epoch(self._epoch) + + def units(self) -> mx.array: + """The arena as ``[units, 2, page, kv_width]``, ordered after prior writes.""" + return self._read().reshape(-1, 2, PAGE_TOKENS, self.geometry.kv_width) + + # Reads --------------------------------------------------------------- + + def history( + self, + plan: PagedCachePlan, + group: int, + rows: np.ndarray, + contexts: np.ndarray, + earliest: np.ndarray | None = None, + ) -> History | None: + """Retained blocks holding tokens before ``contexts``; ``None`` if empty. + + ``earliest`` optionally skips whole blocks before that position. + """ + cache_group = plan.groups[group] + geometry = self.geometry + stride = geometry.blocks_per_slab(group) + starts = np.zeros(len(rows), dtype=np.int64) + tables = [] + for index, row in enumerate(rows.tolist()): + first = int(cache_group.block_table_start_indices[row]) + end = math.ceil(int(contexts[index]) / PAGE_TOKENS) + skip = 0 + if earliest is not None: + skip = max(0, int(earliest[index]) // PAGE_TOKENS - first) + slabs = cache_group.block_slabs(row).astype(np.int64) + slots = cache_group.block_slots(row).astype(np.int64) + count = max(0, end - first) + selected = slice(min(skip, count), count) + tables.append(slabs[selected] * geometry.slab_units + slots[selected]) + starts[index] = first + min(skip, count) + width = max((len(table) for table in tables), default=0) + if width == 0: + return None + bases = np.zeros((len(rows), width), dtype=np.int64) + for index, table in enumerate(tables): + bases[index, : len(table)] = table + return History( + self.units(), + bases, + starts, + contexts.astype(np.int64), + stride, + geometry.kv_heads, + ) + + def state_start(self, slab: int, slot: int) -> int: + return slab * self.geometry.slab_units + slot * self.geometry.state_units + + def read_states(self, starts: np.ndarray) -> mx.array: + geometry = self.geometry + units = starts[:, None] + np.arange(geometry.state_units)[None] + storage = self._read() + values = mx.take(storage, mx.array(units.reshape(-1).astype(np.int32)), 0) + values = values.reshape(len(starts), -1)[:, : geometry.state_elements] + return values.reshape(len(starts), *geometry.state_shape) + + # Writes -------------------------------------------------------------- + + def write_tokens( + self, + plan: PagedCachePlan, + group: int, + keys: Sequence[mx.array], + values: Sequence[mx.array], + tokens: np.ndarray, + ) -> None: + """Scatter every visit's K/V rows for flattened plan ``tokens`` into ``group``.""" + cache_group = plan.groups[group] + geometry = self.geometry + slab = cache_group.append_slab_ids[tokens].astype(np.int64) + slot = cache_group.append_slotnums[tokens].astype(np.int64) + offset = cache_group.append_block_offsets[tokens].astype(np.int64) + layers = len(keys) + units = slab[:, None] * geometry.slab_units + ( + slot[:, None] + np.arange(layers) * geometry.blocks_per_slab(group) + ) + rows = np.arange(2)[None, None, :] * PAGE_TOKENS + offset[:, None, None] + update = pack_key_values( + tuple(keys), tuple(values), len(tokens), geometry.kv_width + ) + indices = units[:, :, None] * (2 * PAGE_TOKENS) + rows + self._epoch = self._storage.scatter_rows( + self._epoch, + mx.array(indices.reshape(-1).astype(np.int32)), + update.reshape(-1, geometry.kv_width).astype(mx.bfloat16), + after=self._readers, + ) + self._readers.clear() + + def write_states(self, starts: Sequence[int], state: mx.array) -> None: + geometry = self.geometry + count = len(starts) + padding = ( + geometry.state_units * geometry.unit_elements - geometry.state_elements + ) + flat = state.astype(mx.bfloat16).reshape(count, -1) + if padding: + flat = mx.concatenate( + [flat, mx.zeros((count, padding), dtype=mx.bfloat16)], axis=1 + ) + units = flat.reshape( + count, geometry.state_units, 2 * PAGE_TOKENS, geometry.kv_width + ) + for index, start in enumerate(starts): + self._epoch = self._storage.write_slice( + self._epoch, + start * geometry.unit_elements, + units[index], + after=self._readers, + ) + self._readers.clear() + + +__all__ = [ + "GLOBAL_GROUP", + "LOCAL_GROUP", + "PAGE_TOKENS", + "STATE_GROUP", + "CacheArena", + "CacheGeometry", + "History", +] diff --git a/models/mlx/resin_models_mlx/inkling2/checkpoint.py b/models/mlx/resin_models_mlx/inkling2/checkpoint.py new file mode 100644 index 00000000..753958e8 --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/checkpoint.py @@ -0,0 +1,339 @@ +"""Load Inkling 2 target weights for MLX, keeping NVFP4/MXFP8 experts packed.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import mlx.core as mx + +from resin.models.inkling2.config import Inkling2Config +from resin_models_mlx.inkling2.model import ( + Controller, + Experts, + Inkling2Weights, + Layer, +) + +PREFIX = "model.llm." + +_NVFP4_ACTIVATIONS = { + "amax_type": "per_token", + "block_size": 16, + "format": "nvfp4_e2m1", + "rounding": "nearest", + "scale_dtype": "float8_e4m3fn", + "scale_selection_rule": "fouroversix_mae", +} +_MXFP8_ACTIVATIONS = { + "block_size": 32, + "format": "mxfp8_e4m3", + "rounding": "nearest", + "scale_dtype": "ue8m0", +} + + +def read_config(root: Path) -> Inkling2Config: + values = json.loads((root / "config.json").read_text()) + if not isinstance(values, dict): + raise ValueError("Inkling 2 config.json must contain an object") + return Inkling2Config.from_hugging_face(values) + + +def expert_precision(root: Path) -> dict[str, str]: + """Each expert weight's format, validated against its required activations.""" + metadata = json.loads((root / "hf_quant_config.json").read_text()) + result: dict[str, str] = {} + for group in metadata["model"]["parameter_groups"]: + precision = group["compute_dtype"] + activations = group.get("required_activation_quantization") + if precision == "nvfp4" and activations != _NVFP4_ACTIVATIONS: + raise ValueError("unsupported Inkling 2 NVFP4 activation format") + if precision == "mxfp8" and activations != _MXFP8_ACTIVATIONS: + raise ValueError("unsupported Inkling 2 MXFP8 activation format") + for name in group["tensors"]: + if ".mlp.experts." in name and name.endswith("_weight"): + if precision not in ("nvfp4", "mxfp8") or name in result: + raise ValueError( + f"unsupported or duplicate expert precision: {name}" + ) + result[name] = precision + return result + + +def expected_tensors(config: Inkling2Config, precision: dict[str, str]) -> set[str]: + names = { + "embed.weight", + "embed_norm.weight", + "norm.weight", + "unembed.weight", + "attn_res.output_query", + } + loop = config.loop + if loop is not None: + names |= { + "middle_cycle_cross_pass_queries", + "middle_cycle_cross_pass_kv_queries", + } + for i in range(config.num_hidden_layers): + local = i in config.local_layer_ids + prefix = f"layers.{i}." + if i: + names.add(f"attn_res.attn_queries.{i - 1}") + names.add(f"attn_res.mlp_queries.{i}") + norms = ( + ("attn_norm",) + if local + else ("q_input_norm", "k_input_norm", "v_input_norm") + ) + names |= {prefix + name + ".weight" for name in (*norms, "mlp_norm")} + for name in ( + "wq_du", + "wk_dv", + "wv_dv", + "wr_du", + "gate_attn", + "attn_sink_proj", + "wo_ud", + ): + names.add(prefix + f"attn.{name}.weight") + names |= { + prefix + "attn.q_l2_clip.scale", + prefix + "attn.rel_l2_clip.scale", + prefix + "attn.rel_logits_proj.proj", + } + for name in ("k_sconv", "v_sconv"): + if local: + names.add(prefix + f"attn.{name}.weight") + else: + names |= { + prefix + f"attn.{name}.static_w", + prefix + f"attn.{name}.weight_proj", + } + names |= {prefix + "attn_sconv.weight", prefix + "mlp_sconv.weight"} + names |= {prefix + "mlp.gate.weight", prefix + "mlp.gate.bias"} + for matrix in ("w13", "w2"): + base = prefix + f"mlp.experts.{matrix}_weight" + names |= {base, base + "_scale"} + if precision.get(PREFIX + base) == "nvfp4": + names |= {base + "_amax", base + "_outer_scale_denominator"} + if loop is not None and loop.core_start <= i < loop.core_end: + for stream in ("attn", "k", "v", "mlp"): + for part in ("down_weight", "gain_weight", "forget_weight"): + names.add(prefix + f"controllers.{stream}.{part}") + return {PREFIX + name for name in names} + + +def _load_tensors(root: Path) -> dict[str, mx.array]: + index = json.loads((root / "model.safetensors.index.json").read_text()) + files = sorted({str(name) for name in index["weight_map"].values()}) + tensors: dict[str, mx.array] = {} + for name in files: + loaded = mx.load(str(root / name)) + assert isinstance(loaded, dict) + tensors.update( + (key, value) for key, value in loaded.items() if key.startswith(PREFIX) + ) + return tensors + + +def _experts(tensors: dict[str, mx.array], prefix: str, mode: str) -> Experts: + def weight(name: str) -> mx.array: + # NVFP4 bytes pack two codes (low nibble first); MXFP8 bytes are E4M3 + # codes. MLX reads both as packed uint32 words along the input axis. + return tensors[prefix + name].view(mx.uint8).view(mx.uint32) + + experts = Experts( + w13=weight("w13_weight"), + w13_scales=tensors[prefix + "w13_weight_scale"].view(mx.uint8), + w2=weight("w2_weight"), + w2_scales=tensors[prefix + "w2_weight_scale"].view(mx.uint8), + mode=mode, + ) + if mode == "nvfp4": + experts.w13_amax = tensors[prefix + "w13_weight_amax"].astype(mx.float32) + experts.w2_amax = tensors[prefix + "w2_weight_amax"].astype(mx.float32) + experts.w13_denominator = tensors[prefix + "w13_weight_outer_scale_denominator"] + experts.w2_denominator = tensors[prefix + "w2_weight_outer_scale_denominator"] + return experts + + +def load_weights(root: Path, config: Inkling2Config) -> Inkling2Weights: + precision = expert_precision(root) + tensors = _load_tensors(root) + expected = expected_tensors(config, precision) + if missing := expected - tensors.keys(): + raise ValueError( + f"Inkling 2 checkpoint is missing target weights: {sorted(missing)}" + ) + if extra := tensors.keys() - expected: + raise ValueError( + f"Inkling 2 checkpoint has unexpected target weights: {sorted(extra)}" + ) + + def get(name: str) -> mx.array: + return tensors[PREFIX + name] + + layers = [] + loop = config.loop + for i in range(config.num_hidden_layers): + local = i in config.local_layer_ids + prefix = f"layers.{i}." + modes = { + precision[PREFIX + prefix + f"mlp.experts.{matrix}_weight"] + for matrix in ("w13", "w2") + } + if len(modes) != 1: + raise ValueError(f"Inkling 2 layer {i} mixes expert precisions") + norms = ( + ("attn_norm",) + if local + else ("q_input_norm", "k_input_norm", "v_input_norm") + ) + attention = { + name: get(prefix + f"attn.{name}.weight") + for name in ( + "wq_du", + "wk_dv", + "wv_dv", + "wr_du", + "gate_attn", + "attn_sink_proj", + ) + } + query = [ + attention[name] + for name in ("wq_du", "wr_du", "gate_attn", "attn_sink_proj") + ] + if local: + k_conv = get(prefix + "attn.k_sconv.weight").reshape(-1, 4) + v_conv = get(prefix + "attn.v_sconv.weight").reshape(-1, 4) + projection = mx.concatenate( + [attention["wk_dv"], attention["wv_dv"], *query] + ) + k_projection = v_projection = None + else: + k_conv = get(prefix + "attn.k_sconv.static_w").astype(mx.float32) + v_conv = get(prefix + "attn.v_sconv.static_w").astype(mx.float32) + projection = mx.concatenate(query) + k_projection = mx.concatenate( + [attention["wk_dv"], get(prefix + "attn.k_sconv.weight_proj")] + ) + v_projection = mx.concatenate( + [attention["wv_dv"], get(prefix + "attn.v_sconv.weight_proj")] + ) + controllers = None + if loop is not None and loop.core_start <= i < loop.core_end: + controllers = { + # Gain and forget projections run in FP32; cast them once. + stream: Controller( + down=get(prefix + f"controllers.{stream}.down_weight"), + gain=get(prefix + f"controllers.{stream}.gain_weight").astype( + mx.float32 + ), + forget=get(prefix + f"controllers.{stream}.forget_weight").astype( + mx.float32 + ), + ) + for stream in ("attn", "k", "v", "mlp") + } + layers.append( + Layer( + local=local, + # Norms compute in FP32; keep their weights in FP32 too. + norms=tuple( + get(prefix + name + ".weight").astype(mx.float32) for name in norms + ), + mlp_norm=get(prefix + "mlp_norm.weight").astype(mx.float32), + projection=projection, + k_projection=k_projection, + v_projection=v_projection, + wo=get(prefix + "attn.wo_ud.weight"), + q_scale=get(prefix + "attn.q_l2_clip.scale"), + rel_scale=get(prefix + "attn.rel_l2_clip.scale"), + rel_proj=get(prefix + "attn.rel_logits_proj.proj"), + k_conv=k_conv, + v_conv=v_conv, + attn_conv=get(prefix + "attn_sconv.weight").reshape(-1, 4), + mlp_conv=get(prefix + "mlp_sconv.weight").reshape(-1, 4), + # The router runs in FP32; keep one FP32 copy rather than casting per step. + router=get(prefix + "mlp.gate.weight").astype(mx.float32), + router_bias=get(prefix + "mlp.gate.bias").astype(mx.float32), + experts=_experts( + tensors, PREFIX + prefix + "mlp.experts.", modes.pop() + ), + controllers=controllers, + ) + ) + loop_queries = None + if loop is not None: + queries = get("middle_cycle_cross_pass_queries").astype(mx.float32) + kv_queries = get("middle_cycle_cross_pass_kv_queries").astype(mx.float32) + # Per core layer: query stream, key stream, value stream, MLP. + loop_queries = mx.stack( + [queries[0::2], kv_queries[0::2], kv_queries[1::2], queries[1::2]], axis=1 + ) + weights = Inkling2Weights( + embed=get("embed.weight"), + embed_norm=get("embed_norm.weight").astype(mx.float32), + norm=get("norm.weight").astype(mx.float32), + unembed=get("unembed.weight"), + attn_queries=[ + get(f"attn_res.attn_queries.{i}").astype(mx.float32) + for i in range(config.num_hidden_layers - 1) + ], + mlp_queries=[ + get(f"attn_res.mlp_queries.{i}").astype(mx.float32) + for i in range(config.num_hidden_layers) + ], + output_query=get("attn_res.output_query").astype(mx.float32), + layers=layers, + loop_queries=loop_queries, + ) + # Materialize every lazy load on this thread: a serving actor thread has + # no CPU stream to run the deferred safetensors reads. One layer at a time + # bounds the transient memory of the views. + for layer in weights.layers: + mx.eval(_arrays(layer)) + mx.eval(_arrays(weights)) + return weights + + +def _arrays(value) -> list[mx.array]: + """Every MLX array reachable from a weights dataclass, list, tuple or dict.""" + if isinstance(value, mx.array): + return [value] + if isinstance(value, (list, tuple)): + return [array for item in value for array in _arrays(item)] + if isinstance(value, dict): + return [array for item in value.values() for array in _arrays(item)] + if isinstance(value, (Layer, Experts, Controller)): + return [ + array for name in value.__slots__ for array in _arrays(getattr(value, name)) + ] + if isinstance(value, Inkling2Weights): + return [ + array + for name in value.__slots__ + if name != "layers" + for array in _arrays(getattr(value, name)) + ] + return [] + + +def load_model(path: str | Path) -> tuple[Inkling2Config, Inkling2Weights]: + root = Path(path).expanduser().resolve() + for name in ("config.json", "model.safetensors.index.json", "hf_quant_config.json"): + if not (root / name).is_file(): + raise FileNotFoundError(f"Inkling 2 checkpoint is missing {name}") + config = read_config(root) + return config, load_weights(root, config) + + +__all__ = [ + "expected_tensors", + "expert_precision", + "load_model", + "load_weights", + "read_config", +] diff --git a/models/mlx/resin_models_mlx/inkling2/decode_attention.py b/models/mlx/resin_models_mlx/inkling2/decode_attention.py new file mode 100644 index 00000000..2e55121a --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/decode_attention.py @@ -0,0 +1,270 @@ +"""Inkling 2 decode attention read in place from paged MLX slabs. + +Flash decoding as in ``resin_models_mlx/paged_attention.py`` (one threadgroup +per partition of positions for one row and the query heads of one KV head, +online softmax, log-sum-exp merge), extended with Inkling's semantics: + +* a per-row lower bound, so local visits see only their last ``window`` keys; +* page tables whose first entry is the row's first retained block; +* a relative bias ``bias[row, head, distance]`` added within its extent. + +Positions, bounds and page-table widths are runtime data: new context lengths +or batch sizes do not compile new kernels. The merged output and log-sum-exp +stay FP32 for Inkling's sink and gate. +""" + +from __future__ import annotations + +from functools import cache, partial + +import mlx.core as mx + +from resin_models_mlx.inkling2.kernels import constant, pad_to_device + +PARTITION_TOKENS = 256 +SIMDGROUPS = 4 + +_HEADER = r""" +template +inline void resin_attend( + thread const float (&q)[GROUP][LANE_DIMS], + thread const float (&k)[LANE_DIMS], + thread const float (&v)[LANE_DIMS], + thread const float (&bias)[GROUP], + thread float (&m)[GROUP], + thread float (&l)[GROUP], + thread float (&acc)[GROUP][LANE_DIMS]) { + for (int h = 0; h < GROUP; ++h) { + float dot = 0.0f; + for (int i = 0; i < LANE_DIMS; ++i) dot += q[h][i] * k[i]; + const float score = simd_sum(dot) + bias[h]; + const float peak = max(m[h], score); + const float correction = fast::exp(m[h] - peak); + const float weight = fast::exp(score - peak); + l[h] = l[h] * correction + weight; + for (int i = 0; i < LANE_DIMS; ++i) { + acc[h][i] = acc[h][i] * correction + weight * v[i]; + } + m[h] = peak; + } +} +""" + +_SOURCE = r""" + constexpr int LANE_DIMS = D / 32; + const uint lane = thread_index_in_simdgroup; + const uint group = simdgroup_index_in_threadgroup; + const uint tid = thread_position_in_threadgroup.x; + const int PAGES = geometry[0]; + const int PARTITIONS = geometry[1]; + const int layer = geometry[2]; + const int EXTENT = geometry[3]; + + const int work = threadgroup_position_in_grid.z; + const int partition = work % PARTITIONS; + const int kv_head = (work / PARTITIONS) % KV_HEADS; + const int row = work / (PARTITIONS * KV_HEADS); + const int first_head = kv_head * GROUP; + + // Absolute positions: history [first, context) then the step's own key. + const int context = meta[row * 3 + 0]; + const int first = meta[row * 3 + 1]; + const int start_block = meta[row * 3 + 2]; + const int total = context + 1; + const int start = first + partition * PART; + const int stop = min(start + PART, total); + + float q[GROUP][LANE_DIMS]; + for (int h = 0; h < GROUP; ++h) { + for (int i = 0; i < LANE_DIMS; ++i) { + q[h][i] = float(queries[((row * HEADS) + first_head + h) * D + + lane * LANE_DIMS + i]) * scale[0]; + } + } + float m[GROUP]; + float l[GROUP]; + float acc[GROUP][LANE_DIMS]; + for (int h = 0; h < GROUP; ++h) { + m[h] = -INFINITY; + l[h] = 0.0f; + for (int i = 0; i < LANE_DIMS; ++i) acc[h][i] = 0.0f; + } + + const int width = KV_HEADS * D; + const int run = PART / SIMDGROUPS; + const int lo = start + int(group) * run; + const int hi = min(lo + run, stop); + const int cached = min(hi, context); + float bias_values[GROUP]; + int p = lo; + while (p < cached) { + const int page_end = min(cached, (p / PAGE + 1) * PAGE); + const long unit = long(pages[row * PAGES + (p / PAGE - start_block)]) + layer; + const device T* key = units + (unit * 2 * PAGE + p % PAGE) * width + + kv_head * D + lane * LANE_DIMS; + const device T* value = key + long(PAGE) * width; + for (; p < page_end; ++p) { + float k[LANE_DIMS]; + float v[LANE_DIMS]; + for (int i = 0; i < LANE_DIMS; ++i) { + k[i] = float(key[i]); + v[i] = float(value[i]); + } + const int distance = context - p; + for (int h = 0; h < GROUP; ++h) { + bias_values[h] = distance < EXTENT + ? float(bias[((row * HEADS) + first_head + h) * EXTENT + distance]) + : 0.0f; + } + resin_attend(q, k, v, bias_values, m, l, acc); + key += width; + value += width; + } + } + if (lo <= context && context < hi) { + const int base = (row * KV_HEADS + kv_head) * D + lane * LANE_DIMS; + float k[LANE_DIMS]; + float v[LANE_DIMS]; + for (int i = 0; i < LANE_DIMS; ++i) { + k[i] = float(current_keys[base + i]); + v[i] = float(current_values[base + i]); + } + for (int h = 0; h < GROUP; ++h) { + bias_values[h] = float(bias[((row * HEADS) + first_head + h) * EXTENT]); + } + resin_attend(q, k, v, bias_values, m, l, acc); + } + + threadgroup float shared_m[SIMDGROUPS][GROUP]; + threadgroup float shared_l[SIMDGROUPS][GROUP]; + threadgroup float shared_acc[SIMDGROUPS][GROUP][D]; + for (int h = 0; h < GROUP; ++h) { + if (lane == 0) { + shared_m[group][h] = m[h]; + shared_l[group][h] = l[h]; + } + for (int i = 0; i < LANE_DIMS; ++i) { + shared_acc[group][h][lane * LANE_DIMS + i] = acc[h][i]; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int index = tid; index < GROUP * D; index += SIMDGROUPS * 32) { + const int h = index / D; + const int d = index % D; + float peak = -INFINITY; + for (int s = 0; s < SIMDGROUPS; ++s) peak = max(peak, shared_m[s][h]); + float sum = 0.0f; + float value = 0.0f; + if (peak != -INFINITY) { + for (int s = 0; s < SIMDGROUPS; ++s) { + const float scaled = fast::exp(shared_m[s][h] - peak); + sum += shared_l[s][h] * scaled; + value += shared_acc[s][h][d] * scaled; + } + } + const int out = ((row * HEADS) + first_head + h) * PARTITIONS + partition; + partial[out * D + d] = value; + if (d == 0) { + maxima[out] = peak; + sums[out] = sum; + } + } +""" + + +@cache +def _kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_decode_attention", + input_names=[ + "queries", + "current_keys", + "current_values", + "units", + "pages", + "meta", + "bias", + "geometry", + "scale", + ], + output_names=["partial", "maxima", "sums"], + source=_SOURCE, + header=_HEADER, + ) + + +@partial(mx.compile, shapeless=True) +def _merge(outputs: mx.array, maxima: mx.array, sums: mx.array): + peak = maxima.max(axis=-1, keepdims=True) + weights = mx.where(maxima == -mx.inf, 0.0, mx.exp(maxima - peak)) + numerator = (outputs * weights[..., None]).sum(axis=2) + denominator = (sums * weights).sum(axis=-1) + return numerator / denominator[..., None], peak[..., 0] + mx.log(denominator) + + +def decode_attention( + queries: mx.array, + current_keys: mx.array, + current_values: mx.array, + units: mx.array, + pages: mx.array, + meta: mx.array, + bias: mx.array, + layer: int, + scale: float, + longest: int, +) -> tuple[mx.array, mx.array]: + """One new token per row over paged history plus itself. + + ``queries`` is ``[rows, heads, D]``; current keys/values ``[rows, KV, D]``; + ``units`` the arena as ``[units, 2, page, KV * D]``; ``pages[row, j]`` the + visit-zero unit of the row's ``j``th retained block, offset by ``layer`` + units; ``meta[row] = (context, first visible position, first block)``; + ``bias`` ``[rows, heads, extent]``. ``longest`` bounds ``context + 1 - + first`` over rows and sets the partition count. Returns FP32 + ``[rows, heads, D]`` outputs and ``[rows, heads]`` log-sum-exps. + """ + rows, heads, dim = queries.shape + kv_heads = current_keys.shape[1] + page = units.shape[2] + group = heads // kv_heads + if dim % 32 or heads % kv_heads: + raise ValueError("unsupported Inkling 2 decode attention geometry") + partitions = max(1, -(-longest // PARTITION_TOKENS)) + pages = pad_to_device(pages) + meta = pad_to_device(meta) + outputs, maxima, sums = _kernel()( + inputs=[ + queries, + current_keys, + current_values, + units, + pages, + meta, + bias, + constant((pages.shape[1], partitions, layer, bias.shape[-1]), "int32"), + constant((float(scale),) * 8, "float32"), + ], + template=[ + ("D", dim), + ("HEADS", heads), + ("KV_HEADS", kv_heads), + ("GROUP", group), + ("PAGE", page), + ("PART", PARTITION_TOKENS), + ("SIMDGROUPS", SIMDGROUPS), + ("T", units.dtype), + ], + grid=(32 * SIMDGROUPS, 1, rows * kv_heads * partitions), + threadgroup=(32 * SIMDGROUPS, 1, 1), + output_shapes=[ + (rows, heads, partitions, dim), + (rows, heads, partitions), + (rows, heads, partitions), + ], + output_dtypes=[mx.float32, mx.float32, mx.float32], + ) + return _merge(outputs, maxima, sums) + + +__all__ = ["PARTITION_TOKENS", "decode_attention"] diff --git a/models/mlx/resin_models_mlx/inkling2/kernels.py b/models/mlx/resin_models_mlx/inkling2/kernels.py new file mode 100644 index 00000000..4935459a --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/kernels.py @@ -0,0 +1,720 @@ +"""Fused Inkling 2 elementwise kernels for Apple GPUs. + +Each replaces a chain of small MLX operations whose launches, not their +arithmetic, dominated batch-one decode. Results follow the CPU references in +``resin_models_cuda/inkling2/kernels.py``. +""" + +from __future__ import annotations + +from functools import cache, lru_cache + +import mlx.core as mx +import numpy as np + + +@lru_cache(maxsize=4096) +def constant(values: tuple, dtype: str) -> mx.array: + """A small device array built from data, reused across steps. + + Kernel metadata (geometry, scales, placeholders) would otherwise cost one + array-creation node per call. Arrays built from NumPy data carry no pending + work, so the cached value is safe on any serving thread. Eight or more + elements keep MLX from binding it as a constant (a different kernel ABI). + """ + padded = list(values) + [0] * max(0, 8 - len(values)) + return mx.array(np.array(padded, dtype=dtype)) + + +def pad_to_device(values: mx.array) -> mx.array: + """Pad leading rows so ``values`` has at least eight elements. + + MLX 0.32.4 binds smaller arrays as constants, a different kernel ABI that + would compile another variant for small batches. Kernels index only the + rows they were given, so padding rows are never read. + """ + if values.size >= 8: + return values + width = values.size // max(1, values.shape[0]) if values.ndim > 1 else 1 + rows = -(-8 // max(1, width)) - values.shape[0] + padding = mx.zeros((rows, *values.shape[1:]), dtype=values.dtype) + return mx.concatenate([values, padding]) + + +_CONVOLUTION_SOURCE = r""" + // One thread per (row, channel). State holds three raw inputs, oldest first. + const uint index = thread_position_in_grid.x; + const uint channel = index % C; + const uint row = index / C; + if (row >= uint(geometry[0])) return; + const int tokens = geometry[1]; + float history[3]; + for (int i = 0; i < 3; ++i) + history[i] = float(state[(ulong(row) * 3 + i) * C + channel]); + for (int t = 0; t < tokens; ++t) { + const ulong at = (ulong(row) * tokens + t) * C + channel; + const float current = float(x[at]); + float output = 0.0f; + if (DYNAMIC) { + // Tap zero is the current token; coefficients stay FP32. + const uint head = channel / (C / HEADS); + const ulong taps = ((ulong(row) * tokens + t) * HEADS + head) * 4; + const float values[4] = {current, history[2], history[1], history[0]}; + for (int tap = 0; tap < 4; ++tap) { + const float coefficient = + float(weight[tap * C + channel]) + float(dynamic[taps + tap]); + output = metal::fma(values[tap], coefficient, output); + } + } else { + // Chronological taps rounded to the input dtype; tap three is current. + const float values[4] = {history[0], history[1], history[2], current}; + for (int tap = 0; tap < 4; ++tap) { + const float coefficient = float(T(weight[channel * 4 + tap])); + output = metal::fma(values[tap], coefficient, output); + } + } + // FP32 roundings of 1 / sqrt(9) and 1 / sqrt(5), as the reference uses. + const float scale = DYNAMIC ? 0.3333333432674408f : 0.4472135901451111f; + y[at] = T((output + current) * scale); + history[0] = history[1]; + history[1] = history[2]; + history[2] = current; + } + for (int i = 0; i < 3; ++i) + next_state[(ulong(row) * 3 + i) * C + channel] = T(history[i]); +""" + + +@cache +def _convolution_kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_short_convolution", + input_names=["x", "state", "weight", "dynamic", "geometry"], + output_names=["y", "next_state"], + source=_CONVOLUTION_SOURCE, + ) + + +def short_convolution( + x: mx.array, + state: mx.array, + weight: mx.array, + dynamic: mx.array | None = None, +) -> tuple[mx.array, mx.array]: + """Four residual taps over three raw history inputs; output and new history. + + ``x`` is ``[B, T, C]`` and ``state`` ``[B, 3, C]`` (oldest first), both BF16. + Static ``weight`` is ``[C, 4]`` in chronological order; dynamic convolutions + pass FP32 ``weight [4, C]`` (tap zero current) and ``dynamic [B, T, H, 4]``. + """ + batch, tokens, channels = x.shape + is_dynamic = dynamic is not None + heads = dynamic.shape[-2] if dynamic is not None else 1 + if dynamic is None: + dynamic = constant((), "float32") + geometry = constant((batch, tokens), "int32") + threads = batch * channels + return tuple( + _convolution_kernel()( + inputs=[x, state, weight, dynamic, geometry], + template=[ + ("C", channels), + ("HEADS", heads), + ("DYNAMIC", is_dynamic), + ("T", x.dtype), + ], + grid=(-(-threads // 256) * 256, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[x.shape, (batch, 3, channels)], + output_dtypes=[x.dtype, x.dtype], + ) + ) # type: ignore[return-value] + + +_SIGMOID = r""" + // MLX's sigmoid (mlx/backend/metal/kernels/unary_ops.h, MIT), bit-for-bit. + inline float resin_sigmoid(float x) { + const float y = 1.0f / (1.0f + metal::precise::exp(metal::abs(x))); + return x < 0.0f ? y : 1.0f - y; + } +""" + +_ROUTE_SOURCE = r""" + // One threadgroup per row; thread e owns expert e. + const uint row = threadgroup_position_in_grid.x; + const uint e = thread_position_in_threadgroup.x; + const uint lane = thread_index_in_simdgroup; + const uint simd = simdgroup_index_in_threadgroup; + threadgroup float best_key[32]; + threadgroup uint best_id[32]; + threadgroup uint chosen[TOP_K]; + const float z = e < E ? float(logits[row * E + e]) : 0.0f; + float key = e < E ? resin_sigmoid(z) + float(bias[e]) : -INFINITY; + for (int k = 0; k < TOP_K; ++k) { + // Largest key; equal keys choose the lower expert ID. + float value = key; + uint id = e; + for (uint offset = 16; offset > 0; offset >>= 1) { + const float other = simd_shuffle_down(value, offset); + const uint other_id = simd_shuffle_down(id, offset); + if (other > value || (other == value && other_id < id)) { + value = other; + id = other_id; + } + } + if (lane == 0) { + best_key[simd] = value; + best_id[simd] = id; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (e == 0) { + float top = best_key[0]; + uint top_id = best_id[0]; + for (uint s = 1; s < (E + 31) / 32; ++s) { + if (best_key[s] > top || (best_key[s] == top && best_id[s] < top_id)) { + top = best_key[s]; + top_id = best_id[s]; + } + } + chosen[k] = top_id; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (e == chosen[k]) key = -INFINITY; + } + if (e == 0) { + // Unbiased log-sigmoids, normalized stably over the selection. + float p[TOP_K]; + float peak = -INFINITY; + for (int k = 0; k < TOP_K; ++k) { + const float value = -float(logits[row * E + chosen[k]]); + // log-sigmoid(z) = -logaddexp(0, -z); within an FP32 ULP of MLX's ops. + const float high = metal::max(value, 0.0f); + const float low = metal::min(value, 0.0f); + p[k] = -(high + log1p(metal::precise::exp(low - high))); + peak = metal::max(peak, p[k]); + } + float shifted[TOP_K]; + for (int k = 0; k < TOP_K; ++k) shifted[k] = metal::precise::exp(p[k] - peak); + float total; + if (TOP_K == 8) { + total = ((shifted[0] + shifted[2]) + (shifted[1] + shifted[3])) + + ((shifted[4] + shifted[6]) + (shifted[5] + shifted[7])); + } else { + total = 0.0f; + for (int k = 0; k < TOP_K; ++k) total += shifted[k]; + } + const float normalizer = peak + metal::precise::log(total); + for (int k = 0; k < TOP_K; ++k) { + ids[row * TOP_K + k] = chosen[k]; + weights[row * TOP_K + k] = metal::precise::exp(p[k] - normalizer) * scale[0]; + } + } +""" + +_FACTOR = r""" + // NVFP4 output scale: activation amax times weight amax over 1536 * denominator. + inline float resin_factor(float activation_amax, float weight_amax, float denominator) { + return (activation_amax * weight_amax) * metal::precise::divide(1.0f, 1536.0f * denominator); + } +""" + +_ACTIVATE_SOURCE = r""" + // One thread per (route, intermediate channel); gate and up rows interleave. + const uint index = thread_position_in_grid.x; + const uint route = index / I; + const uint j = index % I; + if (route >= uint(geometry[0])) return; + float factor = 1.0f; + if (NVFP4) { + factor = resin_factor( + float(activation_amax[rows[route]]), float(weight_amax[ids[route]]), + float(denominator[0])); + } + const ulong at = ulong(route) * (2 * I) + 2 * j; + // The packed GEMM rounds each scaled output to BF16. + const float gate = float(bfloat(float(gate_up[at]) * factor)); + const float up = float(bfloat(float(gate_up[at + 1]) * factor)); + const float capped_gate = GATE_CAP * metal::precise::tanh(gate / GATE_CAP); + const float capped_up = UP_CAP * metal::precise::tanh(up / UP_CAP); + const float sigmoid = resin_sigmoid(gate); + activated[ulong(route) * I + j] = + bfloat(((capped_gate * sigmoid) * capped_up) * float(gamma[route])); +""" + +_COMBINE_SOURCE = r""" + // One thread per (row, hidden channel): round each route, sum slots in order. + const uint index = thread_position_in_grid.x; + const uint row = index / H; + const uint c = index % H; + if (row >= uint(geometry[0])) return; + float total = 0.0f; + for (int slot = 0; slot < TOP_K; ++slot) { + const uint route = inverse[row * TOP_K + slot]; + float factor = 1.0f; + if (NVFP4) { + factor = resin_factor( + float(activation_amax[route]), float(weight_amax[ids[route]]), + float(denominator[0])); + } + const float value = float(bfloat(float(down[ulong(route) * H + c]) * factor)); + total = slot == 0 ? value : total + value; + } + output[ulong(row) * H + c] = bfloat(total); +""" + + +@cache +def _route_kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_route_experts", + input_names=["logits", "bias", "scale"], + output_names=["ids", "weights"], + header=_SIGMOID, + source=_ROUTE_SOURCE, + ) + + +@cache +def _activate_kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_expert_activation", + input_names=[ + "gate_up", + "gamma", + "rows", + "ids", + "activation_amax", + "weight_amax", + "denominator", + "geometry", + ], + output_names=["activated"], + header=_FACTOR + _SIGMOID, + source=_ACTIVATE_SOURCE, + ) + + +@cache +def _combine_kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_expert_combine", + input_names=[ + "down", + "inverse", + "ids", + "activation_amax", + "weight_amax", + "denominator", + "geometry", + ], + output_names=["output"], + header=_FACTOR, + source=_COMBINE_SOURCE, + ) + + +def _geometry(*values: int) -> mx.array: + return constant(tuple(values), "int32") + + +def _placeholder(dtype: str = "float32") -> mx.array: + return constant((), dtype) + + +def route_experts( + logits: mx.array, bias: mx.array, top_k: int, scale: float +) -> tuple[mx.array, mx.array]: + """Top-k by biased sigmoid (lower ID wins ties); unbiased normalized weights.""" + rows, experts = logits.shape + if experts > 1024: + raise ValueError("Inkling 2 routing supports at most 1024 experts") + threads = max(32, -(-experts // 32) * 32) + ids, weights = _route_kernel()( + inputs=[logits, bias, constant((float(scale),) * 8, "float32")], + template=[("E", experts), ("TOP_K", top_k)], + grid=(rows * threads, 1, 1), + threadgroup=(threads, 1, 1), + output_shapes=[(rows, top_k), (rows, top_k)], + output_dtypes=[mx.uint32, mx.float32], + ) + return ids, weights + + +def expert_activation( + gate_up: mx.array, + gamma: mx.array, + gate_cap: float, + up_cap: float, + rows: mx.array | None = None, + ids: mx.array | None = None, + activation_amax: mx.array | None = None, + weight_amax: mx.array | None = None, + denominator: mx.array | None = None, +) -> mx.array: + """Scale (NVFP4), round, then capped SwiGLU times the route weight, in BF16.""" + routes, width = gate_up.shape + intermediate = width // 2 + nvfp4 = activation_amax is not None + if not float(gate_cap).is_integer() or not float(up_cap).is_integer(): + raise ValueError("Inkling 2 expert softcaps must be whole numbers") + placeholder = _placeholder() + threads = routes * intermediate + return _activate_kernel()( + inputs=[ + gate_up, + gamma, + rows if rows is not None else _placeholder("uint32"), + ids if ids is not None else _placeholder("uint32"), + activation_amax if activation_amax is not None else placeholder, + weight_amax if weight_amax is not None else placeholder, + denominator if denominator is not None else placeholder, + _geometry(routes), + ], + template=[ + ("I", intermediate), + ("NVFP4", nvfp4), + ("GATE_CAP", int(gate_cap)), + ("UP_CAP", int(up_cap)), + ], + grid=(-(-threads // 256) * 256, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[(routes, intermediate)], + output_dtypes=[mx.bfloat16], + )[0] + + +def expert_combine( + down: mx.array, + inverse: mx.array, + top_k: int, + ids: mx.array | None = None, + activation_amax: mx.array | None = None, + weight_amax: mx.array | None = None, + denominator: mx.array | None = None, +) -> mx.array: + """Scale (NVFP4) and round each route to BF16; sum each row's slots in order.""" + routes, hidden = down.shape + rows = routes // top_k + placeholder = _placeholder() + threads = rows * hidden + return _combine_kernel()( + inputs=[ + down, + inverse, + ids if ids is not None else _placeholder("uint32"), + activation_amax if activation_amax is not None else placeholder, + weight_amax if weight_amax is not None else placeholder, + denominator if denominator is not None else placeholder, + _geometry(rows), + ], + template=[ + ("H", hidden), + ("TOP_K", top_k), + ("NVFP4", activation_amax is not None), + ], + grid=(-(-threads // 256) * 256, 1, 1), + threadgroup=(256, 1, 1), + output_shapes=[(rows, hidden)], + output_dtypes=[mx.bfloat16], + )[0] + + +_THREADS = 256 + +_MIX_TEMPLATE = r""" + // One threadgroup per token row. Normalize each source over H, score it + // against each query row, softmax over sources, and mix normalized values. + constexpr int PER = (H + THREADS - 1) / THREADS; + constexpr int SIMDS = THREADS / 32; + constexpr int SUMS = S * (R + 1); + const uint row = threadgroup_position_in_grid.x; + const uint tid = thread_position_in_threadgroup.x; + const uint lane = thread_index_in_simdgroup; + const uint simd = simdgroup_index_in_threadgroup; + threadgroup float partial_sums[SUMS][SIMDS]; + threadgroup float totals[SUMS]; + float values[S][PER]; + float sums[SUMS]; + for (int i = 0; i < SUMS; ++i) sums[i] = 0.0f; + $LOADS$ + for (int s = 0; s < S; ++s) + for (int k = 0; k < PER; ++k) sums[s] += values[s][k] * values[s][k]; + $REDUCE$ + float inverse[S]; + for (int s = 0; s < S; ++s) + inverse[s] = metal::precise::rsqrt(totals[s] / float(H) + 1e-6f); + for (int s = 0; s < S; ++s) + for (int k = 0; k < PER; ++k) values[s][k] *= inverse[s]; + for (int i = 0; i < SUMS; ++i) sums[i] = 0.0f; + for (int k = 0; k < PER; ++k) { + const uint c = tid + k * THREADS; + if (c >= H) continue; + for (int r = 0; r < R; ++r) { + const float q = float(queries[r * H + c]); + for (int s = 0; s < S; ++s) sums[S + r * S + s] += values[s][k] * q; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + $REDUCE$ + const float scale = metal::precise::rsqrt(float(H)); + for (int r = 0; r < R; ++r) { + float scores[S]; + float peak = -INFINITY; + for (int s = 0; s < S; ++s) { + scores[s] = totals[S + r * S + s] * scale; + peak = metal::max(peak, scores[s]); + } + float denominator = 0.0f; + for (int s = 0; s < S; ++s) { + scores[s] = metal::precise::exp(scores[s] - peak); + denominator += scores[s]; + } + for (int k = 0; k < PER; ++k) { + const uint c = tid + k * THREADS; + if (c >= H) continue; + float mixed = 0.0f; + for (int s = 0; s < S; ++s) mixed += (scores[s] / denominator) * values[s][k]; + output[(ulong(row) * R + r) * H + c] = mixed; + } + } +""" + +_MIX_REDUCE = r""" + for (int i = 0; i < SUMS; ++i) { + const float value = simd_sum(sums[i]); + if (lane == 0) partial_sums[i][simd] = value; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < SUMS) { + float total = 0.0f; + for (int g = 0; g < SIMDS; ++g) total += partial_sums[tid][g]; + totals[tid] = total; + } + threadgroup_barrier(mem_flags::mem_threadgroup); +""" + + +@cache +def _mix_kernel(sources: int, addend: bool): + loads = [] + for index in range(sources): + extra = ( + " + float(addend[ulong(row) * H + c])" + if addend and index == sources - 1 + else "" + ) + loads.append( + f"for (int k = 0; k < PER; ++k) {{ const uint c = tid + k * THREADS; " + f"values[{index}][k] = c < H ? float(s{index}[ulong(row) * H + c]){extra} : 0.0f; }}" + ) + source = _MIX_TEMPLATE.replace("$LOADS$", "\n ".join(loads)).replace( + "$REDUCE$", _MIX_REDUCE + ) + names = ( + [f"s{i}" for i in range(sources)] + (["addend"] if addend else []) + ["queries"] + ) + return mx.fast.metal_kernel( + name=f"resin_inkling2_depth_mix_{sources}{'a' if addend else ''}", + input_names=names, + output_names=["output"], + source=source, + ) + + +def depth_mix( + sources: list[mx.array], queries: mx.array, addend: mx.array | None = None +) -> mx.array: + """Attention over residual blocks; FP32 ``[rows, R, H]`` for query rows ``R``. + + Each source is ``[rows, H]``; ``addend`` (optional) adds to the last source + before normalization. Values are RMS-normalized (no weight, eps 1e-6). + """ + rows, width = sources[0].shape + queries = queries.reshape(-1, width) + if queries.dtype != mx.float32: + queries = queries.astype(mx.float32) + inputs = [*sources, *([addend] if addend is not None else []), queries] + return _mix_kernel(len(sources), addend is not None)( + inputs=inputs, + template=[ + ("H", width), + ("R", queries.shape[0]), + ("S", len(sources)), + ("THREADS", _THREADS), + ], + grid=(rows * _THREADS, 1, 1), + threadgroup=(_THREADS, 1, 1), + output_shapes=[(rows, queries.shape[0], width)], + output_dtypes=[mx.float32], + )[0] + + +_NORM_SOURCE = r""" + // One threadgroup per row: FP32 sum of squares, then one rounding to the output. + constexpr int PER = (H + THREADS - 1) / THREADS; + constexpr int SIMDS = THREADS / 32; + const uint row = threadgroup_position_in_grid.x; + const uint tid = thread_position_in_threadgroup.x; + const uint lane = thread_index_in_simdgroup; + const uint simd = simdgroup_index_in_threadgroup; + threadgroup float partial_sums[SIMDS]; + threadgroup float total; + float values[PER]; + float sum = 0.0f; + for (int k = 0; k < PER; ++k) { + const uint c = tid + k * THREADS; + values[k] = c < H ? float(x[ulong(row) * H + c]) : 0.0f; + sum += values[k] * values[k]; + } + sum = simd_sum(sum); + if (lane == 0) partial_sums[simd] = sum; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0) { + float value = 0.0f; + for (int g = 0; g < SIMDS; ++g) value += partial_sums[g]; + total = value; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float inverse = metal::precise::rsqrt(total / float(H) + eps[0]); + for (int k = 0; k < PER; ++k) { + const uint c = tid + k * THREADS; + if (c >= H) continue; + float value = values[k] * inverse; + if (WEIGHTED) value *= float(weight[c]); + output[ulong(row) * H + c] = bfloat(value); + } +""" + + +@cache +def _norm_kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_rms_norm", + input_names=["x", "weight", "eps"], + output_names=["output"], + source=_NORM_SOURCE, + ) + + +def rms_norm(x: mx.array, weight: mx.array | None, eps: float) -> mx.array: + """FP32 RMS normalization times an optional FP32 weight, rounded once to BF16.""" + width = x.shape[-1] + rows = x.size // width + threads = 256 if width >= 256 else max(32, -(-width // 32) * 32) + return _norm_kernel()( + inputs=[ + x, + weight if weight is not None else constant((), "float32"), + constant((float(eps),) * 8, "float32"), + ], + template=[("H", width), ("THREADS", threads), ("WEIGHTED", weight is not None)], + grid=(rows * threads, 1, 1), + threadgroup=(threads, 1, 1), + output_shapes=[x.shape], + output_dtypes=[mx.bfloat16], + )[0] + + +_GEMV_SOURCE = r""" + // FP32 output = x[ROWS, K] . W[N, K]^T with BF16 W, FP32 accumulation. + // Each simdgroup owns OUTPUTS consecutive weight rows; every batch row + // reuses each loaded weight vector. + const uint lane = thread_index_in_simdgroup; + const uint simd = simdgroup_index_in_threadgroup; + const uint first = (threadgroup_position_in_grid.x * SIMDS + simd) * OUTPUTS; + const int rows = geometry[0]; + float acc[OUTPUTS][MAX_ROWS]; + for (int o = 0; o < OUTPUTS; ++o) + for (int r = 0; r < MAX_ROWS; ++r) acc[o][r] = 0.0f; + for (uint k = lane * 8; k < K; k += 32 * 8) { + float xs[MAX_ROWS][8]; + for (int r = 0; r < MAX_ROWS; ++r) + for (int i = 0; i < 8; ++i) + xs[r][i] = r < rows ? float(x[ulong(r) * K + k + i]) : 0.0f; + for (int o = 0; o < OUTPUTS; ++o) { + const uint n = first + o; + if (n >= N) break; + const device bfloat* w = weight + ulong(n) * K + k; + float ws[8]; + for (int i = 0; i < 8; ++i) ws[i] = float(w[i]); + for (int r = 0; r < MAX_ROWS; ++r) { + float dot = 0.0f; + for (int i = 0; i < 8; ++i) dot = metal::fma(xs[r][i], ws[i], dot); + acc[o][r] += dot; + } + } + } + for (int o = 0; o < OUTPUTS; ++o) { + const uint n = first + o; + for (int r = 0; r < MAX_ROWS; ++r) { + const float total = simd_sum(acc[o][r]); + if (lane == 0 && n < N && r < rows) output[ulong(r) * N + n] = total; + } + } +""" + + +@cache +def _gemv_kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_bf16_gemv_f32", + input_names=["x", "weight", "geometry"], + output_names=["output"], + source=_GEMV_SOURCE, + ) + + +# Rows per GEMV launch: up to four rows reuse each weight load at full bandwidth +# (2.2 ms for the 201K-row vocabulary on an M4 Max); eight rows in one launch +# run slower than two launches of four. +GEMV_ROWS = 4 + + +def gemv_f32(x: mx.array, weight: mx.array) -> mx.array: + """FP32 ``x @ weight.T`` for BF16 rows; ``weight`` is BF16 ``[N, K]``. + + Reads the BF16 weights at full bandwidth instead of casting them to FP32 + (or keeping an FP32 copy). Each launch serves at most four rows and is + specialized by its row count; more rows, such as prompt scores, run in + groups of four. + """ + rows, width = x.shape + if width % 256: + return x.astype(mx.float32) @ weight.astype(mx.float32).T + if rows > GEMV_ROWS: + return mx.concatenate( + [ + gemv_f32(x[start : start + GEMV_ROWS], weight) + for start in range(0, rows, GEMV_ROWS) + ] + ) + outputs_per_simd, simds = 4, 8 + count = weight.shape[0] + groups = -(-count // (outputs_per_simd * simds)) + return _gemv_kernel()( + inputs=[x.astype(mx.bfloat16), weight, constant((rows,), "int32")], + template=[ + ("K", width), + ("N", count), + ("OUTPUTS", outputs_per_simd), + ("SIMDS", simds), + ("MAX_ROWS", rows), + ], + grid=(groups * 32 * simds, 1, 1), + threadgroup=(32 * simds, 1, 1), + output_shapes=[(rows, count)], + output_dtypes=[mx.float32], + )[0] + + +__all__ = [ + "constant", + "pad_to_device", + "gemv_f32", + "rms_norm", + "depth_mix", + "expert_activation", + "expert_combine", + "route_experts", + "short_convolution", +] diff --git a/models/mlx/resin_models_mlx/inkling2/model.py b/models/mlx/resin_models_mlx/inkling2/model.py new file mode 100644 index 00000000..87750b2d --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/model.py @@ -0,0 +1,605 @@ +"""Inkling 2 target forward pass on MLX: looped layers, depth mixes and sparse MLPs. + +The arithmetic follows the CUDA runner (``resin_models_cuda/inkling2/model.py`` +and its CPU references in ``kernels.py``), including its BF16 rounding points. +Attention storage is supplied by the caller through :class:`AttentionStore`, so +the same forward pass runs over a dense test cache or the Engine's paged arena. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from functools import update_wrapper +from typing import Protocol + +import mlx.core as mx +import numpy as np + +from resin.models.inkling2.config import Inkling2Config +from resin_models_mlx.inkling2.kernels import depth_mix as fused_depth_mix +from resin_models_mlx.inkling2.kernels import ( + expert_activation, + expert_combine, + gemv_f32, + pad_to_device, + rms_norm, + route_experts, + short_convolution, +) +from resin_models_mlx.inkling2.quantization import quantize_activations + +BF16 = mx.bfloat16 +F32 = mx.float32 + + +def _decode_compiled(function): + """Fuse ``function`` with ``mx.compile`` for one-token (decode) inputs only. + + Decode shapes depend only on the batch size, a small bounded set. Prefill + chunk lengths vary with every prompt, so prefill runs uncompiled rather + than compiling a new graph for each new length. + """ + compiled = mx.compile(function) + + def call(first, *args): + return (compiled if first.shape[1] == 1 else function)(first, *args) + + return update_wrapper(call, function) + + +class AttentionStore(Protocol): + """Write one visit's keys and values, then attend over its retained history.""" + + def attend( + self, + local: bool, + slot: int, + q: mx.array, + k: mx.array, + v: mx.array, + bias: mx.array, + scale: float, + window: int, + ) -> tuple[mx.array, mx.array]: + """Return FP32 ``[B, T, H, D]`` outputs and ``[B, T, H]`` log-sum-exps. + + ``q`` is ``[B, T, H, D]``, ``k``/``v`` are ``[B, T, KV, D]`` and ``bias`` + is ``[B, T, H, E]``: entry ``e`` applies to the key ``e`` positions + before the query. ``slot`` indexes the visit within its local or global + cache group. Local visits see at most ``window`` keys. + """ + ... + + +@dataclass(slots=True) +class Experts: + """Packed expert weights for one layer and their quantization modes.""" + + w13: mx.array + w13_scales: mx.array + w2: mx.array + w2_scales: mx.array + mode: str + # NVFP4 only: per-expert weight amax and the output scale denominator. + w13_amax: mx.array | None = None + w2_amax: mx.array | None = None + w13_denominator: mx.array | None = None + w2_denominator: mx.array | None = None + + @property + def group_size(self) -> int: + return 16 if self.mode == "nvfp4" else 32 + + @property + def bits(self) -> int: + return 4 if self.mode == "nvfp4" else 8 + + +@dataclass(slots=True) +class Controller: + down: mx.array + gain: mx.array + forget: mx.array + + +@dataclass(slots=True) +class Layer: + local: bool + # Local layers use ``attn_norm`` for every stream; global layers use q/k/v norms. + norms: tuple[mx.array, ...] + mlp_norm: mx.array + # Packed projections, as in the CUDA runner. Local layers: rows + # [K | V | Q | rel | gate | sink] of one shared source, the last four + # contiguous for a separate query stream. Global layers: [Q | rel | gate | + # sink] here, with K and V packed beside their dynamic-convolution taps. + projection: mx.array + k_projection: mx.array | None + v_projection: mx.array | None + wo: mx.array + q_scale: mx.array + rel_scale: mx.array + rel_proj: mx.array + # Local: chronological [C, 4] static taps. Global: FP32 [4, C] static taps + # (tap zero is the current token); their dynamic part is in K/V projections. + k_conv: mx.array + v_conv: mx.array + attn_conv: mx.array + mlp_conv: mx.array + router: mx.array + router_bias: mx.array + experts: Experts + controllers: dict[str, Controller] | None = None + + +@dataclass(slots=True) +class Inkling2Weights: + embed: mx.array + embed_norm: mx.array + norm: mx.array + unembed: mx.array + attn_queries: list[mx.array] + mlp_queries: list[mx.array] + output_query: mx.array + layers: list[Layer] + # Loop message queries, stacked [core layers, 4, H]: q, k, v and MLP streams. + loop_queries: mx.array | None = None + + +def linear(x: mx.array, weight: mx.array) -> mx.array: + """BF16 GEMM with FP32 accumulation and a BF16 result.""" + return x @ weight.T + + +def linear_f32(x: mx.array, weight: mx.array) -> mx.array: + """FP32 GEMM against a weight stored in FP32 at load.""" + return x.astype(F32) @ weight.T + + +def depth_mix( + sources: list[mx.array], + query: mx.array, + addend: mx.array | None = None, +) -> list[mx.array]: + """Attend over residual blocks with normalized values; FP32 outputs per query row.""" + shape = sources[0].shape + width = shape[-1] + mixed = fused_depth_mix( + [x.reshape(-1, width) for x in sources], + query, + None if addend is None else addend.reshape(-1, width), + ) + return [mixed[:, row].reshape(shape) for row in range(mixed.shape[1])] + + +@_decode_compiled +def l2_clip( + x: mx.array, scale: mx.array | None, threshold: float, tau: mx.array | None +) -> mx.array: + values = x.astype(F32) if scale is None else x.astype(F32) * scale.astype(F32) + norm = mx.sqrt(mx.sum(values * values, axis=-1, keepdims=True)) + values = values * mx.minimum(threshold / (norm + 1e-6), 1.0) + values = values.astype(x.dtype) + if tau is not None: + values = (values.astype(F32) * tau[..., None, None]).astype(x.dtype) + return values + + +def log_scaling_tau(positions: mx.array, n_floor: int, alpha: float) -> mx.array: + effective = (positions + 1).astype(F32) + 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. + """ + 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] + if activation_amax is not None: + activation_amax = pad_to_device(activation_amax) + 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.""" + counts = np.bincount(np.array(sorted_ids), minlength=experts) + stops = np.cumsum(counts) + return [ + (expert, int(stops[expert] - counts[expert]), int(stops[expert])) + for expert in np.flatnonzero(counts).tolist() + ] + + +@_decode_compiled +def _sort_routes(ids, weights, top_k: int): + """Order routes by expert; ``ids``/``weights`` are ``[B, T, top_k]``.""" + flat_ids = ids.reshape(-1) + order = mx.argsort(flat_ids) + source_rows = (order // top_k).astype(mx.uint32) + inverse = mx.argsort(order).astype(mx.uint32) + return flat_ids[order], source_rows, weights.reshape(-1)[order], inverse + + +def sparse_mlp(x: mx.array, layer: Layer, config: Inkling2Config) -> mx.array: + """Route each row to its experts; returns the BF16 sum of BF16-rounded routes.""" + shape = x.shape + flat = x.reshape(-1, shape[-1]) + top_k = config.experts_per_token + ids, weights = route_experts( + flat.astype(F32) @ layer.router.T, layer.router_bias, top_k, config.route_scale + ) + sorted_ids, source_rows, gamma, inverse = _sort_routes( + ids.reshape(*shape[:2], top_k), weights.reshape(*shape[:2], top_k), top_k + ) + 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, + gamma, + config.mlp_gate_softcap, + config.mlp_up_softcap, + source_rows, + sorted_ids, + gate_up_amax if nvfp4 else None, + experts.w13_amax, + experts.w13_denominator, + ) + down, down_amax = _expert_matmul( + activated, experts.w2, experts.w2_scales, experts, None, sorted_ids, segments + ) + return expert_combine( + down, + inverse, + top_k, + sorted_ids, + down_amax if nvfp4 else None, + experts.w2_amax, + experts.w2_denominator, + ).reshape(shape) + + +@_decode_compiled +def _controller( + dest: mx.array, message: mx.array, down: mx.array, gain: mx.array, forget: mx.array +) -> mx.array: + pair = mx.stack([dest, message], axis=-2) + normalized = rms_norm(pair, None, 1e-6).reshape(*dest.shape[:-1], -1) + hidden = linear(normalized, down) + gain_values = mx.tanh(linear_f32(hidden, gain)) + forget_values = mx.tanh(linear_f32(hidden, forget)) + return (1 - forget_values) * dest.astype(F32) + gain_values * message.astype(F32) + + +def controller(dest: mx.array, message: mx.array, weights: Controller) -> mx.array: + """Blend a pass message into a residual stream through a rank-limited gate.""" + return _controller(dest, message, weights.down, weights.gain, weights.forget) + + +def logits( + hidden: mx.array, weights: Inkling2Weights, config: Inkling2Config +) -> mx.array: + """FP32 logits from BF16 weights, sliced to the real vocabulary and softcapped.""" + shape = hidden.shape + values = gemv_f32(hidden.reshape(-1, shape[-1]), weights.unembed) + values = values.reshape(*shape[:-1], -1)[..., : config.unpadded_vocab_size] + cap = config.final_logit_softcapping + return cap * mx.tanh(values * (1.0 / cap)) + + +class Inkling2Model: + """Inkling 2 target over an :class:`AttentionStore`. + + ``state`` holds each visit's raw convolution history, ``[B, visits, 3, W]`` + with channels ``[K inputs | V inputs | attention-conv | MLP-conv]``. + """ + + def __init__(self, config: Inkling2Config, weights: Inkling2Weights) -> None: + if not config.attn_res_normalize_values: + raise ValueError("the Inkling 2 MLX depth mix requires normalized values") + self.config, self.weights = config, weights + order = config.layer_order + slots = {} + for group in ( + config.execution_local_layer_ids, + config.execution_global_layer_ids, + ): + slots.update((visit, slot) for slot, visit in enumerate(group)) + self.visits = tuple((layer, slots[visit]) for visit, layer in enumerate(order)) + self.kv_width = config.num_key_value_heads * config.head_dim + self.state_width = config.state_width() + + def initial_state(self, batch: int) -> mx.array: + shape = (batch, self.config.execution_layer_count, 3, self.state_width) + return mx.zeros(shape, dtype=BF16) + + def embed(self, token_ids: mx.array) -> mx.array: + weights = self.weights + return rms_norm( + weights.embed[token_ids], weights.embed_norm, self.config.rms_norm_eps + ) + + def __call__( + self, + token_ids: mx.array, + positions: mx.array, + state: mx.array, + store: AttentionStore, + *, + last_only: bool = True, + ) -> tuple[mx.array, mx.array]: + """Return softcapped FP32 logits and the next convolution state.""" + hidden, next_state = self.hidden(token_ids, positions, state, store) + if last_only: + hidden = hidden[:, -1:] + return logits(hidden, self.weights, self.config), next_state + + def hidden( + self, + token_ids: mx.array, + positions: mx.array, + state: mx.array, + store: AttentionStore, + ) -> tuple[mx.array, mx.array]: + config, weights = self.config, self.weights + eps = config.rms_norm_eps + tau = log_scaling_tau( + positions, config.log_scaling_n_floor, config.log_scaling_alpha + ) + partial = self.embed(token_ids) + blocks: list[mx.array] = [] + loop = config.loop + prelude: tuple[list[mx.array], mx.array] | None = None + message_bank: list[mx.array] = [] + kv, hidden_size = self.kv_width, config.hidden_size + next_states = [] + for visit, (index, slot) in enumerate(self.visits): + layer = weights.layers[index] + if loop is not None: + if index == loop.core_start: + if prelude is None: + prelude = (blocks.copy(), partial) + else: + prelude_blocks, prelude_partial = prelude + # Only blocks produced inside the previous pass carry messages. + message_bank = [*blocks[len(prelude_blocks) + 1 :], partial] + blocks, partial = prelude_blocks.copy(), prelude_partial + elif index == loop.core_end: + message_bank = [] + streams = ( + depth_mix([*blocks, partial], weights.attn_queries[index - 1]) + if blocks + else [partial] * (1 if layer.local else 3) + ) + messages = None + if message_bank: + assert loop is not None and layer.controllers is not None + assert weights.loop_queries is not None + query = weights.loop_queries[index - loop.core_start] + messages = depth_mix(message_bank, query) + if layer.local: + streams = streams * 3 + streams = [ + controller(stream, message, layer.controllers[name]) + for name, stream, message in zip( + ("attn", "k", "v"), streams, messages[:3], strict=True + ) + ] + if layer.local and messages is None: + q_source = rms_norm(streams[0], layer.norms[0], eps) + sources = (q_source, q_source, q_source) + else: + norms = layer.norms * 3 if layer.local else layer.norms + sources = tuple( + rms_norm(x, norm, eps) + for norm, x in zip(norms, streams, strict=True) + ) + visit_state = state[:, visit] + attention, k_history, v_history = self._attention( + layer, sources, visit_state, tau, visit, slot, store + ) + attention_state = visit_state[..., 2 * kv : 2 * kv + hidden_size] + attention, attention_history = short_convolution( + attention, attention_state, layer.attn_conv + ) + boundary = index % config.n_layers_per_attn_res_block == 0 + mlp_sources = ( + [*blocks, partial, attention] if boundary else [*blocks, partial] + ) + mlp_input = depth_mix( + mlp_sources, + weights.mlp_queries[index], + None if boundary else attention, + )[0] + if messages is not None: + assert layer.controllers is not None + mlp_input = controller(mlp_input, messages[3], layer.controllers["mlp"]) + normalized = rms_norm(mlp_input, layer.mlp_norm, eps) + expert_output = sparse_mlp(normalized, layer, config) + mlp_state = visit_state[..., -hidden_size:] + mlp, mlp_history = short_convolution( + expert_output, mlp_state, layer.mlp_conv + ) + if boundary: + blocks.append(partial) + partial = (attention.astype(F32) + mlp.astype(F32)).astype(BF16) + else: + partial = ( + partial.astype(F32) + attention.astype(F32) + mlp.astype(F32) + ).astype(BF16) + next_states.append( + mx.concatenate( + [k_history, v_history, attention_history, mlp_history], axis=-1 + ) + ) + hidden = rms_norm( + depth_mix([*blocks, partial], weights.output_query)[0], weights.norm, eps + ) + return hidden, mx.stack(next_states, axis=1) + + def _attention( + self, + layer: Layer, + sources: tuple[mx.array, ...], + state: mx.array, + tau: mx.array, + visit: int, + slot: int, + store: AttentionStore, + ) -> tuple[mx.array, mx.array, mx.array]: + config = self.config + q_source, k_source, v_source = sources + batch, tokens, _ = q_source.shape + heads, kv_heads = config.num_attention_heads, config.num_key_value_heads + if layer.local: + heads, kv_heads = ( + config.swa_num_attention_heads, + config.swa_num_key_value_heads, + ) + d, r, width = config.head_dim, config.d_rel, self.kv_width + query_sizes = (heads * d, heads * r, heads * d) + k_dynamic = v_dynamic = None + if layer.local: + if k_source is q_source and v_source is q_source: + projected = linear(q_source, layer.projection) + k_input, v_input = ( + projected[..., :width], + projected[..., width : 2 * width], + ) + query = projected[..., 2 * width :] + else: + k_input = linear(k_source, layer.projection[:width]) + v_input = linear(v_source, layer.projection[width : 2 * width]) + query = linear(q_source, layer.projection[2 * width :]) + else: + assert layer.k_projection is not None and layer.v_projection is not None + query = linear(q_source, layer.projection) + k_packed = linear(k_source, layer.k_projection) + v_packed = linear(v_source, layer.v_projection) + k_input, v_input = k_packed[..., :width], v_packed[..., :width] + k_dynamic = k_packed[..., width:].reshape(batch, tokens, kv_heads, 4) + v_dynamic = v_packed[..., width:].reshape(batch, tokens, kv_heads, 4) + q, relative, gate, sink = mx.split( + query, + [sum(query_sizes[:1]), sum(query_sizes[:2]), sum(query_sizes)], + axis=-1, + ) + k, k_history = short_convolution( + k_input, state[..., :width], layer.k_conv, k_dynamic + ) + v, v_history = short_convolution( + v_input, state[..., width : 2 * width], layer.v_conv, v_dynamic + ) + visit_tau = None if layer.local else tau + q = l2_clip( + q.reshape(batch, tokens, heads, d), + layer.q_scale, + config.qk_l2_clip_threshold, + visit_tau, + ) + k = l2_clip( + k.reshape(batch, tokens, kv_heads, d), + None, + config.qk_l2_clip_threshold, + None, + ) + v = rms_norm(v.reshape(batch, tokens, kv_heads, d), None, config.rms_norm_eps) + relative = l2_clip( + relative.reshape(batch, tokens, heads, r), + layer.rel_scale, + config.rel_l2_clip_threshold, + visit_tau, + ) + bias = relative @ layer.rel_proj + output, lse = store.attend( + layer.local, + slot, + q, + k, + v, + bias, + d**-0.5, + config.sliding_window_size, + ) + gated = output * mx.sigmoid(gate.astype(F32).reshape(batch, tokens, heads, d)) + gated = gated * mx.sigmoid(lse - sink.astype(F32))[..., None] + attended = gated.astype(BF16).reshape(batch, tokens, heads * d) + return linear(attended, layer.wo), k_history, v_history + + +__all__ = [ + "AttentionStore", + "Controller", + "Experts", + "Inkling2Model", + "Inkling2Weights", + "Layer", + "depth_mix", + "l2_clip", + "log_scaling_tau", + "logits", + "sparse_mlp", +] diff --git a/models/mlx/resin_models_mlx/inkling2/quantization.py b/models/mlx/resin_models_mlx/inkling2/quantization.py new file mode 100644 index 00000000..bd6e3851 --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/quantization.py @@ -0,0 +1,202 @@ +# Copyright 2026 SGLang contributors. Licensed under Apache-2.0. +# Adapted from sgl-project/sglang e62ac6279646c686d3b328f58d9b5c2c2d5927dc, +# python/sglang/kernels/ops/inkling2/{nvfp4,moe}.py, as +# resin_models_cuda/inkling2/expert_quantization.py is. +"""Inkling 2 expert activation quantization, emitted as exact dequantized values. + +The checkpoint requires NVFP4 or MXFP8 activations before each expert GEMM. +This follows the CUDA quantizer (adapted from SGLang e62ac627, Apache-2.0): +NVFP4 picks the four- or six-level block scale with lower pairwise-summed +reconstruction error, under a per-row outer scale; MXFP8 uses a power-of-two +block scale. A code times its block scale is exact in BF16, so the kernel +writes those products and leaves the per-row outer scale to the GEMM output. +""" + +from functools import cache + +import mlx.core as mx + +FLOAT_MAX = "3.4028234663852886e38f" + +_HEADER = r""" +// Round a finite magnitude to FP8 E4M3FN with round-to-nearest-even, saturating +// at 448. Subnormals step by 2^-9. +inline float resin_e4m3(float x) { + float a = metal::abs(x); + float q; + if (a >= 448.0f) { + q = 448.0f; + } else if (a < 0.015625f) { + q = metal::rint(a * 512.0f) * 0.001953125f; + } else { + int e; + metal::frexp(a, e); // a = m * 2^e, m in [0.5, 1) + float step = metal::ldexp(1.0f, e - 4); + q = metal::min(metal::rint(a / step) * step, 448.0f); + } + return metal::copysign(q, x); +} + +// Round to FP4 E2M1 with round-to-nearest-even, saturating at 6. +inline float resin_e2m1(float x) { + float a = metal::abs(x); + float q; + if (a < 2.0f) { + q = metal::rint(a * 2.0f) * 0.5f; + } else if (a < 4.0f) { + q = metal::rint(a); + } else { + q = metal::min(metal::rint(a * 0.5f) * 2.0f, 6.0f); + } + return metal::copysign(q, x); +} +""" + +_NVFP4_SOURCE = r""" + #pragma METAL fp contract(off) + const uint row = threadgroup_position_in_grid.x; + const uint lid = thread_position_in_threadgroup.x; + const uint lane = thread_index_in_simdgroup; + const uint simd = simdgroup_index_in_threadgroup; + threadgroup float maxima[32]; + threadgroup float row_amax[1]; + constexpr int BLOCKS = K / 16; + const bool active = int(lid) < BLOCKS; + const long base = long(row) * K + long(lid) * 16; + float v[16]; + float block_max = 0.0f; + for (int i = 0; i < 16; ++i) { + v[i] = active ? float(x[base + i]) : 0.0f; + block_max = metal::max(block_max, metal::abs(v[i])); + } + float m = simd_max(block_max); + if (simd == 0) maxima[lane] = 0.0f; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lane == 0) maxima[simd] = m; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd == 0) { + float total = simd_max(maxima[lane]); + if (lane == 0) row_amax[0] = total; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float amax = row_amax[0]; + if (lid == 0) row_amax_out[row] = amax; + if (!active) return; + const float encoder = metal::min(metal::precise::divide(1536.0f, amax), FLOAT_MAX); + const float decoder = metal::precise::divide(1.0f, encoder); + const float outer_scale = amax * (1.0f / 1536.0f); + float scale6 = resin_e4m3(metal::min(block_max * (encoder * (1.0f / 6.0f)), 448.0f)); + float scale4 = resin_e4m3(metal::min(block_max * (encoder * 0.25f), 448.0f)); + float inverse6 = metal::min(metal::precise::divide(1.0f, scale6 * decoder), FLOAT_MAX); + float inverse4 = metal::min(metal::precise::divide(1.0f, scale4 * decoder), FLOAT_MAX); + float r6[16], r4[16], e6[16], e4[16]; + for (int i = 0; i < 16; ++i) { + r6[i] = resin_e2m1(v[i] * inverse6) * scale6; + r4[i] = resin_e2m1(v[i] * inverse4) * scale4; + e6[i] = metal::abs(r6[i] * outer_scale - v[i]); + e4[i] = metal::abs(r4[i] * outer_scale - v[i]); + } + for (int width = 8; width >= 1; width >>= 1) { + for (int i = 0; i < width; ++i) { + e6[i] = e6[2 * i] + e6[2 * i + 1]; + e4[i] = e4[2 * i] + e4[2 * i + 1]; + } + } + const bool choose4 = e4[0] < e6[0]; + for (int i = 0; i < 16; ++i) { + y[base + i] = choose4 ? r4[i] : r6[i]; + } +""" + +_MXFP8_SOURCE = r""" + #pragma METAL fp contract(off) + const uint row = threadgroup_position_in_grid.x; + const uint lid = thread_position_in_threadgroup.x; + constexpr int BLOCKS = K / 32; + if (int(lid) >= BLOCKS) return; + const long base = long(row) * K + long(lid) * 32; + float v[32]; + float amax = 0.0f; + for (int i = 0; i < 32; ++i) { + v[i] = float(x[base + i]); + amax = metal::max(amax, metal::abs(v[i])); + } + const float raw = amax * (1.0f / 448.0f); + int exponent = int(((as_type(raw) + 0x007FFFFFu) & 0x7F800000u) >> 23); + exponent = raw <= 5.877471754111438e-39f ? 0 : metal::min(exponent, 254); + // Blocks with amax <= 448 * 2^-127 (in practice all-zero) quantize to + // zero; CUDA keeps 2^-127-scaled denormals there. + const float scale = as_type(uint(exponent) << 23); + const float inverse = exponent == 0 ? 0.0f : metal::precise::divide(1.0f, scale); + for (int i = 0; i < 32; ++i) { + float q = metal::clamp(v[i] * inverse, -448.0f, 448.0f); + y[base + i] = resin_e4m3(q) * scale; + } +""" + + +@cache +def _nvfp4_kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_nvfp4_activation", + input_names=["x"], + output_names=["y", "row_amax_out"], + header=_HEADER, + source=_NVFP4_SOURCE.replace("FLOAT_MAX", FLOAT_MAX), + ) + + +@cache +def _mxfp8_kernel(): + return mx.fast.metal_kernel( + name="resin_inkling2_mxfp8_activation", + input_names=["x"], + output_names=["y"], + header=_HEADER, + source=_MXFP8_SOURCE, + ) + + +def _threads(blocks: int) -> int: + return max(32, (blocks + 31) // 32 * 32) + + +def quantize_activations(x: mx.array, mode: str) -> tuple[mx.array, mx.array | None]: + """Return FP32 dequantized activations without the outer scale, and row amax. + + ``x`` is a contiguous BF16 ``[rows, K]`` matrix. NVFP4 values exclude the + per-row outer scale ``amax / 1536``; the returned ``amax`` lets the GEMM + apply it with the weight's scale. MXFP8 has no outer scale and returns ``None``. + """ + + rows, width = x.shape + if mode == "nvfp4": + if width % 16 or width // 16 > 1024: + raise ValueError("NVFP4 activations need a width divisible by 16") + threads = _threads(width // 16) + y, amax = _nvfp4_kernel()( + inputs=[x], + template=[("K", width)], + grid=(rows * threads, 1, 1), + threadgroup=(threads, 1, 1), + output_shapes=[(rows, width), (rows,)], + output_dtypes=[mx.float32, mx.float32], + ) + return y, amax + if mode == "mxfp8": + if width % 32 or width // 32 > 1024: + raise ValueError("MXFP8 activations need a width divisible by 32") + threads = _threads(width // 32) + (y,) = _mxfp8_kernel()( + inputs=[x], + template=[("K", width)], + grid=(rows * threads, 1, 1), + threadgroup=(threads, 1, 1), + output_shapes=[(rows, width)], + output_dtypes=[mx.float32], + ) + return y, None + raise ValueError(f"unsupported Inkling 2 activation precision {mode!r}") + + +__all__ = ["quantize_activations"] diff --git a/models/mlx/resin_models_mlx/inkling2/runner.py b/models/mlx/resin_models_mlx/inkling2/runner.py new file mode 100644 index 00000000..074907f5 --- /dev/null +++ b/models/mlx/resin_models_mlx/inkling2/runner.py @@ -0,0 +1,482 @@ +"""Inkling 2 target-only runner on Apple Silicon over Engine-owned MLX slabs.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING + +import mlx.core as mx +import numpy as np +import torch +from torch.profiler import record_function + +from resin import BatchPhase, RunnerConfig +from resin.backend.capacity import plan_cache_capacity +from resin.backend.plans import PagedCachePlan +from resin.backend.sampling import PromptScores, format_output, prompt_scores +from resin.backend.topology import ParallelismCapabilities +from resin.models.inkling2.config import Inkling2Config +from resin_models_mlx.inkling2.attention import dense_attention +from resin_models_mlx.inkling2.cache import ( + GLOBAL_GROUP, + LOCAL_GROUP, + PAGE_TOKENS, + STATE_GROUP, + CacheArena, + CacheGeometry, + History, +) +from resin_models_mlx.inkling2.checkpoint import load_model +from resin_models_mlx.inkling2.decode_attention import decode_attention +from resin_models_mlx.inkling2.model import Inkling2Model, Inkling2Weights, logits +from resin_models_mlx.live_state import LiveStates +from resin_models_mlx.sampling import MlxSampler + +if TYPE_CHECKING: + from resin import BatchPlan, ForwardOutput, ResourceBinding + +_WORKSPACE_BYTES = 4 * 1024**3 + + +def _to_torch(array: mx.array) -> torch.Tensor: + return torch.from_numpy(np.array(array.astype(mx.float32))) + + +class _StepStore: + """Attention over one step's retained history plus its own new keys. + + The step's keys and values are kept for the runner to write after every + reader of the arena view has been ordered. + """ + + def __init__( + self, + arena: CacheArena, + plan: PagedCachePlan, + rows: np.ndarray, + contexts: np.ndarray, + positions: mx.array, + window: int, + ) -> None: + geometry = arena.geometry + self.positions = positions + self.sequence_ids = plan.batch.sequence_ids[rows] + self.contexts = contexts + self.history: dict[int, History | None] = { + GLOBAL_GROUP: arena.history(plan, GLOBAL_GROUP, rows, contexts), + LOCAL_GROUP: arena.history( + plan, LOCAL_GROUP, rows, contexts, earliest=contexts - (window - 1) + ), + } + self.keys: dict[int, list[mx.array | None]] = { + group: [None] * geometry.layers(group) + for group in (GLOBAL_GROUP, LOCAL_GROUP) + } + self.values: dict[int, list[mx.array | None]] = { + group: [None] * geometry.layers(group) + for group in (GLOBAL_GROUP, LOCAL_GROUP) + } + # Decode reads pages in place; prefill gathers history per visit. + self.paged: dict[int, tuple[mx.array, mx.array, mx.array, int, int]] = {} + if positions.shape[1] == 1: + units = arena.units() + for group in (GLOBAL_GROUP, LOCAL_GROUP): + history = self.history[group] + firsts = ( + np.maximum(contexts - (window - 1), 0) + if group == LOCAL_GROUP + else np.zeros_like(contexts) + ) + if history is None: + pages = np.zeros((len(rows), 1), dtype=np.int32) + starts = firsts // geometry.page_tokens + stride = geometry.blocks_per_slab(group) + else: + pages = history.bases.astype(np.int32) + starts = history.starts + stride = history.layer_stride + meta = np.stack([contexts, firsts, starts], axis=1).astype(np.int32) + longest = int(np.max(contexts + 1 - firsts)) + self.paged[group] = ( + units, + mx.array(pages), + mx.array(meta), + longest, + stride, + ) + + def attend(self, local, slot, q, k, v, bias, scale, window): + group = LOCAL_GROUP if local else GLOBAL_GROUP + self.keys[group][slot] = k + self.values[group][slot] = v + if group in self.paged: + units, pages, meta, longest, stride = self.paged[group] + output, lse = decode_attention( + q[:, 0], + k[:, 0], + v[:, 0], + units, + pages, + meta, + bias[:, 0], + slot * stride, + scale, + longest, + ) + return output[:, None], lse[:, None] + batch, tokens = self.positions.shape + current_valid = mx.ones((batch, tokens), dtype=mx.bool_) + history = self.history[group] + contiguous = None + if history is None: + keys, values = k, v + key_positions, key_valid = self.positions, current_valid + if batch == 1: + context = int(self.contexts[0]) + contiguous = (context, context) + else: + hk, hv, hp, hvalid = history.gather(slot) + if batch == 1: + # One prefill row: drop the last page's unwritten tail so the + # retained history runs contiguously into the chunk's keys. + first = int(history.starts[0]) * PAGE_TOKENS + count = int(self.contexts[0]) - first + hk, hv, hp, hvalid = ( + hk[:, :count], + hv[:, :count], + hp[:, :count], + hvalid[:, :count], + ) + contiguous = (first, int(self.contexts[0])) + keys = mx.concatenate([hk, k], axis=1) + values = mx.concatenate([hv, v], axis=1) + key_positions = mx.concatenate([hp, self.positions], axis=1) + key_valid = mx.concatenate([hvalid, current_valid], axis=1) + return dense_attention( + q, + keys, + values, + key_positions, + key_valid, + self.positions, + bias, + scale, + window if local else None, + contiguous, + ) + + def written(self, group: int) -> tuple[list[mx.array], list[mx.array]]: + keys = [x for x in self.keys[group] if x is not None] + values = [x for x in self.values[group] if x is not None] + if len(keys) != len(self.keys[group]) or len(values) != len(self.values[group]): + raise RuntimeError("an Inkling 2 visit did not produce its keys and values") + return keys, values + + +@dataclass(slots=True) +class _Launch: + """A step's outputs, retained through its GPU-ordered cache writes.""" + + plan: PagedCachePlan + rows: np.ndarray + tokens: np.ndarray + contexts: np.ndarray + store: _StepStore + hidden: mx.array + state: mx.array + last: mx.array + receipts: tuple[int, ...] | None = field(default=None) + + @property + def reads(self) -> tuple[mx.array, ...]: + """Every output computed from the arena, including the held state.""" + keys = [x for group in self.store.keys.values() for x in group if x is not None] + values = [ + x for group in self.store.values.values() for x in group if x is not None + ] + return (self.last, self.hidden, self.state, *keys, *values) + + +@dataclass(slots=True) +class _Completion: + """One overlapped decode step, collected after the next one is launched.""" + + _runner: Inkling2MlxRunner + _plan: BatchPlan + _launch: _Launch + _tokens: mx.array + _continues: bool + _result: ForwardOutput | None = field(default=None, init=False) + + @property + def feedback(self) -> mx.array | None: + # None drains the Engine, so a step past max_seq_len fails in forward + # rather than in an overlapped enqueue, which would poison the Engine. + return self._tokens if self._continues else None + + def result(self) -> ForwardOutput: + if self._result is None: + if self._launch.receipts is None: + # No continuation followed, so this step still owns its writes. + if self._runner._pending is not self._launch: + raise RuntimeError("MLX step lost its pending cache writes") + self._runner._write_pending() + tokens = np.array(self._tokens).astype(np.int64) + receipts = self._launch.receipts + assert receipts is not None + self._result = format_output( + None, tokens, self._plan + ).with_state_checkpoints(receipts) + return self._result + + +class Inkling2MlxRunner: + """Inkling 2 target with paged global/local attention and live conv history.""" + + page_size = 128 + parallelism_capabilities = ParallelismCapabilities() + + def __init__( + self, + model: str | Path | tuple[Inkling2Config, Inkling2Weights], + *, + memory_utilization: float = 0.85, + cache_slab_capacity: int | None = None, + max_seq_len: int | None = None, + max_batch_size: int = 8, + prefill_chunk_size: int = 8192, + workspace_bytes: int = _WORKSPACE_BYTES, + ) -> None: + if workspace_bytes < 0: + raise ValueError("workspace_bytes must be non-negative") + if isinstance(model, tuple): + config, weights = model + self.model_path = None + else: + self.model_path = Path(model) + config, weights = load_model(self.model_path) + self.config = config + self._model = Inkling2Model(config, weights) + limit_positions = config.max_position_embeddings + self.max_seq_len = limit_positions if max_seq_len is None else max_seq_len + if not 0 < self.max_seq_len <= limit_positions: + raise ValueError( + f"max_seq_len must be between 1 and the checkpoint's {limit_positions} positions" + ) + self.prefill_chunk_size = prefill_chunk_size + 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"}, + } + # Logits cover the real vocabulary; embedding rows beyond it are padding. + self.vocab_size = config.unpadded_vocab_size + self.eos_token_id = config.eos_token_id + self.cache_geometry = CacheGeometry.from_config(config, prefill_chunk_size) + geometry = self.cache_geometry + device = mx.device_info() + limit = int(device["max_recommended_working_set_size"]) + self.cache_capacity_plan = plan_cache_capacity( + limit, + max(1, limit - mx.get_active_memory()), + memory_utilization, + geometry.slab_bytes, + # Live convolution history is held for every running request, and + # a step's output state exists beside its input. + overhead_bytes=workspace_bytes + 2 * max_batch_size * geometry.state_bytes, + ) + buffer_slabs = int(device["max_buffer_length"]) // geometry.slab_bytes + # Room for every running request at full context, and as much again + # for reusable prefixes; beyond that, memory is better left unwired. + wanted = 2 * max_batch_size * geometry.sequence_slabs(self.max_seq_len) + 16 + slab_capacity = min( + self.cache_capacity_plan.parent_capacity, buffer_slabs - 1, wanted + ) + if cache_slab_capacity is not None: + slab_capacity = min(slab_capacity, cache_slab_capacity) + if slab_capacity < geometry.sequence_slabs(self.max_seq_len): + raise ValueError( + f"the Inkling 2 cache holds {slab_capacity} slabs, fewer than one " + f"{self.max_seq_len}-token request needs; lower max_seq_len" + ) + self.cache_layout = geometry.layout(slab_capacity) + self._cache = CacheArena(self.cache_layout, geometry) + self.runner_config = RunnerConfig( + max_batch_tokens=prefill_chunk_size, + prefill_chunk_size=prefill_chunk_size, + continuation_prefill=True, + cache_layout=self.cache_layout, + ) + self._sampler = MlxSampler() + self._states = LiveStates(self._cache, self._model.initial_state, STATE_GROUP) + self._pending: _Launch | None = None + + def bind_resources(self, resources: ResourceBinding) -> None: + self._cache.binding.bind_resources(resources) + + def release(self, sequence_ids: list[int]) -> None: + # A pending step would hold the released rows' state again. + self._write_pending() + self._states.release(sequence_ids) + + def _project(self, hidden: torch.Tensor) -> torch.Tensor: + values = logits( + mx.array(hidden.numpy()).astype(mx.bfloat16), + self._model.weights, + self.config, + ) + return _to_torch(values) + + def _launch( + self, + plan: PagedCachePlan, + rows: np.ndarray, + tokens: np.ndarray, + token_ids: mx.array | None = None, + ) -> _Launch: + """Build the step for ``tokens``, flattened plan indices ``[len(rows), width]``.""" + batch = plan.batch + contexts = batch.context_lengths[rows].astype(np.int64) + if token_ids is None: + token_ids = mx.array(batch.token_ids[tokens].astype(np.int32)) + positions = contexts[:, None] + np.arange(tokens.shape[1])[None] + positions_mx = mx.array(positions.astype(np.int32)) + store = _StepStore( + self._cache, + plan, + rows, + contexts, + positions_mx, + self.config.sliding_window_size, + ) + hidden, state = self._model.hidden( + token_ids.reshape(tokens.shape), + positions_mx, + self._states.gather(plan, rows), + store, + ) + last = logits(hidden[:, -1], self._model.weights, self.config) + return _Launch(plan, rows, tokens, contexts, store, hidden, state, last) + + def _write(self, launch: _Launch) -> None: + """Order writes after this graph's readers and hold its live state.""" + self._cache.order_after(launch.reads) + flat = launch.tokens.reshape(-1) + geometry = self.cache_geometry + for group in (GLOBAL_GROUP, LOCAL_GROUP): + keys, values = launch.store.written(group) + width = (-1, geometry.kv_heads, geometry.head_dim) + self._cache.write_tokens( + launch.plan, + group, + [key.reshape(width) for key in keys], + [value.reshape(width) for value in values], + flat, + ) + launch.receipts = self._states.commit( + launch.plan, + launch.rows, + launch.contexts + launch.tokens.shape[1], + launch.state, + ) + + def _write_pending(self) -> None: + """Drain pending cache work before a terminal/ownership transition.""" + launch, self._pending = self._pending, None + if launch is None: + return + self._write(launch) + # No continuation retains the lease here: wait for snapshots and KV + # writes, not only the sampled-token event. + mx.eval(self._cache.epoch) + + def forward(self, plan: BatchPlan) -> ForwardOutput: + self._write_pending() + cache_plan = self._cache_plan(plan) + batch = cache_plan.batch + prefill = plan.phase == BatchPhase.PREFILL + rows = np.arange(batch.num_sequences) + groups = rows[:, None] if prefill else (rows,) + last_logits = [] + prompt_rows = [] + receipts: list[int] = [] + for rows in groups: + if prefill: + selected = batch.token_slice(int(rows[0])) + tokens = np.arange(selected.start, selected.stop)[None] + else: + tokens = rows[:, None] + with record_function("resin.mlx.forward"): + launch = self._launch(cache_plan, rows, tokens) + with record_function("resin.mlx.cache_write"): + self._write(launch) + mx.async_eval(self._cache.epoch, *launch.reads) + last_logits.append(launch.last) + assert launch.receipts is not None + receipts += launch.receipts + if prefill and plan.needs_prompt_logprobs: + scores = prompt_scores( + plan, + _to_torch(launch.hidden[0]), + self._project, + token_start=int(tokens[0, 0]), + ) + if scores is not None: + prompt_rows.append(scores) + # A synchronous result can release the lease immediately: wait for + # every issued cache write, not just the sampled-token event. + combined = ( + last_logits[0] if len(last_logits) == 1 else mx.concatenate(last_logits) + ) + combined = mx.depends(combined, self._cache.epoch) + with record_function("resin.mlx.sample"): + sampled = self._sampler(combined, plan) + return format_output( + _to_torch(combined) if plan.needs_logprobs else None, + sampled, + plan, + prompt_logprobs=PromptScores.concat(prompt_rows), + ).with_state_checkpoints(receipts) + + def _cache_plan(self, plan: BatchPlan) -> PagedCachePlan: + cache_plan = PagedCachePlan.from_plan(plan, self.cache_layout) + # Validate before any cache write: rejected plans must leave no state. + if any(media is not None for media in plan.media): + raise ValueError("the Inkling 2 MLX runner serves text only") + if np.any(cache_plan.token_ids >= self.vocab_size): + raise ValueError("token id is out of range for Inkling 2") + if int(np.max(cache_plan.batch.post_lengths)) > self.max_seq_len: + raise ValueError( + f"sequence exceeds this runner's {self.max_seq_len}-token context" + ) + return cache_plan + + def enqueue( + self, plan: BatchPlan, *, feedback: mx.array | None = None + ) -> _Completion | ForwardOutput: + """Launch a decode step while the previous one still runs on the GPU.""" + if plan.phase != BatchPhase.DECODE or plan.needs_logprobs: + if feedback is not None: + raise RuntimeError("an MLX continuation requires unscored decode") + return self.forward(plan) + cache_plan = self._cache_plan(plan) + previous, self._pending = self._pending, None + rows = np.arange(cache_plan.batch.num_sequences) + with record_function("resin.mlx.enqueue"): + if previous is not None: + # Epoch dependencies order previous reads -> writes -> new + # reads without waiting for the GPU on the calling thread. + self._write(previous) + launch = self._launch(cache_plan, rows, rows[:, None], feedback) + sampled = self._sampler.tokens(launch.last, plan) + mx.async_eval(self._cache.epoch, sampled, *launch.reads) + self._pending = launch + continues = int(np.max(cache_plan.batch.post_lengths)) < self.max_seq_len + return _Completion(self, plan, launch, sampled, continues) + + +__all__ = ["Inkling2MlxRunner"] diff --git a/models/mlx/resin_models_mlx/live_state.py b/models/mlx/resin_models_mlx/live_state.py new file mode 100644 index 00000000..705e1784 --- /dev/null +++ b/models/mlx/resin_models_mlx/live_state.py @@ -0,0 +1,160 @@ +"""Per-request model state kept on the GPU between steps. + +Each running request's state stays in the MLX arrays the model returned for its +last step, so an unchanged decode batch feeds them straight back without +touching the cache arena. The Engine's STATE group still decides when state is +restored from a prefix snapshot, and where snapshots are published; only those +transitions copy through the arena. Requests leave when the Engine releases +them. + +State is any MLX pytree whose leaves share a leading batch axis. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Protocol, cast + +import mlx.core as mx +import numpy as np +from mlx.utils import tree_flatten, tree_map + +from resin.backend.plans import PagedCachePlan + + +class StateArena(Protocol): + def state_start(self, slab: int, slot: int) -> int: ... + + def read_states(self, starts: np.ndarray) -> Any: ... + + def write_states(self, starts: Sequence[int], state: Any) -> None: ... + + +def _batch(state: Any) -> int: + leaves = cast(list[tuple[str, mx.array]], tree_flatten(state)) + return leaves[0][1].shape[0] + + +def take_rows(state: Any, indices: list[int]) -> Any: + if indices == list(range(_batch(state))): + return state + selected = mx.array(indices) + return tree_map(lambda value: mx.take(value, selected, axis=0), state) + + +def _concatenate(parts: list[Any]) -> Any: + if len(parts) == 1: + return parts[0] + return tree_map(lambda *values: mx.concatenate(list(values)), *parts) + + +class LiveStates: + """Per-request state, indexed into the batch arrays that hold it.""" + + def __init__( + self, + arena: StateArena, + initial_state: Callable[[int], Any], + state_group: int, + ) -> None: + self._arena = arena + self._initial_state = initial_state + self._group = state_group + # sequence ID -> (tokens processed, batch state, row in that batch) + self._rows: dict[int, tuple[int, Any, int]] = {} + + def __len__(self) -> int: + return len(self._rows) + + def gather(self, plan: PagedCachePlan, rows: np.ndarray) -> Any: + """State before each of ``rows`` runs, in plan row order.""" + + batch = plan.batch + restore = plan.groups[self._group].state + sources = { + int(row): (int(slab), int(slot)) + for row, slab, slot in (restore.restore_copies if restore else ()) + } + # Source slab zero is the Engine's explicit immutable zero state. + # Preserve every real restore and mixed/held path below. + if len(rows) and all( + int(batch.context_lengths[row]) == 0 and sources.get(int(row)) == (0, 0) + for row in rows + ): + return self._initial_state(len(rows)) + snapshots, fresh = [], [] + held: dict[int, tuple[Any, list[int], list[int]]] = {} + for position, row in enumerate(rows.tolist()): + context = int(batch.context_lengths[row]) + if row in sources: + snapshots.append((position, *sources[row])) + elif context == 0: + fresh.append(position) + else: + sequence = int(batch.sequence_ids[row]) + entry = self._rows.get(sequence) + if entry is None or entry[0] != context: + raise RuntimeError( + f"sequence {sequence} has no live state at position {context}" + ) + _, state, index = entry + group = held.setdefault(id(state), (state, [], [])) + group[1].append(position) + group[2].append(index) + + parts, order = [], [] + for state, positions, indices in held.values(): + parts.append(take_rows(state, indices)) + order += positions + if snapshots: + parts.append( + self._arena.read_states( + np.array([self._arena.state_start(s, t) for _, s, t in snapshots]) + ) + ) + order += [position for position, *_ in snapshots] + if fresh: + parts.append(self._initial_state(len(fresh))) + order += fresh + state = _concatenate(parts) + if order != list(range(len(order))): + state = take_rows(state, np.argsort(order).tolist()) + return state + + def commit( + self, + plan: PagedCachePlan, + rows: np.ndarray, + ends: np.ndarray, + state: Any, + ) -> tuple[int, ...]: + """Hold each row's state after ``ends`` tokens and publish due snapshots. + + Returns the reservation IDs of the snapshots written. + """ + + sequences = plan.batch.sequence_ids + for index, row in enumerate(rows.tolist()): + self._rows[int(sequences[row])] = (int(ends[index]), state, index) + checkpoints = plan.groups[self._group].state + positions = {row: index for index, row in enumerate(rows.tolist())} + written, starts, indices = [], [], [] + for reservation, row, prefix, slab, slot in ( + checkpoints.checkpoint_slots if checkpoints else () + ): + index = positions.get(int(row)) + # A snapshot is valid only at its exact prefix. + if index is not None and int(ends[index]) == int(prefix): + written.append(int(reservation)) + starts.append(self._arena.state_start(int(slab), int(slot))) + indices.append(index) + if written: + self._arena.write_states(starts, take_rows(state, indices)) + return tuple(written) + + def release(self, sequence_ids: Iterable[int]) -> None: + for sequence in sequence_ids: + self._rows.pop(int(sequence), None) + + +__all__ = ["LiveStates", "StateArena", "take_rows"] diff --git a/models/mlx/resin_models_mlx/qwen3_5/state.py b/models/mlx/resin_models_mlx/qwen3_5/state.py index cbc5440d..07b2e928 100644 --- a/models/mlx/resin_models_mlx/qwen3_5/state.py +++ b/models/mlx/resin_models_mlx/qwen3_5/state.py @@ -1,141 +1,17 @@ -"""Live DeltaNet state kept on the GPU between steps. - -Each running request's recurrent and convolution state stays in the MLX arrays -the model returned for its last step, so an unchanged decode batch feeds them -straight back without touching the arena. The Engine's STATE group still -decides when state is restored from a prefix snapshot, and where snapshots are -published; only those transitions copy through the arena. Requests leave when -the Engine releases them. -""" +"""Live DeltaNet state kept on the GPU between steps (see ``live_state.py``).""" from __future__ import annotations -from collections.abc import Iterable - -import mlx.core as mx -import numpy as np -from mlx.utils import tree_map - -from resin.backend.plans import PagedCachePlan +from resin_models_mlx.live_state import LiveStates as _LiveStates from resin_models_mlx.qwen3_5.cache import STATE_GROUP, CacheArena -from resin_models_mlx.qwen3_5.model import LinearState, Qwen35Model - +from resin_models_mlx.qwen3_5.model import Qwen35Model -def _take(state: LinearState, indices: list[int]) -> LinearState: - if indices == list(range(state.recurrent[0].shape[0])): - return state - selected = mx.array(indices) - return tree_map(lambda value: mx.take(value, selected, axis=0), state) - -def _concatenate(parts: list[LinearState]) -> LinearState: - if len(parts) == 1: - return parts[0] - return tree_map(lambda *values: mx.concatenate(list(values)), *parts) - - -class LiveStates: +class LiveStates(_LiveStates): """Per-request DeltaNet state, indexed into the batch arrays that hold it.""" def __init__(self, arena: CacheArena, model: Qwen35Model) -> None: - self._arena = arena - self._model = model - # sequence ID -> (tokens processed, batch state, row in that batch) - self._rows: dict[int, tuple[int, LinearState, int]] = {} - - def __len__(self) -> int: - return len(self._rows) - - def gather(self, plan: PagedCachePlan, rows: np.ndarray) -> LinearState: - """State before each of ``rows`` runs, in plan row order.""" - - batch = plan.batch - restore = plan.groups[STATE_GROUP].state - sources = { - int(row): (int(slab), int(slot)) - for row, slab, slot in (restore.restore_copies if restore else ()) - } - # Source slab zero is the Engine's explicit immutable zero state. - # Preserve every real restore and mixed/held path below. - if len(rows) and all( - int(batch.context_lengths[row]) == 0 and sources.get(int(row)) == (0, 0) - for row in rows - ): - return self._model.initial_state(len(rows)) - snapshots, fresh = [], [] - held: dict[int, tuple[LinearState, list[int], list[int]]] = {} - for position, row in enumerate(rows.tolist()): - context = int(batch.context_lengths[row]) - if row in sources: - snapshots.append((position, *sources[row])) - elif context == 0: - fresh.append(position) - else: - sequence = int(batch.sequence_ids[row]) - entry = self._rows.get(sequence) - if entry is None or entry[0] != context: - raise RuntimeError( - f"sequence {sequence} has no live recurrent state at " - f"position {context}" - ) - _, state, index = entry - group = held.setdefault(id(state), (state, [], [])) - group[1].append(position) - group[2].append(index) - - parts, order = [], [] - for state, positions, indices in held.values(): - parts.append(_take(state, indices)) - order += positions - if snapshots: - parts.append( - self._arena.read_states( - np.array([self._arena.state_start(s, t) for _, s, t in snapshots]) - ) - ) - order += [position for position, *_ in snapshots] - if fresh: - parts.append(self._model.initial_state(len(fresh))) - order += fresh - state = _concatenate(parts) - if order != list(range(len(order))): - state = _take(state, np.argsort(order).tolist()) - return state - - def commit( - self, - plan: PagedCachePlan, - rows: np.ndarray, - ends: np.ndarray, - state: LinearState, - ) -> tuple[int, ...]: - """Hold each row's state after ``ends`` tokens and publish due snapshots. - - Returns the reservation IDs of the snapshots written. - """ - - sequences = plan.batch.sequence_ids - for index, row in enumerate(rows.tolist()): - self._rows[int(sequences[row])] = (int(ends[index]), state, index) - checkpoints = plan.groups[STATE_GROUP].state - positions = {row: index for index, row in enumerate(rows.tolist())} - written, starts, indices = [], [], [] - for reservation, row, prefix, slab, slot in ( - checkpoints.checkpoint_slots if checkpoints else () - ): - index = positions.get(int(row)) - # A snapshot is valid only at its exact prefix. - if index is not None and int(ends[index]) == int(prefix): - written.append(int(reservation)) - starts.append(self._arena.state_start(int(slab), int(slot))) - indices.append(index) - if written: - self._arena.write_states(starts, _take(state, indices)) - return tuple(written) - - def release(self, sequence_ids: Iterable[int]) -> None: - for sequence in sequence_ids: - self._rows.pop(int(sequence), None) + super().__init__(arena, model.initial_state, STATE_GROUP) __all__ = ["LiveStates"] diff --git a/models/mlx/tests/test_inkling2_attention.py b/models/mlx/tests/test_inkling2_attention.py new file mode 100644 index 00000000..8286a83b --- /dev/null +++ b/models/mlx/tests/test_inkling2_attention.py @@ -0,0 +1,131 @@ +"""Inkling 2 paged decode attention against the dense reference attention.""" + +from __future__ import annotations + +import mlx.core as mx +import numpy as np +import pytest + +from resin_models_mlx.inkling2.attention import dense_attention +from resin_models_mlx.inkling2.decode_attention import decode_attention + +PAGE = 128 + + +def _case(contexts, window, heads, kv_heads, dim, extent, seed): + rng = np.random.default_rng(seed) + rows = len(contexts) + width = kv_heads * dim + # Retained blocks: a window keeps only its suffix, starting at a nonzero block. + firsts = [max(0, c - (window - 1)) if window else 0 for c in contexts] + starts = [f // PAGE for f in firsts] + blocks = [max(1, -(-c // PAGE) - s) for c, s in zip(contexts, starts, strict=True)] + table = max(blocks) + units_count = rows * table + 3 + # NaN everywhere a kernel must never read. + units = np.full((units_count, 2, PAGE, width), np.nan, dtype=np.float32) + pages = np.zeros((rows, table), dtype=np.int32) + order = rng.permutation(units_count - 1) + 1 + history_k, history_v = [], [] + used = 0 + for row, context in enumerate(contexts): + keys = rng.standard_normal((context, kv_heads, dim)).astype(np.float32) + values = rng.standard_normal((context, kv_heads, dim)).astype(np.float32) + history_k.append(keys) + history_v.append(values) + for j in range(blocks[row]): + unit = int(order[used]) + used += 1 + pages[row, j] = unit + block = starts[row] + j + lo, hi = block * PAGE, min((block + 1) * PAGE, context) + if hi > lo: + units[unit, 0, : hi - lo] = keys[lo:hi].reshape(hi - lo, width) + units[unit, 1, : hi - lo] = values[lo:hi].reshape(hi - lo, width) + queries = rng.standard_normal((rows, heads, dim)).astype(np.float32) + current_k = rng.standard_normal((rows, kv_heads, dim)).astype(np.float32) + current_v = rng.standard_normal((rows, kv_heads, dim)).astype(np.float32) + bias = (rng.standard_normal((rows, heads, extent)) * 2).astype(np.float32) + meta = np.array( + [[c, f, s] for c, f, s in zip(contexts, firsts, starts, strict=True)], + dtype=np.int32, + ) + return dict( + units=units, + pages=pages, + meta=meta, + queries=queries, + current_k=current_k, + current_v=current_v, + bias=bias, + history_k=history_k, + history_v=history_v, + ) + + +def _dense(case, contexts, window, scale): + bf16 = lambda x: mx.array(x).astype(mx.bfloat16) # noqa: E731 + rows = len(contexts) + longest = max(contexts) + 1 + kv_heads, dim = case["current_k"].shape[1:] + keys = np.zeros((rows, longest, kv_heads, dim), np.float32) + values = np.zeros_like(keys) + valid = np.zeros((rows, longest), bool) + for row, context in enumerate(contexts): + keys[row, :context] = case["history_k"][row] + values[row, :context] = case["history_v"][row] + keys[row, context] = case["current_k"][row] + values[row, context] = case["current_v"][row] + valid[row, : context + 1] = True + positions = np.array(contexts, np.int32)[:, None] + return dense_attention( + bf16(case["queries"])[:, None], + bf16(keys), + bf16(values), + mx.broadcast_to(mx.arange(longest)[None], (rows, longest)).astype(mx.int32), + mx.array(valid), + mx.array(positions), + bf16(case["bias"])[:, None], + scale, + window, + ) + + +@pytest.mark.parametrize( + "contexts,window", + [ + ([0], None), + ([1, 127, 128, 129], None), + ([700, 3, 1500], None), + ([1023, 1024, 1025, 2000], 1024), + ([5, 300], 12), + ], +) +@pytest.mark.parametrize("geometry", [(24, 8, 128, 1024), (4, 2, 32, 12)]) +def test_decode_attention_matches_dense(contexts, window, geometry): + heads, kv_heads, dim, extent = geometry + if window is not None: + window = min(window, extent) if extent < 1024 else window + scale = dim**-0.5 + case = _case(contexts, window, heads, kv_heads, dim, extent, seed=sum(contexts)) + bf16 = lambda x: mx.array(x).astype(mx.bfloat16) # noqa: E731 + firsts = case["meta"][:, 1] + output, lse = decode_attention( + bf16(case["queries"]), + bf16(case["current_k"]), + bf16(case["current_v"]), + bf16(case["units"]), + mx.array(case["pages"]), + mx.array(case["meta"]), + bf16(case["bias"]), + 0, + scale, + int(max(c + 1 - f for c, f in zip(contexts, firsts, strict=True))), + ) + expected, expected_lse = _dense(case, contexts, window, scale) + np.testing.assert_allclose( + np.array(output), np.array(expected[:, 0]), rtol=2e-4, atol=2e-4 + ) + np.testing.assert_allclose( + np.array(lse), np.array(expected_lse[:, 0]), rtol=2e-4, atol=2e-4 + ) diff --git a/models/mlx/tests/test_inkling2_checkpoint.py b/models/mlx/tests/test_inkling2_checkpoint.py new file mode 100644 index 00000000..36faa4ea --- /dev/null +++ b/models/mlx/tests/test_inkling2_checkpoint.py @@ -0,0 +1,193 @@ +"""Inkling 2 Mini on its real checkpoint against the CUDA package's model on CPU. + +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. +""" + +from __future__ import annotations + +import os +from functools import lru_cache +from pathlib import Path + +import mlx.core as mx +import numpy as np +import pytest + +torch = pytest.importorskip("torch") + +CHECKPOINT = os.environ.get("RESIN_TEST_CHECKPOINT") +pytestmark = pytest.mark.skipif( + not CHECKPOINT, reason="RESIN_TEST_CHECKPOINT is not set" +) + + +def _fast_experts(): + """The reference's per-route arithmetic, grouped by expert for speed.""" + from test_inkling2_model import _activations, _weight + + modules = {} + + @lru_cache(maxsize=640) + def weight(module, name, expert): + found = modules[module] + return _weight(found, name, found.precision[name], expert).float() + + def experts(module, hidden, ids, weights): + modules[id(module)] = module + mode = module.precision["w13"] + rows, top_k = ids.shape + down = torch.zeros(rows, top_k, hidden.shape[1], dtype=torch.bfloat16) + + def matmul(x, name, expert): + base, amax = _activations(x, mode) + output = base @ weight(id(module), name, expert).t() + if mode == "nvfp4": + denominator = getattr(module, name + "_weight_outer_scale_denominator") + weight_amax = getattr(module, name + "_weight_amax")[expert] + factor = (amax * weight_amax) * (1.0 / (1536.0 * denominator)) + output = output * factor[:, None] + return output.to(torch.bfloat16) + + for expert in torch.unique(ids).tolist(): + token, slot = (ids == expert).nonzero(as_tuple=True) + gate_up = ( + matmul(hidden[token], "w13", expert).float().view(len(token), -1, 2) + ) + gate, up = gate_up[..., 0], gate_up[..., 1] + activated = ( + ((4 * (gate / 4).tanh()) * gate.sigmoid()) * (25 * (up / 25).tanh()) + ) * weights[token, slot][:, None] + down[token, slot] = matmul(activated.to(torch.bfloat16), "w2", expert) + total = down[:, 0].float() + for slot in range(1, top_k): + total = total + down[:, slot].float() + return total + + return experts + + +def test_real_checkpoint_matches_cpu_reference(monkeypatch): + from test_inkling2_model import ( + DenseStore, + ReferenceCache, + _record, + _relative, + _to_mlx, + reference_attention, + ) + from tokenizers import Tokenizer + + from resin_models_cuda.inkling2 import attention + from resin_models_cuda.inkling2.checkpoint import load_precision + from resin_models_cuda.inkling2.model import Inkling2Target + from resin_models_cuda.inkling2.weights import load_target_weights + from resin_models_mlx.inkling2 import model as mlx_model + from resin_models_mlx.inkling2.checkpoint import load_model + from resin_models_mlx.inkling2.model import Inkling2Model + + assert CHECKPOINT is not None + root = Path(CHECKPOINT).expanduser() + config, weights = load_model(root) + monkeypatch.setattr(attention, "paged_attention", reference_attention) + target = Inkling2Target(config, (5,), precision=load_precision(root)) + load_target_weights(target, root) + target.prepare() + experts = _fast_experts() + for layer in target.layers: + module = layer.mlp.experts # ty: ignore[unresolved-attribute] + monkeypatch.setattr( + module, + "_local", + lambda h, i, w, e=module, max_rows_per_expert=None: experts(e, h, i, w), + ) + model = Inkling2Model(config, weights) + text = (root / "README.md").read_text() + prompt = Tokenizer.from_file(str(root / "tokenizer.json")).encode(text).ids[:24] + + # Teacher-forced: each visit's attention and experts from the reference's inputs. + records = _record(target) + errors = {"attention": 0.0, "mlp": 0.0} + cursor = {"attention": 0, "mlp": 0} + attend, sparse = Inkling2Model._attention, mlx_model.sparse_mlp + + def forced_attention(self, layer, sources, state, tau, visit, slot, store): + index = cursor["attention"] + cursor["attention"] += 1 + forced = tuple(_to_mlx(x) for x in records["sources"][index]) + output, k_history, v_history = attend( + self, layer, forced, state, tau, visit, slot, store + ) + expected = records["attention"][index] + errors["attention"] = max(errors["attention"], _relative(output, expected)) + return _to_mlx(expected), k_history, v_history + + 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 + ) + expected = records["mlp"][index] + errors["mlp"] = max(errors["mlp"], _relative(output, expected)) + return _to_mlx(expected).reshape(x.shape) + + tokens = torch.tensor([prompt]) + positions = torch.arange(len(prompt))[None] + state = torch.zeros( + 1, config.execution_layer_count, 3, config.state_width(), dtype=torch.bfloat16 + ) + with torch.no_grad(): + expected, _, _, _ = target( + tokens, + positions, + ReferenceCache(config, 1, 64), + state, + positions[:, -1] + 1, + len(prompt), + full_logits=True, + prefill=True, + ) + 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.positions = mx.array(positions.numpy()) + actual, _ = model( + mx.array(tokens.numpy()), + store.positions, + model.initial_state(1), + store, + last_only=False, + ) + # Real-checkpoint visits agree within about one BF16 step (2^-8 relative). + assert errors["attention"] < 1e-2 and errors["mlp"] < 1e-2, errors + 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) + reference_state = state + mlx_state = model.initial_state(1) + current, start = tokens, 0 + for step in range(4): + count = current.shape[1] + positions = torch.arange(start, start + count)[None] + with torch.no_grad(): + expected, _, reference_state, _ = target( + current, + positions, + cache, + reference_state, + positions[:, -1] + 1, + start + count, + full_logits=False, + prefill=step == 0, + ) + store.positions = mx.array(positions.numpy()) + actual, mlx_state = model( + mx.array(current.numpy()), store.positions, mlx_state, store + ) + token = int(expected[0, -1].float().argmax()) + assert int(np.argmax(np.array(actual[0, -1]))) == token, step + current, start = torch.tensor([[token]]), start + count diff --git a/models/mlx/tests/test_inkling2_engine.py b/models/mlx/tests/test_inkling2_engine.py new file mode 100644 index 00000000..1e958a57 --- /dev/null +++ b/models/mlx/tests/test_inkling2_engine.py @@ -0,0 +1,428 @@ +"""Inkling 2 MLX runner through the Engine: cache plumbing, overlap and prefix reuse. + +Random tiny Inkling models are numerically chaotic (FP4 activations amplify one +ULP into different tokens), so these tests check exact invariants instead of +comparing against a separately rounded dense model: every history row the arena +returns is byte-identical to the row written for that token prefix, and runs +that perform identical arithmetic produce identical tokens. +""" + +from __future__ import annotations + +import mlx.core as mx +import numpy as np +import pytest + +pytest.importorskip("torch") + +from test_inkling2_model import tiny_config, write_checkpoint # noqa: E402 + +from resin import Engine, SamplingParams # noqa: E402 +from resin_models_mlx.inkling2 import runner as runner_module # noqa: E402 +from resin_models_mlx.inkling2.attention import dense_attention # noqa: E402 +from resin_models_mlx.inkling2.cache import GLOBAL_GROUP, LOCAL_GROUP # noqa: E402 +from resin_models_mlx.inkling2.checkpoint import load_model # noqa: E402 +from resin_models_mlx.inkling2.runner import Inkling2MlxRunner # noqa: E402 + +CHUNK = 128 +CONTEXT = 1024 + + +@pytest.fixture(scope="module") +def weights(tmp_path_factory): + root = tmp_path_factory.mktemp("inkling2") + write_checkpoint(root, tiny_config()) + return load_model(root) + + +def _runner(weights, slabs: int = 256) -> Inkling2MlxRunner: + return Inkling2MlxRunner( + weights, + cache_slab_capacity=slabs, + max_seq_len=CONTEXT, + prefill_chunk_size=CHUNK, + workspace_bytes=64 << 20, + ) + + +def _prompt(length: int, seed: int) -> list[int]: + return np.random.default_rng(seed).integers(0, 300, size=length).tolist() + + +def _generate(engine, prompts, count): + params = SamplingParams(max_output_tokens=count, temperature=0.0) + requests = [engine.submit(prompt, sampling_params=params) for prompt in prompts] + while engine.has_work(): + engine.step() + return [list(request.take_result()) for request in requests] + + +class _Mirror: + """Reference K/V by token prefix, checked against every arena history read.""" + + def __init__(self, prompts, window): + self.prompts = prompts + self.window = window + self.tokens: dict[int, list[int]] = {} + # A request's own writes, and the first write of each token prefix, + # which is what a prefix hit restores. + self.own: dict[tuple, tuple[np.ndarray, np.ndarray]] = {} + self.shared: dict[tuple, tuple[np.ndarray, np.ndarray]] = {} + self.checked = 0 + self.attention_checks = 0 + + def start_step(self, plan, rows, tokens): + batch = plan.batch + for index, row in enumerate(rows.tolist()): + sequence = int(batch.sequence_ids[row]) + context = int(batch.context_lengths[row]) + step = batch.token_ids[tokens[index]].tolist() + known = self.tokens.get(sequence) + if known is None: + # A prefix hit starts mid-prompt: recover its restored tokens. + known = next( + p[:context] + for p in self.prompts + if p[context : context + len(step)] == step + ) + self.tokens[sequence] = known + assert len(known) == context + known += step + + def key(self, sequence, position, group, slot): + return (tuple(self.tokens[sequence][: position + 1]), group, slot) + + def check(self, store, group, slot, k, v): + history = store.history[group] + contexts = store.contexts + if history is not None: + keys, values, key_positions, key_valid = history.gather(slot) + hk = np.array(keys.view(mx.uint16)) + hv = np.array(values.view(mx.uint16)) + positions, valid = np.array(key_positions), np.array(key_valid) + for row, sequence in enumerate(store.sequence_ids.tolist()): + present = {} + for column in np.flatnonzero(valid[row]): + present[int(positions[row, column])] = column + context = int(contexts[row]) + first = ( + max(0, context - (self.window - 1)) if group == LOCAL_GROUP else 0 + ) + needed = range(first, context) + assert set(needed) <= present.keys(), (group, slot, context) + for position in needed: + expected = self.own.get((int(sequence), position, group, slot)) + if expected is None: + expected = self.shared[ + self.key(int(sequence), position, group, slot) + ] + column = present[position] + assert np.array_equal(hk[row, column], expected[0]), position + assert np.array_equal(hv[row, column], expected[1]), position + self.checked += 1 + k_rows = np.array(k.astype(mx.bfloat16).view(mx.uint16)) + v_rows = np.array(v.astype(mx.bfloat16).view(mx.uint16)) + positions = np.array(store.positions) + for row, sequence in enumerate(store.sequence_ids.tolist()): + for column, position in enumerate(positions[row].tolist()): + written = (k_rows[row, column], v_rows[row, column]) + self.own[int(sequence), position, group, slot] = written + self.shared.setdefault( + self.key(int(sequence), position, group, slot), written + ) + + def reference(self_, store, group, slot, q, k, v, bias, scale, window): + """Unsliced dense attention over every mirrored key of each row.""" + positions = np.array(store.positions) + rows, tokens = positions.shape + longest = int(positions.max()) + 1 + kv_heads, dim = k.shape[2], k.shape[3] + keys = np.zeros((rows, longest, kv_heads * dim), np.uint16) + values = np.zeros_like(keys) + valid = np.zeros((rows, longest), bool) + for row, sequence in enumerate(store.sequence_ids.tolist()): + for position in range(int(positions[row, -1]) + 1): + written = self_.own.get((int(sequence), position, group, slot)) + if written is None: + written = self_.shared[ + self_.key(int(sequence), position, group, slot) + ] + keys[row, position] = written[0].reshape(-1) + values[row, position] = written[1].reshape(-1) + valid[row, position] = True + shape = (rows, longest, kv_heads, dim) + return dense_attention( + q, + mx.array(keys).view(mx.bfloat16).reshape(shape), + mx.array(values).view(mx.bfloat16).reshape(shape), + mx.broadcast_to(mx.arange(longest)[None], (rows, longest)).astype(mx.int32), + mx.array(valid), + store.positions, + bias, + scale, + window if group == LOCAL_GROUP else None, + ) + + +def _instrument(monkeypatch, runner, mirror): + launch = runner._launch + + def recorded_launch(plan, rows, tokens, token_ids=None): + assert token_ids is None, "plumbing checks need plan token IDs (no overlap)" + mirror.start_step(plan, rows, tokens) + return launch(plan, rows, tokens, token_ids) + + monkeypatch.setattr(runner, "_launch", recorded_launch) + attend = runner_module._StepStore.attend + + def checked_attend(self, local, slot, q, k, v, bias, scale, window): + group = LOCAL_GROUP if local else GLOBAL_GROUP + mirror.check(self, group, slot, k, v) + output, lse = attend(self, local, slot, q, k, v, bias, scale, window) + expected, expected_lse = mirror.reference( + self, group, slot, q, k, v, bias, scale, window + ) + np.testing.assert_allclose( + np.array(output), np.array(expected), rtol=1e-4, atol=1e-4 + ) + np.testing.assert_allclose( + np.array(lse), np.array(expected_lse), rtol=1e-4, atol=1e-4 + ) + mirror.attention_checks += 1 + return output, lse + + monkeypatch.setattr(runner_module._StepStore, "attend", checked_attend) + + +def test_history_reads_return_exactly_what_was_written(weights, monkeypatch): + config = weights[0] + # Prompts straddle page, chunk and window boundaries; decode crosses more. + prompts = [_prompt(n, seed) for seed, n in enumerate((5, 127, 128, 129, 300))] + runner = _runner(weights) + mirror = _Mirror(prompts, config.sliding_window_size) + _instrument(monkeypatch, runner, mirror) + with Engine(runner, context_length=CONTEXT, enable_overlap=False) as engine: + outputs = _generate(engine, prompts, 20) + assert all(len(output) == 20 for output in outputs) + assert mirror.checked > 10_000 + assert mirror.attention_checks > 400 + assert len(runner._states) == 0 + + +def test_prefix_hit_reads_restored_history_exactly(weights, monkeypatch): + config = weights[0] + shared = _prompt(400, seed=11) + prompts = [shared + _prompt(30, seed=12), shared + _prompt(50, seed=13)] + runner = _runner(weights) + mirror = _Mirror(prompts, config.sliding_window_size) + _instrument(monkeypatch, runner, mirror) + contexts = [] + launch = runner._launch + + def first_context(plan, rows, tokens, token_ids=None): + contexts.append(int(plan.batch.context_lengths[rows[0]])) + return launch(plan, rows, tokens, token_ids) + + monkeypatch.setattr(runner, "_launch", first_context) + with Engine( + runner, context_length=CONTEXT, enable_overlap=False, prefix_cache=True + ) as engine: + _generate(engine, prompts[:1], 4) + contexts.clear() + _generate(engine, prompts[1:], 4) + # The second prompt restored a snapshot inside the shared prefix. + assert 0 < contexts[0] <= len(shared) and contexts[0] % CHUNK == 0 + assert mirror.checked > 1_000 + + +def test_cached_continuation_matches_fresh_and_overlap_matches_sync(weights): + shared = _prompt(384, seed=21) + prompt = shared + _prompt(40, seed=22) + with Engine( + _runner(weights), context_length=CONTEXT, enable_overlap=False + ) as engine: + fresh = _generate(engine, [prompt], 24) + with Engine(_runner(weights), context_length=CONTEXT, prefix_cache=True) as engine: + _generate(engine, [shared + [1, 2, 3]], 2) + cached = _generate(engine, [prompt], 24) + assert cached == fresh + prompts = [_prompt(n, seed) for seed, n in enumerate((7, 130, 260), start=30)] + with Engine( + _runner(weights), context_length=CONTEXT, enable_overlap=False + ) as engine: + sync = _generate(engine, prompts, 24) + runner = _runner(weights) + with Engine(runner, context_length=CONTEXT, enable_overlap=True) as engine: + overlapped = _generate(engine, prompts, 24) + assert engine.overlap_stats[1] > 0 + assert overlapped == sync + assert len(runner._states) == 0 + + +def test_cancel_releases_state_and_context_limit_is_enforced(weights): + runner = _runner(weights) + with Engine(runner, context_length=CONTEXT) as engine: + params = SamplingParams(max_output_tokens=50, temperature=0.0) + request = engine.submit(_prompt(140, seed=40), sampling_params=params) + for _ in range(4): + engine.step() + assert engine.cancel(request) + while engine.has_work(): + engine.step() + assert len(runner._states) == 0 + # The final sampled token is never stored, so a prompt three short of + # the limit yields four tokens; the Engine rejects a fifth. + long_prompt = _prompt(CONTEXT - 3, seed=41) + assert len(_generate(engine, [long_prompt], 4)[0]) == 4 + with pytest.raises(ValueError, match="context"): + _generate(engine, [long_prompt], 5) + + +def test_serving_thread_can_use_weights_loaded_on_another_thread(tmp_path): + from concurrent.futures import ThreadPoolExecutor + + # The HTTP server steps the Engine on its own actor thread; lazily loaded + # safetensors arrays would need the loading thread's CPU stream there. + write_checkpoint(tmp_path, tiny_config()) + weights = load_model(tmp_path) + runner = _runner(weights) + with Engine(runner, context_length=CONTEXT) as engine: + with ThreadPoolExecutor(max_workers=1) as executor: + outputs = executor.submit(_generate, engine, [_prompt(20, seed=50)], 4) + assert len(outputs.result(timeout=120)[0]) == 4 + + +@pytest.mark.parametrize("window,extent", [(300, 200), (200, 300)]) +def test_multi_page_window_and_extent(tmp_path, monkeypatch, window, extent): + from dataclasses import replace + + # Windows and bias extents spanning several pages, unequal to each other, + # with chunks larger than a page and a prefix hit inside the window. + config = replace(tiny_config(), sliding_window_size=window, rel_extent=extent) + write_checkpoint(tmp_path, config) + weights = load_model(tmp_path) + shared = _prompt(700, seed=60) + prompts = [_prompt(n, seed) for seed, n in enumerate((5, 257, 640), start=61)] + prompts += [shared + _prompt(30, seed=64), shared + _prompt(90, seed=65)] + runner = Inkling2MlxRunner( + weights, + cache_slab_capacity=512, + max_seq_len=2048, + prefill_chunk_size=256, + workspace_bytes=64 << 20, + ) + mirror = _Mirror(prompts, window) + _instrument(monkeypatch, runner, mirror) + with Engine( + runner, context_length=2048, enable_overlap=False, prefix_cache=True + ) as engine: + assert all(len(output) == 24 for output in _generate(engine, prompts[:4], 24)) + _generate(engine, prompts[4:], 24) + assert mirror.attention_checks > 400 + + +def test_padded_vocabulary_ids_and_small_caches_are_rejected(weights): + config = weights[0] + runner = _runner(weights) + # Embedding rows past the unpadded vocabulary are padding with no logits. + assert runner.vocab_size == config.unpadded_vocab_size < config.vocab_size + with Engine(runner, context_length=CONTEXT) as engine: + padded = [1, 2, config.unpadded_vocab_size, 3] + params = SamplingParams(max_output_tokens=2, temperature=0.0) + # Rejected while validating the plan, before any cache write. + with pytest.raises(ValueError, match="out of range"): + engine.submit(padded, sampling_params=params) + while engine.has_work(): + engine.step() + assert len(runner._states) == 0 + with pytest.raises(ValueError, match="fewer than one"): + Inkling2MlxRunner( + weights, + cache_slab_capacity=2, + max_seq_len=CONTEXT, + prefill_chunk_size=CHUNK, + workspace_bytes=64 << 20, + ) + + +def test_unseen_lengths_and_sampling_reuse_compiled_kernels(weights, monkeypatch): + from resin_models_mlx.inkling2 import decode_attention, kernels, quantization + + # Record every custom Metal kernel variant: its factory, template and dtypes. + variants: set = set() + for module in (kernels, quantization, decode_attention): + for name in dir(module): + factory = getattr(module, name) + if not ( + name.startswith("_") and name.endswith("_kernel") and callable(factory) + ): + continue + + def recording(*args, factory=factory, name=name, **options): + kernel = factory(*args, **options) + + def call(**launch): + dtypes = tuple(str(x.dtype) for x in launch["inputs"]) + variants.add( + (name, args, tuple(launch.get("template", ())), dtypes) + ) + return kernel(**launch) + + return call + + monkeypatch.setattr(module, name, recording) + + def run(engine, lengths, params): + requests = [ + engine.submit(_prompt(n, seed), sampling_params=params) + for seed, n in enumerate(lengths, start=80) + ] + while engine.has_work(): + engine.step() + for request in requests: + request.take_result() + + greedy = SamplingParams(max_output_tokens=6, temperature=0.0) + with Engine( + _runner(weights), context_length=CONTEXT, max_running_requests=4 + ) as engine: + # Warm the bounded regimes: prefill, decode at each batch size, sampling. + for batch in range(1, 5): + run(engine, [40 + 9 * i for i in range(batch)], greedy) + run( + engine, + [50], + SamplingParams(max_output_tokens=6, temperature=0.7, top_p=0.9, seed=1), + ) + run( + engine, + [50], + SamplingParams(max_output_tokens=6, temperature=0.7, top_k=5, seed=2), + ) + warm = set(variants) + # Unseen prompt and chunk lengths, contexts past the window and page, + # batch mixes and sampling values. + run(engine, [173, 3, 301], greedy) + run( + engine, + [77, 129], + SamplingParams(max_output_tokens=9, temperature=1.3, top_k=3, seed=4), + ) + run( + engine, + [250], + SamplingParams(max_output_tokens=20, temperature=0.31, top_p=0.6, seed=5), + ) + # Every kernel ran during warmup (the GEMV needs widths of 256 or more). + assert {variant[0] for variant in warm} == { + "_activate_kernel", + "_combine_kernel", + "_convolution_kernel", + "_kernel", + "_mix_kernel", + "_mxfp8_kernel", + "_norm_kernel", + "_nvfp4_kernel", + "_route_kernel", + } + assert variants == warm, sorted(map(str, variants - warm)) diff --git a/models/mlx/tests/test_inkling2_kernels.py b/models/mlx/tests/test_inkling2_kernels.py new file mode 100644 index 00000000..30fd993e --- /dev/null +++ b/models/mlx/tests/test_inkling2_kernels.py @@ -0,0 +1,177 @@ +"""Inkling 2 Metal kernels at Mini's real widths against the CUDA CPU references. + +The tiny model in test_inkling2_model.py runs every kernel, but at widths that +skip multi-simdgroup reductions, the BF16 GEMV and multi-value-per-thread rows. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import mlx.core as mx +import numpy as np +import pytest + +torch = pytest.importorskip("torch") +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "cuda" / "tests")) +from _inkling2_expert_reference import dequant, nvfp4_reference # noqa: E402 + +from resin_models_cuda.inkling2 import kernels as reference # noqa: E402 +from resin_models_mlx.inkling2 import kernels # noqa: E402 +from resin_models_mlx.inkling2.quantization import quantize_activations # noqa: E402 + +HIDDEN, INTERMEDIATE, KV_WIDTH, EXPERTS = 2304, 1152, 1024, 128 + + +def _mx(x: torch.Tensor) -> mx.array: + if x.dtype == torch.bfloat16: + return mx.array(x.view(torch.int16).numpy()).view(mx.bfloat16) + return mx.array(x.numpy()) + + +def _torch(x: mx.array) -> torch.Tensor: + if x.dtype == mx.bfloat16: + return torch.from_numpy(np.array(x.view(mx.int16))).view(torch.bfloat16) + return torch.from_numpy(np.array(x)) + + +def _within_bf16_step(actual: torch.Tensor, expected: torch.Tensor) -> None: + # Reductions sum in a different order; allow one BF16 rounding step. + actual, expected = actual.float(), expected.float() + step = expected.abs().clamp(min=1e-30) * 2.0**-7 + assert torch.all((actual - expected).abs() <= step) + + +@pytest.fixture +def generator(): + return torch.Generator().manual_seed(0) + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_rms_norm(generator, dtype): + x = (torch.randn(7, HIDDEN, generator=generator) * 3).to(dtype) + weight = 1 + 0.2 * torch.randn(HIDDEN, generator=generator) + for scale in (weight, None): + actual = kernels.rms_norm(_mx(x), None if scale is None else _mx(scale), 1e-6) + expected = reference.rms_norm(x, scale, 1e-6, dtype=torch.bfloat16) + _within_bf16_step(_torch(actual), expected) + + +@pytest.mark.parametrize("tokens", [1, 5]) +def test_short_convolution(generator, tokens): + x = (torch.randn(3, tokens, HIDDEN, generator=generator) * 2).bfloat16() + state = torch.randn(3, 3, HIDDEN, generator=generator).bfloat16() + weight = (torch.randn(HIDDEN, 4, generator=generator) * 0.3).bfloat16() + actual, history = kernels.short_convolution(_mx(x), _mx(state), _mx(weight)) + expected, expected_history = reference.short_convolution(x, state, weight.float()) + assert torch.equal(_torch(actual), expected) + assert torch.equal(_torch(history), expected_history) + # Dynamic: FP32 static taps (tap zero current) plus per-head BF16 taps. + x = x[..., :KV_WIDTH].contiguous() + state = state[..., :KV_WIDTH].contiguous() + static = torch.randn(4, KV_WIDTH, generator=generator) * 0.3 + dynamic = (torch.randn(3, tokens, 8, 4, generator=generator) * 0.3).bfloat16() + actual, history = kernels.short_convolution( + _mx(x), _mx(state), _mx(static), _mx(dynamic) + ) + expected, expected_history = reference.short_convolution(x, state, static, dynamic) + assert torch.equal(_torch(actual), expected) + assert torch.equal(_torch(history), expected_history) + + +@pytest.mark.parametrize( + "sources,queries,addend", [(1, 1, False), (4, 3, False), (6, 1, True)] +) +def test_depth_mix(generator, sources, queries, addend): + values = [ + (torch.randn(5, HIDDEN, generator=generator) * (index + 1)).bfloat16() + for index in range(sources) + ] + query = torch.randn(queries, HIDDEN, generator=generator) + extra = torch.randn(5, HIDDEN, generator=generator).bfloat16() if addend else None + actual = kernels.depth_mix( + [_mx(x) for x in values], _mx(query), None if extra is None else _mx(extra) + ) + expected = torch.stack( + reference.block_attention_residual( + values, query, normalize_values=True, partial_addend=extra + ), + dim=1, + ) + torch.testing.assert_close(_torch(actual), expected, rtol=1e-5, atol=1e-5) + + +def test_route_experts_breaks_ties_by_lower_id(generator): + logits = torch.randn(9, EXPERTS, generator=generator) * 2 + bias = torch.randn(EXPERTS, generator=generator) * 0.1 + # Exact ties across simdgroups must choose the lower expert ID. + logits[0] = 0.0 + bias_tied = bias.clone() + bias_tied[:] = 0.0 + for scores in (bias, bias_tied): + ids, weights = kernels.route_experts(_mx(logits), _mx(scores), 8, 8.0) + expected_ids, expected_weights = reference.route_experts(logits, scores, 8, 8.0) + assert torch.equal(_torch(ids).long(), expected_ids) + torch.testing.assert_close( + _torch(weights), expected_weights, rtol=1e-6, atol=1e-7 + ) + + +@pytest.mark.parametrize("width", [HIDDEN, INTERMEDIATE]) +def test_activation_quantization(generator, width): + x = ( + torch.randn(17, width, generator=generator) + * 2.0 ** torch.randint(-6, 6, (17, 1)) + ).bfloat16() + x[3] = 0 + packed, scales, amax = nvfp4_reference(x) + values, row_amax = quantize_activations(_mx(x), "nvfp4") + assert row_amax is not None + assert torch.equal( + _torch(values).abs(), dequant(packed, scales, torch.ones_like(amax), 1.0).abs() + ) + assert torch.equal(_torch(row_amax), amax) + grouped = x.float().reshape(17, -1, 32) + raw = grouped.abs().amax(-1) * (1.0 / 448.0) + exponent = ((raw.view(torch.int32) + 0x007FFFFF) & 0x7F800000) >> 23 + exponent = torch.where(raw <= 2.0**-127, 0, exponent.clamp(max=254)) + scale = (exponent << 23).view(torch.float32) + inverse = torch.where(exponent == 0, torch.zeros_like(scale), 1.0 / scale) + codes = ( + (grouped * inverse[..., None]).clamp(-448, 448).to(torch.float8_e4m3fn).float() + ) + values, row_amax = quantize_activations(_mx(x), "mxfp8") + assert row_amax is None + assert torch.equal(_torch(values), (codes * scale[..., None]).flatten(1)) + + +@pytest.mark.parametrize("rows", [1, 3, 4, 8, 9]) +def test_gemv_f32(generator, rows): + weight = (torch.randn(1000, HIDDEN, generator=generator) * 0.02).bfloat16() + x = torch.randn(rows, HIDDEN, generator=generator).bfloat16() + actual = kernels.gemv_f32(_mx(x), _mx(weight)) + torch.testing.assert_close( + _torch(actual), x.float() @ weight.float().t(), rtol=1e-5, atol=1e-5 + ) + + +def test_expert_activation_and_combine(generator): + routes, rows, top_k = 24, 3, 8 + gate_up = torch.randn(routes, 2 * INTERMEDIATE, generator=generator) * 3 + gamma = torch.rand(routes, generator=generator) * 2 + activated = kernels.expert_activation(_mx(gate_up), _mx(gamma), 4.0, 25.0) + rounded = gate_up.bfloat16().float() + gate, up = rounded[:, 0::2], rounded[:, 1::2] + expected = ( + ((4 * (gate / 4).tanh()) * gate.sigmoid()) * (25 * (up / 25).tanh()) + ) * gamma[:, None] + _within_bf16_step(_torch(activated), expected.bfloat16()) + down = torch.randn(routes, HIDDEN, generator=generator) + inverse = torch.randperm(routes, generator=generator).int() + combined = kernels.expert_combine(_mx(down), _mx(inverse), top_k) + routed = down[inverse.long()].bfloat16().float().view(rows, top_k, HIDDEN) + total = routed[:, 0] + for slot in range(1, top_k): + total = total + routed[:, slot] + assert torch.equal(_torch(combined), total.bfloat16()) diff --git a/models/mlx/tests/test_inkling2_model.py b/models/mlx/tests/test_inkling2_model.py new file mode 100644 index 00000000..58c60330 --- /dev/null +++ b/models/mlx/tests/test_inkling2_model.py @@ -0,0 +1,607 @@ +"""Inkling 2 MLX forward pass against the CUDA package's model on CPU PyTorch. + +The reference is ``resin_models_cuda.inkling2.model.Inkling2Target`` loaded +from the same checkpoint files, with only its CUDA kernels replaced: dense +PyTorch attention and packed experts dequantized by the CUDA tests' independent +NVFP4/MXFP8 arithmetic. +""" + +from __future__ import annotations + +import json +import math +import sys +from dataclasses import asdict +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import mlx.core as mx +import numpy as np +import pytest + +torch = pytest.importorskip("torch") +safetensors_torch = pytest.importorskip("safetensors.torch") + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "cuda" / "tests")) +from _inkling2_expert_reference import dequant, nvfp4_reference # noqa: E402 + +from resin.models.inkling2.config import ( # noqa: E402 + Inkling2Config, + Inkling2LoopConfig, +) +from resin_models_mlx.inkling2.checkpoint import load_model # noqa: E402 +from resin_models_mlx.inkling2.model import Inkling2Model # noqa: E402 + +NVFP4_LAYERS = 4 + + +def tiny_config() -> Inkling2Config: + return Inkling2Config( + vocab_size=320, + unpadded_vocab_size=300, + hidden_size=128, + num_hidden_layers=8, + num_attention_heads=4, + num_key_value_heads=2, + head_dim=32, + swa_num_attention_heads=4, + swa_num_key_value_heads=2, + swa_head_dim=32, + d_rel=4, + rel_extent=12, + local_layer_ids=(0, 1, 3, 4, 6), + sliding_window_size=12, + sconv_kernel_size=4, + n_layers_per_attn_res_block=2, + attn_res_normalize_values=True, + intermediate_size=64, + num_routed_experts=16, + experts_per_token=8, + route_scale=2.0, + mlp_gate_softcap=4.0, + mlp_up_softcap=25.0, + qk_l2_clip_threshold=3.0, + rel_l2_clip_threshold=2.0, + rms_norm_eps=1e-6, + max_position_embeddings=4096, + log_scaling_n_floor=16, + log_scaling_alpha=0.1, + final_logit_softcapping=30.0, + eos_token_id=7, + loop=Inkling2LoopConfig(core_start=2, core_end=6, num_passes=3, gate_rank=4), + ) + + +def _hf_config(config: Inkling2Config) -> dict: + text = asdict(config) + loop = text.pop("loop") + text.update( + torch_dtype="bfloat16", + q_bias=False, + o_bias=False, + use_value_norm_no_gamma=True, + n_shared_experts=0, + use_gate_bias=True, + n_routed_experts=config.num_routed_experts, + num_experts_per_tok=config.experts_per_token, + model_max_length=config.max_position_embeddings, + loop_config={**loop, "is_varloop": False}, + ) + for name in ("num_routed_experts", "experts_per_token", "max_position_embeddings"): + text.pop(name) + eos = text.pop("eos_token_id") + return dict( + model_type="inkling2_loop", + architectures=["Inkling2LoopForConditionalGeneration"], + text_config=text, + eos_token_id=eos, + ) + + +def _layer_mode(layer: int) -> str: + return "nvfp4" if layer < NVFP4_LAYERS else "mxfp8" + + +def write_checkpoint(root: Path, config: Inkling2Config, seed: int = 0) -> None: + """Random tensors in the published names, dtypes and packed expert layouts.""" + generator = torch.Generator().manual_seed(seed) + h, d, r = config.hidden_size, config.head_dim, config.d_rel + q, kv = config.num_attention_heads, config.num_key_value_heads + experts, inter = config.num_routed_experts, config.intermediate_size + loop = config.loop + assert loop is not None + tensors: dict[str, torch.Tensor] = {} + + def normal(name, shape, std=0.2, dtype=torch.bfloat16): + tensors["model.llm." + name] = ( + torch.randn(shape, generator=generator) * std + ).to(dtype) + + def positive(name, shape): + tensors["model.llm." + name] = ( + 1 + 0.2 * torch.randn(shape, generator=generator) + ).to(torch.bfloat16) + + normal("embed.weight", (config.vocab_size, h), 1.0) + positive("embed_norm.weight", (h,)) + positive("norm.weight", (h,)) + normal("unembed.weight", (config.vocab_size, h), 0.5) + normal("attn_res.output_query", (h,), 1.0, torch.float32) + core = 2 * (loop.core_end - loop.core_start) + normal("middle_cycle_cross_pass_queries", (core, h), 1.0, torch.float32) + normal("middle_cycle_cross_pass_kv_queries", (core, h), 1.0, torch.float32) + for i in range(config.num_hidden_layers): + local = i in config.local_layer_ids + prefix = f"layers.{i}." + if i: + normal( + f"attn_res.attn_queries.{i - 1}", + (h,) if local else (3, h), + 1.0, + torch.float32, + ) + normal(f"attn_res.mlp_queries.{i}", (h,), 1.0, torch.float32) + for name in ( + ("attn_norm",) + if local + else ("q_input_norm", "k_input_norm", "v_input_norm") + ): + positive(prefix + name + ".weight", (h,)) + positive(prefix + "mlp_norm.weight", (h,)) + for name, size in ( + ("wq_du", q * d), + ("wk_dv", kv * d), + ("wv_dv", kv * d), + ("wr_du", q * r), + ("gate_attn", q * d), + ("attn_sink_proj", q), + ): + normal(prefix + f"attn.{name}.weight", (size, h), h**-0.5) + normal(prefix + "attn.wo_ud.weight", (h, q * d), (q * d) ** -0.5) + positive(prefix + "attn.q_l2_clip.scale", (q, d)) + positive(prefix + "attn.rel_l2_clip.scale", (q, r)) + normal( + prefix + "attn.rel_logits_proj.proj", + (r, config.sliding_window_size if local else config.rel_extent), + 0.5, + ) + for name in ("k_sconv", "v_sconv"): + if local: + normal(prefix + f"attn.{name}.weight", (kv * d, 1, 4), 0.3) + else: + normal(prefix + f"attn.{name}.static_w", (4, kv * d), 0.3) + normal(prefix + f"attn.{name}.weight_proj", (kv * 4, h), h**-0.5) + for name in ("attn_sconv", "mlp_sconv"): + normal(prefix + f"{name}.weight", (h, 1, 4), 0.3) + normal(prefix + "mlp.gate.weight", (experts, h), h**-0.5) + normal(prefix + "mlp.gate.bias", (experts,), 0.1, torch.float32) + mode = _layer_mode(i) + for matrix, (n, k) in (("w13", (2 * inter, h)), ("w2", (h, inter))): + base = prefix + f"mlp.experts.{matrix}_weight" + if mode == "nvfp4": + tensors["model.llm." + base] = torch.randint( + 0, 256, (experts, n, k // 2), generator=generator, dtype=torch.uint8 + ) + levels = torch.tensor([0.5, 0.75, 1.0, 1.5, 2.0]) + choice = torch.randint(0, 5, (experts, n, k // 16), generator=generator) + tensors["model.llm." + base + "_scale"] = levels[choice].to( + torch.float8_e4m3fn + ) + tensors["model.llm." + base + "_amax"] = 0.5 + 0.5 * torch.rand( + experts, generator=generator + ) + tensors["model.llm." + base + "_outer_scale_denominator"] = ( + torch.tensor([6.0 * k**0.5]) + ) + else: + tensors["model.llm." + base] = ( + torch.randn((experts, n, k), generator=generator) * 32 + ).to(torch.float8_e4m3fn) + exponent = 127 - 5 - round(math.log2(k**0.5)) + tensors["model.llm." + base + "_scale"] = torch.full( + (experts, n, k // 32), exponent, dtype=torch.uint8 + ) + if loop.core_start <= i < loop.core_end: + for stream in ("attn", "k", "v", "mlp"): + controller = prefix + f"controllers.{stream}." + normal( + controller + "down_weight", (loop.gate_rank, 2 * h), (2 * h) ** -0.5 + ) + normal(controller + "gain_weight", (h, loop.gate_rank), 0.5) + normal(controller + "forget_weight", (h, loop.gate_rank), 0.5) + root.mkdir(parents=True, exist_ok=True) + safetensors_torch.save_file(tensors, root / "model.safetensors") + (root / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": dict.fromkeys(tensors, "model.safetensors")}) + ) + (root / "config.json").write_text(json.dumps(_hf_config(config))) + nvfp4: dict[str, Any] = { + "compute_dtype": "nvfp4", + "required_activation_quantization": { + "amax_type": "per_token", + "block_size": 16, + "format": "nvfp4_e2m1", + "rounding": "nearest", + "scale_dtype": "float8_e4m3fn", + "scale_selection_rule": "fouroversix_mae", + }, + "tensors": [], + } + mxfp8: dict[str, Any] = { + "compute_dtype": "mxfp8", + "required_activation_quantization": { + "block_size": 32, + "format": "mxfp8_e4m3", + "rounding": "nearest", + "scale_dtype": "ue8m0", + }, + "tensors": [], + } + for i in range(config.num_hidden_layers): + group = nvfp4 if _layer_mode(i) == "nvfp4" else mxfp8 + group["tensors"] += [ + f"model.llm.layers.{i}.mlp.experts.{matrix}_weight" + for matrix in ("w13", "w2") + ] + (root / "hf_quant_config.json").write_text( + json.dumps({"model": {"parameter_groups": [nvfp4, mxfp8]}}) + ) + + +# --- PyTorch reference --------------------------------------------------------- + + +def _mxfp8_activations(x): + grouped = x.float().reshape(x.shape[0], -1, 32) + raw = grouped.abs().amax(-1) * (1.0 / 448.0) + exponent = ((raw.view(torch.int32) + 0x007FFFFF) & 0x7F800000) >> 23 + exponent = torch.where(raw <= 2.0**-127, 0, exponent.clamp(max=254)) + scale = (exponent << 23).view(torch.float32) + inverse = torch.where(exponent == 0, torch.zeros_like(scale), 1.0 / scale) + values = ( + (grouped * inverse[..., None]).clamp(-448, 448).to(torch.float8_e4m3fn).float() + ) + return (values * scale[..., None]).flatten(1) + + +def _activations(x, mode): + if mode == "nvfp4": + packed, scales, amax = nvfp4_reference(x) + return dequant(packed, scales, torch.ones_like(amax), 1.0), amax + return _mxfp8_activations(x), None + + +def _weight(module, name, mode, expert): + weight = getattr(module, name + "_weight")[expert] + scales = getattr(module, name + "_weight_scale")[expert] + if mode == "nvfp4": + return dequant(weight, scales, torch.tensor(1.0), 1.0) + return dequant(weight, scales) + + +def reference_experts(module, hidden, ids, weights): + mode = module.precision["w13"] + result = torch.zeros_like(hidden, dtype=torch.float32) + + def matmul(x, name, expert): + base, amax = _activations(x, mode) + output = base @ _weight(module, name, mode, expert).t() + if mode == "nvfp4": + denominator = getattr(module, name + "_weight_outer_scale_denominator") + weight_amax = getattr(module, name + "_weight_amax")[expert] + output = ( + output + * ((amax * weight_amax) * (1.0 / (1536.0 * denominator)))[:, None] + ) + return output.to(torch.bfloat16) + + for token in range(hidden.shape[0]): + for slot in range(ids.shape[1]): + expert = int(ids[token, slot]) + gate, up = ( + matmul(hidden[token : token + 1], "w13", expert) + .float() + .view(-1, 2) + .unbind(-1) + ) + activated = ( + ((4 * (gate / 4).tanh()) * gate.sigmoid()) * (25 * (up / 25).tanh()) + ) * weights[token, slot] + down = matmul(activated.to(torch.bfloat16)[None], "w2", expert) + result[token] += down[0].float() + return result + + +class ReferenceCache: + """One contiguous page per (row, visit): the reference reads keys [0, length).""" + + def __init__(self, config, batch, capacity): + self.page_tokens, self.slab_units = capacity, 1 + self.counts = { + 0: config.execution_global_layer_count, + 1: config.execution_local_layer_count, + } + self.groups = [ + SimpleNamespace(first_blocks=torch.zeros(batch, dtype=torch.int64)) + for _ in range(2) + ] + shape = ( + batch * config.execution_layer_count, + capacity, + config.num_key_value_heads, + config.head_dim, + ) + self.keys = torch.zeros(shape, dtype=torch.bfloat16) + self.values = torch.zeros_like(self.keys) + self.batch = batch + + def pages(self, group, layer, count): + base = 0 if group == 0 else self.batch * self.counts[0] + return (base + torch.arange(self.batch) * count + layer)[:, None] + + def store_kv(self, keys, values, positions, *, group_index, layer, layer_count): + pages = self.pages(group_index, layer, layer_count).expand_as(positions) + self.keys[pages, positions], self.values[pages, positions] = keys, values + + +def reference_attention( + q, + *, + cache, + group_index, + layer, + layer_count, + positions, + sequence_lengths, + softmax_scale, + window_left, + relative_logits, + **_, +): + outputs, statistics = [], [] + for row in range(q.shape[0]): + page = cache.pages(group_index, layer, layer_count)[row, 0] + length = int(sequence_lengths[row]) + k = cache.keys[page, :length].float() + v = cache.values[page, :length].float() + groups = q.shape[2] // k.shape[1] + k, v = k.repeat_interleave(groups, 1), v.repeat_interleave(groups, 1) + logits = torch.einsum("thd,shd->ths", q[row].float(), k) * softmax_scale + distance = positions[row, :, None] - torch.arange(length)[None] + rel = relative_logits.view(*q.shape[:3], -1)[row] + bias = rel.gather( + 2, distance.clamp(0, rel.shape[-1] - 1)[:, None].expand(-1, q.shape[2], -1) + ) + logits += bias * ((distance >= 0) & (distance < rel.shape[-1]))[:, None] + mask = distance >= 0 + if window_left is not None: + mask &= distance <= window_left + logits.masked_fill_(~mask[:, None], float("-inf")) + outputs.append(torch.einsum("ths,shd->thd", logits.softmax(-1), v)) + statistics.append(logits.logsumexp(-1)) + return torch.stack(outputs), torch.cat(statistics, 0).t() + + +def reference_target(root: Path, config: Inkling2Config, monkeypatch): + from resin_models_cuda.inkling2 import attention + from resin_models_cuda.inkling2.model import Inkling2Target + from resin_models_cuda.inkling2.weights import load_target_weights + + monkeypatch.setattr(attention, "paged_attention", reference_attention) + precision = { + f"model.llm.layers.{i}.mlp.experts.{matrix}_weight": _layer_mode(i) + for i in range(config.num_hidden_layers) + for matrix in ("w13", "w2") + } + # One feature tap (for DSpark) keeps the reference's return shape; logits ignore it. + target = Inkling2Target(config, (1,), precision=precision) + load_target_weights(target, root) + target.prepare() + for layer in target.layers: + experts = layer.mlp.experts # ty: ignore[unresolved-attribute] + monkeypatch.setattr( + experts, + "_local", + lambda h, i, w, e=experts, max_rows_per_expert=None: reference_experts( + e, h, i, w + ), + ) + return target + + +class DenseStore: + """Unpaged MLX attention storage for one batch, indexed by absolute position.""" + + def __init__(self, config: Inkling2Config, batch: int, capacity: int): + shape = (batch, capacity, config.num_key_value_heads, config.head_dim) + self.keys = { + (local, slot): mx.zeros(shape, dtype=mx.bfloat16) + for local, count in ( + (True, config.execution_local_layer_count), + (False, config.execution_global_layer_count), + ) + for slot in range(count) + } + self.values = {key: mx.zeros(shape, dtype=mx.bfloat16) for key in self.keys} + self.positions: mx.array | None = None + + def attend(self, local, slot, q, k, v, bias, scale, window): + assert self.positions is not None + positions = self.positions + batch, tokens = positions.shape + rows = mx.arange(batch)[:, None] + keys = self.keys[local, slot] + values = self.values[local, slot] + keys[rows, positions] = k + values[rows, positions] = v + length = int(np.array(positions).max()) + 1 + keys, values = ( + keys[:, :length].astype(mx.float32), + values[:, :length].astype(mx.float32), + ) + groups = q.shape[2] // keys.shape[2] + keys = mx.repeat(keys, groups, axis=2) + values = mx.repeat(values, groups, axis=2) + logits = mx.einsum("bthd,bshd->bths", q.astype(mx.float32), keys) * scale + distance = positions[:, :, None] - mx.arange(length)[None, None] + extent = bias.shape[-1] + index = mx.clip(distance, 0, extent - 1) + gathered = mx.take_along_axis( + bias.astype(mx.float32), + mx.broadcast_to(index[:, :, None, :], (*bias.shape[:3], length)), + axis=-1, + ) + inside = (distance >= 0) & (distance < extent) + logits = logits + mx.where(inside[:, :, None, :], gathered, 0.0) + mask = distance >= 0 + if local: + mask = mask & (distance <= window - 1) + logits = mx.where(mask[:, :, None, :], logits, -mx.inf) + lse = mx.logsumexp(logits, axis=-1) + probabilities = mx.exp(logits - lse[..., None]) + output = mx.einsum("bths,bshd->bthd", probabilities, values) + return output, lse + + +def _relative(actual: mx.array, expected) -> float: + a = np.array(actual.astype(mx.float32)).reshape(-1) + e = expected.float().numpy().reshape(-1) + return float(np.abs(a - e).max() / max(np.abs(e).max(), 1e-6)) + + +def _record(target): + """Record every visit's attention and MLP inputs/outputs, in visit order.""" + records = {"sources": [], "attention": [], "mlp_input": [], "mlp": []} + for layer in target.layers: + layer.attn.register_forward_pre_hook( + lambda _m, args: records["sources"].append( + tuple(x.clone() for x in args[0]) + ) + ) + layer.attn.register_forward_hook( + lambda _m, _args, output: records["attention"].append(output[0].clone()) + ) + layer.mlp.register_forward_pre_hook( + lambda _m, args: records["mlp_input"].append(args[0].clone()) + ) + layer.mlp.register_forward_hook( + lambda _m, _args, output: records["mlp"].append(output.clone()) + ) + return records + + +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. + + Random tiny models are chaotic under FP4 activation quantization: a one-ULP + change at the first visit moves the reference's own logits by more than the + port does. Each MLX visit therefore (1) rebuilds the reference's attention + and MLP inputs from the reference's earlier outputs, (2) recomputes attention + and experts from the reference's exact inputs, and (3) continues from the + reference's outputs, so differences cannot compound. + """ + 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) + records = _record(target) + loaded_config, weights = load_model(tmp_path) + assert loaded_config == config + model = Inkling2Model(config, weights) + errors = {"sources": 0.0, "attention": 0.0, "mlp_input": 0.0, "mlp": 0.0} + cursor = {"attention": 0, "mlp": 0} + attention = Inkling2Model._attention + sparse = mlx_model.sparse_mlp + + def forced_attention(self, layer, sources, state, tau, visit, slot, store): + index = cursor["attention"] + cursor["attention"] += 1 + reference = records["sources"][index] + for actual, expected in zip(sources, reference, strict=True): + errors["sources"] = max(errors["sources"], _relative(actual, expected)) + forced = tuple(_to_mlx(x) for x in reference) + output, k_history, v_history = attention( + self, layer, forced, state, tau, visit, slot, store + ) + expected = records["attention"][index] + errors["attention"] = max(errors["attention"], _relative(output, expected)) + return _to_mlx(expected), k_history, v_history + + def forced_mlp(x, layer, config): + index = cursor["mlp"] + cursor["mlp"] += 1 + reference = records["mlp_input"][index] + errors["mlp_input"] = max(errors["mlp_input"], _relative(x, reference)) + output = sparse(_to_mlx(reference).reshape(x.shape), layer, config) + expected = records["mlp"][index] + errors["mlp"] = max(errors["mlp"], _relative(output, expected)) + return _to_mlx(expected).reshape(x.shape) + + monkeypatch.setattr(Inkling2Model, "_attention", forced_attention) + monkeypatch.setattr(mlx_model, "sparse_mlp", forced_mlp) + + batch, capacity, decode = 2, 64, 6 + generator = torch.Generator().manual_seed(3) + prompt = torch.randint( + 0, config.unpadded_vocab_size, (batch, prompt_length), generator=generator + ) + cache = ReferenceCache(config, batch, capacity) + store = DenseStore(config, batch, capacity) + torch_state = torch.zeros( + batch, + config.execution_layer_count, + 3, + config.state_width(), + dtype=torch.bfloat16, + ) + mlx_state = model.initial_state(batch) + tokens, start, worst_logits, worst_state = prompt, 0, 0.0, 0.0 + for step in range(decode + 1): + for values in records.values(): + values.clear() + cursor.update(attention=0, mlp=0) + count = tokens.shape[1] + positions = torch.arange(start, start + count)[None].expand(batch, -1) + with torch.no_grad(): + expected, _, torch_state, _ = target( + tokens, + positions, + cache, + torch_state, + positions[:, -1] + 1, + start + count, + full_logits=True, + prefill=step == 0, + ) + store.positions = mx.array(positions.numpy()) + actual, mlx_state = model( + mx.array(tokens.numpy()), store.positions, mlx_state, store, last_only=False + ) + assert cursor == { + "attention": config.execution_layer_count, + "mlp": config.execution_layer_count, + } + worst_logits = max(worst_logits, _relative(actual, expected)) + worst_state = max(worst_state, _relative(mlx_state, torch_state)) + assert (np.array(actual).argmax(-1) == expected.numpy().argmax(-1)).all(), step + start += count + tokens = expected[:, -1:].argmax(-1) + # One BF16 ULP is 2^-8 relative; GEMM accumulation order moves a few values by one. + assert errors["sources"] < 1e-2, errors + assert errors["mlp_input"] < 1e-2, errors + assert errors["attention"] < 2e-2, errors + assert errors["mlp"] < 2e-2, errors + assert worst_logits < 1e-2, worst_logits + assert worst_state < 1e-2, worst_state diff --git a/tests/test_deploy_models.py b/tests/test_deploy_models.py index d62342c8..541a1b61 100644 --- a/tests/test_deploy_models.py +++ b/tests/test_deploy_models.py @@ -101,6 +101,75 @@ def create(**overrides): ) +def test_inkling2_mlx_factory_constructs_text_runner(monkeypatch, tmp_path): + pytest.importorskip("mlx.core") + spec = get_model("inkling2-mini-mlx") + module = importlib.import_module("resin_models_mlx.inkling2") + calls = [] + monkeypatch.setattr( + module, + "Inkling2MlxRunner", + lambda *args, **kwargs: calls.append((args, kwargs)), + ) + + def create(**overrides): + options: dict[str, Any] = dict( + device="mps", + context_length=8192, + max_batch_size=4, + prefill_chunk_size=spec.prefill_chunk_size, + draft_tokens=0, + ) + return create_runner(spec, checkpoint, **(options | overrides)) + + checkpoint = tmp_path / spec.name + create() + assert calls == [ + ( + (checkpoint,), + { + "memory_utilization": spec.gpu_memory_utilization, + "max_seq_len": 8192, + "max_batch_size": 4, + "prefill_chunk_size": 8192, + }, + ) + ] + with pytest.raises(ValueError, match="use draft_tokens=0"): + create(draft_tokens=7) + with pytest.raises(ValueError, match="one Apple Silicon device"): + create(groups=object()) + + +def test_inkling2_mlx_recipe_is_text_only(tmp_path): + from tokenizers import Tokenizer + from tokenizers.models import WordLevel + + tokenizer = Tokenizer(WordLevel({"[UNK]": 0}, unk_token="[UNK]")) + tokenizer.add_special_tokens( + [ + "<|message_system|>", + "<|message_user|>", + "<|message_model|>", + "<|content_text|>", + "<|content_image|>", + "<|content_thinking|>", + "<|content_model_end_sampling|>", + "<|end_message|>", + "<|unused_200054|>", + ] + ) + tokenizer.save(str(tmp_path / "tokenizer.json")) + (tmp_path / "processor_config.json").write_text( + json.dumps({"image_processor": {"size": {"height": 8, "width": 8}}}) + ) + assert create_recipe("inkling2-mini-mlx", tmp_path).input_modalities == ["text"] + assert create_recipe("inkling2-mini", tmp_path).input_modalities == [ + "text", + "image", + ] + + @pytest.mark.parametrize( "name,expected_recipe", [("ornith-1.0-35b", "ornith"), ("qwen3.5-0.8b-mlx", "qwen3_5")], @@ -446,7 +515,9 @@ def forward(self, plan): assert second.take_result() == [len(prompt)] -@pytest.mark.parametrize("name", ["ornith-1.0-35b", "qwen3.5-0.8b-mlx"]) +@pytest.mark.parametrize( + "name", ["ornith-1.0-35b", "qwen3.5-0.8b-mlx", "inkling2-mini-mlx"] +) def test_local_presets_require_an_explicit_checkpoint(tmp_path, name): spec = get_model(name) with pytest.raises(ValueError, match="runs locally"):