diff --git a/docs/ONNX_Runtime_Mobile_NNAPI_perf_considerations.md b/docs/ONNX_Runtime_Mobile_NNAPI_perf_considerations.md new file mode 100644 index 0000000000..3c3c0360cf --- /dev/null +++ b/docs/ONNX_Runtime_Mobile_NNAPI_perf_considerations.md @@ -0,0 +1,111 @@ +# ONNX Runtime Mobile: Performance Considerations When Using NNAPI + +ONNX Runtime Mobile with the NNAPI Execution Provider (EP) can be used to execute ORT format models on Android platforms using NNAPI. This document explains the details of how different optimizations affect performance, and provides some suggestions for performance testing with ORT format models. + +Please review the introductory details for [using NNAPI with ONNX Runtime Mobile](ONNX_Runtime_for_Mobile_Platforms.md#Using-NNAPI-with-ONNX-Runtime-Mobile) first. + + +## 1. ONNX Model Optimization Example + +ONNX Runtime applies optimizations to the ONNX model to improve inferencing performance. These optimizations occur prior to exporting an ORT format model. See the [graph optimization](ONNX_Runtime_Graph_Optimizations.md) documentation for further details of the available optimizations. + +It is important to understand how the different optimization levels affect the nodes in the model, as this will determine how much of the model can be executed using NNAPI. + +*Basic* + +The _basic_ optimizations remove redundant nodes and perform constant folding. Only ONNX operators are used by these optimizations when modifying the model. + +*Extended* + +The _extended_ optimizations replace one or more standard ONNX operators with custom internal ONNX Runtime operators to boost performance. Each optimization has a list of EPs that it is valid for. It will only replace nodes that are assigned to that EP, and the replacement node will be executed using the same EP. + +*Layout* + +_Layout_ optimizations are hardware specific, and should not be used when creating ORT format models. + +### Outcome of optimizations when creating an optimized ORT format model + +Below is an example of the changes that occur in _basic_ and _extended_ optimizations when applied to the MNIST model with only the CPU EP enabled. The optimization level is specified when creating the ORT format model using `convert_onnx_models_to_ort.py`. + + - At the _basic_ level we combine the Conv and Add nodes (the addition is done via the 'B' input to Conv), we combine the MatMul and Add into a single Gemm node (the addition is done via the 'C' input to Gemm), and constant fold to remove one of the Reshape nodes. + - `python /tools/python/convert_onnx_models_to_ort.py --optimization_level basic /dir_with_mnist_onnx_model` + - At the _extended_ level we additionally fuse the Conv and Relu nodes using the internal ONNX Runtime FusedConv operator. + - `python /tools/python/convert_onnx_models_to_ort.py --optimization_level extended /dir_with_mnist_onnx_model` + +Changes to nodes from basic and extended optimizations. + +### Outcome of executing an optimized ORT format model using the NNAPI EP + +If the NNAPI EP is registered at runtime, it is given an opportunity to select the nodes in the loaded model that it can execute. When doing so it will group as many nodes together as possible to minimize the overhead of copying data between the CPU and NNAPI to execute the nodes. Each group of nodes can be considered as a sub-graph. The more nodes in each sub-graph, and the fewer sub-graphs, the better the performance will be. + +For each sub-graph, the NNAPI EP will create an [NNAPI model](https://developer.android.com/ndk/guides/neuralnetworks#model) that replicates the processing of the original nodes. It will create a function that executes this NNAPI model and performs any required data copies between CPU and NNAPI. ONNX Runtime will replace the original nodes in the loaded model with a single node that calls this function. + +If the NNAPI EP is not registered, or can not process a node, the node will be executed using the CPU EP. + +Below is an example for the MNIST model comparing what happens to the ORT format models at runtime if the NNAPI EP is registered. + +As the _basic_ level optimizations result in a model that only uses ONNX operators, the NNAPI EP is able to handle the majority of the model as NNAPI can execute the Conv, Relu and MaxPool nodes. This is done with a single NNAPI model as all the nodes NNAPI can handle are connected. We would expect performance gains from using NNAPI with this model, as the overhead of the device copies between CPU and NNAPI for a single NNAPI node is likely to be exceeded by the time saved executing multiple operations at once using NNAPI. + +The _extended_ level optimizations introduce the custom FusedConv nodes, which the NNAPI EP ignores as it will only take nodes that are using ONNX operators that NNAPI can handle. This results in two nodes using NNAPI, each handling a single MaxPool operation. The performance of this model is likely to be adversely affected, as the overhead of the device copies between CPU and NNAPI (which are required before and after each of the two NNAPI nodes) is unlikely to be exceeded by the time saved executing a single MaxPool operation each time using NNAPI. Better performance may be obtainable by not registering the NNAPI EP so that all nodes in the model are executed using the CPU EP. + +Changes to nodes by NNAPI EP depending on the optimization level the model was created with. + +## 2. Initial Performance Testing + +The best optimization settings will differ by model. Some models may perform better with NNAPI, some models may not. As the performance will be model specific you must performance test to determine the best combination for your model. + +It is suggested to run performance tests: + - with NNAPI enabled and an ORT format model created with _basic_ level optimization + - with NNAPI disabled and an ORT format model created with _extended_ level optimization + +For most scenarios it is expected that one of these two approaches will yield the best performance. + +If using an ORT format model with _basic_ level optimizations and NNAPI yields equivalent or better performance, it _may_ be possible to further improve performance by creating an NNAPI-aware ORT format model. The difference with this model is that the _extended_ optimizations are applied to nodes that can not be executed using NNAPI. Whether any nodes fall into this category is model dependent. + +## 3. Creating an NNAPI-aware ORT format model + +An NNAPI-aware ORT format model will keep all nodes from the ONNX model that can be executed using NNAPI, and allow _extended_ optimizations to be applied to any remaining nodes. + +For our MNIST model that would mean that after the _basic_ optimizations are applied, the nodes in the red shading are kept as-is, and nodes in the green shading could have _extended_ optimizations applied to them. + +Show nodes that are preserved as NNAPI can execute them, and nodes that are considered by extended optimizations. + +To create an NNAPI-aware ORT format model please follow these steps. + +1. Create a 'full' build of ONNX Runtime with the NNAPI EP by [building ONNX Runtime from source](https://github.com/microsoft/onnxruntime/blob/master/BUILD.md#start-baseline-cpu). + + This build can be done on any platform, as the NNAPI EP can be used to create the ORT format model without the Android NNAPI library as there is no model execution in this process. When building add `--use_nnapi --build_shared_lib --build_wheel` to the build flags if any of those are missing. + + Do NOT add the --minimal_build` flag. + - Windows : + ``` + \build.bat --config RelWithDebInfo --use_nnapi --build_shared_lib --build_wheel --parallel + ``` + + - Linux: + ``` + /build.sh --config RelWithDebInfo --use_nnapi --build_shared_lib --build_wheel --parallel + ``` + + - **NOTE** if you have previously done a minimal build you will need to run `git reset --hard` to make sure any operator kernel exclusions are reversed prior to performing the 'full' build. If you do not, you may not be able to load the ONNX format model due to missing kernels. + +2. Install the python wheel from the build output directory. + + - Windows : This is located in `build/Windows///dist/.whl`. + + - Linux : This is located in `build/Linux//dist/.whl`. + + The package name will differ based on your platform, python version, and build parameters. `` is the value from the `--config` parameter from the build command. + ``` + pip install -U build\Windows\RelWithDebIfo\RelWithDebIfo\dist\onnxruntime_noopenmp-1.5.2-cp37-cp37m-win_amd64.whl + ``` + +3. Create an NNAPI-aware ORT format model by running `convert_onnx_models_to_ort.py` as per the [standard instructions](ONNX_Runtime_for_Mobile_Platforms.md#Create-ORT-format-model-and-configuration-file-with-required-operators), with NNAPI enabled (`--use_nnapi`), and the optimization level set to _extended_ (`--optimization_level extended`). This will allow extended level optimizations to run on any nodes that NNAPI can not handle. + + ``` + python /tools/python/convert_onnx_models_to_ort.py --use_nnapi --optimization_level extended /models + ``` + + The python package from your 'full' build with NNAPI enabled must be installed for `--use_nnapi` to be a valid option + +This model can be used with [a minimal build that includes the NNAPI EP](ONNX_Runtime_for_Mobile_Platforms.md#Create-a-minimal-build-for-Android-with-NNAPI-support). \ No newline at end of file diff --git a/docs/ONNX_Runtime_for_Mobile_Platforms.md b/docs/ONNX_Runtime_for_Mobile_Platforms.md index a320f9052a..0cb4d2df4b 100644 --- a/docs/ONNX_Runtime_for_Mobile_Platforms.md +++ b/docs/ONNX_Runtime_for_Mobile_Platforms.md @@ -21,11 +21,9 @@ Once you have cloned the repository, perform the following steps to create a min We will use a helper python script to convert ONNX format models into ORT format models, and to create the configuration file for use with the minimal build. This will require the standard ONNX Runtime python package to be installed. - - - Install the ONNX Runtime nightly python package from https://test.pypi.org/project/ort-nightly/ - - e.g. `pip install -i https://test.pypi.org/simple/ ort-nightly` + - Install the ONNX Runtime python package from https://pypi.org/project/onnxruntime/. Version 1.5.2 or later is required. + - `pip install onnxruntime` - ensure that any existing ONNX Runtime python package was uninstalled first, or use `-U` with the above command to upgrade an existing package - - using the nightly package is temporary until ONNX Runtime version 1.5 is released - Copy all the ONNX models you wish to convert and use with the minimal build into a directory - Convert the ONNX models to ORT format - `python /tools/python/convert_onnx_models_to_ort.py ` @@ -42,7 +40,8 @@ Running `'python /tools/python/convert_onnx_models_to_ort.p You will need to build ONNX Runtime from source to reduce the included operator kernels and other aspects of the binary. -See [here](https://github.com/microsoft/onnxruntime/blob/master/BUILD.md#start-baseline-cpu) for the general ONNX Runtime build instructions. +See [here](https://github.com/microsoft/onnxruntime/blob/master/BUILD.md#start-baseline-cpu) for the general ONNX Runtime build instructions. + #### Binary size reduction options: @@ -55,8 +54,8 @@ The follow options can be used to reduce the build size. Enable all options that - Enable minimal build (`--minimal_build`) - A minimal build will ONLY support loading and executing ORT format models. - RTTI is disabled by default in this build, unless the Python bindings (`--build_wheel`) are enabled. - - If you wish to enable a compiling execution provider such as NNAPI specify `--minimal_build extended`. - - See [here](#Enabling-Execution-Providers-that-compile-kernels-in-a-minimal-build) for more information + - If you wish to enable execution providers that compile kernels such as NNAPI specify `--minimal_build extended`. + - See [here](#Using-NNAPI-with-ONNX-Runtime-Mobile) for more information about using NNAPI with ONNX Runtime Mobile on Android platforms - Disable exceptions (`--disable_exceptions`) - Disables support for exceptions in the build. @@ -121,50 +120,32 @@ so.add_session_config_entry('session.load_model_format', 'ORT') session = onnxruntime.InferenceSession(, so) ``` -## Advanced Usage -### Enabling Execution Providers that compile kernels in a minimal build +## Using NNAPI with ONNX Runtime Mobile -It is possible to enable execution providers that compile kernels in a minimal build. -Currently the NNAPI execution provider is the only execution provider that has support for running in a minimal build. +Using the NNAPI Execution Provider on Android platforms is now supported by ONNX Runtime Mobile. A minimal build targeting Android with NNAPI support must be created. An ORT format model that only uses ONNX operators is also recommended as a starting point. -#### Create NNAPI aware ORT format model - - Create a 'full' (i.e. no usage of the `--minimal_build` flag) build of ONNX Runtime with NNAPI enabled - - **NOTE** do this prior to creating the minimal build - - the process for creating a minimal build will exclude operators that may be needed to load the ONNX model and create the ORT format model - - if you have previously done a minimal build, run `git reset --hard` to make sure any operator kernel exclusions are reversed - - we can not use the ONNX Runtime prebuilt package as NNAPI is not enabled in it - - the 'full' build can be done on any platform - - you do NOT need to create an Android build of ONNX Runtime in order to create an ORT format model that is optimized for usage with NNAPI. - - when the NNAPI execution provider is enabled on non-Android platforms it can only specify which nodes can be assigned to NNAPI. it can NOT be used to execute the model. - - perform a standard build as per the [common build instructions](https://github.com/microsoft/onnxruntime/blob/master/BUILD.md#common-build-instructions), and add `--use_nnapi --build_shared_lib --build_wheel` to the build flags if any of those are missing - - Install the python wheel from the build output directory - - this is located in `build/Windows///dist/.whl` on Windows, or `build/Linux//dist/.whl` on Linux. - - `` is the value from the `--config` parameter from the build command (e.g. Release) - - the package name will differ based on your platform, python version, and build parameters - - e.g. `pip install -U build\Windows\Release\Release\dist\onnxruntime-1.5.2-cp37-cp37m-win_amd64.whl` - - Create an ORT format model by running `tools\python\convert_onnx_models_to_ort.py` as per the above instructions, with the addition of the `--use_nnapi` parameter - - the python package from your 'full' build with NNAPI enabled must be installed for `--use_nnapi` to be a valid option - - this will preserve all the nodes that can be assigned to NNAPI, as well as setup the ability to fallback to CPU execution if NNAPI is not available at runtime, or if NNAPI can not run all the nodes due to device limitations. +For a more in-depth analysis of the performance considerations when using NNAPI with an ORT format model please see [ONNX Runtime Mobile: Performance Considerations When Using NNAPI](ONNX_Runtime_Mobile_NNAPI_perf_considerations.md). -The generated ORT format model can be used on all platforms, however there is an important caveat: - - Basic optimization such as constant folding run prior to the NNAPI execution provider being asked to nominate the nodes it can handle. These optimizations will be included in the ORT format model - - Any potential extended optimizations on nodes that the NNAPI execution provider claims will not occur - - these are optimizations that involve custom non-ONNX operators - - e.g. custom ONNX Runtime FusedConv operator that combines a Conv node and activation node (e.g. Relu) - - Depending on the model, and how many of these potential extended optimizations are prevented, there may be some performance loss if the NNAPI execution provider is not available (e.g. running on a non-Android platform), or does not claim the same set of nodes at runtime - - whether there is any performance loss, and/or whether there is significant performance loss, is model dependent - - please test to ascertain what works best for your scenarios - - you may want to generate one NNAPI aware ORT format model, and one generic ORT format model +### Limit ORT format model to ONNX operators -*Side note:* If losing the extended optimizations is not a concern, you can simply generate an ORT format model that can be used with NNAPI using the default ONNX Runtime package. Specify `--optimization_level basic` instead of `--use_nnapi` when running `tools\python\convert_onnx_models_to_ort.py`. This will mean all nodes that NNAPI could potentially will handle remain available, and at runtime the NNAPI execution provider can take them. +The NNAPI Execution Provider is only able to execute ONNX operators using NNAPI. When creating the ORT format model it is recommended to limit the optimization level to 'basic' so that custom internal ONNX Runtime operators are not added by the 'extended' optimizations. This will ensure that the maximum number of nodes can be executed using NNAPI. See the [graph optimization](ONNX_Runtime_Graph_Optimizations.md) documentation for details on the optimization levels. -#### Create the minimal build with NNAPI support -NOTE: A minimal build with full NNAPI support can only be for the Android platform. -See [these](https://github.com/microsoft/onnxruntime/blob/master/BUILD.md#Android-NNAPI-Execution-Provider) instructions for details on creating an Android build with NNAPI included. +To limit the optimization level when creating the ORT format models using `tools\python\convert_onnx_models_to_ort.py` as per the above [instructions](#1-Create-ORT-format-model-and-configuration-file-with-required-operators), add `--optimization_level basic` to the arguments. + - e.g. `python /tools/python/convert_onnx_models_to_ort.py --optimization_level basic /models` - - Follow the [above](#2-Create-the-minimal-build) instructions to create the minimal build, with the following changes: - - Add `--minimal_build extended` to enable the support for execution providers that compile kernels in the minimal build. - - Add `--use_nnapi` to include NNAPI in the build +### Create a minimal build for Android with NNAPI support + +For NNAPI to be used on Android with ONNX Runtime Mobile, the NNAPI Execution Provider must be included in the minimal build. + +First, read the general instructions for [creating an Android build with NNAPI included](https://github.com/microsoft/onnxruntime/blob/master/BUILD.md#Android-NNAPI-Execution-Provider). These provide details on setting up the components required to create an Android build of ONNX Runtime, such as the Android NDK. + +Once you have all the necessary components setup, follow the instructions to [create the minimal build](#2-Create-the-minimal-build), with the following changes: + - Replace `--minimal_build` with `--minimal_build extended` to enable support for execution providers that dynamically create kernels at runtime, which is needed by the NNAPI Execution Provider. + - Add `--use_nnapi` to include the NNAPI Execution Provider in the build + - Windows example: + `.\build.bat --config RelWithDebInfo --android --android_sdk_path D:\Android --android_ndk_path D:\Android\ndk\21.1.6352462\ --android_abi arm64-v8a --android_api 29 --cmake_generator Ninja --minimal_build extended --use_nnapi --disable_ml_ops --disable_exceptions --build_shared_lib --skip_tests --include_ops_by_config ` + - Linux example: + `./build.sh --config RelWithDebInfo --android --android_sdk_path /Android --android_ndk_path /Android/ndk/21.1.6352462/ --android_abi arm64-v8a --android_api 29 --minimal_build extended --use_nnapi --disable_ml_ops --disable_exceptions --build_shared_lib --skip_tests --include_ops_by_config ` ## Limitations @@ -173,11 +154,11 @@ A minimal build has the following limitations currently: - Model must be converted to ORT format - No support for runtime optimizations - Optimizations should be performed prior to conversion to ORT format + - Execution providers that statically register kernels (e.g. ONNX Runtime CPU Execution Provider) are supported by default - Limited support for runtime partitioning (assigning nodes in a model to specific execution providers) - - Execution providers that will be used at runtime MUST be enabled when creating the ORT format model - - Execution providers that statically register kernels are supported by default (e.g. ORT CPU Execution Provider) - - Execution providers that compile nodes are optionally supported, and nodes they create will be correctly partitioned - - currently this is limited to the NNAPI execution provider + - Execution providers that statically register kernels and will be used at runtime MUST be enabled when creating the ORT format model + - Execution providers that compile nodes are optionally supported, and nodes they create will be correctly partitioned at runtime + - currently this is limited to the NNAPI Execution Provider - No support for custom operators We do not currently offer backwards compatibility guarantees for ORT format models, as we will be expanding the capabilities in the short term and may need to update the internal format in an incompatible manner to accommodate these changes. You may need to regenerate the ORT format models to use with a future version of ONNX Runtime. Once the feature set stabilizes we will provide backwards compatibility guarantees. diff --git a/docs/images/mnist_optimization.png b/docs/images/mnist_optimization.png new file mode 100644 index 0000000000..ea7a00872a Binary files /dev/null and b/docs/images/mnist_optimization.png differ diff --git a/docs/images/mnist_optimization_with_nnapi.png b/docs/images/mnist_optimization_with_nnapi.png new file mode 100644 index 0000000000..fca7ad669a Binary files /dev/null and b/docs/images/mnist_optimization_with_nnapi.png differ diff --git a/docs/images/nnapi_aware_ort_format_model.png b/docs/images/nnapi_aware_ort_format_model.png new file mode 100644 index 0000000000..de4c071fba Binary files /dev/null and b/docs/images/nnapi_aware_ort_format_model.png differ diff --git a/tools/python/convert_onnx_models_to_ort.py b/tools/python/convert_onnx_models_to_ort.py index 84e05315fe..7dc3b95a0f 100644 --- a/tools/python/convert_onnx_models_to_ort.py +++ b/tools/python/convert_onnx_models_to_ort.py @@ -98,6 +98,8 @@ def _get_optimization_level(level): return ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED if level == 'all': # all optimizations, including NCHWc (which has hardware specific logic) + print('WARNING: Enabling layout optimizations is not recommended unless the ORT format model will be executed ' + 'on the same hardware used to create the model.') return ort.GraphOptimizationLevel.ORT_ENABLE_ALL raise ValueError('Invalid optimization level of ' + level)