{
  "schema_version": "1.0",
  "id": "T-26244cf419a9",
  "url": "https://gpuatlas.top/articles/T-26244cf419a9/",
  "title": "KV cache 到底是什么，为什么会占掉那么多显存？",
  "summary": "KV cache保存生成注意力状态，容量由层、KV头、头维、长度、活动量及精度共同决定，特殊架构需另算。",
  "language": "zh-Hans",
  "category": {
    "id": "c-02",
    "name": "推理与上下文",
    "url": "https://gpuatlas.top/categories/c-02/"
  },
  "topics": [],
  "body_text": "KV cache保存语言模型生成时部分注意力Key和Value，新token可以复用此前状态，减少重复计算，但这些状态需要内存或显存。权重装下以后，长文和活动请求仍会继续消耗预算。\n\n常规完整历史自注意力可用条件公式：2×层数×KV头数×头维×保留token×活动序列×每元素字节。第一个2代表K和V，结果是字节，不含分页、元数据、权重和其他缓冲。\n\n假设32层、8个KV头、头维128、8192 token、单序列、每元素2字节，得到1073741824字节，即1GiB。这里只是说明公式的假设结构，不是某个命名模型实测，KV头不能随意用查询头替代。\n\n滑窗、混合线性注意力、共享或其他特殊状态不能机械按全部层完整长度计算。动态、静态、量化与卸载策略也改变分配和执行，固定缓存可能提前预留，降低GPU空间也可能增加时间或质量取舍。\n\n加载通过、长度或活动量增加后失败时，缓存是重要候选，但还需看输入临时峰值。先固定文件和单请求，再逐项比较必要长度、活动数或支持策略，权重低位不自动改变缓存。\n\n从单人短聊改成长历史或多条会话后才失败，可把这两种变化分别复现，观察缓存分配和输入峰值。保存对应结构、缓存类型、精度与保留长度，CPU参与时一并记录主存。这样才能说明容量被哪些状态占用，而不是只凭模型多少B或启动时的一张截图判断。",
  "published_at": null,
  "modified_at": "2026-11-26T15:17:38.690397+00:00",
  "evidence": {
    "type": "documentation_and_conditional_estimates",
    "hardware_tested": false,
    "note": "资料解释与条件估算，非硬件实测。"
  },
  "sources": [
    {
      "id": "transformers-kv-cache",
      "url": "https://raw.githubusercontent.com/huggingface/transformers/main/docs/source/en/kv_cache.md",
      "retrieved_at": "2026-11-25T10:07:29.175278+00:00"
    },
    {
      "id": "vllm-memory",
      "url": "https://raw.githubusercontent.com/vllm-project/vllm/main/docs/configuration/conserving_memory.md",
      "retrieved_at": "2026-11-25T09:52:45.997121+00:00"
    },
    {
      "id": "llamacpp-server",
      "url": "https://raw.githubusercontent.com/ggml-org/llama.cpp/master/tools/server/README.md",
      "retrieved_at": "2026-11-25T09:52:45.997121+00:00"
    }
  ],
  "revision_note": "完善阅读结构；非硬件实测。",
  "representations": {
    "html": "https://gpuatlas.top/articles/T-26244cf419a9/",
    "json": "https://gpuatlas.top/data/articles/T-26244cf419a9.json",
    "markdown": "https://gpuatlas.top/data/articles/T-26244cf419a9.md"
  }
}
