[TokenSpeed 源码解读] 模型、Attention 与 KV Cache

解读 TokenSpeed 如何把模型适配、Attention prologue、backend 路由和多组 KV Cache recipe 组合成统一执行契约。

src/pages/articles/_md/AI/Infra/Inference/TokenSpeed/CodeWiki/main-2026-11/04-model-attention-cache.md

← 返回概览


模块定位

runtime/models/ 与 runtime/layers/attention/ 把 Hugging Face checkpoint 语义翻译成 TokenSpeed 的执行契约。模型文件负责网络结构和权重命名;PagedAttention 负责 projection 后到 core attention 前的统一 prologue;Attention backend 负责读 cache 并执行注意力;cache recipe 负责把模型需要的历史/状态声明成 scheduler 与物理 arena 都能理解的 group。

模块边界的关键原则是:模型描述需要什么,不亲自管理 page。即使模型数量很多,page allocation、prefix match、write location 和 backend selection 仍集中在公共层,避免每个新模型复制一套 KV Cache 逻辑。

模块架构

模型、PagedAttention、Backend、CacheRecipe 与 CacheArena
模型、PagedAttention、Backend、CacheRecipe 与 CacheArena

ModelRegistry 扫描 runtime.models 下导出 EntryClass 的模块,并把 Python 类名作为 HF architectures 的解析键;插件还能显式注册或覆盖 architecture。模型构造 PagedAttention layer,并通过 attention config 选择组件。cache recipe 按 group → pack → bind 生成 CacheMemoryPlan 与 scheduler-facing group specs;CacheArena 独占字节分配,多种 target/draft CachePool 只是带 layer window 与 dtype 的 typed view。

运行期 CacheGroupRouter 把 scheduler 的逻辑 block table 扩成 backend 所需的 kernel page table,并统一产生 write locations。PagedAttention 调用 prologue 完成 QK norm、RoPE、量化和 KV write,再让 backend 只做 core attention。

调用链路

一次 PagedAttention 前向的 prologue、写缓存与 core attention
一次 PagedAttention 前向的 prologue、写缓存与 core attention

模型投影得到 q/k/v 或 MLA latent;PagedAttention.forward() 从 backend/router 取得本层写位置,调用 gqa_prologue() 或 mla_prologue();prologue 验证 shape/dtype/stride,应用可选 norm 与 RoPE,并写入 CacheArena 对应 field;随后 backend 从 page table 和 cache view 执行 prefill/decode attention。backend 不再重复写 KV,避免不同实现对同一 cache 产生两套副作用。

方法速查表
方法 一行职责 关键设计决策
_ModelRegistry.resolve_model_cls() HF architecture → model class 内置实现与插件覆盖共用一个解析口
CacheRecipe.setup() 声明 group、pack layout、绑定容量 一个 family 只有一条 cache pipeline
CacheArena.__init__() 分配 regions、materialize fields、发布 contract arena 是内存与几何唯一所有者
CacheGroupRouter.write_locations() 逻辑 table → 物理 slot 模型不计算 page/slot 算术
PagedAttention.prologue() norm/RoPE/量化/KV write 所有 paged layer 只有一个写入口
PagedAttention.attend() 调用 core attention backend backend 只读 cache,不负责存储
AttentionBackend.refresh_decode_metadata() 原地刷新 decode metadata eager/graph 共用同一 contract

核心实现

Model registry 以 EntryClass 约定发现模型

registry 在启动解析模型包,收集每个模块公开的 EntryClass,再用类名匹配 checkpoint 的 architectures:

@lru_cache
def import_model_classes():
    model_arch_name_to_cls = {}
    package = importlib.import_module("tokenspeed.runtime.models")
    for _, name, _ in pkgutil.iter_modules(package.__path__, package.__name__ + "."):
        module = importlib.import_module(name)
        if hasattr(module, "EntryClass"):
            entry = module.EntryClass
            # list 形式允许一个模块公开多个 architecture class
            ...
    return model_arch_name_to_cls

ModelRegistry = _ModelRegistry(import_model_classes())

这个约定省掉了第二份手写映射表:类名本身就是 architecture key。_try_load_model_cls() 会先检查 plugin registry;插件覆盖内置类时必须显式声明 override=True,避免同名实现被静默替换。

Attention prologue 统一所有 KV writer

gqa_prologue() 把 QK RMSNorm、RoPE、量化与 KV write 视为一个算子;mla_prologue() 对 latent attention 提供相同契约。模型只在 PagedAttention(..., rotary_emb=..., qk_norm=...) 声明步骤,不自行调用 RoPE 再复制 cache。

if k is not None and not ctx.forward_mode.is_idle():
    out = self.prologue(q, k, v, positions, ctx)
    q, k, v = out.q, out.k, out.v
return self.attend(q, k, v, ctx, **kwargs)

decode 时 prologue 返回 k=None, v=None,表示输入已经准备并写入 cache;prefill 则可把新 K/V rows 交给 core attention。backend 固定收到 save_kv_cache=False。统一 writer 让不同 backend、eager/graph、PD layerwise timing 都共享一次副作用,也能用测试枚举合法的例外 writer。

CacheArena 是几何与字节分配的唯一真相

CacheArena 同时持有 CacheMemoryPlan、physical CacheStoragePlan、regions、field views 和 CacheRuntimeContract。CachePool 不再镜像 prefix_granularity 或自己分配 tensor:

class CacheArena:
    """Own the cache allocation, its typed field views, and its contract."""

    @property
    def prefix_granularity(self) -> int:
        return self.plan.prefix_granularity

这个设计允许 target 与 draft 对同一 arena 建立不同 dtype/layer window 的 view,却不会出现“两个 pool 各自报告 page count,scheduler 选错一个”的双重真相。

Recipe 把模型语义压成通用三类 group

每个 cache family 的 CacheRecipe.setup() 依次执行 group、pack、bind:group 声明 Full/SWA/State 与 fields,pack 计算一个物理 parent 内如何布局,bind 根据显存预算决定 parent 数并生成 runtime contract。模型特有几何留在 recipe 或专用 geometry 模块,scheduler 只接收 group id、granularity、page count、packing 与 retention。

logical block 与 kernel page 只在 router 相遇

scheduler 的 block granularity 是资源与 prefix identity 单位,backend 的 kernel_page_size 是 Kernel 读取单位。CacheGroupRouter 是唯一转换点,write location 公式也只在 mapping 层维护。模型不应出现 page_id * page_size + offset;否则 QCP/KVP、packing 或新 cache format 一变,模型实现就会携带过期假设。

设计模式

模式 位置 为什么用
Registry models/registry.py checkpoint architecture 与实现类解耦
Template Method CacheRecipe.setup() 固定 group/pack/bind 次序,子类只填 seam
Adapter CacheGroupRouter scheduler block table 转成 backend page table
Single Owner CacheArena 内存、field view、geometry 与 contract 不重复
Strategy AttentionBackend 同一 PagedAttention 可换 paged/state/vendor backend

模块间交互

上游 ModelExecutor 构造 ForwardContext 并刷新 backend metadata;下游 tokenspeed-kernel.ops.attention.prologue 与各 family public API 实际执行算子。cache recipe 在 startup 把 contract 同时交给 scheduler 和 arena,运行期两边只交换 block table/page id 等轻量值。

扩展方式

新增模型时,先复用已有 layer、Attention config 和 recipe;只有缓存字段或 retention 真正不同才新增 recipe。新增 Attention backend 必须声明 kernel page size、支持的 cache format 与 graph 能力,并通过 router 获取 table/write locations。不要在 backend 写 KV,也不要在模型里重新实现 norm/RoPE/store 链。