CS2680  /  自学手册
00 / 10  ·  INTRO

HARVARD CS2680 · 自学手册 · 2026.11.02

智能体与 AI 系统优化CS2680前十讲自学手册

本课程把智能体看作一个系统问题:模型给出能力上限,harness 决定实际表现,服务系统与 GPU 决定成本和速度。前八讲讲智能体的使用与设计,包括循环、工具、上下文、记忆、多智能体、可靠性、评估和降本;后两讲讲 LLM 推理与 GPU 的基本原理。每讲先列要点,末尾附自测题。

SCROLL

01第 1 讲

课程地图:AI 系统与智能体系统Course map: AI systems and agentic systems

要点

  1. AI 系统关心怎样大规模地训练和服务模型,目标是性能、效率、可靠性与可持续;本课专指 LLM 系统。
  2. 智能体用模型推理、调用工具、多步行动直到完成任务。它像一种新的计算机:LLM 是 CPU,上下文是内存,工具是外设,harness 是操作系统。
  3. 智能体服务是推理与工具交替的长链,每一种负载特征都对应一个系统问题。
  4. 目标不是吞吐量,而是在延迟、成本、资源、可靠性和安全的约束下,最大化任务成功率。

AI 系统与传统计算机系统的五点不同

维度 要点
计算 异构:CPU 负责分词、kernel 启动、数据搬运和工具调用,GPU 负责矩阵乘;prefill 受算力限制,decode 受显存带宽限制;执行时间取决于输出长度,难以调度
非确定性 浮点加法不满足结合律,第 7 位小数的偏差就可能改变下一个 token;来源包括运行时(warp 调度、batch 大小)、软件(FMA 与两次运算、autotuning)和硬件(CUDA core 与 tensor core、FP8 与微缩放格式)。近似计算是可以接受的
内存、存储与通信 权重从数 GB 到数 TB,KV cache 每个 token 数十到数百 KB,prefix cache 跨请求复用 KV;数据搬运是瓶颈;多 GPU 需要流水线、张量、专家和上下文并行,依赖 NCCL、NVLink、InfiniBand、RDMA
快速演化 注意力结构从 MHA 到 GQA、MLA、NSA、线性注意力;负载从多轮对话、长推理、RAG 发展到智能体(长上下文、依赖 prefix cache、需要路由与负载均衡)
可靠性与功耗 年故障率 9%,16K GPU 的集群约每 3 小时坏一块;单卡 700 至 1000 W,单台服务器功耗从 800 W 升到 6000 W

GPU 服务器的功耗约为 CPU 服务器的 8 倍

单台服务器功耗,W

  1. CPU 服务器800 W
  2. GPU 服务器6,000 W
第 1 讲课件

什么是智能体

智能体是一个自主的软件系统:它用 AI 模型围绕目标推理,调用外部工具,执行多步动作,直到任务完成。它的工作方式可以拆成五步:

01计划:把任务拆成子步骤
02行动:调用外部工具
03观察:解读工具结果
04调整:按新信息修订计划
05交付:返回最终结果

需要智能体,是因为 LLM 能力分布很不均衡。它在知识回忆、语言、模式匹配、写代码、跨领域方面超过人,但在持久记忆、可靠理解上下文、避免幻觉、知道自己不知道什么、抵御对抗输入方面很弱。智能体用工具和记忆补足这些短板。

可以把智能体看作一种新的计算机:LLM 对应 CPU,上下文窗口对应内存,工具对应外设,agent harness 对应操作系统,智能体对应应用程序。它的编程模型和失败模型与传统计算机完全不同。

为什么智能体是系统问题

传统 LLM 服务是「请求、推理、响应」一次完成;智能体服务是「推理、工具、推理、工具、检索、推理……」的长链。关键路径跨越 GPU、CPU、存储、网络和外部服务,带来六个问题:步骤间有依赖、每步延迟差异大、要阻塞等待工具、状态快速增长、需要并发与推测、轨迹上任何一处都可能失败。

智能体负载的特征 对应的系统问题
轨迹长 状态与上下文管理
上下文大 内存层次与检索
前缀重复 prefix caching
推理分支 推测执行
工具有依赖 依赖感知的调度
使用不同模型 路由
工具延迟不定 异步执行
有外部副作用 安全与隔离
多个智能体 编排与通信
任务运行时间长 检查点与容错

系统栈自上而下是:应用与用户;智能体与 harness(规划、上下文、记忆、工具、子智能体),旁边是外部环境与工具(网页、文件、API、人);模型;服务系统(批处理、调度、路由、缓存);运行时与 kernel(CUDA、Triton、集合通信);硬件(GPU、CPU、内存、网络、存储)。

优化什么

对智能体而言,吞吐量是错误的目标。真正的目标是在延迟、成本、资源、可靠性和安全的约束下,最大化任务成功率。

真正要优化的指标

  • 任务成功率与准确率
  • 端到端延迟
  • 每个任务消耗的 token
  • 每个成功任务的成本(美元)
  • 每个成功任务的能耗

有用但不够的指标

  • TTFT(首 token 时间)与 TPOT(每 token 时间)
  • 工具调用延迟
  • GPU 利用率

每秒生成更多 token,智能体仍可能更慢、更贵。可观测性是一等问题:智能体的分布式追踪变成了嵌套的轨迹(会话、轮次、智能体步骤、模型请求、工具调用、子智能体),看不见就无法优化。

课程要回答的问题

批处理与延迟为什么批处理提高吞吐量,却会拖慢智能体延迟?什么时候该用更大的模型?
状态放在哪里KV 与 prefix 状态应放在哪里?同一个智能体的多个请求该怎样调度?
重叠与分工工具调用能否与推理重叠?什么时候该派生子智能体?
路由与恢复怎样在异构 GPU 和模型之间路由?30 分钟的智能体任务失败后怎样恢复?
优化目标怎样优化「每个成功任务的成本」,而不是「每秒 token 数」?

课程不讲训练(推理占了主要算力需求)、模型结构设计、通信、功耗与新硬件设计。

附:AI 编码的六个层级,以及智能体、助手与机器人
层级 含义
0 不用 AI,手写代码
1 辅助:AI 自动补全
2 受监督:AI 写函数,人审查
3 限定范围:交出一个任务,审查代码
4 目标驱动:AI 写全部代码,由测试验证
5 并行智能体:子智能体分工
智能体 助手 机器人
目的 自主、主动地执行任务 协助用户完成任务 自动化简单任务或对话
能力 多步复杂动作,能学习、自行决策 响应提示,可以建议,由用户决定 按预设规则,学习能力有限
交互 主动,面向目标 被动,响应请求 被动,响应触发或命令

自测

课程认为,对智能体来说真正要优化的是哪一项?

自测

智能体负载的特征各自对应哪个系统问题?

前缀重复
工具延迟不定
有外部副作用
任务运行时间长

02第 2 讲

Claude Code 如何工作:循环、记忆与扩展How Claude Code works: the loop, memory and extensions

要点

  1. 一次输入会展开为多次模型调用和工具执行:模型提议,harness 检查权限后执行,结果写回上下文。
  2. 上下文是租来的工作记忆;CLAUDE.md 与自动记忆是每次会话都加载的持久文件,过时的记忆比没有更糟。
  3. 四种扩展各管一件事:skill 管怎样做,MCP 管能触达什么,hook 管自动执行,plugin 管打包分发。
01收集上下文:提示、文件、工具结果
02模型生成动作:如 Bash(“pytest”)
03harness 检查权限并执行
04结果写回上下文

循环中的几个事实

  • 输入之前已有 1 万以上 token。 上下文里先放了系统指令、项目环境、记忆(CLAUDE.md)、工具(Read、Edit、Bash、Glob、Grep、Web、Agent)、skill 与 MCP 的名称和描述,最后才是用户的话。skill 与 MCP 起初只有名字,用到时才加载全文。
  • 不会把整个仓库发出去。 仓库留在磁盘上,模型按需取片段,例如 Grep(“authentication”) 只带回几行。
  • 模型提议,harness 执行。 模型发出工具请求,harness 解析、检查权限、在本机执行,tool_result 回到模型上下文。每次请求都以上一次推理和上一次工具结果为条件。
  • 权限层位于意图与执行之间。 工具请求只是提议,需要用户或另一个模型批准(见下表)。
  • 上下文会增长,然后被压缩。 常见上下文长度为 1M token(年初多为 256K)。成本大部分来自 prefix cache 读取。压缩(compaction)会总结旧轨迹,并重新注入 CLAUDE.md 与记忆。
权限模式 含义
手动 每次都由用户确认
接受编辑 编辑自动通过,其他仍需确认
跳过权限 全部直接执行
自动 由一个小模型检查请求

请求的结果有三种:允许(命令运行)、询问(先由用户确认)、拒绝(什么都不发生)。

记忆:上下文是租来的,记忆是自己的

智能体在两次运行之间是无状态的,每个会话从零开始。所谓记忆,实际上就是会话启动时加载的文件。上下文是工作记忆,随会话结束而消失;持久记忆在会话之外保存,下次重新加载。需要记忆的原因有四个:重复的指令、重复的探索、压缩后丢失的决定与理由、不同会话做出不同选择。记忆让指令变成惯例。

CLAUDE.md 自动记忆
谁来写 用户 Claude
内容 指令与规则 学到的经验与模式
范围 项目、用户或组织 每个仓库,worktree 之间共享
加载 每个会话 每个会话(前 200 行或 25KB)
用途 规范、工作流、架构 偏好、纠正、项目背景

CLAUDE.md 按范围从大到小加载,越近的文件越晚读取:组织策略(不可排除)、用户 ~/.claude/CLAUDE.md、项目 ./CLAUDE.md(随代码库共享)、本地 ./CLAUDE.local.md(个人,不入版本库)。

应写进 CLAUDE.md

  • 命令:怎样跑测试、构建、lint
  • 硬约束:不直接提交到 main,不改生成文件
  • 智能体难以低成本推断的事实:目录布局、归属、坑

不该写进去

  • 模型本来就知道的语言或框架知识
  • lint 或格式化工具已经强制的风格
  • 长篇说明、变更记录、任何机密

每个文件少于 200 行,用 Markdown 标题和列表,规则具体,不自相矛盾。太长时拆到 .claude/rules/,一个主题一个文件;加上 paths: 前置信息后,只有在 Claude 碰到匹配文件时才加载。

自动记忆存放在 ~/.claude/projects/<project>/memory/,每个文件标注类型:user(角色与偏好)、feedback(纠正与确认过的做法)、project(进行中的工作和代码里没有的决定)、reference(项目之外的信息)。MEMORY.md 是索引,每次加载前 200 行;主题文件只在相关时读取。常用命令:/memory(浏览、编辑、关闭记忆)、/context(看加载了哪些指令文件)、/init(生成 CLAUDE.md 初稿)、/doctor(找出不该放在 CLAUDE.md 里的内容)。

记忆有代价:每个常驻 token 都是在每次会话开头支付的租金,并与任务争夺同一个窗口。过时的记忆比没有记忆更糟,因为它会主动误导。应该像对待代码一样审查、修剪记忆,并纳入版本控制。

工具与四种扩展机制

核心工具 作用
Read 打开文件、查看状态,用得最多
Search grep 与 glob,不必全部读一遍就能找到
Fetch 拉取网页或文档,会把不可信文本带进来
Edit / Write 修改文件,第一个有后果的工具
Shell 构建、测试、git;不加沙箱时等于整台机器
Delegate 派生子智能体,返回一份摘要

选哪个工具由模型决定。

机制 解决的问题 挂在循环的哪一处
Skill 智能体应当怎样完成任务(知识与流程) 模型推理
MCP 能触达哪些外部数据与动作 工具选择
Hook 在生命周期事件上自动发生什么 任意阶段,可检查、拦截或响应
Plugin 扩展怎样打包和分发 把前三者打成一个可安装单元

以发布流程为例(准备发布、验证、发布到 GitHub、通知团队):

01Skill:按发布步骤执行
02MCP:创建 GitHub release
03Hook:测试失败时阻止发布
04Plugin:把整套配置分享出去

Skill 是一个文件夹:SKILL.md(name 与 description 决定何时被发现,正文是流程),加上 references/ 与 scripts/。会话开始时只加载描述,执行时才加载正文。可以由模型调用(描述与任务匹配时),也可以由用户以 /<skill-name> 显式调用;有副作用的流程通常应要求显式调用;描述清晰且互不重叠,能减少选错。本质上它是上下文工程。

MCP(Model Context Protocol)用标准协议连接外部服务:GitHub、数据库、监控、Figma、Slack、浏览器。调用过程有六步:Claude 认定需要一个动作;MCP 客户端调用工具;MCP 服务器处理连接;外部服务执行操作;结构化结果返回;Claude 评估结果。它几乎与本地工具相同,只是运行在另一个进程里。

Hook 在事件上触发,模型推理本身不是事件。Hook 可以运行命令、HTTP 请求、MCP 工具、提示或子智能体。

01会话开始:加载上下文、记录
02用户提交提示:校验或补充
03工具调用前:检查或拦截
04工具调用后:格式化、测试、记录
05停止前:验证测试

Plugin 把 skills、hooks、agents、.mcp.json、.lsp.json 打成一个包,带来一条命令安装、版本固定、命名空间、团队复用和市场分发。

.claude/ 目录里:CLAUDE.md 与 rules/ 是记忆;settings.json 管权限、hook 与环境变量;skills/ 与 commands/ 是工作流;agents/ 与 hooks/ 是委派与护栏。~/.claude/ 有同样的结构,作用于用户范围;项目设置优先于用户设置。

需求 用什么
遵守公司 API 规范 Skill
从 Jira 读取 issue MCP
每次编辑后运行格式化 Hook
引导多步部署 Skill
完成后发送通知 Hook 加 MCP
阻止写入生产环境 Hook 或策略
跨仓库共享全部配置 Plugin
延伸:MCP 的细节

MCP 之前,N 个 AI 客户端接 M 个服务需要 N×M 套集成。MCP 是一个开放的无状态协议:host(如 Claude Code)为每个服务器运行一个 MCP 客户端,MCP 服务器把系统能力暴露为工具。

MCP 原语 是什么 例子
tools 可调用的动作 create_issue(…)
resources 可读数据,如一个 issue、一个 schema github://issues/123
prompts 服务器提供的提示模板,由用户控制 在 Claude Code 里显示为 /mcp__github__triage_issue

三者可以协作:分诊 issue #123 时,prompt 提供组织的分诊流程,resource 提供 issue 内容,tool 拉取当前的诊断信息。

安全要点:最小权限,令牌只覆盖需要的仓库、表或频道;读写分离,写操作需要审批;不要把工具输出当指令;安装第三方服务器前先审查,它们可能带有提示注入。连接前先问:这个服务器能读什么、能改什么。

MCP 网关是 AI 客户端与多个 MCP 服务器之间的控制层,负责聚合、路由、执行策略、代理身份、观测与扩展。用户、智能体、服务器或合规规则很多时值得使用,但它本身是信任边界,有凭据过宽、丢失终端用户身份、名称冲突、日志泄露机密和单点故障等风险。2026-07-28 版规范是发布以来最大的修订:核心无状态,任何请求可落到任何实例;Mcp-Method 头让网关无需读请求体即可路由,列表结果可按 TTL 缓存;长任务(Tasks)与服务器渲染界面(MCP Apps)以扩展形式提供。

自测

课件的设计练习:每个需求该用哪种机制?

遵守公司 API 规范
从 Jira 读取 issue
每次编辑后运行格式化
引导多步部署
阻止写入生产环境
跨仓库共享全部配置

自测

下面哪一项应该写进 CLAUDE.md?

03第 3 讲

多智能体用法与 Programming 3.0Multi-agent use and Programming 3.0

要点

  1. 只改指令就能改变工作流:Superpowers 用 skill 加 session hook 规定开发流程,Caveman 用 skill、hook、MCP 和本地代理双向压缩 token。
  2. 扩展有三个方向:并行智能体换墙钟时间,子智能体换专注,长时运行换范围;agent team 只在工作需要讨论时才值得。
  3. Programming 3.0 的核心是不确定性:不要指望智能体是确定的,要让周围的系统可靠,自主程度与风险匹配。
  4. 一线数据显示,交给智能体的任务在半年内明显变大,但任务越长,无需人工介入的成功率越低。

案例一:Superpowers

Superpowers 是一个软件开发 plugin。默认智能体拿到需求就开始写代码,靠迭代修错;装上它之后,流程变成:

01人输入需求
02澄清问题
03批准设计
04写详细计划
05测试驱动开发
06审查与验证
07完成或合并分支

它由九个 skill 组成:

Skill 职责
using-superpowers 发现与调用 skill 的规则
brainstorming 把需求变成获批的设计
writing-plans 把设计拆成具体任务
using-git-worktrees 建立隔离的工作区
test-driven-development 红、绿、重构
systematic-debugging 先找根因,再提修复
requesting-code-review 对照计划审查实现
verification-before-completion 报告成功之前要有证据
finishing-a-development-branch 合并、PR、保留或清理

一个 skill 文件包含 name、description、instructions、checkpoints、references、scripts 六部分;流程型 skill 还可以规定入口条件、必做动作、禁止动作、人工审批关口、验证要求和下一个 skill。

只安装 skill,并不能保证智能体会去查看。Superpowers 的办法是加一个在会话启动时运行的 hook(SessionStart):会话启动、清空和压缩后,脚本读取引导 skill 的全文,转义为 JSON,作为 additionalContext 注入上下文。

设计问题 Superpowers 的做法
复杂行为怎样表示 小而可组合的 skill
智能体怎样记得用 由 session hook 注入一个引导 skill
上下文怎样保持可控 任务 skill 只在相关时加载
各阶段怎样衔接 每个 skill 写明关口和下一个 skill
用户怎样安装 全部打包成 plugin
是否必须有命令或 MCP 不必,需要时再加

案例二:Caveman

Caveman 压缩智能体两个方向的 token。原因有三:日志、diff 和工具输出挤占上下文;每一轮都要为 token 付费和等待;等到压缩时再裁剪会丢掉关键细节。例如 786 行测试输出压成一句「3 个测试失败:client.ts:88 处 ETIMEDOUT」。

65%报告的输出 token 降幅;skill 本身增加输入 token,整段会话的节省更少
2压缩方向:skill 改变模型怎样写,代理改变模型读到什么
5MCP 工具:压缩、按原样取回、统计、JSON 与 TOON 互转

它用到全部五种扩展机制,外加一个本地代理:skill 规定简洁文风(保留术语、命令、路径、代码、错误、数字、单位、否定;删去填充、重复、客套、含糊);命令让用户选择模式(/caveman ultra、/caveman off 等);SessionStart hook 决定并保存本会话模式、压缩后恢复规则,UserPromptSubmit hook 检测会话中途的模式切换;MCP 提供压缩与按原样取回;plugin 负责打包。本地代理按类型压缩:日志保留错误、堆栈与首尾,代码保留 import、签名与类型,diff 保留文件与 hunk 头和改动行,JSON 保留键与结构。

Hook 能拦截请求,但不能透明地改写发给 LLM 的请求,所以需要代理。代理拦截每一个请求并改变上下文;MCP 只在被调用时运行,无法改变上下文。如果自己写 harness,则可以直接做。

三种扩展方式

并行智能体 子智能体 长时运行
做法 多个独立任务,各用一个 worktree 把有界任务交给新上下文,拿回摘要 一个大任务跨很多步执行
换来 吞吐量(墙钟时间),不提高答案质量 吞吐量与专注:主线不见中间杂乱 范围:更多工作、更少干预

手动并行。 claude -w feature-payments 与 claude -w bugfix-auth 各开一个 git worktree:独立的工作目录和分支,共享仓库历史,互不触碰文件,不用 stash,不用二次 clone。三个会话时人还能掌握计划;到二十个,就需要一个「自己的克隆」:计划在人脑里,会话彼此看不见,分支要人来合并,过程没有记录、无法重跑。

子智能体 是有独立上下文、工具和权限的专门助手,用途有五:保护主上下文、限制工具与模型、跨项目复用、并行、控制成本(如用 Haiku)。自定义子智能体是一个带 YAML 前置信息的 Markdown 文件(name、description、tools、model),正文就是系统提示,放在 .claude/agents/(项目)或 ~/.claude/agents/(用户)。子智能体最多嵌套 5 层,2 至 3 层最合适;tools 中必须包含 Agent 才能再派生。

内置子智能体 用途
Explore 只读搜索代码库,禁止写和编辑,每次调用可设彻底程度
Plan 计划模式下调研,让探索留在主窗口之外
General-purpose 既要探索又要动手的复杂多步任务

Explore 与 Plan 跳过 CLAUDE.md 和 git status,以求快和省。调用方式按控制力递增:

  1. 01自然语言点名:由 Claude 决定是否委派,作用于一次
  2. 02@agent-名称:本次任务一定运行
  3. 03claude --agent 名称:整个会话采用它的提示、工具和模型
留在主对话 交给子智能体
反复往返的迭代 不会再用的冗长输出
共享上下文的多个阶段 需要限制工具或权限
快速、定点的修改 自成一体、只需返回摘要的工作
延迟敏感 并行、独立的工作;简单工作交给小模型

Agent team(实验功能,默认关闭)由一个 lead 和多个 teammate 组成:lead 派生队友、协调并汇总;每个 teammate 是独立的 Claude Code 实例;共享任务列表供认领;每个智能体有一个 JSON 邮箱,队友之间直接通信。队友不继承对话,但会自动加载 CLAUDE.md 与 skills。适合多角度审查、独立模块、竞争性假设调试和跨层开发;顺序任务、同文件编辑或依赖重的工作,应改用单会话或子智能体。

子智能体 Agent team
通信 只回报给调用者 队友之间直接通信
协调 lead 管理 共享任务列表
适合 只要结果的任务 需要讨论的工作
token 成本 较低 较高

Dynamic workflow 是一个在后台编排大量子智能体的 JavaScript 脚本,适合全库排查 bug、500 个文件的迁移、交叉核对的调研、多角度的计划。启动方式有两种:在提示里写入 ultracode,或者使用 /effort ultracode,由 Claude 自行决定。

长时运行。 /goal “npm run lint exits with zero errors” 交出一个可验证的终态,评估器在每次尝试后复查,满足条件或用完 --max-tries 时停止;「所有集成测试通过」可以,「重构代码」不行。/loop 5m “check CI, fix whatever broke” 按间隔重复同一提示,直到用户按 Esc;默认提示可写在 .claude/loop.md。

案例三:16 个智能体写出一个 C 编译器

16并行智能体,约 2,000 个会话,历时两周
~10 万行 Rust 代码,能构建 x86、ARM、RISC-V 上的 Linux 6.9
2B / 140M输入 / 输出 token,API 费用略低于 2 万美元
~99%主要测试套件通过率

协调完全依靠普通基础设施:每个智能体有独立容器和 git checkout;用 current_tasks/ 里的锁文件认领任务;实现并测试后先拉取他人代码再合并推送、解锁;新会话读进度文档恢复上下文;另有负责文档、性能、质量和去重的专职智能体;自动化测试提供进度信号。没有聊天,也没有管理者智能体。不足之处:合并冲突频繁;所有智能体都卡在同一个内核失败时,并行不再有用;16 位 x86 部分仍依赖 GCC;生成代码效率低于 GCC。

Programming 3.0 与不确定性

讲者的划分 人写什么 经过什么 变成什么
Programming 1.0 机器指令或汇编 硬件执行
Programming 2.0 编程语言 编译器 机器指令
Programming 3.0 用自然语言表达目标 智能体 编程语言,再到机器指令

越往后生产力越高,不确定性也越大。Karpathy 的 Software 3.0 是另一种划分:1.0 的程序是源代码,2.0 是神经网络权重(收集数据并优化),3.0 是 LLM 提示(自然语言)。判断边界划在 1.0、2.0、3.0 之间的哪里,是一项重要的工程能力。

不确定性并不新鲜:硬件(32 与 64 位、字节序)、环境(并发、不可靠网络)、软件(编译器版本、依赖漂移)早已存在,2.0 时代用定宽类型、内存一致性模型、幂等 API、升级前全面测试来应对。3.0 增加了非确定性 kernel 与浮点差异、生成代码时直接触碰环境、采样与 kernel 差异,以及单条提示带来的含糊输入。不确定性分布在五层:自然语言(语义)、检索与上下文(检索漂移、索引更新、截断)、模型生成(采样、软硬件非确定性)、智能体与工具循环(工具失败、环境变化)、生成的程序(生成后通常是确定的,除非运行时调用模型或工具)。

  1. 01定义:先陈述假设,含糊之处让模型执行前确认;给出结果而不是提示,即需求、不变量、约束和验收测试
  2. 02控制:把提议与执行分开,计划先验证再提交;显式管理上下文,掌握记忆、来源与检索,让过时信息失效
  3. 03验证与治理:收紧「生成、验证」循环,频繁而廉价的检查胜过最后一次昂贵审查;深一层测量,建立测试、多指标和可推理的合成负载

不要指望智能体是确定性的,要让它周围的系统可靠。自主程度应与风险匹配。

来自一线的证据:Codex 与 OpenAI 内部

交付给 Codex 的任务在半年内明显变大

处理该类任务的用户占比,%,2025 年 12 月对比 2026 年 5 月

  1. ≥ 1 人时 · 2025.1235.4%
  2. ≥ 1 人时 · 2026.0570.2%
  3. ≥ 8 人时 · 2025.122.1%
  4. ≥ 8 人时 · 2026.0525.6%
第 3 讲课件引用的 Codex 报告(2026 年 6 月)

处理整日任务的用户增加了 12 倍。2026 年上半年活跃用户增长 5 倍以上;过去 28 天用过 Codex 的个人不足 1%,组织为 17.3%,OpenAI 员工几乎全部使用。

28.6%OpenAI 用户一周内同时运行 5 个以上智能体
~2.5中位员工每天的智能体时长(小时)
~71第 99 百分位每天的智能体时长(小时),比 4 月增长 88%
3.14×2026 年 9 月研究员处,智能体工作日与人的工作日之比

2026 年 6 月以前,智能体运行时长少于人的工作量,此后超过;多数研究员有 4 个以上并行工作流;工程师人均改动行数接近 2025 年之前平均水平的 8 倍。人的角色转为规划、委派、监控、审查和整合。

任务越长,无需人工介入就成功的比例越低

无需介入即成功的任务占比,%,按人类完成所需时间分组

  1. 86%<15m
  2. 76%15–30m
  3. 69%30m–1h
  4. 61%1–2h
  5. 57%2–4h
  6. 43%4–8h
  7. 40%8–16h
  8. 23%16–32h
  9. 13%32–64h
  10. 16%64–128h
第 3 讲课件引用的 OpenAI 报告(2026 年 9 月)

委派阶梯从低到高为:聊天机器人(AI 回答,人干活)、助手(人与 AI 一起做)、智能体(人委派一整块工作)、多智能体工作者(人协调多个智能体)、系统化工作流(skill 与智能体运行流程)。课件认为 OpenAI 的员工仍处在阶梯的低处。

附:CLI 编码智能体概览(2026 年 7 月)
类别 代表
模型厂商自带 Claude Code、Codex CLI、Antigravity CLI、Grok Build、Mistral Vibe、Kimi Code、Qwen Code
平台型 Copilot CLI、Cursor CLI、Amp、Auggie、Droid、Junie CLI、Qoder、CodeBuddy
开源,自带密钥 OpenCode、Crush、Goose、Aider、Cline、Kilo、Continue、OpenHands 等
极简内核 Pi、oh-my-pi、mini-SWE-agent、gptme、Open Interpreter
维度 两端
开源与闭源 开源:Codex CLI、OpenCode、Goose、Cline、Pi;闭源:Claude Code、Copilot CLI、Cursor、Droid、Junie
绑定与自带密钥 单一厂商:Claude Code、Antigravity CLI、Grok Build;任意端点:OpenCode 75+ 提供方,Kilo 500+ 模型
沙箱与权限提示 系统沙箱:Codex CLI、Copilot CLI、OpenHands 容器;权限提示:Claude Code 与多数工具
本地与云端 本地优先、无遥测:Goose、Nanocoder、gptme;云端交接:Copilot CLI、Codex、Mistral Vibe
大而全与极简 功能最全:oh-my-pi、Claude Code;只有四个工具:Pi、mini-SWE-agent(约 100 行 Python)

自测

这类工作该留在主对话,还是交给子智能体?

反复往返的迭代
不会再用的冗长输出
快速、定点的修改
需要限制工具或权限
延迟敏感
并行、独立的工作

自测

哪一个适合作为 /goal 的目标?

04第 4 讲

智能体设计 I:循环、工具与上下文Agent design I: the loop, tools and context

要点

  1. 智能体等于模型乘以 harness;只改 harness,同一模型在两个 SWE-bench 版本上解决的任务数提高到原来的 1.7 至 2.3 倍。
  2. 工具设计就是上下文设计:工具少而正交,输出省 token,错误能指导修复。
  3. 上下文有成本、延迟和注意力三重代价,答案位于中间时准确率最低。
  4. 窗口过大时依次使用准入、卸载、变换,LLM 压缩是最后手段。

ReAct 与智能体循环

ReAct 把推理和行动放进同一个循环:思考(已知什么、缺什么、下一步做什么),行动(发出环境能执行的结构化调用),观察(环境返回事实)。只推理时没有任何东西检验推理,小错会累积成自信的幻觉;只行动时工具调用背后没有计划,模型会重复自己。ReAct 让思考引导下一次行动,让观察纠正下一次思考,直到观察足以回答问题,或停止规则结束运行。

  1. 01消息列表以系统提示和用户请求开始
  2. 02在步数上限内循环:调用模型,把回复追加到消息
  3. 03若给出最终答案,返回
  4. 04否则对每个工具调用:校验参数、执行工具、把序列化结果作为 tool 消息追加
  5. 05超过步数上限,报错退出

作为 harness 设计者,要做四件事:写工具定义;组装上下文;校验请求、检查权限并执行;可选地处理结果并管理上下文。编码智能体的三个组件要一起设计,因为它们共享一个上下文窗口:模型加循环;工具与护栏(权限、沙箱、审批);状态(当前窗口里的内容,以及步骤之间带走的东西)。

工具设计:搜索与读取

方法 靠什么找代码 适用 主要成本
glob / grep 字面名称与路径 名字已知或可猜 每次搜索消耗轮次和上下文;字面匹配找不到换了说法的代码
语义索引 代码块嵌入向量的含义;或 Aider 式 repo map(文件树加排序后的符号) 措辞与代码对不上 建立并同步索引
外部信号 堆栈、失败测试、git 历史 已有报告指向代码 只在部分任务中存在
语言服务器(LSP) 编译器的符号图:定义、引用、类型 修改须跟随引用,如重命名 每种语言一个常驻服务器,冷启动慢

实践中先用 grep,名字不够用时再上索引或 LSP。

工具设计:编辑

方法 做法 风险
整文件重写 模型重新生成整个文件 输出随文件长度增长,长文件中未改动的代码会漂移
统一 diff / patch 模型输出 patch,由工具应用 行号或上下文过时会导致 hunk 失败
搜索替换 给出精确锚点字符串和替换内容 锚点含糊、过时或空白不一致时失败
结构化 / AST 编辑 指定对符号的操作,如重命名、加参数 依赖每种语言的工具,可表达的编辑有限,但构造上不会产生非法语法

工具设计:执行与其他

Shell 是最强也最危险的工具:一次调用可以串联、过滤、循环和重试,能触及文件系统、网络、包管理器和二进制,文件与进程在调用结束后仍然存在,shell 能做的智能体都能做。设计时要考虑隔离(在哪里运行、能触及什么)、失败信号(智能体能据以行动的错误)、输出(够用但不过量)、时长(长时与后台进程)和预算(何时停止重试并交还)。另有五类常用工具:记忆与笔记(计划在压缩后仍在)、子智能体(探索后返回候选清单,而不是 40 次读文件)、网页搜索与抓取(先读已安装的源码,再查网络)、浏览器与视觉反馈(截图回传)、向用户提问(一个廉价的问题胜过一个自信的错误补丁)。

少而正交功能重叠的工具会让模型犹豫不决
专用而非通用search_orders(customer_id) 胜过一个原始的 run_sql
输出省 token截断、分页、摘要;工具设计就是上下文设计
错误要能教人返回修复提示,而不只是「参数无效」
默认幂等尽量做到可以安全重试

专用的智能体接口比只给 shell 解决更多问题

SWE-agent 消融实验,GPT-4,解决率,%

  1. 专用 SWE-agent 接口18%
  2. 保留完整交互历史15%
  3. 整文件查看12.7%
  4. 只给 shell11%
  5. 无专用编辑器10.3%
第 4 讲课件(SWE-agent 消融)

从提示工程到目标工程

时期 名称 问题 关注
2023–2024 提示工程 怎样指示模型 措辞、示例、输出格式
2025–2026 上下文工程 模型应看到什么 检索、记忆、历史、压缩
现在 harness 工程 智能体应怎样运行 循环、工具、沙箱、重试、停止
下一步 目标工程 什么算成功 目标、标准、约束、权衡
提示技巧 做法 何时用 何时换下一种
零样本 只给指令 任务常见,格式能用文字说清 规则说不清时,用少样本
少样本 指令加几个示例 输出形状特殊,规则更容易示范 需要步骤时,用思维链
角色与人设 给一个角色 语气或判断重要,受众特定 需要步骤时,用思维链
思维链 先写推理步骤,最后给答案 任务确有步骤,错误源于跳步 有多条路径时,用思维树
思维树 分支、打分、剪枝 多条路线可行,打分便宜 只有一个正确答案时,用自洽
自洽 多次采样后投票 有唯一答案且错误代价高;票数不够(如 3/5)时转人工 阶段可拆时,用链式
提示链 每次调用一件事,校验交接 工作分阶段且每段可校验;不合格只重试该阶段 在调提示本身时,用元提示
元提示 让模型改写自己的提示 有评测集可打分 收益停滞时,重新审视选择

四条通用原则:从简单开始,按需加上下文;分区(上下文、指令、工具、输出规范,按「指令、分隔符、数据」排列);具体而简洁,花巧措辞没有用;把大任务拆小,不要一开始就堆复杂度。提示建议因模型而异,换模型就要重新调。部分技巧已经过时。

上下文工程:上下文是有限资源

Karpathy 的定义:上下文工程是为下一步恰好填入所需信息的艺术与科学。上下文有三重代价:成本(每一步都重发整个窗口)、延迟(提示越大,prefill 与 decode 越慢)、注意力(窗口越满,召回越差,中间部分最容易被忽略)。

答案位于上下文中间时,准确率最低

答案在 20 篇文档中的位置与回答准确率,%

  1. 76%第 1 篇
  2. 61%第 5 篇
  3. 55%第 10 篇
  4. 59%第 15 篇
  5. 71%第 20 篇
Liu et al., “Lost in the Middle”, TACL 12 (2024),转引自第 4 讲课件

长度同样有代价:Chroma 的 Context Rot 测试中,输入从 1K 增至 400K token,简单查找的准确率降到 73%,加入干扰项后降到 46%。

一轮对话的示意 token 预算:系统提示约 2K,工具定义约 6K,项目环境约 8K,检索内容约 25K,消息历史约 80K 且持续增长。窗口过大时有四种手段,从预防性、无损到有损、不可逆依次为:

前三种手段在不做摘要的情况下,把上下文缩小 75% 至 98%

课件示例,处理前后的 token 数

  1. 准入 · 原始 DOM48,000
  2. 准入 · 只留抽取结果900
  3. 卸载 · 60 个工具 schema42,000
  4. 卸载 · 索引加 3 个 schema3,100
  5. 变换 · 保留全部结果96,000
  6. 变换 · 只留最新状态24,000
第 4 讲课件示例
手段 做法
准入 在入口把关:定向检索(只取字段,不取整篇)、整形工具输出、整形不了再截断、把原始数据交给子智能体隔离处理
卸载 需要时再加载:渐进式工具定义、工具搜索(保留索引,按需取 schema)、工具输出返回句柄、任务清单写在磁盘、持久记忆只留小索引
变换 有选择地丢弃历史:去重(每个对象只留最新状态)、观察遮蔽(去掉 N 步之前的工具结果)、滑动窗口(只留开头和最近几轮)
压缩 最后手段,用 LLM:滚动摘要、到上限时全量摘要、自动记忆把关键事实存到窗口外。要为输出预留空间,保留系统前缀,压缩后重新注入关键事实

上下文失败有五种,命名之后修法就明显了:投毒(幻觉进入窗口,之后被当作事实引用)、分心(历史太长,智能体开始模仿自己过去的动作)、混淆(无关的工具和文档把答案带偏)、冲突(新旧信息矛盾却同时保留)、漂移(真正的目标被埋没,换成了附近的子目标)。

同一个模型只改 harness,两个基准上解决的任务数都明显增加:SWE-bench Verified 由 43/169 增至 72/169,SWE-bench Pro 由 31/316 增至 72/316。改动是压缩旧工具输出、保持最近的观察可见、检测重复与停滞、卡住时介入。一部分看似「模型失败」的问题,其实是上下文和控制循环的失败。
延伸:ReAct 之外

ReAct 每一步都循环;Reflexion 在失败后循环(尝试、评估、反思、重试);Plan-and-execute 在偏离计划时循环(计划、执行、重新计划);树搜索不循环,一次展开多个分支并行探索,只留最好的一条。

自测

这些做法属于哪一种上下文管理手段?

只取需要的字段,不取整篇
保留工具索引,按需加载 schema
每个对象只保留最新状态
到上限时用 LLM 总结历史
把原始数据交给子智能体处理
去掉 N 步之前的工具结果

自测

「历史太长,智能体开始模仿自己过去的动作」属于哪种上下文失败?

05第 5 讲

智能体设计 II:多智能体系统Agent design II: multi-agent systems

要点

  1. 多智能体不是默认选项;拆分的理由是专门化、隔离、并行和上下文管理。
  2. 每种架构都回答三个问题:谁来协调、怎样分解、怎样通信;真实系统都是混合的。
  3. 子任务要写清目标、边界、输出和完成判据;只有省下的工作超过协调开销,并行才有用。
  4. 通信是分布式系统问题:控制与内容分开,用幂等键和回滚路径应对超时。

三张图与八种架构

每种架构背后都有三个问题:控制图(谁来协调:一个主管、一个层级,或没有人;运行中是否交接)、任务图(怎样分解:规划者预先拆分、竞价,或由局部规则自发形成)、通信图(怎样通信:直接消息、广播,或共享工作区)。

类别 架构 核心思想 适合 弱点
集中式 主管与工人 一个规划者,多个执行者 可拆分、可并行的子任务 主管成为瓶颈,它的上下文增长最快
集中式 层级式 主管管理子主管 本身可递归分解的任务 错误逐级放大;每个边界传多少上下文
集中式 流水线 / DAG 每个阶段喂给下一个,边界有类型化契约 阶段清晰、有序 错误向下传播,无法回头;最容易调试
去中心 市场与拍卖 智能体按能力、成本、延迟竞标 动态分配,任务落到最便宜的合格者 竞价是自报的,可能夸大能力
去中心 黑板 通过共享状态(数据库、文件系统、git 仓库)协调 围绕一个共享产物 状态过时;一致性、并发、来源、版本、回收
去中心 委员会与辩论 先各自作答,再由裁判或投票裁决 判断类任务 群体思维:同一模型、同一上下文,盲点相同
去中心 蜂群 无固定协调者,直接协商 局部协商 O(n²) 条消息,冲突难解,产品中少见
混合 动态拓扑 运行中增删或重连智能体 结构未知;简单任务保持便宜 每次形状不同,失败难复现

真实系统都是混合的。例如:规划智能体按动态任务 DAG 分派给编码、调研、测试、审查智能体,大家共享一个 git 仓库,需要时重新规划。这同时用到了主管、层级、共享内存和流水线。

01规划智能体
02动态任务 DAG
03编码 · 调研 · 测试 · 审查
04共享 git 仓库
05必要时重新规划

任务分解

分解的维度有六种:按数据(每个智能体处理一部分文档)、按专长(安全、性能、正确性、法律)、按阶段(计划、实现、测试、审查)、按假设(各自调查一种解释)、按工具(网页、数据库、代码执行)、按权限(不同管理域)。例如一个 200 个文件的 PR,先按文件拆,再按安全和性能拆。

一个好的子任务要写清:目标、输入与相关上下文、边界与排除项、可用工具与权限、输出 schema、完成判据、预算与期限、依赖。

差的子任务

  • 「调研存储系统」

好的子任务

  • 「找出 2026 年发表的存储相关论文,返回标题、日期、系统贡献、评测规模和一手来源链接,排除数据库查询优化」

粒度需要权衡:太大则缺少并行;太小则调度与通信开销占主导。多智能体耗时约等于规划时间加关键路径时间加通信时间加合并时间。只有省下的串行工作超过这些开销时,并行才有用。例如把 20 次一行查询合并成 4 个子任务。

分解可以是静态的(执行前已知,如总结 5 个 PDF),也可以是动态的(发现死链就派生查询任务)、递归的(审查智能体为每个子领域再派生子智能体)、机会式的(空闲智能体认领下一个未标注文档)。动态分解必须设派生上限、预算、深度上限和终止条件,否则委派会递归爆炸。

常见分解失败 例子
重叠 两个智能体总结同一篇论文
缺口 「2020–2023」加「2025–2026」,漏了 2024
隐藏依赖 定价需要规模估算,运行时才发现
无法合并 一个返回自由文本,一个返回 JSON
丢失全局上下文 每一节都没问题,整份报告自相矛盾
掉队者 六个智能体 20 秒完成,一个用了 4 分钟

通信

维度 选项 经验法则
拓扑(谁能和谁说话) 主管与工人、点对点、网状 镜像任务的依赖关系
介质(信息怎样交换) 消息传递(队列或总线)、共享内存(如共享任务列表)、文件与产物(含数据库) 每条链路一种介质
信道(信息怎样传递) 点对点、广播、发布订阅、共享黑板、请求响应、产物传递 只有所有人都必须知道时才广播
格式与语义 自然语言加控制字段 按字段路由,不按文字路由

自然语言灵活但含糊,结构化消息易校验但表达力弱,实用的做法是两者都用:消息里带 task_id、type、status、claim、confidence、evidence、artifact 等字段。把控制和内容分开,运行时认识的操作有 DELEGATE、QUERY、REPORT、HANDOFF、UPDATE、CANCEL、ACK、ERROR、COMPLETE。这样运行时无需问 LLM 消息是什么意思,就能路由、重试和停止。

通信是困难的分布式系统问题。智能体 A 让 B「购买 8 个 GPU 实例」,网络超时没有回复:B 执行了吗?重试还是放弃?至多一次还是至少一次?能否做到恰好一次?需要用 task_id 做幂等键,准备补偿与回滚路径,并想清楚重复购买由谁买单。

多智能体系统继承了分布式系统的全部难题:并发与非确定性、不可靠网络(延迟、丢包、乱序、重复)、没有全局时钟、部分失败(分不清慢的智能体和死的智能体)、副本状态一致性、调试与可观测性(时钟漂移下的分布式日志)。另外还要解决调度(谁下一个运行、运行多久)、资源分配(模型、CPU)、状态管理(检查点、记忆、来源、版本),而且没有预定的请求流。黑盒 LLM 让情况更难:

问题 表现
信息丢失 摘要丢掉了执行者知道的内容
上下文污染 关键信息被埋没
过时信息 B 在 X=5 之后仍按 X=3 行动
信念冲突 A 说安全,B 说有漏洞
所有权丢失 每个智能体都以为别人负责
通信环路 A 问 B,B 问 C,C 问 A
难以诊断 说不清为什么失败

A2A 与 MCP

A2A 是智能体之间的协议。每个 A2A 服务器在 /.well-known/agent-card.json 发布一张 Agent Card,写明身份、技能、端点、能力(如流式)和认证方式。三个抽象:消息(客户端与智能体之间的一轮)、任务(有 ID 和生命周期的有状态工作单元)、产物(任务的输出)。后续消息加入同一个任务。任务生命周期为:提交、工作中,可暂停于「需要输入」或「需要认证」后恢复,终态为完成、失败、拒绝或取消。跟踪长任务有三种方式:轮询(短任务)、流式(交互输出)、推送通知(数小时的任务)。A2A 只标准化通信,不负责编排:委派、拆分和停止仍由 harness 决定。

01提交
02工作中
03需要输入或认证时暂停,之后恢复
04完成 · 失败 · 拒绝 · 取消
MCP A2A
主要抽象 能力 / 工具 智能体 / 任务
关系 智能体到服务 智能体到智能体
发现 工具、资源、提示 智能体能力
工作单元 一次工具调用 长时任务
内部状态 能力接口 最好不透明
类比 设备或 API 接口 服务间 RPC

一个 A2A 远程智能体内部可能调用二十个 MCP 服务器。MCP 由 host 而不是模型决定暴露什么。

设计原则

  1. 01先问是否真的需要多智能体:单个智能体够用时,多智能体通常只增加开销
  2. 02按任务依赖决定拓扑,尽量减少通信
  3. 03找出信息丢失点:汇总节点就是细节丢失的地方
  4. 04划定失败隔离边界,确保系统不会停滞

稠密网状结构很少是好的默认选项。更多通信会增加上下文压力,却不一定增加有用信息。

自测

这类任务最适合哪种架构?

可拆分、可并行的独立子任务
阶段清晰、有固定顺序
需要判断的任务
把任务动态分配给最便宜的合格者

自测

两个智能体分别负责「2020–2023」和「2025–2026」,结果漏了 2024。这是哪种分解失败?

06第 6 讲

智能体设计 III:记忆与可靠性Agent design III: memory and reliability

要点

  1. 记忆的每一环都是策略决定:写不写、存成什么、放在哪里、何时取用、怎样归纳、何时遗忘。
  2. 记忆需要有效时间和来源,遗忘是一等操作。
  3. 每步成功率 95% 时,50 步的运行只有 8% 完全无错;误差会累积,也会传播。
  4. 故障来自任务描述、harness、模型、工具和环境五处,各有对应的设计手段。

记忆的六个设计问题

01写入还是跳过:值得保留吗
02编码与组织:应变成什么形式
03存储:放在哪里
04检索:这个任务需要它吗
05反思与归纳:能得出什么更广的结论
06保留、更新、删除:它仍然有效吗

写入。 记录每一次交互,召回高但噪声大;有选择地写入,精度高。依据可以是用户明确要求、确定性规则、小分类器或定期的 LLM 复查。

组织形式 例子 特点
原始事件 「我们把服务从 vLLM 迁到了 SGLang。」 保真,但大而冗余
非结构化摘要 「用 SGLang 做模型服务。」 紧凑,可能丢失上下文
结构化状态 serving_engine = SGLang 可查询,受 schema 约束
知识图谱 Project → USES → SGLang 实体相连,能表达随时间的变化
存储后端 例子 擅长
纯文件 CLAUDE.md、草稿本 便于查看、diff、搜索
键值或关系数据库 Redis、SQLite、Postgres JSONB 精确查找、过滤、事务
向量库 pgvector、Chroma、Pinecone 精确或近似的相似度搜索
图数据库 Neo4j、FalkorDB(Graphiti) 关系查询与多跳遍历
使用时机 做法 优点 缺点
自动 每轮都搜索、调用 LLM、写入 可预测、简单 增加延迟和无关上下文
运行时控制 满足条件才搜索或写入 有选择、高效 需要规则或分类器
模型控制 把 search、add、update、forget 作为工具交给 LLM 按需 可能漏读漏写

很多系统混合使用,读和写的策略可以不同。

检索。 基本流程是查询、向量搜索、取前 k 条、放进提示。但语义相关只是信号之一,还要看范围(同一用户、项目、实体或任务)、重要性(漏掉或带入的代价)、有效性(此时此任务是否成立)、来源(出处、置信度、证据)。

反思。 多次问到 vLLM、SGLang、TRT-LLM 和 LLM 调度,可以归纳为「对 LLM 推理系统有持续兴趣,置信度中等」。归纳适合在积累足够新证据后(每 N 个事件或上下文满时)、事实冲突或重复时进行,尽量放到后台任务。

遗忘是一等操作。 原因有过时、错误或冲突、隐私与安全、存储与检索成本。手段有标记无效、永久删除、TTL 过期、分层并从活跃记忆中逐出。记忆需要有效时间和来源:2026 年 4 月「用 vLLM 服务」,6 月被「用 SGLang 服务」取代,并注明来源是第 28 段对话。

归属。 由智能体自有(harness 里的文件:CLAUDE.md、草稿本、任务笔记,由 harness 存盘),或由专门的记忆系统提供(智能体调用的服务,记忆成为跨智能体、跨会话共享的 API)。

记忆系统 类型 输入与检索
Mem0 以事实为中心 按用户、智能体或运行划分范围;向量搜索加过滤,可选图记忆
Graphiti 时间感知的知识图谱 从对话片段中抽取实体和带有效期的事实;混合语义、关键词与图搜索
supermemory 画像、记忆与文档 同时维护用户画像、记忆和文档,关联来源与时间
记忆的失败模式 表现
检索遗漏 相关记忆存在却没找到
上下文污染 太多无关记忆进入上下文
记忆幻觉 把推断存成事实:「在哈佛读书」变成「哈佛访问学生」
过时 旧事实覆盖新信息
隔离失败 记忆越过用户边界
过度泛化 一次事件变成长期偏好
持久化提示注入 不可信内容日后以指令的形式返回
无限增长 规模随寿命增长,检索成本上升、质量下降

评估记忆看四个方面:检索(精度、召回)、写入与更新(精度、召回、过时记忆比例)、治理(删除合规、范围隔离)、系统(延迟、token 开销、存储增长)。端到端基准主要测智能体能否在长对话历史上回忆与推理,覆盖召回、时间推理、更新、偏好和拒答:LoCoMo(ACL 2024,10 段长对话,1,540 题)、LongMemEval(ICLR 2025,5 种记忆能力,500 题)、BEAM(ICLR 2026,最长 1000 万 token,2,000 题)。记忆栈有两种形态:独立记忆层(智能体运行时、Mem0 或 Letta 等记忆管理、向量 SQL 图或对象存储),或记忆放在 harness 里(运行时自己管理,存为 Markdown 文件)。

可靠性:误差会累积

每步成功率 95% 时,50 步的运行只有 8% 完全无错

运行全程无错的概率,%,按轨迹步数,假设各步独立

  1. 95%1 步
  2. 77%5 步
  3. 60%10 步
  4. 36%20 步
  5. 8%50 步
第 6 讲课件(0.95 的 n 次方)

只有每一步都成功,运行才算成功;而且错误会传播,真实运行比这个估算更糟。故障可能源自五处:任务描述、harness、模型、工具层、环境。

失败 例子 修法
目标含糊 「修复登录 bug」,修错了三个中的一个 写明文件、症状和复现方法
代理目标 「让测试通过」,删掉了失败的测试 禁止改测试,审查 diff
未说明的约束 「加快搜索」,破坏了公开 API 写明哪些不能改
没有完成定义 「整理解析器」,一直重构不停 给出退出测试和停止规则
目标冲突 「最小改动,覆盖所有边界」,悄悄放弃了边界 显式排序目标
任务描述:把「完成」写成测试预先给验收测试,列出不能改的东西
harness:给每次运行设界限制步数、成本和时间;检查点与回滚
模型:要求证据每个结论都要有证据,做验证,必要时换更强的模型
工具:大声失败类型明确的 schema,错误与空结果分开
环境:固定并隔离新建且固定版本的沙箱,偶发失败先重试再判断

我们对大规模运行的智能体仍然了解不多,正式的最佳实践也很少。

自测

这些故障源自哪里?

要求「让测试通过」,结果删掉了失败的测试
没有步数或成本预算,跑了 200 步毫无进展
说「测试应该过了」,却什么都没运行
日期没有时区,任务差了 8 小时
闰年导致失败

自测

每步成功率 95%,各步独立,20 步全程无错的概率约为?

07第 7 讲

智能体设计 IV:评估Agent design IV: evaluation

要点

  1. 评估对象从基础模型变成了模型、提示、工具与 harness 的整体,评分依据变成测试和环境状态。
  2. 八个代表性基准各测一种环境:问答、函数调用、网页、桌面、代码仓库、客服、终端和模拟公司。
  3. 难点在于数据泄漏有四层、单轮交互奖励猜测、只看成功率会忽略成本和安全。
  4. 基准饱和得越来越快;真实的智能体要同时看能力、成本和速度。

简史与评估目标

评估智能体有两条路:组件级(规划与任务分解、记忆的抽取整合检索、工具的发现选择与参数化、错误恢复)和端到端(成功率、单任务成本、完成时长)。基准的演进方向是:范围更大、指令更不具体、场景更真实、题目更新。

时期 代表基准 关注
2018 年前 Penn Treebank、WikiText、LAMBADA、SQuAD 语言建模与窄任务
2018–2019 GLUE、SuperGLUE、ARC、HellaSwag、WinoGrande 迁移学习与通用理解
2020–2022 MMLU、BIG-bench、GSM8K、MATH、HumanEval、TruthfulQA、HELM 基础模型能力
2023–2024 MT-Bench、Chatbot Arena、IFEval、LongBench、MMMU、GPQA、AgentBench、WebArena、GAIA、SWE-bench、OSWorld、τ-bench 智能体与工具、长上下文、多模态
2024–2025 MMLU-Pro、LiveBench、LiveCodeBench、FrontierMath、Humanity’s Last Exam 难度、鲁棒性、新鲜度
2025–2026 GDPval、BrowseComp、Terminal-Bench、ARC-AGI-3 范围更大、更接近真实使用
评估目标 代表基准 成功的含义
预测文本 PTB、WikiText 对观测文本给出高概率
给出正确答案 MMLU、GSM8K、GPQA、HLE 与已知答案一致
给出受偏好的回答 Arena、AlpacaEval、MT-Bench 获得人或模型的好评
写出能运行的代码 HumanEval、LiveCodeBench、SWE-bench 通过可执行测试
完成交互任务 WebArena、OSWorld、τ-bench、Terminal-Bench 达到要求的环境状态

指标方面:早期用困惑度(留出文本上平均负对数似然的指数,越低越好)、准确率或 F1、偏好胜率。能力用 pass@k(k 次中至少一次通过)与 pass^k(k 次全部通过,由 τ-bench 提出)。成本主要是 LLM 费用,常被忽略的有工具调用和缓存未命中。延迟也不只是 LLM 的延迟。

基准评测循环:对每个任务,把环境重置到初始状态;在未结束且未超预算时,观察环境,由智能体根据指令、观察、历史和工具选择动作,环境执行;最后由评估器根据最终答案、最终环境状态和轨迹打分。

八个代表性基准

基准 智能体所在环境 典型动作 评分依据 要点
GAIA 网页、文件、代码工具 搜索、看文件、计算 简短的最终答案 466 道人写题,分 3 级(≤5 步、5–10 步、任意长);评整个智能体系统;不评发邮件、订票这类动作
BFCL 函数与 API 接口 结构化函数调用 调用、参数和结果状态 用 AST 或执行检查;常见错误是编造 ID(应向用户询问)和无关调用;应看分类得分而非总分
WebArena 自托管网站 点击、输入、导航 网站或后端状态 812 个任务,购物、管理、Reddit、GitLab、地图、维基;观察为无障碍树;Verified 版去掉 LLM 裁判,改为对 HTTP 轨迹的确定性检查
OSWorld 完整桌面虚拟机 鼠标、键盘、应用操作 文件、应用和系统状态 369 个任务,观察为截图;OSWorld 2.0(2026)有 108 个长流程,常超过 1 小时,约 27 个检查点给部分分
SWE-bench 软件仓库 查看、编辑、运行测试 补丁能否通过测试 变体有 Verified(人工核验)、Lite(300 题)、Multilingual(9 种语言)、Multimodal、Pro(更难、多文件)
τ-bench 客服 API 与对话 与用户对话、调用 API 数据库状态与回复 用户由 LLM 模拟,智能体受航司政策约束;奖励为动作分乘输出分;只读调用可以不同,意外写入即失败
Terminal-Bench 隔离的终端容器 任意 shell 命令 任务专属的验证测试 编程、运维、数据处理、训练模型、安全、科学流程;TB 2.0 有 89 题,TB 4.0 剔除饱和题后为 66 题,超时 8 小时
TheAgentCompany 模拟的软件公司 用网页应用、写代码、和同事沟通 流程检查点与最终状态 175 个任务,涵盖软件、项目管理、数据科学、人事、财务;部分分 = 0.5 × 得分比例 + 0.5 × 是否完全完成

Terminal-Bench 介于 SWE-bench 与 OSWorld 之间:通过容器里的 shell 行动、观察终端输出,任务从配置、调试、修复到构建,不需要预测鼠标坐标,专测长程推理与系统交互。pass^k 比 pass@k 严格得多:前者要求 k 次独立运行全部成功,后者一次成功即可。

评估为何困难

训练泄漏任务或其人工修复出现在训练数据里
评估时泄漏智能体上网搜到并抄了未来的修复
环境泄漏沙箱暴露了未来的提交或隐藏测试
基准过拟合提示与脚手架在公开测试集上调过

智能体表现约是 LLM、提示、脚手架、工具、检索器、记忆和环境的函数,任一组件都可能带入基准信息,例如微调用了基准答案作为轨迹、RAG 语料里索引了答案、记忆里存着以前的尝试、研究者反复看失败用例来调系统。因此「模型没有在测试集上训练过」远远不够。评估智能体需要真实工具,而真实工具扩大了泄漏面。

单轮交互。 多数基准只给一条完整的指令,提示进、最终状态出,中间没有用户。真实工作是含糊的、会修改、会被打断的。单轮评分奖励自信的猜测,因为问一个澄清问题要花步数又不得分。应当补测:目标不明确时是否提问、中途被纠正后是否重新计划、能否跨轮次记住约束。

其他挑战:只看成功率不够(200 步、40 美元的运行与 12 步、0.30 美元的运行不可同日而语);非确定性让单次运行的分数只是噪声;没有任何机制惩罚途中删文件、发邮件或花钱;只看结果会放过侥幸或不安全的运行,而轨迹匹配又会误判合理的不同路径。

前沿模型追上基线的时间越来越短

从基准发布到前沿模型达到所标基线所用的月数

  1. GLUE(2018)· 人类水平 87.114 个月
  2. MMLU(2020)· 专家水平 89.839 个月
  3. GPQA Diamond(2023)· 博士专家 69.710 个月
  4. SWE-bench Verified(2024)· 33% → 95%22 个月
  5. ARC-AGI-2(2025)· 普通人 6011 个月
  6. ARC-AGI-3(2026)· 0.5% → 62.7%6 个月
第 7 讲课件

基准饱和得很快。截至 2026 年 9 月,SQuAD、GLUE、SuperGLUE、MMLU、MATH、HumanEval、Chatbot Arena、MT-Bench、WebArena、SWE-bench Verified、GPQA Diamond、MMMU、OSWorld 等已饱和;FrontierMath、Humanity’s Last Exam、ARC-AGI-2/3、Terminal-Bench、GDPval、SWE-bench Pro、Remote Labor Index、OSWorld 2.0 仍未饱和。饱和指前沿达到人类基线,或顶尖模型之间拉不开差距。

维度 过去 现在的前沿
评估对象 基础模型 模型、提示、工具与 harness 的整体
交互 静态、单轮 有状态、长程
评分者 精确匹配或似然 测试、环境状态、人或裁判模型
数据集 固定、公开 新鲜、隐藏、动态或防污染
主要指标 平均准确率 成功率之外,还有可靠性、质量、成本、延迟
主要关注 跨样本泛化 在真实约束与安全要求下稳健完成
真实世界的智能体要同时看能力、可用性、成本和速度。课件用帕累托支配排名:若 A 在所有指标上都不差于 B,且至少一项更好,则 A 支配 B;第一名就是帕累托前沿。

自测

同一任务独立运行 4 次,只有 1 次成功。pass@4 与 pass^4 分别如何?

自测

这些基准按什么评分?

GAIA
SWE-bench
τ-bench
OSWorld

08第 8 讲

智能体设计 V:降本、提速与 harness 架构Agent design V: cost, speed and harness architecture

要点

  1. 成本等于用户、会话、轮、步、token 与单价的乘积;中间三项靠缩短轨迹压低,单价靠缓存、批处理和路由压低。
  2. 缓存读取占 token 的绝大部分;留在上下文里的 token,之后每一步都要再付一次钱。
  3. 每项节省都有反作用,要在同一批任务上测净效果,并给每个任务设上限。
  4. 完成时间由关键路径决定;harness 架构从单体、模块化到微内核,职责逐步从代码移到服务。
01每任务轮数
02每轮步数
03每步 token 数
04每 token 价格

减少轮数与步数

本讲只讨论 LLM 成本,不含其他算力成本。

第 k 轮要重读前 k−1 轮,所以总成本随轮数平方增长。课程统计学生的 Claude Code 使用:单提示会话占 68%(作业 1)和 75%(作业 2),少数会话超过 100 轮。用户回来追问,是因为没有计划、提前停止或从未检查。对策是预先确认目标与计划、把任务拆成各带完成判据的子任务、交付前自行验证,目标是不需要用户介入就完成任务。

多数轮次只有几步(主要因为 effort 设为 medium 或 high),也有接近 1,000 步的。每次模型调用都会重读全部上下文,所以调用越少越省:把独立调用合并到一步(一步读五个文件而不是五步)、复用以前成功的计划和 skill、开始时一次读入所需文件。相关研究有技能库(Voyager、SkillRL)、经验提炼(ExpeL、ReasoningBank)、计划模板缓存、持久对话记忆(Mem0、LightMem、SimpleMem)。任务重复出现时复用才划算,记忆维护和过时条目可能抵消节省。

减少每步 token

97.6%作业 1 中缓存读取 token 的占比
208K / 301K主智能体每步上下文中位数(作业 1 / 作业 2)
~80K子智能体每步中位数,p90 约 200K
1 : 10 : 50缓存读取、输入、输出的典型价格比

输出约比新 prefill(缓存写入)小 5 倍,新 prefill 约比缓存读取小 100 倍;上下文增长很快,第 500 步左右达到 650K 至 670K。留在上下文里的 token 会在之后每一步再付一次钱。

减少输入 做法
丢掉过时的 截断过时结果;压缩历史;遮蔽已用过的工具输出;把旧轮次总结为状态
缩小进来的 压缩观察,只保留错误而不是完整日志;大输出存文件,只传路径
只加载需要的 选择性检索,只给相关工具与记忆;把探索隔离到子智能体,只返回摘要

相关研究:ACON 把峰值上下文降低 26% 至 54%;LLMLingua 最多减少 20 倍 token,但压缩只在长提示上划算;MemGPT 把上下文当作快速内存;用代码过滤 MCP 结果,150K 降到 2K;工具搜索减少 85% 工具 token,程序化工具调用减少 37%。TRACE 发现摘要会导致返工。

减少输出:在提示里写明长度、格式和跳过什么(「不超过 100 字」「只返回 JSON」「不要复述问题」);在 API 里设 max_tokens(可能把答案截在半句,而且推理本身可能用完上限);要求只含必要字段的结构化输出(用枚举限制可选字段,工具调用周围的文字都是纯成本);按步骤调整推理 effort(查找与格式化用 low,规划与调试用 high)。注意严格格式可能损害推理。

压低单价

缓存加批处理可把输入单价降到基础价的 5%

相对基础输入 token 的价格倍数,Claude API

  1. 输出 token5×
  2. 基础输入 token1×
  3. 批处理输入0.5×
  4. 缓存输入0.1×
  5. 批处理加缓存输入0.05×
第 8 讲课件

保持前缀稳定(系统提示、工具、早期历史),能等的工作走批处理(评测、回填、批量任务)。模型路由有三种:预先选定(用偏好数据训练的路由器,也可选择智能体角色,如 RouteLLM、MasRouter)、失败后升级(先用便宜模型,检查不通过再换大的;检查可以是学习的打分器、自我验证或执行反馈,如 FrugalGPT、AutoMix、EcoAssistant)、每步重新选择(按历史和预算路由,由编排器把模型当工具调用,如 ToolOrchestra)。难点是:便宜模型的一个规划错误可能浪费后面很多步。系统层面的降价手段留到后续课程:MoE、量化、剪枝、蒸馏、针对负载微调;推测解码、KV cache 优化、更好的调度;更快的 kernel 与专用加速器。

每项节省都有反作用

手段 反作用
压缩 被丢掉的文件要重读,摘要会改写缓存
路由 便宜模型的坏计划会增加步数或导致失败
子智能体 每个子智能体都要重读共享文件和指令
推测 猜错会浪费 token,并争抢同一批工具

净节省等于总节省减去反作用,要在同一批任务上同时测量。给每个任务设上限(示例:10 美元、80 次模型调用、15 分钟工具时间、每步重试 2 次),在验证通过、N 步内没有新测试通过、同一错误重复或触及上限时停止,并附摘要交接。上限可按成功任务 p95 的 2 倍设定。带摘要停下来的任务,比失控的任务便宜。

  1. 01步骤每次都一样:让 LLM 写一次脚本,之后直接运行
  2. 02输入格式固定:用正则、解析器、模板,每次调用零成本
  3. 03标签或分数范围窄:训练一个小分类器
  4. 04流程固定、几乎不需要推理:把流程脚本化,只在需要推理的步骤调用 LLM

让智能体更快

完成时间由关键路径决定,而不是所有步骤之和。更快通常也更便宜,但不总是:小模型可能要更多步,并行会消耗更多 token。

加速 LLM 服务前面所有降本手段都能减少延迟:更少的轮、步、token,更便宜的服务
改进编排异步执行(工具运行时开始下一步)、持久会话(同一个 shell 或浏览器跨步保持打开)、流式与流水线(LLM 回复未完成就开始工具调用)、服务同址部署
加速工具构建、测试、页面加载可能比模型调用还慢:缓存工具结果、把重计算放到服务器、换更快的工具、对挂起的调用设超时;调模型之前先测每步的工具时间
并行一步内发出多个独立的工具调用;把独立子任务交给并行子智能体,再合并摘要;共享状态需要合并步骤
推测动作便宜模型预测下一个动作,在主模型思考时先执行;猜对省掉等待,猜错丢弃,代价是一次调用;适合猜中率高、动作可撤销的情形

推测的对象从下一个工具(SPORK)、工具加参数(PASTE)、任意动作,到多条分支(B-PASTE)和整段已执行的链。预测来源有模型(小模型草拟)、自推测(同一模型的早期分支)、历史(过往轨迹,如 PASTE 根据 search 之后通常是 visit,从搜索结果填入 URL 提前执行)。开放问题:在有限的 GPU、CPU 和 API 预算下,怎样调度推测调用,使节省的关键路径时间超过浪费的工作。

优化是一个循环:运行并记录每次调用、token、工具与等待;测量成本与延迟的来源;一次只改一处(压缩、路由、缓存或并行);在同一批任务上重新评估成功率、花费和 p95 延迟;重复。

Harness 的三种架构

维度 单体 模块化 微内核
设计原则 全部集成在一个运行时 通过接口抽象,一个控制器 最小内核加外部服务
替换组件 困难 容易(如 Docker 换成 Firecracker 只换一个 provider) 协议匹配时容易
执行隔离 可选 可选 架构上的重点
部署 通常在一起 可在一起或分开 通常独立
独立扩展 有限 可以 强
通信开销 低 低到中 可能更高
典型用途 独立智能体 智能体框架 多智能体基础设施
优点 实现与调试简单,状态易共享 职责清晰,便于测试,第三方可接入 服务独立扩展,故障隔离,基础设施共享
缺点 组件紧耦合,难以共享基础设施 控制器仍掌管生命周期,协调逻辑变复杂 失败模式更多,端到端调试更难,需要标准协议

以运行一段 Python 为例:单体直接在本地执行,跳数最少但难以隔离;模块化调用 SandboxProvider.run(code),换实现不换智能体;微内核把请求发给执行服务,由它负责分配、隔离和沙箱生命周期。职责从代码移到接口,再移到服务。

八个 harness 各自的独特设计

harness 定位 独特之处
Claude Code Anthropic,TypeScript,闭源 围绕 Claude 的策略层与类型化 hook
Codex CLI OpenAI,Rust 先沙箱后审批:命令在无网络沙箱中运行,只有出沙箱才请求批准;补丁格式由 Lark 语法约束,分四轮匹配 hunk
DeepSeek Harness TypeScript 连循环本身也是插件,可用 YAML 层替换;每个请求是会话日志的冻结视图,harness 只追加日志;比较并交换式编辑,文件在模型上次读取后改过则编辑失败
OpenCode TypeScript、Bun harness 是一个服务器,TUI、SDK 和网页端共用同一个 OpenAPI 接口;九种替换器从精确匹配到锚点匹配,拒绝过大的模糊匹配;每步用影子 git 仓库做快照,/undo 能恢复文件
Pi TypeScript 极简内核只有四个工具,没有 MCP、子智能体和审批;只在预期节省达到 0.05 美元以上时才发缓存保温请求;pi-ai 支持 42 个提供方、10 种协议
oh-my-pi TypeScript 加 Rust hashline 编辑:用 4 位十六进制文件标签加行号,模型不必重打旧文本;一个 shell 常驻,原生提供搜索、AST、LSP 与调试器;snapcompact 把旧历史转成图片
OpenClaw TypeScript 面向 27 个聊天渠道的网关,每个会话一条队列;压缩前先静默写入带日期的笔记,召回结合全文与向量搜索;用围栏隔离不可信文本,网络读取会污染本轮,并监控机密哨兵
Hermes Agent Python 后台分支审视被提示的轮次,再修改记忆和 skill;在窗口 50% 时就开始压缩,是八个中最早的;任何副作用之前先把工具调用写入会话数据库

自测

每项节省手段的反作用是什么?

被丢掉的文件要重读,摘要会改写缓存
便宜模型的坏计划增加步数或导致失败
每个都要重读共享文件和指令
猜错浪费 token,并争抢同一批工具

自测

在 Claude API 上,批处理加缓存后,输入 token 的价格约为基础输入价的多少?

09第 9 讲

LLM 基础:一次请求的生命周期与 TransformerLLM basics: the life of a request and the transformer

要点

  1. 一次请求经过分词、调度、prefill、decode、反分词和流式输出六个阶段。
  2. Prefill 受算力限制,决定首 token 时间;decode 受显存带宽限制,决定每秒 token 数。
  3. KV cache 每 token 的大小决定并发上限;GQA 让 Llama 3 70B 的 KV 降到每 token 320 KB。
  4. MoE 的内存随总参数增长,计算随激活参数增长。
01分词
02调度
03Prefill:首 token 时间
04Decode 与采样:每秒 token 数
05反分词
06流式输出

六个阶段

  • 分词。 文本被切成 token 而不是单词,平均每个 token 3 至 4 个字符,「Serving is hard」是 4 个 token。token 数决定成本和内存,不同模型的分词器不同。字节级 BPE 从 256 个字节值出发,反复合并最常见的相邻对,因此没有未知 token。词表越大,token 越少,但嵌入表越大。
  • 调度与批处理。 请求独立到达,GPU 需要批次。连续批处理让请求在任意一步加入或离开,不必等凑满一批;准入数量受 KV cache 显存限制。
  • Prefill。 整段提示一次前向,所有提示 token 并行计算注意力;受算力限制,成本随长度增长;生成 KV cache 并输出第一个 token。
  • Decode 与采样。 每个新 token 一次前向,KV cache 每步增长一个 token;受带宽限制,所以要批处理;cache 满时抢占或排队。采样从 logits 中选下一个 token,参数会改变答案和运行时长(见下表)。
  • 反分词与流式输出。 token ID 生成后即转成文本发出,未完整的字符先缓存;遇到停止 token、长度上限或断开连接即结束;提前停止会释放 cache。
采样参数 例 作用
temperature 0 为 0 时总选最高者,大于 1 时更多 token 有机会
top-k 50 从最可能的 k 个中采样,k 固定
top-p 0.9 取累积概率达到 p 的最少 token,随置信度自适应

Transformer 的结构

01token ID
02嵌入:每个 ID 变成 8,192 维向量
03Transformer 块 × 80:自注意力加 FFN
04LM head:词表中每个 token 一个分数
05softmax:下一个 token 的概率

模型是相同 Transformer 块的堆叠。输入是整数 token ID,嵌入层把每个 ID 变成向量(Llama 3 70B 为 8,192 维);经过 L 个块(Llama 3 70B 为 80 个),每块含自注意力(在 token 之间混合信息)和前馈网络(逐个变换 token);LM head 为词表中每个 token 打分,softmax 变成概率。

每个块采用 pre-norm 与残差:先 RMSNorm 再进注意力,结果加回残差流;再 RMSNorm 进 FFN,结果再加回。RMSNorm 用均方根缩放,每个维度一个可学习增益;pre-norm 让深层堆叠训练稳定;残差流贯穿 80 个块,每个子层只加一个更新量。

自注意力让每个 token 读取它之前的所有 token。每个 token 生成查询 Q、键 K、值 V(由 X 分别乘以权重矩阵得到),Q 与 K 的点积除以 √dₖ 后决定从每个 token 读取多少;除以 √dₖ 是因为点积随维度增大,缩放可防止 softmax 饱和。因果掩码在对角线以上填 −∞,遮住未来 token;softmax 让每行权重之和为 1;输出是 V 各行的加权混合。n 个 token 产生 n² 个分数,每层 FLOPs 约为 4n²d。若把分数矩阵 S 全部存下,8,192 个 token、64 头、80 层需要约 690 GB;FlashAttention 分块计算 softmax,从不存储 S。

步骤 公式 形状
输入 X n × d
查询 Q = X W_Q n × dₖ
分数 S = Q Kᵀ ÷ √dₖ n × n
权重 A = softmax(S + M) n × n
输出 O = A V n × dᵥ

多头注意力把 Q、K、V 拆成 64 个 128 维的头,各自做带掩码的注意力,再用 Wₒ 混合。64 × 128 = 8,192,FLOPs 与一个宽头相同,拆分改变的是学到的模式(有的头看前一个 token,有的看第一个 token,有的看附近,有的看全文),而不是成本。

KV cache 与共享 KV 头

KV cache 每 token 大小 = 2 × 层数 × KV 头数 × 头维度 × 每值字节数。MHA 每个查询头有自己的 KV 头;GQA 让多个查询头共享一组 KV 头;MQA 所有查询头共享一个 KV 头。以 8 个查询头为例,三者的 KV cache 分别为 1 倍、四分之一、八分之一。Llama 3 70B 的 64 个查询头共享 8 个 KV 头:2 × 80 × 8 × 128 × 2 B = 320 KB 每 token,MHA 则是 2.5 MB。

Llama 3 70B 参数 数值
模型宽度 d 8,192
层数 L 80
查询头 H 与头维度 dₖ 64 与 128
KV 头 Hₖᵥ 8
FFN 隐层宽度 28,672(3.5 倍 d)
词表 V 128,256

Llama 3 70B 的参数大部分在 FFN

参数量,十亿,按组件

  1. 注意力(80 层)12.1B
  2. FFN(80 层)56.4B
  3. 嵌入与 LM head2.1B
Meta, The Llama 3 Herd of Models (2024),第 9 讲课件推算

每层注意力约 151M 参数,FFN 约 705M,80 层合计 68.5B,加上嵌入与 LM head 共 70.6B。图中注意力和 FFN 的合计由每层数值乘以 80 得出。

系统视角的估算

141 GB权重(BF16,每参数 2 字节)
141 GFLOPs每 token 计算量(约 2 × 参数量)
320 KB每 token 的 KV cache

在 2 块 H200(合计 1,978 TFLOP/s、9.6 TB/s、282 GB)上,8 万 token 的提示:1 个请求 prefill 约 9.95 秒,所需显存 167 GB;64 个请求则需要 637 秒和 1,779 GB。上下文变长时,计算按 n² 增长,KV cache 按 n 线性增长,这正是支持长序列的难点。

MoE:内存看总参数,计算看激活参数

MoE 把每个块的 FFN 换成一个路由器和一组较小的专家 FFN,每个 token 只运行其中几个(如 8 选 2),再加权求和。

模型 专家 总参数 每 token 激活 权重(BF16)
Llama 2 70B 全部(稠密) 69B 69B 138 GB
Mixtral 8x7B 8 选 2 46.7B 12.9B 93 GB
Llama 3.1 405B 全部(稠密) 405B 405B 810 GB
DeepSeek-V3 257 选 9 671B 37B 1,342 GB

DeepSeek-V3 每个 token 只激活 37B 参数

每 token 激活参数,十亿;每 token GFLOPs 约为其 2 倍

  1. Llama 2 70B69B
  2. Mixtral 8x7B12.9B
  3. Llama 3.1 405B405B
  4. DeepSeek-V337B
Jiang et al. 2024;DeepSeek-AI 2024;Touvron et al. 2023;Llama Team 2024,转引自第 9 讲课件

质量相当时计算更少:Mixtral 以约五分之一的 FLOPs 达到 Llama 2 70B 的水平;DeepSeek-V3 以约十一分之一的 FLOPs 与 Llama 3.1 405B 相当,但需要 1.7 倍的内存。

延伸:八种进阶结构
结构 做法 对推理服务的影响
滑动窗口 局部层只看最近 w 个 token,少数全局层保留长程召回(Gemma 3 为 5 局部 1 全局,w = 1,024;Mistral 7B 全部局部,w = 4,096) 128K 上下文下,Gemma 3 的 KV 约为全全局层的六分之一
多头潜在注意力(MLA) 每个 token 只缓存一个压缩潜向量,需要时重建 K 和 V DeepSeek-V2 比 DeepSeek 67B 的 KV cache 少 93%,生成吞吐提高 5.8 倍
线性注意力 固定大小的状态原地更新;Gated DeltaNet 先衰减旧状态再写入(Qwen3-Next 为 36 层 GDN 加 12 层注意力,Kimi Linear、Qwen3.5 同为 3 比 1) 四分之三的层每个请求只保存恒定大小的状态
状态空间模型 每个通道一个小状态,由 token 决定衰减(Mamba 的选择性机制,Mamba-2 化为矩阵乘) 没有增长的 KV cache,Mamba 报告生成吞吐最高为 Transformer 的 5 倍
稀疏注意力 轻量索引器为过去的 token 打分,每个查询只读前 2,048 个(DeepSeek-V3.2) 每 token 的计算封顶,但所有 token 的 KV 仍要存储
循环 Transformer 同一个块重复 K 次 深度只增加计算和延迟,不增加权重
多 token 预测 一次预测多个 token 课件仅列出名称
扩散语言模型 经过几步并行细化填充被遮盖的 token(LLaDA 8B、Dream 7B) 一次前向填多个 token,但步数越少质量越差

自测

哪个阶段受显存带宽限制,并决定每秒 token 数?

自测

Llama 3 70B 有 80 层、8 个 KV 头、头维度 128,用 BF16。每 token 的 KV cache 约为?

10第 10 讲

GPU 基础:为什么 decode 受带宽限制GPU basics: why decode is bandwidth-bound

要点

  1. GPU 用数千个简单核心换取吞吐,靠切换 warp 隐藏访存延迟。
  2. 每个 kernel 受峰值算力、显存带宽和显存容量限制;roofline 的脊点区分两类瓶颈。
  3. batch 1 的 decode 只用到 H200 峰值算力的 0.5%;批处理有帮助,但 decode 注意力始终受带宽限制。
  4. 新一代 GPU 的算力增长快于带宽;提高有效带宽,要让更多字节同时在途。

GPU 与 CPU

64 核服务器 CPU NVIDIA H200 SXM
并行单元 64 核 132 个 SM,16,896 个 FP32 核
在途线程 270,336(每 SM 2,048)
显存带宽 约 0.46 TB/s(DDR5) 4.8 TB/s(HBM3e)
峰值稠密算力 约 5 TFLOPs FP32 989 TFLOPs BF16
隐藏延迟的方式 缓存、乱序执行 切换到就绪的 warp

CPU 像跑车,两个人最快到达;GPU 像车队,单程慢,但一次运送几千人。LLM 适合 GPU,因为每个 token 都在同样的权重上做同样的矩阵乘。

  • warp 切换隐藏访存延迟。 一个 warp 等内存时,另一个 warp 发射指令,计算单元保持忙碌。A100、H200、B200 的每个 SM 有 4 个 warp 调度器,每个管理最多 16 个 warp,共 64 个驻留 warp。
  • SIMT。 一条 warp 指令驱动 32 个线程,取指、译码和调度只付一次成本,相当于 32 条标量指令。
  • 分支发散。 同一 warp 的线程走不同分支时,两条路径要轮流执行,例如 f 只用 32 条通道中的 8 条,g 用 24 条。
GPU 放弃了 换来了
单线程速度(时钟不高、不做推测,串行代码慢得多) 面积和功耗用于数千个运算单元
并行必须显式(约 27 万线程才能填满 132 个 SM,小任务会让芯片空闲) 靠切换 warp 而非缓存与推测来隐藏延迟
控制流共享(32 个线程一组,分支发散损失吞吐) 一次取指和译码驱动 32 个核
每线程片上存储小(满占用时约 240 字节) 所有线程状态常驻,切换 warp 没有成本

三项指标与 roofline

显存带宽逐代提高,但增速低于算力

HBM 带宽,TB/s;Rubin 为初步数据

  1. 2 TB/sA100
  2. 4.8 TB/sH200
  3. 8 TB/sB200
  4. 22 TB/sRubin
第 10 讲课件(NVIDIA 数据表)
A100 H200 B200 Rubin
峰值 BF16 算力(决定数学运算多快) 312 TFLOP/s 989 TFLOP/s 2,250 TFLOP/s 约 4,000 TFLOP/s
显存带宽(决定读权重和 KV cache 多快) 2.0 TB/s 4.8 TB/s 8 TB/s 约 22 TB/s
显存容量(决定放得下多少权重和 KV) 80 GB HBM2e 141 GB HBM3e 180 GB HBM3e 288 GB HBM4

算力是引擎,带宽是油管,容量是油箱。kernel 时间约等于「字节数 ÷ 带宽」与「FLOPs ÷ 峰值算力」中的较大者。

Decode,batch 1:算力在等

  • 每 token 3.3 毫秒
  • 从 HBM 读 16 GB 权重
  • 每个权重只用一次,0.016 毫秒的计算等 3.3 毫秒的读取
  • tensor core 99.5% 的时间空闲

Prefill,2,048 个 token:算力忙碌

  • 每段提示 33 毫秒
  • 权重加载后 HBM 读取空闲
  • 每个权重服务 2,048 个 token,计算决定速度
  • 33 TFLOP,接近峰值

Roofline 模型用算术强度(FLOPs ÷ 进出 HBM 的字节数)判断瓶颈。脊点 = 峰值算力 ÷ 带宽,H200 约为 206 FLOP/B。脊点左侧受带宽限制,速度 = 带宽 × 强度;右侧受算力限制,速度 = 峰值。

运算 算术强度(b 为每元素字节数)
向量加法,长度 N 1/(3b)
GEMV(decode),N × N,每个权重用一次 约 2/b
decode 注意力,每个 KV 条目每头用一次 2/b
方阵 GEMM,每个元素约复用 N 次 2N/(3b)

batch 1 的 decode 是约 1 FLOP/B 的 GEMV,在 H200 上只能用到 989 TFLOP/s 中的约 5,也就是峰值的 0.5%。提高利用率要提高算术强度:更大的批、量化、减少 KV 流量。批处理能把权重 GEMV 推近脊点(batch 256 时为 256),但 decode 注意力始终停在 2/b,因为每个请求读的是自己的 KV。

上下文变长后,每步 decode 读取的字节主要来自 KV cache

每个 decode 步从 HBM 读取的总字节,GB;Llama 3 8B,batch 16,BF16;权重固定 16.1 GB

  1. 18.2 GB1K
  2. 24.7 GB4K
  3. 33.3 GB8K
  4. 50.5 GB16K
  5. 84.8 GB32K
第 10 讲课件(Llama 3 论文与 H200 数据表推算)

每 token 的 KV 为 128 KiB,随 batch 与长度增长;按 4.8 TB/s 计,一步从 1K 时的 3.8 毫秒增至 32K 时的 17.7 毫秒。低精度把脊点进一步右移:Rubin 的稠密 NVFP4 需要约 1,600 FLOP/B 才能受算力限制。从 A100 到 Rubin,BF16 算力增长约 13 倍,带宽约 9 倍,kernel 越来越受带宽限制。

H200 的内部结构

H200 有 132 个 SM,共享 50 MB L2 缓存和 141 GB HBM3e(6 个堆栈,4.8 TB/s),NVLink 到其他 GPU 为 900 GB/s。每个 SM 分为 4 个分区,各有 64 KB 寄存器、32 个 FP32 核和一个 tensor core,每周期发射一条 warp 指令;SM 内共享 256 KB 的 L1 与共享内存,驻留 2,048 个线程。

Tensor core 一条指令完成一个小矩阵乘加 D = A × B + C(如 16×16 乘 16×8),一次 mma 等于 2,048 次乘加,是一条 FMA 工作量的 64 倍。矩阵乘占 LLM FLOPs 的 99% 以上,softmax 与 norm 用 FP32 核。它快的原因有四:每 FLOP 的指令更少;专用乘加数据通路;操作数复用(A 的值供多列,B 的值供多行);低精度(FP16、BF16、FP8)提高吞吐、缩小操作数,通常用更高精度累加。

内存层级(H200) 容量 延迟(Hopper) 带宽
寄存器 每 SM 256 KB 在流水线中 每条指令读取
共享内存 / L1 每 SM 256 KB 约 30 周期(L1 命中约 40) 每 SM 每周期 128 B,132 个 SM 合计约 33 TB/s
L2 缓存 50 MB 约 250 周期 Hopper 上约 12 TB/s
HBM3e 141 GB,6 个堆栈 约 500 周期 4.8 TB/s
主机内存与其他 GPU 微秒级 NVLink 4 每方向 450 GB/s;PCIe 5.0 约 64 GB/s

显存是一条 250 纳秒的管道

利特尔定律:带宽 = 在途字节 ÷ 延迟。朴素 kernel 每个 SM 只有约 4 KB 在途,只能达到 2.2 TB/s,即峰值的 45%;要跑满 4.8 TB/s,每个 SM 需要约 9 KB 在途(4.8 TB/s × 250 ns ÷ 132)。管道长度由硬件决定,提高带宽的唯一办法是让管道里有更多字节:使用 16 字节向量加载、每个线程发出四个独立加载、使用批量异步复制(TMA)。

H200(Hopper) B200(Blackwell) Rubin
HBM 141 GB HBM3e 180 GB HBM3e 288 GB HBM4
带宽 4.8 TB/s 8 TB/s 22 TB/s
全卡在途字节 1.2 MB 2.0 MB 5.5 MB
每 SM 在途字节 9 KB 14 KB 25 KB
新数据通路特性 TMA、cluster TMEM、2-SM MMA 内联 TMA 描述符

延伸:合并访问让 32 个线程的连续 4 字节读取合成一个 128 B 请求;16 字节向量加载让一条 warp 指令搬 512 B;cp.async(Ampere 起)不经寄存器直接拷到共享内存;Hopper 的 TMA 由一个线程发起整块拷贝,一条指令即有数十 KB 在途,TMA 多播让一次 L2 读取同时落到一个 cluster(最多 8 个线程块)的各个 SM;Blackwell 把结果放进 256 KB 的 tensor memory,释放寄存器给更多加载,并让两个 SM 合作完成一个矩阵乘,各取一半的共享数据块。

从单卡到多卡

HGX H200(8 卡节点) GB200 NVL72(机架)
组成 8 块 GPU 经 NVSwitch 互联,8 张 400 Gb/s 网卡接入外部网络 每行 4 GPU 加 2 CPU,共 9 行经 NVLink 交换机互联
HBM 带宽 4.8 TB/s 8 TB/s
NVLink 900 GB/s 1.8 TB/s
RDMA 50 GB/s 100 GB/s

从 G80(2006)到 B300(2025),峰值算力增长约 43,000 倍,带宽只增长约 90 倍。二十年的主线是从图形转向通用计算(CUDA、缓存、HBM2、NVLink、tensor core),再转向低精度 AI 引擎(TF32、BF16、FP8、TMA、FP4、TMEM、NVL72)。

延伸:其他加速器
芯片 特点 编程方式
AMD MI355X 8 个计算芯粒,软件看作一块 GPU;256 MB Infinity Cache;64 线程 wavefront;稠密 FP8 5.0 PF,288 GB,8 TB/s ROCm 与 HIP;PyTorch、vLLM、SGLang 可运行;Triton 或 Composable Kernel
Google TPU Ironwood 权重驻留的脉动阵列,3D 环面互联 9,216 片;稠密 FP8 4.6 PF,192 GB,7.4 TB/s JAX 或 PyTorch/XLA;Pallas 写自定义 kernel
Amazon Trainium3 每片 8 个 NeuronCore,各含张量、向量、标量引擎;每核 32 MB 软件管理 SRAM,无硬件缓存;2.5 PF MXFP8,144 GB,4.9 TB/s Neuron SDK;NKI 用 Python 显式搬运数据块;没有 CUDA
Cerebras WSE-3 整片晶圆一颗芯片,44 GB 片上 SRAM,无片外内存 更大的模型需要流式加载权重
Groq LPU 230 MB SRAM,无片外内存 8 位 70B 模型约需 300 颗芯片
Microsoft Maia 200 272 MB SRAM 加 216 GB HBM3e 仅在 Azure 内可用

自测

课件的课堂提问:H200 做 batch 1 的 decode 时,用到峰值算力的多少?

自测

这些运算在 H200 上受什么限制?

方阵 GEMM,N = 8192
batch 1 的 GEMV
decode 注意力
2,048 个 token 的 prefill

∞SOURCES

来源与说明

  • 内容全部来自本文件夹中第 1 至 10 讲的公开课件。课程为 Harvard CS2680,讲者 Juncheng Yang,课程页为 cs2680.com。
  • 课件中引用的第三方数据保留原出处:ReAct(arXiv 2210.03629)、Liu et al.「Lost in the Middle」(TACL 2024)、Chroma Context Rot、Breunig「How Contexts Fail」(2025)、Lewis「Same Model, Different Harness」(arXiv 2608.26218)、Anthropic「Building a C compiler」、Codex 与 OpenAI 内部使用报告(2026 年 6 月与 9 月)、Meta Llama 3 论文、NVIDIA 白皮书与数据表,以及各基准的原始论文。
  • 已略去:课程介绍、评分与政策、作业与截止日期、计算资源、课堂互动和「下节课」页。两份作业分享 PDF(assignment3_sharing、assignment3_feedback)设有密码,未能读取,未纳入。
  • 图表均按课件中的数值重绘。Llama 3 70B 注意力与 FFN 的合计参数由课件的每层数值乘以 80 得出,其余数值均为课件原值。

HARVARD CS2680 · STUDY HANDBOOK · 2026.11.02

Agents and AI system optimizationCS2680A study handbook for CS2680, lectures 1 to 10

The course treats an agent as a systems problem. The model sets the ceiling, the harness sets realized performance, and the serving system and GPU set cost and speed. Lectures 1 to 8 cover using and designing agents: the loop, tools, context, memory, multi-agent systems, reliability, evaluation and cost. Lectures 9 and 10 cover how LLM inference and GPUs work. Each lecture opens with its key points and ends with a self-check.

SCROLL

01LECTURE 1

Course map: AI systems and agentic systems课程地图:AI 系统与智能体系统

Key points

  1. AI systems ask how to train and serve models at scale, for performance, efficiency, reliability and sustainability; here that means LLM systems.
  2. An agent uses a model to reason, call tools and act over many steps until a task is done. It is a new kind of computer: the LLM is the CPU, context is RAM, tools are peripherals, the harness is the OS.
  3. Agent serving is a long chain of inference and tool calls, and each property of the workload names a systems problem.
  4. The objective is not throughput but task success under latency, cost, resource, reliability and security constraints.

Five ways AI systems differ from traditional systems

Dimension What differs
Compute Heterogeneous: the CPU tokenizes, launches kernels, moves data and runs tool calls, the GPU does matmuls. Prefill is compute-bound, decode is memory-bandwidth-bound. Execution time depends on output length, which complicates scheduling
Non-determinism Floating-point addition is not associative, and a shift in the seventh decimal can flip the next token. Sources are the runtime (warp scheduling, batch size), software (fused multiply-add vs two ops, autotuning) and hardware (CUDA vs tensor cores, FP8 vs micro-scaling formats). Approximate computing is acceptable
Memory, storage, communication Weights run from GBs to TBs, the KV cache takes tens to hundreds of KB per token, and a prefix cache reuses KV across requests. Data movement is the bottleneck. Multi-GPU serving needs pipeline, tensor, expert and context parallelism over NCCL, NVLink, InfiniBand and RDMA
Fast-moving models and workloads Attention moved from MHA to GQA, MLA, NSA and linear attention. Workloads moved from multi-turn chat, long reasoning and RAG to agents, which need long context, prefix caching, routing and load balancing
Reliability and power 9% annual failure rate: a 16K-GPU cluster loses a GPU about every 3 hours. A GPU draws 700 to 1000 W, and server power rose from 800 W to 6,000 W

Server power rose about eightfold with GPUs

Power per server, W

  1. CPU server800 W
  2. GPU server6,000 W
Lecture 1 slides

What an agent is

An AI agent is an autonomous software system that uses an AI model to reason about a goal, use external tools and execute multi-step actions until a task is finished. Its work breaks into five steps:

01Plan: break the task into sub-steps
02Act: call external tools
03Observe: interpret the results
04Adapt: revise the plan on new information
05Deliver: return the final result

Agents are needed because LLMs are uneven. They are superhuman at recalling facts, language, pattern matching, generating code and working across domains, and weak at persistent memory, reliably understanding context, avoiding hallucination, knowing what they don’t know and resisting adversarial input. Tools and memory fill the gaps.

An agent can be read as a new kind of computer: the LLM is the CPU, the context window is RAM, tools are peripherals, the agent harness is the operating system and the agent is the application. Its programming model and failure model are entirely different.

Why agents are a systems problem

Traditional LLM serving is one request, one inference, one response. Agent serving is a chain: infer, tool, infer, tool, retrieval, infer. The critical path spans GPU, CPU, storage, network and external services, which brings dependencies between steps, highly variable step latency, blocking on tools, rapidly growing state, concurrency and speculation, and failures anywhere in the trajectory.

Property of the agent workload Systems problem it names
Long trajectories State and context management
Huge context Memory hierarchy and retrieval
Repeated prefixes Prefix caching
Branching reasoning Speculative execution
Tool dependencies Dependency-aware scheduling
Different models Routing
Variable tool latency Asynchronous execution
External side effects Security and isolation
Multiple agents Orchestration and communication
Long-running tasks Checkpointing and fault tolerance

The stack, top to bottom: application and user; agent and harness (planning, context, memory, tools, subagents), beside the external environment and tools (web, files, APIs, humans); the model; the serving system (batching, scheduling, routing, caching); runtime and kernels (CUDA, Triton, collectives); hardware (GPU, CPU, memory, network, storage).

What to optimize

Throughput is the wrong objective for an agent. The objective is to maximize task success subject to latency, cost, resources, reliability and security.

What we actually optimize

  • Task success and accuracy
  • End-to-end latency
  • Tokens per task
  • Dollars per successful task
  • Energy per successful task

Useful, but insufficient

  • TTFT and TPOT
  • Tool-call latency
  • GPU utilization

More tokens per second can still mean a slower, costlier agent. Observability is a first-class problem: for agents the distributed trace becomes a nested trajectory of sessions, turns, agent steps, model requests, tool calls and subagents. You cannot optimize what you cannot observe.

Questions the course answers

Batching and latencyWhy does batching raise throughput but hurt agent latency? When should an agent use a larger model?
Where state livesWhere should KV and prefix state live? How should requests from one agent be scheduled?
Overlap and delegationCan tool calls overlap with inference? When should we spawn a subagent?
Routing and recoveryHow do we route across heterogeneous GPUs and models? How do we recover a 30-minute agent after a failure?
The objectiveHow do we optimize dollars per successful task rather than tokens per second?

The course does not cover training (inference dominates compute demand), model architecture design, communication, power and energy, or new hardware design.

Also: six levels of AI coding, and agents vs assistants vs bots
Level Meaning
0 No AI, hand-written code
1 Assist: AI autocompletion
2 Supervised: AI writes functions, you review
3 Scoped: hand off a task, review the code
4 Goal-driven: AI writes all, tests verify
5 Parallel agents: subagents split the work
Agent Assistant Bot
Purpose Performs tasks autonomously and proactively Assists users with tasks Automates simple tasks or conversations
Capabilities Complex multi-step actions; learns and decides independently Responds to prompts and can recommend; the user decides Follows predefined rules; limited learning
Interaction Proactive, goal-oriented Reactive, responds to requests Reactive, responds to triggers

Self-check

Which does the course say we should actually optimize for an agent?

Self-check

Which systems problem does each workload property name?

Repeated prefixes
Variable tool latency
External side effects
Long-running tasks

02LECTURE 2

How Claude Code works: the loop, memory and extensionsClaude Code 如何工作:循环、记忆与扩展

Key points

  1. One prompt expands into many model calls and tool runs: the model proposes, the harness checks permission and executes, the result goes back into context.
  2. Context is rented working memory; CLAUDE.md and auto memory are files loaded every session, and stale memory is worse than none.
  3. Each extension does one job: a skill says how, MCP reaches outside, a hook enforces, a plugin packages and distributes.
01Gather context: prompt, files, tool results
02Model proposes an action, e.g. Bash(“pytest”)
03Harness checks permission and runs it
04Result goes back into context

Facts about the loop

  • Context is over 10K tokens before you type. System instructions, project environment, memory (CLAUDE.md), tools (Read, Edit, Bash, Glob, Grep, Web, Agent), and skill and MCP names and descriptions come first, then the user’s words. Skills and MCP start as names only; the full text loads when Claude reaches for them.
  • It does not send your repository. The repo stays on disk and Claude pulls slices on demand: Grep(“authentication”) brings back a handful of lines.
  • The model proposes, the harness executes. The model emits a tool request; the harness resolves it, checks permissions and runs it on your machine; the tool_result goes back into the model’s context. Every request is conditioned on the previous inference and the previous tool result.
  • Permissions sit between intent and execution. A tool request is a proposal that needs your approval or another model’s (table below).
  • Context grows, then gets compacted. A typical window is 1M tokens (256K was common earlier in the year). Prefix-cache reads account for most of the cost. Compaction summarizes the old trajectory and re-injects CLAUDE.md and memory.
Permission mode Meaning
Manual You confirm each request
Accept edits Edits pass automatically; other requests still ask
Bypass permissions Everything runs directly
Auto A small model checks each request

A request ends in one of three ways: allowed (the command runs), ask (you confirm first) or denied (nothing happens).

Memory: context is rented, memory is owned

Agents are stateless between runs; every session starts from zero, and memory is just files loaded at session start. Context is working memory and dies with the session; persistent memory survives and is reloaded. Memory answers four problems: repeated instructions, repeated discovery, decisions whose reasons vanish at compaction, and sessions that make different choices. Memory is how instruction becomes convention.

CLAUDE.md Auto memory
Who writes it You Claude
Contains Instructions and rules Learnings and patterns
Scope Project, user or organization Per repository, shared across worktrees
Loaded Every session Every session (first 200 lines or 25KB)
Use for Standards, workflows, architecture Preferences, corrections, project context

CLAUDE.md files load broadest scope first, and the closest file is read last: managed policy (org-wide, cannot be excluded), user ~/.claude/CLAUDE.md, project ./CLAUDE.md (shared through source control), local ./CLAUDE.local.md (personal, gitignored).

Belongs in CLAUDE.md

  • Commands: how to run tests, the build, the linter
  • Hard constraints: never commit to main, never edit generated files
  • Facts the agent cannot cheaply infer: layout, ownership, gotchas

Does not belong

  • What the model already knows about the language or framework
  • Style a linter or formatter already enforces
  • Long prose, changelogs, anything secret

Keep each file under 200 lines, in Markdown headers and bullets, with concrete and consistent rules. When it grows, split it into .claude/rules/, one topic per file; with a paths: frontmatter a rule loads only when Claude touches matching files.

Auto memory lives in ~/.claude/projects/<project>/memory/, each file tagged with a type: user (role and preferences), feedback (corrections and confirmed approaches), project (ongoing work and decisions not in the code), reference (information outside the project). MEMORY.md is the index, and its first 200 lines load each session; topic files are read only when relevant. Commands: /memory (browse, edit, disable), /context (which instruction files loaded), /init (a starter CLAUDE.md), /doctor (content that may not belong in CLAUDE.md).

Remembering has a cost. Every permanent token is rent paid at the start of every session, and memory competes with the task for the same window. Stale memory is worse than none because it actively misleads. Treat memory like code: review it, prune it, keep it in version control.

Tools and four extension mechanisms

Core tool What it does
Read Opens a file or inspects state; the most used tool
Search grep and glob: find it without reading everything
Fetch Pulls a page or doc, bringing untrusted text inside
Edit / Write Changes files; the first tool with consequences
Shell Build, test, git; the whole machine unless sandboxed
Delegate Spawns a subagent that returns a summary

The model decides which to use.

Mechanism Problem it solves Where it attaches in the loop
Skill How the agent should perform a task (knowledge and procedure) Model reasoning
MCP Which external data and actions it can reach Tool selection
Hook What happens automatically at a lifecycle event Any stage: inspect, block or react
Plugin How extensions are packaged and distributed Bundles the other three into one installable unit

A release workflow (prepare, validate, publish to GitHub, notify the team) shows the split:

01Skill: follow the release procedure
02MCP: create the GitHub release
03Hook: block publishing when tests fail
04Plugin: share the complete setup

A skill is a folder: SKILL.md (the name and description control discovery; the body holds the procedure) plus references/ and scripts/. Descriptions load at session start; the body loads only when the skill runs. A skill is invoked by the model when its description matches the task, or by the user as /<skill-name>. Side-effecting workflows should usually require explicit invocation, and clear, distinct descriptions reduce wrong selections. Think of it as context engineering.

MCP (Model Context Protocol) connects an agent to external services through a standard protocol: GitHub, databases, monitoring, Figma, Slack, a browser. A call takes six steps: Claude identifies a needed action, the MCP client calls a tool, the MCP server handles the connection, the external service performs the operation, structured results return, and Claude evaluates them. It is almost identical to a local tool, but runs in another process.

Hooks fire on events; model reasoning is not an event. A hook can run a command, an HTTP request, an MCP tool, a prompt or a subagent.

01Session start: load context, log
02User prompt: validate or add
03Before tool use: inspect or block
04After tool use: format, test, log
05Before stopping: verify tests

A plugin packages skills, hooks, agents, .mcp.json and .lsp.json, and gives one-command installation, pinned versions, namespacing, team reuse and marketplace distribution.

Inside .claude/: CLAUDE.md and rules/ are memory; settings.json holds permissions, hooks and environment variables; skills/ and commands/ are workflows; agents/ and hooks/ are delegation and guardrails. The same layout at ~/.claude/ applies to user scope, and project settings win over user settings.

Requirement Mechanism
Apply the company API conventions Skill
Read an issue from Jira MCP
Run formatting after every edit Hook
Guide a multi-step deployment Skill
Send a completion notification Hook plus MCP
Block writes to production Hook or policy
Share everything across repositories Plugin
Further: MCP in detail

Before MCP, N AI clients and M services needed N×M integrations. MCP is an open, stateless protocol: the host (such as Claude Code) runs one MCP client per server, and each MCP server exposes a system’s capabilities as tools.

MCP primitive What it is Example
tools Actions Claude can call create_issue(…)
resources Readable data, such as an issue or a schema github://issues/123
prompts Reusable templates a server exposes, user-controlled Shown in Claude Code as /mcp__github__triage_issue

They cooperate: to triage issue #123, the prompt supplies the organization’s triage procedure, the resource supplies the issue, and a tool retrieves current diagnostics.

Security: least privilege, scoping the token to the repo, table or channel you need; separate reads from writes and keep mutations behind approval; never treat returned content as instructions; vet third-party servers, which can carry prompt injection. Before connecting, ask what the server can read and what it can change.

An MCP gateway is a control layer between an AI client and several MCP servers that aggregates, routes, enforces policy, brokers identity, observes and scales. It is worth it when many users, agents, servers, credentials or compliance rules must be governed consistently, but it is a trust boundary with risks of broad credentials, lost end-user identity, name collisions, secrets in logs and a single point of failure. The 2026-07-28 spec is the largest revision since launch: a stateless core in which any request can land on any instance; Mcp-Method headers that let gateways route without reading the body, with list results cacheable by TTL; and Tasks for long-running work and MCP Apps for server-rendered UIs, shipped as extensions.

Self-check

The design exercise from the slides: which mechanism fits each requirement?

Apply the company API conventions
Read an issue from Jira
Run formatting after every edit
Guide a multi-step deployment
Block writes to production
Share everything across repositories

Self-check

Which belongs in CLAUDE.md?

03LECTURE 3

Multi-agent use and Programming 3.0多智能体用法与 Programming 3.0

Key points

  1. Changing only the instructions changes the workflow: Superpowers sets a development process with skills and a session hook; Caveman compresses tokens both ways with skills, hooks, MCP and a local proxy.
  2. Scaling has three axes: parallel agents buy wall-clock time, subagents buy focus, long-running agents buy scope; agent teams pay off only when the work needs discussion.
  3. Programming 3.0 is about uncertainty: do not expect the agent to be deterministic; make the surrounding system dependable and match autonomy to risk.
  4. Field data: delegated tasks grew much larger in six months, but the longer the task, the fewer succeed without a human stepping in.

Case study: Superpowers

Superpowers is a software-development plugin. A default agent starts coding on a feature request and fixes by iteration; with the plugin, the work follows a fixed path:

01Human types the request
02Clarify the problem
03Approve a design
04Write a detailed plan
05Test-driven build
06Review and verify
07Finish or integrate the branch

It consists of nine skills:

Skill Responsibility
using-superpowers Rules for discovering and invoking skills
brainstorming Turns a request into an approved design
writing-plans Decomposes the design into concrete tasks
using-git-worktrees Creates an isolated workspace
test-driven-development Enforces red, green, refactor
systematic-debugging Finds root causes before proposing fixes
requesting-code-review Reviews implementation against the plan
verification-before-completion Requires evidence before reporting success
finishing-a-development-branch Merge, pull request, retention or cleanup

A skill file has six parts: name, description, instructions, checkpoints, references and scripts. A process skill can also define entry conditions, required and prohibited actions, human approval gates, verification requirements and the next skill.

Installing skills makes them available but does not make the agent check them. Superpowers solves this with a SessionStart hook that runs at startup, after clear and after compaction: a script reads the bootstrap skill, escapes it as JSON and returns it as additionalContext.

Design question Superpowers’ answer
How is complex behavior represented? Small, composable skills
How does the agent remember to use them? A bootstrap skill injected by a session hook
How is context kept manageable? Task skills load only when relevant
How do stages coordinate? Each skill names its gates and successor
How do users install it? Everything packaged as a plugin
Does every plugin need commands or MCP? No; add them only when needed

Case study: Caveman

Caveman compresses an agent’s tokens in both directions, for three reasons: logs, diffs and tool output crowd out the work; every turn is paid for and waited on; and trimming late at compaction drops what mattered. For example, 786 lines of test output become “3 tests fail: ETIMEDOUT at client.ts:88”.

65%Reported reduction in output tokens; the skill adds input tokens, so whole-session savings are lower
2Directions: the skill changes how the model writes, the proxy changes what it reads
5MCP tools: compress, byte-exact retrieve, stats, JSON to TOON and back

It uses all five extension mechanisms plus a local proxy. A skill sets the concise style (keep technical terms, commands, paths, code, errors, numbers, units and negation; drop filler, repetition, pleasantries and hedging). Commands let the user pick a mode (/caveman ultra, /caveman off and others). A SessionStart hook decides and stores the session’s mode and restores the rules after compaction; a UserPromptSubmit hook detects mode changes mid-conversation. MCP exposes compression and retrieval of the original. The plugin packages it all. The proxy compresses by type: errors, stack traces, head and tail for logs; imports, signatures and types for code; file and hunk headers and changed lines for diffs; keys and structure for JSON.

Hooks can intercept requests but cannot transparently rewrite the request to the LLM, so a proxy is needed. The proxy intercepts every request and changes the context; MCP runs only when called and cannot. If you write your own harness, you can do it directly.

Three ways to scale

Parallel agents Subagents Long-running agent
How Independent tasks, each in its own worktree Delegate a bounded task to a fresh context and get back a summary Carry a larger job across many steps
Buys Throughput (wall-clock time), not answer quality Throughput and focus: the parent never sees the intermediate mess Scope: more work with less intervention

Parallel agents by hand. claude -w feature-payments and claude -w bugfix-auth each get a git worktree: a separate working directory and branch that share the repository’s history, so edits never touch another session’s files, with no stashing and no second clone. With three sessions you can hold the plan. With twenty you need a clone of yourself: the plan lives in your head, sessions cannot see each other, you reconcile the branches, and nothing is written down to rerun.

Subagents are specialized assistants with their own context window, tools and permissions, used to preserve context, enforce constraints, reuse prompts across projects, run in parallel and control cost (for instance with Haiku). A custom subagent is a Markdown file with YAML frontmatter (name, description, tools, model) whose body becomes the system prompt, kept in .claude/agents/ (project) or ~/.claude/agents/ (user). Subagents nest up to five levels, and two to three is the sweet spot; Agent must be in tools before a subagent can spawn children.

Built-in subagent Use
Explore Read-only search of the codebase; write and edit denied; thoroughness set per call
Plan Research during plan mode, so exploration stays out of the main window
General-purpose Complex multi-step work that needs both exploration and action

Explore and Plan skip CLAUDE.md and git status to stay fast and cheap. Ways to invoke, in increasing control:

  1. 01Name it in the prompt: Claude decides whether to delegate, for one request
  2. 02@agent-name: guaranteed to run for one task
  3. 03claude --agent name: the whole session adopts its prompt, tools and model
Keep in the main conversation Delegate to a subagent
Iterative back-and-forth Verbose output you won’t reuse
Phases that share context Tool or permission restrictions
Quick, targeted changes Self-contained work returning a summary
When latency matters Parallel, independent work; simple work on a small model

Agent teams (experimental, off by default) are several Claude Code sessions with one lead and several teammates. The lead spawns teammates, coordinates and synthesizes; each teammate is a separate instance with its own context; a shared task list holds work items to claim; each agent has a JSON mailbox, and teammates talk to each other directly. Teammates do not inherit your conversation but load CLAUDE.md and skills automatically. Teams suit review from several angles, independent modules, debugging with competing hypotheses and cross-layer work; for sequential tasks, same-file edits or heavy dependencies, use one session or subagents.

Subagents Agent teams
Communication Back to the caller only Teammate to teammate
Coordination The lead manages the work Shared task list
Best for Result-only tasks Work that needs discussion
Token cost Lower Higher

A dynamic workflow is a JavaScript script that orchestrates many subagents in the background, for a codebase-wide bug sweep, a 500-file migration, cross-checked research or a plan from several angles. Type ultracode in the prompt, or use /effort ultracode and let Claude decide.

Long-running agents. /goal “npm run lint exits with zero errors” hands over a verifiable end state; an evaluator rechecks it after each attempt, and the run stops when the goal holds or --max-tries runs out. “All integration tests pass” works; “refactor the code” does not. /loop 5m “check CI, fix whatever broke” re-runs a prompt on an interval until you press Esc; a default prompt can live in .claude/loop.md.

Case study: sixteen agents built a C compiler

16Agents in parallel, about 2,000 sessions over two weeks
~100KLines of Rust that build Linux 6.9 on x86, ARM and RISC-V
2B / 140MInput / output tokens; just under $20,000 in API cost
~99%Pass rate on major test suites

Plain infrastructure did the orchestration: each agent had its own container and git checkout; tasks were claimed with lock files in current_tasks/; an agent implemented and tested, pulled everyone else’s work, then merged, pushed and unlocked; fresh sessions read progress docs to regain context; specialist agents handled docs, performance, quality and deduplication; automated tests gave a progress signal. There was no chat and no manager agent. The limits: merge conflicts were frequent; parallelism stopped helping once every agent hit the same kernel failure; part of 16-bit x86 still leaned on GCC; and the generated code was less efficient than GCC’s.

Programming 3.0 and uncertainty

The lecturer’s framing The human writes Through Into
Programming 1.0 Machine instructions or assembly Hardware
Programming 2.0 A programming language A compiler Machine instructions
Programming 3.0 A goal in natural language An agent A program, then machine instructions

Each step raises productivity and uncertainty. Karpathy’s Software 3.0 is a different framing: the 1.0 program is source code, 2.0 is neural-network weights (collect data, optimize), 3.0 is LLM prompts (natural language). Knowing where to draw the boundary between 1.0, 2.0 and 3.0 is an important engineering skill.

Uncertainty is not new. Hardware (32 vs 64 bit, endianness), environment (concurrency, unreliable networks) and software (compiler versions, dependency drift) were handled in 2.0 by fixed-width types, memory consistency models, idempotent APIs and testing before upgrades. 3.0 adds non-deterministic kernels and floating-point variance, code generation that touches the environment as it writes, sampling, and ambiguous input from a single prompt. Uncertainty sits in five layers: natural language (semantics), retrieval and context (retrieval drift, index updates, truncation), model generation (sampling, software and hardware non-determinism), the agent and tool loop (tool failure, environment change), and the generated program (usually deterministic once generated, unless it calls models or tools at runtime).

  1. 01Define: state assumptions up front and have the model confirm anything ambiguous before it executes; specify outcomes, not prompts, with requirements, invariants, constraints and acceptance tests
  2. 02Control: separate proposal from execution and validate plans before anything commits; manage context explicitly, owning memory, provenance and retrieval and expiring stale information
  3. 03Verify and govern: tighten the generate-verify loop, since cheap, frequent checks beat one expensive review at the end; measure one level deeper with tests, several metrics and synthetic workloads you can reason about

Do not expect the agent to be deterministic; make the surrounding system dependable. Match autonomy to risk.

Evidence from the field: Codex and OpenAI

Tasks delegated to Codex grew much larger in six months

Share of users tackling tasks of each size, %, December 2025 vs May 2026

  1. ≥ 1 human-hour · 2025.1235.4%
  2. ≥ 1 human-hour · 2026.0570.2%
  3. ≥ 8 human-hours · 2025.122.1%
  4. ≥ 8 human-hours · 2026.0525.6%
Codex report (June 2026), cited in lecture 3

Users tackling full-day tasks rose twelvefold. Active users grew more than five times in the first half of 2026. In the last 28 days, under 1% of individuals and 17.3% of organizations used Codex, against nearly all OpenAI workers.

28.6%OpenAI users who ran 5 or more agents at once in a week
~2.5Agent-hours per day for the median employee
~71Agent-hours per day at the 99th percentile, up 88% since April
3.14×Agent workdays over researcher workdays, September 2026

Before June 2026, agent runtime trailed human labor; now it exceeds it. Most researchers run four or more concurrent workflows, and lines changed per engineer approach eight times the pre-2025 average. The human role shifts to planner, delegator, monitor, reviewer and integrator.

The longer the task, the fewer succeed without human intervention

Tasks that succeeded with zero interventions, %, by estimated time for a human

  1. 86%<15m
  2. 76%15–30m
  3. 69%30m–1h
  4. 61%1–2h
  5. 57%2–4h
  6. 43%4–8h
  7. 40%8–16h
  8. 23%16–32h
  9. 13%32–64h
  10. 16%64–128h
OpenAI report (September 2026), cited in lecture 3

The delegation ladder, bottom to top: chatbot (AI answers, the human does the work), assistant (human and AI work together), agent (the human delegates a whole unit of work), multi-agent worker (the human coordinates several agents), systematized workflows (skills and agents run processes). The slides place OpenAI’s workforce near the bottom.

Also: CLI coding agents, mid-2026
Group Examples
Model labs Claude Code, Codex CLI, Antigravity CLI, Grok Build, Mistral Vibe, Kimi Code, Qwen Code
Platform CLIs Copilot CLI, Cursor CLI, Amp, Auggie, Droid, Junie CLI, Qoder, CodeBuddy
Open source, bring your own key OpenCode, Crush, Goose, Aider, Cline, Kilo, Continue, OpenHands and others
Minimal cores Pi, oh-my-pi, mini-SWE-agent, gptme, Open Interpreter
Axis The two ends
Open vs closed Open: Codex CLI, OpenCode, Goose, Cline, Pi. Closed: Claude Code, Copilot CLI, Cursor, Droid, Junie
Locked vs bring your own key One vendor: Claude Code, Antigravity CLI, Grok Build. Any endpoint: OpenCode with 75+ providers, Kilo with 500+ models
Sandbox vs prompt OS sandbox: Codex CLI, Copilot CLI, OpenHands containers. Permission prompts: Claude Code and most others
Local vs cloud Local-first, no telemetry: Goose, Nanocoder, gptme. Cloud handoff: Copilot CLI, Codex, Mistral Vibe
Maximal vs minimal Everything included: oh-my-pi, Claude Code. Four tools only: Pi, mini-SWE-agent (about 100 lines of Python)

Self-check

Keep it in the main conversation, or delegate to a subagent?

Iterative back-and-forth
Verbose output you won’t reuse
Quick, targeted changes
Tool or permission restrictions
Latency matters
Parallel, independent work

Self-check

Which works as a /goal?

04LECTURE 4

Agent design I: the loop, tools and context智能体设计 I:循环、工具与上下文

Key points

  1. Agent = model × harness; changing only the harness raised tasks solved on two SWE-bench variants by 1.7 to 2.3 times.
  2. Tool design is context design: few, orthogonal tools, token-cheap output, errors that teach.
  3. Context costs money, latency and attention, and accuracy is lowest when the answer sits in the middle.
  4. When the window gets too large, use admission, offloading and transformation first; LLM compaction is the last resort.

ReAct and the agent loop

ReAct puts reasoning and acting in one loop: a thought (what do I know, what is missing, what next), an action (a structured call the environment can run) and an observation (the environment answers with facts). Reasoning alone is never checked, so small errors compound into confident hallucination; acting alone has no plan behind it, so the model repeats itself. In ReAct, thoughts steer the next action and observations correct the next thought, until the observations answer the question or a stopping rule ends the run.

  1. 01Start the message list with the system prompt and the user request
  2. 02Loop up to a step limit: call the model and append its reply
  3. 03If it gives a final answer, return it
  4. 04Otherwise, for each tool call: validate the arguments, run the tool, append the serialized result as a tool message
  5. 05Raise an error when the step limit is exceeded

As a harness designer you write the tool definitions, assemble the context, validate requests, check permissions and run them, and optionally process results and manage context. A coding agent’s three components share one context window and are designed together: the model plus loop; tools and guardrails (permissions, sandboxing, approval); and state, meaning what is in the window now plus what the agent carries between steps.

Tool design: search and read

Approach Finds code by Best when Main cost
glob / grep Literal names and paths The name is known or guessable Turns and context per search; lexical matching misses paraphrase
Semantic index Meaning of embedded chunks, or an Aider-style repo map (file tree plus ranked symbols) The wording won’t match the code Building and re-syncing the index
Extrinsic signals Stack traces, failing tests, git history A report already points at code Exists only for some tasks
Language server (LSP) The compiler’s symbol graph: definitions, references, types Edits must follow references, as in a rename A live server per language; slow cold start

In practice, start with grep and reach for an index or LSP when names run out.

Tool design: editing

Approach How Risk
Whole-file rewrite The model regenerates the file Output scales with file size; untouched code drifts on long files
Unified diff / patch The model emits a patch that a tool applies Hunks fail when line numbers or context go stale
Search and replace An exact anchor string plus its replacement Fails on ambiguous, stale or whitespace-off anchors
Structured / AST edit An operation on a symbol, such as rename or add parameter Per-language tooling and a limited set of edits, but valid by construction

Tool design: execution and other tools

The shell is the most powerful and most dangerous tool. One call can chain, filter, loop and retry; it reaches the filesystem, network, package managers and binaries; files and processes outlive the call; whatever the shell can do, the agent can do. Design for isolation (where code runs and what it can reach), failure signals the agent can act on, output that is enough but not too much, duration (long-running and background processes) and budgets (when to stop retrying and hand back). Five other common tools: memory and notes (plans survive compaction), subagents (exploration returns a shortlist rather than 40 file reads), web search and fetch (read the installed source first, then the web), browser and visual feedback (screenshot the render and feed it back), and asking the user (one cheap question beats a confident wrong patch).

Few, orthogonal toolsOverlapping tools make the model dither between them
Purpose-built, not genericsearch_orders(customer_id) beats a raw run_sql
Token-cheap outputTruncate, paginate, summarize: tool design is context design
Errors that teachReturn the fix hint, not just “invalid argument”
Idempotent by defaultSafe to retry whenever possible

A purpose-built agent interface solves more issues than a bare shell

SWE-agent ablation on GPT-4, resolve rate, %

  1. Purpose-built SWE-agent18%
  2. Full interaction history15%
  3. Full-file view12.7%
  4. Shell only11%
  5. No specialized editor10.3%
Lecture 4 slides (SWE-agent ablation)

From prompt engineering to goal engineering

Period Name Question Concerns
2023–2024 Prompt engineering How should we instruct the model? Wording, examples, output formats
2025–2026 Context engineering What should the model see? Retrieval, memory, history, compaction
Now Harness engineering How should the agent operate? Loop, tools, sandbox, retries, stopping
Next Goal engineering What counts as success? Objectives, criteria, constraints, trade-offs
Technique How Use it when Move on when
Zero-shot Instruction only The task is common and the format fits in words The rule is tacit: few-shot
Few-shot Instruction plus a few examples The output shape is unusual or the rule is easier shown The task needs steps: chain-of-thought
Role and persona Give the model a role Tone or judgment matters; the audience is specific The task needs steps: chain-of-thought
Chain-of-thought Reasoning steps first, answer last The task has steps and errors come from skipped work Several paths exist: tree-of-thought
Tree-of-thought Branch, score, prune Several routes are plausible and cheap to score One right answer: self-consistency
Self-consistency Sample several times and vote One right answer and an expensive wrong call; route to a human below the floor (e.g. 3/5) Separable stages: chaining
Prompt chaining One job per call, validated handoffs Work splits into stages you can validate; retry only the failed stage The prompt itself is being tuned: meta prompting
Meta prompting The model rewrites its own prompt You have an eval set to score on Gains stall: revisit the choice

Four practices: start simple and add context only when needed; partition into sections (context, instructions, tools, output spec, in the order instruction, delimiter, data); be specific and concise, since clever phrasing buys nothing; split big tasks rather than front-loading complexity. Prompting advice is model-specific; re-tune when you switch models. Some techniques have already expired.

Context engineering: context is a finite resource

Karpathy’s definition: context engineering is the art and science of filling the context window with just the right information for the next step. Context costs in three ways: money (every step re-sends the window), latency (bigger prompts prefill and decode more slowly) and attention (recall fades as the window fills, and the middle gets missed).

Accuracy is lowest when the answer sits in the middle

Answer accuracy by position of the answer among 20 documents, %

  1. 76%1st
  2. 61%5th
  3. 55%10th
  4. 59%15th
  5. 71%20th
Liu et al., “Lost in the Middle”, TACL 12 (2024), cited in lecture 4

Length costs too: in Chroma’s Context Rot test, as input grew from 1K to 400K tokens, accuracy fell to 73% on simple lookup and 46% with distractors.

An illustrative budget for one agent turn: system prompt about 2K, tool definitions about 6K, project environment about 8K, retrieved context about 25K, message history about 80K and growing. When the window gets too large there are four strategies, from preventive and lossless to lossy and irreversible:

The first three strategies shrink context by 75% to 98% without summarizing

Tokens before and after, examples from the slides

  1. Admission · raw DOM48,000
  2. Admission · extract only900
  3. Offloading · 60 tool schemas42,000
  4. Offloading · index plus 33,100
  5. Transformation · every result96,000
  6. Transformation · newest state24,000
Lecture 4 slide examples
Strategy How
Admission Guard what enters: targeted retrieval (fetch fields, not documents), shape tool output, truncate only when shaping cannot, hand the raw payload to a subagent
Offloading Do not load until needed: progressive tool definitions, tool search (keep an index, fetch schemas on demand), tool output returned as a handle, task list kept on disk, persistent memory with a small index
Transformation Drop history selectively: deduplication (newest state of each object), observation masking (strip tool results older than N steps), sliding window (keep the head and recent turns)
Compaction The last resort, using an LLM: rolling summary, full summary at the limit, auto memory that persists key facts outside the window. Reserve headroom for output, preserve the system prefix, re-inject critical facts afterwards

Five ways context fails, and naming the failure makes the fix obvious: poisoning (a hallucination enters the window and is later cited as fact), distraction (history grows until the agent imitates its own past actions), confusion (irrelevant tools and documents steer the answer off course), clash (new and old information contradict and both stay) and drift (the real goal is buried and swapped for a nearby subgoal).

Changing only the harness: SWE-bench Verified rose from 43/169 to 72/169 and SWE-bench Pro from 31/316 to 72/316. The changes were compacting old tool outputs, keeping recent observations visible, detecting repetition and stalls, and intervening when stuck. Some apparent model failures are context and control-loop failures.
Further: beyond ReAct

ReAct loops every step. Reflexion loops after a failure (attempt, evaluate, critique, retry). Plan-and-execute loops on deviation (plan, execute steps, re-plan). Tree search does not loop: one wide pass explores branches in parallel and keeps the best.

Self-check

Which context strategy is each technique?

Fetch fields, not whole documents
Keep a tool index; load schemas on demand
Keep only the newest state of each object
Summarize history with an LLM at the limit
Hand the raw payload to a subagent
Strip tool results older than N steps

Self-check

“History grows until the agent imitates its own past actions.” Which context failure is this?

05LECTURE 5

Agent design II: multi-agent systems智能体设计 II:多智能体系统

Key points

  1. Multiple agents are not a default; the reasons to split are specialization, isolation, parallelism and context management.
  2. Every architecture answers three questions: who coordinates, how work is decomposed, how agents communicate. Real systems are hybrids.
  3. A subtask states its objective, boundaries, output and completion test; parallelism helps only when the work saved exceeds the coordination cost.
  4. Communication is a distributed systems problem: separate control from content, and handle timeouts with idempotency keys and rollback paths.

Three graphs and eight architectures

Every architecture answers three questions. The control graph: who coordinates, whether one supervisor, a hierarchy or nobody, and does that change at runtime (handoff)? The task graph: how is work decomposed, whether up front by a planner, by bidding or emergently from local rules? The communication graph: how do agents talk, by direct message, broadcast or a shared workspace?

Category Architecture Core idea Best for Weakness
Centralized Supervisor–worker One planner, many workers Separable, parallel subtasks The supervisor bottlenecks; its context grows fastest
Centralized Hierarchical Supervisors of supervisors Tasks that already decompose recursively Errors amplify; how much context crosses each boundary
Centralized Pipeline / DAG Each stage feeds the next through a typed contract Clear ordered stages Errors propagate with no path back; cheapest to debug
Decentralized Market / auction Agents bid on capability, cost and latency Dynamic allocation to the cheapest capable agent Bids are self-reported and can overstate ability
Decentralized Blackboard Coordination through shared state (database, filesystem, git repo) One shared artifact Stale state; consistency, concurrency, provenance, versioning, garbage collection
Decentralized Committee / debate Answer, then a judge or vote reconciles Judgment calls Groupthink: same model and context, same blind spot
Decentralized Swarm Direct negotiation, no coordinator Local negotiation O(n²) messages, hard conflict resolution; rare in products
Hybrid Dynamic topology Agents added, removed or rewired at runtime Unknown structure; simple tickets stay cheap Every run takes a different shape, so failures are hard to reproduce

Real systems are hybrids. A planner dispatches a dynamic task DAG to coder, researcher, tester and reviewer agents that share a git repository, re-planning when needed. That combines supervisor, hierarchy, shared memory and pipeline.

01Planner agent
02Dynamic task DAG
03Coder · researcher · tester · reviewer
04Shared git repository
05Re-plan if needed

Task decomposition

Work can be split by data (each agent takes some documents), expertise (security, performance, correctness, legal), stage (plan, implement, test, review), hypothesis (agents investigate competing explanations), tool (web, database, code execution) or authority (different administrative domains). A 200-file PR might be split by files, then by security and performance.

A good subtask states its objective, inputs and relevant context, boundaries and exclusions, available tools and permissions, expected output schema, completion test, budget and deadline, and dependencies.

Poor subtask

  • “Research storage systems”

Better subtask

  • “Identify storage-related papers published in 2026; return title, date, system contribution, evaluation scale and primary-source URL; exclude database query optimization”

Granularity is a trade-off: tasks too large leave little parallelism, tasks too small let scheduling and communication dominate. T(multi) ≈ T(planning) + T(critical path) + T(communication) + T(merge). Parallelism helps only when the sequential work saved exceeds planning, communication and integration costs; for example, 20 one-line lookups batched into 4 subtasks.

Decomposition can be static (known before execution, such as summarizing five PDFs) or dynamic (a dead link spawns a lookup task), recursive (a review agent spins up one subagent per subfield) or opportunistic (an idle agent picks up the next unlabeled document). Dynamic decomposition needs spawning limits, budgets, depth limits and termination conditions, or delegation explodes recursively.

Common failure Example
Overlap Two agents summarize the same paper
Gap “2020–2023” plus “2025–2026” skips 2024
Hidden dependency Pricing needs sizing, found only at run time
Unmergeable outputs One agent returns free text, another JSON
Lost global context Every section is fine; the report contradicts itself
Straggler Six agents finish in 20 s, one takes 4 minutes

Communication

Dimension Options Rule of thumb
Topology (who talks to whom) Supervisor–worker, peer-to-peer, mesh Mirror the task’s dependencies
Medium (how information is exchanged) Message passing (queue or bus), shared memory (such as a task list), files and artifacts (including databases) One medium per link
Channel (how it is passed) Point-to-point, broadcast, publish–subscribe, shared blackboard, request–response, artifact passing Broadcast only when all must know
Format and semantics Natural language plus control fields Route on the fields, not the prose

Natural language is flexible but ambiguous; structured messages are easy to validate but less expressive. A practical design uses both, with fields such as task_id, type, status, claim, confidence, evidence and artifact. Separate control from content: operations the runtime knows are DELEGATE, QUERY, REPORT, HANDOFF, UPDATE, CANCEL, ACK, ERROR and COMPLETE, so the runtime can route, retry and stop without asking an LLM what a message meant.

Communication is a hard distributed systems problem. Agent A tells B to “purchase 8 GPU instances” and the network times out with no reply. Did B execute? Retry or give up? At-most-once or at-least-once? Is exactly-once even available? Use an idempotency key on the task_id, plan a compensation or rollback path, and decide who pays for a double purchase.

Multi-agent systems inherit the problems of distributed systems: concurrency and non-determinism, unreliable networks (delay, drop, reordering, duplication), no global clock, partial failure (a slow agent looks like a dead one), consistency among replicated state, and debugging across logs with clock drift. They add scheduling (who runs next, and for how long), resource allocation (models, CPU) and state management (checkpoints, memory, provenance, versioning), with no predetermined request flow. Black-box LLMs make it harder still:

Problem What happens
Information loss Summaries drop what the worker knew
Context pollution What matters gets buried
Stale information B still acts on X=3 after X=5
Conflicting beliefs A says safe, B says vulnerable
Lost ownership Each agent thinks another owns it
Communication loops A asks B, B asks C, C asks A
Opaque failure Why did it fail?

A2A and MCP

A2A is the agent-to-agent protocol. Each A2A server publishes an Agent Card at /.well-known/agent-card.json with its identity, skills, endpoints, capabilities (such as streaming) and auth scheme. Three abstractions: a message (one turn between client and agent), a task (a stateful unit of work with an ID and a lifecycle) and an artifact (the task’s output). Follow-ups join the same task. A task moves from submitted to working, can pause for input or auth and resume, and ends completed, failed, rejected or canceled. Callers track long tasks by polling (short jobs), streaming (interactive output) or push notification (hours-long jobs). A2A standardizes communication, not orchestration: delegation, splitting and stopping stay with the harness.

01Submitted
02Working
03Pauses for input or auth, then resumes
04Completed · failed · rejected · canceled
MCP A2A
Primary abstraction Capability / tool Agent / task
Relationship Agent to service Agent to agent
Discovery Tools, resources, prompts Agent capabilities
Unit of work One tool invocation Long-running task
Internal state Capability interface Ideally opaque
Analogy Device or API interface Service-to-service RPC

One A2A remote agent may itself call twenty MCP servers. In MCP the host, not the model, decides what is exposed.

Design principles

  1. 01Ask whether multiple agents are necessary: when one agent is enough, more usually add only overhead
  2. 02Decide the topology from task dependencies and minimize communication
  3. 03Identify information-loss points: aggregation nodes are where detail drops
  4. 04Identify failure-containment boundaries so the system does not stall

A dense mesh is rarely the best default. More communication can raise context pressure without adding useful information.

Self-check

Which architecture suits each kind of task?

Separable subtasks that can run in parallel
Clear stages in a fixed order
Judgment calls
Dynamic allocation to the cheapest capable agent

Self-check

One agent covers 2020–2023, another 2025–2026, and 2024 is missed. Which decomposition failure is this?

06LECTURE 6

Agent design III: memory and reliability智能体设计 III:记忆与可靠性

Key points

  1. Every stage of memory is a policy decision: whether to write, what form, where to store, when to retrieve, how to generalize, when to forget.
  2. Memory needs valid time and provenance, and forgetting is a first-class operation.
  3. At 95% success per step, only 8% of 50-step runs are error-free; errors compound and propagate.
  4. Faults originate in the task specification, harness, model, tools and environment, and each has its own fix.

Six questions for agent memory

01Write or skip: is it worth keeping?
02Encode and organize: what should it become?
03Store: where should it live?
04Retrieve: does this task need it?
05Reflect: what broader lesson follows?
06Keep, update or delete: is it still valid?

Writing. Writing every interaction raises recall and noise; selective writing raises precision. Triggers can be an explicit user request, deterministic rules, a small classifier or a periodic LLM review.

Organization Example Trait
Raw events “We moved serving from vLLM to SGLang.” High fidelity; large and redundant
Unstructured summary “Uses SGLang for model serving.” Compact, may lose context
Structured state serving_engine = SGLang Queryable; the schema constrains
Knowledge graph Project → USES → SGLang Linked entities and change over time
Backend Examples Good at
Plain files CLAUDE.md, scratchpad Easy to inspect, diff and search
Key-value or relational database Redis, SQLite, Postgres JSONB Exact lookup, filtering, transactions
Vector store pgvector, Chroma, Pinecone Exact or approximate similarity search
Graph database Neo4j, FalkorDB (Graphiti) Relationship queries and multi-hop traversal
When memory is used How Strength Weakness
Automatic Search, LLM, add on every turn Predictable and simple Adds latency and irrelevant context
Runtime-controlled Search or add only when a condition holds Selective and efficient Needs rules or a classifier
Model-controlled Search, add, update and forget as tools for the LLM Demand-driven May miss useful reads or writes

Many systems mix them, and read and write policies may differ.

Retrieval. The basic pipeline is query, vector search, top-k, prompt. Semantic match is one signal; the others are scope (same user, project, entity or task), importance (the cost of missing or including it), validity (true for this task at this time) and provenance (source, confidence, evidence).

Reflection. Questions about vLLM, SGLang, TRT-LLM and LLM scheduling suggest the hypothesis “frequent interest in LLM inference systems, medium confidence”. Consolidate after enough new evidence (every N events or at context fill), when facts conflict or repeat, and in a background job when possible.

Forgetting is a first-class operation. Reasons: stale, incorrect or conflicting information, privacy and security, storage and retrieval cost. Controls: mark invalid, erase permanently, expire after a TTL, create tiers and evict from active memory. Memory needs valid time and provenance: “serves models with vLLM” held in April 2026 and was superseded in June by “serves with SGLang”, sourced to episode 28.

Ownership. Agent-owned memory is files in the harness (CLAUDE.md, a scratchpad, task notes) that the harness persists to disk. A dedicated memory system is a service the agent calls, which makes memory an API shared across agents and sessions.

Memory system Kind Input and retrieval
Mem0 Fact-centric Scoped by user, agent or run; filtered vector search, optional graph memory
Graphiti Temporal knowledge graph Entities and time-aware facts from episodes; hybrid semantic, keyword and graph search
supermemory Profile, memory and documents A user profile kept alongside memories and documents, linked to source and time
Failure mode What happens
Retrieval miss Relevant memory exists but isn’t found
Context pollution Too many irrelevant memories enter context
Memory hallucination An inference stored as fact: “studying at Harvard” becomes “visiting student at Harvard”
Staleness An old fact overrides newer information
Isolation failure Memory crosses a user boundary
Overgeneralization One event becomes a durable preference
Persistent prompt injection Untrusted content returns later as instructions
Unbounded growth Size grows with lifetime, so retrieval cost and quality degrade

Memory is evaluated on retrieval (precision, recall), writes and updates (precision, recall, stale-memory rate), governance (deletion compliance, scope isolation) and system cost (latency, token overhead, store growth). End-to-end benchmarks mainly test recall and reasoning over user–assistant histories, covering recall, temporal reasoning, updates, preferences and abstention: LoCoMo (ACL 2024, 10 long dialogues, 1,540 questions), LongMemEval (ICLR 2025, 5 memory abilities, 500 questions) and BEAM (ICLR 2026, up to 10M tokens, 2,000 questions). The memory stack takes two forms: a separate memory layer (an agent runtime, memory management such as Mem0 or Letta, and vector, SQL, graph or object storage), or memory inside the harness (managed by the runtime, stored as Markdown files).

Reliability: errors compound

At 95% per step, only 8% of 50-step runs are error-free

Chance a run is error-free, %, by number of steps, assuming independent steps

  1. 95%1 step
  2. 77%5
  3. 60%10
  4. 36%20
  5. 8%50
Lecture 6 slides (0.95 to the power n)

A run succeeds only if every step does, and error propagation makes real runs worse than this. Faults originate in five places: the task specification, the harness, the model, the tool layer and the environment.

Failure Example Fix
Ambiguous goal “Fix the login bug”; fixed the wrong one of three Name the file, symptom and repro
Proxy objective “Make the tests pass”; deleted the failing test Forbid test edits; review the diff
Unstated constraint “Speed up search”; broke the public API State what must not change
No definition of done “Clean up the parser”; never stopped refactoring Give an exit test and a stop rule
Conflicting goals “Minimal diff, every edge case”; silently dropped edge cases Rank the goals explicitly
Specification: write “done” as a testAcceptance tests up front; list what must not change
Harness: bound every runStep, cost and time caps; checkpoint and roll back
Model: demand evidenceProof for every claim; verify; use stronger models
Tool: fail loudlyTyped schemas; errors distinct from empty results
Environment: pin and isolateFresh, pinned sandboxes; retry flakes before judging

We do not yet understand agents at scale, and there is little formal best practice.

Self-check

Where did each fault originate?

Told to “make the tests pass”, it deleted the failing test
No step or cost budget: 200 steps, no progress
“Tests probably pass now”, with nothing run
A date with no time zone: a job 8 hours off
Failed because of a leap year

Self-check

At 95% success per step, independent steps, how likely is a 20-step run to be error-free?

07LECTURE 7

Agent design IV: evaluation智能体设计 IV:评估

Key points

  1. The object of evaluation moved from the base model to model, prompt, tools and harness together, graded by tests and environment state.
  2. Eight representative benchmarks each test one environment: Q&A, function calls, the web, the desktop, a repository, customer service, a terminal and a simulated company.
  3. It is hard because leakage has four layers, single-turn tasks reward guessing, and success rate alone ignores cost and safety.
  4. Benchmarks saturate ever faster; a real agent is judged on capability, cost and speed together.

History and objectives

An agent can be evaluated by component (planning and decomposition; memory extraction, consolidation and retrieval; tool discovery, selection and parameterization; error recovery) or end to end (success rate, cost per task, time to finish). Benchmarks are moving toward larger scope, less specific instructions, more realistic use and newer problems.

Period Representative benchmarks Focus
Before 2018 Penn Treebank, WikiText, LAMBADA, SQuAD Language modeling, narrow tasks
2018–2019 GLUE, SuperGLUE, ARC, HellaSwag, WinoGrande Transfer learning, general understanding
2020–2022 MMLU, BIG-bench, GSM8K, MATH, HumanEval, TruthfulQA, HELM Foundation-model capability
2023–2024 MT-Bench, Chatbot Arena, IFEval, LongBench, MMMU, GPQA, AgentBench, WebArena, GAIA, SWE-bench, OSWorld, τ-bench Agents and tool use, context, modalities
2024–2025 MMLU-Pro, LiveBench, LiveCodeBench, FrontierMath, Humanity’s Last Exam Difficulty, robustness, freshness
2025–2026 GDPval, BrowseComp, Terminal-Bench, ARC-AGI-3 Larger scope, more realistic use
Objective Representative benchmarks What success means
Predict text PTB, WikiText High probability on observed text
Produce a correct answer MMLU, GSM8K, GPQA, HLE Match a known answer
Produce a preferred response Arena, AlpacaEval, MT-Bench Favorable human or model judgment
Produce functioning code HumanEval, LiveCodeBench, SWE-bench Pass executable tests
Complete an interactive task WebArena, OSWorld, τ-bench, Terminal-Bench Reach the required environment state

Metrics: earlier benchmarks used perplexity (exponentiated average negative log-likelihood on held-out text, lower is better), accuracy or F1, and preference win rate. Capability uses pass@k (at least one of k attempts passes) and pass^k (all k pass, introduced by τ-bench). Cost is mostly LLM cost; tool calls and cache misses are often overlooked. Latency is not only the LLM’s.

The benchmark loop: for each task, reset the environment to the task’s initial state; while not terminated and within budget, observe, let the agent pick an action from the instruction, observation, history and tools, and execute it; finally an evaluator scores the final answer, the final environment state and the trajectory.

Eight representative benchmarks

Benchmark Agent operates in Typical actions Graded on Notes
GAIA Web, file and code tools Search, inspect files, calculate A short final answer 466 human-written questions in 3 levels (≤5 steps, 5–10 steps, arbitrarily long); tests the whole agent system; does not test actions such as sending email or booking
BFCL Function and API interface Structured function calls Calls, arguments and resulting state AST or execution checks; typical errors are invented IDs (should ask the user) and irrelevant calls; read category scores, not the composite
WebArena Self-hosted websites Click, type, move between pages Website or backend state 812 tasks across shopping, admin, Reddit, GitLab, maps, Wikipedia; accessibility-tree observations; WebArena-Verified drops the LLM judge for deterministic checks on HTTP traces
OSWorld A full desktop VM Mouse, keyboard, apps Files, app and system state 369 tasks with screenshot observations; OSWorld 2.0 (2026) has 108 long workflows, often over an hour, with about 27 checkpoints for partial credit
SWE-bench A software repository Inspect, edit, run tests Whether the patch passes tests Variants: Verified (human-checked), Lite (300 tasks), Multilingual (9 languages), Multimodal, Pro (harder, multi-file)
τ-bench Customer-service APIs and dialogue Talk to a user, call APIs Database state and the reply An LLM simulates the user; the agent is bound by airline policy; reward is action × output; read-only calls may vary but unintended writes fail
Terminal-Bench An isolated terminal container Arbitrary shell commands Task-specific verifier tests Programming, sysadmin, data processing, model training, security, science; 89 tasks in TB 2.0, 66 in TB 4.0 after pruning saturated ones; 8-hour timeout
TheAgentCompany A simulated software company Web apps, code, files, talking to coworkers Workflow checkpoints and final state 175 tasks across software, PM, data science, HR, finance; partial score = 0.5 × earned/total + 0.5 × full completion

Terminal-Bench sits between SWE-bench and OSWorld: the agent acts through shell commands in a container and sees terminal output, on tasks that configure, debug, repair and build, with no mouse-coordinate grounding, so it tests long-horizon reasoning and system interaction. pass^k is much stricter than pass@k: all k independent runs must succeed, not one.

Why evaluation is hard

Training leakageThe task or its human fix was in the training data
Eval-time leakageThe agent searches the web and copies the future fix
Environment leakageThe sandbox exposes future commits or hidden tests
Benchmark overfittingPrompts and scaffold tuned on the public test set

Agent performance is roughly a function of the LLM, prompt, scaffold, tools, retriever, memory and environment, and any of them can carry benchmark information: solutions used as fine-tuning trajectories, answers indexed in a RAG corpus, earlier attempts kept in memory, researchers tuning on test failures. Saying “the model was not trained on the test set” is nowhere near sufficient. Realistic tools are required for agent evaluation, and they widen the leakage surface.

A single user turn. Most benchmarks give one fully specified instruction: prompt in, final state out, no user in the loop. Real work is ambiguous, revised and interrupted, and single-turn scoring rewards confident guessing because a clarifying question costs steps and earns nothing. Worth testing: does the agent ask when the goal is underspecified, re-plan after a mid-task correction, and carry constraints across turns?

Other challenges: success rate alone cannot tell a 200-step, $40 run from a 12-step, $0.30 run; non-determinism makes single-run scores noise; nothing penalizes deleted files, sent emails or money spent on the way to a pass; outcome-only scoring passes lucky or unsafe runs, while trajectory matching fails valid ones.

The frontier reaches each baseline faster

Months from a benchmark’s release to the frontier reaching the stated baseline

  1. GLUE (2018) · human level 87.114 mo
  2. MMLU (2020) · expert level 89.839 mo
  3. GPQA Diamond (2023) · PhD experts 69.710 mo
  4. SWE-bench Verified (2024) · 33% → 95%22 mo
  5. ARC-AGI-2 (2025) · average human 6011 mo
  6. ARC-AGI-3 (2026) · 0.5% → 62.7%6 mo
Lecture 7 slides

Benchmarks saturate quickly. As of September 2026, SQuAD, GLUE, SuperGLUE, MMLU, MATH, HumanEval, Chatbot Arena, MT-Bench, WebArena, SWE-bench Verified, GPQA Diamond, MMMU and OSWorld are saturated; FrontierMath, Humanity’s Last Exam, ARC-AGI-2 and 3, Terminal-Bench, GDPval, SWE-bench Pro, Remote Labor Index and OSWorld 2.0 remain open. Saturated means the frontier reached the human baseline or top models stopped separating.

Dimension Earlier evaluation Current frontier
Object evaluated The base model Model plus prompt, tools and harness
Interaction Static, single-turn Stateful, long-horizon
Grader Exact match or likelihood Tests, environment state, humans or judge models
Dataset Fixed and public Fresh, hidden, dynamic or contamination-aware
Main metric Average accuracy Reliability, quality, cost and latency beside success
Primary concern Generalization across examples Robust completion under realistic constraints and safety requirements
A real-world agent is judged on capability, usability, cost and speed together. The slides rank by Pareto dominance: A dominates B if A is no worse on any metric and better on at least one, and rank 1 is the Pareto frontier.

Self-check

A task runs 4 times independently and succeeds once. What are pass@4 and pass^4?

Self-check

What is each benchmark graded on?

GAIA
SWE-bench
τ-bench
OSWorld

08LECTURE 8

Agent design V: cost, speed and harness architecture智能体设计 V:降本、提速与 harness 架构

Key points

  1. Cost is users × sessions × turns × steps × tokens × price; the middle three shrink with shorter trajectories, the price with caching, batching and routing.
  2. Cache reads are most of the tokens, and every token left in context is paid for again on every later step.
  3. Every saving has a counter-cost: measure the net effect on the same tasks and cap each task’s budget.
  4. Completion time is the critical path; harness architectures run from monolithic to modular to microkernel as responsibility moves from code to services.
01Turns per task
02Steps per turn
03Tokens per step
04Price per token

Fewer turns and steps

This lecture covers LLM cost only, not other compute costs.

Turn k re-reads turns 1 to k−1, so total cost grows with the square of the turn count. In the course’s own Claude Code logs, single-prompt sessions were 68% (assignment 1) and 75% (assignment 2), and a few marathon sessions ran past 100 turns. Users come back because there was no plan, the agent stopped early or it never checked. The remedies are confirming goal and plan once before acting, splitting into subtasks that each carry a done check, and self-verifying before handoff, so the task finishes with no user check-ins.

Most turns take few steps (largely because effort was set to medium or high), but some ran almost 1,000. Every model call re-reads the full context, so fewer calls cost less: batch independent calls into one step (read five files in one step, not five), reuse plans and skills that worked, and load the files you need at the start. Related work covers skill libraries (Voyager, SkillRL), insights from experience (ExpeL, ReasoningBank), plan-template caching and durable conversational memory (Mem0, LightMem, SimpleMem). Reuse pays when tasks recur; memory upkeep and stale entries can erase the savings.

Fewer tokens per step

97.6%Share of tokens that were cache reads, assignment 1
208K / 301KMain-agent median context per step (assignments 1 / 2)
~80KSubagent median per step; p90 about 200K
1 : 10 : 50Typical price ratio: cache read, input, output

Output was about five times smaller than fresh prefill (cache writes), and fresh prefill about a hundred times smaller than cache reads. Context grows fast, reaching 650K to 670K tokens around step 500. Tokens that stay in context are paid for again on every later step.

Reduce input How
Drop what is stale Truncate stale results; compact the history; mask tool outputs already used; summarize old turns into state
Shrink what enters Compress observations, keeping errors rather than the full log; save big outputs to files and pass a path
Load only what is needed Retrieve selectively, with only relevant tools and memory; isolate exploration in a subagent that returns a summary

Related results: ACON cut peak context by 26% to 54%; LLMLingua reached up to 20× fewer tokens, though prompt compression pays off only on long prompts; MemGPT treats context as fast memory; filtering MCP results in code took 150K tokens to 2K; tool search cut tool tokens by 85% and programmatic tool calling by 37%. TRACE found that summaries cause rework.

For output: state length, format and what to skip in the prompt (“answer in 100 words or fewer”, “return only JSON”, “don’t restate the problem”); set max_tokens in the API (it can cut an answer mid-sentence, and reasoning can use up the cap); require a schema with only the needed fields (restrict enums and optional fields; prose around a tool call is pure cost); and match reasoning effort to the step (low for lookups and formatting, high for planning and debugging). Strict formats can hurt reasoning.

A lower price per token

Batching plus caching brings input to 5% of the base price

Price per token relative to base input, Claude API

  1. Output token5×
  2. Base input token1×
  3. Batch input0.5×
  4. Cached input0.1×
  5. Batch plus cached input0.05×
Lecture 8 slides

Keep prefixes stable (system prompt, tools, early history) and batch what can wait (evals, backfills, bulk jobs). Model routing comes in three forms: choose up front (a router trained on preference data, which can also pick agent roles, as in RouteLLM and MasRouter), escalate on failure (a cheap model first, a larger one when a check fails; checks can be a learned scorer, self-verification or execution feedback, as in FrugalGPT, AutoMix and EcoAssistant) and re-route each step (on history and budget, with an orchestrator calling models as tools, as in ToolOrchestra). The hard part: one cheap planning mistake can waste many later actions. System techniques for lowering price come in later lectures: MoE, quantization, pruning, distillation and workload-targeted fine-tuning; speculative decoding, KV-cache optimization and better scheduling; faster kernels and specialized accelerators.

Every saving has a counter-cost

Technique Counter-cost
Compaction Dropped files get re-read, and the summary rewrites the cache
Routing A bad plan from a cheap model adds steps or a failed attempt
Subagents Each subagent re-reads the shared files and instructions
Speculation Wrong guesses burn tokens and contend for the same tools

Net saving = gross saving − counter-cost, measured on the same tasks. Cap each task’s budget (illustrative limits: $10, 80 model calls, 15 minutes of tool time, 2 retries per step) and stop when the verifier passes, no new test passes in N steps, the same error repeats, or a limit hits, handing off with a summary. Limits can be set from traced runs, for example at twice the p95 of successful tasks. A stopped task with a summary costs less than a runaway one.

  1. 01Same steps every time: have the LLM write the script once, then just run it
  2. 02Fixed input format: parse with regex, parsers and templates at no cost per call
  3. 03Narrow label or score: train a small classifier
  4. 04Fixed workflow with little reasoning: script the workflow and call the LLM only at the steps that need it

Making the agent faster

Completion time is the critical path, not the sum of every step. Faster is usually cheaper, but not always: small models may take more steps, and parallel work spends more tokens.

Speed up LLM servingEvery cost technique above also cuts latency: fewer turns, steps and tokens, cheaper serving
Improve orchestrationAsynchronous execution (start the next step while a tool runs), persistent sessions (one shell or browser across steps), streaming and pipelining (start the tool call before the response finishes), colocated services
Speed up tool callsBuilds, tests and page loads can outlast the model call: cache tool results, run heavy compute on a server, use faster tools, time out hung calls; measure tool time per step before tuning the model
ParallelizeIssue independent tool calls in one step; split independent subtasks across parallel subagents and merge their summaries; shared state needs a merge step
Speculative actionsA cheap model predicts the next action, which runs while the main model thinks; a match skips the wait, a miss costs one discarded call; it pays when guesses are often right and actions can be undone

What is speculated ranges from the next tool (SPORK) and the tool with arguments (PASTE) to any action, several branches (B-PASTE) and a whole executed chain. Predictions come from a draft model, from an early fork of the same model, or from history (PASTE sees that a search is usually followed by a visit and fills the URL from the result to run it early). The open question: how to schedule speculative calls under limited GPU, CPU and API budgets so that the critical-path time saved exceeds the work wasted.

Optimization is a loop: run and log every call, token, tool and wait; measure where cost and latency come from; change one thing (compaction, routing, caching or parallelism); re-evaluate success, spend and p95 latency on the same tasks; repeat.

Three harness architectures

Dimension Monolithic Modular Microkernel
Design principle Everything in one runtime Interfaces, one controller Minimal core plus services
Replacing a component Difficult Easy (Docker to Firecracker is one provider swap) Easy, if protocols match
Execution isolation Optional Optional An architectural emphasis
Deployment Usually together Together or separate Often independent
Independent scaling Limited Possible Strong
Communication cost Low Low to medium Potentially higher
Typical use Standalone agents Agent frameworks Multi-agent infrastructure
Strengths Simple to build and debug; easy shared state Clear responsibilities; testable; third parties plug in Independent scaling, fault isolation, shared infrastructure
Weaknesses Tight coupling; hard to share infrastructure The controller still owns the lifecycle; coordination grows complex More failure modes, harder end-to-end debugging, needs standard protocols

Running one Python snippet: the monolith executes it locally, with the fewest hops but weak isolation; the modular harness calls SandboxProvider.run(code), so you swap the provider, not the agent; the microkernel sends a request to an execution service that owns allocation, isolation and sandbox lifecycle. Responsibility moves from code to interfaces to services.

What is unique in eight harnesses

Harness Profile Distinctive design
Claude Code Anthropic, TypeScript, closed A policy layer and typed hooks around Claude
Codex CLI OpenAI, Rust Sandbox before approval: commands run in a sandbox with no network, and the agent asks only to leave it; a Lark grammar sets the patch envelope, and hunks are matched in four passes
DeepSeek Harness TypeScript Even the loop is a plugin, replaceable through YAML layers; each request is a frozen view of the session log, to which the harness only appends; compare-and-swap edits fail if the file changed since the model last read it
OpenCode TypeScript, Bun The harness is a server: the TUI, SDKs and web app share one OpenAPI HTTP server; nine replacers go from exact to anchor match and reject fuzzy matches that are too large; a shadow git repository snapshots each step so /undo restores files
Pi TypeScript A minimal core of four tools, with no MCP, subagents or approvals; cache warming only when the expected saving is $0.05 or more; pi-ai supports 42 providers on 10 wire APIs
oh-my-pi TypeScript plus Rust Hashline edits: a 4-hex file tag plus line numbers, so the model never retypes old text; one shell stays open, with native search, AST, LSP and a debugger; snapcompact turns old history into images
OpenClaw TypeScript A gateway for 27 chat channels with one queue lane per session; before compaction a silent turn writes dated notes, and recall combines full-text and vector search; fences isolate untrusted text, a network read taints the turn, and secret sentinels are monitored
Hermes Agent Python A background fork examines nudged turns and edits memory and skills; compaction starts at 50% of the window, the earliest of the eight; tool-call rows are written to the session database before any side effect

Self-check

Which saving carries each counter-cost?

Dropped files get re-read; the summary rewrites the cache
A cheap model’s bad plan adds steps or a failed attempt
Each one re-reads the shared files and instructions
Wrong guesses burn tokens and contend for tools

Self-check

On the Claude API, batched and cached input costs about what share of the base input price?

09LECTURE 9

LLM basics: the life of a request and the transformerLLM 基础:一次请求的生命周期与 Transformer

Key points

  1. A request passes through six stages: tokenize, schedule, prefill, decode, detokenize, stream.
  2. Prefill is compute-bound and sets time to first token; decode is bandwidth-bound and sets tokens per second.
  3. KV-cache size per token caps concurrency; GQA brings Llama 3 70B to 320 KB per token.
  4. In MoE, memory scales with total parameters and compute with active ones.
01Tokenize
02Schedule
03Prefill: time to first token
04Decode and sample: tokens per second
05Detokenize
06Stream

Six stages

  • Tokenize. Text is split into tokens, not words, at about 3 to 4 characters per token: “Serving is hard” is four tokens. Token count drives cost and memory, and tokenizers differ across models. Byte-level BPE starts from the 256 byte values and repeatedly merges the most frequent adjacent pair, so there are no unknown tokens. A bigger vocabulary means fewer tokens but a larger embedding table.
  • Schedule and batch. Requests arrive independently and GPUs want batches. Continuous batching lets requests join or leave at any step, with no wait for a full batch; admission is capped by KV-cache memory.
  • Prefill. The whole prompt runs in one pass with all prompt tokens attending in parallel. It is compute-bound, its cost grows with length, and it builds the KV cache and emits the first token.
  • Decode and sample. One forward pass per new token, and the cache grows by one token per step. It is bandwidth-bound, so batch it; when the cache is full, preempt or queue. Sampling picks the next token from the logits, and its settings change the answer and how long the request runs (table below).
  • Detokenize and stream. Token IDs become text as they are produced, with partial characters buffered. A stop token, length limit or disconnect ends the stream, and stopping early frees cache memory.
Sampling setting Example Effect
temperature 0 0 always takes the top token; above 1 widens the choice
top-k 50 Samples from the k most likely tokens; k is fixed
top-p 0.9 The fewest tokens summing to p; adapts to confidence

The transformer

01Token IDs
02Embedding: each ID becomes an 8,192-dim vector
03Transformer block × 80: self-attention plus FFN
04LM head: one score per vocabulary token
05Softmax: next-token probabilities

A model is a stack of identical transformer blocks. Integer token IDs enter an embedding that turns each into a vector (8,192 dimensions in Llama 3 70B); they pass through L blocks (80 in Llama 3 70B), each with self-attention (mixes information across tokens) and a feed-forward network (transforms each token on its own); an LM head scores every vocabulary token, and softmax turns scores into probabilities.

Each block is pre-norm with a residual stream: RMSNorm, then attention, added back to the stream; RMSNorm, then the FFN, added back again. RMSNorm rescales by the root mean square with one learned gain per dimension; pre-norm keeps deep stacks stable in training; the residual stream flows through all 80 blocks, and each sublayer only adds an update.

Self-attention lets each token read every earlier token. Each token emits a query Q, key K and value V (X times learned weight matrices). Q·K divided by √dₖ decides how much to read from each token; the scaling stops softmax from saturating, because the dot product grows with dₖ. A causal mask puts −∞ above the diagonal to hide future tokens, softmax makes each row sum to 1, and the output is a weighted mix of the rows of V. n tokens give n² scores, about 4n²d FLOPs per layer. Storing the score matrix S for 8,192 tokens, 64 heads and 80 layers would take about 690 GB; FlashAttention computes softmax tile by tile and never stores S.

Step Formula Shape
Input X n × d
Queries Q = X W_Q n × dₖ
Scores S = Q Kᵀ ÷ √dₖ n × n
Weights A = softmax(S + M) n × n
Output O = A V n × dᵥ

Multi-head attention splits Q, K and V into 64 heads of 128 dimensions, runs masked attention in each, and mixes them with Wₒ. Since 64 × 128 = 8,192, the FLOPs equal one wide head: splitting changes what is learned (some heads attend to the previous token, the first token, nearby tokens, the whole context), not the cost.

The KV cache and shared KV heads

KV cache per token = 2 × layers × KV heads × head dimension × bytes per value. In MHA each query head has its own KV head; GQA lets groups of query heads share KV heads; MQA shares one KV head across all. With 8 query heads, their KV caches are 1×, ¼× and ⅛×. Llama 3 70B’s 64 query heads share 8 KV heads: 2 × 80 × 8 × 128 × 2 B = 320 KB per token, against 2.5 MB with MHA.

Llama 3 70B Value
Model width d 8,192
Layers L 80
Query heads H and head dimension dₖ 64 and 128
KV heads 8
FFN hidden width 28,672 (3.5 × d)
Vocabulary V 128,256

Most of Llama 3 70B’s parameters sit in the FFN

Parameters, billions, by component

  1. Attention (80 layers)12.1B
  2. FFN (80 layers)56.4B
  3. Embedding and LM head2.1B
Meta, The Llama 3 Herd of Models (2024); derived in lecture 9

Attention takes about 151M parameters per layer and the FFN about 705M; 80 layers make 68.5B, and with the embedding and LM head the total is 70.6B. The attention and FFN totals in the chart are the per-layer figures times 80.

Systems intuition

141 GBWeights (BF16, 2 bytes per parameter)
141 GFLOPsCompute per token (about 2 × parameters)
320 KBKV cache per token

On two H200s (1,978 TFLOP/s, 9.6 TB/s and 282 GB in total), an 80,000-token prompt takes about 9.95 s to prefill and 167 GB of memory for one request, and 637 s and 1,779 GB for 64 requests. Compute grows with n² and the KV cache linearly with n, which is what makes long sequences hard.

MoE: memory scales with total parameters, compute with active ones

MoE replaces each block’s FFN with a router and a set of smaller expert FFNs; only a few run per token (for example 2 of 8), and their outputs are summed with weights.

Model Experts Total Active per token Weights (BF16)
Llama 2 70B All (dense) 69B 69B 138 GB
Mixtral 8x7B 2 of 8 46.7B 12.9B 93 GB
Llama 3.1 405B All (dense) 405B 405B 810 GB
DeepSeek-V3 9 of 257 671B 37B 1,342 GB

DeepSeek-V3 activates only 37B parameters per token

Active parameters per token, billions; GFLOPs per token are about twice this

  1. Llama 2 70B69B
  2. Mixtral 8x7B12.9B
  3. Llama 3.1 405B405B
  4. DeepSeek-V337B
Jiang et al. 2024; DeepSeek-AI 2024; Touvron et al. 2023; Llama Team 2024; cited in lecture 9

Same quality, less compute: Mixtral matches Llama 2 70B at about a fifth of the FLOPs, and DeepSeek-V3 rivals Llama 3.1 405B at about an eleventh, but needs 1.7 times the memory.

Further: eight advanced variants
Variant How Serving effect
Sliding window Local layers read only the last w tokens; a few global layers keep long-range recall (Gemma 3: 5 local to 1 global, w = 1,024; Mistral 7B: all local, w = 4,096) At 128K context, Gemma 3 stores about 6× less KV than all-global layers
Multi-latent attention (MLA) Cache one compressed latent per token and rebuild K and V when needed DeepSeek-V2 cuts KV cache 93% against DeepSeek 67B and lifts generation throughput 5.8×
Linear attention A fixed-size state updated in place; Gated DeltaNet fades the old state, then overwrites (Qwen3-Next: 36 GDN plus 12 attention layers; Kimi Linear and Qwen3.5 use the same 3:1 recipe) Three of four layers hold a constant-size state per request at any length
State-space models A small state per channel whose decay each token sets (Mamba’s selectivity; Mamba-2 turns the scan into matmuls) No growing KV cache; Mamba reports up to 5× a transformer’s generation throughput
Sparse attention A light indexer scores past tokens and each query reads only the top 2,048 (DeepSeek-V3.2) Work per token is capped, but every token’s KV is still stored
Looped transformers One block applied K times Depth costs compute and latency, not weights
Multi-token prediction Predict several tokens at once Listed by name only in the slides
Diffusion LMs Fill masked tokens over a few parallel refinement steps (LLaDA 8B, Dream 7B) One pass fills many tokens, but fewer steps cost quality

Self-check

Which stage is bandwidth-bound and sets tokens per second?

Self-check

Llama 3 70B has 80 layers, 8 KV heads, head dimension 128, in BF16. How large is its KV cache per token?

10LECTURE 10

GPU basics: why decode is bandwidth-boundGPU 基础:为什么 decode 受带宽限制

Key points

  1. A GPU trades a few fast cores for thousands of simple ones and hides memory latency by switching warps.
  2. Every kernel is bounded by peak compute, memory bandwidth and capacity; the roofline’s ridge point separates the two kinds of bottleneck.
  3. Batch-1 decode uses 0.5% of an H200’s peak compute; batching helps, but decode attention stays bandwidth-bound.
  4. Compute grows faster than bandwidth each generation; reaching full bandwidth means keeping more bytes in flight.

GPU and CPU

64-core server CPU NVIDIA H200 SXM
Parallel units 64 cores 132 SMs, 16,896 FP32 cores
Threads in flight 270,336 (2,048 per SM)
Memory bandwidth about 0.46 TB/s (DDR5) 4.8 TB/s (HBM3e)
Peak dense math about 5 TFLOPs FP32 989 TFLOPs BF16
Hides latency by Caches, out-of-order cores Switching to a ready warp

A CPU is a sports car that carries two riders fastest; a GPU is a bus fleet, slower per trip but moving thousands. LLMs fit GPUs because every token runs the same matmuls on the same weights.

  • Warp switching hides memory latency. While one warp waits on memory, another issues, so the math units stay busy. On A100, H200 and B200, each SM has four warp schedulers that manage up to 16 warps each, 64 resident warps per SM.
  • SIMT. One warp instruction drives 32 threads; fetch, decode and scheduling are paid once, the work of 32 scalar instructions.
  • Branch divergence. When threads in a warp take different branches, the warp runs both paths in turn: f might use 8 of 32 lanes and g the other 24.
The GPU gives up In exchange it gets
Single-thread speed (modest clock, no speculation; serial code runs far slower) Area and power spent on thousands of arithmetic units
Implicit parallelism (about 270K threads to fill 132 SMs; small jobs leave the chip idle) Latency hidden by switching warps, not by caches and speculation
Independent control flow (threads run in groups of 32; divergence costs throughput) One fetch and decode drives 32 cores
On-chip memory per thread (about 240 bytes at full occupancy) Every thread’s state stays resident, so warp switches are free

Three limits and the roofline

Memory bandwidth rises each generation, but more slowly than compute

HBM bandwidth, TB/s; Rubin preliminary

  1. 2 TB/sA100
  2. 4.8 TB/sH200
  3. 8 TB/sB200
  4. 22 TB/sRubin
Lecture 10 slides (NVIDIA datasheets)
A100 H200 B200 Rubin
Peak BF16 compute (how fast the math runs) 312 TFLOP/s 989 TFLOP/s 2,250 TFLOP/s about 4,000 TFLOP/s
Memory bandwidth (how fast weights and KV are read) 2.0 TB/s 4.8 TB/s 8 TB/s about 22 TB/s
Memory capacity (how many weights and KV entries fit) 80 GB HBM2e 141 GB HBM3e 180 GB HBM3e 288 GB HBM4

Compute is the engine, bandwidth the fuel line, capacity the tank. Kernel time ≈ max(bytes ÷ bandwidth, FLOPs ÷ peak).

Decode, batch 1: compute waits

  • 3.3 ms per token
  • 16 GB of weights read from HBM
  • Each weight used once: 0.016 ms of math waits on 3.3 ms of reads
  • Tensor cores idle 99.5% of the time

Prefill, 2,048 tokens: compute is busy

  • 33 ms per prompt
  • HBM idle once weights are loaded
  • Each weight feeds 2,048 tokens, so math sets the pace
  • 33 TFLOP, near peak

The roofline uses arithmetic intensity, FLOPs per byte moved to or from HBM, to find the limit. The ridge point is peak FLOP/s ÷ bandwidth, about 206 FLOP/B on H200. Left of the ridge a kernel is memory-bound (speed = bandwidth × intensity); right of it, compute-bound (speed = peak).

Operation Arithmetic intensity (b bytes per element)
Vector add, length N 1/(3b)
GEMV (decode), N × N, each weight used once about 2/b
Decode attention, each KV entry used once per head 2/b
Square GEMM, each element reused about N times 2N/(3b)

Batch-1 decode is a GEMV at about 1 FLOP/B and reaches about 5 of the H200’s 989 TFLOP/s, 0.5% of peak. To raise it, increase arithmetic intensity: batch more, quantize, shrink KV traffic. Batching lifts weight GEMVs toward the ridge (256 at batch 256), but decode attention stays at 2/b because each request reads its own KV.

With longer context, most bytes read per decode step come from the KV cache

HBM bytes read per decode step, GB; Llama 3 8B, batch 16, BF16; weights fixed at 16.1 GB

  1. 18.2 GB1K
  2. 24.7 GB4K
  3. 33.3 GB8K
  4. 50.5 GB16K
  5. 84.8 GB32K
Lecture 10 slides (from the Llama 3 paper and H200 datasheet)

The KV cache is 128 KiB per token and grows with batch × length; at 4.8 TB/s a step takes 3.8 ms at 1K and 17.7 ms at 32K. Lower precision pushes the ridge further right: Rubin’s dense NVFP4 needs about 1,600 FLOP per byte to be compute-bound. From A100 to Rubin, BF16 compute grows about 13× and bandwidth about 9×, so kernels are increasingly bandwidth-bound.

Inside the H200

The H200 has 132 SMs that share a 50 MB L2 cache and 141 GB of HBM3e in six stacks at 4.8 TB/s, with 900 GB/s of NVLink to other GPUs. Each SM has four partitions, each with 64 KB of registers, 32 FP32 cores and a tensor core, issuing one warp instruction per cycle; the SM shares 256 KB of L1 and shared memory and keeps 2,048 threads resident.

Tensor cores perform a small matrix multiply-add D = A × B + C (such as 16×16 by 16×8) per instruction: one mma is 2,048 multiply-adds, 64 times an FMA’s work. Matmuls are over 99% of LLM FLOPs; softmax and norms use the FP32 cores. They are fast for four reasons: fewer instructions per FLOP, dedicated multiply-add datapaths, operand reuse (each value of A feeds several output columns, each value of B several rows), and lower precision (FP16, BF16, FP8) that raises throughput and shrinks operands, usually with higher-precision accumulation.

Memory level (H200) Capacity Latency (Hopper) Bandwidth
Registers 256 KB per SM In the pipeline Read every instruction
Shared memory / L1 256 KB per SM About 30 cycles (40 for an L1 hit) 128 B/clock per SM, about 33 TB/s over 132 SMs
L2 cache 50 MB About 250 cycles About 12 TB/s on Hopper
HBM3e 141 GB in 6 stacks About 500 cycles 4.8 TB/s
Host memory and peer GPUs Microseconds NVLink 4 450 GB/s each way; PCIe 5.0 about 64 GB/s

Memory is a 250 ns pipe

Little’s law: bandwidth = bytes in flight ÷ latency. A naive kernel keeps about 4 KB in flight per SM and reaches 2.2 TB/s, 45% of peak; filling 4.8 TB/s needs about 9 KB per SM (4.8 TB/s × 250 ns ÷ 132). The hardware fixes the pipe’s length, so the only way to raise bandwidth is to keep more bytes inside it: 16-byte vector loads, four independent loads per thread, and bulk asynchronous copies (TMA).

H200 (Hopper) B200 (Blackwell) Rubin
HBM 141 GB HBM3e 180 GB HBM3e 288 GB HBM4
Bandwidth 4.8 TB/s 8 TB/s 22 TB/s
Bytes in flight, GPU 1.2 MB 2.0 MB 5.5 MB
Bytes in flight, per SM 9 KB 14 KB 25 KB
New data-path feature TMA, clusters TMEM, 2-SM MMA Inline TMA descriptors

Further detail: coalescing merges 32 threads’ consecutive 4-byte reads into one 128 B request; 16-byte vector loads let one warp instruction move 512 B; cp.async (Ampere and later) copies into shared memory without staging in registers; Hopper’s TMA lets one thread start a whole tile copy, putting tens of KB in flight from one instruction, and TMA multicast lands one L2 read in the shared memory of every SM in a cluster of up to 8 thread blocks; Blackwell keeps results in 256 KB of tensor memory, freeing registers for more loads, and pairs two SMs on one matrix multiply, each fetching half the shared tile.

From one GPU to many

HGX H200 (8-GPU node) GB200 NVL72 (rack)
Layout 8 GPUs over NVSwitch; 8 NICs at 400 Gb/s to the scale-out network Rows of 4 GPUs plus 2 CPUs, 9 rows joined by NVLink switches
HBM bandwidth 4.8 TB/s 8 TB/s
NVLink 900 GB/s 1.8 TB/s
RDMA 50 GB/s 100 GB/s

From G80 (2006) to B300 (2025), peak math grew about 43,000× and bandwidth about 90×. Two decades moved from graphics to general-purpose compute (CUDA, caches, HBM2, NVLink, tensor cores), then to low-precision AI engines (TF32, BF16, FP8, TMA, FP4, TMEM, NVL72).

Further: other accelerators
Chip Traits Programming
AMD MI355X 8 compute dies seen as one GPU; 256 MB Infinity Cache; 64-thread wavefronts; 5.0 PF dense FP8, 288 GB, 8 TB/s ROCm and HIP; PyTorch, vLLM and SGLang run; Triton or Composable Kernel
Google TPU Ironwood Weight-stationary systolic arrays in a 3D torus of 9,216 chips; 4.6 PF dense FP8, 192 GB, 7.4 TB/s JAX or PyTorch/XLA; Pallas for custom kernels
Amazon Trainium3 8 NeuronCores per chip, each with tensor, vector and scalar engines; 32 MB software-managed SRAM per core, no hardware cache; 2.5 PF MXFP8, 144 GB, 4.9 TB/s Neuron SDK; NKI kernels in Python move tiles explicitly; no CUDA
Cerebras WSE-3 A whole wafer as one chip, 44 GB on-chip SRAM, no off-chip memory Larger models stream weights in
Groq LPU 230 MB SRAM, no off-chip memory A 70B model at 8 bits needs about 300 chips
Microsoft Maia 200 272 MB SRAM plus 216 GB HBM3e Available only inside Azure

Self-check

The in-class question: during batch-1 decode, what share of an H200’s peak compute is used?

Self-check

What limits each operation on an H200?

Square GEMM, N = 8192
Batch-1 GEMV
Decode attention
Prefill of 2,048 tokens

∞SOURCES

Sources and notes

  • All content comes from the ten public slide decks in this folder, 1_intro to 10_llm_serving_basics_2a, Harvard CS2680, Juncheng Yang, course site cs2680.com.
  • Third-party data cited in the slides keeps its source: ReAct (arXiv 2210.03629), Liu et al., “Lost in the Middle” (TACL 2024), Chroma’s Context Rot, Breunig, “How Contexts Fail” (2025), Lewis, “Same Model, Different Harness” (arXiv 2608.26218), Anthropic, “Building a C compiler”, Codex and OpenAI internal usage reports (June and September 2026), Meta’s Llama 3 paper, NVIDIA whitepapers and datasheets, and each benchmark’s original paper.
  • Left out: course overview, grading and policy, assignments and deadlines, computing resources, in-class exercises and “next class” slides. The two assignment-sharing PDFs (assignment3_sharing, assignment3_feedback) are password-protected and were not read.
  • Charts are redrawn from the values in the slides. The attention and FFN totals for Llama 3 70B are the per-layer figures in the slides times 80; every other value is as given in the slides.