Paddle-Lite Python API 详解:MobileConfig、PaddlePredictor 与 Tensor 的完整接口实践指南
【免费下载链接】Paddle-LitePaddlePaddle High Performance Deep Learning Inference Engine for Mobile and Edge (飞桨高性能深度学习端侧推理引擎)项目地址: https://gitcode.com/GitHub_Trending/pa/Paddle-Lite
本文基于 Paddle-Lite 官方 Python API 参考文档,结合仓库中lite/api/python的 pybind11 绑定源码与lite/demo/python官方推理示例,系统讲解create_paddle_predictor、MobileConfig、PaddlePredictor、Tensor及TargetType/PrecisionType/DataLayoutType/Place/PowerMode等核心类型。读完本文,你将掌握用 Python 加载 NaiveBuffer 优化模型、完成「配置—建预测器—写输入—执行—取输出」完整推理链路的方法,并理解每个接口在 C++ 层面对应的真实实现与适用限制。
一、Python API 模块结构与导入方式
Paddle-Lite 的 Python 接口由 pybind11 绑定生成。绑定入口位于 pybind.h,其中PYBIND11_MODULE(lite, m)声明了模块名lite,并依次调用BindLiteApi(核心 API)与BindLiteOpt(模型优化工具接口,受LITE_ON_TINY_PUBLISH宏控制)。因此所有接口都归属于paddlelite.lite子模块,标准导入方式为:
from paddlelite.lite import *从 pybind.cc 的BindLiteApi函数(约 L103-L131)可以看到,模块内注册的核心符号包括:CxxConfig、MobileConfig、PowerMode、Place(内含TargetType、PrecisionType、DataLayoutType枚举)、CLTuneMode、CLPrecisionType、Tensor、CxxPredictor、LightPredictor,以及全局工厂函数create_paddle_predictor。这也解释了为什么文档中create_paddle_predictor(config)可以直接写成模块级函数调用。
Python 包的构建与打包由 setup.py.in 完成:核心推理库被编译为lite.so(Windows 下为lite.pyd),连同第三方依赖库一起放入paddlelite.libs目录,并随paddlelite包分发;包内还附带paddle_lite_opt脚本,用于在本地执行模型优化。
二、create_paddle_predictor:预测器工厂函数
官方文档签名:
paddlelite.lite.create_paddle_predictor(config: MobileConfig)根据MobileConfig配置构建预测器。
示例:
# 设置 MobileConfig config = MobileConfig() config.set_model_from_file(<your_model_path>) # 根据 MobileConfig 创建 PaddlePredictor predictor = create_paddle_predictor(config)- 参数
config:用于构建预测器的配置信息。
- 返回值
- 生成的预测器对象。
源码层面的双重载
在 pybind.cc 中,create_paddle_predictor实际注册了两个重载:
// 重载 1:CxxConfig -> CxxPaddleApiImpl(完整版预测器,非 tiny 发布包中提供) m->def("create_paddle_predictor", [](const CxxConfig &config) -> std::unique_ptr<CxxPaddleApiImpl> { auto x = std::unique_ptr<CxxPaddleApiImpl>(new CxxPaddleApiImpl()); x->Init(config); return std::move(x); }); // 重载 2:MobileConfig -> LightPredictorImpl(轻量版预测器) m->def("create_paddle_predictor", [](const MobileConfig &config) -> std::unique_ptr<LightPredictorImpl> { auto x = std::unique_ptr<LightPredictorImpl>(new LightPredictorImpl()); x->Init(config); return std::move(x); });- 传入
MobileConfig时返回轻量级LightPredictorImpl,直接加载已优化好的 NaiveBuffer 模型,不做运行时 IR 优化,这是移动端/端侧场景的主路径; - 传入
CxxConfig时返回CxxPaddleApiImpl,支持运行时 Pass 优化并可通过save_optimized_model导出优化模型(详见第七节)。
三、MobileConfig:轻量预测器的配置中心
官方文档定义:
class paddle_lite.lite.MobileConfig;MobileConfig是用来配置构建轻量级 PaddlePredictor 的配置信息,如 NaiveBuffer 格式的模型地址、能耗模式、工作线程数等。
注意:输入的模型需要使用 Model Optimize Tool(见 模型优化工具文档)转化为 NaiveBuffer 格式的优化模型。
示例:
config = MobileConfig() # 设置 NaiveBuffer 格式模型文件,从文件加载模型时使用 config.set_model_from_file(<your_model_path>) # 设置工作线程数 config.set_threads(4) # 设置能耗模式 config.set_power_mode(LITE_POWER_HIGH) # 根据 MobileConfig 创建 PaddlePredictor predictor = create_paddle_predictor(config)set_model_from_file
MobileConfig.set_model_from_file(x: str)设置模型文件,当需要从磁盘加载模型时使用。
- 参数:
x:模型文件路径(NaiveBuffer 合并格式的单文件,通常以.nb结尾)。
set_model_from_buffer(绑定源码中的补充接口)
文档未展开,但从 pybind.cc 可以看到MobileConfig还绑定了内存加载接口:
MobileConfig.set_model_from_buffer(buffer: bytes) MobileConfig.set_model_buffer(model_buffer, param_buffer) # 已废弃 MobileConfig.is_model_from_memory()对应 C++ 声明见 paddle_api.h 中的MobileConfig类:set_model_from_buffer支持从内存 buffer 加载合并格式模型,适合 App 内嵌模型文件的场景;set_model_buffer/model_buffer/param_buffer为老接口,源码中已标注deprecated,建议在 v3.0 前迁移到set_model_from_file/set_model_from_buffer。
set_model_dir与model_dir
MobileConfig.set_model_dir(x: str)注意:Lite 模型格式在 release/v2.3.0 之后修改,本接口为加载老格式模型的接口,将在 release/v3.0.0 废弃。建议替换为set_model_from_file接口。
设置模型文件夹路径,当需要从磁盘加载老格式模型时使用。
- 参数:
x:模型文件夹路径。
MobileConfig.model_dir()获取设置的模型文件夹路径。
- 返回值:模型文件夹路径。
set_power_mode与power_mode
MobileConfig.set_power_mode(mode: PowerMode)设置 CPU 能耗模式。若不设置,则默认使用LITE_POWER_HIGH(Python 文档口径;C++ 基类ConfigBase中mode_初始化为LITE_POWER_NO_BIND,见 paddle_api.h,实际默认值以具体平台编译路径为准)。
注意:只在开启OpenMP时生效,否则系统自动调度。
- 参数:
PowerMode:CPU 能耗模式(取值见第六节PowerMode枚举说明)。
MobileConfig.power_mode()获取设置的 CPU 能耗模式。
- 返回值:设置的 CPU 能耗模式。
set_threads与threads
MobileConfig.set_threads(threads: int)设置工作线程数。若不设置,则默认使用单线程。
注意:只在开启OpenMP的模式下生效,否则只使用单线程。
- 参数:
threads:工作线程数。
MobileConfig.threads()获取设置的工作线程数。
- 返回值:工作线程数。
源码佐证:在 pybind.cc 中,set_threads/threads/set_power_mode/power_mode四个接口被#ifdef LITE_WITH_ARM包裹,即只在 ARM 后端编译时暴露到 Python 侧——这与“仅在 ARM CPU 场景有意义”的语义一致。
其他后端相关配置接口
从 pybind.cc 的BindLiteMobileConfig可见,MobileConfig还绑定了以下接口,官方文档未逐一展开,供多后端用户参考:
# OpenCL 后端 config.set_opencl_binary_path_name(bin_path, bin_name) config.set_opencl_tune(CLTuneMode.CL_TUNE_NORMAL, tuned_path, tuned_name, 4) config.set_opencl_precision(CLPrecisionType.CL_PRECISION_AUTO) # Metal 后端(iOS) config.set_metal_use_mps(True) config.set_metal_use_memory_reuse(True) config.set_metal_lib_path(<path to lite.metallib>) # NNAdapter 后端(华为昇腾、瑞芯微 NPU、高通 QNN 等) config.set_nnadapter_device_names([...]) config.set_nnadapter_context_properties(<str>) config.set_nnadapter_model_cache_dir(<dir>) config.set_nnadapter_dynamic_shape_info({...}) config.set_nnadapter_model_cache_buffers(...)OpenCL 调优/精度选项的完整语义在 C++ 头文件 paddle_api.h 中有注释:CL_TUNE_NONE/RAPID/NORMAL/EXHAUSTIVE对应关闭/快速/常规(推荐)/穷举式的算子算法搜索;CL_PRECISION_AUTO(fp16 可用则优先 fp16,默认)、CL_PRECISION_FP32(强制 fp32)、CL_PRECISION_FP16(强制 fp16)。官方示例 mobilenetv1_light_api.py 中即演示了 OpenCL 与 Metal 两类后端的配置方式。
四、PaddlePredictor:预测器接口与完整推理流程
class paddle_lite.lite.PaddlePredictorPaddlePredictor是 Paddle Lite 的预测器,由create_paddle_predictor根据MobileConfig进行创建。用户可以根据 PaddlePredictor 提供的接口设置输入数据、执行模型预测、获取输出等。
官方文档给出的完整示例(图像分类):
from paddlelite.lite import * import numpy as np from PIL import Image # (1) 设置配置信息 config = MobileConfig() config.set_model_from_file("./mobilenet_v1_opt.nb") # (2) 创建预测器 predictor = create_paddle_predictor(config) # (3) 从图片读入数据 image = Image.open('./example.jpg') resized_image = image.resize((224, 224), Image.BILINEAR) image_data = np.array(resized_image).transpose(2, 0, 1).reshape(1, 3, 224, 224) # (4) 设置输入数据 input_tensor = predictor.get_input(0) input_tensor.from_numpy(image_data) # (5) 执行预测 predictor.run() # (6) 得到输出数据 output_tensor = predictor.get_output(0) print(output_tensor.shape()) print(output_tensor.numpy())仓库中的官方 Demo mobilenetv1_light_api.py 与上述流程一一对应,并补充了真实场景的前后处理:命令行参数--model_dir(优化后模型路径)、--input_shape(默认1 3 224 224)、--backend(arm/opencl/x86/x86_opencl/metal)、--image_path、--label_path、--print_results;图像经 resize、BGR→RGB、/255.0归一化,再按 ImageNet 均值[0.485, 0.456, 0.406]、标准差[0.229, 0.224, 0.225]标准化后from_numpy写入输入,run()之后用np.argmax对照labels.txt输出类别名与得分。
get_input
PaddlePredictor.get_input(i: int)获取输入 Tensor 的引用,用来设置模型的输入数据。
- 参数:
i:输入 Tensor 的索引。 - 返回值:第
i个输入 Tensor 的引用。
get_output
PaddlePredictor.get_output(i: int)获取输出 Tensor 的引用,用来获取模型的输出结果。
- 参数:
i:输出 Tensor 的索引。 - 返回值:第
i个输出 Tensor 的引用。
绑定源码佐证:Python 侧的LightPredictor类实际绑定的接口比文档列出的更多,见 pybind.cc:除get_input/get_output/run/get_version外,还提供get_input_names()、get_output_names()、get_input_by_name(name)、get_output_by_name(name),便于多输入/多输出模型按名字定位张量。这些接口最终落到 C++ 侧LightPredictorImpl(light_api.h),其底层LightPredictor::Run()会先执行CheckInputValid()校验输入精度与模型期望是否一致,再驱动RuntimeProgram执行——这就是“设置输入数据后调用run()”的底层约束来源。
run
PaddlePredictor.run()执行模型预测,需要在设置输入数据后调用。
get_version
PaddlePredictor.get_version()用于获取当前库使用的代码版本。若代码有相应标签则返回标签信息,如v2.0-beta;否则返回代码的 branch (commit id),如develop (7e44619)。
- 返回值:当前库使用的代码版本信息。
五、Tensor:数据组织与读写
class paddle_lite.lite.TensorTensor 是 Paddle Lite 的数据组织形式,用于对底层数据进行封装并提供接口对数据进行操作,包括设置 Shape、数据、LoD 信息等。
注意:用户应使用PaddlePredictor的get_input和get_output接口获取输入/输出的Tensor。
resize
Tensor.resize(shape: list[int])设置 Tensor 的维度信息。
- 参数:
shape:维度信息。
shape
Tensor.shape()获取 Tensor 的维度信息。
- 返回值:Tensor 的维度信息。
set_lod与lod
Tensor.set_lod(lod: list[list[int]])设置 Tensor 的 LoD 信息。
- 参数:
lod:Tensor 的 LoD 信息,类型为二维的list(C++ 侧类型见 paddle_api.h 中lod_t = std::vector<std::vector<uint64_t>>,主要用于 NLP 变长序列场景)。
Tensor.lod()获取 Tensor 的 LoD 信息。
- 返回值:Tensor 的 LoD 信息,类型为二维的
list。
precision与target
Tensor.precision()获取 Tensor 的精度信息。
- 返回值:
Tensor的精度信息,类型为PrecisionType。
Tensor.target()获取 Tensor 的数据所处设备信息。
- 返回值:
Tensor的数据所处设备信息(TargetType)。
numpy()与from_numpy():与 NumPy 互转的底层实现
这是 Python API 与 C++ API 相比最实用的增量接口,官方文档示例中已用到(from_numpy/numpy)。其实现位于 tensor_py.h:
numpy():TensorToPyArray(L76-L128)将 Tensor 按 shape/precision 构造为 NumPy 数组,对 Host/ARM 等内存可见设备直接共享底层 buffer(零拷贝,通过py::capsule保持 Tensor 生命周期);对 XPU 设备则先xpu_wait()+xpu_memcpy拷回 Host 再包装。from_numpy(array, place=TargetType.Host):SetTensorFromPyArray(L163-L192)会先Resize到 NumPy 数组的维度再memcpy数据。支持的 dtype 为 bool、float32、float64、int8、int16、int32、int64、uint8;不支持 float16/uint16 输入(源码注释中明确说明)。XPU 目标会自动走xpu_memcpy。- 此外,pybind.cc 还通过宏生成了按类型直接读写 raw data 的接口:
float_data()/set_float_data(data)、int8_data()/set_int8_data(data)、int32_data()/set_int32_data(data)、uint8_data()/set_uint8_data(data),对应 C++ 侧CopyToCpu/CopyFromCpu。
六、基础类型:TargetType、PrecisionType、DataLayoutType、Place、PowerMode
TargetType
enum paddle_lite.lite.TargetTypeTargetType为目标设备硬件类型,用户可以根据应用场景选择硬件平台类型。
枚举型变量TargetType的取值包括{X86, CUDA, ARM, OpenCL, FPGA, NPU}等。从 pybind.cc 的绑定定义看,实际注册的取值更为完整:Unk, Host, X86, ARM, OpenCL, Any, FPGA, XPU, BM, MLU, RKNPU, APU, HUAWEI_ASCEND_NPU, IMAGINATION_NNA, INTEL_FPGA, Metal, NNAdapter。
PrecisionType
enum paddle_lite.lite.PrecisionTypePrecisionType为模型中 Tensor 的数据精度,默认值为 FP32 (float32)。
枚举型变量PrecisionType的取值包括{FP32, INT8, INT32, INT64}等。绑定源码(pybind.cc)中的完整取值为Unk, FP32, INT8, INT32, Any, FP16, BOOL, INT64, INT16, UINT8, FP64。
DataLayoutType
enum paddle_lite.lite.DataLayoutTypeDataLayoutType为 Tensor 的数据格式,默认值为 NCHW(number, channel, height, weight)。
枚举型变量DataLayoutType的取值包括{NCHW, NHWC}等。完整绑定取值还包括ImageDefault, ImageFolder, ImageNW(OpenCL GPU 的 Image 布局)与MetalTexture2DArray, MetalTexture2D(iOS Metal)等,见 pybind.cc。
Place
class paddle_lite.lite.PlacePlace是TargetType、PrecisionType和DataLayoutType的集合,说明运行时的设备类型、数据精度和数据格式。
从 pybind.cc 的构造绑定看,其签名为Place(target, precision=PrecisionType.FP32, layout=DataLayoutType.NCHW, device=0),并暴露is_valid()方法。Place主要服务于完整版CxxConfig.set_valid_places([...]),用于指定“哪些设备/精度/格式组合可用于 kernel 选择”,官方示例 mobilenetv1_full_api.py 中展示了 OpenCL 后端典型的多级 Place 回退列表(FP16 Image 布局优先,回退 NCHW FP32,再回退 platform/host)。
PowerMode
enum paddle_lite.lite.PowerModePowerMode为 ARM CPU 能耗模式,用户可以根据应用场景设置能耗模式获得最优的能效比。
| 选项 | 说明 |
|---|---|
| LITE_POWER_HIGH | 绑定大核运行模式。如果 ARM CPU 支持 big.LITTLE,则优先使用并绑定 Big cluster,如果设置的线程数大于大核数量,则会将线程数自动缩放到大核数量。如果系统不存在大核或者在一些手机的低电量情况下会出现绑核失败,如果失败则进入不绑核模式。 |
| LITE_POWER_LOW | 绑定小核运行模式。如果 ARM CPU 支持 big.LITTLE,则优先使用并绑定 Little cluster,如果设置的线程数大于小核数量,则会将线程数自动缩放到小核数量。如果找不到小核,则自动进入不绑核模式。 |
| LITE_POWER_FULL | 大小核混用模式。线程数可以大于大核数量,当线程数大于核心数量时,则会自动将线程数缩放到核心数量。 |
| LITE_POWER_NO_BIND | 不绑核运行模式(推荐)。系统根据负载自动调度任务到空闲的 CPU 核心上。 |
| LITE_POWER_RAND_HIGH | 轮流绑定大核模式。如果 Big cluster 有多个核心,则每预测 10 次后切换绑定到下一个核心。 |
| LITE_POWER_RAND_LOW | 轮流绑定小核模式。如果 Little cluster 有多个核心,则每预测 10 次后切换绑定到下一个核心。 |
Python 侧这 6 个枚举值与 C++ 的lite_api::PowerMode一一对应,绑定代码见 pybind.cc。
七、进阶:完整版 Python API(CxxConfig / CxxPredictor)
轻量 API 面向“已优化好的 NaiveBuffer 模型直接跑”;而完整版 API 面向“原始 Protobuf 模型 + 运行时优化/多后端选择”。pybind.cc 中的CxxConfig绑定包含:模型来源(set_model_dir/set_model_file/set_param_file/set_model_buffer)、set_valid_places、set_threads/set_power_mode、OpenCL/Metal/NNAdapter 全套配置、add_discarded_pass、is_model_from_memory;pybind.cc 中的CxxPredictor绑定则包含get_input/get_output/get_input_by_name/get_output_by_name/run/get_version、Synchronize,以及两个关键的模型导出接口:
predictor.save_optimized_model(output_dir) # 导出 NaiveBuffer 优化模型 predictor.save_optimized_pb_model(output_dir) # 导出优化后的 Protobuf 模型对应 C++ 虚函数SaveOptimizedModel(paddle_api.h)注释明确指出:该 API 目前由CxxConfig路径支持,导出的优化模型可再被MobileConfig复用——即「Full API 优化导出 → Light API 部署」正是端侧工程的标准工作流,与文档中“输入模型需先用 Model Optimize Tool 转为 NaiveBuffer 格式”(模型优化工具文档)相衔接。
官方示例 mobilenetv1_full_api.py 完整演示了该流程:按平台选择platform_place(x86_64 →TargetType.X86,否则TargetType.ARM),按--backend组装places列表并config.set_valid_places(places),create_paddle_predictor(config)后立即predictor.save_optimized_model("opt_" + backend),随后走与轻量 API 完全一致的「get_input(0)→from_numpy→run→get_output(0).numpy()」链路;NNAdapter 后端还演示了set_nnadapter_device_names(逗号分隔多设备)、set_nnadapter_context_properties、set_nnadapter_model_cache_dir、set_nnadapter_subgraph_partition_config_path、set_nnadapter_mixed_precision_quantization_config_path的用法(L164-L185)。
此外,绑定中还暴露了Opt类(pybind.cc),提供run_optimize、check_if_model_supported、print_supported_ops、visualize_optimized_nb_model等能力,相当于paddle_lite_opt工具的 Python 化入口,可用于在脚本中直接执行模型转换与算子支持性检查。
八、适用前提与限制小结
综合文档与源码,使用 Paddle-Lite Python API 需注意以下前提:
- 模型格式:
MobileConfig(轻量 API)只接受经 Model Optimize Tool 转换的 NaiveBuffer 模型(set_model_from_file指向.nb单文件);set_model_dir是 v2.3.0 之前的老格式加载接口,规划在 v3.0 废弃,新工程应使用set_model_from_file; - 线程与能耗模式:
set_threads/set_power_mode仅在 ARM 且开启 OpenMP 的构建中生效(源码中这组接口被LITE_WITH_ARM条件编译),其余平台由系统调度; - NumPy 互转:
from_numpy支持 bool/float32/float64/int8/int16/int32/int64/uint8 八种 dtype,不支持 float16 输入;numpy()对 Host/ARM 场景是零拷贝共享内存,XPU 场景会显式同步并拷贝; - 预测器选择:轻量路径(
MobileConfig+LightPredictor)用于端侧部署;需要多后端 kernel 选择、Pass 定制或优化模型导出时使用完整版(CxxConfig+CxxPredictor),且完整版接口在非 tiny 发布包中才可用; - 版本核对:可用
predictor.get_version()打印当前lite.so的代码版本(tag 或 branch+commit id),配合 版本说明 确认运行库与文档匹配。
【免费下载链接】Paddle-LitePaddlePaddle High Performance Deep Learning Inference Engine for Mobile and Edge (飞桨高性能深度学习端侧推理引擎)项目地址: https://gitcode.com/GitHub_Trending/pa/Paddle-Lite
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考