前提:github下载源码编译相关工具
1.模型转换
X2Paddle可以将caffe、tensorflow、onnx模型转换成Paddle支持的模型。目前支持版本为caffe 1.0;tensorflow 1.x,推荐1.4.0;ONNX 1.6.0,OpSet支持 9, 10, 11版本。如果您使用的是PyTorch框架,请先转换为ONNX模型之后再使用X2Paddle工具转化为Paddle模型。
(1)x2paddle库安装
1.pip install x2paddle
2.安装最新版本,可使用如下安装方式
pip install git+https://github.com/PaddlePaddle/X2Paddle.git@develop
3.参数作用
--framework源模型类型 (tensorflow、caffe、onnx)
--prototxt当framework为caffe时,该参数指定caffe模型的proto文件路径
--weight当framework为caffe时,该参数指定caffe模型的参数文件路径
--save_dir指定转换后的模型保存目录路径
--model当framework为tensorflow/onnx时,该参数指定tensorflow的pb模型文件或onnx模型路径
--input_shape_dict[可选] For ONNX, 定义ONNX模型输入大小
--caffe_proto[可选] 由caffe.proto编译成caffe_pb2.py文件的存放路径,当存在自定义Layer时使用,默认为None
--define_input_shape[可选] For TensorFlow, 当指定该参数时,强制用户输入每个Placeholder的shape
--enable_code_optim[可选] For PyTorch, 是否对生成代码进行优化,默认为False
--to_lite[可选] 是否使用opt工具转成Paddle-Lite支持格式,默认为False
--lite_valid_places[可选] 指定转换类型,可以同时指定多个backend(以逗号分隔),opt将会自动选择最佳方式,默认为arm
--lite_model_type[可选] 指定模型转化类型,目前支持两种类型:protobuf和naive_buffer,默认为naive_buffer
--disable_feedback[可选] 是否关闭X2Paddle使用反馈;X2Paddle默认会统计用户在进行模型转换时的成功率,以及转换框架来源等信息,以便于帮忙X2Paddle根据用户需求进行迭代,不会上传用户的模型文件。如若不想参与反馈,可指定此参数为False即可
(2)CAFFE2Paddle
x2paddle --framework=caffe \
--prototxt=deploy.prototxt \
--weight=deploy.caffemodel \
--save_dir=pd_model
(3)TensorFlow2Paddle
x2paddle --framework=tensorflow \
--model=tf_model.pb \
--save_dir=pd_model
(4)onnx2Paddle
x2paddle --framework=onnx \
--model=onnx_model.onnx \
--save_dir=pd_model
(5)PyTorch2Paddle
from x2paddle.convert import pytorch2paddle
torch_module.eval()
pytorch2paddle(module=torch_module,
save_dir="./pd_model",
jit_type="trace",
input_examples=[torch_input])
# module (torch.nn.Module): PyTorch的Module。
# save_dir (str): 转换后模型的保存路径。
# jit_type (str): 转换方式。默认为"trace"。
# input_examples (list[torch.tensor]): torch.nn.Module的输入示例,list的长度必须与输入的长度一致。默认为None。
(1)jit_type为"trace"时,input_examples不可为None,转换后自动进行动转静;
(2)jit_type为"script"时,当input_examples为None时,只生成动态图代码;当input_examples不为None时,才能自动动转静。
(6)转换结果说明
在指定的 save_dir 下生成两个目录
1.inference_model : 模型结构和参数均序列化保存的模型格式
2.model_with_code : 保存了模型参数文件和模型的python代码
(7)使用X2paddle导出Padde-Lite支持格式
from x2paddle.convert import onnx2paddle
onnx2paddle(model_path, save_dir,
convert_to_lite=True,
lite_valid_places="arm",
lite_model_type="naive_buffer")
# model_path(str)为ONNX模型路径
# save_dir(str)为转换后模型保存路径
# convert_to_lite(bool)表示是否使用opt工具,默认为False
# lite_valid_places(str)指定转换类型,默认为arm
# lite_model_type(str)指定模型转化类型,默认为naive_buffer
1.x2paddle.convert.tf2paddle
x2paddle.convert.tf2paddle(model_path,save_dir,define_input_shape=False,convert_to_lite=False,lite_valid_places="arm", lite_model_type="naive_buffer")
(1)model_path (str): TensorFlow pb模型路径
(2)save_dir (str): 转换后模型保存路径
(3)define_input_shape (bool): 是否指定输入大小,默认为False
(4)convert_to_lite (bool): 是否使用opt工具转成Paddle-Lite支持格式,默认为False
(5)lite_valid_places (str): 指定转换类型,可以同时指定多个backend(以逗号分隔),opt将会自动选择最佳方式,默认为arm
lite_model_type (str): 指定模型转化类型,目前支持两种类型:protobuf和naive_buffer,默认为naive_buffer
2.x2paddle.convert.caffe2paddle
x2paddle.convert.caffe2paddle(proto_file,weight_file,save_dir,caffe_proto,convert_to_lite=False,lite_valid_places="arm", lite_model_type="naive_buffer")
(1)proto_file (str): caffe模型的prototxt文件
(2)weight_file (str): caffe模型的权重文件
(3)save_dir (str): 转换后模型保存路径
(4)caffe_proto (str): 可选:由caffe.proto编译成caffe_pb2.py文件的存放路径,当存在自定义Layer时使用,默认为None
(5)convert_to_lite (bool): 是否使用opt工具转成Paddle-Lite支持格式,默认为False
(6)lite_valid_places (str): 指定转换类型,可以同时指定多个backend(以逗号分隔),opt将会自动选择最佳方式,默认为arm
lite_model_type (str): 指定模型转化类型,目前支持两种类型:protobuf和naive_buffer,默认为naive_buffer
3.x2paddle.convert.onnx2paddle
x2paddle.convert.onnx2paddle(model_path,save_dir,convert_to_lite=False,lite_valid_places="arm",lite_model_type="naive_buffer")
(1)model_path (str): TensorFlow pb模型路径
(2)save_dir (str): 转换后模型保存路径
(3)convert_to_lite (bool): 是否使用opt工具转成Paddle-Lite支持格式,默认为False
(4)lite_valid_places (str): 指定转换类型,可以同时指定多个backend(以逗号分隔),opt将会自动选择最佳方式,默认为arm
lite_model_type (str): 指定模型转化类型,目前支持两种类型:protobuf和naive_buffer,默认为naive_buffer
4.x2paddle.convert.pytorch2paddle
x2paddle.convert.pytorch2paddle(module,save_dir,jit_type="trace",input_examples=None,convert_to_lite=False, lite_valid_places="arm", lite_model_type="naive_buffer")
(1)module (torch.nn.Module): PyTorch的Module
(2)save_dir (str): 转换后模型保存路径
(3)jit_type (str): 转换方式。目前有两种:trace和script,默认为trace
(4)input_examples (list[torch.tensor]): torch.nn.Module的输入示例,list的长度必须与输入的长度一致。默认为None。
(5)convert_to_lite (bool): 是否使用opt工具转成Paddle-Lite支持格式,默认为False
(6)lite_valid_places (str): 指定转换类型,可以同时指定多个backend(以逗号分隔),opt将会自动选择最佳方式,默认为arm
(7)lite_model_type (str): 指定模型转化类型,目前支持两种类型:protobuf和naive_buffer,默认为naive_buffer
2.算子支持列表
(1)TensorFlow
SourceURL:file:///home/trq/data/模型转化文档/Paddlepaddle使用.docx
Abs | Add | AddN | AddV2 |
All | ArgMax | AvgPool | BatchMatmul |
BatchMatmulV2 | BatchToSpaceNd | BiasAdd | Cast |
Ceil | Concat | ConcatV2 | Const |
Conv2D | Conv2DBackpropInput | Conv3D | DepthToSpace |
DepthwiseConv2DNative | DivNoNan | Equal | Erf |
Exp | ExpandDims | Fill | Floor |
FloorDiv | FloorMod | FusedBatchnorm | FusedBatchnormV3 |
GatherNd | GatherV2 | Greater | GreaterEqual |
Identity | IteratorV2 | LeakyRelu | LessEqual |
LogicalAnd | Matmul | Max | Maximum |
MaxPool | Mean | Merge | Minimum |
MirrorPad | Mul | Neg | NotEqual |
OneHot | OneShotIterator | Pack | Pad |
PadV2 | Placeholder | PlaceholderWithDefault | Pow |
Prod | RandomUniform | Range | RealDiv |
Relu | Relu6 | Reshape | ResizeBilinear |
ResizeNearestNeighbor | ReverseV2 | Rsqrt | Shape |
Sigmoid | Sign | Size | Slice |
Softmax | Softplus | SpaceToBatchNd | Split |
SplitV | Square | SquaredDifference | Squeeze |
StopGradient | StridedSlice | Sub | Sum |
Switch | Tanh | Tile | TopKV2 |
Transpose | Unpack | Where | IteratorGetNext |
swish_f32 |
|
|
(2)CAFFE
Input | Convolution | Deconvolution | Pooling |
LRN | InnerProduct | Softmax | Slice |
Concat | PReLU | Accuracy | Eltwise |
BatchNorm | Scale | Reshape | ArgMax |
Crop | Flatten | Power | Reduction |
Axpy | ROIPolling | Permute | DetectionOutput |
Normalize | Select | ShuffleChannel | ConvolutionDepthwise |
ReLU | AbsVal | Sigmoid | TanH |
ReLU6 | Upsample | MemoryData |
(3)ONNX
Abs | ArgMax | AverageOool | BatchNormalization |
Cast | Ceil | Clip | Constant |
ConstantOfShape | Conv | ConvTranspose | DepthToSpace |
Div | Elu | Equal | Erf |
Exp | Expand | Flatten | Floor |
Gather | Gemm | GlobalAveragePool | GlobalMaxPool |
Greater | HardSigmoid | Identity | InstanceNormalization |
LeakyRelu | Less | Log | LogSoftmax |
LRN | LSTM | Matmul | MaxPool |
MaxRoiPool | Mul | NonZero | NonMaxSuppression |
Not | OneHot | Pad | Pow |
PRelu | Range | Reciprocal | ReduceL1 |
ReduceL2 | ReduceMax | ReduceMean | ReduceMin |
ReduceProd | ReduceSum | Relu | Reshape |
Resize | RoiAlign | ScatterND | Shape |
Shrink | Sigmoid | Sign | Size |
Slice | Softmax | SoftPlus | SoftSign |
Split | Sqrt | Squeeze | Sub |
Sum | Tanh | Tile | TopK |
Transpose | Unsqueeze | Upsample | Where |
Add | Concat | Max | Min |
GreaterOrEqual | GatherND | And | cos |
Neg | SpaceToDepth | GatherElement | Sin |
CumSum | Or | Xor | Mod |
(4)PYTORCH
SourceURL:file:///home/trq/data/模型转化文档/Paddlepaddle使用.docx
aten::abs | aten::adaptive_avg_pool2d | aten::addmm | aten::add |
aten::add_ | aten::__and__ | aten::append | aten::arange |
aten::avg_pool2d | aten::avg_pool3d | aten::avg_pool1d | aten::batch_norm |
aten::cat | aten::chunk | aten::clamp | aten::__contains__ |
aten::constant_pad_nd | aten::contiguous | aten::conv2d | aten::_convolution |
aten::conv_transpose2d | aten::cos | aten::cumsum | aten::detach |
aten::dict | aten::dim | aten::div_ | aten::div |
aten::dropout | aten::dropout_ | aten::embedding | aten::eq |
aten::exp | aten::expand | aten::expand_as | aten::eye |
aten::feature_dropout | aten::flatten | aten::Float | aten::floor |
aten::floordiv | aten::floor_divide | aten::full_like | aten::gather |
aten::gelu | aten::__getitem__ | aten::gt | aten::hardtanh_ |
aten::index_select | aten::Int | aten::__is__ | aten::__isnot__ |
aten::layer_norm | aten::le | aten::leaky_relu_ | aten::len |
aten::log | aten::lt | aten::masked_fill_ | aten::masked_fill |
aten::max | aten::max_pool2d | aten::matmul | aten_min |
aten::mean | aten::meshgrid | aten::mul | aten::mul_ |
aten::ne | aten::neg | aten::__not__ | aten::ones |
aten::permute | aten::pow | aten::relu | aten::relu_ |
aten::relu6 | aten::repeat | aten::reshape | aten::rsub |
aten::ScalarImplicit | aten::select | aten::_set_item | aten::sigmoid |
aten::sin | aten::size | aten::slice | aten::softmax |
aten::softplus | aten::sqrt | aten::squeeze | aten::stack |
aten::sub | aten::t | aten::tanh | aten::split |
aten::transpose | aten::to | aten::type_as | aten::unsqueeze |
aten::upsample_bilinear2d | aten::values | aten::view | aten::warn |
aten::where | aten::zeros | aten::zeros_like | aten::bmm |
aten::sub_ | aten:erf | aten::lstm | aten::gather |
aten::upsample_nearest2d | aten::split_with_sizes | aten::sum | aten::instance_norm |
aten::bitwise_not | aten::bitwise_xor | aten::bitwise_and | aten::silu |
aten::repeat_interleave | aten::maxpool1d | aten::frobenius_norm | aten::format |
aten::complex | aten::real | aten::imag | aten::fft_rfftn |
aten::fft_irfftn | aten::hardsigmoid | aten::hardswish | aten::linear |
aten::rsqrt | aten::replication_pad1d | aten::full | aten::group_norm |
aten::argmax | aten::copy | aten::upsample_trilinear3d | aten::clone |
aten::rand | aten::randn |
|
3.模型推理API
(1)paddle.inference
1.导入paddle.inference
import paddle.inference as paddle_infer
2.创建 config
# config = paddle_infer.Config()
config = paddle_infer.Config("./mobilenet_v1.pdmodel", "./mobilenet_v1.pdiparams")
# 设置 CPU 加速库线程数为 10
config.set_cpu_math_library_num_threads(10)
3.根据 config 创建 predictor
predictor = paddle_infer.create_predictor(config)
4.获取模型输入
input_names = predictor.get_input_names()
# 根据名称获取输入 Tensor 的句柄
input_tensor = predictor.get_input_handle(input_names[0])
5.从 CPU 获取数据,设置到 Tensor 内部
fake_input = numpy.random.randn(1, 3, 224, 224).astype("float32")
input_tensor.copy_from_cpu(fake_input)
6.执行预测
predictor.run()
7.对象获取输出 Tensor
output_names = predictor.get_output_names()
# 根据名称获取输出 Tensor 的句柄
predictor.get_output_handle(output_names[0])
# output_tens# 释放中间 Tensor
predictor.clear_intermediate_tensor()
# 释放内存池中的所有临时 Tensor
predictor.try_shrink_memory()
8.从Tensor 中获取数据到 CPU数据到自身
paddle.inference.Tensor.copy_to_cpu()
(2)paddlelite.lite
1.导入paddle.lite
from paddlelite.lite import *
2.设置配置信息
config = MobileConfig()
config.set_model_from_file("Your dictionary/opt.nb")
3.创建预测器
predictor = create_paddle_predictor(config)
4.设置输入数据
input_tensor = predictor.get_input(0)
input_tensor.from_numpy(data.reshape(1, 3, 256, 256).astype(np.float32))
5.执行预测
predictor.run()
6.得到输出数据
output_tensor = predictor.get_output(0).numpy()