FlashInfer推理内核库教程 · 06-split-KV调度与FA2内核
06 - split-KV 调度与 FA2 内核执行:把长序列切给每个 SM
所属系列:FlashInfer 推理内核库教程 | 前置:05-后端路由与硬件适配 | 下一篇:07-多后端家族巡礼
证据基线:commit253986e2。主战场:include/flashinfer/attention/scheduler.cuh(plan 期调度)、csrc/batch_decode.cu+include/flashinfer/attention/decode.cuh(decode run)、include/flashinfer/attention/prefill.cuh(FA2 启动)。
本篇知识图谱
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
本篇目标
- 吃透 split-KV 的动机与 plan 期三件事:SM 预算、
FA2DetermineCtaTileQ、kv_chunk_size 三分支与调度三元组表。 - 看懂 decode 侧判满逻辑:occupancy 预算、CUDA graph 恒开 vs 非图短序列关。
- 拆开 run 期的两次发射:partition kernel 与 MergeStates/VariableLengthMergeStates 归并。
- 掌握 FA2 启动路径三闸:smem 双重校验、
DISPATCH_NUM_MMA_KV模板实例化、PDL 启动;收尾看持久化 POD kernel。
1. 灵魂问题:为什么 split-KV
batch=1、KV=16K 时,一条请求的 KV 工作量只有一份——除非把它切开。split-KV 把每条请求的 KV 轴切成若干 chunk,每个 chunk 交给一个 CTA 独立算出"局部 softmax 的分子与 log-sum-exp",最后用 MergeStates 把各 chunk 的 (partial_o, partial_lse) 数学归并成最终输出(Derived,依据 02 章 run 期 tmp_v/tmp_s 的角色与下文 MergeStates 调用)。切几段、每段多大就是 plan 期的全部调度工作。
2. plan 期三件事
2.1 decode 侧:occupancy 预算 + 二分(scheduler.cuh:178-215)
decode 的 split 决策从硬件实测开始(include/flashinfer/attention/scheduler.cuh:180-187,Observed):cudaOccupancyMaxActiveBlocksPerMultiprocessor 算出每 SM 能驻留几个 kernel block,乘上 SM 总数得 max_grid_size = num_blocks_per_sm * num_sm——这就是一次能同时跑的 CTA 总预算。然后(:188-195):
batch_size * gdy >= max_grid_size(gdy 为 KV 方向网格数):网格已满,不切——并行度已被 batch 撑满,再切只增加归并成本;- 否则
PartitionPagedKVCacheBinarySearchMinNumPagePerBatch(max_grid_size, gdy, num_pages, ...)(:202-205)——在预算内二分出"每段最少多少页",使切分后的新批量恰好铺满 SM。
最后一段判据值得抄原文(:206-212,Observed):
1 | if (new_batch_size == batch_size && !enable_cuda_graph) { |
非图模式下短序列免切(省一次归并发射);图模式下恒开——因为图的执行序列必须形状恒定,partition 路径的临时缓冲与归并步骤不能按 replay 变化。
2.2 cta_tile_q:FA2DetermineCtaTileQ 的两种输入(scheduler.cuh:612-637)
prefill 的 Q-tile 大小由 FA2DetermineCtaTileQ 决定,但喂它的输入分两路(Observed):CUDA graph 路径取 max_qo_len——注释明说 “We assume that the dummy data based on which the CUDA graph is created fixes the maximum number of tokens”(:612-617,用捕获时的最大形状定 tile,保证 replay 内恒定);非图路径取平均 packed_qo_len(:626-631)。tile 定下后逐请求累加 total_num_tiles_q(:633-636)。
2.3 kv_chunk_size 三分支与调度三元组表(scheduler.cuh:647-701)
prefill 的 KV chunk 走三分支(:647-656,Observed):
disable_split_kv→kv_chunk_size = int64 最大值(:649-650)——单段,等价不切;fixed_split_size > 0→ 直接采用固定段长(:651-652)——调用方显式锁 KV split(vLLM 的 batch-invariance 场景,04 章提过);- 否则
PrefillBinarySearchKVChunkSize(enable_cuda_graph, max_batch_size_if_split, ...)(:654-656)——max_batch_size_if_split这份 SM 预算在这里进搜索,二分出"切分后新批量不超预算"的最大 chunk。
然后是调度产物的落地——三元组表(:666-689,Observed):对每请求 × 每 q_tile × 每 kv_chunk 三层循环,push_back 出三根平行数组 request_indices / qo_tile_indices / kv_tile_indices(:675-682)——run 期每个 CTA 凭下标查"我算哪条请求的哪块 Q、哪段 KV";同时填 merge_indptr(每行归并几段)与 o_indptr(:684-688)。图模式取 padded_batch_size = max(max_batch_size_if_split, total_num_tiles_q)(:691-695)并 CHECK 新批量不超 pad——与 04 章的图适配呼应。收尾 kv_chunk_size *= page_size(:697-698),返回十元组(:699-701,split_kv/new_batch_size/padded_batch_size/cta_tile_q/kv_chunk_size/request_indices/qo_tile_indices/kv_tile_indices/merge_indptr/o_indptr 十个元素)。
3. run 期:partition + MergeStates 两次发射
交棒侧(csrc/batch_decode.cu:222-244,Observed):先凭 02 章的偏移切片取调度数组(:223-229);plan_info.split_kv 时取 tmp_v/tmp_s 临时缓冲(float 工作区切片,:230-232)与图模式的 block_valid_mask(:233-236);最终一次 dispatch 调用把 params, tmp_v, tmp_s, enable_pdl, stream 交出去(:240-244)。
发射侧(include/flashinfer/attention/decode.cuh:742-757,宿主函数为 SingleDecodeWithKVCacheDispatched,awk 定位;tensor-core 版 BatchDecodeWithPagedKVCacheDispatched 同签名起于 :766):split 时先把输出指针重定向到临时缓冲——params.o = tmp; params.lse = tmp_lse(:746-747),launch partition kernel(:750-751);然后按变体归并(:752-757):
1 | if constexpr (AttentionVariant::use_softmax) { |
prefill 侧同款逻辑但走变长归并:VariableLengthMergeStates(tmp_v, tmp_s, params.merge_indptr, o, lse, ...)(include/flashinfer/attention/prefill.cuh:5191-5194)——merge_indptr 正是 2.3 节那张"每行归并几段"的表;非 softmax 变体走 VariableLengthAttentionSum(:5196-5198)。两次发射的分工(Derived,依据上述代码序):partition kernel 每段独立算局部 softmax,MergeStates 对齐 log-sum-exp 后线性组合——数学上等价于整段 softmax。
4. FA2 启动路径三闸(prefill.cuh:5106-5200)
FA2 的 launch 包着三层闸门(全部 Observed):
- 模板实例化闸:
DISPATCH_NUM_MMA_KV(min(max_num_mma_kv_smem, max_num_mma_kv_reg), NUM_MMA_KV, {...})(:5106-5107)——按 KV-tile 数在"smem 能装多少"与"寄存器装多少"的较小者上展开模板循环。 - smem 双重校验闸:第一重是
KTraits::IsInvalid()的配置合法性(:5113-5122);第二重是精确 sizeof 校验——解析预算可能欠计真实结构体(注释:“cross-warp merge buffers, padding”),所以smem_size > max_smem_per_block_optin时用清晰错误替代 launch 期的cudaErrorInvalidValue(:5139-5150)。随后cudaFuncSetAttribute申请超额动态 smem(:5151-5152)。 - PDL 启动闸:
enable_pdl时装配cudaLaunchAttributeProgrammaticStreamSerialization(:5154-5165)并改走cudaLaunchKernelEx(:5172,5186)——Programmatic Dependent Launch 让本 kernel 与前序 kernel 的尾声重叠启动(这正是 02 章run_args末尾enable_pdl的物理意义)。
partition 分支即在此闸内分流:tmp_v == nullptr → partition_kv=false 直射(:5167-5176);否则重定向输出后发射、再归并(:5177-5200)。
5. 收尾:prefill+decode 重叠的持久化 POD kernel
split-KV 的多段并行在普通 kernel 里靠 grid 铺开;POD(prefill-and-decode overlap)则把两份工作塞进一个持久 kernel。模板 PersistentKernelTemplate(include/flashinfer/attention/persistent_template.cuh:56-97,Observed):
__launch_bounds__取两个 runner 线程数的最大值(max_threads编译期归约,:50-60)——两类 kernel 共用同一 blockDim;- 签名收
params_1、params_2两份__grid_constant__参数(:60-63); - 执行序(
:78-86):BlockPersistentRunner1::Run→BlockPersistentRunner2::Run→grid.sync()(cooperative groups 全网格同步)→BlockReductionRunner::Run把partial_o/partial_lse按merge_indptr归并进final_o/final_lse。
语义解读(Derived,依据 01 章 import 面的 PODWithPagedKVCacheWrapper(flashinfer/__init__.py:340-341)与上述结构):两个 runner 分别承载 prefill 与 decode 任务,在同一 kernel 生命周期内重叠执行,避免两次独立 launch 之间的空隙;归并 runner 收口与 第 3 节的 MergeStates 同族——只是从"kernel 间两次发射"变成"kernel 内一次收口"。profiler 变体(:88-96)只是给每步夹了闭包,结构不变。
6. 全链一图
1 | %%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%% |
本篇小结
- plan 期:decode 用 occupancy×SM 数定预算、判满不切(
scheduler.cuh:180-195),二分铺满(:202-205),图恒开、非图短序列关(:206-212);prefill 的cta_tile_q图用 max_qo_len、非图用均值(:612-631);kv_chunk_size 三分支 disable/fixed/binary-search(:649-656)。 - 调度产物:三层循环 push 出
request/qo_tile/kv_tile_indices三元组表 +merge_indptr(:675-688),图下padded_batch_size = max(预算, tiles)(:691-695)。 - run 期:一次 dispatch 交棒(
batch_decode.cu:240-244)→ partition kernel 重定向输出到 tmp(decode.cuh:746-751)→MergeStates/VariableLengthMergeStates二次归并(decode.cuh:754、prefill.cuh:5191-5194)。 - 启动三闸:
DISPATCH_NUM_MMA_KV在 smem/寄存器预算上实例化(prefill.cuh:5106-5107);解析预算 + 精确 sizeof 双重 smem 校验(:5139-5150);PDL 走cudaLaunchKernelEx重叠启动(:5154-5186)。 - POD 收尾:双 runner 持久 kernel
Run1→Run2→grid.sync→Reduction(persistent_template.cuh:78-86),把 prefill+decode 重叠进一次 launch(角色映射标 Derived)。
前置:05-后端路由与硬件适配 | 下一篇:07-多后端家族巡礼 | 回目录:README