# Speculative decoding on an M3 Max: Qwen3.5-9B draft → Qwen 27B target (MLX), vs the 35B-A3B MoE **Question.** On an M3 Max (64 GB), does a Qwen3.5-9B draft model make a 4-bit Qwen 27B decode faster in MLX? How does the speedup depend on the task and on the number of draft tokens `k`? And is a speculated dense 27B ever faster than just running Qwen3.6-35B-A3B (MoE)? ## Two findings from setup (before any GPU run) 1. **Qwen3.8-27B is not a valid target for this draft.** Its vocabulary and special tokens match Qwen3.5-9B exactly, but its pre-tokenizer regex drops `\p{M}` (Unicode combining marks). On our 2,931-token sample the token ids diverge at Devanagari text (`स्` vs `स` + `्त`). Our English chat prompts happen to tokenize the same, but the method only allows pairs with identical tokenization. So, as planned, **Qwen3.6-27B is the primary target** and Qwen3.8 is dropped (`out/compat.json`, re-checked by every run). 2. **mlx_lm's built-in speculative decoding (`--draft-model`) refuses these models.** Qwen3.5/3.6 are hybrids: 3 of every 4 layers are Gated DeltaNet (linear attention) with a recurrent `ArraysCache`. mlx_lm rolls back rejected draft tokens by trimming the cache, and it raises `ValueError: Speculative decoding requires a trimmable prompt cache` for these models. This is true in mlx_lm 0.31.3 (installed) and 0.32.2 (latest on PyPI when this was written). The run records the exact exception (`metrics.stock_mlx_lm_draft_model_works`). So `specdec.py` re-implements mlx_lm's speculative loop with one change: it restores the non-trimmable layers from snapshots. - **Draft model:** it runs one token per step, so we keep a snapshot after every step. A snapshot is just a list of references, because MLX arrays are immutable. - **Target model:** it verifies `k+1` tokens in one forward pass, so there is no intermediate state to restore. After a rejection we restore the pre-verify state and **re-run the accepted tokens**. MLX never evaluates those logits, so the lm_head is skipped. That re-forward is the extra price hybrid models pay for speculation, and every speculative number includes it. The acceptance rule is mlx_lm's: accept a draft token iff it equals the target's own greedy or sampled token, so the output distribution is the target's. `test_specdec.py` checks that greedy speculative output equals plain greedy output token for token. It uses a toy hybrid model and a numpy stand-in for `mlx.core`, and covers k = 1-6, perfect/noisy/bad drafts, and both the snapshot-restore path and the KV-trim path. ## What it measures Model pairs: - Target: Qwen3.6-27B-4bit (Qwen3.8-27B-4bit if it ever passes the tokenizer check). - Draft: Qwen3.5-9B-MLX-4bit. - Reference: Qwen3.6-35B-A3B-4bit with no draft. Prompts: 12 prompts we wrote (`prompts.py`), 4 categories × 3. **code** asks for a refactor, tests or a new method on our own `prompts/inventory.py`. **extract** turns a paragraph into JSON, a table or a status update. **explain** covers TCP slow start, B-trees and DNS. **creative** is a story, a poem and a letter. The chat template is applied with **thinking disabled** (`enable_thinking=False`). Decoding: - Exactly 256 tokens per run: EOS is masked to −inf, which enforces a minimum length. - Greedy main run, configs: baseline (no draft), k = 2, 4, 6. - Extra pass at temp 0.7 with k = 4 on code and creative. - 3 repeats, interleaved round-robin: repeat-major, prompts shuffled per repeat, config order rotated per prompt. - One warm-up generation per config, not counted. - One Python process per model with both models resident (`mlx_lm` API, wired memory limit set as mlx_lm does). Reported in `results.json` (per category and config): - Decode tok/s: median, min-max and all samples. - Speedup vs baseline. - Acceptance rate: accepted / proposed draft tokens, from the per-token `from_draft` flags. - Per-position acceptance α, used by the theory model. - TTFT, end-to-end time for 256 tokens and peak MLX memory. - Rollback re-forwards per run. - Greedy token identity vs baseline: % of runs identical, and the first differing position. - MoE tok/s and MoE / best-dense ratio. - Thermal drift: baseline speed in the last repeat vs the first. - Model load times and weight sizes. Theory check: - The draft/target cost ratio `c` comes from a forward-pass microbenchmark at the context of the code_refactor prompt (474 tokens), and also from draft-alone vs baseline decode speed. - The microbenchmark also measures the target's cost to verify S = 1..k+1 tokens and to re-forward S tokens. - The *classic* expected speedup is `(1-α^(k+1)) / ((1-α)(kc+1))`. The *hybrid-aware* version adds the measured verify and rollback costs. Both are compared with measured speedups (`tables.measured_vs_theory`). - A grid for smaller drafts (c = 0.05-0.2) is in `tables.theory_grid_classic`. ## Reproduce Requirements: Apple Silicon Mac, the four models in the HF cache (`~/.cache/huggingface/hub`), and miniconda Python 3.13 with `mlx` and `mlx-lm` installed. No network is used. ```zsh ./run.sh # full run, ≤ 40 min, writes results.json, out/results_runs.csv, out/plots/*.png ./run.sh --smoke # 10-second CPU smoke test with a synthetic backend -> results-smoke.json (fake numbers) python test_specdec.py # rollback-logic test only ``` Before a real run: plug in power, turn Low Power Mode off (High Power on, if the machine has it) and close other apps. `envinfo.py` logs the power source, the Low Power Mode setting and `pmset -g therm` before and after the run. It also logs `powermetrics` thermal/power samples if passwordless `sudo` is configured; otherwise this is noted as a caveat. What `run.sh` does: 1. Logs the environment: machine, macOS build, mlx / mlx_lm / numpy / transformers versions and the HF commit hash of every model. 2. Runs the rollback unit test. 3. Runs the tokenizer compatibility check, which picks the target. 4. Runs the dense benchmark (target + draft): stock-flag check, microbenchmark, warm-ups, then the interleaved schedule. 5. Runs the MoE reference. 6. Logs the thermal state again. 7. Runs `analyze.py`, which writes `results.json`. **Time budget.** The benchmark part is hard-capped at 38 minutes. The dense process gets everything except about 6 minutes kept for the MoE and the analysis. After the warm-ups, `bench.py` projects the schedule from measured per-run times and drops work in the spec's order until it fits: 1. The temp-0.7 pass. 2. k = 6. 3. Repeats 3 → 2. 4. k = 2. 5. Repeats 2 → 1. What was dropped is listed in `results.json` → `plan` and `caveats`. A deadline check before each run and a SIGALRM watchdog stop a process that overruns. Rows are written to disk as they finish, so analysis still works on partial data. Pinned analysis environment: pandas 3.0.6, matplotlib 3.11.2 and numpy 2.5.4. They are installed offline from `./wheels` into `.venv-analysis` with `pip --no-index`. `uv run --offline` panicked inside our sandbox, which blocks macOS proxy lookup, so the run uses a plain venv. The MLX stack (mlx 0.31.2, mlx-lm 0.31.3) is the installed conda one, and its versions are recorded at run time. ## Files | file | purpose | |---|---| | `run.sh` | end-to-end driver (zsh) | | `specdec.py` | speculative decoding loop with hybrid-cache rollback | | `bench.py` | per-model benchmark process, planner, stock-flag check, microbenchmark, `--fake`/`--dry-run` | | `compat.py` | tokenizer compatibility check, picks the target | | `prompts.py`, `prompts/inventory.py` | the 12 prompts and our code file | | `analyze.py` | results.json, results_runs.csv, plots | | `envinfo.py` | versions, hardware, power and thermal logging | | `test_specdec.py` | CPU test of the rollback logic | ## Caveats - Speculative numbers come from our loop, not stock mlx_lm, because stock mlx_lm cannot run these models. On rejection, the hybrid rollback re-runs the accepted tokens through the target. A kernel that exposes per-token DeltaNet states would avoid that cost, so these numbers are a lower bound on what hybrid-aware speculation could do. - EOS masking keeps every run at 256 tokens. Text written after a natural end of the answer can be more or less predictable than the answer itself. - The 9B draft is large, about a third of the 27B target. Small drafts (0.5-2B) would behave differently; see the theory grid. - Temp-0.7 acceptance uses mlx_lm's match rule, not rejection sampling, which would accept more. - Peak memory in the dense process includes the draft's weights even for the no-draft baseline, because both models stay resident. `weights_gb__*` gives each model's size. - The results cover one machine, one model pair and 12 prompts. Acceptance depends on the prompt, so categories are reported separately and there is no single headline average.