Week 3 · Technical Foundations 2
2026-09-28
We continue from where we left off last week.
\(\mathrm{input}_t = \text{fixed prefix} + \text{history before call } t\)
Each call re-reads the fixed prefix and all of the history so far. The history grows by one turn per call, so the total input over a task grows with the square of the number of calls.

GPT-4 128K could find one planted sentence almost everywhere in short contexts, but often missed it past about 73K tokens when it sat in the upper half of the document.
Greg Kamradt, “Pressure Testing GPT-4-128K With Long Context Recall”, 8 November 2023
Linear projections: \(Q = XW_Q,\; K = XW_K,\; V = XW_V\)
Causal self-attention: \(A = \mathrm{softmax}\!\left(\dfrac{QK^\top + M}{\sqrt{d_k}}\right),\; O = AV\)
The new token becomes a query \(q_t\).
Every token so far has a key. The query is compared against all of them.
Softmax turns the scores into weights that sum to 1.
The output is a weighted mix of the values. Not a lookup, a blend.
Linear projections: \(Q = XW_Q,\; K = XW_K,\; V = XW_V\)
Causal self-attention: \(A = \mathrm{softmax}\!\left(\dfrac{\bbox[4px,border:3px solid #7a4b2a]{QK^\top + M}}{\sqrt{d_k}}\right),\; O = AV\)
Rows of \(QK^\top + M\) are queries and columns are keys. \(M\) masks every key that comes after its query.
Every query is compared with every key before it, so the work grows as \(O(n^2)\) in the sequence length \(n\).
Causal window mask:
\[M^{(w)}_{ij} = \begin{cases} 0, & 0 \le i - j < w \\ -\infty, & \text{otherwise} \end{cases}\]
Using the same attention equation, work falls from \(O(n^2)\) to \(O(nw)\).
A local layer cannot directly retrieve distant tokens.
Start from standard attention: \[o_t = \sum_{i=1}^{t} \mathrm{softmax}_i\!\left(q_t^\top k_i/\sqrt{d_k}\right) v_i\]
Replace the normalization with a bilinear score: \[\mathrm{softmax}_i\!\left(q_t^\top k_i/\sqrt{d_k}\right) \;\longrightarrow\; q_t^\top k_i\]
Reassociate, then update recurrently: \[o_t = \sum_{i=1}^{t} (q_t^\top k_i)\, v_i = \Big(\sum_{i=1}^{t} k_i v_i^\top\Big)^{\!\top} q_t = S_t^\top q_t\] \[S_t = S_{t-1} + k_t v_t^\top\]
What is the shape of \(S_t\)?
\(S_t \in \mathbb{R}^{d_k \times d_v}\). It is a constant size, whatever \(t\) is.
Prediction and error: \[\hat v_t = S_{t-1}^\top k_t, \qquad e_t = v_t - \hat v_t\]
Delta-rule write: \[S_t = S_{t-1} + \beta_t k_t e_t^\top, \qquad o_t = S_t^\top q_t\]
\(\hat v_t\) is what the memory currently returns for \(k_t\), \(e_t\) is its error, and \(\beta_t \in [0,1]\) is the correction strength.
Whole-state decay: \[\tilde S_{t-1} = \alpha_t S_{t-1}\]
Correction after decay: \[S_t = \tilde S_{t-1} + \beta_t k_t \big(v_t - \tilde S_{t-1}^\top k_t\big)^\top\]
\(\alpha_t \in [0,1]\) is a scalar retention gate and \(\tilde S_{t-1}\) is the decayed memory. Setting \(\alpha_t = 1\) recovers DeltaNet.
Per-channel decay: \[D_t = \mathrm{Diag}(\boldsymbol{\alpha}_t), \qquad \tilde S_{t-1} = D_t S_{t-1}\]
KDA recurrence: \[S_t = \big(I - \beta_t k_t k_t^\top\big) D_t S_{t-1} + \beta_t k_t v_t^\top\]
\(\boldsymbol{\alpha}_t \in [0,1]^{d_k}\) is a vector retention gate, \(D_t\) is its diagonal matrix, and \(I\) is the \(d_k \times d_k\) identity. Equal retention in every channel recovers Gated DeltaNet.

Hatched blocks are what is cached for each token. Grouped-query and multi-query attention share keys and values across query heads; multi-head latent attention caches one compressed vector and projects keys and values back out of it.
DeepSeek-AI, DeepSeek-V2, 2024, figure 3
All of these trade how well the history is remembered for less compute, meaning computation time plus storage and memory.
All of them compress the history, and so they all risk losing the ability to retrieve that history in longer contexts.
| Model | Local or stateful calculation | Global calculation | Local : global |
|---|---|---|---|
| Qwen3.8-Flash-Next | Gated DeltaNet | QSA sparse retrieval | 36 : 12 ≈ 3 : 1 |
| GLM-5.3-Flash | Kimi Delta Attention | DSA + IndexPool | 34 : 11 ≈ 3 : 1 |
| Kimi K3 | Kimi Delta Attention | dense Gated MLA | 69 : 24 ≈ 3 : 1 |
| Nemotron 3 Ultra | Mamba-2 | dense GQA | 48 : 12 = 4 : 1 |
| Inkling-Small | 512-token window | dense GQA | 35 : 7 = 5 : 1 |
| DeepSeek-V4-Pro-0813 | 128-token window branch | compressed sparse or dense | interleaved branches |
Source: CMU 11-768, AI Agents, lecture 3, slide 16.
Long documents have naturally long context: books, codebases, and collections of documents that belong to the same broader context.
Packed examples provide efficient long training batches.
Agent trajectories provide long sequential interactions.
Synthetic tasks enable controlled long-context experiments.
Input to the first layer: \[z_t = E[x_t] + p_t\]
Fixed sinusoidal encoding: \[p_{t,2\ell} = \sin(t/\omega_\ell), \qquad p_{t,2\ell+1} = \cos(t/\omega_\ell)\] \[\omega_\ell = 10000^{2\ell/d}\]
The adjacent values \(p_{t,2\ell}\) and \(p_{t,2\ell+1}\) form a coordinate pair inside the position vector.
\(x_t\) is a token ID, \(E\) is the embedding table, \(p_t\) is the position vector, and \(\ell\) indexes the pairs. Position enters before the projections that produce \(Q\), \(K\), and \(V\).
A 2D rotation: \[R_\theta = \begin{pmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{pmatrix}\]
One rotation per coordinate pair, each at its own speed \(\theta_\ell\): \[R(i) = \begin{pmatrix} R_{i\theta_0} & & \\ & \ddots & \\ & & R_{i\theta_{d/2-1}} \end{pmatrix}\]
Rotate rows of \(Q\) and \(K\): \[\tilde q_i = R(i)\, q_i, \qquad \tilde k_j = R(j)\, k_j\]
The score depends on relative displacement: \[\tilde q_i^\top \tilde k_j = q_i^\top R(j-i)\, k_j\]
\(V\) is unchanged; attention uses the same equation with rotated \(Q\) and \(K\).
Input to the first layer: \[z_t = E[x_t]\]
The attention equation is unchanged: \[A = \mathrm{softmax}\!\left(\frac{QK^\top + M}{\sqrt{d_k}}\right), \qquad O = AV\]
Order is inferred from causal computation or recurrent dynamics, not from \(p_t\) or \(R(t)\).
This removes position extrapolation, but not the need to train long-range behaviour.
Uniform position interpolation: \[R(t) \longrightarrow R(t/s) \quad\text{equivalently}\quad \theta_\ell \longrightarrow \theta_\ell / s\]
Every RoPE dimension is stretched by the same scale \(s = L'/L\).
Long positions stay inside the phase range seen during pretraining.
YaRN is based on RoPE. It can be used with lightweight fine-tuning, and also at inference time.
Frequency-selective interpolation: \[\theta'_\ell = (1-\gamma_\ell)\,\frac{\theta_\ell}{s} + \gamma_\ell\, \theta_\ell, \qquad 0 \le \gamma_\ell \le 1\]
Attention-temperature adjustment: \[A = \mathrm{softmax}\!\left(\frac{\tilde Q \tilde K^\top + M}{\tau\sqrt{d_k}}\right), \qquad \sqrt{1/\tau} = 0.1 \ln s + 1\]
\(\gamma_\ell\) goes from 0 for long wavelengths to 1 for short wavelengths, and \(\tau\) is the attention temperature.
| Model | Context-length training | Position method | How it reaches maximum context |
|---|---|---|---|
| Qwen3.8-Flash-Next | 262K native; full curriculum undisclosed | partial RoPE | YaRN extension to 1M |
| DeepSeek V4 | 4K → 16K → 64K → 1M | partial RoPE | progressive training + YaRN |
| GLM-5.3-Flash | 1M native; exact curriculum undisclosed | NoPE in main attention | no RoPE rescaling |
| Kimi K3 | 8K → 64K → 256K → 1M | NoPE | progressive training to 1M |
| Nemotron 3 Ultra | 1M long-context CPT; SFT to 512K | implicit order in Mamba; no RoPE | trained and evaluated at long lengths |
| Inkling | 1M context; curriculum undisclosed | relative position embedding | learned relative representation |
Source: CMU 11-768, AI Agents, lecture 3, slide 33.
--workers=1 and rerun./tmp/ci.log.--workers=1 passes./tmp/ci.log.A synthetic example, adapted from CMU 11-768, AI Agents, lecture 3.
Trigger: a token threshold. Compact before you hit the limit.
How do you set the threshold? Reserve room for the next output: both the agent's next action and the compaction model's own output.
Select and replace. Protect the beginning, compact the older region, and keep the recent tail.
Recover. Even if old messages are removed from the active context, you may keep the original history elsewhere.
Each summary is made from the previous summary plus the newest turns, \(\hat s_{k+1} = C(\hat s_k \oplus R_k)\), so small losses add up.
A synthetic example, adapted from CMU 11-768, AI Agents, lecture 3.

pi compacts when the context passes the window minus 16,384 reserved tokens. It keeps the last 20K tokens word for word and replaces older messages with a structured summary. The originals stay in the session file, but they are no longer sent to the model.
pi coding agent documentation, docs/compaction.md, github.com/earendil-works/pi, 22 September 2026

Codex compacts at 90 percent of the context window by default and asks the model for a handoff summary with this prompt. On OpenAI models it asks the provider instead, and gets back an encrypted summary that neither the user nor the harness can read.
OpenAI Codex CLI source code, github.com/openai/codex, prompt last changed 1 June 2026

Claude Code summarizes the conversation, then reloads project instructions, memory, and the plan from disk and re-reads recent files. The original messages stay in the session transcript.
Claude Code documentation, “What survives compaction”, code.claude.com/docs/en/context-window, fetched 27 September 2026
Model: inference and architecture, KV cache
Harness: context compaction
Long context and context compaction are common triggers for misalignment.
1M tokens is currently the common upper end for production frontier models.
1M tokens is roughly 750,000 English words.
| Book | Tokens | Copies in 1M |
|---|---|---|
| Harry Potter and the Philosopher’s Stone | 103K | 10 |
| A Game of Thrones | 390K | 2.6 |
| The Lord of the Rings, all three volumes | 607K | 1.6 |
| Harry Potter, books 1 to 5 | 956K | 1.0 |
| Harry Potter, all seven books | 1.45M | 0.7 |
Estimated from published word counts at about 0.75 words per token. Newer Claude models fit about 555,000 words in 1M tokens, so each book takes about a third more.
1M tokens is roughly 85,000 to 140,000 lines of code.
| Software project | Tokens | Copies in 1M |
|---|---|---|
| nanoGPT | 13K | 75 |
React, the react package only |
119K | 8 |
| Redis, the server code | 2.2M | 1/2 |
| Git | 6.7M | 1/7 |
| Python (CPython) | 19M | 1/19 |
| Linux kernel | 440M | 1/440 |
Source code of each project at its latest release in September 2026, counted with OpenAI’s GPT-4o tokenizer.
Managing long context can be a hard task for humans as well.
How do we inform people about, and address, the unexpected behaviours that context compaction causes?
We want the agent to learn knowledge from experience that generalizes. Raw trajectories take space and do not generalize well, so we write skills or let the LLM induce them.
We cannot keep an infinite amount of history in the context, so some information has to be stored outside it.
Agents can lose track of where they are in a long-horizon task. An explicit plan helps them follow their progress.
All three solve the problem the same way: they propose clever ways to structure and maintain the context.
As a user, you also manage skills, memory, and plans, mostly by hand and in an ad hoc way. Models and harnesses are not designed to help you with that.
What mechanisms like these could help people with their own management tasks, and what does that mean for human control?

Claude writes one file per memory on its own. The index loads at the start of every session, and memory files are read on demand.
Claude Code documentation, “How Claude remembers your project”, code.claude.com/docs/en/memory, fetched 27 September 2026

The name and description are always in the system prompt. The body loads when the skill is triggered, and files in examples/ only when needed.
Anthropic, public skills repository, github.com/anthropics/skills, skills/internal-comms/SKILL.md, December 2025
Memory: facts retrieved from storage and appended to the context after a query
Skill: two tasks with the same structure share one procedure
sales.csv.users.csv.Skill: what is in the context, and when
--- name: csv-to-chart description: Plot a time series from a CSV file. Use when the user asks for a chart of values over time. ---# CSV to chart 1. Load the CSV and check the column names. 2. Parse the date column. 3. Group by the period the user asked for. 4. Plot with labelled axes and save a PNG. For unusual date formats, run scripts/parse_dates.py.
name and description always in the system prompt
the body loaded when the skill is triggered; the script only if needed
Memory: retrieved on demand and used
search_memory("flight preferences")Memory
Induced skill
A skill is repaired or retired based on the outcome of using it.

System instructions are fixed. Working context holds key facts about the user and the agent’s persona. The FIFO queue holds recent messages, starting with a summary of the evicted ones. The LLM moves data to and from recall and archival storage by emitting function calls.
Packer et al., “MemGPT: Towards LLMs as Operating Systems”, arXiv 2310.08560, 2023, figure 3
Compared with RoPE, YaRN, or linear attention, what is different?
MemGPT handles long context at the system or harness layer. The model itself does not change.
What is a computing efficiency caveat?
Hint: KV cache.

Mem0 handles memory storage, retrieval, and updates. It extracts facts from each new exchange and lets the LLM add, update, or delete memories, or leave them as they are. Since April 2026, Mem0 only adds memories on its own and leaves updates and deletes to the application.
Chhikara et al., “Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory”, ECAI 2025, figure 2

Create a skill right after you finish a workflow you want to repeat, so the agent already has a good example in its context. Then test the skill a few times.
Michelini and Neubig, “How to Create Effective Agent Skills”, OpenHands blog, 27 February 2026
A plan is an explicit representation of intended future behaviour: the actions or subgoals an agent will attempt, with any ordering or dependencies among them.
A plan is for this task, in contrast to a skill.
A plan organizes future work.
A plan is a proposal, not a guarantee.

It gives the model extra compute and a scratchpad it can refer back to.
Kojima et al., “Large Language Models are Zero-Shot Reasoners”, NeurIPS 2022, figure 1

/plan or Shift+Tab switches Codex into Plan mode. It asks clarifying questions, proposes a plan, and then asks whether to implement it, implement it in a fresh thread, or keep planning.
OpenAI Codex CLI source code, github.com/openai/codex, commit e6f4af1, 28 September 2026

Shift+Tab or /plan switches Claude Code into plan mode, where it reads and explores but cannot edit. It writes the plan to a file and asks for approval. You can approve, keep planning, or edit the plan yourself.
Claude Code documentation, “Permission modes”, code.claude.com/docs/en/permission-modes, fetched 27 September 2026

pi has no plan mode, by design. You talk the plan through with the agent, or keep it in a file such as PLAN.md that the agent reads and updates.
An example extension adds one. /plan removes the edit and write tools and blocks shell commands that are not on an allowlist. After each answer it asks whether to execute the plan, stay in plan mode, or refine the plan.
Mario Zechner, “What I learned building an opinionated and minimal coding agent”, 30 November 2025; pi repository, examples/extensions/plan-mode, github.com/earendil-works/pi
| Codex | Claude Code | pi, with the example extension | |
|---|---|---|---|
| While planning | The plan-mode prompt forbids edits. No read-only switch was found in the harness. | The harness blocks edits until the plan is approved. | Edit and write are removed, and shell commands off the allowlist are blocked. |
| After approval | The plan stays in the conversation, or opens a fresh thread. | The plan file is put back into the context after each compaction. | The remaining steps are put back into the context before each turn. |
| Progress | The model updates an update_plan checklist. | A task list on older models; newer models track work without one. | The model marks steps done with [DONE:n] tags. |
| Revision | The model rewrites the checklist; the user can switch back to Plan mode. | The user keeps planning, edits the file, or re-enters plan mode; Claude can re-enter it too. | The user edits PLAN.md or turns plan mode off and on. |
In all three, nothing checks that the work actually follows the approved plan.

Plan-then-execute fixes the program before the agent sees any web content. An injected review can change the data the program uses, but it cannot add new actions.
Piet et al., “Web Agents Should Adopt the Plan-Then-Execute Paradigm”, arXiv 2605.14290, May 2026, figure 1
Plan a sequence of actions that reaches a final state.
Tower of Hanoi: move all disks from A to C, one disk at a time, never putting a larger disk on a smaller one.
A seven-move plan:
The goal may not be clearly specified, or it contains ambiguity that the agent handles.
The plan is coarser grained and higher level.
The agent deals with an open world, so more effort goes into observation, verification, and recovery from errors.
ls dataraw/ README.md summary.csvcat data/summary.csvcondition,n,mean_completion_s manual,8,58.0 agent,8,41.0 agent_review,8,44.6
summary.csv). I've filled this number into the blank in report.md.data/README.md:
data/raw/export_2026-09-12.csv has 10 agent participants, including two added on Sep 10. Their mean is 43.6 seconds.
A person could specify or modify the plan to require a step: read data/README.md.
But the plan might be high level, and the user may not expect that such a detailed instruction is needed.
More exploration of the environment and replanning would help, but they also cost more. That is a trade-off.
Pros and cons?
Back in 10 minutes.
peach-research-lab.github.io/agent-human-control/studio/w3
The same kind of page as last week: real runs of an open source agent on a small local model, exactly what the model received and produced.
New this week: blue harness rows. They show what the harness did between model calls: a compaction, a memory extraction, or the start of a new session. After a compaction, the messages the model no longer receives are dimmed.
Full context view. Pick a call from the menu to see the exact string the model read at that call, including the compaction calls.
Tasks D and E stop after the plan. Answer prompt 1 before you click “Show the rest of the run”. An “After the run” panel then shows the state the agent left behind, which the agent never saw.
10 minutes
Trajectory: lab meeting minutes. Eight model calls, one of them a compaction. Four prompts on the page:
30 minutes
Five trajectories, tasks A to E, one problem each. Do as many as you can, in the order B, D, A, C, E.
Three prompts per task:
For each task, A to E: what went wrong, and which message shows it first?
A: a summary is a lossy copy of your instructions, and after compaction it is the only copy the model has. Here it turned a list of eight into three examples.
B: a permission given for one batch of replies became a standing rule, and it removed the moment where a person would have caught the phishing email.
C: a skill only works while its text is in the input. The same model refused with the skill in view and complied without it.
D: the person approved the plan they read; the agent executed the harness’s copy of it.
E: the agent did exactly what the person approved, and the plan was missing the step that would have shown the risk.
When pi compacts, it turns the older messages into plain text for the summarizing model. Before that, it cuts every tool result at 2,000 characters.
const TOOL_RESULT_MAX_CHARS = 2000;
...
truncateForSummary(content, TOOL_RESULT_MAX_CHARS)
The agent itself read each file in full. Only the summarizer’s copy is cut. But once compaction runs, the summary replaces the original, and it is the only copy the agent has left.
pi has no built-in plan mode. Task D uses the plan-mode extension that ships with pi as an example. After the agent writes its plan, the extension copies each numbered step into a short to-do list. It reads each step up to the first *, because it expects that character to close a bold title.
The same list is what the extension sends the model with “Execute each step in order.”
The plan the person approved:
The step the agent received:
The agent archived all 90 application logs and then deleted all of them, including the 14 most recent ones that the approved plan kept.
Pick one round 2 trajectory.
Say what went wrong, which message shows it first, and where in the run a person could have stepped in and caught it.
Optional: open the memory or saved instructions of an assistant you use, such as ChatGPT’s saved memories or a CLAUDE.md or AGENTS.md file, and find one entry that applies more broadly than you meant it to.
Export your notes from the studio page and paste them into your Canvas submission. Due Friday, October 2, midnight.
Before next Monday
Submit the studio reflection by this Friday, October 2, midnight.
Submit the reading response by next Monday, October 5, noon.
Yao et al., τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains, 2024.
Both are submitted on Canvas.
Research spotlight, October 5
Control protocols against an untrusted agent: Manasha Sekar
User and context modelling in the harness: Vineel Vennelakanti
Judging contextual information flows in the harness: Ananyaa Mylsamy
| Criterion | Points |
|---|---|
| Problem framing from the two anchor papers | 25 |
| Methods and their evidence | 25 |
| Limits of each solution against the anchor problem | 15 |
| Limits of the level and the closing slide | 15 |
| Takeaways for the course project | 10 |
| Delivery and discussion | 10 |
Out of 100 points. Each talk has 15 minutes plus 5 minutes for questions. What each level of marks means is on the course website, on the Research spotlight page.