固定动态输入形状

如果模型可以与 NNAPI 或 CoreML 一起使用(如模型可用性检查器所报告的),则从将输入形状设为“固定”中受益。这是因为 NNAPI 不支持动态输入形状,并且 CoreML 在使用固定输入形状时性能可能更好。

例如,模型通常具有动态批处理大小,以便训练更高效。在移动端场景中,批处理大小通常为 1。通过将其设置为 1 将批处理大小维度设为“固定”可能会允许 NNAPI 运行模型。

该辅助工具可用于更新特定维度或整个输入形状。

目录

用法

python -m onnxruntime.tools.make_dynamic_shape_fixed -h
usage: make_dynamic_shape_fixed.py:make_dynamic_shape_fixed_helper [-h] [--dim_param DIM_PARAM] [--dim_value DIM_VALUE] [--input_name INPUT_NAME] [--input_shape INPUT_SHAPE] input_model output_model

Assign a fixed value to a dim_param or input shape. Provide either dim_param and dim_value or input_name and input_shape.

positional arguments:
  input_model           Provide path to ONNX model to update.
  output_model          Provide path to write updated ONNX model to.

optional arguments:
  -h, --help            show this help message and exit
  --dim_param DIM_PARAM
                        Symbolic parameter name. Provide dim_value if specified.
  --dim_value DIM_VALUE
                        Value to replace dim_param with in the model. Must be > 0.
  --input_name INPUT_NAME
                        Model input name to replace shape of. Provide input_shape if specified.
  --input_shape INPUT_SHAPE
                        Shape to use for input_shape. Provide comma separated list for the shape. All values must be > 0. e.g. --input_shape 1,3,256,256

为了确定模型所需的更新,通常有助于在 Netron 中查看模型以检查输入。

固定符号维度

这里有一个示例模型,使用 Netron 查看,其中‘input:0’的批处理大小有一个名为‘batch’的符号维度。我们将更新它以使用固定值 1。

Model with symbolic dimension in input shape


python -m onnxruntime.tools.make_dynamic_shape_fixed --dim_param batch --dim_value 1 model.onnx model.fixed.onnx

替换后,您应该看到‘input:0’的形状现在被“固定”为 [1, 36, 36, 3]。

Model with symbolic dimension in input shape replaced with fixed value

固定输入形状

这里有一个示例模型,其‘x’输入具有未命名的动态维度。Netron 使用‘?’表示这些维度。由于维度没有名称,我们需要使用 --input_shape 选项更新形状。

Model with dynamic input shape


python -m onnxruntime.tools.make_dynamic_shape_fixed --input_name x --input_shape 1,3,960,960 model.onnx model.fixed.onnx

替换后,您应该看到‘x’的形状现在被“固定”为 [1, 3, 960, 960]。

Updated model with dynamic input shape now having fixed values