Lecture 3. Memory, context and search
The question we will answer today
Five kinds of memory and one core rule
| Kind | What it stores | Lifetime | Written by | How it is read |
|---|---|---|---|---|
| Parameters | Knowledge from training | Until next model | Training | Used on every token |
| Context & KV cache | This request’s tokens | One request | App and model | Read by attention |
| Prompt cache | Computed prompt prefix | 5–60 minutes | Server | Reused on matching prefix |
| Document index | Document chunks & vectors | Until rebuilt | Indexing job | Searched, copied in |
| Memory store | Notes from past chats | Months | Model, app, user | Loaded or searched |
Only parameters and context compute the answer—everything else must be copied in.
| In a computer | In an LLM system | Role |
|---|---|---|
| CPU cache | KV cache, prompt cache | Avoids recomputing work that was just done |
| RAM | Context window | Fast working memory, but limited and cleared after use |
| Disk | Indexes, memory store, files | Large persistent storage that must be loaded into RAM to use |
| Firmware / ROM | Model parameters | Built-in knowledge and skills baked in at the factory |
MemGPT (Packer et al., 2023) treats an LLM agent like an operating system: old text is paged out of the context to disk, and the model calls a function to page it back in.
Question 1
Answer. (a) Model parameters. (b) Memory file, loaded at session start. (c) Repository, read via a tool call. (d) Context window, reused from the prompt cache. (e) Nowhere—unless searched.
What is baked into the model weights
Allen-Zhu and Li, 2024; the reversal curse, Berglund et al., 2023.
| Questions on events after cutoff | Accuracy |
|---|---|
| Base model (no documents) | 0.48 |
| Fine-tuned on the articles | 0.50 |
| Fine-tuned on paraphrased articles | 0.59 |
| Articles put in the context (RAG) | 0.88 |
Use fine-tuning for skills and tone. Put new or private facts in the context.
Mistral 7B: Ovadia et al., Microsoft, 2024. Hallucinations from unfamiliar facts: Gekhman et al., Google, 2024.
Whatever is in the context steers the answer—for better or worse.
ClashEval, Stanford, 2024; Sufficient Context, Google, 2025; BrokenMath, ETH Zurich, 2025.
Working memory for a single request
Per token: 2 × layers × KV heads × head size × bytes
Llama 3 70B uses 320 KiB per token—about 40 GiB for 128K tokens.
OpenAI conversation-state guide (previous_response_id); see Question 3 for the 20-turn calculation.
Question 2
Exactly one of the 20 Wikipedia passages contains the answer.
Answer. Accuracy drops to 54%—worse than giving it no documents at all! (With only the single right passage, accuracy jumps to 88%.)
Accuracy is U-shaped: the start and the end are used best, while the middle of a long context is used much worse. Always put the best passages first.
Lost in the Middle, Liu et al., Stanford, 2023 (GPT-3.5-Turbo, June 2023; Natural Questions).
A large window is a ceiling, not a target—send only what the task needs.
NoLiMa, Adobe Research, 2025; Context Rot, Chroma, 2025.
Put static content first: tools, system instructions, and reference documents.
Anthropic: read 0.05×; write 1.25× (5 min) or 2× (1 hour). OpenAI: read 0.1×. October 2026.
Question 3
System prompt: 4,000 tokens. Each turn adds 300 user tokens and 700 reply tokens.
Claude Sonnet 5.5: $2 per million input tokens (cache write ×1.25, cache read ×0.05).
Answer. Without caching: 276K input tokens billed at full price = $0.55.
With caching: 23K new tokens written + 253K tokens read from cache = $0.084 (6.6× cheaper).
| Technique | How it keeps the context small |
|---|---|
| Clear old tool results | Drops bulky file reads or search outputs once used |
| Compaction | Replaces the conversation history with a short summary |
| Sub-agents | Runs a subtask in a clean window and returns a brief report |
| Notes in files | Saves plans and state to disk (NOTES.md) to read back later |
Context management moves details out of the window—at the risk of losing nuances.
Anthropic, 2025–2026: clearing old tool outputs saved 84% of tokens on a 100-turn task; Claude Code’s context per request grew 2.6× in six months.
Demonstration
Claude Code in a copy of this lecture’s folder; login required
Finding external knowledge and loading it into the context
RAG does not change the model—it searches external storage and copies text into the prompt.
Term introduced by Lewis et al., 2020, combining “parametric” (weights) and “non-parametric” (index) memory.
| Method | How it scores a chunk | What it is best at |
|---|---|---|
| BM25 (keyword) | Counts shared words; rare words carry more weight | Exact names, error codes, identifiers |
| Embeddings (dense) | Maps text to vectors and compares the cosine of the angle between them | Synonyms, paraphrases, meaning |
| Hybrid search | Runs both and merges the two rankings (e.g., RRF) | Both exact terms and paraphrases |
Approximate vector indexes (such as HNSW) find the closest matches among millions of vectors in under a millisecond.
| Pipeline | What it adds | Missed in top 20 |
|---|---|---|
| Embeddings only | Vector search over raw document chunks | 5.7% |
| + Chunk context | A short note placing each chunk in its document | 3.7% |
| + BM25 (hybrid) | Combines exact keyword matches with vectors | 2.9% |
| + Reranking | Re-scores the top 150 candidates and keeps 20 | 1.9% |
Under ~200K tokens? Skip RAG and put all the documents into a cached prompt.
Contextual Retrieval, Anthropic, 2024.
Demonstration
Terminal in materials/retrieval-demo; LM Studio running EmbeddingGemma-300m for step 3
Question 4
Knowledge base: 200K or 800K tokens. RAG retrieves 20 chunks × 800 tokens (16K per question).
Claude Sonnet 5.5: $2 per million input tokens (cache write ×1.25, cache read ×0.05).
Answer. Uncached base: $400/day (200K) or $1,600/day (800K).
Cached base: $20.50/day (200K) or $82/day (800K). RAG: $32/day either way.
Below ~320K tokens, caching the entire knowledge base in the prompt is cheaper than RAG.
| Approach | Best when | Breaks when |
|---|---|---|
| All in context, cached | Small base (<300K tokens), many requests | Base outgrows the window or adds noise |
| RAG pipeline | Large collection, similar questions, low latency | Search misses a chunk, or the index is stale |
| Agentic search (grep, reads) | Code, changing files, multi-step questions | Multiple calls use ~4× more tokens |
For code, live search beats vector indexes: Claude Code uses grep, and Cursor dropped its embedding index in 2026.
Boris Cherny, Latent Space, 2025; Cursor forum, July 2026; Anthropic, multi-agent research, 2025.
Carrying notes and facts from one chat to the next
Coding agents combine both: Claude Code always loads MEMORY.md (a short index) and reads topic files on demand; Codex loads memory_summary.md and searches MEMORY.md when needed.
Claude Code memory docs: loads the first 200 lines or 25 KB of MEMORY.md. Codex source: summary up to 2,500 tokens; memories off by default. October 2026.
| Operation | How it works in practice |
|---|---|
| Write | Explicit requests (“Remember…”), background extraction, or agent notes |
| Read | Injected at session start, or retrieved by search when needed |
| Update | Overwrite the old note, or keep both entries with dates |
| Forget | Delete the memory entry—deleting the chat often leaves extracted facts behind |
Updating old memories is harder than saving new ones.Keep critical project rules in one file you edit by hand (CLAUDE.md, AGENTS.md).
| App | What it stores | How it enters the chat | How to make it forget |
|---|---|---|---|
| ChatGPT | Saved facts plus background summaries of past chats | Automatically injected into every chat | Delete the memory item itself (deleting the chat is not enough) |
| Claude | Topic notes (scoped per project) and past chats | Loaded per project, or searched via visible tool calls | Edit or delete the topic note |
| Gemini | No separate memory store—only your past chats | Pulled from past chats when relevant | Delete the chats that contain it |
Help pages of OpenAI, Anthropic and Google, October 2026. In the EEA and the UK, ChatGPT’s chat-history memory is opt-in.
Rehberger, 2024; Microsoft, 2026; Trojan Hippo, 2026; CHI 2026; forgetting benchmark, October 2026 (at most 1.5% of requests).
Demonstration
Tracing one request, resolving conflicts, and key takeaways
| # | What happens | Memory involved |
|---|---|---|
| 1 | Session starts: prompt, tools, and MEMORY.md load | Memory store → context |
| 2 | Question sent; the unchanged prefix is reused | Prompt cache → KV cache |
| 3 | The model decides to run grep test_sum | Parameters + context |
| 4 | The app runs the tool and appends the output | Repository → context |
| 5 | The model generates the answer token by token | Parameters + context |
| 6 | “Remember: run pytest -x” is saved to a file | Context → memory store |
| 7 | Window nears its limit: compaction summarizes the chat | Context → summary |
Every arrow is a copy step—and every copy can drop a detail or let bad data in.
| Conflict | What happens | What helps |
|---|---|---|
| Document vs. weights | Model trusts a wrong document | Show citations; flag contradictions |
| Old memory vs. today | Outdated notes override current setup | Store dates; prefer the current chat |
| Retrieved text vs. prompt | Prompt injection hijacks the agent | Treat as data; limit tool permissions |
| Summary vs. original | Compaction drops a needed detail | Keep key facts in files; re-read source |
| Index vs. live files | Search index lags behind edits | Re-index, or search files directly |
Models are trained to rank system and user instructions above tool outputs (the instruction hierarchy, OpenAI, 2024), but do not follow this reliably.
| Kind | What it gives you | When it fails |
|---|---|---|
| Parameters | Skills and common facts from training (no sources) | A fact is rare, private, or new |
| Context | Working memory for this request, paid per token | It gets too long or buries facts |
| Prompt cache | Reuses an unchanged prefix 10–20× cheaper | The start of the prompt changes |
| Document index | Finds chunks in large collections to copy in | A chunk is missed, or index is stale |
| Memory store | Carries notes and preferences across sessions | Notes go stale, bias, or get poisoned |
Answer = parameters + context. The model remembers nothing between requests—everything else is copied in, and every copy can lose or add something.
5–10 minutes to design the memory setup
Question P
Answers 300 student questions a day about a 600-page textbook (~400K tokens). Must cite page numbers.
Helps developers navigate and debug a 2-million-line repo (~20M tokens) that changes every day.
Works with one mathematician across months of sessions. Tracks notation, open problems, and failed attempts.
For each system, decide:
| Task | Memory used | Always loaded | Retrieved or searched | Written back |
|---|---|---|---|---|
| 1. Course | Prompt cache, document index | System instructions (cached) | 20 chunks with page numbers, or the whole book cached | Nothing |
| 2. Codebase | Prompt cache, memory file, repository | Prompt, tools, project memory file | Live grep and file reads (code changes daily) | Memory file; summary on compaction |
| 3. Research | Memory store, past sessions | Short notes file (notation, open problems) | Search over past sessions and papers | Research notes with dates |