DEV Community

Cover image for On-Device LLM Memory Is a KV Cache Problem, Not a Weights Problem
AI Explore
AI Explore

Posted on

On-Device LLM Memory Is a KV Cache Problem, Not a Weights Problem

TL;DR — Teams size on-device language models by the weight file, then get killed by the OS when context grows. The KV cache scales with every token and is the real memory budget on a phone or edge box. Treat context length as an allocation, budget it per device tier, and test at the worst case, not the demo prompt.

Every on-device model conversation starts with the same number: how big is the file. It's a fine number for deciding whether users will tolerate the download. It is a bad number for deciding whether the app survives.

My thesis: on constrained hardware, the weights are the fixed cost and the KV cache is the variable cost. The variable cost is the one that kills you, because it depends on what users type, what you retrieve, and how long a session runs. You don't control any of those at build time.

The arithmetic nobody does in the design doc

During generation, a transformer keeps the key and value tensors for every previous token at every layer, so it doesn't recompute them. The size of that cache is simple:

2 × layers × kv_heads × head_dim × bytes_per_element × tokens

Take a hypothetical small model with 24 layers, 8 key/value heads, a head dimension of 64, and a 16-bit cache. That is 2 × 24 × 8 × 64 × 2 bytes, or 48 KiB per token. The numbers are illustrative, not any particular model's, but the shape is realistic.

  • At 2,048 tokens: roughly 96 MiB. Nobody notices.

  • At 8,192 tokens: 384 MiB. Noticeable on a low-end device.

  • At 32,768 tokens: 1.5 GiB. That is now larger than the 4-bit weights of a model with around a billion parameters.

That last line is the whole argument. Quantization shrinks the weights by a fixed factor and you ship the result. The cache grows linearly with context, and a long-context feature turns a model that fit comfortably into one that doesn't.

Why the failure mode is worse than slowness

On a server, running out of memory is an alert and a restart. On a phone or embedded device, the operating system decides your process is the one to reclaim. The user sees the app vanish or reload.

That has three nasty properties:

  • It looks like an app bug. There's no "model out of memory" error to log. Crash reports show a process termination with no stack that points at the cache.

  • It's conditional on everything else. The memory ceiling depends on what other apps are resident, which is why it passes on your test device and fails in the field.

  • It correlates with your best users. Long sessions and heavy retrieval are the engaged use cases. The crash lands on exactly the people who use the feature most.

A latency regression degrades gracefully. A memory overrun is a cliff.

Treat context as an allocation, not a feature

Server-side, a context window is a pricing and quality knob. On-device, it's a malloc. The design consequence is that context length needs an owner and a budget, like any other scarce resource.

What that looks like in practice:

  • Set a hard token ceiling per device tier. Derive it from the cache formula and the memory you can safely claim, not from the model's advertised maximum context. The advertised maximum describes what the architecture permits, not what your user's device can hold.

  • Enforce it before inference, not during. Count tokens on the assembled prompt (system text, history, retrieved chunks, tool output) and trim or summarize until it fits. Discovering the overrun mid-generation is too late.

  • Budget by component. Give the system prompt, conversation history, and retrieved context separate allowances. Otherwise the most recently added feature eats the others' share without anyone deciding that it should.

  • Pick an eviction policy on purpose. Dropping the oldest turns, summarizing them, and keeping a sliding window are different quality tradeoffs. Choose one and evaluate it; don't let truncation happen by accident.

Architecture choices that are really memory choices

If you control model selection, the cache formula tells you which architectural details matter more than parameter count.

KV head count. Grouped-query and multi-query attention share key/value heads across query heads. That cuts the kv_heads term directly. Two models with similar weight sizes can differ several-fold in per-token cache cost. Read the config, not just the model card headline.

Local or sliding-window attention. Layers that only attend to a bounded window cap their cache at the window size regardless of total context. A model that mixes these with a few global layers has a much flatter memory curve.

Cache precision. You can store the cache at lower precision than the weights' compute path. That's a separate decision from weight quantization with its own quality risks, especially on tasks that depend on exact recall from earlier in the context. Evaluate it separately.

Prefix reuse. If every request begins with the same system prompt, keeping its cache around saves compute and time-to-first-token. It also pins memory permanently. That is a trade, not a free win.

Test the worst case, on the worst device

Most on-device evals check output quality on representative prompts. That tells you nothing about the cliff. Add a separate class of test whose only job is to find the memory ceiling:

  • Run the longest context your product can legally assemble, not the average one.

  • Do it on the lowest-tier device you support, with realistic background load.

  • Measure peak resident memory across a full generation, not the model's load-time footprint.

  • Repeat across a long session to catch fragmentation and cache growth that never releases.

Then gate releases on the headroom, not just on accuracy. If peak memory sits within a thin margin of the kill threshold, you don't have a working feature. You have one that works until another app opens.

The takeaway

Small models made on-device AI feasible, but "it fits" is a claim about a snapshot. The weights fit once, at load. The cache is renegotiated on every token, and the negotiation is with an operating system that has no interest in your feature.

So size by the formula, not the file. Cap context per device tier, enforce it before inference, choose architectures for their KV footprint, and test the ugliest input on the weakest hardware. The teams that ship stable edge AI aren't the ones with the smallest model. They're the ones who know exactly how much memory a conversation costs and refuse to let it exceed the budget.

Top comments (0)