forked from microsoft/onnxruntime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
2673 lines (2332 loc) · 116 KB
/
Copy pathbuild.py
File metadata and controls
2673 lines (2332 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# SPDX-FileCopyrightText: Copyright 2024 Arm Limited and/or its affiliates <open-source-office@arm.com>
# Licensed under the MIT License.
from __future__ import annotations
import contextlib
import json
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
from pathlib import Path
def version_to_tuple(version: str) -> tuple:
v = []
for s in version.split("."):
with contextlib.suppress(ValueError):
v.append(int(s))
return tuple(v)
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
REPO_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, "..", ".."))
sys.path.insert(0, os.path.join(REPO_DIR, "tools", "python"))
import util.android as android # noqa: E402
from build_args import parse_arguments # noqa: E402
from util import ( # noqa: E402
generate_android_triplets,
generate_linux_triplets,
generate_macos_triplets,
generate_vcpkg_triplets_for_emscripten,
generate_windows_triplets,
get_logger,
is_linux,
is_macOS,
is_windows,
parse_qnn_version_from_sdk_yaml,
run,
)
log = get_logger("build")
class BaseError(Exception):
"""Base class for errors originating from build.py."""
class BuildError(BaseError):
"""Error from running build steps."""
def __init__(self, *messages):
super().__init__("\n".join(messages))
class UsageError(BaseError):
"""Usage related error."""
def __init__(self, message):
super().__init__(message)
def _check_python_version():
required_minor_version = 8
if (sys.version_info.major, sys.version_info.minor) < (3, required_minor_version):
raise UsageError(
f"Invalid Python version. At least Python 3.{required_minor_version} is required. "
f"Actual Python version: {sys.version}"
)
_check_python_version()
def is_reduced_ops_build(args):
return args.include_ops_by_config is not None
def resolve_executable_path(command_or_path):
"""Returns the absolute path of an executable."""
if command_or_path and command_or_path.strip():
executable_path = shutil.which(command_or_path)
if executable_path is None:
raise BuildError(f"Failed to resolve executable path for '{command_or_path}'.")
return os.path.abspath(executable_path)
else:
return None
def get_linux_distro():
try:
with open("/etc/os-release") as f:
dist_info = dict(line.strip().split("=", 1) for line in f)
return dist_info.get("NAME", "").strip('"'), dist_info.get("VERSION", "").strip('"')
except (OSError, ValueError):
return "", ""
def get_config_build_dir(build_dir, config):
# build directory per configuration
return os.path.join(build_dir, config)
def run_subprocess(
args,
cwd=None,
capture_stdout=False,
dll_path=None,
shell=False,
env=None,
python_path=None,
cuda_home=None,
):
if env is None:
env = {}
if isinstance(args, str):
raise ValueError("args should be a sequence of strings, not a string")
my_env = os.environ.copy()
if dll_path:
if is_windows():
if "PATH" in my_env:
my_env["PATH"] = dll_path + os.pathsep + my_env["PATH"]
else:
my_env["PATH"] = dll_path
else:
if "LD_LIBRARY_PATH" in my_env:
my_env["LD_LIBRARY_PATH"] += os.pathsep + dll_path
else:
my_env["LD_LIBRARY_PATH"] = dll_path
# Add nvcc's folder to PATH env so that our cmake file can find nvcc
if cuda_home:
my_env["PATH"] = os.path.join(cuda_home, "bin") + os.pathsep + my_env["PATH"]
if python_path:
if "PYTHONPATH" in my_env:
my_env["PYTHONPATH"] += os.pathsep + python_path
else:
my_env["PYTHONPATH"] = python_path
my_env.update(env)
log.info(" ".join(args))
return run(*args, cwd=cwd, capture_stdout=capture_stdout, shell=shell, env=my_env)
def update_submodules(source_dir):
run_subprocess(["git", "submodule", "sync", "--recursive"], cwd=source_dir)
run_subprocess(["git", "submodule", "update", "--init", "--recursive"], cwd=source_dir)
def setup_test_data(source_onnx_model_dir, dest_model_dir_name, build_dir, configs):
# create the symlink/shortcut of onnx models dir under build_dir
# currently, there're 2 sources of onnx models, one is build in OS image, another is
# from {source_dir}/js/test, which is downloaded from onnx web.
if is_windows():
src_model_dir = os.path.join(build_dir, dest_model_dir_name)
if os.path.exists(source_onnx_model_dir) and not os.path.exists(src_model_dir):
log.debug(f"creating shortcut {source_onnx_model_dir} -> {src_model_dir}")
run_subprocess(["mklink", "/D", "/J", src_model_dir, source_onnx_model_dir], shell=True)
for config in configs:
config_build_dir = get_config_build_dir(build_dir, config)
os.makedirs(config_build_dir, exist_ok=True)
dest_model_dir = os.path.join(config_build_dir, dest_model_dir_name)
if os.path.exists(source_onnx_model_dir) and not os.path.exists(dest_model_dir):
log.debug(f"creating shortcut {source_onnx_model_dir} -> {dest_model_dir}")
run_subprocess(["mklink", "/D", "/J", dest_model_dir, source_onnx_model_dir], shell=True)
elif os.path.exists(src_model_dir) and not os.path.exists(dest_model_dir):
log.debug(f"creating shortcut {src_model_dir} -> {dest_model_dir}")
run_subprocess(["mklink", "/D", "/J", dest_model_dir, src_model_dir], shell=True)
else:
src_model_dir = os.path.join(build_dir, dest_model_dir_name)
if os.path.exists(source_onnx_model_dir) and not os.path.exists(src_model_dir):
log.debug(f"create symlink {source_onnx_model_dir} -> {src_model_dir}")
os.symlink(source_onnx_model_dir, src_model_dir, target_is_directory=True)
def use_dev_mode(args):
if args.compile_no_warning_as_error:
return False
if args.use_acl:
return False
if is_macOS() and (args.ios or args.visionos or args.tvos):
return False
if args.use_qnn:
return True
SYSTEM_COLLECTIONURI = os.getenv("SYSTEM_COLLECTIONURI") # noqa: N806
if SYSTEM_COLLECTIONURI:
return False
return True
def add_default_definition(definition_list, key, default_value):
for x in definition_list:
if x.startswith(key + "="):
return definition_list
definition_list.append(key + "=" + default_value)
def number_of_parallel_jobs(args):
return os.cpu_count() if args.parallel == 0 else args.parallel
def number_of_nvcc_threads(args):
if args.nvcc_threads >= 0:
return args.nvcc_threads
nvcc_threads = 1
try:
import psutil # noqa: PLC0415
available_memory = psutil.virtual_memory().available
if isinstance(available_memory, int) and available_memory > 0:
if available_memory >= 64 * 1024 * 1024 * 1024:
# When available memory is large enough, chance of OOM is small.
nvcc_threads = min(4, int(available_memory / (8 * 4 * 1024 * 1024 * 1024)))
else:
# NVCC need a lot of memory to compile 48 flash attention cu files.
# Here we select number of threads to ensure each thread has enough memory (>= 4 GB).
memory_per_thread = 4 * 1024 * 1024 * 1024
fmha_cu_files = 48
fmha_parallel_jobs = min(fmha_cu_files, number_of_parallel_jobs(args))
nvcc_threads = max(1, int(available_memory / (memory_per_thread * fmha_parallel_jobs)))
print(
f"nvcc_threads={nvcc_threads} to ensure memory per thread >= 4GB for available_memory={available_memory} and fmha_parallel_jobs={fmha_parallel_jobs}"
)
except ImportError:
print(
"Failed to import psutil. Please `pip install psutil` for better estimation of nvcc threads. Use nvcc_threads=1"
)
return nvcc_threads
# See https://learn.microsoft.com/en-us/vcpkg/commands/install
def generate_vcpkg_install_options(build_dir, args):
# NOTE: each option string should not contain any whitespace.
vcpkg_install_options = ["--x-feature=tests"]
if args.use_acl:
vcpkg_install_options.append("--x-feature=acl-ep")
if args.use_azure:
vcpkg_install_options.append("--x-feature=azure-ep")
if args.use_cann:
vcpkg_install_options.append("--x-feature=cann-ep")
if args.use_coreml:
vcpkg_install_options.append("--x-feature=coreml-ep")
if args.use_cuda:
vcpkg_install_options.append("--x-feature=cuda-ep")
if args.use_dml:
vcpkg_install_options.append("--x-feature=dml-ep")
if args.use_dnnl:
vcpkg_install_options.append("--x-feature=dnnl-ep")
if args.use_jsep:
vcpkg_install_options.append("--x-feature=js-ep")
if args.use_migraphx:
vcpkg_install_options.append("--x-feature=migraphx-ep")
if args.use_nnapi:
vcpkg_install_options.append("--x-feature=nnapi-ep")
if args.use_openvino:
vcpkg_install_options.append("--x-feature=openvino-ep")
if args.use_qnn:
vcpkg_install_options.append("--x-feature=qnn-ep")
if args.use_rknpu:
vcpkg_install_options.append("--x-feature=rknpu-ep")
if args.use_tensorrt:
vcpkg_install_options.append("--x-feature=tensorrt-ep")
if args.use_vitisai:
vcpkg_install_options.append("--x-feature=vitisai-ep")
if args.use_vsinpu:
vcpkg_install_options.append("--x-feature=vsinpu-ep")
if args.use_webgpu:
vcpkg_install_options.append("--x-feature=webgpu-ep")
if args.wgsl_template == "dynamic":
vcpkg_install_options.append("--x-feature=webgpu-ep-wgsl-template-dynamic")
if args.use_webnn:
vcpkg_install_options.append("--x-feature=webnn-ep")
if args.use_xnnpack:
vcpkg_install_options.append("--x-feature=xnnpack-ep")
overlay_triplets_dir = None
folder_name_parts = []
if args.enable_address_sanitizer:
folder_name_parts.append("asan")
if args.use_binskim_compliant_compile_flags and not args.android and not args.build_wasm:
folder_name_parts.append("binskim")
if args.disable_rtti:
folder_name_parts.append("nortti")
if args.build_wasm and not args.disable_wasm_exception_catching and not args.disable_exceptions:
folder_name_parts.append("exception_catching")
if args.disable_exceptions:
folder_name_parts.append("noexception")
if args.minimal_build is not None:
folder_name_parts.append("minimal")
if args.build_wasm or len(folder_name_parts) == 0:
# It's hard to tell whether we must use a custom triplet or not. The official triplets work fine for most common situations. However, if a Windows build has set msvc toolset version via args.msvc_toolset then we need to, because we need to ensure all the source code are compiled by the same MSVC toolset version otherwise we will hit link errors like "error LNK2019: unresolved external symbol __std_mismatch_4 referenced in function ..."
# So, to be safe we always use a custom triplet.
folder_name = "default"
else:
folder_name = "_".join(folder_name_parts)
overlay_triplets_dir = (Path(build_dir) / folder_name).absolute()
vcpkg_install_options.append(f"--overlay-triplets={overlay_triplets_dir}")
if "AGENT_TEMPDIRECTORY" in os.environ:
temp_dir = os.environ["AGENT_TEMPDIRECTORY"]
vcpkg_install_options.append(f"--x-buildtrees-root={temp_dir}")
elif "RUNNER_TEMP" in os.environ:
temp_dir = os.environ["RUNNER_TEMP"]
vcpkg_install_options.append(f"--x-buildtrees-root={temp_dir}")
# Config asset cache
if args.use_vcpkg_ms_internal_asset_cache:
terrapin_cmd_path = shutil.which("TerrapinRetrievalTool")
if terrapin_cmd_path is None:
terrapin_cmd_path = "C:\\local\\Terrapin\\TerrapinRetrievalTool.exe"
if not os.path.exists(terrapin_cmd_path):
terrapin_cmd_path = None
if terrapin_cmd_path is not None:
vcpkg_install_options.append(
"--x-asset-sources=x-script,"
+ terrapin_cmd_path
+ " -b https://vcpkg.storage.devpackages.microsoft.io/artifacts/ -a true -u Environment -p {url} -s {sha512} -d {dst}\\;x-block-origin"
)
else:
vcpkg_install_options.append(
"--x-asset-sources=x-azurl,https://vcpkg.storage.devpackages.microsoft.io/artifacts/\\;x-block-origin"
)
return vcpkg_install_options
def generate_build_tree(
cmake_path,
source_dir,
build_dir,
cuda_home,
cudnn_home,
nccl_home,
tensorrt_home,
tensorrt_rtx_home,
migraphx_home,
acl_home,
acl_libs,
qnn_home,
snpe_root,
cann_home,
path_to_protoc_exe,
configs,
cmake_extra_defines,
args,
cmake_extra_args,
):
log.info("Generating CMake build tree")
cmake_dir = os.path.join(source_dir, "cmake")
cmake_args = [cmake_path, cmake_dir]
if not use_dev_mode(args):
cmake_args += ["--compile-no-warning-as-error"]
types_to_disable = args.disable_types
# enable/disable float 8 types
disable_float8_types = args.android or ("float8" in types_to_disable)
# enable/disable float 4 type
disable_float4_types = args.android or ("float4" in types_to_disable)
disable_optional_type = "optional" in types_to_disable
disable_sparse_tensors = "sparsetensor" in types_to_disable
disable_string_type = "string" in types_to_disable
if is_windows():
cmake_args += [
"-Donnxruntime_USE_DML=" + ("ON" if args.use_dml else "OFF"),
"-Donnxruntime_USE_WINML=" + ("ON" if args.use_winml else "OFF"),
"-Donnxruntime_USE_TELEMETRY=" + ("ON" if args.use_telemetry else "OFF"),
"-Donnxruntime_ENABLE_PIX_FOR_WEBGPU_EP=" + ("ON" if args.enable_pix_capture else "OFF"),
]
if args.caller_framework:
cmake_args.append("-Donnxruntime_CALLER_FRAMEWORK=" + args.caller_framework)
if args.winml_root_namespace_override:
cmake_args.append("-Donnxruntime_WINML_NAMESPACE_OVERRIDE=" + args.winml_root_namespace_override)
if args.disable_memleak_checker or args.enable_address_sanitizer:
cmake_args.append("-Donnxruntime_ENABLE_MEMLEAK_CHECKER=OFF")
else:
cmake_args.append("-Donnxruntime_ENABLE_MEMLEAK_CHECKER=ON")
if args.use_winml:
cmake_args.append("-Donnxruntime_BUILD_WINML_TESTS=" + ("OFF" if args.skip_winml_tests else "ON"))
if args.dml_path:
cmake_args += [
"-Donnxruntime_USE_CUSTOM_DIRECTML=ON",
"-Ddml_INCLUDE_DIR=" + os.path.join(args.dml_path, "include"),
"-Ddml_LIB_DIR=" + os.path.join(args.dml_path, "lib"),
]
if args.dml_external_project:
cmake_args += [
"-Donnxruntime_USE_CUSTOM_DIRECTML=ON",
"-Ddml_EXTERNAL_PROJECT=ON",
]
if args.use_gdk:
cmake_args += [
"-DCMAKE_TOOLCHAIN_FILE=" + os.path.join(source_dir, "cmake", "gdk_toolchain.cmake"),
"-DGDK_EDITION=" + args.gdk_edition,
"-DGDK_PLATFORM=" + args.gdk_platform,
"-Donnxruntime_BUILD_UNIT_TESTS=OFF", # gtest doesn't build for GDK
]
if args.use_dml and not (args.dml_path or args.dml_external_project):
raise BuildError("You must set dml_path or dml_external_project when building with the GDK.")
elif not is_macOS():
cmake_args.append(
"-Donnxruntime_ENABLE_EXTERNAL_CUSTOM_OP_SCHEMAS="
+ ("ON" if args.enable_external_custom_op_schemas else "OFF")
)
cmake_args += [
"-Donnxruntime_RUN_ONNX_TESTS=" + ("ON" if args.enable_onnx_tests else "OFF"),
"-Donnxruntime_GENERATE_TEST_REPORTS=ON",
"-DPython_EXECUTABLE=" + sys.executable,
"-Donnxruntime_USE_VCPKG=" + ("ON" if args.use_vcpkg else "OFF"),
"-Donnxruntime_USE_MIMALLOC=" + ("ON" if args.use_mimalloc else "OFF"),
"-Donnxruntime_ENABLE_PYTHON=" + ("ON" if args.enable_pybind else "OFF"),
"-Donnxruntime_BUILD_CSHARP=" + ("ON" if args.build_csharp else "OFF"),
"-Donnxruntime_BUILD_JAVA=" + ("ON" if args.build_java else "OFF"),
"-Donnxruntime_BUILD_NODEJS=" + ("ON" if args.build_nodejs else "OFF"),
"-Donnxruntime_BUILD_OBJC=" + ("ON" if args.build_objc else "OFF"),
"-Donnxruntime_BUILD_SHARED_LIB=" + ("ON" if args.build_shared_lib else "OFF"),
"-Donnxruntime_BUILD_APPLE_FRAMEWORK=" + ("ON" if args.build_apple_framework else "OFF"),
"-Donnxruntime_USE_DNNL=" + ("ON" if args.use_dnnl else "OFF"),
"-Donnxruntime_USE_NNAPI_BUILTIN=" + ("ON" if args.use_nnapi else "OFF"),
"-Donnxruntime_USE_VSINPU=" + ("ON" if args.use_vsinpu else "OFF"),
"-Donnxruntime_USE_RKNPU=" + ("ON" if args.use_rknpu else "OFF"),
"-Donnxruntime_ENABLE_MICROSOFT_INTERNAL=" + ("ON" if args.enable_msinternal else "OFF"),
"-Donnxruntime_USE_VITISAI=" + ("ON" if args.use_vitisai else "OFF"),
"-Donnxruntime_USE_TENSORRT=" + ("ON" if args.use_tensorrt else "OFF"),
"-Donnxruntime_USE_NV=" + ("ON" if args.use_nv_tensorrt_rtx else "OFF"),
"-Donnxruntime_USE_TENSORRT_BUILTIN_PARSER="
+ ("ON" if args.use_tensorrt_builtin_parser and not args.use_tensorrt_oss_parser else "OFF"),
# interface variables are used only for building onnxruntime/onnxruntime_shared.dll but not EPs
"-Donnxruntime_USE_TENSORRT_INTERFACE=" + ("ON" if args.enable_generic_interface else "OFF"),
"-Donnxruntime_USE_CUDA_INTERFACE=" + ("ON" if args.enable_generic_interface else "OFF"),
"-Donnxruntime_USE_NV_INTERFACE=" + ("ON" if args.enable_generic_interface else "OFF"),
"-Donnxruntime_USE_OPENVINO_INTERFACE=" + ("ON" if args.enable_generic_interface else "OFF"),
"-Donnxruntime_USE_VITISAI_INTERFACE=" + ("ON" if args.enable_generic_interface else "OFF"),
"-Donnxruntime_USE_QNN_INTERFACE=" + ("ON" if args.enable_generic_interface else "OFF"),
"-Donnxruntime_USE_MIGRAPHX_INTERFACE=" + ("ON" if args.enable_generic_interface else "OFF"),
# set vars for migraphx
"-Donnxruntime_USE_MIGRAPHX=" + ("ON" if args.use_migraphx else "OFF"),
"-Donnxruntime_DISABLE_CONTRIB_OPS=" + ("ON" if args.disable_contrib_ops else "OFF"),
"-Donnxruntime_DISABLE_ML_OPS=" + ("ON" if args.disable_ml_ops else "OFF"),
"-Donnxruntime_DISABLE_GENERATION_OPS=" + ("ON" if args.disable_generation_ops else "OFF"),
"-Donnxruntime_DISABLE_RTTI="
+ ("ON" if args.disable_rtti or (args.minimal_build is not None and not args.enable_pybind) else "OFF"),
"-Donnxruntime_DISABLE_EXCEPTIONS=" + ("ON" if args.disable_exceptions else "OFF"),
# Need to use 'is not None' with minimal_build check as it could be an empty list.
"-Donnxruntime_MINIMAL_BUILD=" + ("ON" if args.minimal_build is not None else "OFF"),
"-Donnxruntime_EXTENDED_MINIMAL_BUILD="
+ ("ON" if args.minimal_build and "extended" in args.minimal_build else "OFF"),
"-Donnxruntime_MINIMAL_BUILD_CUSTOM_OPS="
+ (
"ON"
if (args.minimal_build is not None and ("custom_ops" in args.minimal_build or args.use_extensions))
else "OFF"
),
"-Donnxruntime_REDUCED_OPS_BUILD=" + ("ON" if is_reduced_ops_build(args) else "OFF"),
"-Donnxruntime_CLIENT_PACKAGE_BUILD=" + ("ON" if args.client_package_build else "OFF"),
"-Donnxruntime_ENABLE_SESSION_THREADPOOL_CALLBACKS="
+ ("ON" if args.enable_session_threadpool_callbacks else "OFF"),
"-Donnxruntime_BUILD_MS_EXPERIMENTAL_OPS=" + ("ON" if args.ms_experimental else "OFF"),
"-Donnxruntime_ENABLE_LTO=" + ("ON" if args.enable_lto else "OFF"),
"-Donnxruntime_USE_ACL=" + ("ON" if args.use_acl else "OFF"),
"-Donnxruntime_USE_JSEP=" + ("ON" if args.use_jsep else "OFF"),
"-Donnxruntime_USE_WEBGPU=" + ("ON" if args.use_webgpu else "OFF"),
"-Donnxruntime_USE_EXTERNAL_DAWN=" + ("ON" if args.use_external_dawn else "OFF"),
"-Donnxruntime_WGSL_TEMPLATE=" + args.wgsl_template,
# Training related flags
"-Donnxruntime_ENABLE_NVTX_PROFILE=" + ("ON" if args.enable_nvtx_profile else "OFF"),
"-Donnxruntime_ENABLE_TRAINING=" + ("ON" if args.enable_training else "OFF"),
"-Donnxruntime_ENABLE_TRAINING_OPS=" + ("ON" if args.enable_training_ops else "OFF"),
"-Donnxruntime_ENABLE_TRAINING_APIS=" + ("ON" if args.enable_training_apis else "OFF"),
# Enable advanced computations such as AVX for some traininig related ops.
"-Donnxruntime_ENABLE_CPU_FP16_OPS=" + ("ON" if args.enable_training else "OFF"),
"-Donnxruntime_USE_NCCL=" + ("ON" if args.enable_nccl else "OFF"),
"-Donnxruntime_BUILD_BENCHMARKS=" + ("ON" if args.build_micro_benchmarks else "OFF"),
"-Donnxruntime_GCOV_COVERAGE=" + ("ON" if args.code_coverage else "OFF"),
"-Donnxruntime_ENABLE_MEMORY_PROFILE=" + ("ON" if args.enable_memory_profile else "OFF"),
"-Donnxruntime_ENABLE_CUDA_LINE_NUMBER_INFO=" + ("ON" if args.enable_cuda_line_info else "OFF"),
"-Donnxruntime_USE_CUDA_NHWC_OPS=" + ("ON" if args.use_cuda and not args.disable_cuda_nhwc_ops else "OFF"),
"-Donnxruntime_BUILD_WEBASSEMBLY_STATIC_LIB=" + ("ON" if args.build_wasm_static_lib else "OFF"),
"-Donnxruntime_ENABLE_WEBASSEMBLY_EXCEPTION_CATCHING="
+ ("OFF" if args.disable_wasm_exception_catching else "ON"),
"-Donnxruntime_ENABLE_WEBASSEMBLY_API_EXCEPTION_CATCHING="
+ ("ON" if args.enable_wasm_api_exception_catching else "OFF"),
"-Donnxruntime_ENABLE_WEBASSEMBLY_EXCEPTION_THROWING="
+ ("ON" if args.enable_wasm_exception_throwing_override else "OFF"),
"-Donnxruntime_WEBASSEMBLY_RUN_TESTS_IN_BROWSER=" + ("ON" if args.wasm_run_tests_in_browser else "OFF"),
"-Donnxruntime_ENABLE_WEBASSEMBLY_JSPI=" + ("ON" if args.enable_wasm_jspi else "OFF"),
"-Donnxruntime_ENABLE_WEBASSEMBLY_THREADS=" + ("ON" if args.enable_wasm_threads else "OFF"),
"-Donnxruntime_ENABLE_WEBASSEMBLY_DEBUG_INFO=" + ("ON" if args.enable_wasm_debug_info else "OFF"),
"-Donnxruntime_ENABLE_WEBASSEMBLY_PROFILING=" + ("ON" if args.enable_wasm_profiling else "OFF"),
"-Donnxruntime_ENABLE_LAZY_TENSOR=" + ("ON" if args.enable_lazy_tensor else "OFF"),
"-Donnxruntime_ENABLE_CUDA_PROFILING=" + ("ON" if args.enable_cuda_profiling else "OFF"),
"-Donnxruntime_USE_XNNPACK=" + ("ON" if args.use_xnnpack else "OFF"),
"-Donnxruntime_USE_WEBNN=" + ("ON" if args.use_webnn else "OFF"),
"-Donnxruntime_USE_CANN=" + ("ON" if args.use_cann else "OFF"),
"-Donnxruntime_DISABLE_FLOAT8_TYPES=" + ("ON" if disable_float8_types else "OFF"),
"-Donnxruntime_DISABLE_FLOAT4_TYPES=" + ("ON" if disable_float4_types else "OFF"),
"-Donnxruntime_DISABLE_SPARSE_TENSORS=" + ("ON" if disable_sparse_tensors else "OFF"),
"-Donnxruntime_DISABLE_OPTIONAL_TYPE=" + ("ON" if disable_optional_type else "OFF"),
"-Donnxruntime_DISABLE_STRING_TYPE=" + ("ON" if disable_string_type else "OFF"),
"-Donnxruntime_CUDA_MINIMAL=" + ("ON" if args.enable_cuda_minimal_build else "OFF"),
]
if args.minimal_build is not None:
add_default_definition(cmake_extra_defines, "ONNX_MINIMAL_BUILD", "ON")
if args.rv64:
add_default_definition(cmake_extra_defines, "onnxruntime_CROSS_COMPILING", "ON")
if not args.riscv_toolchain_root:
raise BuildError("The --riscv_toolchain_root option is required to build for riscv64.")
if not args.skip_tests and not args.riscv_qemu_path:
raise BuildError("The --riscv_qemu_path option is required for testing riscv64.")
cmake_args += [
"-DRISCV_TOOLCHAIN_ROOT:PATH=" + args.riscv_toolchain_root,
"-DRISCV_QEMU_PATH:PATH=" + args.riscv_qemu_path,
"-DCMAKE_TOOLCHAIN_FILE=" + os.path.join(source_dir, "cmake", "riscv64.toolchain.cmake"),
]
emscripten_cmake_toolchain_file = None
emsdk_dir = None
if args.build_wasm:
emsdk_dir = os.path.join(cmake_dir, "external", "emsdk")
emscripten_cmake_toolchain_file = os.path.join(
emsdk_dir, "upstream", "emscripten", "cmake", "Modules", "Platform", "Emscripten.cmake"
)
if args.use_vcpkg:
# Setup CMake flags for vcpkg
# Find VCPKG's toolchain cmake file
vcpkg_cmd_path = shutil.which("vcpkg")
vcpkg_toolchain_path = None
if vcpkg_cmd_path is not None:
vcpkg_toolchain_path = Path(vcpkg_cmd_path).parent / "scripts" / "buildsystems" / "vcpkg.cmake"
if not vcpkg_toolchain_path.exists():
if is_windows():
raise BuildError(
"Cannot find VCPKG's toolchain cmake file. Please check if your vcpkg command was provided by Visual Studio"
)
# Fallback to the next
vcpkg_toolchain_path = None
# Fallback to use the "VCPKG_INSTALLATION_ROOT" env var
vcpkg_installation_root = os.environ.get("VCPKG_INSTALLATION_ROOT")
if vcpkg_installation_root is None:
# Fallback to checkout vcpkg from github
vcpkg_installation_root = os.path.join(os.path.abspath(build_dir), "vcpkg")
if not os.path.exists(vcpkg_installation_root):
run_subprocess(
["git", "clone", "-b", "2025.08.27", "https://github.com/microsoft/vcpkg.git", "--recursive"],
cwd=build_dir,
)
vcpkg_toolchain_path = Path(vcpkg_installation_root) / "scripts" / "buildsystems" / "vcpkg.cmake"
if args.build_wasm:
# While vcpkg has a toolchain cmake file for most build platforms(win/linux/mac/android/...), it doesn't have one to wasm. Therefore we need to do some tricks here.
# Here we will generate two toolchain cmake files. One for building the ports, one for building onnxruntime itself.
# The following one is for building onnxruntime itself
new_toolchain_file = Path(build_dir) / "toolchain.cmake"
old_toolchain_lines = []
# First, we read the official toolchain cmake file provided by emscripten into memory
emscripten_root_path = os.path.join(emsdk_dir, "upstream", "emscripten")
with open(emscripten_cmake_toolchain_file, encoding="utf-8") as f:
old_toolchain_lines = f.readlines()
emscripten_root_path_cmake_path = emscripten_root_path.replace("\\", "/")
# This file won't be used by vcpkg-tools when invoking 0.vcpkg_dep_info.cmake or vcpkg/scripts/ports.cmake
with open(new_toolchain_file, "w", encoding="utf-8") as f:
f.write(f'set(EMSCRIPTEN_ROOT_PATH "{emscripten_root_path_cmake_path}")\n')
# Copy emscripten's toolchain cmake file to ours.
f.writelines(old_toolchain_lines)
vcpkg_toolchain_path_cmake_path = str(vcpkg_toolchain_path).replace("\\", "/")
# Add an extra line at the bottom of the file to include vcpkg's toolchain file.
f.write(f"include({vcpkg_toolchain_path_cmake_path})")
# Then tell cmake to use this toolchain file.
vcpkg_toolchain_path = new_toolchain_file.absolute()
# This file is for building the vcpkg ports.
empty_toolchain_file = Path(build_dir) / "emsdk_vcpkg_toolchain.cmake"
with open(empty_toolchain_file, "w", encoding="utf-8") as f:
f.write(f'set(EMSCRIPTEN_ROOT_PATH "{emscripten_root_path_cmake_path}")\n')
# The variable VCPKG_MANIFEST_INSTALL is OFF while building the ports
f.write("if(NOT VCPKG_MANIFEST_INSTALL)\n")
flags_to_pass = [
"CXX_FLAGS",
"CXX_FLAGS_DEBUG",
"CXX_FLAGS_RELEASE",
"C_FLAGS",
"C_FLAGS_DEBUG",
"C_FLAGS_RELEASE",
"LINKER_FLAGS",
"LINKER_FLAGS_DEBUG",
"LINKER_FLAGS_RELEASE",
]
# Overriding the cmake flags
f.writelines("SET(CMAKE_" + flag + ' "${VCPKG_' + flag + '}")\n' for flag in flags_to_pass)
# Copy emscripten's toolchain cmake file to ours.
f.writelines(old_toolchain_lines)
f.write("endif()")
# We must define the VCPKG_CHAINLOAD_TOOLCHAIN_FILE cmake variable, otherwise vcpkg won't let us go.
add_default_definition(
cmake_extra_defines, "VCPKG_CHAINLOAD_TOOLCHAIN_FILE", str(empty_toolchain_file.absolute())
)
generate_vcpkg_triplets_for_emscripten(
build_dir,
configs,
emscripten_root_path,
args.enable_wasm_jspi,
not args.disable_rtti,
not args.disable_wasm_exception_catching,
args.minimal_build is not None,
args.enable_address_sanitizer,
args.use_full_protobuf,
)
elif args.android:
generate_android_triplets(
build_dir, configs, args.android_cpp_shared, args.android_api, args.use_full_protobuf
)
elif is_windows():
generate_windows_triplets(build_dir, configs, args.msvc_toolset, args.use_full_protobuf)
elif is_macOS():
osx_target = args.apple_deploy_target
if args.apple_deploy_target is None:
osx_target = os.environ.get("MACOSX_DEPLOYMENT_TARGET")
if osx_target is not None:
log.info(f"Setting VCPKG_OSX_DEPLOYMENT_TARGET to {osx_target}")
generate_macos_triplets(build_dir, configs, osx_target, args.use_full_protobuf)
else:
# Linux, *BSD, AIX or other platforms
generate_linux_triplets(build_dir, configs, args.use_full_protobuf)
add_default_definition(cmake_extra_defines, "CMAKE_TOOLCHAIN_FILE", str(vcpkg_toolchain_path))
# Choose the cmake triplet
triplet = None
if args.build_wasm:
triplet = "wasm32-emscripten"
elif args.android:
if args.android_abi == "armeabi-v7a":
triplet = "arm-neon-android"
elif args.android_abi == "arm64-v8a":
triplet = "arm64-android"
elif args.android_abi == "x86_64":
triplet = "x64-android"
elif args.android_abi == "x86":
triplet = "x86-android"
else:
raise BuildError("Unknown android_abi")
elif is_windows():
target_arch = platform.machine()
if args.arm64:
target_arch = "ARM64"
elif args.arm64ec:
target_arch = "ARM64EC"
cpu_arch = platform.architecture()[0]
if target_arch == "AMD64":
if cpu_arch == "32bit" or args.x86:
triplet = "x86-windows-static" if args.enable_msvc_static_runtime else "x86-windows-static-md"
else:
triplet = "x64-windows-static" if args.enable_msvc_static_runtime else "x64-windows-static-md"
elif target_arch == "ARM64":
triplet = "arm64-windows-static" if args.enable_msvc_static_runtime else "arm64-windows-static-md"
elif target_arch == "ARM64EC":
triplet = "arm64ec-windows-static" if args.enable_msvc_static_runtime else "arm64ec-windows-static-md"
else:
raise BuildError("unknown python arch")
elif is_macOS():
for kvp in cmake_extra_defines:
parts = kvp.split("=")
if len(parts) != 2:
continue
key = parts[0]
value = parts[1]
if key == "CMAKE_OSX_ARCHITECTURES" and len(value.split(";")) == 2:
triplet = "universal2-osx"
if triplet:
log.info(f"setting target triplet to {triplet}")
add_default_definition(cmake_extra_defines, "VCPKG_TARGET_TRIPLET", triplet)
# By default on Windows we currently support only cross compiling for ARM/ARM64
if is_windows() and (args.arm64 or args.arm64ec or args.arm) and platform.architecture()[0] != "AMD64":
# The onnxruntime_CROSS_COMPILING flag is deprecated. Prefer to use CMAKE_CROSSCOMPILING.
add_default_definition(cmake_extra_defines, "onnxruntime_CROSS_COMPILING", "ON")
if args.use_extensions:
add_default_definition(cmake_extra_defines, "OPENCV_SKIP_SYSTEM_PROCESSOR_DETECTION", "ON")
if args.use_cache:
cmake_args.append("-Donnxruntime_BUILD_CACHE=ON")
if not (is_windows() and args.cmake_generator != "Ninja"):
cmake_args.append("-DCMAKE_CXX_COMPILER_LAUNCHER=ccache")
cmake_args.append("-DCMAKE_C_COMPILER_LAUNCHER=ccache")
if args.use_cuda:
cmake_args.append("-DCMAKE_CUDA_COMPILER_LAUNCHER=ccache")
if args.external_graph_transformer_path:
cmake_args.append("-Donnxruntime_EXTERNAL_TRANSFORMER_SRC_PATH=" + args.external_graph_transformer_path)
if args.use_dnnl:
cmake_args.append("-Donnxruntime_DNNL_GPU_RUNTIME=" + args.dnnl_gpu_runtime)
cmake_args.append("-Donnxruntime_DNNL_OPENCL_ROOT=" + args.dnnl_opencl_root)
cmake_args.append("-Donnxruntime_DNNL_AARCH64_RUNTIME=" + args.dnnl_aarch64_runtime)
cmake_args.append("-Donnxruntime_DNNL_ACL_ROOT=" + args.dnnl_acl_root)
if args.build_wasm:
cmake_args.append("-Donnxruntime_ENABLE_WEBASSEMBLY_SIMD=" + ("ON" if args.enable_wasm_simd else "OFF"))
if args.enable_wasm_relaxed_simd:
if not args.enable_wasm_simd:
raise BuildError(
"Wasm Relaxed SIMD (--enable_wasm_relaxed_simd) is only available with Wasm SIMD (--enable_wasm_simd)."
)
cmake_args += ["-Donnxruntime_ENABLE_WEBASSEMBLY_RELAXED_SIMD=ON"]
if args.use_migraphx:
cmake_args.append("-Donnxruntime_MIGRAPHX_HOME=" + migraphx_home)
if args.use_tensorrt:
cmake_args.append("-Donnxruntime_TENSORRT_HOME=" + tensorrt_home)
if args.use_nv_tensorrt_rtx:
cmake_args.append("-Donnxruntime_TENSORRT_RTX_HOME=" + tensorrt_rtx_home)
if args.use_cuda:
nvcc_threads = number_of_nvcc_threads(args)
cmake_args.append("-Donnxruntime_NVCC_THREADS=" + str(nvcc_threads))
cmake_args.append(f"-DCMAKE_CUDA_COMPILER={cuda_home}/bin/nvcc")
add_default_definition(cmake_extra_defines, "onnxruntime_USE_CUDA", "ON")
if args.cuda_version:
add_default_definition(cmake_extra_defines, "onnxruntime_CUDA_VERSION", args.cuda_version)
# TODO: this variable is not really needed
add_default_definition(cmake_extra_defines, "onnxruntime_CUDA_HOME", cuda_home)
if cudnn_home:
add_default_definition(cmake_extra_defines, "onnxruntime_CUDNN_HOME", cudnn_home)
if is_windows():
if args.enable_msvc_static_runtime:
add_default_definition(
cmake_extra_defines, "CMAKE_MSVC_RUNTIME_LIBRARY", "MultiThreaded$<$<CONFIG:Debug>:Debug>"
)
# Set flags for 3rd-party libs
if not args.use_vcpkg:
if args.enable_msvc_static_runtime:
add_default_definition(cmake_extra_defines, "ONNX_USE_MSVC_STATIC_RUNTIME", "ON")
add_default_definition(cmake_extra_defines, "protobuf_MSVC_STATIC_RUNTIME", "ON")
# The following build option was added in ABSL 20240722.0 and it must be explicitly set
add_default_definition(cmake_extra_defines, "ABSL_MSVC_STATIC_RUNTIME", "ON")
add_default_definition(cmake_extra_defines, "gtest_force_shared_crt", "OFF")
else:
# CMAKE_MSVC_RUNTIME_LIBRARY is default to MultiThreaded$<$<CONFIG:Debug>:Debug>DLL
add_default_definition(cmake_extra_defines, "ONNX_USE_MSVC_STATIC_RUNTIME", "OFF")
add_default_definition(cmake_extra_defines, "protobuf_MSVC_STATIC_RUNTIME", "OFF")
add_default_definition(cmake_extra_defines, "ABSL_MSVC_STATIC_RUNTIME", "OFF")
add_default_definition(cmake_extra_defines, "gtest_force_shared_crt", "ON")
if acl_home and os.path.exists(acl_home):
cmake_args += ["-Donnxruntime_ACL_HOME=" + acl_home]
if acl_libs and os.path.exists(acl_libs):
cmake_args += ["-Donnxruntime_ACL_LIBS=" + acl_libs]
if nccl_home and os.path.exists(nccl_home):
cmake_args += ["-Donnxruntime_NCCL_HOME=" + nccl_home]
if qnn_home and os.path.exists(qnn_home):
cmake_args += ["-Donnxruntime_QNN_HOME=" + qnn_home]
if snpe_root and os.path.exists(snpe_root):
cmake_args += ["-DSNPE_ROOT=" + snpe_root]
if cann_home and os.path.exists(cann_home):
cmake_args += ["-Donnxruntime_CANN_HOME=" + cann_home]
if args.use_openvino:
cmake_args += [
"-Donnxruntime_USE_OPENVINO=ON",
"-Donnxruntime_NPU_NO_FALLBACK=" + ("ON" if args.use_openvino == "NPU_NO_CPU_FALLBACK" else "OFF"),
"-Donnxruntime_USE_OPENVINO_GPU=" + ("ON" if args.use_openvino == "GPU" else "OFF"),
"-Donnxruntime_USE_OPENVINO_CPU=" + ("ON" if args.use_openvino == "CPU" else "OFF"),
"-Donnxruntime_USE_OPENVINO_NPU=" + ("ON" if args.use_openvino == "NPU" else "OFF"),
"-Donnxruntime_USE_OPENVINO_GPU_NP=" + ("ON" if args.use_openvino == "GPU_NO_PARTITION" else "OFF"),
"-Donnxruntime_USE_OPENVINO_CPU_NP=" + ("ON" if args.use_openvino == "CPU_NO_PARTITION" else "OFF"),
"-Donnxruntime_USE_OPENVINO_NPU_NP=" + ("ON" if args.use_openvino == "NPU_NO_PARTITION" else "OFF"),
"-Donnxruntime_USE_OPENVINO_HETERO=" + ("ON" if args.use_openvino.startswith("HETERO") else "OFF"),
"-Donnxruntime_USE_OPENVINO_DEVICE=" + (args.use_openvino),
"-Donnxruntime_USE_OPENVINO_MULTI=" + ("ON" if args.use_openvino.startswith("MULTI") else "OFF"),
"-Donnxruntime_USE_OPENVINO_AUTO=" + ("ON" if args.use_openvino.startswith("AUTO") else "OFF"),
]
# VitisAI and OpenVINO providers currently only support full_protobuf option.
if args.use_full_protobuf or args.use_openvino or args.use_vitisai or args.gen_doc or args.enable_generic_interface:
cmake_args += ["-Donnxruntime_USE_FULL_PROTOBUF=ON", "-DProtobuf_USE_STATIC_LIBS=ON"]
if args.use_cuda and not is_windows():
nvml_stub_path = cuda_home + "/lib64/stubs"
cmake_args += ["-DCUDA_CUDA_LIBRARY=" + nvml_stub_path]
if args.nnapi_min_api:
cmake_args += ["-Donnxruntime_NNAPI_MIN_API=" + str(args.nnapi_min_api)]
if args.android:
if not args.android_ndk_path:
raise BuildError("android_ndk_path required to build for Android")
if not args.android_sdk_path:
raise BuildError("android_sdk_path required to build for Android")
android_toolchain_cmake_path = os.path.join(args.android_ndk_path, "build", "cmake", "android.toolchain.cmake")
cmake_args += [
"-DANDROID_PLATFORM=android-" + str(args.android_api),
"-DANDROID_ABI=" + str(args.android_abi),
"-DANDROID_MIN_SDK=" + str(args.android_api),
"-DANDROID_USE_LEGACY_TOOLCHAIN_FILE=false",
]
if args.disable_rtti:
add_default_definition(cmake_extra_defines, "CMAKE_ANDROID_RTTI", "OFF")
if args.disable_exceptions:
add_default_definition(cmake_extra_defines, "CMAKE_ANDROID_EXCEPTIONS", "OFF")
if not args.use_vcpkg:
cmake_args.append("-DCMAKE_TOOLCHAIN_FILE=" + android_toolchain_cmake_path)
else:
cmake_args.append("-DVCPKG_CHAINLOAD_TOOLCHAIN_FILE=" + android_toolchain_cmake_path)
if args.android_cpp_shared:
cmake_args += ["-DANDROID_STL=c++_shared"]
if is_macOS() and not args.android:
add_default_definition(cmake_extra_defines, "CMAKE_OSX_ARCHITECTURES", args.osx_arch)
# Code sign the binaries, if the code signing development identity and/or team id are provided
if args.xcode_code_signing_identity:
cmake_args += ["-DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY=" + args.xcode_code_signing_identity]
if args.xcode_code_signing_team_id:
cmake_args += ["-DCMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM=" + args.xcode_code_signing_team_id]
if args.use_qnn:
if args.qnn_home is None or os.path.exists(args.qnn_home) is False:
raise BuildError("qnn_home=" + qnn_home + " not valid." + " qnn_home paths must be specified and valid.")
cmake_args += ["-Donnxruntime_USE_QNN=ON"]
if args.use_qnn == "static_lib":
cmake_args += ["-Donnxruntime_BUILD_QNN_EP_STATIC_LIB=ON"]
if args.android and args.use_qnn != "static_lib":
raise BuildError("Only support Android + QNN builds with QNN EP built as a static library.")
if args.use_qnn == "static_lib" and args.enable_generic_interface:
raise BuildError("Generic ORT interface only supported with QNN EP built as a shared library.")
if args.use_coreml:
cmake_args += ["-Donnxruntime_USE_COREML=ON"]
if args.use_webnn:
if not args.build_wasm:
raise BuildError("WebNN is only available for WebAssembly build.")
cmake_args += ["-Donnxruntime_USE_WEBNN=ON"]
# TODO: currently we allows building with both --use_jsep and --use_webgpu in this working branch.
# This situation is temporary. Eventually, those two flags will be mutually exclusive.
#
# if args.use_jsep and args.use_webgpu:
# raise BuildError("JSEP (--use_jsep) and WebGPU (--use_webgpu) cannot be enabled at the same time.")
if args.enable_wasm_jspi:
if args.use_jsep:
raise BuildError("JSEP (--use_jsep) and WASM JSPI (--enable_wasm_jspi) cannot be enabled at the same time.")
if args.disable_wasm_exception_catching:
raise BuildError("Cannot set WebAssembly exception catching in JSPI build.")
if not args.use_webgpu:
if args.use_external_dawn:
raise BuildError("External Dawn (--use_external_dawn) must be enabled with WebGPU (--use_webgpu).")
if is_windows():
if args.enable_pix_capture:
raise BuildError(
"Enable PIX Capture (--enable_pix_capture) must be enabled with WebGPU (--use_webgpu) on Windows"
)
elif args.use_webgpu == "shared_lib":
# Shared library build (plugin EP)
cmake_args += ["-Donnxruntime_USE_EP_API_ADAPTERS=ON"]
if args.build_wasm:
raise BuildError("Only static library build of WebGPU EP is supported for WebAssembly build.")
if args.use_snpe:
cmake_args += ["-Donnxruntime_USE_SNPE=ON"]
if not args.no_kleidiai:
cmake_args += ["-Donnxruntime_USE_KLEIDIAI=ON"]
if args.use_qmx:
cmake_args += ["-Donnxruntime_USE_QMX_KLEIDIAI_COEXIST=ON"]
if args.enable_arm_neon_nchwc:
cmake_args += ["-Donnxruntime_USE_ARM_NEON_NCHWC=ON"]
if args.enable_rvv:
cmake_args += ["-Donnxruntime_USE_RVV=ON"]
if not args.no_sve:
cmake_args += ["-Donnxruntime_USE_SVE=ON"]
if is_macOS() and (args.macos or args.ios or args.visionos or args.tvos):
# Note: Xcode CMake generator doesn't have a good support for Mac Catalyst yet.
if args.macos == "Catalyst" and args.cmake_generator == "Xcode":
raise BuildError("Xcode CMake generator ('--cmake_generator Xcode') doesn't support Mac Catalyst build.")
if (args.ios or args.visionos or args.tvos or args.macos == "MacOSX") and not args.cmake_generator == "Xcode":
raise BuildError(
"iOS/MacOS framework build requires use of the Xcode CMake generator ('--cmake_generator Xcode')."
)
needed_args = [
args.apple_sysroot,
args.apple_deploy_target,
]
arg_names = [
"--apple_sysroot " + "<the location or name of the macOS platform SDK>",
"--apple_deploy_target " + "<the minimum version of the target platform>",
]
if not all(needed_args):
raise BuildError(
"iOS/MacOS framework build on MacOS canceled due to missing arguments: "
+ ", ".join(val for val, cond in zip(arg_names, needed_args, strict=False) if not cond)
)
# note: this value is mainly used in framework_info.json file to specify the build osx type
platform_name = "macabi" if args.macos == "Catalyst" else args.apple_sysroot
cmake_args += [
"-Donnxruntime_BUILD_SHARED_LIB=ON",
"-DCMAKE_OSX_SYSROOT=" + args.apple_sysroot,
# we do not need protoc binary for ios cross build
"-Dprotobuf_BUILD_PROTOC_BINARIES=OFF",
"-DPLATFORM_NAME=" + platform_name,
]
if args.ios:
cmake_args += [
"-DCMAKE_SYSTEM_NAME=iOS",
"-DCMAKE_TOOLCHAIN_FILE="
+ (args.ios_toolchain_file if args.ios_toolchain_file else "../cmake/onnxruntime_ios.toolchain.cmake"),
]
# for catalyst build, we need to manually specify cflags for target e.g. x86_64-apple-ios14.0-macabi, etc.
# https://forums.developer.apple.com/forums/thread/122571
if args.macos == "Catalyst":
macabi_target = f"{args.osx_arch}-apple-ios{args.apple_deploy_target}-macabi"
cmake_args += [
f"-DCMAKE_CXX_FLAGS=--target={macabi_target}",
f"-DCMAKE_C_FLAGS=--target={macabi_target}",
f"-DCMAKE_ASM_FLAGS=--target={macabi_target}",
]
else:
cmake_args += [
"-DCMAKE_OSX_DEPLOYMENT_TARGET=" + args.apple_deploy_target,
]
if args.visionos:
cmake_args += [
"-DCMAKE_SYSTEM_NAME=visionOS",
"-DCMAKE_TOOLCHAIN_FILE="
+ (
args.visionos_toolchain_file
if args.visionos_toolchain_file
else "../cmake/onnxruntime_visionos.toolchain.cmake"
),
"-Donnxruntime_ENABLE_CPUINFO=OFF",
]
if args.tvos:
cmake_args += [
"-DCMAKE_SYSTEM_NAME=tvOS",
"-DCMAKE_TOOLCHAIN_FILE="
+ (
args.tvos_toolchain_file
if args.tvos_toolchain_file
else "../cmake/onnxruntime_tvos.toolchain.cmake"
),
]
if args.build_wasm:
if not args.use_vcpkg:
cmake_args.append("-DCMAKE_TOOLCHAIN_FILE=" + emscripten_cmake_toolchain_file)
if args.disable_wasm_exception_catching:
# WebAssembly unittest requires exception catching to work. If this feature is disabled, we do not build
# unit test.
cmake_args += [
"-Donnxruntime_BUILD_UNIT_TESTS=OFF",
]
# add default emscripten settings
emscripten_settings = list(args.emscripten_settings)
# set -s MALLOC
if args.wasm_malloc is not None:
add_default_definition(emscripten_settings, "MALLOC", args.wasm_malloc)
add_default_definition(emscripten_settings, "MALLOC", "dlmalloc")
# set -s STACK_SIZE=5242880
add_default_definition(emscripten_settings, "STACK_SIZE", "5242880")
if emscripten_settings:
cmake_args += [f"-Donnxruntime_EMSCRIPTEN_SETTINGS={';'.join(emscripten_settings)}"]
# Append onnxruntime-extensions cmake options
if args.use_extensions:
cmake_args += ["-Donnxruntime_USE_EXTENSIONS=ON"]
# default path of onnxruntime-extensions, using git submodule
for config in configs: