New Tool Radar

AI Concepts

How to Cap MLX’s KV Cache for Long Generations

Set --max-kv-size on an mlx-lm generation so a long prompt or long reply fits in the memory you have, at a known quality cost.

Schematic diagram with four steps: pick a max KV size, run the generation with --max-kv-size, check the answer still uses the early prompt, then adjust the size to fit memory and quality.

Long prompts and long generations grow the key-value cache, and on a Mac the cache eats the same unified memory the model uses. mlx-lm has a rotating fixed-size KV cache: --max-kv-size n caps it, so a long generation fits in the memory you have.

Set the max KV size on the generate command

Add --max-kv-size to the generate command with the size you can afford: smaller values like 512 use very little RAM but result in worse quality, while larger values like 4096 or higher use more RAM but keep better quality. The cache rotates, so the oldest entries leave as new ones arrive — that is the trade, not a bug.

mlx_lm.generate --model mlx-community/Llama-3.2-3B-Instruct-4bit \
  --prompt "Summarize this long document..." --max-kv-size 4096

A small KV size is a quality setting, not just a memory setting: when the cache rotates, the model forgets the earliest part of the prompt. For a long document, 4096 or higher is the sane starting point; drop to 512 only when the machine forces you to.

Try it: four checks

Check What you should see If you do not see it
Flag accepted The generate command runs with –max-kv-size Check the flag spelling
Generation fits A long generation finishes without a memory error Lower the size if it does not
Quality at 4096 The answer still uses the early prompt Raise the size if it forgets
Quality at 512 The answer degrades as documented That is the expected trade

Expected result. We checked the mlx-lm README, which documents the rotating fixed-size KV cache, the –max-kv-size argument, and the 512 versus 4096 quality trade. We did not run a generation on this machine.

Limits

This guide covers the KV cache cap only. The right size depends on the model and the prompt length. We did not test any setting ourselves.

Sources

See all