Skip to content

Latest commit

 

History

History
45 lines (23 loc) · 10.3 KB

MEMORY.md

File metadata and controls

45 lines (23 loc) · 10.3 KB

LLMOS — The Memory Manager

How the working set is kept correct: what the CPU sees at each phase of a task, and how context and the KV cache are managed as one thing. A design.

Status: design, 2026-07-06.

Correctness first

Speed is worth having, but it is not the point. The point of managing memory in LLMOS is correctness: the CPU — the model — can only be as right as the things in front of it. When the working set fills past the window and the oldest tokens are silently dropped, the first casualties are the identity prompt and the task itself, and a process that has forgotten what it was asked will confidently produce the wrong answer. We have watched this happen: on the runs that saturated the window, not one succeeded. And it is not only about what falls out when the window overflows. A window that stays full of things irrelevant to the current step degrades the answer even when nothing is dropped, because the model spends its attention on stale greps and half-read files and edits the wrong line. That is the real reason to remove context: we remove what is irrelevant to get a better result, not a quicker one. Any speedup is a side effect we are not optimizing for. So memory management here is not about throughput; it is the mechanism that keeps only the right information in front of the CPU so the answer comes out right. Everything below is organized around that, and where a choice trades a little speed for a better chance at a correct answer — an extra pass, a fresh prefill, a more careful read — we take it.

The two tiers, and where this fits

LLMOS already has a design for the disk: the librarian, which decides what is worth keeping in the brain and what is worth retrieving. This document is about the tier above it — the working set, the context window the CPU actually sees on each instruction, whose physical form is the KV cache in the GPU. The librarian manages the annex; the memory manager manages the desk. A page fault between them — recall — already exists. What is missing is the desk's own discipline: today the working set is append-only. Every file read, every shell result, every step stays resident forever, and the desk simply piles up until nothing more fits. No operating system manages RAM that way.

Context and cache are one thing

Every token pushed through the model produces, per layer, one cached key and value; context and cache grow together, in pairs, exactly as the intuition says. But the pairs are chained, not independent. The cached entry at a position was computed while attending to everything before it, and its position is baked into it by the rotary embedding, so the cache behaves like a prefix, not a set. Dropping the last token is free. Pulling something out of the middle invalidates everything after it — those entries attended to what you removed, and their positions all shift — so the suffix must be recomputed. But only the suffix: everything up to the cut is still correct and stays cached, and recomputing what follows is a single parallel prefill, not a slow step-by-step decode. Managing the window is therefore the same act as managing the cache, and it comes with one rule that governs the entire design: keep the permanent things at the front and the disposable things at the back, so edits land near the tail where the suffix to recompute is short, and the stable prefix — identity, and the task — stays cached and is never recomputed at all. It also means a cut low in the window is affordable, not forbidden: it recomputes more, but it is one prefill, paid once, and it is why compaction belongs at phase boundaries rather than every step.

The structure: a segment table with a watermark

The working set is a table of segments, not a stream of tokens. A segment is a whole unit — the pinned preamble, one tool call and its result, a compacted digest — held in order, each tagged with the phase that produced it, an importance, a recency, and its span in tokens. Above the disposable segments sit the pinned ones: identity and the task, the boot ROM of the process, never evicted. The one field that ties the logical table to the physical cache is a valid-up-to watermark: the cache is trustworthy up to the earliest segment we changed, and everything past it is dirty and will be recomputed on the next pass. That watermark is the real record of what goes with what. A linked list can hold the order, but the operation a linked list makes look free — splice out any node — is the one the cache makes expensive, so the table is the honest picture: contiguous blocks, pinned first, disposable last, with a line drawn at the first dirty block.

The working set is phase-dependent

A solve is not one workload; it is a sequence of phases, each needing different things resident. Reproduce needs the task and yields a failing command. Locate needs that command and the tools to search, and yields a place — a file and a span — and a cause. Fix needs the place and the code window and yields an edit. Verify needs the reproduction and the edit and yields a verdict. The exploration that Locate needed — a dozen greps, three half-read files — is dead weight the moment Fix begins; it will never be looked at again, yet left in place it crowds the window and, worse, can mislead the model into editing the wrong thing. So the working set turns over at phase boundaries. Crossing into Fix, the manager evicts the finished phase's clutter, keeps the pinned task and the distilled diagnosis, and pages in the one code window Fix actually needs. This is where compaction happens — infrequent, batched, at a natural checkpoint — so we pay the one small prefill once and then run lean, rather than churning the cache every step.

Reseeding, not surgery

There is a simpler way to see the whole operation, and it is the one to build. You do not reach into the cache and splice anything out. At a turnover you start a fresh context — a new chat — and enter the compacted working set into it: the pinned task, the digests of the finished phases, and the few segments the next phase actually needs. The old cache is simply dropped. Because the new context is small and clean, computing its cache from scratch is a single cheap prefill, and the one part that is byte-for-byte unchanged — the pinned preamble at the very front — the engine reuses anyway. So the segment table is not something we edit token by token; it is the state we serialize into the opening of the next context. Within a phase we append and the cache grows normally; at the boundary we reseed. This is the same move a person makes when a conversation has grown long and tangled — start again with a clean summary — and it is what LLMOS already does elsewhere as a continuation note. It turns the whole memory manager into one honest question: what does the summary contain? That is a correctness question, not a cache-surgery question, and it is the right thing to be spending our attention on.

Losing nothing that correctness needs

Because correctness comes first, eviction is never deletion. An evicted segment is compacted into a short, faithful digest that stays in the window — "searched A and B; the bug is in C, lines 120–140; the edit that returns X instead of Y" — and its full form goes to the brain, one recall away. If a later phase turns out to need what was compacted, that is an ordinary page fault: recall it, or simply re-read the file window. The discipline is that the digest must preserve every fact a later phase depends on; when in doubt, keep it. A memory manager that made the window smaller by forgetting the one thing that mattered would be optimizing the wrong quantity, and under a correctness-first rule that is the cardinal sin.

What the freed budget is for

Reclaiming the window is not so the run finishes sooner; it is so the budget can be spent on being right. A working set that stays small and clean makes room for the moves that raise accuracy: decomposing the task into passes, each with a clean focused context, so Locate is not distracted by a failed edit and Fix is not buried under spent exploration; verifying a fix more than once and against more than the single reproduction the model first wrote; and, where it matters, solving a hard instance several times and keeping the answer that actually verifies rather than the first one produced. Every one of these costs inference. Under a correctness-first rule they are worth paying for, and they are only affordable if the window is not already full of finished work.

Black box now, our engine later

There are two regimes and the design spans both. Today the model runs behind llama-server (llama.cpp), which we do not reach into; we hand it a prompt and it reuses the cached prefix and recomputes the divergent tail. So evicting from the cache is, for now, a consequence of us rebuilding the prompt from the resident segments — the engine keeps the pairing for us. The segment table is what we control, and it is enough to keep the working set correct against a black box. The same abstraction, unchanged, drives real memory management the day LLMOS runs its own inference: then the segment table maps onto the actual key-value store, and a middle block can be dropped without recomputing the suffix — attention sinks plus a recent window, or heavy-hitter eviction that keeps the tokens actually attended to — which is genuine cache surgery and a real reason to eventually own the model instead of renting it. One structure, two backends; we do not rewrite the manager when we graduate.

What to build first

The smallest correct version is a working-set manager the kernel runs the way it runs the scheduler: pin the task, tag each new segment with the phase that produced it, and when a phase ends or the window crosses a watermark, compact the finished segments into faithful digests and reseed — start the next context from the pinned task, the digests, and the few segments the next phase needs. Within a phase it simply appends; at the boundary it starts clean. The first digests can be deterministic, built straight from the trace, with a re-read superseding the read it repeats; summarization on the cheap Mac model comes in only when a mechanical digest is not faithful enough. It earns its keep on the workload in front of us, and it is a general facility, not a benchmark trick: it manages any process's window, which is the thing LLMOS most needs and does not yet have.