ncnn推理框架教程 · 02-用户面API三层封装与自定义层扩展

02 - 用户面 API 三层封装与自定义层扩展

所属系列:ncnn 推理框架教程 | 前置:01-项目全景与构建上手 | 下一篇:03-懒执行图遍历与双后端调度
证据基线:commit eb8a50d2。本章主战场:src/net.h、src/c_api.h、src/c_api.cpp、python/src/main.cpp、src/layer.h、examples/piper.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
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((用户面API三层封装))
第一层 C++主接口
Net 生命周期
load_param 结构
load_model 权重
21个重载五类来源
Extractor 执行句柄
input extract 按名或索引
type 0 解包 type 1 保布局
allocator 注入点族
第二层 纯C ABI
c_api.h 452行
NCNN_C_API 门控
句柄结构体包 pthis
pipelinecache load save
mat_create 1d到4d全家
第三层 pyncnn
PYBIND11_MODULE ncnn
PyLayer 可继承子类
register_custom_layer 绑定
自定义层扩展
register_custom_layer
按类型名字符串
按索引 CustomBit
DEFINE_LAYER_CREATOR 工厂
piper 三模块实例

本篇目标

  1. 分清 ncnn 对外的三层封装各自服务谁:C++ 主接口(App 开发者)、纯 C ABI(FFI 绑定者)、pyncnn(Python 用户)。
  2. 掌握 load_param/load_model 21 个重载的五类来源与编译门控,能按部署场景选对加载入口。
  3. 理解 extract 的 type=0/type=1 语义差异与 Extractor 上的 allocator 注入点族。
  4. 会用 register_custom_layer + DEFINE_LAYER_CREATOR 接入自定义算子,以 piper TTS 的内嵌模块为完整实例。

1. 三层封装总览

grep 三份对外头文件的入口即得全貌:

层 文件与入口 服务对象 门控
C++ 主接口 src/net.h(Net :70 起 / Extractor :177 起) C++ App 开发者 随 NCNN_STDIO/NCNN_STRING/NCNN_PLATFORM_API/NCNN_VULKAN 分区启用
纯 C ABI src/c_api.h(全文件 wc -l 实测 452 行) Rust/Java/Go 等 FFI 整文件包在 #if NCNN_C_API(src/c_api.h:10)里,对应构建开关 NCNN_C_API(默认 ON,CMakeLists.txt:74)
Python 绑定 python/src/main.cpp:131 PYBIND11_MODULE(ncnn, m) Python 用户 NCNN_PYTHON(默认 OFF,CMakeLists.txt:92);pybind11 为子模块(.gitmodules:4-5)

三层不是"包装套包装":C ABI 直接包 C++ 对象(句柄结构体持 pthis 裸指针),pyncnn 直接绑 C++ 类——C++ 接口是唯一真身,另两层是它的两种投影。

2. 第一层:Net 与 Extractor

2.1 load_param / load_model:21 个重载的五类来源

grep -n 'load_param\|load_model' src/net.h 实测:load_param 14 个(本名 8 + load_param_bin 6)+ load_model 7 个 = 21 个重载,按数据来源分五类(均在 src/net.h:69-135):

来源类 重载 门控 语义要点
抽象流 load_param(const DataReader&)(:70) load_param_bin(:73) load_model(:75) 无 自定义数据源(网络/加密流)的统一入口
文件 FILE*(:81/:93/:101)、路径 const char*(:82/:94/:102)、Windows 宽字符(:84/:96/:104)、字符串内存 load_param_mem(:89) NCNN_STDIO+NCNN_STRING(bin 版只要 STDIO) 最常用;路径版即第 01 章示例所用
外部内存 load_param(const unsigned char*)(:111) load_model(const unsigned char*)(:118) 无 返回消耗字节数;:113-115 注释明确 load_model 不拷贝权重、只引用,内存须保持存活且 32-bit 对齐(:109/:116)
Android 资产 AAsset*(:124/:128/:132) 与 AAssetManager*(:125/:129/:133) 各三件 NCNN_PLATFORM_API + __ANDROID_API__ >= 9(:120-121) APK assets 直读,免落盘
二进制 param load_param_bin(FILE*/路径/宽字符)(:93-97) NCNN_STDIO 配合 ncnn2mem 的 .param.bin 形态(第 09 章)

注意一个不对称性:load_param 有纯文本、二进制、字符串三种形态,load_model 只有流/文件/内存三种——权重天生就是二进制,没有"文本形态"。

2.2 Extractor:执行句柄与注入点族

Net 只负责装载,真正的执行句柄由 create_extractor()(src/net.h:141)产出的 Extractor 持有(类定义 src/net.h:177 起)。它在执行前可注入的资源(:194-215):

1
2
3
4
5
6
void set_light_mode(bool enable);                    // :194 中间 blob 即时回收,默认开(第 04 章主轴)
void set_blob_allocator(Allocator*); // :197
void set_workspace_allocator(Allocator*); // :200
void set_kvcache_allocator(Allocator*); // :203 KV cache 专属分配通道(第 05 章主轴)
void set_kvcache_max_seqlen_hint(int); // :206 预分配提示(第 05 章)
// Vulkan 三件套 + kvcache_vkallocator // :209-215

kvcache 钩子直接挂在 Extractor 之上、与普通 allocator 并列——这是本版本"LLM 化走层与分配器"路线在 API 面的第一个可见痕迹。

2.3 input / extract:按名或索引,type 定输出形态

src/net.h:218-238:input/extract 各有按 blob 名(:221/:227,NCNN_STRING 门控)与按索引(:232/:238)两版;Vulkan 版返回 VkMat 并携带 VkCompute 录制命令(:248/:257)。关键在 extract 的 type 参数(:225-226 原文注释):

type = 0, default / type = 1, do not convert fp16/bf16 or / and packing, required for kv cache

  • type=0:返回前做布局解包与精度转换,交还"干净的 fp32 Mat"——给人看、给后续 numpy 用。
  • type=1:保留内部 fp16/bf16、pack4/8 打包布局原样输出——省一次转换,且是取 KV cache 输出的唯一正确方式(解包再打包会破坏 KV 布局语义)。第 05 章会看到 MultiHeadAttention/SDPA 的 K/V 输出强制走 type=1。

3. 第二层:纯 C ABI——FFI 的直通管道

src/c_api.h 全部 452 行包在 #if NCNN_C_API(:10) 与 extern "C"(:14-16) 里,导出的每个函数操作一个前置声明的句柄结构体(如 typedef struct __ncnn_mat_t* ncnn_mat_t,:109),C 侧只见指针不见对象。src/c_api.h:10-131 覆盖了四个核心分区:

  1. version(:18-19):ncnn_version/ncnn_version_number——FFI 绑定者的第一个冒烟测试。
  2. allocator(:21-33):ncnn_allocator_create_pool_allocator/_unlocked_pool_allocator(:31-32)——把第 04 章的池分配器也开给 C 用户。
  3. pipelinecache(:35-53):NCNN_VULKAN 双层门控内提供 load_memory/save_memory(:43-44) 与路径版 load/save(:46-47,Windows 宽字符另配 _w 版 :49-50)——SPIR-V 编译缓存的跨进程复用,GPU 冷启动优化的重要开关。
  4. option(:55-106) 与 mat(:108-135):option 侧完整暴露线程数(:61-62)、set_kvcache_allocator(:66)、set_kvcache_max_seqlen_hint(:67)、fp16/int8/bf16/int16 各精度策略(:74-83)与 coopmat(:85/:103);mat 侧是维度×所有权×元素的正交矩阵——ncnn_mat_create_1d~4d(:112-115)、NCNN_BATCH 门控的 _batch 后缀(:116-121)、外部内存 _external(:122-125)、带 elemsize/elempack 的 _elem(:126-129) 及其 _batch 组合(:130-135)。

实现侧的典型样本(src/c_api.cpp):ncnn_net_create(:1610) 是 malloc(句柄) + new Net() 的直通封装;ncnn_extractor_create(:1814) 同理;按名/按索引的 ncnn_extractor_input/extract(:1831/:1836) 与 ncnn_extractor_input_index/extract_index(:1845/:1850) 镜像了 C++ 层的两种寻址——其中 extract 还负责把返回的 Mat 再包一层句柄(:1839 附近 new Mat(mat0))。给 FFI 的启示:生命周期完全由 C 侧显式管理(create/destroy 成对出现),这正是 Rust/Java 绑定喜欢它的原因。

4. 第三层:pyncnn——可继承的 Python 绑定

python/src/main.cpp:131 是模块入口 PYBIND11_MODULE(ncnn, m)。两个设计点值得注意:

  1. Layer 可被 Python 子类化:py::class_<Layer, PyLayer>(m, "Layer")(:1017) 用 PyLayer trampoline 暴露了 load_param/load_model/create_pipeline/destroy_pipeline(:1019-1022)、全套能力标志(one_blob_only、support_inplace、support_vulkan、support_packing 等 :1023-1031)与四种 forward/forward_inplace 重载(:1032-1040)——Python 里写 class MyOp(ncnn.Layer) 覆写 forward 即是合法的自定义层实现,性能敏感处再用 C++ 落地。
  2. register_custom_layer 的 Python 版(:1066 起):接受 creator/destroyer 两个 Python callable,内部先试 custom_layer_to_index(:1071) 把类型名换算索引,再落到 C++ 的 net.register_custom_layer(:1081/:1095);Python 侧还维护 custom_layer_registry_size 与 CustomBit 位(:118-121/:1072),保证动态注册的索引不与内建层冲突。

5. 扩展机制:register_custom_layer + DEFINE_LAYER_CREATOR

C++ 侧的扩展点在 src/net.h:60-67,两条注册通道:

1
2
3
4
5
6
#if NCNN_STRING
int register_custom_layer(const char* type, layer_creator_func creator,
layer_destroyer_func destroyer = 0, void* userdata = 0); // :60 按类型名
#endif
int register_custom_layer(int index, layer_creator_func creator,
layer_destroyer_func destroyer = 0, void* userdata = 0); // :67 按索引

头文件注释(:57-58、:63-65)写明了三条硬规则:注册可覆写内建层;覆写者 creator 返回 null 时参数加载直接失败、不会回退内建实现;自定义索引必须带 LayerType::CustomBit,未打标的槽位号必须 < 1000000。工厂函数由宏生成(src/layer.h:199-202):DEFINE_LAYER_CREATOR(name) 展开为 name##_layer_creator,函数体就一句 new name。配对的 DEFINE_LAYER_DESTROYER(:204 起) 处理带管线资源的层。Net 的 create_custom_layer/create_overwrite_builtin_layer 是两个 virtual(src/net.h:162-166)——想接管分派逻辑可以子类化 Net。

5.1 实例:piper 的三个内嵌模块

examples/piper.cpp(wc -l 实测 739 行)是把自定义层机制用到极致的案例:一个 TTS 模型里有三个 pnnx 转不出的算子,作者直接把层实现内嵌进示例文件,注册进图后其余流程照常。以 relative_embeddings_k_module 为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class relative_embeddings_k_module : public ncnn::Layer   // examples/piper.cpp:33
{
public:
relative_embeddings_k_module() { one_blob_only = true; } // :36-38 单输入声明

virtual int forward(const ncnn::Mat& bottom_blob, ncnn::Mat& top_blob,
const ncnn::Option& opt) const // :40-41
{
...
#pragma omp parallel for num_threads(opt.num_threads) // :50 层内 OpenMP 并行
for (int q = 0; q < num_heads; q++) { ... 滑窗平移拷贝 ... }
return 0;
}
};

DEFINE_LAYER_CREATOR(relative_embeddings_k_module) // :75 工厂宏

enc_p.register_custom_layer(
"piper.train.vits.attentions.relative_embeddings_k_module",
relative_embeddings_k_module_layer_creator); // :547-548 按名注册

这个实例浓缩了四条工程要点:① 自定义层只写 CPU naive 的 forward 就能入图(one_blob_only=true 声明单输入形态),不用管 GPU/Vulkan——不支持时走 CPU 边界,第 03 章会看到调度层如何自动搬运;② 层内并行用 opt.num_threads 而非硬编码线程数(:50),尊重用户配置;③ 注册用类型名字符串(:547/:548/:589 共三处)——pnnx 导出的 .param 里带着这些原始模块名,按名注册比手工查索引稳;④ 索引通道(:67)留给"param 已用数字 type"或不想依赖 NCNN_STRING 的场景,两通道覆盖部署的两端。

6. 选型建议

场景 用哪层 一句话理由
C++ App 集成 Net/Extractor 重载最全、opt 粒度最细
Rust/Java/Go 绑定 c_api 452 行纯 C 面,create/destroy 显式生命周期
快速原型/预研算子 pyncnn PyLayer 子类当天出活,C++ 移植后置
模型含私算子 register_custom_layer 按名 param 里类型名即注册键,免查索引

本篇小结

  • 三层封装 = 一个真身(C++)+ 两个投影:C ABI(c_api.h 452 行、#if NCNN_C_API 门控 :10)与 pyncnn(PYBIND11_MODULE :131、PyLayer trampoline :1017)。
  • 加载面:load_param 14(本名 8 + load_param_bin 6)+ load_model 7 共 21 个重载(src/net.h:69-135),DataReader 是一切形态的抽象底座,load_model(unsigned char*) 零拷贝引用外部内存。
  • 执行面:extract 按名(:227)/按索引(:238)双寻址,type=0 解包转 fp32、type=1 保留打包布局(KV cache 必用);allocator 注入点族(:194-215)中 kvcache 钩子(:203/:206)直通第 05 章。
  • 扩展面:按名(:60)/按索引(:67)双通道注册,DEFINE_LAYER_CREATOR(:199-202) 造工厂;piper 三模块示范"内嵌实现 + 按名注册 + opt.num_threads 并行"的最小完整路径。

前置:01-项目全景与构建上手 | 下一篇:03-懒执行图遍历与双后端调度 | 回目录:README