Run this model with HF Jobs

Run balllvin/Inkling-2-Mini-MLX on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/balllvin/Inkling-2-Mini-MLX. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/balllvin/Inkling-2-Mini-MLX on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/balllvin/Inkling-2-Mini-MLX. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/balllvin/Inkling-2-Mini-MLX. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Inkling-2-Mini-MLX / README.md
balllvin's picture
Rename runtime package to inkling-mac, integrate paoloanzn/ane-native ANE runtime, tune prefill & M1-M4 fallback
771c6c5 verified
|
Raw History Blame Contribute Delete
28.7 kB
---
library_name: mlx
license: mit
pipeline_tag: text-generation
base_model: thinkingmachines/Inkling-2-Mini
base_model_relation: finetune
language:
- en
tags:
- mlx
- apple-silicon
- metal-4
- m5
- moe
- nvfp4
- mxfp8
- speculative-decoding
- inkling-2-mini
---
# inkling-mac
**Fast local inference for [`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini) on Apple Silicon (MLX + Metal 4 + Apple Neural Engine).**
*(Formerly `inkling-mlx` β€” renamed to **`inkling-mac`**; the `inkling-mlx` CLI entry point remains as a compatibility alias.)*
- **GitHub (Code & Native Metal 4 / ANE Engine):** [`github.com/Balllvin/inkling-mac`](https://github.com/Balllvin/inkling-mac)
- **Hugging Face (Model Card & Setup Mirror):** [`huggingface.co/balllvin/Inkling-2-Mini-MLX`](https://huggingface.co/balllvin/Inkling-2-Mini-MLX)
- **Base Weights (Apache 2.0):** [`huggingface.co/thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini)
- **BS Code / DeepSeek Harness Adapter:** [`huggingface.co/balllvin/BS-0.5-Mini`](https://huggingface.co/balllvin/BS-0.5-Mini) β€” optimized for [`Balllvin/BS`](https://github.com/Balllvin/BS) (`bscode`) and DeepSeek Harness PTC mode (agent teamwork on or off); pass `--adapter balllvin/BS-0.5-Mini` to `inkling-mac serve` on Apple Silicon / MLX, or pair [`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini) on non-MLX hosts.
- **Included Optimization Playbook:** [`skills/mlx-apple-silicon-inference/SKILL.md`](skills/mlx-apple-silicon-inference/SKILL.md)
- **Third-Party Attribution:** [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) β€” ANE runtime (`ane_runtime.{h,mm}`, `ane_prefill.{h,mm}`, `native_ane.py`) adapted from [`paoloanzn/ane-native`](https://github.com/paoloanzn/ane-native) (Paolo Anzani).
---
## Why `inkling-mac`?
Standard Mac runners lose massive performance on `Inkling-2-Mini` due to its **3-pass looped architecture (48 layer visits per token)**, **mixed NVFP4 + MXFP8 experts**, **unbounded GPU command buffer flushes**, **multi-GB prefill attention masks**, and **unused built-in speculative drafter**.
`inkling-mac` runs the **exact unmodified `thinkingmachines/Inkling-2-Mini` checkpoint** β€” same **3 loop passes**, same **unquantized 256k BF16 KV cache**, same **NVFP4 / MXFP8 / BF16 precision**, and the built-in **`mtp.safetensors` drafter** β€” with custom Metal 4, Apple Neural Engine (ANE), and MLX kernels behind an OpenAI-compatible HTTP/SSE API (`/v1/chat/completions`, `/v1/models`, `/health`):
- **Up to `4.6x` faster single-agent output (`120 tok/s`):** Unifies GPU draft + verify + rejection sampling into a single Metal command buffer with zero accuracy loss (`100%` byte-identical greedy output).
- **Up to `3.0x` faster for 1–4 concurrent local agents (`117.7 tok/s`):** Built specifically for real local multi-agent workflows (`B=1..4`) without cloud API costs.
- **Up to `7.7x` faster batched throughput (`277–335 tok/s`):** Scales smoothly up to `B=64` with zero swap inside 64 GB unified memory, and fixes a `49.8x` long-context batch collapse (`16k B=4`: `1.87 -> 93.12 tok/s`).
- **Nearly `2x` faster cold prompt prefill:** Cuts cold `16k` time-to-first-token from `21.4 s` to `11.14 s` (`1,464 tok/s` served, `1,739 tok/s` in-process at `4k`).
- **Bit-exact quality (`KL = 2.48e-10`):** Matches PyTorch Transformers logit-for-logit (`16/16` chat top-1, `96–98%` GSM8K-50, `2/2` needle retrieval up to `250k` tokens).
### At-a-Glance Before vs After (`Apple M5 Pro 64 GB`)
| Workload | Before (Baseline) | After (`inkling-mlx`) | Speedup |
|---|---:|---:|---:|
| **Single User (`B=1` Plain, `ctx=512`)** | `25.98 tok/s` *(stock `mlx-vlm`)* | **`48.97 tok/s`** | **`1.88x`** |
| **Single Agent w/ Tools (`B=1` MTP, `T=0.0`)** | `25.98 tok/s` *(stock `mlx-vlm`)* | **`120.19 tok/s`** | **`4.63x`** |
| **4 Concurrent Agents (`B=4` MTP, `ctx=512`)** | `39.31 tok/s` agg *(stock `mlx-vlm`)* | **`117.68 tok/s` agg** (`27.59/stream`) | **`2.99x`** |
| **32 Concurrent Streams (`B=32`, `ctx=512`)** | `36.10 tok/s` agg *(initial MLX)* | **`277.11 tok/s` agg** (`8.75/stream`) | **`7.68x`** |
| **Max Batch Clean (`B=64`, `ctx=512`)** | *(OOM / collapse)* | **`335.48 tok/s` agg** (`41.3 GB` peak, `0` swap) | β€” |
| **Cold `16k` Prompt TTFT (`B=1`)** | `20.58–21.4 s` | **`11.14 s`** (`1,464.3 tok/s`) | **`1.85x–1.92x`** |
| **Cold `16k` 4-Stream Decode (`B=4`)** | `1.87 tok/s` agg *(initial MLX)* | **`93.12 tok/s` agg** (`23.28/stream`) | **`49.8x`** |
> **Hardware target:** Built and tuned specifically for **Apple M5** (per-core Metal 4 Neural Accelerators / NAX). Measured and verified on a **MacBook Pro (`Mac17,9`) with Apple M5 Pro (18-core CPU: 6 Super + 12 Performance, 20-core GPU, Metal 4), 64 GB unified memory, macOS 26.5.1 (Xcode 26.5 SDK), MLX 0.32.4**. On M1–M4 Macs or `< macOS 26`, pass `--skip-build` for the pure MLX fallback or see [Chip Compatibility & Porting Guide](#chip-compatibility--porting-guide).
---
## Getting Started
### Prerequisites, Model to Download & RAM Requirements
#### Model Weights
`inkling-mac` downloads and runs Thinking Machines Lab's official [`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini) checkpoint unmodified (`~20.2 GB` download, **`>= 25 GB` free SSD space** recommended):
- `model-00001-of-00001.safetensors` (`~19.53 GB`, mixed NVFP4 / MXFP8 / BF16 weights)
- `mtp.safetensors` (`~0.64 GB`, built-in 3-layer speculative drafter)
- `config.json` and tokenizer files
Fetch it explicitly into `~/models/Inkling-2-Mini` via `inkling-mac download`, or pass `--model thinkingmachines/Inkling-2-Mini` directly to `inkling-mac serve` for automatic download and caching. *(Note: text generation and OpenAI tool calling are supported; the vision encoder is not wired into this MLX server.)*
#### Unified RAM Tiers
| Unified Memory | Status | Recommended Setup / Limits |
|---|---|---|
| **16–24 GB** | Not supported | Resident text + MTP runtime exceeds `20 GB` even before KV cache and prefill scratch. |
| **32 GB** | Minimum | Single-stream (`B=1`) short/medium context (`<= 16k–32k`); run with `--no-mtp --cache-limit-gb 2.0`. |
| **48 GB** | Supported | `B=1..4` with MTP up to `64k–128k`, or `B=1` up to `256k` with `--no-mtp`. |
| **64 GB** | **Recommended (Tested)** | Full `256k` BF16 KV context with MTP (`~29.6 GiB` active, `~38.6 GB` peak, `0` swap), `B=1..4` concurrent MTP agents, or up to `B=64` batched decode at `ctx=512` (`41.3 GB` peak, `0` swap). |
| **96–128 GB+** | Supported | Multiple concurrent `128k–256k` streams and larger prefix caches. |
#### Software Requirements
- **Apple M5 native path (recommended):** Apple M5 / M5 Pro / M5 Max / M5 Ultra Mac, **macOS 26+**, Xcode Command Line Tools (`xcode-select --install`), Python `3.11–3.13` (or `uv`).
- **M1–M4 / older macOS fallback (untested):** Metal 3.1+ (macOS 14+), Python `3.11–3.13`, started with `inkling-mlx serve --skip-build`.
### Agent Quickstart Prompt
Copy and paste this prompt into any coding agent on an Apple Silicon Mac:
```text
Set up and verify `inkling-mac` on this Mac:
1. Check hardware and memory (`system_profiler SPHardwareDataType`): confirm Apple Silicon with >= 32 GB unified RAM (64 GB recommended). Confirm whether this Mac has an Apple M5-family chip and macOS 26+ with Xcode Command Line Tools installed.
2. Clone `https://github.com/Balllvin/inkling-mac` (or `https://huggingface.co/balllvin/Inkling-2-Mini-MLX`) and `cd` into it.
3. Run `bash scripts/setup.sh` (or create a Python 3.11–3.13 venv, `pip install -e .`, and run `bash scripts/build_native.sh` on Apple Silicon / macOS 26+). On older M1–M4 Macs, `libinkling_decode.dylib` and `libinkling_mtp_draft.dylib` fall back gracefully to SIMT while `libinkling_ane.dylib` accelerates ANE prefill offload (`--ane-mode auto`).
4. Download `thinkingmachines/Inkling-2-Mini` from Hugging Face into `~/models/Inkling-2-Mini` using `.venv/bin/inkling-mac download --repo thinkingmachines/Inkling-2-Mini --local-dir ~/models/Inkling-2-Mini` (skip if `config.json`, `model-00001-of-00001.safetensors`, and `mtp.safetensors` are already present).
5. Run the verification suite:
- `.venv/bin/python -m unittest tests/test_engine.py tests/test_adapter.py tests/test_parser_tool_recovery.py tests/test_round2_fixes.py tests/test_ane_runtime.py -v`
- On Apple M5 / macOS 26+ after `build_native.sh` succeeds:
- `.venv/bin/python tests/test_flash_attn.py`
- `.venv/bin/python tests/test_prefill_moe.py`
- `.venv/bin/python tests/test_mtp_draft.py`
6. Start the OpenAI-compatible server on `127.0.0.1:8095` via `.venv/bin/inkling-mac serve --model ~/models/Inkling-2-Mini --host 127.0.0.1 --port 8095` (add `--skip-build` on `< macOS 26`, `--no-ane` to disable ANE, and `--no-mtp --cache-limit-gb 2.0` if unified RAM is 32 GB) and wait until `http://127.0.0.1:8095/health` reports `"ready": true`.
7. Send one test request to `http://127.0.0.1:8095/v1/chat/completions` and report the `/health` JSON, completion text, usage, and throughput metrics.
```
### Manual Setup & Serving
```bash
git clone https://github.com/Balllvin/inkling-mac.git
cd inkling-mac
# One-shot setup (Apple Silicon + macOS 26+): creates .venv, installs inkling-mac, compiles native Metal 4 + ANE .dylibs
DOWNLOAD_MODEL=1 bash scripts/setup.sh
# Or step by step
python3 -m venv .venv && source .venv/bin/activate
pip install -e .
inkling-mac build # Compiles Metal 4 + ANE dylibs (falls back automatically if NAX unavailable)
inkling-mac download --repo thinkingmachines/Inkling-2-Mini --local-dir ~/models/Inkling-2-Mini
# Serve OpenAI-compatible API (auto-downloads from HF if passed a repo ID)
inkling-mac serve --model ~/models/Inkling-2-Mini --host 127.0.0.1 --port 8095
# On 32 GB Macs: add --no-mtp --cache-limit-gb 2.0
# ANE options: --ane-mode auto|force|off or --no-ane (default auto: GPU NAX on M5, ANE offload on M1-M4)
```
Example request:
```bash
curl -s http://127.0.0.1:8095/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "inkling-2-mini",
"messages": [{"role": "user", "content": "Write an O(n) Fibonacci helper in Python."}],
"max_tokens": 256,
"temperature": 0.0
}'
```
---
## Verified Benchmarks (Before vs After on Apple M5 Pro 64 GB)
All numbers below were measured on a **MacBook Pro (`Mac17,9`, Apple M5 Pro 20-core GPU, 64 GB RAM, macOS 26.5.1, MLX 0.32.4, AC power)** over the live HTTP server unless noted otherwise. Hardware ceilings measured on this machine:
- **Sustained DRAM Read Bandwidth:** **`282.6 GB/s`** (theoretical `B=1` plain ceilings: `50.5 tok/s` @ `512`, `48.8` @ `4k`, `45.6` @ `16k`, `20.4` @ `250k`)
- **Peak BF16 Compute:** **`29.38 TFLOP/s`** (theoretical prefill ceilings: `3,210 tok/s` @ `<= 4k`, `3,060 tok/s` @ `16k`)
> *Note on host load:* Rows labeled `(thermalState=1)` were measured while the machine was also running unrelated background CPU/GPU work (sustained DRAM bandwidth was `140–195 GB/s` instead of `282.6 GB/s` idle), so idle speeds are equal or higher.
### 1. Interactive & Low-Concurrency Local Agents (`B = 1..4`, `ctx=512`, Cold Prefill)
| Scenario | Before (Baseline) | `inkling-mlx` | Speedup | % Plain BW Ceiling |
|---|---|---|---:|---:|
| **`B=1` Plain Decode** (`T=0.0`) | `25.98 tok/s`, `841 ms` TTFT *(stock `mlx-vlm 0.8.0`)* | **`48.97 tok/s`**, `576 ms` TTFT | **`1.88x`** | **`97.0%`** |
| **`B=1` MTP Tool Calling** (`T=0.0`) | `25.98 tok/s` *(stock `mlx-vlm 0.8.0`)* | **`120.19 tok/s`** (`acc=6.67`) | **`4.63x`** | **`236.4%`** |
| **`B=1` MTP Code Refactor** (`T=0.0`) | `25.98 tok/s` *(stock `mlx-vlm 0.8.0`)* | **`86.86 tok/s`** | **`3.34x`** | **`170.3%`** |
| **`B=1` MTP 6-Prompt Median** (`T=0.0`) | `25.98 tok/s` *(stock `mlx-vlm 0.8.0`)* | **`66.79 tok/s`** | **`2.57x`** | **`130.5%`** |
| **`B=1` MTP Sampled** (`T=0.7`, `thermalState=1`) | β€” | **`50.05 tok/s`** med (**`97.91/s`** tool) | β€” | **`97.8%–192.6%`** |
| **`B=2` Plain Batched** (`T=0.0`) | `35.73 tok/s` agg (`18.75/stream`, `mlx-vlm`) | **`64.75 tok/s` agg** (`32.38/stream`) | **`1.81x`** | **`85.1%`** |
| **`B=2` Unified MTP** (`T=0.0`, `thermalState=1`) | `35.73 tok/s` agg *(stock `mlx-vlm 0.8.0`)* | **`94.98 tok/s` agg** (`47.49/stream`) | **`2.66x`** | **`122.7%`** |
| **`B=2` Unified MTP Sampled** (`T=0.7`, `thermalState=1`) | β€” | **`91.69 tok/s` agg** (`45.84/stream`) | β€” | **`118.4%`** |
| **`B=4` Plain Batched** (`T=0.0`) | `39.31 tok/s` agg (`14.48/stream`, `mlx-vlm`) | **`107.06 tok/s` agg** (`26.77/stream`) | **`2.72x`** | **`102.0%`** |
| **`B=4` Unified MTP** (`T=0.0`, `thermalState=1`) | `39.31 tok/s` agg *(stock `mlx-vlm 0.8.0`)* | **`117.68 tok/s` agg** (`27.59/stream`) | **`2.99x`** | **`108.9%`** |
| **`B=4` Unified MTP Sampled** (`T=0.7`, `thermalState=1`) | β€” | **`101.73 tok/s` agg** (`21.91/stream`) | β€” | **`81.1%`** |
### 2. High-Concurrency Batched Throughput (`B = 8..64`, Cold Prefill)
| Batch & Context | Before (Baseline) | `inkling-mlx` | Speedup | Notes / Memory |
|---|---|---|---:|---|
| **`B=8`, `ctx=512`** | `44.70 tok/s` agg (`10.13/s`), `6.55 s` TTFT *(stock `mlx-vlm`)* | **`160.19 tok/s`** (`20.03/stream`), `3.10 s` TTFT | **`3.58x`** | `115.9%` BW ceil |
| **`B=16`, `ctx=512`** | `35.11 tok/s` agg (`3.40/s`), `10.23 s` TTFT *(initial MLX engine)* | **`218.33 tok/s`** (`13.86/stream`), `6.24 s` TTFT | **`6.22x`** | `117.2%` BW ceil |
| **`B=32`, `ctx=512`** | `36.10 tok/s` agg (`1.83/s`), `18.25 s` TTFT *(initial MLX engine)* | **`277.11 tok/s`** (`8.75/stream`), `12.28 s` TTFT | **`7.68x`** | `100.1%` BW ceil |
| **`B=48`, `ctx=512`** | β€” | **`308.17 tok/s`** (`6.48/stream`) | β€” | `thermalState=1`, `0` swap |
| **`B=64`, `ctx=512`** | *(OOM / collapse)* | **`335.48 tok/s`** (`5.28/stream`) | β€” | `41.3 GB` peak, `0` swap |
| **`B=32`, `ctx=4,096`** | *(collapse)* | **`235.80 tok/s`** (`7.49/stream`) | β€” | `101.8%` ceil, `41.3 GB` peak, `0` swap |
### 3. Long Context (`4k`, `16k`, `250k`) & Cold Prefill / TTFT
| Condition | Before (Baseline) | `inkling-mlx` | Speedup | % Hardware Ceiling |
|---|---|---|---:|---:|
| **Cold `4k` `B=1` Decode / TTFT** | `23.48 tok/s` / `5.44 s` (`756/s`, `mlx-vlm`) | **`48.28 tok/s`** / **`2.98 s`** (`1,381/s` served; `1,739/s` in-proc) | **`2.06x` dec / `1.83x` TTFT** | `99.0%` dec / `45.1%–54.2%` prefill |
| **Cold `4k` `B=4` Decode / TTFT** | `10.23 tok/s` / `26.09 s` *(stock `mlx-vlm`)* | **`105.94 tok/s`** (`26.50/stream`) / **`12.52 s`** | **`10.36x` dec / `2.08x` TTFT** | `108.4%` dec / `43.0%` prefill |
| **Cold `4k` `B=8` Decode / TTFT** | `10.04 tok/s` / `48.61 s` *(stock `mlx-vlm`)* | **`139.91 tok/s`** (`17.49/stream`) / **`22.38 s`** (`1,471.5/s`) | **`13.94x` dec / `2.17x` TTFT** | `111.1%` dec / `48.1%` prefill |
| **Cold `16k` `B=1` Decode / TTFT** | `24.76 tok/s` / `20.58–21.4 s` (`762–792/s`) | **`42.69 tok/s`** / **`11.14 s`** (`1,464.3/s`, `thermalState=1`) | **`1.72x` dec / `1.85x–1.92x` TTFT** | `93.6%` dec / `47.9%` prefill |
| **Cold `16k` `B=4` Decode** | `1.87 tok/s` agg (`1.57/s`, *initial MLX engine*) | **`93.12 tok/s` agg** (`23.28/stream`) | **`49.8x`** | `108.4%` BW ceil |
| **`250k` Context (`250,102` tok, `B=1`)** | *(untested / OOM)* | **`19.79 tok/s`** (`29.74 GB` active / `38.64 GB` peak) | β€” | `97.1%` BW ceil (`2/2` needle PASS) |
### 4. End-to-End Multi-Turn Agentic Coding Suite (`20` Real Tool-Using Tasks)
| Engine & Concurrency | Tasks Passed | Median Task Wall | Total Suite Wall | Throughput | Speedup |
|---|---:|---:|---:|---:|---:|
| **Initial MLX Engine (`c=4`)** | `18/20` (`90%`) | `171.40 s` | `1,053.6 s` | `1.14 tasks/min` | `1.0x` |
| **`inkling-mlx` (`c=1` w/ MTP, `5.33` avg acc)** | **`19/20` (`95%`)** | **`34.40 s`** | `979.4 s` | `1.23 tasks/min` | **`4.98x`** / task |
| **`inkling-mlx` (`c=4`)** | **`20/20` (`100%`)** | **`111.64 s`** | **`672.3 s`** | **`1.78 tasks/min`** | **`1.57x`** total |
| **`inkling-mlx` (`c=8`)** | **`19/20` (`95%`)** | `170.26 s` | **`614.6 s`** | **`1.95 tasks/min`** | **`1.71x`** total |
### 5. Quality Verification & Official Upstream Model Benchmarks
Because `inkling-mlx` keeps all released weights (`NVFP4` / `MXFP8` / `BF16`), all `3` loop passes (`48` layer visits), and full `BF16` KV cache precision untouched:
- **Logit & Speculative Equivalence:** `16/16` chat top-1 agreement (`mean KL = 2.48e-10` vs PyTorch Transformers MPS reference); `100%` byte-identical single-stream greedy speculative parity + lossless `T=0.7` rejection sampling; `4/4` decode-only `B=2` SIMT exact parity and `B=4` batched prefill `4/4` top-1 (`KL <= 2.88e-10`).
- **Downstream Verification on M5 Pro:** GSM8K-50 **`48–49 / 50` (`96–98%`)**; tool-call parser + live HTTP **`20/20 + 6/6`**; **`131,014`-tok and `249,926`-tok needle-in-a-haystack retrieval `2/2 PASS`** (`-96 MB` swap delta).
- **Official Thinking Machines Lab Scores (`thinkingmachines/Inkling-2-Mini`):** `26.4B` total / `5.4B` effective active (`5/26B`): **SWEBench Verified `79.2%`**, **SWEBench Pro v2 `77.9%`**, **Vibe Code Bench v1.1 `77.9%`**, **SWEBench Multilingual `73.7%`**, **Terminal Bench v2.1 `71.6%`**, **DeepSearchQA `85.3%`**, **MCP Atlas `82.7%`**, **BrowseComp `79.0%`**, **ARC-AGI v1 / v2 `84.5% / 49.3%`**, **GraphWalks BFS 256K `69.7%`**, **LongBench v2 `66.9%`**. *(See [`balllvin/Inkling-2-Mini-MLX`](https://huggingface.co/balllvin/Inkling-2-Mini-MLX) for the complete official table.)*
---
## Deep Technical Details: How the Optimizations Work
Stock MLX hits four bottlenecks on `Inkling-2-Mini`: ~10 GPU command-buffer flushes per token (`max_ops_per_cb = 50`), redundant expert loads / `4.3x` `SwitchGLU` sorting cliffs across batch sizes, repeated `lm_head` reads at batching, and multi-GB attention masks + unbatched conv/norm dispatches during prefill. `inkling-mac` solves each stage without sacrificing numerical fidelity:
1. **Single-Command-Buffer Native Metal 4 Decode (`src/inkling_mac/native/decode_runner.mm`)**:
- Executes all `48` layer visits (embedding, RMSNorm, attention/MLP depth residuals, message gates, packed QKV/gate, causal `ShortConv`, chronological `ring_idx` split-K GQA, FP32 MoE routing, NVFP4/MXFP8 experts, `lm_head`, and greedy `head_argmax`) inside **one `MTLCommandBuffer`** (`MTLDispatchTypeSerial`) via zero-copy `16 KB` page-aligned `MTLBuffer` wrappers.
- Eliminates `~5–8 ms` per step of Python graph-building and command-buffer flush latency.
2. **Unified `B=1..4` GPU-Accept MTP Speculative Decoding (`decode_runner.mm` + `mtp_draft_runner.mm`)**:
- Runs the built-in 3-layer DSpark + folded FP64 `MarkovHead` drafter (`mtp.safetensors`, `636 MB`) in a single native Metal CB, then verifies `sum(K_i + 1) <= 32` draft tokens across `1..4` unmerged concurrent streams in a single target verify CB β€” running greedy or exact Leviathan rejection sampling on the GPU, committing/rolling back target KV + draft KV + `ShortConv` states, and capturing target hidden states with **zero intermediate CPU waits**.
- Automatically triggers Metal 4 Neural Accelerator (NAX) batched kernels at `M >= 9`, caps adaptive `K <= 5` for `B >= 3` to bound verification tile cost, uses an adaptive cooldown burst (`ema_acc < 1.65`) when speculation efficiency dips on `B=1`, and seamlessly transitions to `BatchKVCache` continuous batching when `B >= 5`.
3. **Regime-Specialized Quantized MoE Kernels (`src/inkling_mac/moe_kernels.py` & `native/prefill_moe_nax.mm`)**:
- **`M = 1..2`**: Direct 1-expert-per-threadgroup kernel (`moe_m1_experts`) with inline `dot8_nvfp4` (`97–99%` DRAM bandwidth).
- **`M = 3..112`**: Zero-spill compact `(tile_expert, tile_t0)` tile-table grouped kernel (`moe_grouped_tiles`) using `#pragma unroll` scalar accumulators (removing LLVM stack spills), vectorized `uint4` loads, and a `256`-entry `half2` E2M1 LUT (`72–89%` DRAM BW, `0.00e+00` batch invariance across `M`, reads `lm_head` only once per step).
- **`M >= 128`**: Metal 4.0 NAX (`mpp::tensor_ops::matmul2d`) double-buffered grouped MoE with GPU radix bucketing, indirect dispatch, and a fused 64-channel 128B-aligned combine+residual dispatch (`21.9–27.1 TFLOP/s`).
4. **Metal 4.0 NAX Zero-Mask FlashAttention (`src/inkling_mac/native/flash_attn_nax.mm`)**:
- Computes causal bounds, sliding window (`w=1024`), and ragged per-sequence `key_start` arithmetically inside tiles, avoiding `107 GB` of dense mask traffic at `16k` context and scaling cleanly to `256k`.
- Computes hardware NAX Toeplitz relative attention bias (`16x32x16`) and exact FP32 query-dependent sinks directly in online softmax (`3.6x` faster SWA, `2.5x` faster `16k` global).
5. **`MTLMathModeSafe` Occupancy & Exact Numerical Parity**:
- Compiling decode/MoE/MTP compute pipelines with `MTLMathModeSafe` disables floating-point reassociation on Apple M5 (`applegpu_g17s`), cutting live register pressure and boosting SIMD occupancy (`11–29%` speedup) while preserving `0.00e+00` BF16 bit-exactness.
6. **Memory, Prefix Sharing & macOS VM Safety (`src/inkling_mac/engine.py`, `native_decode.py`, `native_mtp.py`)**:
- Shares long system-prompt prefixes (`>= 128` tokens) across concurrent burst arrivals (`~93%` cache hit rate on multi-turn tool trajectories), pre-allocates `GrowingKVCache` cleanly with `--cache-limit-gb 4.0`, checks `PrefixCache` byte limits **before** cloning `> 8 GB` `256k` KV caches (`-12.5 GB` peak spike eliminated), never caches VA-keyed mutable `MTLBuffer` wrappers across MLX frees, and validates object `is` identity alongside `id()` to defeat CPython LIFO freelist aliasing.
---
## Model Size, Memory Budget & Context Scaling
### Exact Checkpoint Weight Footprint (`thinkingmachines/Inkling-2-Mini`)
| Component | Bytes | GiB | Precision / Notes |
|---|---:|---:|---|
| Routed experts (layers 0–19) | `11,466,199,200` | `10.679` | NVFP4 (E2M1 + E4M3 `[1,16]` scale + FP32 `amax`) |
| Routed experts (layers 20–23) | `4,204,265,472` | `3.916` | MXFP8 (F8_E4M3 + UE8M0 `[1,32]` scale) |
| Attention projections & norms (layers 0–23) | `1,307,510,784` | `1.218` | BF16 (`q/k/v/r/o/gate_proj`, `sconv`, `rel_proj`, norms) |
| Token embeddings (`[201024, 2304]`) | `926,318,592` | `0.863` | BF16 |
| LM head (`[201024, 2304]`) | `926,318,592` | `0.863` | BF16 (accumulated in FP32 without storing FP32 copy) |
| Loop controllers (layers 6–17) | `42,467,328` | `0.040` | BF16 message gates (`down`, `forget`, `gain`) |
| Routers, depth residuals & norms | `16,278,528` | `0.015` | BF16 + FP32 |
| **Text LLM Resident Total** | **`18,889,358,496`** | **`17.592`** | Main file `model-00001-of-00001.safetensors` (`19.53 GB` on disk incl. vision) |
| **MTP Drafter (`mtp.safetensors`)** | **`635,795,744`** | **`0.592`** | BF16 3-layer DSpark + folded `MarkovHead` (`+96 MiB` folded) |
| **Total Text + MTP Resident** | **`19,525,154,240`** | **`18.184`** | **`~20.4 GB`** MLX active after warmup (excl. eager vision) |
### KV Cache & Bandwidth Scaling Across Context Lengths (`48` Visits, `3` Loop Passes)
Per-stream BF16 KV & state memory (`n_kv = 8`, `head_dim = 128`, `2` bytes K + `2` bytes V = `4,096 B/tok/visit`):
- **40 sliding-window visits** (`window = 1,024`): capped at **`160 MiB` (`0.156 GiB`)** per stream (`min(ctx, 1024) * 163,840 B`).
- **8 full-attention visits**: grows linearly at **`32 KiB/tok` (`32,768 B/tok`)** (`1 GiB` per `32,768` tokens).
- **ShortConv states**: `~3.8 MiB` per stream; **MTP Draft KV (`B <= 4`)**: `1` global layer (`4,096 B/tok` = `1.00 GiB` at `256k`) + `8 MiB` local layers.
Total DRAM read per plain `B=1` decode step = **`5.493 GB` active weights + KV bytes read**:
| Context (`ctx`) | KV / Stream | Total Resident (`B=1` w/ MTP) | 4-Stream KV (`B=4`) | Max Clean Streams (`<= 51.8 GiB` GPU WS) | `B=1` BW Read / Step | Theoretical `B=1` Plain Ceiling (`@ 282.6 GB/s`) |
|---:|---:|---:|---:|---:|---:|---:|
| **`512`** | `0.092 GiB` | `~20.5 GiB` | `0.37 GiB` | `64+` (max-batch / scratch limited) | `5.59 GB` | `50.5 tok/s` |
| **`4,096`** | `0.281 GiB` | `~20.7 GiB` | `1.13 GiB` | `64+` (`32` verified) | `5.79 GB` | `48.8 tok/s` |
| **`16,384`** | `0.656 GiB` | `~21.1 GiB` | `2.63 GiB` | `~39` | `6.20 GB` | `45.6 tok/s` |
| **`32,768`** | `1.156 GiB` | `~21.7 GiB` | `4.63 GiB` | `~22` | `6.74 GB` | `41.9 tok/s` |
| **`65,536`** | `2.156 GiB` | `~22.8 GiB` | `8.63 GiB` | `~11` | `7.81 GB` | `36.2 tok/s` |
| **`131,072` (128k)** | `4.156 GiB` | `~25.1 GiB` | `16.63 GiB` | `~6` | `9.96 GB` | `28.4 tok/s` |
| **`262,144` (256k)** | `8.156 GiB` | `~29.6 GiB` | `32.63 GiB` | `3` (plain, w/ `4 GB` cache) | `14.25 GB` | `19.8 tok/s` |
*Uses `--cache-limit-gb 4.0` + `~1.5–2.0 GiB` prefill scratch inside M5 Pro's `51.84 GiB` (`55.66 GB`) recommended GPU working set.*
---
## Chip Compatibility, ANE Integration & M1–M4 Support
`inkling-mac` targets all **Apple Silicon Macs** (`M1` through `M5`):
| Subsystem | Apple M5 (`Apple10`, macOS 26+) | Apple M1 / M2 / M3 / M4 (`Apple7`–`Apple9`) | Notes |
|---|---|---|---|
| **ANE Runtime & Prefill Offload** (`native/ane_runtime.{h,mm}`, `ane_prefill.{h,mm}`) | Hardware-verified (`2` ANE cores, `24/24` sessions) | Available on all Apple Silicon Macs (`--ane-mode auto`) | Adapted from [`paoloanzn/ane-native`](https://github.com/paoloanzn/ane-native); zero-copy `IOSurface` <-> `MTLBuffer`. `auto` stays GPU-only on M5 NAX and enables ANE `o_proj` offload on non-NAX Macs (`--ane-mode force` enables it on M5). |
| **Native 1-CB Decode & MTP** (`native/decode_runner.mm`, `native/mtp_draft_runner.mm`) | Compiles & runs (`B=1..4` MTP + batched) | Supported with SIMT fallback | `decode_runner.mm` makes `lib_nax` optional and falls back to SIMT at `M >= 9`; `mtp_draft_runner.mm` targets `MTLLanguageVersion3_2` (SIMT). |
| **Metal 4.0 NAX FlashAttention & Prefill MoE** (`flash_attn_nax.mm`, `prefill_moe_nax.mm`) | Native 4x–10x speedup (`prefill_chunk=1024` default) | Pure MLX + Metal 3.1 SIMT fallback | `flash_attn_nax` / `prefill_moe_nax` gracefully fall back to `kernels.py` / `moe_kernels.py` on non-NAX hardware. |
| **NVIDIA CUDA / AMD ROCm / Intel / CPU-only** | β€” | Not supported | Depends on Apple Unified Memory, Metal, CoreML/ANE, and `mlx`. |
### Latest `inkling-mac` Interleaved A/B Highlights (`Apple M5 Pro 64 GB`)
- **Prefill Chunk Tuning (`prefill_chunk=1024` default vs `512` / `8192`)**:
- `S=4,096`: `3,768.9 ms` (`1,086.8 tok/s`) @ `chunk=512` -> **`3,217.8 ms` (`1,272.9 tok/s`, `+17.1%`)** @ `chunk=1024`
- `S=16,384` (vs old `serve.py` `8192` default): `34,529.9 ms` (`474.5 tok/s`, `33.02 GB`) @ `8192` -> **`20,598.7 ms` (`795.4 tok/s`, `20.25 GB`, `1.68x` faster & `-12.77 GB` peak RAM)** @ `1024` (`thermalState=1`)
- **Logit & ANE Parity**:
- Baseline vs `inkling-mac`: **`KL = 3.600e-12`**, greedy token match (`68014 == 68014`), `max_top_diff = 1.717e-05`
- GPU vs GPU+ANE (`S=1024`, `--ane-mode force`): **`KL = 3.784e-04`**, greedy token match (`152743 == 152743`)
- **Engine Decode (`thermalState=1`, `prefill_chunk=1024`)**: `B=1` MTP **`65.68 tok/s`** (`mtp_mean_acc=4.5`) vs `B=1` plain `31.45 tok/s`; `B=16` plain **`162.40 tok/s`** sum (`140.16` wall agg); `B=32` plain **`247.04 tok/s`** sum (`171.85` wall agg).
---
## Included MLX Optimization Skill, Attribution, Testing & License
- **Skill:** [`skills/mlx-apple-silicon-inference/SKILL.md`](skills/mlx-apple-silicon-inference/SKILL.md) β€” reusable Apple Silicon MLX and Metal 4 optimization playbook.
- **Third-Party Attribution:** ANE private runtime, MIL compilation, `IOSurface` zero-copy sharing, and dynamic power-of-two scaling in [`src/inkling_mac/native/ane_runtime.{h,mm}`](src/inkling_mac/native/ane_runtime.mm), [`ane_prefill.{h,mm}`](src/inkling_mac/native/ane_prefill.mm), and [`src/inkling_mac/native_ane.py`](src/inkling_mac/native_ane.py) are adapted from [`https://github.com/paoloanzn/ane-native`](https://github.com/paoloanzn/ane-native) (Paolo Anzani; see [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md)).
- **Testing:**
```bash
PYTHONPATH=src:. .venv/bin/python -m unittest tests/test_engine.py tests/test_adapter.py tests/test_parser_tool_recovery.py tests/test_round2_fixes.py tests/test_ane_runtime.py -q
PYTHONPATH=src .venv/bin/python tests/test_flash_attn.py
PYTHONPATH=src .venv/bin/python tests/test_prefill_moe.py
PYTHONPATH=src .venv/bin/python tests/test_mtp_draft.py
```
- **License:** Engine code is MIT ([`LICENSE`](LICENSE)). Upstream [`thinkingmachines/Inkling-2-Mini`](https://huggingface.co/thinkingmachines/Inkling-2-Mini) weights remain licensed under **Apache 2.0** by Thinking Machines Lab, Inc.