將動態輸入形狀固定

如果模型可以與 模型可用性檢查器 報告的 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