将动态输入形状固定

如果模型可以与 模型可用性检查器 报告的 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