Retrieve, Then Generate: Closing the Speed Gap on a Phone

September 2026 · 13 min read

In September I installed Solair, another private, on-device AI app for iPhone, on the same iPhone 14 Pro I test Atlas on. I asked both apps similar questions. Solair started answering almost immediately, while Atlas sat there thinking. Both apps run a small language model locally on a 6 GB phone. My first guess was that the other runtime simply decoded faster, so I measured that first. The two decoders were close: Gemma 4 E2B on LiteRT-LM produced about 55 tokens per second, and Qwen 3.5 2B on MLX about 61. A 10% difference in decode speed doesn't make one app feel instant and the other one sluggish.

The difference was in what each app asked the model to do on every turn. This post is about that, which I've started calling the turn shape. It covers the two weeks it took to fix it, a regex I wrote and then deleted, and the design Atlas ships now for every model on every backend.

Atlas series

  1. Fitting a Second Brain Into 8,192 Tokens (the July original)
  2. Taming Small Models That Don't Speak Your Tool Protocol
  3. Retrieve, Then Generate: Closing the Speed Gap on a Phone
  4. Letting the Network In Without Letting the Data Out
  5. Ears and Eyes on a Phone: Voice and Vision in Atlas
  6. The Experiments I Didn't Ship
  7. Atlas, July to November

What a turn used to look like

A chat app like Solair sends your message to the model and streams back the reply in one generation. Atlas is a second brain, so most questions are about your own notes, mail and calendar, and in the summer the model fetched that context itself through tools. The prompt Atlas sent was about 1,350 tokens before you typed a word, and most of that was the JSON schemas of twelve or thirteen tools. A typical question then went through these steps:

  1. Prefill the system prompt and all those tool declarations.
  2. Let the model think, then emit a search_knowledge call.
  3. Run the search, which takes milliseconds because retrieval never touches the LLM (that's invariant #4 from the first post).
  4. Prefill the search results back into the conversation.
  5. Let the model think again, and only then start the answer you can see.

That adds up to two generations and two prefills for each visible answer, plus a token reserve set aside for the tool round, which on a 4,096-token window leaves very little room for anything else. The worst part was a step I hadn't drawn on any diagram because it wasn't supposed to happen at all.

The cost I couldn't see: backgrounding

Atlas had a setting called "Free model memory in background", on by default. When you switched apps, locked the phone or pulled down a notification, Atlas tore down the inference engine to be a good memory citizen. That sounds reasonable until you count how often a normal person backgrounds an app on iOS. In practice it happened between nearly every pair of turns. Each return to the app then paid for a cold engine rebuild and a full prefill of the system prompt, because the KV cache that held it was gone with the engine.

The KV-cache discipline from the July post (one conversation per chat, prefill only the new message) was correct, and also mostly theoretical, because the cache rarely survived long enough to be reused. Solair keeps its model resident. Once I put the two turns next to each other, the gap was easy to explain:

Three chat turn shapes compared Top: the summer turn, which starts with a cold engine rebuild, prefills the prompt with all tool schemas, thinks, calls search, prefills the results, thinks again and only then answers. Middle: retrieve-then-generate, where LLM-free retrieval runs first and one generation answers from the injected excerpts. Bottom: the gated turn that shipped, which keeps a fixed tool set so the cache stays warm, injects excerpts only when retrieval is confident, and lets capable models search when they decide to. The time to first visible token comes earliest in the bottom two lanes.
The order of phases is real, but the widths are schematic and not measured durations. The marker is the first token you actually see. Every block to its left is time you spend looking at a spinner.

The fix for that was a one-line policy change with a paragraph of justification. Every LiteRT backend is now exempt from the routine background suspend. A real memory-pressure signal from iOS still unloads the model unconditionally, because the OS outranks my latency budget. The "free memory" toggle still exists, but it now only governs MLX models, and the label in Settings says so. The policy lives in a small function, LLMBackgroundSuspendPolicy.shouldSuspendOnRoutineBackground, so it is unit-testable without building the whole engine.

Retrieve, then generate

With the model resident, the second generation was the next biggest cost, so I removed it. Atlas already had everything it needed to search without the model: hybrid BM25 and vector retrieval, a regex calendar parser, and an excerpt formatter. I made the excerpt formatter shared, so the search_knowledge tool and a new Pipeline.preRetrieve produce byte-identical output. Then the default chat turn became:

  1. Run the search before the model sees anything, which is LLM-free and takes milliseconds.
  2. Put the excerpts, together with a date line, inside the pending user message.
  3. Generate once.

The location of the excerpts in step 2 matters more than it looks. Atlas used to inject context as extra .system messages in the history. On a warm LiteRT turn the runtime already holds the earlier conversation in its KV cache, so Atlas only sends the newest message, messages.last. Anything I injected anywhere else was invisible on every warm turn. I found out later that the graph context, the self-model and the learned principles had been silently invisible that way for weeks. The pending user message is the one place every turn is guaranteed to deliver, so that's where the context rides.

The UI didn't need to change. agentQuery synthesizes the same search_knowledge events the tool used to emit, so the tool row, the sources pill, the citations and the "found nothing" row (invariant #9) all render exactly as before. The default turn carried no tools at all, which also meant no tool-round reserve in the token budget.

The quality numbers moved in a direction I didn't expect. On LFM2.5 1.2B, the abstention score (how often the model correctly says it doesn't know, instead of inventing something) rose from 0.07 to 0.79, with groundedness at 0.94 and lookup recall at 1.00. Small models are bad at deciding to search and good at reading what's in front of them. Putting the evidence in front of them made them more honest.

A regex that decided which tools to carry

Some turns still need tools: "remind me to call the plumber", "add lunch with my sister on Friday", "how did I sleep this week". So I wrote TurnIntentGate, an LLM-free regex classifier in English and Dutch, that attached only the tool subset a turn needed. A reminder request got create_reminder and list_reminders, a mail question got search_email and read_email_thread, and a plain question got nothing.

It worked, and it shipped. Twelve days later I deleted it, because of the cache key.

A warm conversation can only be reused when the inputs that shaped its KV cache haven't changed. In Atlas that's a two-field struct, ConversationCacheKey: the system prompt and the sorted list of tool names. If either changes, the cached conversation is evicted and the next turn rebuilds cold. I'd learned this lesson once already in August, when the system prompt contained today's date. That line made the key change every midnight, so any conversation you resumed the next morning rebuilt from scratch. The date moved out of the system prompt and into the per-turn preface.

The intent gate repeated the same mistake with tools. Every time a turn needed a different subset than the turn before, the key flipped and the whole conversation was prefilled again. A gate I'd written to save latency was causing cold prefills of its own.

How a changing tool set invalidates the KV cache Four chat turns in two rows. In the regex-gate row the tool list changes between turns, so the cache key changes and turns two, three and four each rebuild cold. In the fixed-set row every turn carries the same tools plus search_knowledge, the key stays the same, and turns two to four reuse the warm cache. Regex gate: tools chosen per turn key = hash(system prompt, sorted tool names) Fixed set: the same tools on every turn the model decides whether to call them
Each card is one turn of the same chat. A key change evicts the cached conversation, so the next turn prefills everything again. The labels say "cold" and "warm" as well, so the colors are never the only signal.

Second thoughts: let the model search again

Retrieve-then-generate was fast, but after living with it for a week I changed my mind about part of it. The excerpts were now in front of the model on every turn, including "what's 2 + 2?" and "thanks!". I started reading the models' hidden reasoning with the headless harness I'd built (AtlasCLI ask, which runs a full agent turn on the real index and captures the thinking), and a pattern showed up quickly:

So the always-on injection was itself a form of context bloat. I wrote a set of candidate designs and ran each of them against every LFM on both runtimes. I also gave myself one constraint up front: a single design for every model on every backend, with no per-model retrieval modes and no special case for the 4,096-token tier. I've seen what per-model branches do to a codebase over time.

The arms in the experiment were inject (always put the excerpts in), agentic (give the model the search tool and inject nothing), and gated (give the model the tool, and inject excerpts only when retrieval is confident). The bench had 16 lookup turns, 4 follow-ups, 6 questions that should be abstained on, and 10 "restraint" turns where the right move is not to search at all.

Model · runtimeArmLookupFollow-upAbstainRestraint
LFM2.5 1.2B · LiteRTinject13/162/45/61/10
LFM2.5 1.2B · LiteRTgated12/163/45/66/10
LFM2.5 1.2B · MLXagentic2/16–––
LFM2.5 1.2B · MLXgated12/164/43/69/10
LFM2.5 2.6B · LiteRTagentic16/163/45/610/10
LFM2.5 2.6B · LiteRTgated15/164/45/69/10
LFM2 8B-A1B · MLXagentic12/162/45/610/10
LFM2 8B-A1B · MLXgated13/162/46/69/10

The table shows a dilemma. Agentic retrieval is the best arm on the capable models and close to useless on the 1.2B, which simply never calls a tool on either runtime (2 lookups out of 16). Always-on injection rescues the 1.2B's lookups and ruins its restraint (1 out of 10). The gated arm is within about one turn of the best arm everywhere, so with the "one design for all" constraint in place, it won.

What ships now: the gated turn

Since 24 September, every chat turn for every model works like this:

So the 1.2B, which won't search, still gets the evidence whenever there's evidence worth reading. The 2.6B and 8B models, which search well, do so when they decide the injected excerpts aren't enough. Chit-chat gets a clean prompt. If the prefetch was unconfident on a question-shaped turn, the "found nothing" row still appears, so the UI stays honest about what was searched.

The cheapest token is the one the cache already holds, so I stopped making choices that throw the cache away.

A tool on every turn has a price on the smallest tier. On a 4,096-token window the compact system prompt is about 909 tokens and the chat tool declarations were about 1,251, with 1,024 reserved for the answer. That leaves roughly 900 tokens for the message, its excerpts and the conversation history. During the first run a full excerpt block tipped the 1.2B over the window (4,122 of 4,096 tokens) and the turn was refused. The fix sheds the weakest excerpts, always keeping at least one, before Atlas gives up on a turn. Once excerpt shedding was in place, the shipped build had zero errors (down from three overflow refusals) and zero act-tool false positives on the bench.

The trick that wasn't possible

One cost was left over: the very first turn of a brand-new chat still has to prefill the system prompt. My plan was to prefill that once during warmup into a template conversation, and then clone() it for every new chat. LiteRT-LM v0.17 has a clone call, so I built it and measured it.

It saved nothing. createConversation returns in under a millisecond with a KV-cache token count of zero, and the count stays zero until the first sendMessage, which prefills the system prompt and the message together. A clone of a fresh conversation copies an empty cache. With the full system prompt the first turn's time to first token was 0.46 seconds, against 0.08 seconds with a tiny prompt, and the template made no difference to either. The C API has no conversation-level prefill. The only raw prefill call lives one layer down, without the chat template, the tool loop or the thought channel.

I removed the template machinery and kept one test. ConversationPrefillTimingTests asserts that a new conversation's cache is empty and that a clone carries nothing. On the day upstream starts prefilling at creation, that test fails, and the failure is my signal to try again. I track it as "W3" in the file where I watch upstream changes. I like this pattern for dead ends that might come back to life: write down why the idea didn't work, and let a test notice when that reason stops being true.

The attempt did turn up one real bug. Swift tears down stored properties in declaration order, and LiteRTLMService declared its native engine before the conversation cache. A session destroyed after its engine segfaulted at deinit, so the engine is now declared last, with a comment explaining why.

Postscript: MLX went cold too

Three days after the gated turn shipped, I found the same class of bug on the other runtime. On MLX, every follow-up turn prefilled cold. The pending user message was fed to the model with its preface (date, language, excerpts), but the stored history kept the raw message, and the chat template drops past reasoning. So on the next turn the resident cache and the rebuilt prompt diverged at the previous user message, and everything after that point was prefilled again.

The fix takes a snapshot of the cache at the start of the newest user message and rolls back to it on the next turn. An earlier version checkpointed at the newest message of any kind, which was usually a tool result, and that overwrote the useful checkpoint. Follow-up time to first token on the 8B went from 1.1–1.2 seconds to 0.2–0.4 seconds. AtlasCLI ask … --then … now runs a two-turn conversation headless, and any mlx.cache.cold mark on a follow-up is treated as a bug.

What I'd tell myself in August

Measure the turn, not the model. Tokens per second on both runtimes were within 10% of each other, and the user-visible gap came from everything that happened around decoding: a teardown on app switch, a second generation, a cache key that flipped. None of those appear in a model benchmark, and all of them show up in a PerfLog trace of one real turn.

The other lesson is about the KV cache. Anything that feeds into the cache key (the system prompt, the tool list, the date) has to stay stable across turns, and anything that varies per turn belongs in the one message the runtime actually sends. Both of the bugs in this post came from putting a changing value somewhere the cache key could see it.

Solair still has the faster cold start for a brand-new chat, and I can't fix that until W3 flips. The rest of the gap is closed, and the answers got more honest on the way.

Try Atlas

Get Atlas for iPhone & iPad or get Atlas for Mac on the App Store.

References