ncnn推理框架教程 · 08-Vulkan后端与GPU显存管理

08 - Vulkan 后端与 GPU 显存管理

所属系列:ncnn 推理框架教程 | 前置:07-CPU卷积kernel深潜:im2col GEMM、Winograd 与 INT8 | 下一篇:09-转换量化工具链与工程实践
证据基线:commit eb8a50d2。本章主战场:src/allocator.h、src/allocator.cpp、src/net.cpp、src/gpu.h、src/gpu.cpp、src/layer/vulkan/sdpa_vulkan.cpp。
所有断言 Observed in source(标注处除外)。

本篇知识图谱

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
28
29
30
31
32
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((Vulkan后端与显存))
分配器三件套
VkBlobAllocator 16MB大块
空闲区间offset子分配
集显优先统一内存
AMD iGPUs 择大device-local
VkWeightAllocator 8MB
set_weights_in_disk落盘
device host 双层限额
finalize_weights 封存
Staging 与 WeightStaging
AHardwareBuffer 图像
shader基建
331个comp hex嵌入
运行期glslang编SPIR-V
PipelineCache 缓存pipeline
驱动规避
vendorID 分派
Adreno 0x5143
Mali 0x13b5
四个bug workaround
subgroup size 分档
coopmat全家桶
KHR EXT NV QCOM
形状 8_8_16 16_8_8 等
int8 bf16 变体
SDPA flash-attention
coopmat shader
共享内存上限自适应
UNROLL 三级收缩

本篇目标

  1. 拆懂 GPU 侧分配器家族的分工:激活用 VkBlobAllocator、权重用 VkWeightAllocator、上传用 Staging、图像可走 AHB。
  2. 理解 shader 基建:GLSL 源文本 hex 嵌入 → 运行期内建 glslang 编译 → PipelineCache 复用。
  3. 认识 驱动规避层:vendorID/deviceID 级 bug 分派与 vendor 相关的 subgroup 默认值。
  4. 以 SDPA flash-attention coopmat shader 为例看"按设备能力自适应收缩 tile"的最后一公里。

1. 分配器三件套:激活、权重、搬运

GPU 侧分配器的类族(src/allocator.h:312-462):

① VkBlobAllocator——激活/中间 blob(:312-333):构造默认大块 16MB——explicit VkBlobAllocator(const VulkanDevice*, size_t preferred_block_size = 16 * 1024 * 1024); // 16M(:315)。分配策略是大块内 offset 子分配(src/allocator.cpp:735-754):先在已有块的空闲区间里切(it->first += aligned_size 推进空闲起点),切不动才开新块(new_block_size = max(block_size, aligned_size) :744,usage 为 STORAGE|TRANSFER_SRC|TRANSFER_DST :748)。内存堆选择有两条注释级决策(:759-774,image 路径 :1047-1057 同构):集显优先统一内存(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT + HOST_VISIBLE_BIT 组合 :763-765);AMD iGPU 若 device-local 堆更大则专投 device-only(:767-774,device_local_heap_index < buffer_heap_index && size > size 才切换)。这块策略与第 03 章的 Vulkan extract 通路直接相连:acquire_blob_allocator(src/net.cpp:3349)拿到的就是它。

② VkWeightAllocator——权重专用(src/allocator.h:336-358,默认块 8MB :339):本版本给权重层加了完整的三档策略 API——set_weight_file_directory(:346,权重落盘目录)、set_weights_in_disk(:349-350,权重驻磁盘文件而非显存)、set_weight_memory_limit(device_memory_limit, host_memory_limit)(:352-353,device/host 双层驻留限额,按装载顺序逐出)、finalize_weights(:355-356,“flush and seal file weights after uploads complete”)。装配现场(src/net.cpp:2388-2395):load_model 里若无用户 allocator 则 new 一个,set_weights_in_disk(opt.use_weights_in_disk),且仅在落盘模式下才套用双层限额(:2392-2394);上传通道 opt_upload 的 blob/workspace vkallocator 全部指向它(:2407-2408)——权重从 host 拷进 weight 池。上传完成后(src/net.cpp:2508):cmd_upload->submit_and_wait() 成功即调 finalize_weights() 把落盘权重封存。

③ 搬运与图像(src/allocator.h:382-462):VkStagingAllocator(:382+,host↔device 中转缓冲,record_upload/download 的目的地)、VkWeightStagingAllocator(:414+,权重上传专用 staging,src/net.cpp:2397-2399)、VkAndroidHardwareBufferImageAllocator(:437+,AHardwareBuffer 导入为 VkImage,摄像头零拷贝进 GPU)。

2. shader 基建:hex 嵌入 + 运行期编译

ncnn 不带预编译 SPIR-V,而是把 GLSL 源码文本直接嵌进库:

  • 构建期:cmake/ncnn_add_shader.cmake:2-17 对每个 .comp 跑自定义命令生成 xxx.comp.hex.h(ncnn_generate_shader_comp_header.cmake 把源码转成 hex 字节数组),再 string(APPEND layer_shader_registry "{xxx_comp_data, sizeof(xxx_comp_data)},") 挂进 shader 注册表。331 个 .comp(第 01 章实测)→ 331 份 hex 数组 + 一张注册表(layer_shader_spv_data.h.in/layer_shader_registry.h.in 汇总,src/CMakeLists.txt:197-200 configure)。
  • 运行期:PipelineCache::create_pipeline 拿到 comp_data 后经 glslang 编译——glslang::TIntermediate* ir = s.getIntermediate(); ... glslang::GlslangToSpv(*ir, spirv);(src/gpu.cpp:6531-6538,NCNN_COVERAGE 时额外插桩);随后 resolve_shader_info + compile_shader_module 建 VkShaderModule(src/pipeline.cpp:451-464)。第 01 章的"glslang 子模块硬依赖"在这里兑现:编译器跟库走,驱动只收 SPIR-V。
  • 复用:Pipeline::create 委托 pipeline_cache->get_pipeline(...)(src/pipeline.cpp:219-224)——同一 shader+specialization 组合只建一次 VkPipeline。

3. 驱动规避:vendorID/deviceID 级的分派

移动 GPU 的驱动碎片化是 Vulkan 后端的真正战场。ncnn 的对策分三层:

① 硬编码规避表(src/gpu.cpp:513-590):头注释是一张 Mali/Adreno deviceID 对照表(Mali 0x13b5:t760→g77;Adreno 0x5143:506→650,:513-534),初始化时按 physicalDeviceProperties.vendorID/deviceID/apiVersion 设四个 bug 开关(:536-590):旧版 Adreno 驱动 bug_corrupted_online_pipeline_cache(:541-545)、“storage buffer 无 L1” 的 bug_storage_buffer_no_l1(:547-552,qcom855/865 系列明确豁免 :547/:549)、旧 Adreno 的 bug_buffer_image_load_zero(:554-561)、以及"驱动接受隐式 fp16 算术"的 bug_implicit_fp16_arithmetic(Mali 十款 deviceID :563-579、Adreno 845/855/865 :581-589)——它们在 gpu.h:282-287 暴露为查询接口,供各 vulkan 层改写本地尺寸或 shader 变体。

② vendor 默认 subgroup size(src/gpu.cpp:1414-1418):get_vendor_default_subgroup_size——Adreno 0x5143 默认 128、Mali 0x13b5 默认 16、PowerVR 0x1010 也单独分档;驱动不报 subgroupSize 时的兜底值直接影响 coopmat tile 形状。

③ 扩展全家桶(src/gpu.h:318-384):cooperative matrix 家族六件——support_cooperative_matrix 及 _conversion、形状变体 _8_8_16/_16_8_8/_16_8_16/_16_16_16、support_int8_cooperative_matrix、support_bf16_cooperative_matrix(:318-330);外加整墙的 support_VK_KHR_* 扩展查询(cooperative_matrix、8bit/16bit_storage、buffer_device_address、dedicated_allocation…:331-384)。shader 变体选择前先查这些布尔,缺哪个降级到哪个。

4. 收尾实例:SDPA 的 flash-attention coopmat shader

SDPA_vulkan(src/layer/vulkan/sdpa_vulkan.cpp:200-260)展示了全套机制的合奏:

准入门(:199-218):QCOM 路径要求 subgroup 具备 BASIC 操作位(:200-202)、排除 bf16/无 fp16 算术(:203-204)、形状约束四连——FA_coopmat_M ≥4 且 2 的幂、N∈[8,64] 且 2 的幂、N 必须是 subgroup_size 的 1/2/4 分频、K==16(:206-211);任一不满足 use_qcom_flash_attention = false。最终准入还需 FA_coopmat_M != 0 && N%8<mark>0 && K%8</mark>0 && N==K && subgroup_size ≥ N && (非 0x5143 或 QCOM 路径可用)(:213-218)。

自适应收缩(:222-249)——本章的题眼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int UNROLL_P_N = std::min(4, FA_coopmat_subgroup_size / FA_coopmat_N);   // :226 初始 tile
for (;;)
{
// K and V share storage in sdpa_fa_cm
const size_t shared_bytes = 16 * (rows + UNROLL_P_N * FA_coopmat_N) * (FA_coopmat_K / 8)
+ 4 * rows * ((UNROLL_P_N + 1) * FA_coopmat_N + 3); // :231-232
const uint32_t invocations = FA_coopmat_subgroup_size * FA_UNROLL_WG_M; // :233
if (shared_bytes <= vkdev->info.max_shared_memory_size()
&& invocations <= vkdev->info.max_workgroup_invocations()
&& invocations <= vkdev->info.max_workgroup_size_x()
&& (uint32_t)FA_UNROLL_WG_M <= vkdev->info.max_compute_workgroup_subgroups())
break; // :234-236 全过即定稿
if (UNROLL_P_N > 1) UNROLL_P_N /= 2; // :238-239 先缩 P 维展开
else if (FA_UNROLL_WG_M > 1) FA_UNROLL_WG_M = 1; // :240-241 再缩 workgroup 行数
else if (FA_UNROLL_SG_M > 1) FA_UNROLL_SG_M = 1; // :242-243 再缩 subgroup 行数
else { use_flash_attention = false; break; } // :244-248 全缩完仍放不下→放弃 FA
}

共享内存占用量式化计算(:231-232,K/V 共享存储),四条硬件上限(shared memory / workgroup invocations / workgroup size_x / compute workgroup subgroups)逐一校验,按"先缩 N 方向展开、再缩行数"的固定顺序收缩,缩到 0 就整体放弃 FA 走普通 coopmat。定稿的 UNROLL 三个值随 FA_coopmat_M/N/K/subgroup_size 一起作为 specialization 常量注入(:251-266)——同一份 .comp 源,在不同 Mali/Adreno 上编译出不同 tile 的 SPIR-V。这就是"331 个 hex shader + 运行期 glslang + vendorID 规避 + coopmat 探测"四件套在单个算子上的完整闭环。

本篇小结

  • 分配器家族:激活 = VkBlobAllocator(16MB 大块 offset 子分配 src/allocator.h:314、src/allocator.cpp:735-754;集显统一内存优先、AMD iGPU 择更大 device-local 堆 :759-774);权重 = VkWeightAllocator(8MB、set_weights_in_disk 落盘 + device/host 双层限额 + finalize_weights 封存,装配于 src/net.cpp:2388-2395、上传后封存 :2508);搬运 = Staging/WeightStaging,图像可走 AHB(src/allocator.h:382-462)。
  • shader 基建:.comp → hex 源文本嵌入(cmake/ncnn_add_shader.cmake:2-17,331 个)→ 运行期内建 glslang 编 SPIR-V(src/gpu.cpp:6531-6538)→ PipelineCache 复用 VkPipeline(src/pipeline.cpp:219-224)。
  • 驱动规避:Mali 0x13b5 / Adreno 0x5143 对照表 + 四个 bug 开关(src/gpu.cpp:536-590)、vendor 默认 subgroup size(:1414-1418)、coopmat 六件套与 KHR 扩展墙(src/gpu.h:318-384)。
  • 闭环实例:SDPA flash-attention——形状准入(sdpa_vulkan.cpp:199-218)+ 共享内存/invocation 上限驱动 UNROLL 三级收缩(:222-249)+ specialization 注入(:251-266)。

前置:07-CPU卷积kernel深潜:im2col GEMM、Winograd 与 INT8 | 下一篇:09-转换量化工具链与工程实践 | 回目录:README