ncnn推理框架教程 · 05-KVcache专属通道与LLM化改造

05 - KV cache 专属通道与 LLM 化改造

所属系列:ncnn 推理框架教程 | 前置:04-Mat张量与内存池:lightmode即时回收 | 下一篇:06-层注册与ISA运行时分发
证据基线:commit eb8a50d2。本章主战场:src/net.cpp、src/layer/multiheadattention.cpp、src/layer/sdpa.cpp、src/layer/gemm.h、src/layer/gemm.cpp、src/layer/arm/gemm_arm.cpp。
所有断言 Observed in source(标注处除外)。本章是本版本(eb8a50d2)最显著的"新面":ncnn 的 LLM 能力如何落地。

本篇知识图谱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((KVcache专属通道))
设计哲学
不走引擎层
改层与分配器
无KV管理器 无分页
专属分配通道
set_kvcache_allocator
必须异于blob_allocator
convert_layout 豁免
batch 互斥校验
容量策略 层内
hint 预分配
否则 reserve 16到256
增长 capacity除2
旧数据 memcpy 迁移
容量编码 cstep除w
复用判定 allocator相等
输出路径
type 1 保留打包布局
MHA SDPA K V 强制type1
Gemm块量化
W4 6 8bit
块32 64 128
quantize_term 编码
Gemm_arm 五档分派

本篇目标

  1. 理解 ncnn "LLM 化"的路线选择:不改引擎、不加 KV 管理器,能力下沉到层与分配器。
  2. 拆懂 kvcache_allocator 专属通道的准入规则与特权(跳过布局转换)。
  3. 掌握 层内容量策略:hint 预分配、16~256 起步、capacity/2 增长、cstep/w 编码容量。
  4. 认识 Gemm 层的 W4/6/8bit×块 32/64/128 权重块量化谱系与 Gemm_arm 的五档分派。

1. 路线选择:LLM 化不走引擎层

与 llama.cpp 的 Memory 家族(引擎级 KV 管理:slot 分配、defrag、seq 操作 API)对照,ncnn 的选择截然不同(Observed in source 的结构事实):

  • 引擎层只加了两个钩子:Extractor::set_kvcache_allocator/set_kvcache_max_seqlen_hint(src/net.h:203/:206),C ABI 同步暴露(src/c_api.h:66-67)。没有 KV 管理器类、没有 slot 概念、没有 seq_rm/shift 这类序列操作 API。
  • 真正的逻辑在两个注意力层里:MultiHeadAttention 与 SDPA 各自内嵌 create_or_grow_kvcache(src/layer/multiheadattention.cpp:267-305、src/layer/sdpa.cpp:53-91)。
  • 运行时状态依旧住在第 04 章的 blob_mats 槽里:KV cache 不是特殊存储,就是普通 Mat,只是换了分配器。

这套设计的含义(Derived):ncnn 不想做 LLM 服务引擎,它只想让"把一个自回归模型当计算图跑"成为可能——图的驱动循环(token by token 调 extract)仍由宿主 App 承担。

2. 专属分配通道:准入规则与特权

extract 入口的守门(src/net.cpp:3298-3316):

1
2
3
4
5
6
7
8
9
10
11
12
if (d->opt.kvcache_allocator && d->opt.kvcache_allocator == d->opt.blob_allocator)
{
NCNN_LOGE("kvcache_allocator must be different from blob_allocator"); // :3298-3301
return -1;
}
#if NCNN_BATCH
if (d->opt.kvcache_allocator)
{
for (...) if (d->blob_mats[i].n > 1)
NCNN_LOGE("kvcache does not support batch"); return -1; // :3304-3313
}
#endif

两条硬规则:① kvcache_allocator 必须异于 blob_allocator(否则直接拒绝执行——原因见第 4 节的复用判定:靠"指针身份"区分 KV blob,混用即失效);② kvcache 与 batch 互斥(任何 blob 带 n>1 即拒绝)。层内也有一致的第二道闸:MultiHeadAttention::forward 开头 if (kv_cache && bottom_blobs[0].n > 1) return -1;(src/layer/multiheadattention.cpp:310-313)。

通道内的两个"特权":

  1. 跳过布局转换:convert_layout 第二行就是 if (opt.kvcache_allocator && bottom_blob.allocator == opt.kvcache_allocator) return 0;(src/net.cpp:400-402)——KV blob 永不被 fp16/packing 协商改写,布局由注意力层完全自治。
  2. 统一的回收出口:层执行后的 bottom release 条件是 opt.lightmode || (opt.kvcache_allocator && bottom_blob.allocator == opt.kvcache_allocator)(src/net.cpp:804-807,批路径 :774-777)——即无论 lightmode 开关如何,KV blob 的槽引用都会在层后立即释放,它没有别的释放路径;注意 release 只减第 04 章的引用计数,真正的容量命运由层自己决定(下一节)。

3. 层内容量策略:分配、增长、复用、迁移

两层的 create_or_grow_kvcache 逐行同构(以 SDPA src/layer/sdpa.cpp:53-91 为准读,MHA 在 multiheadattention.cpp:267-305):

① 复用判定靠分配器指针身份(:55-57):

1
2
3
Allocator* allocator = opt.kvcache_allocator;
const bool reuse = !cache.empty() && cache.allocator == allocator;
const int current_capacity = reuse ? (int)(cache.cstep / cache.w) : 0;

cache.allocator == opt.kvcache_allocator 是"这确实是经专属通道分配的 KV blob"的唯一凭据——这正是第 2 节禁止混用分配器的原因(Derived:身份判定 + 强制异源 = 无歧义)。容量编码为 cstep/w:Mat 按容量创建后 h 只标当前有效长度(:75),总容量藏在 cstep(channel 步进)里,cstep / w 即能容纳的序列长度。

② 容量策略三段式(SDPA kvcache_capacity src/layer/sdpa.cpp:30-51,MHA src/layer/multiheadattention.cpp:244-265):

1
2
3
4
5
6
7
8
9
10
11
if (current_capacity == 0 && max_seqlen_hint >= new_seqlen && max_seqlen_hint > 0)
return max_seqlen_hint; // 首次且有 hint:一步到位预分配
int capacity = max(current_capacity, new_seqlen);
if (current_capacity == 0) { // 首次无 hint:16 ~ 256 起步
reserve = capacity < 16 ? 16 - capacity : capacity;
if (reserve > 256) reserve = 256;
} else { // 增长:capacity/2,下限 16
reserve = capacity / 2;
if (reserve < 16) reserve = 16;
}
return capacity + reserve; // 溢出保护见 :50/:264

首次带 kvcache_max_seqlen_hint(第 02 章的 API,src/net.h:206)→ 按 hint 一次分配免后续搬迁;无 hint → 最小 16 起步(首 token 也别浪费)、上限 256;已有缓存要扩 → 每次扩 50%。

③ 增长即搬迁(SDPA :70-90,MHA :284-304):新建容量 Mat(m.create(head_dim, capacity, num_kv_head, ...) :71)→ m.h = new_seqlen(:75)→ 逐 channel memcpy 拷旧数据(:77-86,valid_head_size = cache.w * cache.h * elemsize,只搬有效长度)→ new_cache = m。旧缓冲随引用归零回 kvcache_allocator——如果你给它的是池分配器,旧容量块自然回池复用(第 04 章的机制在这里接力)。

④ 调用现场:MHA 三处前向变体各两次调用(fp32 版 multiheadattention.cpp:445/:449,int8 版 :958/:962,块量化版 :1510/:1514);SDPA 在 :148/:152/:390。K/V 双缓存共享同一策略,dst_seqlen = past_seqlen + new_seqlen。

4. 输出路径:type=1 保留 KV 布局

第 03 章已见 extract 的输出协商(src/net.cpp:3401-3410),这里从 KV 视角重读:

1
2
3
4
5
feat = d->blob_mats[blob_index];                      // :3401
// preserve kv cache storage layout and reserved capacity
if (layer && (layer->typeindex == LayerType::MultiHeadAttention || layer->typeindex == LayerType::SDPA)
&& layer->tops.size() == 3 && blob_index != layer->tops[0])
type = 1; // :3406-3410 K/V 强制 type=1

MHA 的三输出布局:top_blobs[0] 是注意力结果,top_blobs[1]/[2] 是更新后的 cached_xk/cached_xv(src/layer/multiheadattention.cpp:344-345)。当用户 extract 的是后两者时强制 type=1——跳过解包与 fp32 转换(第 03 章 :3412-3476 的 type == 0 条件全部失效),注释原文即 “preserve kv cache storage layout and reserved capacity”(:3406)。语义闭环(Derived):下一轮 decode 时这个 blob 作为 past_xk(bottom 侧 cached_xk_i,:342-343)传回来,create_or_grow 才能凭 cstep 读出容量、凭 allocator 判定复用——输出不做转换,正是输入能无缝续用的前提。type 参数的本义在 src/net.h:226-238:type = 1, do not convert fp16/bf16 or / and packing, required for kv cache(:226-227 注释)。

KV 回流还有一个隐性约定:宿主 App 每轮 decode 要把 top_blobs[1]/[2] 喂回下一轮的 bottom——ncnn 不管理"KV 在哪一轮",只保证"给什么接什么"。这就是库形态 LLM 的全部分寸。

5. 独立 Gemm 层:W4/6/8bit × 块 32/64/128 的块量化谱系

除了注意力层的 KV 通道,本版本还把 Gemm 做成了独立层并挂上权重块量化(LLM 矩阵乘的 fp32 兜底路径)。能力开关在 src/layer/gemm.h:56-61:weight_block_quantize、weight_block_quantize_bits、weight_block_quantize_block_size、weight_block_quantize_has_input_scale;编码解码在 Gemm::get_weight_block_quantize_params(src/layer/gemm.cpp:11-28):

1
2
3
weight_bits     = quantize_term / 100;        // 只认 4 / 6 / 8(:17-18)
format_code = quantize_term % 100 / 10; // 0/1,1 表示带输入 scale(:20-21)
block_size_code = quantize_term % 10; // 0→32, 1→64, 其余→128(:26)

即 W4/W6/W8 × 块 32/64/128 共九种组合由一个 quantize_term 整数编码——这与第 09 章 ncnnllm2table 的 bits*100+10+block_code 编码互为镜像(工具侧写入、层侧解码)。激活侧按块动态量化(weight_block_quantize_activation_row_int8,src/layer/gemm.cpp:53 起,block_count = ceil(K/block_size)),权重侧 create_pipeline 时离线打包(forward_weight_block_quantize 声明于 src/layer/gemm.h:28)。

6. Gemm_arm 五档分派

Gemm_arm::forward(src/layer/arm/gemm_arm.cpp:4760-4802)的五档优先级链:

档 进入条件 分派
1 weight_block_quantize && bits==8 forward_wq_int8(:4762-4767);W4/W6 落回 Gemm::forward 参考实现(:4769)
2 quantize_term(传统 INT8) forward_int8(:4773-4776)
3 ARM82 + fp16 storage(+arithmetic) forward_fp16sa / forward_fp16s(:4783-4789)
4 bf16 storage forward_bf16s(:4793-4794)
5 VFPV4 + fp16 storage forward_fp16s(:4798-4801)

create_pipeline 侧同构(:4592-4631):create_pipeline_wq_int8(:4595-4597) → create_pipeline_int8(:4603-4605) → fp16sa/fp16s(:4610-4617) → bf16s(:4620-4624) → VFPV4 fp16s(:4626-4630)。观察(Observed in source + 由此推论标注):ARM 特化的 W8A8 路径存在(wq_int8),而 W4/W6 目前只有 naive 参考 GEMM(:4769 落回基类)——小尺寸块量化在 CPU 上的快路径尚待 ISA kernel 落地,这是读这份代码时要注意的能力边界。

本篇小结

  • 路线:LLM 化 = 引擎层两个钩子(src/net.h:203/:206)+ 两个注意力层内嵌 KV 管理 + 独立 Gemm 层;无 KV 管理器、无分页、无序列操作 API——自回归循环由宿主驱动。
  • 通道规则:kvcache_allocator 必须异于 blob_allocator(src/net.cpp:3298-3301)、与 batch 互斥(:3304-3313);通道内 blob 跳过 convert_layout(:400-402)、层后统一 release(:774-777/:804-807)。
  • 容量策略在层内:hint 一步到位(MHA :246-247)、否则 16~256 起步、增长 capacity/2 下限 16(:251-262);容量编码 cstep/w、复用凭 allocator == opt.kvcache_allocator(SDPA :55-57);增长即新建+逐 channel memcpy 迁移(SDPA :70-90)。
  • 输出闭环:MHA/SDPA 三输出的 K/V 强制 type=1(src/net.cpp:3406-3410),保布局保容量,与下一轮的 past_xk/xv 无缝续接。
  • Gemm 块量化:quantize_term 编码 W4/6/8 × 块 32/64/128(src/layer/gemm.cpp:11-28),Gemm_arm 五档分派 wq_int8 → int8 → fp16sa → fp16s → bf16s(gemm_arm.cpp:4760-4802),W4/W6 暂无 ARM 特化 kernel。

前置:04-Mat张量与内存池:lightmode即时回收 | 下一篇:06-层注册与ISA运行时分发 | 回目录:README