* Deprecate Python global configuration functions [Part 1] (#5923) Enable options to be set via execution provider (EP)-specific options and log deprecation warning from current global configuration functions. * remove dnnl_dll_path from post build copy (#6142) * Model Fusion For Bart (#6105) Fusion fix for Bart models * Unify IExecutionProvider and IExecutionProviderFactory interfaces (#6108) * Remove Provider_IExecutionProvider and make the internal IExecutionProvider usable by shared providers * Change Provider_IExecutionProviderFactory to be the core version. * Enable running the mnist_training sample without cuda (#6085) Signed-off-by: George Nash <george.nash@intel.com> * nnapi add min max support (#6117) * Fix CUDA test hang: (#6138) - Make condition check in `CUDAAllocatorTest` to ensure CUDA device is present. * Fix TensorRT kernel conflict issue for subgraphs of control flow operators (#6115) * add static subgraph kernel index * change kernel naming to avoid conflicts * Add gradient registration for Abs. (#6139) * Partition initial optimizer state for Zero-1 (#6093) * Initial changes * Working changes * Working changes * Cleanup * fix windows CI * Review comments * review comments * Fix edge case in BFCArena where allocation failures could lead to an infinite loop. (#6145) #4656 * Revert "work around of the build break in mac (#6069)" (#6150) This reverts commit3cae28699b. * Fix clean_docker_image_cache.py detection of image pushes. (#6151) Fix clean_docker_image_cache.py detection of image pushes. They were being ignored because the expected HTTP status code was wrong. For pushes, it's 201 instead of 200. * MLAS: add NEON version of int8 depthwise convolution (#6152) * Using a map of of ops to stages as input of partition function. (#5940) * New partition algorithm running before AD * Convert cut_group_info into device map. Work in progress -- works for bert-tiny with pp=2 * Removing code for partition of bwd graphs * Remove old code * Adding some verification code * Handle Shared Initializer * Renaming rank with stage * Added first unit test * new test * redundant check * undo change in bert * Moved cut-based partition to testing utils file Co-authored-by: xzhu1900 Co-authored-by: wschin * New conversion function and tests * minor * remove test that is not needed2 * improve GetDeviceAssignment and PR comments * minor changes * PR comments * improving documentation and variable naming * add documentation * Variable naming and docs * more doc improvements * more doc improvements * missing static cast * Fix test file for windows * Fix test file for windows * Fix test file for windows * stage id is not the same as rank id * PR comments * PR comments * More comments * More comments * Minor fix to satisfy c++14 (#6162) * Deprecating Horovod and refactored Adasum computations (#5468) deprecated horovod submodule refactored adasum logic to be ort-native added tests for native kernel and e2e tests * Update TensorRT-ExecutionProvider.md (#6161) * Bugfix for topk cuda kernel (#6164) * fix the issue that std::numeric_limits cannot handle half type * adding a test Co-authored-by: Du Li <duli@OrtTrainingDev4.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> * Revert "Fuse MatMulIntegerToFloat only when scales are scalar (#6008)" (#6169) This reverts commitf2dcba7afe. * Remove ignored build warnings for pybind on Mac (#6165) * save_checkpoint, load_checkpoint and aggregate_checkpoints (#6136) * save_checkpoint and load_checkpoint implementations * checkpoint aggregation logic * unit tests for save_checkpoint, load_checkpoint and aggregate_checkpoints * Don't try to bind unused inputs in the Training frontend (#6166) * Update documentation for contributing a PR and add deprecation notices for PyOp and ORT server. (#6172) * aggregate model states only for the case when mixed precision was true (#6176) * [NNAPI EP] Enable per-channel quantization for QlinearConv (#6155) * Enable qlinearconv per-channel quantization * Fix the android CI test failure * Add Android Version Check for Per-Channel Quant * Address PR comments * Fix some minor issues * Add verification of per-channel zero points * Make the error tolerance configurable * Fix typo in BERT pretraining script (#6175) A misplaced `}` meant that the `'enable_adasum'` option was interpreted incorrectly, causing the test to fail. * Update get_docker_image.py to enable use without image cache container registry. (#6177) Update get_docker_image.py to enable use without image cache container registry. * Helper for compiling EP to generate deterministic unique ids for use in MetaDef names (#6156) * Create a helper for generating unique ids that can be used by an EP that creates compiled nodes and needs ids to be deterministic for a model when used in multiple sessions. Added to IExecutionProvider as this can potentially be used by all compiling EPs and is more robust than a simplistic counter (although EP implementer is free to choose either approach). * Restructure the helper so it can be called across the EP bridge. Add ability to call id generation helper from EP bridge - convert DNNL EP to use helper to validate Address issue where a new Model may be loaded into the same address as a previous one. - hash the bytes in the Graph instance (1728 bytes currently) to use as the key to the full hash for the model Add lock around id generation to ensure no issues if multiple sessions partitions graphs at exactly the same time. - Extremely unlikely but would be hard to debug and the locking cost is not an issue as it's only incurred during graph partitioning and not execution. * Backend APIs for checkpointing (#5803) * Add backend API GetOptimizerState and GetModelState * add GetPartitionInfoMap * Android coverage dashboard (#6163) * Write the report to a file. * Post code coverage to the Dashboard database. * Add usage details of unified MCR container image (#6182) Going forward, a single unifed docker image will be published in MCR. The hardware accelerator target choice will have to be made in the application using OpenVINO EP's runtime config options. * improve perf for softmax (#6128) * improve perf for both gathergrad and softmax * revert the change in gathergrad and will be done in another PR. * address comments from code review. * Tune fast Gelu to use exp(x) instead of tanh(x) on Rocm platform (#6174) * tune fast gelu to use exp(x) instead of tanh(x) on rocm * update to use expression 2/(1+exp(-2x))-1 for stability * Add Status.csv to EP Perf Tool (#6167) * merge master, keep postprocess status commit * download float16.py everytime * removing hardcoded values * Lochi/quantization tool for trt (#6103) * Initial implementation of generating calibration dynamic range table * Initialize validation support for Quantization * Initialize validation support for Quantization (cont.) * Improve validation support for Quantization * Improve validation support for Quantization * Rewrite/Refine for calibration and validation * Rewrite/Refine for calibration and validation (cont.) * Refine code * Refine code * Add data reader for BERT * Add flatbuffers to serialize calibration table * Refine code and add BERT evaluation * Refine the code * minor modification * Add preprocess/postprocess of vision team yolov3 and refine the code * Update annotation * Make bbox cooridates more accurate * Fix bug * Add support of batch processing * Batch processing for model zoo yolov3 * Add batch inference for evaluation * Refine the code * Add README * Add comments * Refine the code for PR * Remove batch support checking in data_reader and refine the code * Refine the code for PR * Refine the code for PR review Co-authored-by: Olivia Jain <oljain@microsoft.com> * Implement ScatterND for CUDA EP (#6184) * Condition fix in Resize operator (#6193) * Clean up checkpoint tests to use the new checkpoint functions (#6188) * add deprecation warning for old checkpoint functions * update all the distributed checkpoint tests to use new checkpoint functions * Implement comparing outputs that are sequence of maps of strings to floats (#6180) * Implement conversion from ortvalue to Itensor for string tensors and comparing sequence of maps of strings to floats * PR comments * Dockerfile to build onnxruntime with ROCm 4.0 * Add ability to skip GPU tests based on GPU adapter name (#6198) * Implement conversion from ortvalue to Itensor for string tensors and comparing sequence of maps of strings to floats * PR comments * Add ability to skip gpu tests according to adapter description * spacing * spacing * spacing * Openvino ep 2021.2 (#6196) * Enabling fasterrcnn variant and vehicle detector * changes for 2021_2 branch * yolov3_pytorch commit * fixed braces in basic_backend.cc * ci information added * faster rcnn variant and vehicle detector changes were made in 2021.1 and not in 2021.2 * some changes to support unit tests * disable some tests which are failing * fix myriad tests for vehicle detector * Did some cleanup *cleaned up comments *Disabled Add_Broadcast_0x1 and Add_Broadcast_1x0 tests on MYRIAD_FP16 backend due to a bug *cleaned up capability_2021_2.cc file *Removed extra conditions which were added for some validation in backend_utils Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * yolov3 pytorch workaround to ensure that the output names are matched * gemmoptest fixed on myriad * Fixed MYRIADX CPP Test Failures *Expand,GatherND,Range,Round op's are only supported in model *where op with float input data types are not supported and fixed *Scatter and ScatterElements op's with negative axis are fixed *Reshape op with 0 dim value are not supported and fixed *Disabled InstanceNorm_2 test on MYRIADX Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * make changes to yolov3 pytorch * Fixed python unit tests *Fixed failing python tests on vpu, GPU and CPU Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * Fixes POW op failures on GPU_FP16 Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * Clean up capability_2021_2.cc Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * Updated docx for MultiThreading option *Added extra info on setting the num_of_threads option using the API and it's actual usage Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * fixed slice and removed extra prints * Disabled failing python tests Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * Minor changes added in capabilty_2021_2 Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * made changes to slice to avoid failures * Disabling FP16 support for GPU_FP32 ->Inferencing an FP16 model on GPU_FP32 leads to accuracy mismatches. so, we would rather use GPU_FP16 to infer an FP16 model on GPU Device Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * Updated docx for Inferencing a FP16 Model Signed-off-by: MaajidKhan <n.maajidkhan@gmail.com> * fix for mask rcnn * Script for installing openvino from source * Updated with openvino 2021.2 online installation * code comment fixes fixed accuracy mismatch for div * Update OpenvinoEP-ExecutionProvider.md updated for 2021.2 branch * Update README.md updated dockerfile documentation * Update BUILD.md build.md update documentation * permissiong change of install_openvino.sh * made changes to align with microsoft onnxruntime changes * Updated with ov 2021.2.200 Co-authored-by: suryasidd <surya.siddharth.pemmaraju@intel.com> Co-authored-by: sfatimar <sahar.fatima@intel/com> Co-authored-by: MaajidKhan <n.maajidkhan@gmail.com> Co-authored-by: mohdansx <mohdx.ansari@intel.com> * Fix a memory leak in test_inference.cc (#6201) * Fix a memory leak in test_inference.cc * Use TArray in AMD element-wise kernels, rather than manually copying memory to device. * Remove most ROCm-specific element-wise code and reuse CUDA element-wise code. * Minor change to improve performance for operator Pad. (#5537) * small improvment for pad * Support double for operators Log, Reciprocal, Sum (CPU) (#6032) * Support double for operators Log, Reciprocal, Sum * remove tesdt erf_double * Support double for operators Where, LpNormalisation (#6034) * Support double for operators Relu, Tanh, Sigmoid (#6221) * Fix ImportError in build.py (#6231) There is a possible ImportError where build.py can import the wrong 'util' package if there are others present in `sys.path` already * Removed executor todo that looks dead. (#6234) * Remove MKLML/openblas/jemalloc build config (#6212) * Remove python 3.5 * Update the readme file * Upgrade build.py to assert for python 3.6+ Upgrade build.py to assert for python 3.6+ as python 3.5 cannot build anymore todays master. * Support MLFloat16 type in Pow opset-12 CUDA kernel (#6233) * MLAS: handle MlasGemm(M/N/K==0) cases (#6238) * Support double for operator TopK + fix one bug in TopK implementation for GPU for double (#6220) * Support double for operator TopK * add static classes for topk/double * fix cast issue in topk * Support double for operator Gemm + fix bug in gemm implementation for cuda, rocm when sizeof(type) != sizeof(float) (#6223) * Support double for operator Gemm * fix type size while copying data in gemm operator for GPU * fix type in gemm implementation for rocm * Support double for operator ReduceMean, ReduceLogSumExp (#6217) * Support double for operators ReduceMean, ReduceLogSumExp * Support double for operator ArgMin (#6222) * Support double for operator ArgMin * add test specifically for double * add new test on pai-excluded-tests.txt * Update BUILD.md * Update manylinux docker image to the latest (#6242) * Fix allocator issue for TensorRT IOBinding (#6240) * Fix issue: https://github.com/microsoft/onnxruntime/issues/6094 Root cause: we didn't expose the OrtMemoryInfo for TRT, so it will cause issue if user want use IObinding for Tensorrt. Short term fix, add the OrtMemoryInfo for TRT. Long term should unify the allocator for CUDA and TRT * Tune BiasGeluGradDx kernel in approximation mode to avoid tanh(...) on Rocm (#6239) * bias gelu grad use exp(...) instead * update cuda to rocm * missing semicolon * comment * remove dockerfile * missing factor of two * Refactor EP Perf Tool (#6202) * merge master, keep postprocess status commit * download float16.py everytime * using variables to reference eps * adding ACL EP to ep perf tool * accuracy with absolute tolerance configurable * add acl to dict + remove commented line * Documentation for distributed CI tests pipeline (#6140) * Remove a debug log in provider_test_utils.cc (#6200) * Add the Concat Slice Elimination transform, fix constant_folding transform (#5457) * Add concat slice transform + test * Cosmetic improvements in concat slice transform * Remove unrelated file, fix comment, fix constant folding bug * Add test onnx graph * fix windows build * Review comments * review comment Co-authored-by: Aishwarya <aibhanda@OrtTrainingDev4.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> * Add MakeStringLite which uses current locale, update some MakeString call sites to use it instead. (#6252) * Add MakeStringLite which uses current locale, update macros to use that to generate messages. * Convert calls to MakeStringLite(). * Liqun/speech model loop to scan (#6070) Provide a tool to convert Loop to Scan for Nuphar performance Fix Nuphar CI pipeline failures. Co-authored-by: liqun <liqun@OrtTrainingDev4.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> * model parallel refinement (#6244) * Megatron Transformation as a seperate step * remove useless header * clang formating * Re-Structure megatron transformer for subsquent changes * fix comments * Allow querying a GraphProto's doc_string as part of ModelMetadata (#6248) * Fix Linux/Mac error message on input type mismatch (#6256) * add bfloat16 to gathergrad type constrains (#6267) Co-authored-by: Cheng Tang <chenta@microsoft.com> * Fix VS 2017 build break (#6276) * Deprecate Python global configuration functions [Part 2] (#6171) Update Python API to allow more flexibility for setting providers and provider options. The providers argument (InferenceSession/TrainingSession constructors, InferenceSession.set_providers()) now also accepts a tuple of (name, options dict). Fix get_available_providers() API (and the corresponding function in the C API) to return the providers in default priority order. Now it can be used as a starting point for the providers argument and maintain the default priority order. Convert some usages of the deprecated global configuration functions to use EP-specific options instead. Update some EP-specific option parsing to fail on unknown options. Other clean up. * Add script to preprocess python documentation before publishing (#6129) * add script to preprocessing python documentation before publishing * rename past to past_key_values for GPT-2 (#6269) rename past to past_key_values for transformers 4.* * Rename MakeString and ParseString functions. (#6272) Rename MakeString to MakeStringWithClassicLocale, MakeStringLite to MakeString, *ParseString to *ParseStringWithClassicLocale. Add missing pass-through versions of MakeStringWithClassicLocale for string types. * Increase timeout for Linux GPU CUDA11 build. (#6280) * Add helper to compare model with different precision (#6270) * add parity_check_helper.py * add real example * remove lines * Fix Min/Max CPU kernels for float16 type (#6205) * fix data_ptr assertion error for past_sequence_length=0 in GPT-2 (#6284) fix io binding crash for past_sequence_length=0 * A list of changes in transformers tool (#6224) * longformer fp16 e2e * add fp16/fp32 parity check helper file * excludes nodes with subgraph in profiling * use onnxconverter_common to do fp32->fp16 * add version check for onnxconverter_common * remove helper file * add pkg installation on notebooks and script * Workaround for static_cast<double>(half) * Add workaround to remove ROCm-specific binary-elementwise files. * Update nuget build (#6297) 1. Update the ProtoSrc path. The old one is not used anymore. 2. Regenerate OnnxMl.cs 3. Delete some unused code in tools/ci_build/build.py 4. Avoid set intra_op_param.thread_pool_size in ModelTests in OpenMP build. 5. Fix a typo in the C API pipeline. * Enable ONNX backend test of SequenceProto input/output (#6043) * assert sequence tensor and remove skips * update testdata json * use ONNX 1.8 in cgmanifest.json * use previous commit to workaround * update ONNX commit ID in docker * skip test_maxpool_2d_dilations test for now * update function name * add --sequence_lengths option (#6285) * more dtype for Equal CUDA kernel (#6288) Co-authored-by: Vincent Wang <weicwang@microsoft.com> * Force reinstall onnx python package on Windows (#6309) * update transformers required package versions (#6315) * Remove abs in LpPool (#6303) * Support 1D input for Conv + Mul/Add fusion optimizer with test (#6295) * Support 1D input (N C H) for Conv + Mul/Add fusion optimizer with test cases and test models. * Add longformer to python package (#6314) * add longformer to python package * move test related script and data to a new folder * Avoid false sharing on thread pool data structures (#6298) Description: This change adds alignment and padding to avoid false sharing on fields in the thread pool. It also adds a new microbenchmark to profile thread-pool performance over short loops. Motivation and Context MobileNet on a 2*12-core system showed a performance gap between the ORT thread pool and OpenMP. One cause appeared to be false sharing on fields in the thread pool: ThreadPoolParallelSection::tasks_finished (which the main thread spins on waiting for workers to complete a loop), and the RunQueue::front_ and back_ fields (used respectively by the worker thread and the main thread). The additional micro-benchmark BM_ThreadPoolSimpleParallelFor tests performance of loops of different sizes at different thread counts. The results below are on a machine with 2*14-core processors (E5-2690 v4) running with 1, 14, 15, and 28 threads. For each test, the microbenchmark has N threads run a loop with N iterations; hence a perfect result is for the time taken to be constant as additional threads are added (although we will also see power management effects helping at very low thread counts). The loop durations (100000, 10000, 1000) correspond roughly to 200us, 20us, and 2us on this machine. Before change: BM_ThreadPoolSimpleParallelFor/1/1/100000/real_time 17153 us 17154 us 32 BM_ThreadPoolSimpleParallelFor/14/14/100000/real_time 22553 us 22553 us 30 BM_ThreadPoolSimpleParallelFor/15/15/100000/real_time 21521 us 21521 us 29 BM_ThreadPoolSimpleParallelFor/28/28/100000/real_time 24111 us 24111 us 24 BM_ThreadPoolSimpleParallelFor/1/1/10000/real_time 1719 us 1719 us 407 BM_ThreadPoolSimpleParallelFor/14/14/10000/real_time 3409 us 3409 us 200 BM_ThreadPoolSimpleParallelFor/15/15/10000/real_time 3541 us 3541 us 201 BM_ThreadPoolSimpleParallelFor/28/28/10000/real_time 4576 us 4576 us 151 BM_ThreadPoolSimpleParallelFor/1/1/1000/real_time 174 us 174 us 4017 BM_ThreadPoolSimpleParallelFor/14/14/1000/real_time 1586 us 1586 us 402 BM_ThreadPoolSimpleParallelFor/15/15/1000/real_time 1586 us 1586 us 397 BM_ThreadPoolSimpleParallelFor/28/28/1000/real_time 2864 us 2864 us 232 After change: BM_ThreadPoolSimpleParallelFor/1/1/100000/real_time 17160 us 17160 us 33 BM_ThreadPoolSimpleParallelFor/14/14/100000/real_time 20989 us 20989 us 31 BM_ThreadPoolSimpleParallelFor/15/15/100000/real_time 22286 us 22286 us 31 BM_ThreadPoolSimpleParallelFor/28/28/100000/real_time 24631 us 24631 us 25 BM_ThreadPoolSimpleParallelFor/1/1/10000/real_time 1718 us 1718 us 407 BM_ThreadPoolSimpleParallelFor/14/14/10000/real_time 2868 us 2868 us 242 BM_ThreadPoolSimpleParallelFor/15/15/10000/real_time 2907 us 2907 us 240 BM_ThreadPoolSimpleParallelFor/28/28/10000/real_time 3872 us 3872 us 186 BM_ThreadPoolSimpleParallelFor/1/1/1000/real_time 175 us 175 us 3938 BM_ThreadPoolSimpleParallelFor/14/14/1000/real_time 933 us 933 us 659 BM_ThreadPoolSimpleParallelFor/15/15/1000/real_time 912 us 912 us 591 BM_ThreadPoolSimpleParallelFor/28/28/1000/real_time 1976 us 1976 us 317 * fix opset imports for function body (#6287) * fix function opsets * add tests and update onnx * changes per review comments * add comments * plus updates * build fix * Remove false positive prefast warning from threadpool (#6324) * Java: add Semmle to Java publishing pipelines (#6326) Add Semmle to Java API pipeline Add security results publishing and add Java GPU. * Quantization support for split operator with its NHWC support (#6107) * Make split working for quantization. * NHWC transformer support for split operator * Refactor some according to Feedback. Will add test cases soon. * Fix build error on windows. * Add test case for split op on uint8_t support * Add nhwc_transformer_test for split uint8_t support * Some change according to PR feedbacks. * Liqun/enable pipeline parallel test (#6331) enable pipeline parallel test Co-authored-by: liqun <liqun@OrtTrainingDev4.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> * Use onnxruntime_USE_FULL_PROTOBUF=OFF for the cuda execution provider (#6340) This removes a special case of the cuda EP. * MLAS: add fallback implementation for quantized GEMM (#6335) Add a non-vectorized version of the kernel used for the quantized version of MlasGemm. * Delete float16.py (#6336) No longer needed. Also doesn't pass policheck. * Enable add + softmax fusion for Rocm platform (#6259) * add bias softmax; tests appear to pass * check fusion occurs for rocm as well * check for rocm provider compatible as well * build for cpu scenario as well * try again; broader cope * proper scope on kGpuExecutionProvider * been editing wrong file * remove commented #include lines * try again due to mac os ci error * try again * test fusion both cuda and rocm to avoid mac ci error * add external data support to tensor proto utils (#6257) * update unpack tensor utilities to support loading external data * more updates * fix test * fix nuphar build * minor build fix * add tests * fix Android CI * fix warning * fix DML build failure and some warnings * more updates * more updates * plus few updates * plus some refactoring * changes per review * plus some change * remove temp code * plus updates to safeint usage * build fix * fix for safeint * changed wording. (#6337) * Remove OpSchema dummy definition. Only needed for Function now, and we can just exclude the method in Function (#6321) * remove gemmlowp submodule (#6341) * [NNAPI] Add pow support (#6310) * Add support for running Android emulator from build.py on Windows. (#6317) * fix the pipeline failure (#6346) * Train BERT Using BFloat16 on A100 (#6090) * traing bert using bf16 * Adam support bf16 * bugfix * add fusedmatmul support * fix after merge from master. * bugfix * bugfix after merge from master * fast reduction for bf16. * resolve comments * fix win build * bugfix * change header file. Co-authored-by: Vincent Wang <weicwang@microsoft.com> * Fix DerefNullPtr issues raised by SDLNativeRules. (#6348) * update quantize to support basic optimization and e2e example for image classification (#6313) update the resnet50-v1 to standard one from onnx zoo. add an example for mobilenet run basic optimization before quantization fix a bug in Clip * Enable graph save for orttrainer (#6333) * Enable graph save for orttrainer * Fix CI * Update orttraining/orttraining/python/training/orttrainer_options.py * Update orttraining/orttraining/python/training/orttrainer_options.py * Update orttraining/orttraining/python/training/orttrainer_options.py * Update orttraining/orttraining/python/training/orttrainer_options.py * Update orttraining/orttraining/python/training/orttrainer_options.py Co-authored-by: Thiago Crepaldi <thiago.crepaldi@microsoft.com> * Add PREfast to python packaging pipeline (#6343) * Add PREfast to python packaging pipeline * fix longformer benchmark io_binding output_buffers (#6345) * fix longformer benchmark io_binding output_buffers * format * import benchmark_helper from parent directory. * Use readelf for minimal build binary size checks. (#6338) * Use readelf for minimal build binary size checks. The on-disk size grows in 4KB chunks which makes it hard to see how much growth an individual checkin causes. Only downside is that the sum of the sections is larger than the on-disk size (assumably things get packed smaller on disk and some of the section alignment constraints can be ignored) * Remove unused function * Java: Set C language warnings to W4 and adjust JNI code (#6347) Set /W3 for C language and fix up JNI warnings. * Pipeline Parallel Experimental Python API (#5815) * Add create session to WinML telemetry to track WinML Usage (#6356) * Fix one more SDL warning (#6359) * fix -Wdangling-gsl (#6357) * Add python example of TensorRT INT8 inference on ResNet model (#6255) * add trt int8 example on resnet model * Update e2e_tensorrt_resnet_example.py * remove keras dependency and update class names * move ImageNetDataReader and ImageClassificationEvaluator to tensorrt resnet example * simplify e2e_tensorrt_resnet_example.py * Update preprocessing.py * merge tensorrt_calibrate * Update calibrate.py * Update calibrate.py * generalize calibrate * Update calibrate.py * fix issues * fix formating * remove augment_all * This added telemetry isn't needed (#6363) * Wezuo/memory analysis (#5658) * merged alloc_plan * pass compilation * Start running, incorrect allocation memory info * add in comments * fix a bug of recording pattern too early. * debugging lifetime * fix lifetime * passed mnist * in process of visualization * Add code to generate chrome trace for allocations. * in process of collecting fragmentation * before rebuild * passed mnist * passed bert tiny * fix the inplace reuse * fix the exception of weight in pinned memory * add guards to ensure the tensor is in AllocPlan * add customized profiling * debugging * debugging * fix the reuse of differnt location type * add rank * add the rank * add fragmentation * add time_step_trace * Add summary for each execution step (total bytes, used/free bytes). * add top k * change type of top k parameter * remove prints * change heap to set{ * add the name pattern * add the useage for pattern * add partition * change to static class * add custom group * remove const * update memory_info * in process of adding it as runtime config * change the memory profiling to be an argument * add some comments * add checks to recored meomry_info in traaining session * set the "local rank setting" to correct argument. * addressing comments * format adjustment * formatting * remove alloc_interval * update memory_info.cc to skip session when there is no tensor for a particular memory type * fix memory_info multiple iteration seg-fault * consolidate mainz changes * fixed some minor errors * guard by ORT_MINIMAL_BUILD * add ORT_MEMORY_PROFILE flag * added compiler flag to turn on/off memory profiling related code * clean up the code regarding comments * add comments * revoke the onnx version * clean up the code to match master * clean up the code to match master * clean up the code to match master Co-authored-by: Jesse Benson <benson.jesse@gmail.com> Co-authored-by: Wei Zuo <wezuo@OrtTrainingDev3.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: wezuo <wezuo@az-eus-v100-32gb-5-worker-mgtbby.eastus.cloudapp.azure.com> Co-authored-by: wezuo <wezuo@az-eus-v100-32gb-5-worker-yclzsf.eastus.cloudapp.azure.com> * Support MLFloat16 in CumSum Cuda op for Opset 14 (#6355) * Add CumSum-14 for Cuda * fix convert_common version retrival (#6382) * Refine auto_pad based pad computation in ConvTranspose (#6305) * Fix SDL warning (#6390) * Add max_norm for gradient clipping. (#6289) * add max_norm as user option for gradient clipping * add adam and lamb test cases for clip norm * add frontend tests * Add the custom op project information (#6334) * Dont use default string marshalling in C# (#6219) * Fix Windows x86 compiler warnings in the optimizers project (#6377) * [Perf] Optimize Tile CPU and CUDA kernels for a corner case (#6376) * Unblock Android CI code coverage failure (#6393) * fix build on cuda11 (#6394) Co-authored-by: Vincent Wang <weicwang@microsoft.com> * Load the model path correctly (#6369) * Fix some compile warnings (#6316) * OpenVino docker file changes to bypass privileged mode Description: Builds and installs libusb without UDEV support, which is used for communicating with the VPU device. Motivation and Context This enables the resulting docker container to be run without '--privileged' and '--network host' options which may not be suitable in deployment environments. * Megatron checkpointing (#6293) * Add bart fairseq run script * Add frontend change to enable megatron * Initial changes for checkpointing * Megatron optim state loading, checkpoint aggregation, frontend distributed tests for H, D+H * Add load_checkpoint changes * Fix CI * Cleanup * Fix CI * review comments * review comments * review comments: * Fix generate_submodule_cgmanifest.py Windows issues. (#6404) * Continue memory planning when unknown shape tensor is encountered. (#6413) * Reintroduce experimental api changes and fix remote build break (#6385) Co-authored-by: Ori Levari <orlevari@microsoft.com> * Add support for custom ops to minimal build. (#6228) * Add support for custom ops to minimal build. Cost is only ~8KB so including in base minimal build. * enable pipeline to run quantization tests (#6416) * enable pipeline to run quantization tests setup test pipeline for quantization * Minor cmake change (#6431) * Liqun/liqun/enable pipeline parallel test2 (#6399) * enable data and pipeline parallism test Co-authored-by: liqun <liqun@OrtTrainingDev4.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> * Farewell TrainableDropout (#5793) * Deprecate TrainableDropout kernel. * Update bert_toy_postprocessed.onnx to opset 12. * Add more dropout tests. * Fix BiasDropout kernel. Co-authored-by: Ubuntu <OrtTrainingDev3@OrtTrainingDev3.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: Sherlock Huang <bahuang@OrtTrainingDev3.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: Sergii Dymchenko <sedymche@microsoft.com> * fix null dereference warning (#6437) * Expose graph ModelPath to TensorRT shared library (#6353) * Update graph_viewer.cc * Update tensorrt_execution_provider.cc * Update graph_viewer.h * Update tensorrt_execution_provider.cc * Update tensorrt_execution_provider.cc * Update provider_api.h * Update provider_bridge_ort.cc * Update provider_interfaces.h * Update provider_interfaces.h * expose GraphViewer ModelPath API to TRT shared lib * add modelpath to compile * update * add model_path to onnx tensorrt parser * use GenerateMetaDefId to generate unique TRT kernel name * use GenerateMetaDefId to generate unique TRT engine name * fix issue * Update tensorrt_execution_provider.cc * remove GetVecHash * Update tensorrt_execution_provider.h * convert wchar_t to char for tensorrt parser * update tensorrt parser to include latest changes * fix issues * Update tensorrt_execution_provider.cc * merge trt parser latest change * add PROVIDER_DISALLOW_ALL(Path) * add tool for generating test data for longformer (#6415) * only build experimental api in redist (#6465) Co-authored-by: Sheil Kumar <sheilk@microsoft.com> * Add an option to save the training graph after optimization (#6410) * expose optimized_model_filepath in SessionOptions as `debug.graph_save_paths.model_with_training_graph_after_optimization_path` in `ORTTrainerOptions` * Share allocator between CUDA EP & TRT EP. (#6332) * Share allocator between CUDA EP & TRT EP. limitation: 1. Does not cover the per-thread allocator created by CUDA EP, still need to figure out the way to remove it 2. Need to have more identifiers to make it able to share CPU allocator across all EPs * fix max norm clipping test in python packaging pipeline test (#6468) * fix python packaging pipeline * make clip norm test compatabile with both V100 and M60 GPUs * Initial version of CoreML EP (#6392) * Bug 31463811: Servicing: Redist (Nuget) conflicts with Microsoft.AI.MachineLearning starting 21H1+ (#6460) * update load library code to have the fullly qualified path * make it work for syswow32 * git Revert "make it work for syswow32" This reverts commit b9f594341b7cf07241b18d0c376af905edcabae3. Co-authored-by: Sheil Kumar <sheilk@microsoft.com> * dequantize 1st input of lstm back if it is quantized (#6444) * [java] Adds support for OrtEnvironment thread pools (#6406) * Updates for Gradle 7. * Adding support for OrtThreadingOptions into the Java API. * Fixing a typo in the JNI code. * Adding a test for the environment's thread pool. * Fix cuda test, add comment to failure. * Updating build.gradle * fix SDL native rule warning #6246 (#6461) * fix SDL rule (#6464) * use tickcount64 (#6447) Co-authored-by: Ori Levari <orlevari@microsoft.com> * Update pypi package metadata (#6354) * Update setup file data * add missing comma * remove python 3.5 * fix typo bracket * Delete nuget extra configs (#6477) * Op kernel type reduction infrastructure. (#6466) Add infrastructure to support type reduction in Op kernel implementations. Update Cast and IsInf CPU kernels to use it. * Fixing a leak in OnnxSequences with String keys or values. (#6473) * Increase the distributes tests pipeline timeout to 120 minutes (#6479) * [CoreML EP] Add CI for CoreML EP (macOS) and add coreml_flags for EP options (#6481) * Add macos coreml CI and coreml_flags * Move save debuggubg model to use environment var * Move pipeline off from macos CI template * Fix an issue building using unix make, add parallel to build script * Fixed build break for shared_lib and cmpile warning * Fix a compile warning * test * Revert the accidental push from another branch This reverts commit 472029ba25d50f9508474c9eeceb3454cead7877. * Add ability to track per operator types in reduced build config. (#6428) * Add ability to generate configuration that includes required types for individual operators, to allow build size reduction based on that. - Add python bindings for ORT format models - Add script to update bindings and help info - Add parsing of ORT format models - Add ability to enable type reduction to config generation - Update build.py to only allow operator/type reduction via config - simpler to require config to be generated first - can't mix a type aware (ORT format model only) and non-type aware config as that may result in insufficient types being enabled - Add script to create reduced build config - Update CIs * merge e2e with distributed pipeline (#6443) merge e2e with distributed pipeline * Fix test breaks in Windows ingestion pipeline (#6476) * fix various build breaks with Windows build * fix runtime errors loading libraries from system32 * add build_inbox check to winml_test_common * use raw string * cleanup * fix dll load Co-authored-by: Sheil Kumar <sheilk@microsoft.com> * Speed up the Mac CI runs (#6483) * expose learningmodelpixelrange property (#5877) * Fix of support api version bug for [de]quantize (#6492) * SDL fixes: add proper casts/format specifiers (#6446) * SDL annotation fixes (#6448) Co-authored-by: Ori Levari <orlevari@microsoft.com> * [OpenVINO-EP] Remove support for OpenVINO 2020.2 (#6493) * Removed OpenVINO 2020.2 support * Updated documentation and build.py * Removed unnecessary libraries from setup.py * Support pad operator in quantization and quantized nhwc transformer. Fix Pad operator bug. (#6325) Support pad operator in quantization tool. Support pad operator in quantized nhwc transformer. Fix pad() operator bug when pad input's inner(right) most axis value is zero for Edge and Reflect mode, it copied wrong value to the cells to be padded. Note the Constant mode will not trigger this bug, as Edge/Reflect need copy value from the already copied array while Constant mode only fill specified value. Add more test cases to cover pad() operator bug fixed here. Fix quantization tools uint8/int8 value overflow issue when quantize weights in python. * Improve work distribution for Expand operator, and sharded LoopCounter configuration (#6454) Description: This PR makes two changes identified while looking at a PGAN model. First, it uses ThreadPool::TryParallelFor for the main parallel loops in the Expand operator. This lets the thread pool decide on the granularity at which to distribute work (unlike TrySimpleParallelFor). Profiling showed high costs when running "simple" loops with 4M iterations each of which copied only 4 bytes. Second, it updates the sharded loop counter in the thread pool so that the number of shards is capped by the number of threads. This helps make the performance of any other high-contention "simple" loops more robust at low thread counts by letting each thread work on its own "home" shard for longer. Motivation and Context Profiling showed a PGAN model taking 2x+ longer with the non-OpenMP build. The root cause was that the OpenMP build uses simple static scheduling of loop iterations, while the non-OpenMP build uses dynamic scheduling. The combination of large numbers of tiny iterations is less significant with static scheduling --- although still desirable to avoid, given that each iteration incurs a std::function invocation. * Update document of transformer optimization (#6487) * nuphar test to avoid test data download to improve passing rate (#6467) nuphar test to avoid test data download to improve passing rate * Fuse cuda conv with activation (#6351) * optimize cuda conv by fused activation * remove needless print out * exclude test from cpu * handle status error from cudnn 8.x * add reference to base class * add hipify * [CoreML EP] Add support for some activations/Transpose, move some shared helpers from NNAPI to shared space (#6498) * Init change * Move some helper from nnapi ep to shared * Add transpose support * Fix trt ci build break * Refine transformers profiler output (#6502) * output nodes in the original order; grouped by node name * add document for profiler * Update to match new test setup. (#6496) * Update to match new test setup. * Add Gemm(7) manually for now. Will fix properly on Monday. It's used by mnist.ort as that is created by optimizing mnist.onnx to level 1 causing 2 nodes to be replaced by a Gemm and the op to be missing from the required list as that is created using the original onnx model. * Enable dense sequence optimized version of Pytorch exported BERT-L on AMD GPU (#6504) * Permit dense seq optimization on BERT-L pytorch export by enabling ReduceSumTraining, Equal, and NonZero on AMD * enable Equal tests * enable fast_matrix_reduction test case * Optimize GatherGrad for AMD GPU (#6381) * optimize gathergrad * address comments Co-authored-by: Weixing Zhang <wezhan@microsoft.com> * add explicit barriers for buffer overread and overrwrite (#6484) Co-authored-by: Ori Levari <orlevari@microsoft.com> * fix sdl bugs for uninitialized variables and returns (#6450) Co-authored-by: Ori Levari <orlevari@microsoft.com> * handle hr error conditions (#6449) Co-authored-by: Ori Levari <orlevari@microsoft.com> * Dnnl training (#6045) * Add ReluGrad and ConvGrad ops for the dnnl provider * the mnist sample is updated to add the --use_dnnl option that will cause the sample to use the dnnl execution provider for nodes that exist in dnnl provider. * Added the ability to find forward ops. Dnnl backward gradient ops require the forward primitive description and workspace from the forward operation. * Enable specifying the execution provider for Gradient Checker Tests * Prevent memory leak when running dnnl_provider in training mode Prevent creating a SubgraphPrimitivePool when the code is built with the ENABLE_TRAINING build flag. Instead create a SubgraphPrimitive directly. The SubgraphPrimitivePool was causing a pool of SubgraphPrimitives to be stashed in a map for reuse. Due to the way the Training Loop uses threads the pool of SubgraphPrimitives were not being reuse instead a new pool of SubgraphPrimitives being created each run. The old pool was not instantly freed. This behavior could be a language error when using thread_local memory. Signed-off-by: George Nash <george.nash@intel.com> * Added fixes to maxpoolgrad and memory leak. Maxpoolgrad will now pass all unit tests. With the conv and convgrad disabled for dnnl, mnist is able to train till 95% Signed-off-by: Chethan Palangotu Keshava <chethan.palangotu.keshava@intel.com> * Fixed misc issues when testing training code with dnnl provider * fix conv_grad dnnl tests with dilation to run dnnl execution provider * update mnist training sample to accept convolution type models convolution models require the input shape to be {1, 28, 28} instead of the flat {728} image that is used for the gemm models this will enable models that require the different shape by adding `--model_type conv` to the command line when running the mnist sample. (while testing a workaround was used see #4762) * Disable weight caching in dnnl conv operator when using training When training we can not use cached weights because the weight will be updated each run. This re-enables dnnl Conv and ConvGrad Ops. The weight caching was the source of the error from Conv when training. * Fix issues found when building grad ops on Linux * The dnnl_convgrad code was over using the scope operator causing a compilation problem. * The dnnl_maxpoolgrad code had a logic error that is was comparing with the source description when it should have been comparing with the destination despription. * Update BUILD.md so it shows DNNL for training * Updated the table of contents. Since the same providers are listed twice. Once for Infrance and again for Training an HTML anchor was added to distinguish the second header from the first for the TOC. * Fix build failure when not using --enable-training build option * reorganize the gradient operators so they are grouped together * Fix issues found when running onnx_backend_test_series.py * Pooling code only supports 2 outputs when built with --enable-training * Address code review feedback * class member variables end in underscore_ * use dst instead of dist to match pattern use elsewhere in DNNL code. * Remove workaround that was introduced to handle problems running convolution based training models. See issue #4762 Signed-off-by: George Nash <george.nash@intel.com> * Isolate training code and code cleanup * Do not build if dnnl_gpu_runtime if enable_training is set training code does not support dnnl_gpu_runtime yet. * Isolated Training code inside ifdefs so that they wont affect project if built without training enabled * Inadvertant changes in whitespace were removed to make code review simpler * Undid some code reordering that was not needed * comments added to closing #endif statments to simplify reading complex ifdefs * Modified the GetPrimitiveDesc functions to return shared_ptr instead of raw pointer. This matches what was done in Pool code and is safer memory code. Signed-off-by: George Nash <george.nash@intel.com> * Address code review issues - whitespace changes caused by running clang-format on the code - Several spelling errors fixed - Removed/changed some ifdefs to improve readability - other misc. changes in responce to code review. Signed-off-by: George Nash <george.nash@intel.com> * Code changes to address code review - Simplify iteration code using `auto` keyword - remove C style cast that was not needed - remove instance variable that was not needed [relugrad.h] - added the execution providers to `ComputeGradientErrorInternal()` and `ComputeTheoreticalJacobianTranspose()` instead of using a pointer to an instance varaible [gradient_checker.h/.cc] Signed-off-by: George Nash <george.nash@intel.com> * Combined the default gradient ops test and dnnl gradient ops test for ConvGrad and MaxPoolGrad into one function with the help of a helper function. This will reduce repeated code. Signed-off-by: Palangotu Keshava, Chethan's avatarChethan Palangotu Keshava <chethan.palangotu.keshava@intel.com> * Replaced the stack used by convgrad to vector so that the vector(used as stack) can be easily cleared everytime the graph is created. This will prevent memory leak from convolution kernels being pushed constantly onto the stack. Signed-off-by: chethan.palangotu.keshava@intel.com * Code clean up and formating updates - Removed empty else statment - updated indentation of code that was causing double curly brackets to look unususal - Changed check for NumDimensions to Size in Relu and ReluGrad error checking code. - isolated training code Signed-off-by: George Nash <george.nash@intel.com> * Restore inadvertantly removed ConvGrad tests When combining the DNNL and CPU version of the ConvGrad tests two test were inadvertantly excluded. This adds back the Conv3d and Conv3d with strides test cases. Signed-off-by: George Nash <george.nash@intel.com> * Add validation to ConvGrad This validates the dimensions of the ConvGrad match the passed in Convolution forward primitive description. The current code for DNNL ConvGrad makes the assumption that the ConvGrad nodes will be visited in the reverse order from the corresponding Conv nodes The added validation will return an error if this assumption is not true. Signed-off-by: George Nash <george.nash@intel.com> * Do not create new execution providers in provider_test_utils This removes the code that generated new execution providers in the OpTester::Run function. This was added because the std::move was leaving the `entry` value empty so subsequent calls would cause a segfault. Problem is this potentially changed the execution_provider because it would create the default provider dropping any custom arguments. When the now removed code was originally added the std::move was causing crashes when the GradientChecker unit tests were run. However, it is no longer causing problems even with the code removed. Signed-off-by: George Nash <george.nash@intel.com> * Change the forward conv stack to a forward conv map This changes how the forward conv kernel is mapped to the bwd ConvGrad kernel the problematic stack is no longer used. The convolution stack made the assumption that the corresponding ConvGrad operator would be visited in reverse order of the forward Conv operators. This was always problematic and was unlikely to work for inception models. Important changes: - The weight_name is added to the ConvGrad dnnl_node making it possible to use the weight_name as a lookup key to find the Conv forward Kernel - the `std::vector fwd_conv_stack_` has been replaced with a `std::map fwd_conv_kernel_map_` - Although it is not needed lock_guards were added when writing to and reading from the fwd_conv_kernel_map_ as well as the fwd_kernel_map_. These should always be accessed by a single thread when preparing the dnnl subgraphs so the guard should not be needed but its added just in case. - Updated the comments ConvGrad.h code to no longer mention the stack. The error check is not removed. It will be good to verify there are no errors as we continue to test against more models. Signed-off-by: George Nash <george.nash@intel.com> Co-authored-by: Chethan Palangotu Keshava <chethan.palangotu.keshava@intel.com> Co-authored-by: unknown <63478620+jeyblu@users.noreply.github.com> * Lochi/refactor yolov3 quantization (#6290) * Refactor the code and move data reader, preprocessing, evaluation to E2E_example_mode * Refactor the code. Move data reader, preprocessing, evaluation to model specific example under E2E_example_mode * refactor code * Move yolov3 example to specific folder and add additional pre/post processing * Print a warning message for using newer c_api header on old binary (#6507) * Fix issues with ArmNN build setup (#6495) * ArmNN build fixes * Update BUILD.md to document that the ACL paths must be specified to build ArmNN * Fix CUDA build error. We don't setup the link libraries correctly/consistently so improve that. * Fix Windows CI builds by updating test scripts to work with numpy 1.20. (#6518) * Update onnxruntime_test_python.py to work with numpy 1.20. Some aliases are deprecated in favor of the built-in python types. See https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations np.array with bytes for entries and dtype of np.void no longer automatically pads. Change a test to adjust for that. * Fix another test script * Fix ORTModule branch for orttraining-* pipelines * Update pytorch nightly version dependency Co-authored-by: Edward Chen <18449977+edgchen1@users.noreply.github.com> Co-authored-by: George Wu <jywu@microsoft.com> Co-authored-by: Cecilia Liu <ziyue.liu7@gmail.com> Co-authored-by: Ryan Hill <38674843+RyanUnderhill@users.noreply.github.com> Co-authored-by: George Nash <george.nash@intel.com> Co-authored-by: Guoyu Wang <62914304+gwang-msft@users.noreply.github.com> Co-authored-by: Yateng Hong <toothache9010@gmail.com> Co-authored-by: stevenlix <38092805+stevenlix@users.noreply.github.com> Co-authored-by: Derek Murray <Derek.Murray@microsoft.com> Co-authored-by: ashbhandare <ash.bhandare@gmail.com> Co-authored-by: Scott McKay <skottmckay@gmail.com> Co-authored-by: Changming Sun <chasun@microsoft.com> Co-authored-by: Tracy Sharpe <42477615+tracysh@users.noreply.github.com> Co-authored-by: Juliana Franco <jufranc@microsoft.com> Co-authored-by: Pranav Sharma <prs@microsoft.com> Co-authored-by: Tixxx <tix@microsoft.com> Co-authored-by: Jay Rodge <jayrodge@live.com> Co-authored-by: Du Li <duli1@microsoft.com> Co-authored-by: Du Li <duli@OrtTrainingDev4.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: Yufeng Li <liyufeng1987@gmail.com> Co-authored-by: baijumeswani <bmeswani@microsoft.com> Co-authored-by: Sergii Dymchenko <sedymche@microsoft.com> Co-authored-by: jingyanwangms <47403504+jingyanwangms@users.noreply.github.com> Co-authored-by: satyajandhyala <satya.k.jandhyala@gmail.com> Co-authored-by: S. Manohar Karlapalem <manohar.karlapalem@intel.com> Co-authored-by: Weixing Zhang <weixingzhang@users.noreply.github.com> Co-authored-by: Suffian Khan <sukha@microsoft.com> Co-authored-by: Olivia Jain <oljain@microsoft.com> Co-authored-by: Chi Lo <54722500+chilo-ms@users.noreply.github.com> Co-authored-by: Hariharan Seshadri <shariharan91@gmail.com> Co-authored-by: Ryan Lai <rylai@microsoft.com> Co-authored-by: Jesse Benson <jesseb@microsoft.com> Co-authored-by: sfatimar <64512376+sfatimar@users.noreply.github.com> Co-authored-by: suryasidd <surya.siddharth.pemmaraju@intel.com> Co-authored-by: sfatimar <sahar.fatima@intel/com> Co-authored-by: MaajidKhan <n.maajidkhan@gmail.com> Co-authored-by: mohdansx <mohdx.ansari@intel.com> Co-authored-by: Xavier Dupré <xadupre@users.noreply.github.com> Co-authored-by: Michael Goin <mgoin@vols.utk.edu> Co-authored-by: Michael Giba <michaelgiba@gmail.com> Co-authored-by: William Tambellini <wtambellini@sdl.com> Co-authored-by: Hector Li <hecli@microsoft.com> Co-authored-by: Aishwarya <aibhanda@OrtTrainingDev4.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: liqunfu <liqfu@microsoft.com> Co-authored-by: liqun <liqun@OrtTrainingDev4.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: pengwa <pengwa@microsoft.com> Co-authored-by: Tang, Cheng <souptc@gmail.com> Co-authored-by: Cheng Tang <chenta@microsoft.com> Co-authored-by: Tianlei Wu <tlwu@microsoft.com> Co-authored-by: Ye Wang <52801275+wangyems@users.noreply.github.com> Co-authored-by: Chun-Wei Chen <jacky82226@gmail.com> Co-authored-by: Vincent Wang <wangwchpku@outlook.com> Co-authored-by: Vincent Wang <weicwang@microsoft.com> Co-authored-by: Luyao Ren <375833274@qq.com> Co-authored-by: Zhang Lei <zhang.huanning@hotmail.com> Co-authored-by: Tim Harris <tiharr@microsoft.com> Co-authored-by: Ashwini Khade <askhade@microsoft.com> Co-authored-by: Dmitri Smirnov <yuslepukhin@users.noreply.github.com> Co-authored-by: Alberto Magni <49027342+alberto-magni@users.noreply.github.com> Co-authored-by: Wei-Sheng Chin <wschin@outlook.com> Co-authored-by: wezuo <49965641+wezuo@users.noreply.github.com> Co-authored-by: Jesse Benson <benson.jesse@gmail.com> Co-authored-by: Wei Zuo <wezuo@OrtTrainingDev3.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: wezuo <wezuo@az-eus-v100-32gb-5-worker-mgtbby.eastus.cloudapp.azure.com> Co-authored-by: wezuo <wezuo@az-eus-v100-32gb-5-worker-yclzsf.eastus.cloudapp.azure.com> Co-authored-by: Wenbing Li <10278425+wenbingl@users.noreply.github.com> Co-authored-by: Martin Man <supermt@gmail.com> Co-authored-by: M. Zeeshan Siddiqui <mzs@microsoft.com> Co-authored-by: Ori Levari <ori.levari@microsoft.com> Co-authored-by: Ori Levari <orlevari@microsoft.com> Co-authored-by: Ubuntu <OrtTrainingDev3@OrtTrainingDev3.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: Sherlock Huang <bahuang@OrtTrainingDev3.af05slrtruoetgaxwwjv5nsq5e.px.internal.cloudapp.net> Co-authored-by: Sheil Kumar <smk2007@gmail.com> Co-authored-by: Sheil Kumar <sheilk@microsoft.com> Co-authored-by: Ryota Tomioka <ryoto@microsoft.com> Co-authored-by: Adam Pocock <adam.pocock@oracle.com> Co-authored-by: Yulong Wang <f.s@qq.com> Co-authored-by: Faith Xu <faxu@microsoft.com> Co-authored-by: Xiang Zhang <xianz@microsoft.com> Co-authored-by: suryasidd <48925384+suryasidd@users.noreply.github.com> Co-authored-by: RandySheriffH <48490400+RandySheriffH@users.noreply.github.com> Co-authored-by: Weixing Zhang <wezhan@microsoft.com> Co-authored-by: Chethan Palangotu Keshava <chethan.palangotu.keshava@intel.com> Co-authored-by: unknown <63478620+jeyblu@users.noreply.github.com>
61 KiB
Building ONNX Runtime
Dockerfiles / Pre-built packages
Content
- Start: Baseline CPU
- Supported architectures and build environments
- Common Build Instructions
- Additional Build Instructions - complete list:
./build.sh (or .\build.bat) --help- Reduced Operator Kernel Build
- ONNX Runtime for Mobile Platforms
- ONNX Runtime Server (Linux)
- Execution Provider Shared Libraries
- Execution Providers
- Options
- Architectures
- Baseline CPU
- Traning Enabled Execution Providers
Inferencing
Start: Baseline CPU
Prerequisites
- Checkout the source tree:
git clone --recursive https://github.com/Microsoft/onnxruntime cd onnxruntime - Install cmake-3.13 or higher from https://cmake.org/download/.
Build Instructions
Windows
Open Developer Command Prompt for Visual Studio version you are going to use. This will properly setup the environment including paths to your compiler, linker, utilities and header files.
.\build.bat --config RelWithDebInfo --build_shared_lib --parallel
The default Windows CMake Generator is Visual Studio 2017, but you can also use the newer Visual Studio 2019 by passing --cmake_generator "Visual Studio 16 2019" to .\build.bat
Linux
./build.sh --config RelWithDebInfo --build_shared_lib --parallel
macOS
By default, ORT is configured to be built for a minimum target macOS version of 10.12. The shared library in the release Nuget(s) and the Python wheel may be installed on macOS versions of 10.12+.
If you would like to use Xcode to build the onnxruntime for x86_64 macOS, please add the --user_xcode argument in the command line
./build.sh --config RelWithDebInfo --build_shared_lib --parallel --use_xcode
While without this flag, the cmake build generator will be Unix makefile by default. Also, if you want to try cross compiling for Apple Silicon in an Intel-based MacOS machine, please add the argument --osx_arch arm64 with a cmake > 3.19, however the unit tests will be skipped due to the incompatible CPU instruction set.
Notes
- Please note that these instructions build the debug build, which may have performance tradeoffs
- To build the version from each release (which include Windows, Linux, and Mac variants), see these .yml files for reference: CPU, GPU
- The build script runs all unit tests by default (for native builds and skips tests by default for cross-compiled builds).
- If you need to install protobuf 3.6.1 from source code (cmake/external/protobuf), please note:
- CMake flag protobuf_BUILD_SHARED_LIBS must be turned OFF. After the installation, you should have the 'protoc' executable in your PATH. It is recommended to run
ldconfigto make sure protobuf libraries are found. - If you installed your protobuf in a non standard location it would be helpful to set the following env var:
export CMAKE_ARGS="-DONNX_CUSTOM_PROTOC_EXECUTABLE=full path to protoc"so the ONNX build can find it. Also runldconfig <protobuf lib folder path>so the linker can find protobuf libraries.
- CMake flag protobuf_BUILD_SHARED_LIBS must be turned OFF. After the installation, you should have the 'protoc' executable in your PATH. It is recommended to run
- If you'd like to install onnx from source code (cmake/external/onnx), use:
export ONNX_ML=1 python3 setup.py bdist_wheel pip3 install --upgrade dist/*.whl
Supported architectures and build environments
Architectures
| x86_32 | x86_64 | ARM32v7 | ARM64 | |
|---|---|---|---|---|
| Windows | YES | YES | YES | YES |
| Linux | YES | YES | YES | YES |
| macOS | NO | YES | NO | NO |
Environments
| OS | Supports CPU | Supports GPU | Notes |
|---|---|---|---|
| Windows 10 | YES | YES | VS2019 through the latest VS2015 are supported |
| Windows 10 Subsystem for Linux |
YES | NO | |
| Ubuntu 16.x | YES | YES | Also supported on ARM32v7 (experimental) |
| macOS | YES | NO |
GCC 4.x and below are not supported.
OS/Compiler Matrix:
| OS/Compiler | Supports VC | Supports GCC | Supports Clang |
|---|---|---|---|
| Windows 10 | YES | Not tested | Not tested |
| Linux | NO | YES(gcc>=4.8) | Not tested |
| macOS | NO | Not tested | YES (Minimum version required not ascertained) |
Common Build Instructions
| Description | Command | Additional details |
|---|---|---|
| Basic build | build.bat (Windows) ./build.sh (Linux) |
|
| Release build | --config Release | Release build. Other valid config values are RelWithDebInfo and Debug. |
| Use OpenMP | --use_openmp | OpenMP will parallelize some of the code for potential performance improvements. This is not recommended for running on single threads. |
| Build using parallel processing | --parallel | This is strongly recommended to speed up the build. |
| Build Shared Library | --build_shared_lib | |
| Enable Training support | --enable_training |
APIs and Language Bindings
| API | Command | Additional details |
|---|---|---|
| Python | --build_wheel | |
| C# and C packages | --build_nuget | Builds C# bindings and creates nuget package. Currently supported on Windows and Linux only. Implies --build_shared_lib Detailed instructions can be found below. |
| WindowsML | --use_winml --use_dml --build_shared_lib |
WindowsML depends on DirectML and the OnnxRuntime shared library |
| Java | --build_java | Creates an onnxruntime4j.jar in the build directory, implies --build_shared_libCompiling the Java API requires gradle v6.1+ to be installed in addition to the usual requirements. |
| Node.js | --build_nodejs | Build Node.js binding. Implies --build_shared_lib |
Reduced Operator Kernel Build
Reduced Operator Kernel builds allow you to customize the kernels in the build to provide smaller binary sizes - see instructions.
ONNX Runtime for Mobile Platforms
For builds compatible with mobile platforms, see more details in ONNX_Runtime_for_Mobile_Platforms.md. Android and iOS build instructions can be found below on this page - Android, iOS
Build ONNX Runtime Server on Linux
Read more about ONNX Runtime Server here.
Build instructions are here
Build Nuget packages
Currently only supported on Windows and Linux.
Prerequisites
- dotnet is required for building csharp bindings and creating managed nuget package. Follow the instructions here to download dotnet. Tested with versions 2.1 and 3.1.
- nuget.exe. Follow the instructions here to download nuget
- On Windows, downloading nuget is straightforward and simply following the instructions above should work.
- On Linux, nuget relies on Mono runtime and therefore this needs to be setup too. Above link has all the information to setup Mono and nuget. The instructions can directly be found here. In some cases it is required to run
sudo apt-get install mono-completeafter installing mono.
Build Instructions
Windows
.\build.bat --build_nuget
Linux
./build.sh --build_nuget
Nuget packages are created under <native_build_dir>\nuget-artifacts
Execution Provider Shared Libraries
The DNNL, TensorRT, and OpenVINO providers are built as shared libraries vs being statically linked into the main onnxruntime. This enables them to be loaded only when needed, and if the dependent libraries of the provider are not installed onnxruntime will still run fine, it just will not be able to use that provider. For non shared library providers, all dependencies of the provider must exist to load onnxruntime.
Built files
On Windows, shared provider libraries will be named 'onnxruntime_providers_*.dll' (for example onnxruntime_providers_openvino.dll). On Unix, they will be named 'libonnxruntime_providers_*.so' On Mac, they will be named 'libonnxruntime_providers_*.dylib'.
There is also a shared library that shared providers depend on called onnxruntime_providers_shared (with the same naming convension applied as above).
Note: It is not recommended to put these libraries in a system location or added to a library search path (like LD_LIBRARY_PATH on Unix). If multiple versions of onnxruntime are installed on the system this can make them find the wrong libraries and lead to undefined behavior.
Loading the shared providers
Shared provider libraries are loaded by the onnxruntime code (do not load or depend on them in your client code). The API for registering shared or non shared providers is identical, the difference is that shared ones will be loaded at runtime when the provider is added to the session options (through a call like OrtSessionOptionsAppendExecutionProvider_OpenVINO or SessionOptionsAppendExecutionProvider_OpenVINO in the C API). If a shared provider library cannot be loaded (if the file doesn't exist, or its dependencies don't exist or not in the path) then an error will be returned.
The onnxruntime code will look for the provider shared libraries in the same location as the onnxruntime shared library is (or the executable statically linked to the static library version).
Execution Providers
CUDA
Prerequisites
- Install CUDA and cuDNN
- ONNX Runtime is built and tested with CUDA 10.2 and cuDNN 8.0.3 using Visual Studio 2019 version 16.7. ONNX Runtime can also be built with CUDA versions from 10.1 up to 11.0, and cuDNN versions from 7.6 up to 8.0.
- The path to the CUDA installation must be provided via the CUDA_PATH environment variable, or the
--cuda_homeparameter - The path to the cuDNN installation (include the
cudafolder in the path) must be provided via the cuDNN_PATH environment variable, or--cudnn_homeparameter. The cuDNN path should containbin,includeandlibdirectories. - The path to the cuDNN bin directory must be added to the PATH environment variable so that cudnn64_8.dll is found.
Build Instructions
Windows
.\build.bat --use_cuda --cudnn_home <cudnn home path> --cuda_home <cuda home path>
Linux
./build.sh --use_cuda --cudnn_home <cudnn home path> --cuda_home <cuda home path>
A Dockerfile is available here.
Notes
-
Depending on compatibility between the CUDA, cuDNN, and Visual Studio 2017 versions you are using, you may need to explicitly install an earlier version of the MSVC toolset.
-
CUDA 10.0 is known to work with toolsets from 14.11 up to 14.16 (Visual Studio 2017 15.9), and should continue to work with future Visual Studio versions
-
CUDA 9.2 is known to work with the 14.11 MSVC toolset (Visual Studio 15.3 and 15.4)
- To install the 14.11 MSVC toolset, see this page.
- To use the 14.11 toolset with a later version of Visual Studio 2017 you have two options:
-
Setup the Visual Studio environment variables to point to the 14.11 toolset by running vcvarsall.bat, prior to running the build script. e.g. if you have VS2017 Enterprise, an x64 build would use the following command
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" amd64 -vcvars_ver=14.11For convenience, .\build.amd64.1411.bat will do this and can be used in the same way as .\build.bat. e.g..\build.amd64.1411.bat --use_cuda -
Alternatively, if you have CMake 3.13 or later you can specify the toolset version via the
--msvc_toolsetbuild script parameter. e.g..\build.bat --msvc_toolset 14.11
-
If you have multiple versions of CUDA installed on a Windows machine and are building with Visual Studio, CMake will use the build files for the highest version of CUDA it finds in the BuildCustomization folder. e.g. C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\VC\VCTargets\BuildCustomizations. If you want to build with an earlier version, you must temporarily remove the 'CUDA x.y.*' files for later versions from this directory.
TensorRT
See more information on the TensorRT Execution Provider here.
Prerequisites
- Install CUDA and cuDNN
- The TensorRT execution provider for ONNX Runtime is built and tested with CUDA 11.0 and cuDNN 8.0.
- The path to the CUDA installation must be provided via the CUDA_PATH environment variable, or the
--cuda_homeparameter. The CUDA path should containbin,includeandlibdirectories. - The path to the CUDA
bindirectory must be added to the PATH environment variable so thatnvccis found. - The path to the cuDNN installation (path to folder that contains libcudnn.so) must be provided via the cuDNN_PATH environment variable, or
--cudnn_homeparameter.
- Install TensorRT
- The TensorRT execution provider for ONNX Runtime is built on TensorRT 7.1 and is tested with TensorRT 7.1.3.4.
- The path to TensorRT installation must be provided via the
--tensorrt_homeparameter.
Build Instructions
Note that TensorRT is built as a shared provider library
Windows
.\build.bat --cudnn_home <path to cuDNN home> --cuda_home <path to CUDA home> --use_tensorrt --tensorrt_home <path to TensorRT home>
Linux
./build.sh --cudnn_home <path to cuDNN e.g. /usr/lib/x86_64-linux-gnu/> --cuda_home <path to folder for CUDA e.g. /usr/local/cuda> --use_tensorrt --tensorrt_home <path to TensorRT home>
Dockerfile instructions are available here
NVIDIA Jetson TX1/TX2/Nano/Xavier
These instructions are for JetPack SDK 4.4.
-
Clone the ONNX Runtime repo on the Jetson host
git clone --recursive https://github.com/microsoft/onnxruntime -
Specify the CUDA compiler, or add its location to the PATH.
Cmake can't automatically find the correct nvcc if it's not in the PATH.
export CUDACXX="/usr/local/cuda/bin/nvcc"or:
export PATH="/usr/local/cuda/bin:${PATH}" -
Install the ONNX Runtime build dependencies on the Jetpack 4.4 host:
sudo apt install -y --no-install-recommends \ build-essential software-properties-common libopenblas-dev \ libpython3.6-dev python3-pip python3-dev python3-setuptools python3-wheel -
Cmake is needed to build ONNX Runtime. Because the minimum required version is 3.13, it is necessary to build CMake from source. Download Unix/Linux sources from https://cmake.org/download/ and follow https://cmake.org/install/ to build from source. Version 3.17.5 and 3.18.4 have been tested on Jetson.
-
Build the ONNX Runtime Python wheel:
./build.sh --config Release --update --build --parallel --build_wheel \ --use_cuda --cuda_home /usr/local/cuda --cudnn_home /usr/lib/aarch64-linux-gnuNote: You may optionally build with experimental TensorRT support.
./build.sh --config Release --update --build --parallel --build_wheel \ --use_tensorrt --cuda_home /usr/local/cuda --cudnn_home /usr/lib/aarch64-linux-gnu \ --tensorrt_home /usr/lib/aarch64-linux-gnu
DNNL and MKLML
See more information on DNNL and MKL-ML here.
Build Instructions
The DNNL execution provider can be built for Intel CPU or GPU. To build for Intel GPU, install Intel SDK for OpenCL Applications. Install the latest GPU driver - Windows graphics driver, Linux graphics compute runtime and OpenCL driver.
Note that DNNL is built as a shared provider library
Windows
.\build.bat --use_dnnl
Linux
./build.sh --use_dnnl
To build for Intel GPU, replace dnnl_opencl_root with the path of the Intel SDK for OpenCL Applications.
Windows
.\build.bat --use_dnnl --dnnl_gpu_runtime ocl --dnnl_opencl_root "c:\program files (x86)\intelswtools\sw_dev_tools\opencl\sdk"
Linux
./build.sh --use_dnnl --dnnl_gpu_runtime ocl --dnnl_opencl_root "/opt/intel/sw_dev_tools/opencl-sdk"
OpenVINO
See more information on the OpenVINO Execution Provider here.
Prerequisites
-
Install the Intel® Distribution of OpenVINOTM Toolkit Release 2021.2 for the appropriate OS and target hardware :
Follow documentation for detailed instructions.
2021.2 is the recommended OpenVINO version. OpenVINO 2020.3 is minimal OpenVINO version requirement. The minimum ubuntu version to support 2021.2 is 18.04.
-
Configure the target hardware with specific follow on instructions:
- To configure Intel® Processor Graphics(GPU) please follow these instructions: Windows, Linux
- To configure Intel® MovidiusTM USB, please follow this getting started guide: Linux
- To configure Intel® Vision Accelerator Design based on 8 MovidiusTM MyriadX VPUs, please follow this configuration guide: Windows, Linux. Follow steps 3 and 4 to complete the configuration.
- To configure Intel® Vision Accelerator Design with an Intel® Arria® 10 FPGA, please follow this configuration guide: Linux
-
Initialize the OpenVINO environment by running the setupvars script as shown below:
- For Linux run:
$ source <openvino_install_directory>/bin/setupvars.sh- For Windows run:
C:\ <openvino_install_directory>\bin\setupvars.bat -
Extra configuration step for Intel® Vision Accelerator Design based on 8 MovidiusTM MyriadX VPUs:
- After setting the environment using setupvars script, follow these steps to change the default scheduler of VAD-M to Bypass:
- Edit the hddl_service.config file from $HDDL_INSTALL_DIR/config/hddl_service.config and change the field "bypass_device_number" to 8.
- Restart the hddl daemon for the changes to take effect.
- Note that if OpenVINO was installed with root permissions, this file has to be changed with the same permissions.
- After setting the environment using setupvars script, follow these steps to change the default scheduler of VAD-M to Bypass:
Build Instructions
Note that OpenVINO is built as a shared provider library
Windows
.\build.bat --config RelWithDebInfo --use_openvino <hardware_option>
Note: The default Windows CMake Generator is Visual Studio 2017, but you can also use the newer Visual Studio 2019 by passing --cmake_generator "Visual Studio 16 2019" to .\build.bat
Linux
./build.sh --config RelWithDebInfo --use_openvino <hardware_option>
--use_openvino: Builds the OpenVINO Execution Provider in ONNX Runtime.
<hardware_option>: Specifies the default hardware target for building OpenVINO Execution Provider. This can be overriden dynamically at runtime with another option (refer to OpenVINO-ExecutionProvider.md for more details on dynamic device selection). Below are the options for different Intel target devices.
| Hardware Option | Target Device |
|---|---|
CPU_FP32 |
Intel® CPUs |
GPU_FP32 |
Intel® Integrated Graphics |
GPU_FP16 |
Intel® Integrated Graphics with FP16 quantization of models |
MYRIAD_FP16 |
Intel® MovidiusTM USB sticks |
VAD-M_FP16 |
Intel® Vision Accelerator Design based on 8 MovidiusTM MyriadX VPUs |
VAD-F_FP32 |
Intel® Vision Accelerator Design with an Intel® Arria® 10 FPGA |
HETERO:<DEVICE_TYPE_1>,<DEVICE_TYPE_2>,<DEVICE_TYPE_3>... |
All Intel® silicons mentioned above |
MULTI:<DEVICE_TYPE_1>,<DEVICE_TYPE_2>,<DEVICE_TYPE_3>... |
All Intel® silicons mentioned above |
Specifying Hardware Target for HETERO or Multi-Device Build:
HETERO:<DEVICE_TYPE_1>,<DEVICE_TYPE_2>,<DEVICE_TYPE_3>... MULTI:<DEVICE_TYPE_1>,<DEVICE_TYPE_2>,<DEVICE_TYPE_3>... The <DEVICE_TYPE> can be any of these devices from this list ['CPU','GPU','MYRIAD','FPGA','HDDL']
A minimum of two DEVICE_TYPE'S should be specified for a valid HETERO or Multi-Device Build.
Example: HETERO:MYRIAD,CPU HETERO:HDDL,GPU,CPU MULTI:MYRIAD,GPU,CPU
For more information on OpenVINO Execution Provider's ONNX Layer support, Topology support, and Intel hardware enabled, please refer to the document OpenVINO-ExecutionProvider.md in $onnxruntime_root/docs/execution_providers
NUPHAR
See more information on the Nuphar Execution Provider here.
Prerequisites
- The Nuphar execution provider for ONNX Runtime is built and tested with LLVM 9.0.0. Because of TVM's requirement when building with LLVM, you need to build LLVM from source. To build the debug flavor of ONNX Runtime, you need the debug build of LLVM.
- Windows (Visual Studio 2017):
REM download llvm source code 9.0.0 and unzip to \llvm\source\path, then install to \llvm\install\path cd \llvm\source\path mkdir build cd build cmake .. -G "Visual Studio 15 2017 Win64" -DLLVM_TARGETS_TO_BUILD=X86 -DLLVM_ENABLE_DIA_SDK=OFF msbuild llvm.sln /maxcpucount /p:Configuration=Release /p:Platform=x64 cmake -DCMAKE_INSTALL_PREFIX=\llvm\install\path -DBUILD_TYPE=Release -P cmake_install.cmake
Note that following LLVM cmake patch is necessary to make the build work on Windows, Linux does not need to apply the patch. The patch is to fix the linking warning LNK4199 caused by this LLVM commit
diff --git "a/lib\\Support\\CMakeLists.txt" "b/lib\\Support\\CMakeLists.txt"
index 7dfa97c..6d99e71 100644
--- "a/lib\\Support\\CMakeLists.txt"
+++ "b/lib\\Support\\CMakeLists.txt"
@@ -38,12 +38,6 @@ elseif( CMAKE_HOST_UNIX )
endif()
endif( MSVC OR MINGW )
-# Delay load shell32.dll if possible to speed up process startup.
-set (delayload_flags)
-if (MSVC)
- set (delayload_flags delayimp -delayload:shell32.dll -delayload:ole32.dll)
-endif()
-
# Link Z3 if the user wants to build it.
if(LLVM_WITH_Z3)
set(Z3_LINK_FILES ${Z3_LIBRARIES})
@@ -187,7 +181,7 @@ add_llvm_library(LLVMSupport
${LLVM_MAIN_INCLUDE_DIR}/llvm/ADT
${LLVM_MAIN_INCLUDE_DIR}/llvm/Support
${Backtrace_INCLUDE_DIRS}
- LINK_LIBS ${system_libs} ${delayload_flags} ${Z3_LINK_FILES}
+ LINK_LIBS ${system_libs} ${Z3_LINK_FILES}
)
set_property(TARGET LLVMSupport PROPERTY LLVM_SYSTEM_LIBS "${system_libs}")
- Linux Download llvm source code 9.0.0 and unzip to /llvm/source/path, then install to /llvm/install/path
cd /llvm/source/path
mkdir build
cd build
cmake .. -DLLVM_TARGETS_TO_BUILD=X86 -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)
cmake -DCMAKE_INSTALL_PREFIX=/llvm/install/path -DBUILD_TYPE=Release -P cmake_install.cmake
Build Instructions
Windows
.\build.bat --llvm_path=\llvm\install\path\lib\cmake\llvm --use_mklml --use_nuphar --build_shared_lib --build_csharp --enable_pybind --config=Release
- These instructions build the release flavor. The Debug build of LLVM would be needed to build with the Debug flavor of ONNX Runtime.
Linux:
./build.sh --llvm_path=/llvm/install/path/lib/cmake/llvm --use_mklml --use_nuphar --build_shared_lib --build_csharp --enable_pybind --config=Release
Dockerfile instructions are available here.
DirectML
See more information on the DirectML execution provider here.
Windows
.\build.bat --use_dml
Notes
The DirectML execution provider supports building for both x64 and x86 architectures. DirectML is only supported on Windows.
ARM Compute Library
See more information on the ACL Execution Provider here.
Prerequisites
- Supported backend: i.MX8QM Armv8 CPUs
- Supported BSP: i.MX8QM BSP
- Install i.MX8QM BSP:
source fsl-imx-xwayland-glibc-x86_64-fsl-image-qt5-aarch64-toolchain-4*.sh
- Install i.MX8QM BSP:
- Set up the build environment
source /opt/fsl-imx-xwayland/4.*/environment-setup-aarch64-poky-linux
alias cmake="/usr/bin/cmake -DCMAKE_TOOLCHAIN_FILE=$OECORE_NATIVE_SYSROOT/usr/share/cmake/OEToolchainConfig.cmake"
- See Build ARM below for information on building for ARM devices
Build Instructions
- Configure ONNX Runtime with ACL support:
cmake ../onnxruntime-arm-upstream/cmake -DONNX_CUSTOM_PROTOC_EXECUTABLE=/usr/bin/protoc -Donnxruntime_RUN_ONNX_TESTS=OFF -Donnxruntime_GENERATE_TEST_REPORTS=ON -Donnxruntime_DEV_MODE=ON -DPYTHON_EXECUTABLE=/usr/bin/python3 -Donnxruntime_USE_CUDA=OFF -Donnxruntime_USE_NSYNC=OFF -Donnxruntime_CUDNN_HOME= -Donnxruntime_USE_JEMALLOC=OFF -Donnxruntime_ENABLE_PYTHON=OFF -Donnxruntime_BUILD_CSHARP=OFF -Donnxruntime_BUILD_SHARED_LIB=ON -Donnxruntime_USE_EIGEN_FOR_BLAS=ON -Donnxruntime_USE_OPENBLAS=OFF -Donnxruntime_USE_ACL=ON -Donnxruntime_USE_DNNL=OFF -Donnxruntime_USE_MKLML=OFF -Donnxruntime_USE_OPENMP=ON -Donnxruntime_USE_TVM=OFF -Donnxruntime_USE_LLVM=OFF -Donnxruntime_ENABLE_MICROSOFT_INTERNAL=OFF -Donnxruntime_USE_BRAINSLICE=OFF -Donnxruntime_USE_NUPHAR=OFF -Donnxruntime_USE_EIGEN_THREADPOOL=OFF -Donnxruntime_BUILD_UNIT_TESTS=ON -DCMAKE_BUILD_TYPE=RelWithDebInfo
The -Donnxruntime_USE_ACL=ON option will use, by default, the 19.05 version of the Arm Compute Library. To set the right version you can use:
-Donnxruntime_USE_ACL_1902=ON, -Donnxruntime_USE_ACL_1905=ON, -Donnxruntime_USE_ACL_1908=ON or -Donnxruntime_USE_ACL_2002=ON;
To use a library outside the normal environment you can set a custom path by using -Donnxruntime_ACL_HOME and -Donnxruntime_ACL_LIBS tags that defines the path to the ComputeLibrary directory and the build directory respectively.
-Donnxruntime_ACL_HOME=/path/to/ComputeLibrary, -Donnxruntime_ACL_LIBS=/path/to/build
- Build ONNX Runtime library, test and performance application:
make -j 6
- Deploy ONNX runtime on the i.MX 8QM board
libonnxruntime.so.0.5.0
onnxruntime_perf_test
onnxruntime_test_all
Native Build Instructions (validated on Jetson Nano and Jetson Xavier)
- Build ACL Library (skip if already built)
cd ~
git clone -b v20.02 https://github.com/Arm-software/ComputeLibrary.git
cd ComputeLibrary
sudo apt-get install -y scons g++-arm-linux-gnueabihf
scons -j8 arch=arm64-v8a Werror=1 debug=0 asserts=0 neon=1 opencl=1 examples=1 build=native
-
Cmake is needed to build ONNX Runtime. Because the minimum required version is 3.13, it is necessary to build CMake from source. Download Unix/Linux sources from https://cmake.org/download/ and follow https://cmake.org/install/ to build from source. Version 3.17.5 and 3.18.4 have been tested on Jetson.
-
Build onnxruntime with --use_acl flag with one of the supported ACL version flags. (ACL_1902 | ACL_1905 | ACL_1908 | ACL_2002)
./build.sh --config RelWithDebInfo --use_acl ACL_2002 --update --build --build_wheel --parallel --acl_home ~/ComputeLibrary --acl_libs ~/ComputeLibrary/build
ArmNN
See more information on the ArmNN Execution Provider here.
Prerequisites
- Supported backend: i.MX8QM Armv8 CPUs
- Supported BSP: i.MX8QM BSP
- Install i.MX8QM BSP:
source fsl-imx-xwayland-glibc-x86_64-fsl-image-qt5-aarch64-toolchain-4*.sh
- Install i.MX8QM BSP:
- Set up the build environment
source /opt/fsl-imx-xwayland/4.*/environment-setup-aarch64-poky-linux
alias cmake="/usr/bin/cmake -DCMAKE_TOOLCHAIN_FILE=$OECORE_NATIVE_SYSROOT/usr/share/cmake/OEToolchainConfig.cmake"
- See Build ARM below for information on building for ARM devices
Build Instructions
./build.sh --use_armnn
The Relu operator is set by default to use the CPU execution provider for better performance. To use the ArmNN implementation build with --armnn_relu flag
./build.sh --use_armnn --armnn_relu
The Batch Normalization operator is set by default to use the CPU execution provider. To use the ArmNN implementation build with --armnn_bn flag
./build.sh --use_armnn --armnn_bn
To use a library outside the normal environment you can set a custom path by providing the --armnn_home and --armnn_libs parameters to define the path to the ArmNN home directory and build directory respectively. The ARM Compute Library home directory and build directory must also be available, and can be specified if needed using --acl_home and --acl_libs respectively.
./build.sh --use_armnn --armnn_home /path/to/armnn --armnn_libs /path/to/armnn/build --acl_home /path/to/ComputeLibrary --acl_libs /path/to/acl/build
RKNPU
See more information on the RKNPU Execution Provider here.
Prerequisites
- Supported platform: RK1808 Linux
- See Build ARM below for information on building for ARM devices
- Use gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu instead of gcc-linaro-6.3.1-2017.05-x86_64_arm-linux-gnueabihf, and modify CMAKE_CXX_COMPILER & CMAKE_C_COMPILER in tool.cmake:
set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++) set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
Build Instructions
Linux
-
Download rknpu_ddk to any directory.
-
Build ONNX Runtime library and test:
./build.sh --arm --use_rknpu --parallel --build_shared_lib --build_dir build_arm --config MinSizeRel --cmake_extra_defines RKNPU_DDK_PATH=<Path To rknpu_ddk> CMAKE_TOOLCHAIN_FILE=<Path To tool.cmake> ONNX_CUSTOM_PROTOC_EXECUTABLE=<Path To protoc> -
Deploy ONNX runtime and librknpu_ddk.so on the RK1808 board:
libonnxruntime.so.1.2.0 onnxruntime_test_all rknpu_ddk/lib64/librknpu_ddk.so
Vitis-AI
See more information on the Xilinx Vitis-AI execution provider here.
For instructions to setup the hardware environment: Hardware setup
Linux
./build.sh --use_vitisai
Notes
The Vitis-AI execution provider is only supported on Linux.
Options
OpenMP
Build Instructions
Windows
.\build.bat --use_openmp
Linux/macOS
./build.sh --use_openmp
OpenBLAS
Prerequisites
- OpenBLAS
- Windows: See build instructions here
- Linux: Install the libopenblas-dev package
sudo apt-get install libopenblas-dev
Build Instructions
Windows
.\build.bat --use_openblas
Linux
./build.sh --use_openblas
DebugNodeInputsOutputs
OnnxRuntime supports build options for enabling debugging of intermediate tensor shapes and data.
Build Instructions
Set onnxruntime_DEBUG_NODE_INPUTS_OUTPUT to build with this enabled.
Linux
./build.sh --cmake_extra_defines onnxruntime_DEBUG_NODE_INPUTS_OUTPUTS=1
Windows
.\build.bat --cmake_extra_defines onnxruntime_DEBUG_NODE_INPUTS_OUTPUTS=1
Configuration
The debug dump behavior can be controlled with several environment variables. See onnxruntime/core/framework/debug_node_inputs_outputs_utils.h for details.
Examples
To specify that node output data should be dumped (to stdout by default), set this environment variable:
ORT_DEBUG_NODE_IO_DUMP_OUTPUT_DATA=1
To specify that node output data should be dumped to files for nodes with name "Foo" or "Bar", set these environment variables:
ORT_DEBUG_NODE_IO_DUMP_OUTPUT_DATA=1
ORT_DEBUG_NODE_IO_NAME_FILTER="Foo;Bar"
ORT_DEBUG_NODE_IO_DUMP_DATA_TO_FILES=1
Architectures
64-bit x86 (also known as x86_64 or AMD64)
This is the default.
32-bit x86
Build Instructions
Windows
- add
--x86argument when launching.\build.bat
Linux
(Not officially supported)
ARM
There are a few options for building for ARM.
- Cross compiling for ARM with simulation (Linux/Windows) - Recommended; Easy, slow
- Cross compiling on Linux - Difficult, fast
- Native compiling on Linux ARM device - Easy, slower
- Cross compiling on Windows
Cross compiling for ARM with simulation (Linux/Windows)
EASY, SLOW, RECOMMENDED
This method rely on qemu user mode emulation. It allows you to compile using a desktop or cloud VM through instruction level simulation. You'll run the build on x86 CPU and translate every ARM instruction to x86. This is much faster than compiling natively on a low-end ARM device and avoids out-of-memory issues that may be encountered. The resulting ONNX Runtime Python wheel (.whl) file is then deployed to an ARM device where it can be invoked in Python 3 scripts.
Here is an example for Raspberrypi3 and Raspbian. Note: this does not work for Raspberrypi 1 or Zero, and if your operating system is different from what the dockerfile uses, it also may not work.
The build process can take hours.
Cross compiling on Linux
Difficult, fast
This option is very fast and allows the package to be built in minutes, but is challenging to setup. If you have a large code base (e.g. you are adding a new execution provider to onnxruntime), this may be the only feasible method.
1. Get the corresponding toolchain.
TLDR; Go to https://www.linaro.org/downloads/, get "64-bit Armv8 Cortex-A, little-endian" and "Linux Targeted", not "Bare-Metal Targeted". Extract it to your build machine and add the bin folder to your $PATH env. Then skip this part.
You can use GCC or Clang. Both work, but instructions here are based on GCC.
In GCC terms:
- "build" describes the type of system on which GCC is being configured and compiled
- "host" describes the type of system on which GCC runs. "target" to describe the type of system for which GCC produce code When not cross compiling, usually "build" = "host" = "target". When you do cross compile, usually "build" = "host" != "target". For example, you may build GCC on x86_64, then run GCC on x86_64, then generate binaries that target aarch64. In this case,"build" = "host" = x86_64 Linux, target is aarch64 Linux.
You can either build GCC from source code by yourself, or get a prebuilt one from a vendor like Ubuntu, linaro. Choosing the same compiler version as your target operating system is best. If ths is not possible, choose the latest stable one and statically link to the GCC libs.
When you get the compiler, run aarch64-linux-gnu-gcc -v This should produce an output like below:
Using built-in specs.
COLLECT_GCC=/usr/bin/aarch64-linux-gnu-gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/aarch64-linux-gnu/9/lto-wrapper
Target: aarch64-linux-gnu
Configured with: ../gcc-9.2.1-20190827/configure --bindir=/usr/bin --build=x86_64-redhat-linux-gnu --datadir=/usr/share --disable-decimal-float --disable-dependency-tracking --disable-gold --disable-libgcj --disable-libgomp --disable-libmpx --disable-libquadmath --disable-libssp --disable-libunwind-exceptions --disable-shared --disable-silent-rules --disable-sjlj-exceptions --disable-threads --with-ld=/usr/bin/aarch64-linux-gnu-ld --enable-__cxa_atexit --enable-checking=release --enable-gnu-unique-object --enable-initfini-array --enable-languages=c,c++ --enable-linker-build-id --enable-lto --enable-nls --enable-obsolete --enable-plugin --enable-targets=all --exec-prefix=/usr --host=x86_64-redhat-linux-gnu --includedir=/usr/include --infodir=/usr/share/info --libexecdir=/usr/libexec --localstatedir=/var --mandir=/usr/share/man --prefix=/usr --program-prefix=aarch64-linux-gnu- --sbindir=/usr/sbin --sharedstatedir=/var/lib --sysconfdir=/etc --target=aarch64-linux-gnu --with-bugurl=http://bugzilla.redhat.com/bugzilla/ --with-gcc-major-version-only --with-isl --with-newlib --with-plugin-ld=/usr/bin/aarch64-linux-gnu-ld --with-sysroot=/usr/aarch64-linux-gnu/sys-root --with-system-libunwind --with-system-zlib --without-headers --enable-gnu-indirect-function --with-linker-hash-style=gnu
Thread model: single
gcc version 9.2.1 20190827 (Red Hat Cross 9.2.1-3) (GCC)
Check the value of --build, --host, --target, and if it has special args like --with-arch=armv8-a, --with-arch=armv6, --with-tune=arm1176jz-s, --with-fpu=vfp, --with-float=hard.
You must also know what kind of flags your target hardware need, which can differ greatly. For example, if you just get the normal ARMv7 compiler and use it for Raspberry Pi V1 directly, it won't work because Raspberry Pi only has ARMv6. Generally every hardware vendor will provide a toolchain; check how that one was built.
A target env is identifed by:
- Arch: x86_32, x86_64, armv6,armv7,arvm7l,aarch64,...
- OS: bare-metal or linux.
- Libc: gnu libc/ulibc/musl/...
- ABI: ARM has mutilple ABIs like eabi, eabihf...
You can get all these information from the previous output, please be sure they are all correct.
2. Get a pre-compiled protoc:
Get this from https://github.com/protocolbuffers/protobuf/releases/download/v3.11.2/protoc-3.11.2-linux-x86_64.zip and unzip after downloading. The version must match the one onnxruntime is using. Currently we are using 3.11.2.
3. (Optional) Setup sysroot to enable python extension. Skip if not using Python.
Dump the root file system of the target operating system to your build machine. We'll call that folder "sysroot" and use it for build onnxruntime python extension. Before doing that, you should install python3 dev package(which contains the C header files) and numpy python package on the target machine first.
Below are some examples.
If the target OS is raspbian-buster, please download the RAW image from their website then run:
$ fdisk -l 2020-02-13-raspbian-buster.img
Disk 2020-02-13-raspbian-buster.img: 3.54 GiB, 3787456512 bytes, 7397376 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: dos Disk identifier: 0xea7d04d6
| Device | Boot | Start | End | Sectors | Size | Id | Type |
|---|---|---|---|---|---|---|---|
| 2020-02-13-raspbian-buster.img1 | 8192 | 532479 | 524288 | 256M | c | W95 FAT32 (LBA) | |
| 2020-02-13-raspbian-buster.img2 | 532480 | 7397375 | 6864896 | 3.3G | 83 | Linux |
You'll find the the root partition starts at the 532480 sector, which is 532480 * 512=272629760 bytes from the beginning.
Then run:
$ mkdir /mnt/pi
$ mount -r -o loop,offset=272629760 2020-02-13-raspbian-buster.img /mnt/pi
You'll see all raspbian files at /mnt/pi. However you can't use it yet. Because some of the symlinks are broken, you must fix them first. In /mnt/pi, run
$ find . -type l -exec realpath {} \; |grep 'No such file'
It will show which are broken. Then you can fix them by running:
$ mkdir /mnt/pi2
$ cd /mnt/pi2
$ sudo tar -C /mnt/pi -cf - . | sudo tar --transform 'flags=s;s,^/,/mnt/pi2/,' -xf -
Then /mnt/pi2 is the sysroot folder you'll use in the next step.
If the target OS is Ubuntu, you can get an image from https://cloud-images.ubuntu.com/. But that image is in qcow2 format. Please convert it before run fdisk and mount.
qemu-img convert -p -O raw ubuntu-18.04-server-cloudimg-arm64.img ubuntu.raw
The remaining part is similar to raspbian.
If the target OS is manylinux2014, you can get it by: Install qemu-user-static from apt or dnf. Then run the docker Ubuntu:
docker run -v /usr/bin/qemu-aarch64-static:/usr/bin/qemu-aarch64-static -it --rm quay.io/pypa/manylinux2014_aarch64 /bin/bash
The "-v /usr/bin/qemu-aarch64-static:/usr/bin/qemu-aarch64-static" arg is not needed on Fedora.
Then, inside the docker, run
cd /opt/python
./cp35-cp35m/bin/python -m pip install numpy==1.16.6
./cp36-cp36m/bin/python -m pip install numpy==1.16.6
./cp37-cp37m/bin/python -m pip install numpy==1.16.6
./cp38-cp38/bin/python -m pip install numpy==1.16.6
These commands will take a few hours because numpy doesn't have a prebuilt package yet. When completed, open a second window and run
docker ps
From the output:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5a796e98db05 quay.io/pypa/manylinux2014_aarch64 "/bin/bash" 3 minutes ago Up 3 minutes affectionate_cannon
You'll see the docker instance id is: 5a796e98db05. Use the following command to export the root filesystem as the sysroot for future use.
docker export 5a796e98db05 -o manylinux2014_aarch64.tar
4. Generate CMake toolchain file
Save the following content as tool.cmake
SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_SYSTEM_VERSION 1)
SET(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
SET(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
SET(CMAKE_FIND_ROOT_PATH /mnt/pi)
If you don't have a sysroot, you can delete the last line.
5. Run CMake and make
Append -DONNX_CUSTOM_PROTOC_EXECUTABLE=/path/to/protoc -DCMAKE_TOOLCHAIN_FILE=path/to/tool.cmake to your cmake args, run cmake and make to build it. If you want to build Python package as well, you can use cmake args like:
-Donnxruntime_GCC_STATIC_CPP_RUNTIME=ON -DCMAKE_BUILD_TYPE=Release -Dprotobuf_WITH_ZLIB=OFF -DCMAKE_TOOLCHAIN_FILE=path/to/tool.cmake -Donnxruntime_ENABLE_PYTHON=ON -DPYTHON_EXECUTABLE=/mnt/pi/usr/bin/python3 -Donnxruntime_BUILD_SHARED_LIB=OFF -Donnxruntime_DEV_MODE=OFF -DONNX_CUSTOM_PROTOC_EXECUTABLE=/path/to/protoc "-DPYTHON_INCLUDE_DIR=/mnt/pi/usr/include;/mnt/pi/usr/include/python3.7m" -DNUMPY_INCLUDE_DIR=/mnt/pi/folder/to/numpy/headers
After running cmake, run
$ make
6. (Optional) Build Python package
Copy the setup.py file from the source folder to the build folder and run
python3 setup.py bdist_wheel -p linux_aarch64
If targeting manylinux, unfortunately their tools do not work in the cross-compiling scenario. Run it in a docker like:
docker run -v /usr/bin/qemu-aarch64-static:/usr/bin/qemu-aarch64-static -v `pwd`:/tmp/a -w /tmp/a --rm quay.io/pypa/manylinux2014_aarch64 /opt/python/cp37-cp37m/bin/python3 setup.py bdist_wheel
This is not needed if you only want to target a specfic Linux distribution (i.e. Ubuntu).
Native compiling on Linux ARM device
Easy, slower
Docker build runs on a Raspberry Pi 3B with Raspbian Stretch Lite OS (Desktop version will run out memory when linking the .so file) will take 8-9 hours in total.
sudo apt-get update
sudo apt-get install -y \
sudo \
build-essential \
curl \
libcurl4-openssl-dev \
libssl-dev \
wget \
python3 \
python3-pip \
python3-dev \
git \
tar
pip3 install --upgrade pip
pip3 install --upgrade setuptools
pip3 install --upgrade wheel
pip3 install numpy
# Build the latest cmake
mkdir /code
cd /code
wget https://cmake.org/files/v3.13/cmake-3.16.1.tar.gz;
tar zxf cmake-3.16.1.tar.gz
cd /code/cmake-3.16.1
./configure --system-curl
make
sudo make install
# Prepare onnxruntime Repo
cd /code
git clone --recursive https://github.com/Microsoft/onnxruntime
# Start the basic build
cd /code/onnxruntime
./build.sh --config MinSizeRel --update --build
# Build Shared Library
./build.sh --config MinSizeRel --build_shared_lib
# Build Python Bindings and Wheel
./build.sh --config MinSizeRel --enable_pybind --build_wheel
# Build Output
ls -l /code/onnxruntime/build/Linux/MinSizeRel/*.so
ls -l /code/onnxruntime/build/Linux/MinSizeRel/dist/*.whl
Cross compiling on Windows
Using Visual C++ compilers
-
Download and install Visual C++ compilers and libraries for ARM(64). If you have Visual Studio installed, please use the Visual Studio Installer (look under the section
Individual componentsafter choosing tomodifyVisual Studio) to download and install the corresponding ARM(64) compilers and libraries. -
Use
.\build.batand specify--armor--arm64as the build option to start building. Preferably useDeveloper Command Prompt for VSor make sure all the installed cross-compilers are findable from the command prompt being used to build using the PATH environmant variable.
Android
Prerequisites
The SDK and NDK packages can be installed via Android Studio or the sdkmanager command line tool. Android Studio is more convenient but a larger installation. The command line tools are smaller and usage can be scripted, but are a little more complicated to setup. They also require a Java runtime environment to be available.
General Info:
- API levels: https://developer.android.com/guide/topics/manifest/uses-sdk-element.html
- Android ABIs: https://developer.android.com/ndk/guides/abis
- System Images: https://developer.android.com/topic/generic-system-image
Android Studio
Install Android Studio from https://developer.android.com/studio
Install any additional SDK Platforms if necessary
- File->Settings->Appearance & Behavior->System Settings->Android SDK to see what is currently installed
- Note that the SDK path you need to use as --android_sdk_path when building ORT is also on this configuration page
- Most likely you don't require additional SDK Platform packages as the latest platform can target earlier API levels.
Install an NDK version
- File->Settings->Appearance & Behavior->System Settings->Android SDK
- 'SDK Tools' tab
- Select 'Show package details' checkbox at the bottom to see specific versions. By default the latest will be installed which should be fine.
- 'SDK Tools' tab
- The NDK path will be the 'ndk/{version}' subdirectory of the SDK path shown
- e.g. if 21.1.6352462 is installed it will be {SDK path}/ndk/21.1.6352462
sdkmanager from command line tools
-
If necessary install the Java Runtime Environment and set the JAVA_HOME environment variable to point to it
- https://www.java.com/en/download/
- Windows note: You MUST install the 64-bit version (https://www.java.com/en/download/manual.jsp) otherwise sdkmanager will only list x86 packages and the latest NDK is x64 only.
-
For sdkmanager to work it needs a certain directory structure. First create the top level directory for the Android infrastructure.
- in our example we'll call that
.../Android/
- in our example we'll call that
-
Download the command line tools from the 'Command line tools only' section towards the bottom of https://developer.android.com/studio
-
Create a directory called 'cmdline-tools' under your top level directory
- giving
.../Android/cmdline-tools
- giving
-
extract the 'tools' directory from the command line tools zip file into this directory
- giving
.../Android/cmdline-tools/tools - Windows note: preferably extract using 7-zip.
If using the built in Windows zip extract tool you will need to fix the directory structure
by moving the jar files from
tools\lib\_up totools\lib
- giving
-
you should now be able to run Android/cmdline-tools/bin/sdkmanager[.bat] successfully
- if you see an error about it being unable to save settings and the sdkmanager help text,
your directory structure is incorrect.
- see the final steps in this answer to double check: https://stackoverflow.com/a/61176718
- if you see an error about it being unable to save settings and the sdkmanager help text,
your directory structure is incorrect.
-
Run
.../Android/cmdline-tools/bin/sdkmanager --listto see the packages available -
Install the SDK Platform
- Generally installing the latest is fine. You pick an API level when compiling the code and the latest platform will support many recent API levels
- e.g.
sdkmanager --install "platforms;android-29"
- e.g.
- This will install into the 'platforms' directory of our top level directory
- so the 'Android' directory in our example
- The SDK path to use as --android_sdk_path when building is this top level directory
- Generally installing the latest is fine. You pick an API level when compiling the code and the latest platform will support many recent API levels
-
Install the NDK
- Find the available NDK versions by running
sdkmanager --list - Install
- you can install a specific version or the latest (called 'ndk-bundle')
- e.g.
sdkmanager --install "ndk;21.1.6352462"- NDK path in our example with this install would be
.../Android/ndk/21.1.6352462
- NDK path in our example with this install would be
- NOTE: If you install the ndk-bundle package the path will be
.../Android/ndk-bundleas there's no version number
- Find the available NDK versions by running
Android Build Instructions
Cross compiling on Windows
The Ninja generator needs to be used to build on Windows as the Visual Studio generator doesn't support Android.
./build.bat --android --android_sdk_path <android sdk path> --android_ndk_path <android ndk path> --android_abi <android abi, e.g., arm64-v8a (default) or armeabi-v7a> --android_api <android api level, e.g., 27 (default)> --cmake_generator Ninja
e.g. using the paths from our example
./build.bat --android --android_sdk_path .../Android --android_ndk_path .../Android/ndk/21.1.6352462 --android_abi arm64-v8a --android_api 27 --cmake_generator Ninja
Cross compiling on Linux and macOS
./build.sh --android --android_sdk_path <android sdk path> --android_ndk_path <android ndk path> --android_abi <android abi, e.g., arm64-v8a (default) or armeabi-v7a> --android_api <android api level, e.g., 27 (default)>
Build Android Archive (AAR)
Android Archive (AAR) files, which can be imported directly in Android Studio, will be generated in your_build_dir/java/build/outputs/aar, by using the above building commands with --build_java
To build on Windows with --build_java enabled you must also:
- set JAVA_HOME to the path to your JDK install
- this could be the JDK from Android Studio, or a standalone JDK install
- e.g. Powershell:
$env:JAVA_HOME="C:\Program Files\Java\jdk-15"CMD:set JAVA_HOME=C:\Program Files\Java\jdk-15
- install Gradle and add the directory to the PATH
- e.g. Powershell:
$env:PATH="$env:PATH;C:\Gradle\gradle-6.6.1\bin"CMD:set PATH=%PATH%;C:\Gradle\gradle-6.6.1\bin
- e.g. Powershell:
- run the build from an admin window
- the Java build needs permissions to create a symlink, which requires an admin window
Android NNAPI Execution Provider
If you want to use NNAPI Execution Provider on Android, see NNAPI Execution Provider.
Build Instructions
Android NNAPI Execution Provider can be built using building commands in Android Build instructions with --use_nnapi
iOS
Prerequisites
- A Mac computer with latest macOS
- Xcode, https://developer.apple.com/xcode/
- CMake, https://cmake.org/download/
- Python 3, https://www.python.org/downloads/mac-osx/
General Info:
-
iOS Platforms
The following two platforms are supported
- iOS device (iPhone, iPad) with arm64 architecture
- iOS simulator with x86_64 architecture
armv7, armv7s and i386 architectures are not currently supported.
tvOS and watchOS platforms are not currently supported.
-
apple_deploy_target
Specify the minimum version of the target platform (iOS) on which the target binaries are to be deployed.
-
Code Signing
If the development team ID which has a valid code signing certificate is specified, Xcode will code sign the onnxruntime library in the building process, otherwise, the onnxruntime will be built without code signing. It may be required or desired to code sign the library for iOS devices. For more information, see Code Signing.
Build Instructions
Run one of the following build scripts from the ONNX Runtime repository root,
Cross build for iOS simulator
./build.sh --config <Release|Debug|RelWithDebInfo|MinSizeRel> --use_xcode \
--ios --ios_sysroot iphonesimulator --osx_arch x86_64 --apple_deploy_target <minimal iOS version>
Cross build for iOS device
./build.sh --config <Release|Debug|RelWithDebInfo|MinSizeRel> --use_xcode \
--ios --ios_sysroot iphoneos --osx_arch arm64 --apple_deploy_target <minimal iOS version>
Cross build for iOS device and code sign the library
./build.sh --config <Release|Debug|RelWithDebInfo|MinSizeRel> --use_xcode \
--ios --ios_sysroot iphoneos --osx_arch arm64 --apple_deploy_target <minimal iOS version> \
--xcode_code_signing_team_id <Your Apple developmemt team ID>
AMD MIGraphX
See more information on the MIGraphX Execution Provider here.
Prerequisites
- Install ROCM
- The MIGraphX execution provider for ONNX Runtime is built and tested with ROCM3.3
- Install MIGraphX
- The path to MIGraphX installation must be provided via the
--migraphx_home parameter.
- The path to MIGraphX installation must be provided via the
Build Instructions
Linux
./build.sh --config <Release|Debug|RelWithDebInfo> --use_migraphx --migraphx_home <path to MIGraphX home>
Dockerfile instructions are available here
Training
Baseline CPU
Build Instructions
To build ORT with training support add --enable_training build instruction.
All other build options are the same for inferencing as they are for training.
Windows
.\build.bat --config RelWithDebInfo --build_shared_lib --parallel --enable_training
The default Windows CMake Generator is Visual Studio 2017, but you can also use the newer Visual Studio 2019 by passing
--cmake_generator "Visual Studio 16 2019" to .\build.bat
Linux/macOS
./build.sh --config RelWithDebInfo --build_shared_lib --parallel --enable_training
Training Enabled Execution Providers
CUDA
Prerequisites
The default NVIDIA GPU build requires CUDA runtime libraries installed on the system:
These dependency versions should reflect what is in Dockerfile.training.
Build instructions
-
Checkout this code repo with
git clone https://github.com/microsoft/onnxruntime -
Set the environment variables: adjust the path for location your build machine
export CUDA_HOME=<location for CUDA libs> # e.g. /usr/local/cuda export CUDNN_HOME=<location for cuDNN libs> # e.g. /usr/local/cuda export CUDACXX=<location for NVCC> #e.g. /usr/local/cuda/bin/nvcc export PATH=<location for openmpi/bin/>:$PATH export LD_LIBRARY_PATH=<location for openmpi/lib/>:$LD_LIBRARY_PATH export MPI_CXX_INCLUDE_PATH=<location for openmpi/include/> source <location of the mpivars script> # e.g. /data/intel/impi/2018.3.222/intel64/bin/mpivars.sh -
Create the ONNX Runtime wheel
- Change to the ONNX Runtime repo base folder:
cd onnxruntime - Run
./build.sh --enable_training --use_cuda --config=RelWithDebInfo --build_wheel
This produces the .whl file in
./build/Linux/RelWithDebInfo/distfor ONNX Runtime Training. - Change to the ONNX Runtime repo base folder:
ROCM
Prerequisites
The default AMD GPU build requires ROCM software toolkit installed on the system:
These dependency versions should reflect what is in Dockerfile.training.
Build instructions
-
Checkout this code repo with
git clone https://github.com/microsoft/onnxruntime -
Create the ONNX Runtime wheel
- Change to the ONNX Runtime repo base folder:
cd onnxruntime - Run
./build.sh --config RelWithDebInfo --enable_training --build_wheel --use_rocm --rocm_home /opt/rocm --nccl_home /opt/rocm --mpi_home <location for openmpi>
This produces the .whl file in
./build/Linux/RelWithDebInfo/distfor ONNX Runtime Training. - Change to the ONNX Runtime repo base folder:
DNNL and MKLML
Build Instructions
Linux
./build.sh --enable_training --use_dnnl
Windows
.\build.bat --enable_training --use_dnnl
Add --build_wheel to build the ONNX Runtime wheel
This will produce a .whl file in build/Linux/RelWithDebInfo/dist for ONNX Runtime Training