面向边缘设备(Apple M4 Pro, 24 GB)的多智能体 KV cache 持久化系统。通过将每个 agent 的 KV cache 以 Q4 格式持久化到磁盘并直接在量化张量上做注意力计算,将上下文恢复从 $O(n)$ prefill 降为 I/O-bound 加载。三个架构不同的模型上实现 11–136× TTFT 加速、4× agent 容量、PPL 影响 −0.7% 至 +3.0%。
边缘设备(24 GB 统一内存)上的多智能体 LLM 推理面临内存生命周期问题。FP16 KV cache 在 8K 上下文长度下仅能容纳 3 个 agent(Gemma 3 12B, M4 Pro, 10.2 GB cache 预算)。每次 agent 切换必须全量 re-prefill——Gemma 3 12B 在 4K context 下需 15.7 秒。边缘设备的 token 处理速度约 260 tok/s(M4 Pro),比数据中心 GPU(10,000+ tok/s)慢 40×。
将多 agent 的对话历史拼接到一个长 prompt 引入二次注意力开销($(20K/4K)^2 = 25\times$)和位置偏差。分离 KV cache 避免此问题,但在固定 RAM 设备上 $N$ 个 agent × $C$ tokens 需要缓存生命周期管理。
三组件系统:
ModelCacheSpec 抽象层覆盖 GQA(Gemma 3 / Llama 3.1,对称 K=V)和 MLA(DeepSeek,非对称 K=192, V=128),所有上层组件对模型架构无感。
核心技术壁垒: 多智能体交替执行(一个 agent 生成时另一个加载 cache)提供时间间隙隐藏磁盘 I/O 延迟。这使 KV cache 持久化仅在 UMA 设备上具备架构可行性——SSD→内存带宽约 7 GB/s,占统一内存带宽的 ~2.6%,加载后以全带宽访问。在离散 GPU 上,PCIe 5.0 瓶颈使 VRAM→host 带宽从 1,792 GB/s 骤降至 ~64 GB/s(28× 悬崖),此方案不具吸引力。block pool 作为 page table、SSD 作为 swap,系统实现了对注意力状态的虚拟内存语义。

Paper Figure 1: System architecture. Multiple agents maintain isolated KV caches in a persistent block pool. The Q4 pipeline quantizes cache data on save and operates directly on quantized tensors during attention.
系统自上而下三层:Agent 层(Code Assistant、Reviewer、Planner 等各持 2K–4K context)→ Block Pool 层(per-agent namespace 隔离,256-token 固定块大小)→ Q4 Pipeline 层(量化 + fused attention + safetensors 持久化)。数据流双向:Save 路径将 FP16 KV 量化为 Q4 写入磁盘,Load/Reload 路径从 safetensors 直接加载 Q4 张量进入注意力层。关键性能标注:30–130× TTFT 降低、72% 内存节省、亚秒级重载。

Paper Figure 4: Architecture comparison. Gemma 3 uses GQA with hybrid sliding-window layers (8 global + 40 sliding, K=V=256). DeepSeek uses MLA with asymmetric K/V dimensions (K=192, V=128) and MoE routing. Both connect to the model-agnostic block pool through ModelCacheSpec.
ModelCacheSpec 定义层数、KV head 数、head 维度和量化参数,是模型无关性的抽象边界。GQA 模型需要 5D query reshape($(B, n_{kv}, n_{rep}, L, D)$)实现 broadcast 兼容,以及 window-aware chunked prefill mask;MLA 模型需要额外的 v_head_dim 字段处理非对称维度,MoE routing 产生更大中间张量预算(4096 MB vs Gemma 的 2048 MB)。两类架构的差异被 ModelCacheSpec 封装,上层 block pool 和 Q4 pipeline 完全共用。
Batched Quantized Inference: BatchQuantizedKVCache 实现 merge(左填充 + 按 batch 维堆叠)→ update_and_fetch(统一 batch 注意力 + KV 更新)→ extract(拆回 per-agent cache),将两个 agent 的 decode 合并为单次 Metal kernel dispatch。ConcurrentScheduler 在 prefill 阶段按 512 token 块交替处理多 agent,在 decode 阶段交替生成,适配 Orca 的 iteration-level 调度到量化 cache + 边缘设备场景。MLX 非线程安全,所有推理经单线程调度器串行执行(RLock 保护跨线程 I/O)。
Prefix Matching: 采用字符级文本比较而非 token ID 比较,避免 BPE 分词的上下文依赖性(相同文本在不同上下文可产生不同 token 序列)。返回 EXACT / EXTEND / DIVERGE 三种匹配状态,50% 公共前缀阈值决定复用资格。多阶段工作流中 prompt 单调增长,实际总是 EXTEND 匹配。
无形式化作者证明 — 仅实证。 系统包含解析性内存模型(Q4/FP16 比率推导),但无形式化性能/收敛保证。可形式化但未形式化的量:给定内存预算 $M$、agent 数 $N$、SSD 带宽 $B_{ssd}$,warm cache TTFT 的上界。
| 符号 | 含义 | 取值范围 |
|---|---|---|
| $h$ | KV head 数 | 8(Gemma/Llama), 16(DeepSeek) |
| $d$ | head dimension | 128–256 |
| $n$ | 序列长度(tokens) | 1K–32K |
| $g$ | 量化 group size | 64 |
| $B$ | batch size | 1–2 |
| $L$ | 层数 | 27–48 |
| $D_K$, $D_V$ | K/V head 维度 | 对称 128–256 或非对称 192/128 |
FP16 每层 KV 存储:$4hdn$ bytes(K + V 各 $2hdn$)。Q4 每层存储:$hdn(1 + 8/g)$ bytes(4-bit packed 数据 + bfloat16 scale 和 bias per group)。
$$Q4/FP16 = (1 + 8/g) / 4 = 0.281 \quad (g = 64)$$
物理意义:无论模型维度如何,Q4 一律节省 72% 内存。Gemma 3 12B 在 4K context 时每 agent FP16 需 1,536 MB($2 \times 8 \times 256 \times 4096 \times 2 \times 48$ bytes),Q4 仅需 432 MB。
GQA 的 batched attention 需要将 query reshape 为 5D 张量 $(B, n_{kv}, n_{rep}, L, D)$,其中 $n_{rep} = n_q / n_{kv}$(Gemma: 16/8 = 2),实现 broadcast 兼容。
| # | 检验项 | 预期 | 实际 | 判定 |
|---|---|---|---|---|
| 1 | 内存比率 0.281 在三模型一致 | Q4/FP16 ≈ 0.281 | Table 2 + Appendix D 均验证 | ✓ |
| 2 | 4× agent 容量提升 | Q4 fits ≈ 4× FP16 | 24 vs 6 (4K), 12 vs 3 (8K), 6 vs 1 (16K) | ✓ |
| 3 | Cold TTFT 线性缩放 $O(n)$ | 线性关系 | Fig 2: 三模型 cold 均线性(双对数直线) | ✓ |
| 4 | Warm/Hot TTFT 近平坦 | 弱依赖 $n$ | Gemma warm 475–1819 ms (1K–32K),32K 处上翘因 cache > 3 GB | ✓ |
| 5 | PPL 影响 < 5% | 可容忍降级 | −0.7% / +2.8% / +3.0%,与 KIVI 4-bit 文献一致 | ✓ |
| 6 | Cross-phase 加速随阶段累积 | Phase $N$ > Phase 1 | Table 7: 1.0× → 1.9× (Phases 1–5, Gemma) | ✓ |
实验规模: 1,132 次独立测量 + 36 次交错到达测试。3 个模型 × 6 上下文长度 × 3 cache 状态 × 2 batch 大小。每配置 6 次取中位数,11–240 秒自适应冷却(thermal-aware)。硬件:Apple MacBook Pro M4 Pro, 24 GB LPDDR5X, 273 GB/s。

Paper Figure 2: TTFT scaling across cache states (Gemma solid, DeepSeek dashed, Llama dotted). Cold prefill scales linearly; warm and hot caches reduce TTFT by up to 136× at 32K (Gemma) and 111× at 16K (Llama).
Cold TTFT 随 context 线性增长(Gemma 32K 达 172 秒),Warm/Hot 近乎平坦(Gemma 32K warm 仅 1.8 s / hot 1.3 s)。16K 下加速倍数:Gemma 93×, DeepSeek 45×, Llama 111×。Llama 获得最高 warm 加速比因其 8B 参数量使 warm reload 相对其 cold prefill 更快。DeepSeek cold 最快(27 层 vs Gemma 48 层)但 warm 加速比相应较低。
意外发现:短 context(1K–8K)下 Gemma/Llama 的 warm(磁盘加载)比 hot(内存驻留)更快 40–55%,在 6 次测量中全部重现无交叉。原因:mx.load() 的优化顺序 I/O 路径 vs hot 路径的 per-layer hash 查找和散列内存访问。32K 时反转(disk I/O 占主导,cache > 3 GB)。

Paper Table 5: Head-to-head TTFT comparison. Agent-memory uses Q4 KV with disk persistence; vllm-mlx uses FP16 KV with volatile prefix cache. Both share the same mlx-lm inference engine, isolating cache strategy differences.
4K 下 Q4 warm(290 ms)与 FP16 prefix(290 ms)完全持平——读取 4× 小文件的 SSD 时间抵消反量化开销。vllm-mlx 在 8K 时需独立测试(多 context 配置下 FP16 被驱逐),16K 时即使单 context 独立运行也在第 3 次测量失败。Cold prefill vllm-mlx 快 2.3×(4K: 4,394 ms vs 10,235 ms),差距源于 agent-memory 的编排层开销而非 Q4 量化本身(用 FP16 KV 的 agent-memory 仅快 259 ms)。Restart 后 agent-memory 保持 warm 状态,vllm-mlx 全部丢失。

Paper Figure 5: Agent cache state across prisoner's dilemma phases. Permanent agents (Warden, Marco, Danny) start cold and transition to warm/hot via cross-phase injection. The Analyst appears only in Phase 5 (cold start).
5 阶段(审讯 A → 审讯 B → 庭院 → 最终对峙 → 裁决)、4 agent(3 永久 + 1 临时)、25 轮对话。Persistent 模式在 Phase 1 无优势(均冷启动),Phase 5 TTFT 降低 1.9×(Gemma: 3,292 ms → 1,705 ms),总耗时降低 23%(72.9 s → 56.1 s)。DeepSeek 改善较小(1.3×)因其 27 层冷启动本身已快。10-expert Wikipedia 路由场景中 warm cache 实现 24.2× TTFT 降低(Gemma: 20.5 s cold → 847 ms warm)。

Paper Table 11: Feature comparison. Pool = per-agent cache isolation, BQ4 = batched Q4 inference, WM = cross-phase KV persistence, Edge = UMA device support, Disk = persistent cache survives restart.
本系统是唯一同时具备 per-agent isolation、batched Q4 inference、working memory、edge device 支持和 disk persistence 的方案。最接近的是 llama.cpp(Q4 KV + per-slot save/restore),但使用 GGML 后端、需手动 API 调用、无自动多 agent 管理。MemArt 有 KV reuse blocks + working memory 但面向数据中心。vllm-mlx 有 prefix caching 但无量化 KV、无持久化。
Q4 KV cache PPL 影响(WikiText-2, 512-token 滑动窗口,256-token 步幅):Gemma −0.10 PPL(−0.7%),Llama +0.12(+2.8%),DeepSeek +0.19(+3.0%)。Gemma 对称 KV 维度(K=V=256)提供冗余吸收量化噪声;DeepSeek MLA 将 K/V 压缩为低秩潜在表示(非对称 K=192, V=128),冗余更少,量化误差影响更大。局限:512 token 窗口短于 Gemma 的 sliding-window attention(window=1024),未报告置信区间。
| # | 论点 | 依据 | 隐含假设 |
|---|---|---|---|
| 1 | 边缘设备固定 RAM 下,$N$ 个 agent 各持 $C$ tokens 需缓存生命周期管理;拼接有 $O(n^2)$ 注意力开销 | §2.1-2.2, Table 1:M4 Pro 仅 10.2 GB cache 预算;FP16 at 8K 仅放 3 agents | agents 需独立 KV cache(位置偏差使拼接方案不可接受) |
| 2 | Q4 量化使 KV cache 内存降低 72%(比率 0.281),4× agent 容量提升 | §3.2, Table 2:解析推导 $(1+8/g)/4$,三模型实测验证 | group quantization ($g=64$) 的量化误差可容忍——PPL 影响 < +3% |
| 3 | 磁盘持久化将 $O(n)$ compute-bound prefill 替换为 $O(n)$ I/O-bound reload | §3.1, Table 3:Gemma 4K cold 15,736 ms → warm 577 ms(27×) | UMA SSD 带宽(~7 GB/s)足够亚秒级重载;safetensors 零反序列化开销 |
| 4 | 多 agent 交替执行为 cache 重载提供时间间隙——Agent A 生成时 Agent B 加载 | §5.1:block pool = page table, SSD = swap 的虚拟内存类比 | agents 确实交替而非并行;$1/N$ 重载延迟落入临界路径(未端到端测量) |
| 5 | Head-to-head vs vllm-mlx:Q4 warm 与 FP16 prefix 速度相当,但 Q4 在高内存压力和 restart 后仍可用 | §4.4, Table 5:4K 下 290 ms vs 290 ms;FP16 在 16K 失败 | 两系统共享同一推理引擎(mlx-lm),对比仅隔离 cache 策略 |
开源仓库: agent-memory — 19 天 44 sessions 开发,301 commits,17.8K 行源码 + 31K 行测试 + 12.7K 行 benchmark 基础设施。
| 组件 | 实现位置 | 说明 |
|---|---|---|
| Block Pool / AgentBlocks / KVBlock | 仓库核心模块 | per-agent namespace 隔离,256-token 块,safetensors 持久化 |
| BatchQuantizedKVCache | 仓库核心模块 | merge / update_and_fetch / extract,左填充 + batch 堆叠 |
| ConcurrentScheduler | 仓库核心模块 | 单线程调度器 + RLock,512 token chunk prefill |
| ModelCacheSpec | 仓库核心模块 | 模型无关抽象,含 v_head_dim 支持 MLA 非对称维度 |
| quantized attention patch | mlx-lm monkey-patch | fused Q4 scaled dot-product attention, mx.compile(shapeless=True) |
| prefix matching | 仓库核心模块 | 字符级文本比较,EXACT / EXTEND / DIVERGE |
| OpenAI-compatible API | 仓库服务层 | drop-in 兼容,支持 SSE streaming |
KV cache 磁盘持久化的架构可行性取决于 SSD→内存带宽比率和多 agent 交替提供的 I/O 隐藏窗口。UMA(Apple Silicon)SSD 以 ~7 GB/s 读入 273 GB/s 统一内存,一次加载后全带宽访问。离散 GPU(RTX 5090)VRAM 1,792 GB/s 内部带宽,但 PCIe 5.0 host↔device 仅 ~64 GB/s,28× 悬崖使每次 cache miss 代价高昂。此外系统依赖 MLX 的 quantized_scaled_dot_product_attention 在 Q4 张量上直接做注意力——若无 fused Q4 attention kernel,需反量化回 FP16 再计算,消除延迟优势。
mx.eval(),遗漏任一点导致空 cache、OOM 或 attention NaN(paper 记录 6 种故障模式)。MLX 非线程安全(并发 mx.eval() 触发 Metal assertion failures),系统被迫采用单线程调度器 + RLock 的协作式并发模型——batch=2 的两个 agent decode 合并为单次 Metal kernel dispatch 而非真并行。开发中最隐蔽的 bug(batch=2 cache corruption)的初始假设(lazy tensor chain)被验证脚本自身的串行时序掩盖,最终定位为 scheduler 线程和 event loop 间的竞态条件。