# Reusing the prompt cache in MLX: TTFT for long system prompts on an M3 Max How much time to first token (TTFT) goes away when an agent's long, fixed system prompt (instructions plus tool schemas) is served from a reused prompt cache instead of being prefilled on every turn? The benchmark compares **Qwen3.6-35B-A3B 4-bit** (hybrid MoE: linear-attention state plus attention) with **Gemma 3 12B 4-bit** (dense, sliding-window attention) at 2k, 8k and 16k token prefixes. Optionally it also runs 32k for Qwen. ## What is measured | path | what the clock includes | |---|---| | `cold` | `stream_generate` on the full prompt with a fresh cache | | `mem` | `copy.deepcopy` of a prefilled `make_prompt_cache`, plus the suffix prefill (~25–33 tokens) | | `disk_warm` | `load_prompt_cache` of a `.safetensors` file already in the page cache, plus the suffix | | `disk_cold` | the same, but loaded from a fresh copy written with `F_NOCACHE`. `mincore()` confirms 0% residency before the load, so no `sudo purge` is needed | | `server` | `mlx_lm.server` with default settings, 10 streaming chat requests sharing the system prompt; client-side TTFT, request 1 vs requests 2–10, plus the server's `cached_tokens` | For each cell (model × prefix) the benchmark also records: - one-time cache build time - cache file size and in-memory size - whether the cache is trimmable - deep-copy time - cold and warm load times - peak unified memory (absolute, and above the run's starting point) - cold prefill throughput Correctness checks: - 64-token greedy outputs of the `mem` and `disk_cold` paths are compared with the cold run of the same question: exact-match % and first divergence index. - The first token of every run is compared with the cold run. - Server text is compared with the cold run's greedy text. ### Prompts `prompts.py` generates a seeded, synthetic agent system prompt: rules plus made-up JSON tool schemas, roughly 18 tools at 2k and 155–165 tools at 16k. It contains no personal or third-party data. The tool count is fitted per model with that model's own tokenizer and chat template. The cached prefix is the longest common token prefix over all 10 rendered prompts, checked token by token. Rendering uses the same `apply_chat_template` call as `mlx_lm.server`, with `enable_thinking=false`. Each prefix length starts with a different header and seed, so the server cannot reuse one length's cache for another. ### Repeats and ordering - **Cached paths:** 5 questions × 5 repeats per cell. For disk, that is 5 cold-file loads and 20 warm-file loads. - **Cold baseline:** 5 runs per cell, one per question, spread across the 5 repeats. This was capped to fit the 40-minute budget. - **Ordering:** conditions are interleaved round-robin within each (repeat, question) slot, not run in blocks, and every record has a timestamp. - **Warm-up:** one warm-up generation per model, not counted. ## Reproduce Requires an Apple Silicon Mac and both models already in the Hugging Face cache (`mlx-community/Qwen3.6-35B-A3B-4bit`, `mlx-community/gemma-3-12b-it-4bit`). The run needs no network. ```zsh ./run.sh --dry-run # builds/validates prompts with the tokenizers only (no GPU) ./run.sh # full run, ~20–30 min; writes raw/*.jsonl and results.json python summarize.py --raw raw --out results.json # re-summarize raw data ``` `run.sh` uses `/opt/homebrew/Caskroom/miniconda/base/bin/python` and does the following: 1. Records the environment to `raw/env.json`. 2. Runs `bench.py` and then the `mlx_lm.server` client (`server_bench.py`) for Qwen, then the same for Gemma. The server is started and stopped inside `run.sh` on port 8765 (override with `PORT`). 3. Runs the optional Qwen 32k pass if at least ~12 minutes of budget remain. 4. Runs `summarize.py`. Each bench gets a deadline: if the machine is slower than expected, the bench stops starting new repeats and the partial data is still summarized (this is noted in `caveats`). Cache files go to `caches/` and are deleted at the end (set `KEEP_CACHES=1` to keep them). Before running: close other apps, plug in AC power, and keep the same power mode. ## Pinned software (from the machine used) Python 3.13.5, mlx 0.31.2 (mlx-metal 0.31.2), mlx-lm 0.31.3, numpy 2.4.2, httpx 0.28.1, transformers 5.12.1, tokenizers 0.22.2. Models are pinned by their snapshot hashes in the HF cache: Qwen `38740b84…`, Gemma `86cc6a8d…`. `results.json → environment` records the versions actually used. Hardware: Apple M3 Max (Mac15,9, 16-core CPU), 64 GB unified memory, macOS 27.0.1 (26A434). ## Output `results.json` has these top-level keys: - `question` - `environment` - `runs` - `metrics` - `observations` - `caveats` Metric names follow `..[.]`, for example `ttft_ms.qwen36_35b_a3b.16384.mem` or `speedup_x.gemma3_12b.16384.disk_cold`. Each metric holds the median, the unit, all samples, and a note with n and the min–max spread. Raw per-run JSONL, including generated token IDs, is in `raw/`. ## Caveats - **Cold-disk loads:** these use `F_NOCACHE` copies, not a full `purge`. Residency is measured with `mincore()` and reported per cell. - **Absolute peak memory** includes the harness's own in-memory prefix caches for all lengths. Use `peak_mem_over_start_gb` for the cost of one run. - **Server results** are mlx_lm.server's default behaviour (LRU prompt cache, one series per length), not a ceiling. Its cache behaviour depends on the mlx-lm version. - **Gemma's cache is also non-trimmable:** `RotatingKVCache` becomes non-trimmable once the prefix passes the 1024-token window, so both models are forked by deep copy. Trimmability is reported per cell (`cache_trimmable`). - **Different models, not a speed contest:** the two models differ in size and architecture. Compare how much caching helps each one, not which model is faster. - **Single session:** the data comes from one machine in one session, so thermal state and background load can shift absolute numbers. Timestamps in `raw/` make drift visible.