PaddleX

张开发
2026/4/21 17:42:42 15 分钟阅读

分享文章

PaddleX
PaddleX模型产线CLI命令行使用说明在使用CLI命令行进行模型产线快速推理前请确保您已经按照PaddleX本地安装教程完成了PaddleX的安装。一、使用示例1. 快速体验以图像分类产线为例使用方式如下paddlex --pipeline image_classification \ --input https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_image_classification_001.jpg \ --device gpu:0 \ --save_path ./output/ \ --topk 5只需一步就能完成推理预测并保存预测结果相关参数说明如下1pipeline模型产线名称或是模型产线配置文件的本地路径如模型产线名 “image_classification”或模型产线配置文件路径 “path/to/image_classification.yaml”2input待预测数据文件路径支持本地文件路径、包含待预测数据文件的本地目录、文件URL链接3engine推理引擎可选paddle、paddle_static、paddle_dynamic、hpi、flexible、transformers、genai_client4device用于设置模型推理设备如为GPU则可以指定卡号如 “cpu”、“gpu:2”默认情况下如GPU可用则使用GPU 0否则使用CPU5save_path预测结果的保存路径默认情况下不保存预测结果6use_hpip启用高性能推理插件7hpi_config高性能推理配置8推理超参数不同产线根据具体情况提供了不同的推理超参数设置该参数优先级大于产线配置文件。对于图像分类产线则支持通过topk参数设置输出的前 k 个预测结果。其他产线请参考对应的产线说明文档。2. 自定义产线配置如需对产线进行修改可获取产线配置文件后进行修改仍以图像分类产线为例获取配置文件方式如下paddlex --get_pipeline_config image_classification # Please enter the path that you want to save the pipeline config file: (default ./) ./configs/ # The pipeline config has been saved to: configs/image_classification.yaml然后可修改产线配置文件configs/image_classification.yaml如图像分类配置文件内容为pipeline_name: image_classification SubModules: ImageClassification: module_name: image_classification model_name: PP-LCNet_x0_5 model_dir: null batch_size: 4 device: gpu:0 topk: 5在修改完成后即可使用该配置文件进行模型产线推理预测方式如下paddlex --pipeline configs/image_classification.yaml \ --input https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_image_classification_001.jpg \ --save_path ./output/ # {input_path: /root/.paddlex/predict_input/general_image_classification_001.jpg, class_ids: [296, 170, 356, 258, 248], scores: array([0.62817, 0.03729, 0.03262, 0.03247, 0.03196]), label_names: [ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus, Irish wolfhound, weasel, Samoyed, Samoyede, Eskimo dog, husky]}二、PaddleX CLI 参数说明产线推理1. 通用参数--pipeline产线名称或产线配置文件路径.yaml/.yml--input输入数据路径、目录或 URL--save_path结果保存目录--device推理设备如cpu、gpu:0--engine统一指定产线推理引擎--use_hpip启用高性能推理插件仅在未显式指定--engine时有意义--hpi_config高性能推理插件配置使用 Python 字面量格式传入如{backend: trt}--get_pipeline_config导出指定产线默认配置文件。2. 引擎配置方式系统说明CLI 当前提供--engine参数用于快速切换推理引擎engine_config通过产线配置文件进行设置。2.1 方式 A命令行直接指定引擎paddlex --pipeline image_classification \ --input ./demo.jpg \ --engine paddle_static \ --device cpu2.2 方式 B配置文件中指定engine和engine_configpipeline_name: image_classification engine: paddle_static engine_config: device_type: cpu cpu_threads: 4 SubModules: ImageClassification: module_name: image_classification model_name: PP-LCNet_x1_0使用方式paddlex --pipeline ./configs/image_classification.yaml \ --input ./demo.jpg2.3 方式 C全局配置 子模块/子产线覆盖pipeline_name: OCR engine: paddle_static engine_config: device_type: cpu cpu_threads: 4 SubModules: TextRecognition: module_name: text_recognition model_name: PP-OCRv5_server_rec engine: transformers engine_config: dtype: float16 device_map: cuda:02.4 各引擎支持的engine_config字段CLI 下engine_config主要通过配置文件设置常用字段及含义如下1paddle_staticrun_mode运行模式、device_type/device_id设备、cpu_threadsCPU 线程数、delete_pass禁用 pass 列表、enable_new_ir、enable_cinn、trt_cfg_settingTRT 底层参数、trt_use_dynamic_shapes、trt_collect_shape_range_info、trt_discard_cached_shape_range_info、trt_dynamic_shapes[min,opt,max]形状、trt_dynamic_shape_input_data动态形状填充输入、trt_shape_range_info_pathshape range 文件路径、trt_allow_rebuild_at_runtime运行时重建 TRT 引擎、mkldnn_cache_capacityoneDNN 缓存2paddle_dynamicdevice_type/device_id动态图执行设备3hpimodel_name一般自动注入、device_type/device_id、auto_config自动选后端、backend指定后端、backend_config后端参数、hpi_info模型先验信息、auto_paddle2onnx自动 Paddle2ONNX4transformersdtype精度、device_map设备映射、trust_remote_code是否信任远程代码、attn_implementation注意力实现、generation_config生成参数、model_kwargs、tokenizer_kwargs5genai_clientbackend服务后端、server_url服务地址、max_concurrency并发上限、client_kwargs客户端透传参数6flexible无固定字段约束。说明paddle是自动解析引擎不单独定义engine_config字段产线实际生效时由“全局配置 子模块/子产线覆盖”共同决定。3. 参数优先级1--engine的优先级高于产线配置文件中的engine2engine_config由配置文件控制可在全局设置也可在子模块或子产线中覆盖3在任一层级中当该层未显式设置engine时会按该层支持的引擎选择参数自动解析最终引擎其中若该层支持genai_config且genai_config.backend指向服务器后端则解析为genai_client否则若use_hpipTrue则优先解析为hpi否则若对应模型仅支持flexible则解析为flexible否则回退为paddle再根据模型文件自动解析为paddle_static或paddle_dynamic4同一层级内engine的优先级高于use_hpip/genai_config但如果子模块或子产线未显式设置engine而显式设置了use_hpip则会优先按这一层重新解析引擎而不是继续继承上一级的engine如果子模块未显式设置engine但显式设置了指向服务器后端的genai_config.backend也会优先按子模块这一层重新解析引擎5当子模块或子产线因本层use_hpip改为本层自动解析引擎时或当子模块因指向服务器后端的genai_config改为本层自动解析引擎时不再继续继承上一级的engine_config需要在该层按最终引擎补充配置6各产线专属参数例如--topk优先级高于配置文件同名字段。4. 哪些场景可以不安装 PaddlePaddle以下场景可在未安装 PaddlePaddle 时运行前提是模型和依赖已满足使用transformers引擎注意若产线中任一模块最终走paddle/hpi引擎仍需安装 PaddlePaddle使用flexible引擎时是否依赖飞桨框架取决于具体模型实现请参考对应模型/产线文档说明。PaddleX模型产线Python脚本使用说明在使用 Python 脚本进行模型产线快速推理前请确保您已经按照 PaddleX 本地安装教程完成了 PaddleX 的安装。一、使用示例以图像分类产线为例使用方式如下from paddlex import create_pipeline pipeline create_pipeline(image_classification) output pipeline.predict(https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_image_classification_001.jpg, batch_size1, topk5) for res in output: res.print(json_formatFalse) res.save_to_img(./output/) res.save_to_json(./output/res.json)简单来说只需三步调用create_pipeline()方法实例化预测模型产线对象调用预测模型产线对象的predict()方法进行推理预测调用print()、save_to_xxx()等相关方法对预测结果进行打印输出或是保存。二、API说明1. 调用create_pipeline()方法实例化预测模型产线对象create_pipeline实例化预测模型产线对象参数pipelinestr类型产线名或是本地产线配置文件路径如“image_classification”、“/path/to/image_classification.yaml”configdict | None类型直接传入产线配置字典。若传入该参数可不传pipelinedevicestr类型用于设置模型推理设备如为 GPU 则可以指定卡号如“cpu”、“gpu:2”默认情况下如GPU可用则使用GPU 0否则使用CPUenginestr | None类型推理引擎。可选paddle、paddle_static、paddle_dynamic、hpi、flexible、transformers、genai_clientengine_configdict | None类型推理引擎配置针对解析后引擎的扁平 dict或仅按引擎名分桶的 dict见 4.2 节。若设置将传递并合并到各子模块pp_optionPaddlePredictorOption类型用于改变运行模式等配置项关于推理配置的详细说明请参考下文5-兼容配置PaddlePredictorOptionuse_hpipbool | None类型是否启用高性能推理插件None表示使用配置文件中的配置hpi_configdict | None类型高性能推理配置返回值BasePipeline类型。2. 调用预测模型产线对象的predict()方法进行推理预测predict使用定义的预测模型产线对输入数据进行预测参数input任意类型支持str类型表示的待预测数据文件路径或是包含待预测文件的目录或是网络URL对于CV任务支持numpy.ndarray表示的图像数据对于TS任务支持pandas.DataFrame类型数据同样支持上述类型所构成的list类型返回值generator每次调用返回一个样本的预测结果3. 对预测结果进行可视化模型产线的预测结果支持访问、可视化及保存可通过相应的属性或方法实现具体如下属性strstr类型表示的预测结果返回值str类型预测结果的str表示jsonjson格式表示的预测结果返回值dict类型img预测结果的可视化图返回值PIL.Image类型html预测结果的HTML表示返回值str类型更多不同产线的预测结果支持不同的表示方式更多属性请参考具体产线文档方法print()将预测结果输出需要注意当预测结果不便于直接输出时会省略相关内容参数json_formatbool类型默认为False表示不使用json格式化输出indentint类型默认为4当json_format为True时有效表示json格式化的类型ensure_asciibool类型默认为False当json_format为True时有效返回值无save_to_json()将预测结果保存为json格式的文件需要注意当预测结果包含无法json序列化的数据时会自动进行格式转换以实现序列化保存参数save_pathstr类型结果保存的路径indentint类型默认为4当json_format为True时有效表示json格式化的类型ensure_asciibool类型默认为False当json_format为True时有效返回值无save_to_img()将预测结果可视化并保存为图像参数save_pathstr类型结果保存的路径返回值无save_to_csv()将预测结果保存为CSV文件参数save_pathstr类型结果保存的路径返回值无save_to_html()将预测结果保存为HTML文件参数save_pathstr类型结果保存的路径返回值无save_to_xlsx()将预测结果保存为XLSX文件参数save_pathstr类型结果保存的路径返回值无更多不同产线的预测结果支持不同的存储方式更多方法请参考具体产线文档4. 推理引擎与配置PaddleX 产线支持统一的engineengine_config配置并支持“全局 子模块”分层设置。4.1 引擎列表paddle自动解析引擎当模块使用本地模型目录时根据本地模型文件解析为paddle_static或paddle_dynamic否则根据模块支持情况自动选择优先paddle_staticpaddle_staticPaddle Inference 静态图推理paddle_dynamicPaddle 动态图推理hpi高性能推理插件flexible灵活运行时引擎transformers基于 Hugging Face Transformers 的推理引擎genai_client调用外部生成式 AI 服务的客户端引擎。4.2 扁平与分桶engine_config本节说明**同一层级**上engine_config字典的**形态**与下一节「配置方式」并列而不是第四种配置途径。在同一层级例如create_pipeline(...)或 YAML 中某一块中engine_config可以是扁平仅针对**最终解析出的**引擎的参数字典例如paddle_static下的{device_type: gpu, device_id: 0}。分桶顶层键**只能**为已注册的引擎名paddle_static、paddle_dynamic、hpi、flexible、transformers、onnxruntime、genai_client每个键对应一个嵌套 dict。最终引擎确定后仅使用当前解析引擎对应键下的配置作为该引擎的扁平配置。若该引擎无对应键则使用空配置并发出警告。严格规则同一顶层**禁止**混用「分桶键」与「扁平字段」。请要么全部使用扁平 dict要么全部使用分桶 dict。4.3 配置方式方式 1通过create_pipeline传参设置全局引擎from paddlex import create_pipeline pipeline create_pipeline( pipelineimage_classification, devicegpu:0, enginepaddle_static, engine_config{ device_type: gpu, device_id: 0, }, )方式 2通过产线配置文件设置引擎pipeline_name: image_classification engine: paddle_static engine_config: device_type: gpu device_id: 0 SubModules: ImageClassification: module_name: image_classification model_name: PP-LCNet_x1_0方式 3对子模块单独覆盖pipeline_name: OCR engine: paddle_static engine_config: device_type: cpu cpu_threads: 4 SubModules: TextRecognition: module_name: text_recognition model_name: PP-OCRv5_server_rec engine: transformers engine_config: dtype: float16 device_type: gpu device_id: 04.4 生效规则create_pipeline(..., engine...)传参优先级高于配置文件中的同名字段全局engine_config会与子模块或子产线的engine_config合并同名字段以后者优先在任一层级中当engineNone时会按该层支持的引擎选择参数自动解析最终引擎其中若该层支持genai_config且genai_config.backend指向服务器后端如fastdeploy-server、vllm-server、sglang-server、mlx-vlm-server、llama-cpp-server则解析为genai_client否则若use_hpipTrue则优先解析为hpi否则若对应模型仅支持flexible则解析为flexible否则等价于paddle当模块使用本地模型目录时根据本地模型文件解析为paddle_static或paddle_dynamic否则根据模块支持情况自动选择优先paddle_static同一层级内engine的优先级高于use_hpip/genai_config当子模块或子产线未显式设置engine但显式设置了use_hpip时会优先按这一层重新解析引擎而不是继续继承上一级的engine当子模块未显式设置engine但显式设置了指向服务器后端的genai_config.backend时也会优先按子模块这一层重新解析引擎而不是继续继承上一级的engine上述情况下如果该层改为本层自动解析引擎则不会继续继承上一级的engine_config应在该层按最终引擎补充对应配置。显式设置engine时use_hpip不再生效显式设置engine_config时pp_option与hpi_config作为兼容参数通常不再需要。4.5 是否必须安装 PaddlePaddle在以下场景中可以不安装 PaddlePaddle产线中相关模型使用enginetransformers注意若产线中模块最终使用paddle/hpi引擎仍需安装 PaddlePaddle使用flexible引擎时是否依赖飞桨框架取决于具体模型实现请参考对应模型/产线文档说明。4.6 各引擎engine_config字段说明以下字段同样适用于产线中各子模块全局配置可被子模块覆盖paddle_staticrun_mode运行模式如paddle、trt_fp32、trt_fp16、mkldnndevice_type/device_id设备类型和设备编号cpu_threadsCPU 推理线程数delete_pass手动禁用的图优化 pass 列表enable_new_ir是否启用新 IRenable_cinn是否启用 CINNtrt_cfg_settingTensorRT 底层配置透传trt_use_dynamic_shapes是否启用 TRT 动态形状trt_collect_shape_range_info是否自动采集 shape range 信息trt_discard_cached_shape_range_info是否丢弃并重采 shape rangetrt_dynamic_shapes动态形状配置格式为输入名到[min,opt,max]trt_dynamic_shape_input_data动态形状采集时的输入填充数据trt_shape_range_info_pathshape range 文件路径trt_allow_rebuild_at_runtime运行时是否允许重建 TRT 引擎mkldnn_cache_capacityoneDNNMKLDNN缓存容量。paddle_dynamicdevice_type/device_id动态图执行设备及编号。hpimodel_name模型名通常自动注入device_type/device_id设备类型和编号auto_config是否自动选择后端及默认配置backend显式指定后端backend_config后端专属配置如run_mode、TRT 精度等hpi_info模型先验信息如动态 shapeauto_paddle2onnx缺少 ONNX 模型时是否自动转换。transformersdtype推理数据类型device_type/device_id推理设备类型和设备编号trust_remote_code是否信任远程自定义代码attn_implementation注意力实现方式generation_config文本生成参数model_kwargs模型加载附加参数processor_kwargsprocessor / image processor 加载附加参数tokenizer_kwargs兼容保留的加载附加参数会与processor_kwargs合并使用。genai_clientbackend远端服务后端类型server_url服务地址服务器后端必填max_concurrency最大并发请求数client_kwargs透传客户端参数如鉴权参数。flexible无固定字段约束按具体模型自定义解析。说明paddle为自动解析引擎不单独定义engine_config字段除flexible外多数引擎会校验字段并拒绝未知参数。5. 兼容配置PaddlePredictorOptionPaddlePredictorOption作为兼容配置保留建议新项目优先使用engine_config。生效范围主要用于paddle_static兼容配置常用字段run_mode运行模式如paddle、trt_fp32、trt_fp16、mkldnndevice推理设备如cpu、gpu:0cpu_threadsCPU 推理线程数trt_dynamic_shapesTensorRT 动态形状配置trt_dynamic_shape_input_data动态形状采集时输入填充数据。迁移建议优先使用engine engine_config当同时传入engine_config与pp_option时以engine_config为准。产线并行推理指定多个推理设备对于部分产线的 CLI 和 Python APIPaddleX 支持同时指定多个推理设备。如果指定了多个设备产线初始化时将在每个设备上创建一个底层产线类对象的实例并对接收到的输入进行并行推理。例如对于通用版面解析 v3 产线paddlex --pipeline PP-StructureV3 \ --input input_images/ \ --use_doc_orientation_classify False \ --use_doc_unwarping False \ --use_textline_orientation False \ --save_path ./output \ --device gpu:0,1,2,3pipeline create_pipeline(pipelinePP-StructureV3, devicegpu:0,1,2,3) output pipeline.predict( inputinput_images/, use_doc_orientation_classifyFalse, use_doc_unwarpingFalse, use_textline_orientationFalse, )以上两个例子均使用 4 块 GPU编号为 0、1、2、3对input_images目录中的文件进行并行推理。指定多个设备时推理接口仍然与指定单设备时保持一致。请查看产线使用教程以了解某一产线是否支持指定多个推理设备。多进程并行推理示例除了使用 PaddleX 内置的多设备并行推理功能外用户也可以结合实际场景通过包装 PaddleX 产线推理 API 调用逻辑等手段实现并行推理加速以期达到更优的加速比。如下是使用 Python 多进程实现多卡、多实例并行处理输入目录中的文件的示例代码import argparse import sys from multiprocessing import Manager, Process from pathlib import Path from queue import Empty from paddlex import create_pipeline from paddlex.utils.device import constr_device, parse_device def worker(pipeline_name_or_config_path, device, task_queue, batch_size, output_dir): pipeline create_pipeline(pipeline_name_or_config_path, devicedevice) should_end False batch [] while not should_end: try: input_path task_queue.get_nowait() except Empty: should_end True else: batch.append(input_path) if batch and (len(batch) batch_size or should_end): try: for result in pipeline.predict(batch): input_path Path(result[input_path]) if result.get(page_index) is not None: output_path f{input_path.stem}_{result[page_index]}.json else: output_path f{input_path.stem}.json output_path str(Path(output_dir, output_path)) result.save_to_json(output_path) print(fProcessed {repr(str(input_path))}) except Exception as e: print( fError processing {batch} on {repr(device)}: {e}, filesys.stderr ) batch.clear() def main(): parser argparse.ArgumentParser() parser.add_argument( --pipeline, typestr, requiredTrue, helpPipeline name or config path. ) parser.add_argument(--input_dir, typestr, requiredTrue, helpInput directory.) parser.add_argument( --device, typestr, requiredTrue, helpSpecifies the devices for performing parallel inference., ) parser.add_argument( --output_dir, typestr, defaultoutput, helpOutput directory. ) parser.add_argument( --instances_per_device, typeint, default1, helpNumber of pipeline instances per device., ) parser.add_argument( --batch_size, typeint, default1, helpInference batch size for each pipeline instance., ) parser.add_argument( --input_glob_pattern, typestr, default*, helpPattern to find the input files., ) args parser.parse_args() input_dir Path(args.input_dir) if not input_dir.exists(): print(fThe input directory does not exist: {input_dir}, filesys.stderr) return 2 if not input_dir.is_dir(): print(f{repr(str(input_dir))} is not a directory., filesys.stderr) return 2 output_dir Path(args.output_dir) if output_dir.exists() and not output_dir.is_dir(): print(f{repr(str(output_dir))} is not a directory., filesys.stderr) return 2 output_dir.mkdir(parentsTrue, exist_okTrue) device_type, device_ids parse_device(args.device) if device_ids is None or len(device_ids) 1: print( Please specify at least two devices for performing parallel inference., filesys.stderr, ) return 2 if args.batch_size 0: print(Batch size must be greater than 0., filesys.stderr) return 2 with Manager() as manager: task_queue manager.Queue() for img_path in input_dir.glob(args.input_glob_pattern): task_queue.put(str(img_path)) processes [] for device_id in device_ids: for _ in range(args.instances_per_device): device constr_device(device_type, [device_id]) p Process( targetworker, args( args.pipeline, device, task_queue, args.batch_size, str(output_dir), ), ) p.start() processes.append(p) for p in processes: p.join() print(All done) return 0 if __name__ __main__: sys.exit(main())假设将上述脚本存储为mp_infer.py以下是一些调用示例# 通用版面解析 v3 产线 # 处理 input_images 目录中所有文件 # 使用 GPU 0、1、2、3每块 GPU 上 1 个产线实例每个实例一次处理 1 个输入文件 python mp_infer.py \ --pipeline PP-StructureV3 \ --input_dir input_images/ \ --device gpu:0,1,2,3 \ --output_dir output1 # 通用版面解析 v3 产线 # 处理 input_images 目录中所有后缀为 .jpg 的文件 # 使用 GPU 0、2每块 GPU 上 2 个产线实例每个实例一次处理 4 个输入文件 python mp_infer.py \ --pipeline PP-StructureV3 \ --input_dir input_images/ \ --device gpu:0,2 \ --output_dir output2 \ --instances_per_device 2 \ --batch_size 4 \ --input_glob_pattern *.jpg转自https://paddlepaddle.github.io/PaddleX/latest/pipeline_usage/instructions/parallel_inference.html#_3

更多文章