-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathsetup.py
More file actions
2425 lines (2162 loc) · 116 KB
/
Copy pathsetup.py
File metadata and controls
2425 lines (2162 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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# Copyright 2024, 2026 Arm Limited and/or its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# Part of this code is from pybind11 cmake_example, so attach the license below.
# That project has since dropped setup.py, so this points at the last revision
# that still had it instead of at a branch.
# https://github.com/pybind/cmake_example/blob/7a94877f581a14de4de1a096fb053a55fc2a66bf/setup.py
# Copyright (c) 2016 The Pybind Development Team, All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# You are under no obligation whatsoever to provide any bug fixes, patches, or
# upgrades to the features, functionality or performance of the source code
# ("Enhancements") to anyone; however, if you choose to make your Enhancements
# available either publicly, or directly to the author of this software, without
# imposing a separate written license agreement for such Enhancements, then you
# hereby grant the following license: a non-exclusive, royalty-free perpetual
# license to install, use, modify, prepare derivative works, incorporate into
# other computer software, distribute, and sublicense such enhancements or
# derivative works thereof, in binary and source code form.
import contextlib
# Import this before distutils so that setuptools can intercept the distuils
# imports.
import importlib.util
import logging
import os
import re
import shlex
import shutil
import site
import stat
import subprocess
import sys
from distutils import log # type: ignore[import-not-found]
from distutils.sysconfig import get_python_lib # type: ignore[import-not-found]
from pathlib import Path, PurePosixPath
from typing import List, Optional
# Clean dynamic import using importlib
_install_utils_path = Path(__file__).parent / "install_utils.py"
_spec = importlib.util.spec_from_file_location("install_utils", _install_utils_path)
if _spec is None:
raise ImportError(f"Could not create module spec for {_install_utils_path}")
install_utils = importlib.util.module_from_spec(_spec)
if _spec.loader is None:
raise ImportError(f"Module spec has no loader for {_install_utils_path}")
_spec.loader.exec_module(install_utils)
from setuptools import Extension, find_namespace_packages, setup
from setuptools.command.build import build
from setuptools.command.build_ext import build_ext
from setuptools.command.build_py import build_py
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
)
# Headers swept in by a directory copy that a consumer of the wheel cannot use, because each needs
# something the wheel does not carry. Publishing one is worse than leaving it out: the failure arrives in
# someone else's project rather than here.
#
# Matched on the path ending, not the bare file name, so an entry names one specific header rather than
# every file that happens to share its name. Anything under a directory beginning with "test" is already
# dropped separately, so those need no entry here.
#
# Only headers that nothing else the wheel installs includes belong here. A header other shipped headers
# pull in must keep shipping even when it cannot be compiled on its own.
_UNSHIPPABLE_HEADERS = frozenset(
{
# Needs a header generated when the schema is compiled, which in turn needs the FlatBuffers C++
# headers. Those are a third-party library this wheel does not vendor.
"runtime/executor/tensor_parser.h",
# Reads processor details through cpuinfo, whose headers the wheel does not publish.
"extension/threadpool/cpuinfo_utils.h",
# Holds a pthreadpool member by value, so it needs that library's header, which the wheel does not
# publish either. The component it belongs to is a link dependency the runtime carries, not
# something a consumer includes.
"extension/threadpool/threadpool.h",
# Declares CPUCachingAllocator, whose implementation is in a component no shipped library links,
# so including it compiles and then fails at link time with an undefined reference.
"extension/memory_allocator/cpu_caching_malloc_allocator.h",
# Declares BundledModule, which is built only for the Python bindings, so its implementation is in
# the Python extension. A C++ application cannot link that, and building the source instead needs
# bundled-program headers the wheel does not publish.
"extension/module/bundled_module.h",
# Declares FileDescriptorDataLoader, whose implementation is in no CMake target at all, so no
# shipped library defines it. Including it compiles and then fails at link time.
"extension/data_loader/file_descriptor_data_loader.h",
}
)
try:
from tools.cmake.cmake_cache import CMakeCache
except ImportError:
sys.path.insert(
0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools", "cmake")
)
from cmake_cache import CMakeCache # type: ignore[no-redef, import-not-found]
def _is_macos() -> bool:
return sys.platform == "darwin"
def _is_windows() -> bool:
return sys.platform == "win32"
def _is_env_flag_enabled(name: str) -> bool:
return os.environ.get(name, "").strip().upper() in {"1", "ON", "TRUE", "YES"}
def _is_minimal_build() -> bool:
return _is_env_flag_enabled("EXECUTORCH_BUILD_MINIMAL")
def _minimal_cmake_flags() -> List[str]:
return [
"-DEXECUTORCH_BUILD_COREML=OFF",
"-DEXECUTORCH_BUILD_CUDA=OFF",
"-DEXECUTORCH_BUILD_DEVTOOLS=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_DATA_LOADER=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_FLAT_TENSOR=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_LLM=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_LLM_RUNNER=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_MODULE=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_NAMED_DATA_MAP=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_RUNNER_UTIL=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_TENSOR=OFF",
"-DEXECUTORCH_BUILD_EXTENSION_TRAINING=OFF",
"-DEXECUTORCH_BUILD_KERNELS_CUSTOM_AOT=OFF",
"-DEXECUTORCH_BUILD_KERNELS_LLM=OFF",
"-DEXECUTORCH_BUILD_KERNELS_LLM_AOT=OFF",
"-DEXECUTORCH_BUILD_KERNELS_OPTIMIZED=OFF",
"-DEXECUTORCH_BUILD_KERNELS_QUANTIZED=OFF",
"-DEXECUTORCH_BUILD_KERNELS_QUANTIZED_AOT=OFF",
"-DEXECUTORCH_BUILD_MLX=OFF",
"-DEXECUTORCH_BUILD_OPENVINO=OFF",
"-DEXECUTORCH_BUILD_PORTABLE_OPS=OFF",
"-DEXECUTORCH_BUILD_PYBIND=OFF",
"-DEXECUTORCH_BUILD_QNN=OFF",
"-DEXECUTORCH_BUILD_TESTS=OFF",
"-DEXECUTORCH_BUILD_VULKAN=OFF",
"-DEXECUTORCH_BUILD_XNNPACK=OFF",
"-DEXECUTORCH_BUILD_CMSIS_NN_PYBINDS=OFF",
]
def _minimal_packages() -> List[str]:
return sorted(
find_namespace_packages(
where="src",
include=[
"executorch",
"executorch.data",
"executorch.data.bin",
"executorch.exir",
"executorch.exir.*",
"executorch.extension",
"executorch.extension.flat_tensor",
"executorch.extension.flat_tensor.*",
"executorch.extension.pytree",
],
exclude=[
"*.test",
"*.test.*",
"*.tests",
"*.tests.*",
"*.__pycache__",
"*.__pycache__.*",
],
)
)
# The published project names for the CUDA runtime components a CUDA wheel links but
# does not bundle, keyed by CUDA major version. Not derivable from a suffix rule: the
# CUDA 12 wheels carry a "-cu12" suffix while the CUDA 13 ones are published under
# unsuffixed names. A train with no entry here declares nothing rather than guessing a
# name that may not exist.
#
# Only what a shipped library actually loads. Measured on a built wheel, the CUDA
# libraries need the CUDA runtime and nothing else, because cuRAND is used only through
# its device-side header API, which compiles into the object rather than linking a
# library, and the generated model library embeds its kernels rather than compiling them
# at run time, so there is no runtime compiler to satisfy either.
# Bounded to the train the binaries were built against. The shipped libraries record
# NEEDED libcudart.so.<major> and a runtime path into that train's own directory, so a
# resolution to a different major installs a different layout and a different soname and the
# wheel is unimportable. Nothing catches that at install time; it surfaces as an unresolved
# libcudart on first import. The 12 package is already major-specific by name, but the 13 one
# is not, so it needs the specifier to say what the name does not.
_CUDA_RUNTIME_PACKAGES = {
"12": ("nvidia-cuda-runtime-cu12>=12,<13",),
"13": ("nvidia-cuda-runtime>=13,<14",),
}
# Where each train installs its libraries under site-packages. CUDA 13 collects them in
# one directory while CUDA 12 gives each component its own, so the search path differs by
# train and cannot be a single literal.
#
# Every declared package needs its directory here, and nothing else belongs. The loader only
# searches what is recorded here, so a missing directory leaves a shipped library unable to find
# a package that is installed, and an extra one implies a dependency the wheel does not have.
_CUDA_LIBRARY_DIRECTORIES = {
"12": ("nvidia/cuda_runtime/lib",),
"13": ("nvidia/cu13/lib",),
}
def _cmake_args() -> List[str]:
"""CMAKE_ARGS split into arguments, tolerating an unbalanced quote.
shlex is the correct parser for a value that names a shell argument list, but it raises on an
unbalanced quote, and a path containing an apostrophe is enough to trigger it. Both callers run at
module scope, so the exception surfaced as a traceback during the build rather than a diagnosable
error. Falling back to whitespace splitting keeps the build working for the case that caused it.
"""
raw = os.environ.get("CMAKE_ARGS", "")
try:
return shlex.split(raw)
except ValueError:
return raw.split()
# Release rows that ship no CUDA. Only the metadata side reads this. The shell classifier is
# deliberately broader, treating every name it does not recognise as CPU, so the two do not
# agree on rows like rocm or xpu and are not meant to. What matters is that a row this side
# calls CPU declares no CUDA runtime, which is what the list is for.
_CPU_ROW_NAMES = ("cpu", "cpu-aarch64")
def _row_is_cpu_only() -> bool:
"""Whether the release row this build belongs to names itself a CPU row.
The metadata side already reads the row to decide which NVIDIA packages to declare, so the build
has to read the same input or the two disagree and the wheel ships a delegate it cannot load.
Absent means unknown rather than CPU, which keeps a plain local build behaving as before.
"""
raw = (
(os.environ.get("CU_VERSION") or os.environ.get("DESIRED_CUDA") or "")
.strip()
.lower()
)
return raw in _CPU_ROW_NAMES
def _cuda_train() -> str:
"""The CUDA major version this wheel is being built for, or "" for a CPU wheel.
The release row's own field wins when it is set, because a row states the train it
targets and that is more authoritative than whichever toolkit happens to sit on the
builder. The wheel build exports CU_VERSION; DESIRED_CUDA is the matrix field name.
Falling back to the installed toolkit matters for every build that is not a release
job. The build turns CUDA on by detecting a toolkit, so keying only off the release
field produced a wheel that carried the CUDA libraries with no dependency declarations
and no way to find the CUDA runtime.
Returns "" when the build did not enable CUDA, so a CPU wheel declares nothing even on
a machine that has a toolkit installed.
Raises when a release row names a train the installed toolkit does not provide. The
declared packages and the loader paths both come from this value, so disagreeing with
the toolkit that compiled the libraries produces a wheel that installs cleanly and then
cannot load: a cu126 row built against a 13.0 toolkit declares the CUDA 12 runtime for
binaries that need libcudart.so.13.
"""
# An explicit OFF first, ahead of the release field. A CPU row on a builder that has a
# toolkit installed sets both, so reading the row field first would declare a runtime
# the wheel never loads.
if not install_utils.is_cmake_option_on(
_cmake_args(),
"EXECUTORCH_BUILD_CUDA",
default=True,
):
return ""
raw = os.environ.get("CU_VERSION") or os.environ.get("DESIRED_CUDA") or ""
# A row spelled "cpu" is a CPU row, unless the caller asked for CUDA explicitly. The
# shortcut exists so a local build named that way with nothing requested does not fall
# through and raise on the unsupported-train branch below. It must not swallow an explicit
# request, because that request still reaches CMake, which builds the CUDA libraries: the
# wheel would then carry them with no dependency declared and no path to the runtime.
if raw.lower() in _CPU_ROW_NAMES and not install_utils.is_cmake_option_on(
_cmake_args(), "EXECUTORCH_BUILD_CUDA", default=False
):
return ""
if raw.lower() in _CPU_ROW_NAMES:
# Reached only when the caller turned CUDA on for a CPU row. Refused rather than
# guessed, because the option already reached CMake and built the libraries, so
# declaring nothing would ship them with no runtime dependency and no way to find
# it. Named here so the reader is not sent to add "cpu" to a list of CUDA trains.
raise RuntimeError(
f"the build names a CPU row while also asking for CUDA "
f"(EXECUTORCH_BUILD_CUDA=ON in CMAKE_ARGS). Those contradict: the CUDA "
f"libraries would be built and shipped with no runtime dependency declared. "
f"Pick one, either drop the option or name a CUDA row instead of {raw!r}."
)
# Reduce to digits and match against the same (major, minor) trains the shell classifier
# uses. Previously this took the first two digits and matched against major only, so a
# row spelled with an unsupported minor (say cu125) was classified CPU by the shell and
# CUDA 12 here, and the wheel then declared CUDA runtime packages for a CPU build.
digits = re.sub(r"[^0-9]", "", raw)
# The same rows as `trains` below, keeping both numbers rather than reducing to the
# major, so the guard can tell two rows of one major apart.
_CUDA_ROW_MINORS = {
f"{major}{minor}": (major, minor)
for major, minor in install_utils.SUPPORTED_CUDA_VERSIONS
}
trains = {
f"{major}{minor}": str(major)
for major, minor in install_utils.SUPPORTED_CUDA_VERSIONS
}
requested = trains.get(digits, "")
# Read the toolkit version directly, without the (major, minor) validator, so the guard
# below fires on any mismatch rather than only on the three listed pairs.
detected_version = install_utils._detected_cuda_version()
detected_major = detected_version[0] if detected_version is not None else None
detected = (
str(detected_major)
if detected_major is not None and str(detected_major) in _CUDA_RUNTIME_PACKAGES
else ""
)
if requested:
# A row that names a train has to be buildable for that train. Reported here
# rather than left to produce a mismatched wheel, because nothing downstream
# compares the two: the metadata comes from the row and the binaries come from
# the toolkit.
if detected and detected != requested:
raise RuntimeError(
f"this build targets CUDA {requested} (from "
f"{'CU_VERSION' if os.environ.get('CU_VERSION') else 'DESIRED_CUDA'}="
f"{raw!r}) but the installed toolkit is CUDA {detected}. The declared "
"runtime packages and the loader search paths come from the requested "
"train while the libraries are compiled by the installed one, so the "
"wheel would install and then fail to load. Install a matching toolkit "
"or build the row that matches this one."
)
# The check above compares majors, which two rows of the same major share. A row
# names its train down to the minor, so cu130 and cu132 both reduce to 13 and a
# cu132 row built against a 13.0 toolkit passed. The device code and the version
# in the wheel's local label both come from the row, so that wheel claims a
# toolkit it was not compiled by. Compared here rather than folded above so the
# message can name both numbers.
if detected_version is not None and digits in _CUDA_ROW_MINORS:
requested_pair = _CUDA_ROW_MINORS[digits]
if detected_version != requested_pair:
requested_text = f"{requested_pair[0]}.{requested_pair[1]}"
detected_text = f"{detected_version[0]}.{detected_version[1]}"
raise RuntimeError(
f"this build targets CUDA {requested_text} (from "
f"{'CU_VERSION' if os.environ.get('CU_VERSION') else 'DESIRED_CUDA'}="
f"{raw!r}) but the installed toolkit is CUDA {detected_text}. Those "
"share a major version, so the runtime dependency this wheel declares "
"is correct while the device code and the version recorded in its "
"local label are not. Install a matching toolkit or build the row "
"that matches this one."
)
return requested
if raw and not requested:
# A row named something this packaging does not recognise. Silently reporting the
# builder's toolkit instead contradicts "the row's field wins" and produced a
# wheel tagged for one train carrying another.
supported = ", ".join(
f"cu{major}{minor}"
for major, minor in install_utils.SUPPORTED_CUDA_VERSIONS
)
raise RuntimeError(
f"the release row requests CUDA {raw!r}, which is not a train this project "
f"supports ({supported}). Add it to SUPPORTED_CUDA_VERSIONS in install_utils "
"and to _CUDA_RUNTIME_PACKAGES and _CUDA_LIBRARY_DIRECTORIES here, or build "
"a supported row. Falling back to whatever toolkit this builder has would tag "
"the wheel for one train and fill it with another."
)
# Fall back to the installed toolkit, because keying this off a release variable alone produced a wheel
# that carried the CUDA libraries while declaring no CUDA runtime and recording no way to reach one.
#
# Two ways CUDA gets built, and both have to agree with what is declared here. The build gate turns it
# on when a SUPPORTED train is installed, so a toolkit whose minor is unlisted builds CPU-only and
# declaring runtime packages for it would make a CPU wheel demand four CUDA wheels. An explicit ON
# bypasses that gate and reaches CMake directly, where find_package(CUDAToolkit) accepts a toolkit
# this packaging does not list, so the libraries ship and the runtime has to be declared for them.
# Asking only whether the train is supported got the first case right and the second wrong.
explicit_on = install_utils.is_cmake_option_on(
_cmake_args(),
"EXECUTORCH_BUILD_CUDA",
default=False,
)
if not install_utils.is_cuda_available() and not explicit_on:
return ""
if explicit_on and not detected:
# The explicit request reaches CMake either way, so returning "" here shipped the
# CUDA libraries with no runtime declared and no path to one, which is the wheel
# this whole function exists to prevent. An unlisted minor still resolves to a
# major and is fine; an unlisted major has nothing to declare.
installed = (
f"CUDA {detected_major}"
if detected_major is not None
else "no CUDA toolkit"
)
raise RuntimeError(
f"the build asks for CUDA (EXECUTORCH_BUILD_CUDA=ON in CMAKE_ARGS) but found "
f"{installed}, and this packaging declares a runtime only for CUDA "
f"{', '.join(sorted(_CUDA_RUNTIME_PACKAGES))}. The libraries would still be "
"built and shipped with nothing to load them against. Install a toolkit on one "
"of those majors, or add this one to _CUDA_RUNTIME_PACKAGES and "
"_CUDA_LIBRARY_DIRECTORIES."
)
return detected
def _cuda_libraries_built(cmake_cache_dir: Optional[str]) -> bool:
"""Whether this build produced the CUDA libraries, read from the CMake cache.
The build turns CUDA on from the cache, so the cache is the fact that decides what ships. The
release row's CUDA version is a different question: a build on a toolkit whose train this packaging
does not recognise still produces the libraries while declaring no train, and gating anything else on
the train left that wheel carrying libraries with no matching header.
Falls back to the train when no cache is readable, which is the case for a source distribution where
nothing was built here anyway.
"""
cache_path = os.path.join(cmake_cache_dir or "", "CMakeCache.txt")
if os.path.exists(cache_path):
return CMakeCache(cache_path=cache_path).is_enabled("EXECUTORCH_BUILD_CUDA")
return bool(_cuda_train())
def _verify_cuda_runtime_matches_train(cmake_cache_dir: Optional[str]) -> None:
"""Fail the build when the linked CUDA runtime is not the train being declared.
The declared packages come from the compiler version, while the library that actually gets
linked comes from find_package(CUDAToolkit). Those are normally the same toolkit, but
CUDAToolkit_ROOT steers the second and not the first, so they can split inside a single
find_package call: measured with the compiler at 13.0 and that variable at 12.8,
CUDAToolkit_VERSION reported 13.0.88 while the binary needed libcudart.so.12. Packaging
would then declare the CUDA 13 runtime for a wheel that cannot load without CUDA 12.
Read from the CMake cache rather than from the environment, because the cache records what
the build resolved rather than what was requested.
"""
train = _cuda_train()
if not train:
return
cache_path = os.path.join(cmake_cache_dir or "", "CMakeCache.txt")
if not os.path.exists(cache_path):
return
cache = CMakeCache(cache_path=cache_path)
if not cache.is_enabled("EXECUTORCH_BUILD_CUDA"):
return
linked = cache.get("CUDA_cudart_LIBRARY")
if linked is None or not linked.value:
return
# Read the major from the resolved file name rather than from the recorded path, because the
# conventional way to name a toolkit is the versionless /usr/local/cuda symlink, which carries
# no version at all. Matching the directory accepted that spelling silently, which is the one
# the guard's own message tells the user to set. The resolved name ends in the soname the
# loader will ask for, which is the thing the declared package has to agree with.
found = re.search(r"libcudart\.so\.(\d+)", os.path.realpath(linked.value))
if found is None or found.group(1) == train:
return
raise RuntimeError(
f"this build declares the CUDA {train} runtime but linked the CUDA "
f"{found.group(1)} one from {linked.value!r}, so the wheel would install and then "
"fail to load. The declared train follows the CUDA compiler while the linked "
"libraries follow find_package(CUDAToolkit), so point CUDACXX and CUDAToolkit_ROOT "
"at the same toolkit."
)
def _cuda_dependencies() -> List[str]:
"""Runtime libraries a CUDA wheel needs but does not bundle.
Declared rather than vendored, the way the PyTorch CUDA wheels do it, so one copy is
shared with torch instead of shipping a second one.
"""
train = _cuda_train()
# Marked for Linux, because a CUDA wheel is only built there and these nvidia wheels publish no
# distribution for the other platforms, so an unmarked requirement would make a source install
# elsewhere fail on a dependency it cannot satisfy and does not need.
return [
f"{name}; platform_system == 'Linux'"
for name in _CUDA_RUNTIME_PACKAGES.get(train, ())
]
# Directories inside the wheel that hold libraries a shipped library links, relative to the package
# root rather than to the linking library, because the wheel ships libraries at more than one depth.
#
# The CUDA libraries are split across two directories and reference each other in both directions:
# the delegate in lib/ links the shims library in backends/cuda/, and the shims library links the
# stream helper back in lib/. So both hops are needed.
#
# Applied to every shipped library rather than mapping each library to the directories it happens to
# need. An unused hop costs nothing at load time, while a missing one produces a wheel that installs
# and then fails to load, and a per-library mapping would have to be revisited every time a library
# moves.
_SIBLING_LIBRARY_DIRECTORIES = ("backends/cuda", "lib", "src/executorch/lib")
def _sibling_library_search_paths(depth: int = 1) -> List[str]:
"""Loader paths that reach another directory inside this same package.
`depth` is how many directories separate the linking library from the package root, and it has to
be honoured for the same reason the CUDA hops honour it: the wheel ships libraries at depth one
(lib/) and depth two (backends/cuda/, extension/pybindings/ and others). Measured with a fixed
pair sized for one depth, six of twelve hops landed somewhere that does not exist, and the hop
from lib/ escaped the package entirely into a sibling of it, where an unrelated library with a
matching SONAME could satisfy the dependency first.
"""
up = "/".join([".."] * depth)
token = _loader_relative_token()
return [f"{token}/{up}/{directory}" for directory in _SIBLING_LIBRARY_DIRECTORIES]
def _loader_relative_token() -> str:
"""The token a runtime search path uses to mean "the directory this file is in".
ELF spells it $ORIGIN and Mach-O spells it @loader_path. Both are literal text in the
recorded path, so the wrong one becomes a directory of that name and resolves to
nothing.
"""
return "@loader_path" if sys.platform == "darwin" else "$ORIGIN"
def _cuda_runtime_search_paths(depth: int = 1) -> List[str]:
"""Loader paths that reach the CUDA wheels installed beside this one.
Those wheels install as siblings of this package, so the hop has to climb out of the package first.
`depth` is how many directories separate the library from the package root, and the wheel ships
libraries at more than one depth: a hop sized for one of them lands inside this package from the
other, where nothing is found.
"""
train = _cuda_train()
out = "/".join([".."] * (depth + 1))
return [
f"{_loader_relative_token()}/{out}/{directory}"
for directory in _CUDA_LIBRARY_DIRECTORIES.get(train, ())
]
def _is_cuda_toolkit_directory(entry: str) -> bool:
"""Whether a runtime search path entry names a library directory inside a CUDA toolkit.
Matched on the two layouts a toolkit actually installs rather than on the word "cuda" appearing
somewhere above the directory. Scanning a window of components dropped a torch directory whose build
root happened to be named after a CUDA version, and torch's directory is the one absolute path a
shipped library has to keep.
Position alone cannot separate the two, because a real targets layout puts the cuda-named component at
the same depth a build root does, so each layout is spelled out instead.
"""
parts = [part.lower() for part in PurePosixPath(entry).parts]
if not parts or parts[-1] not in ("lib", "lib64"):
return False
def cuda_named(part: str) -> bool:
return bool(re.fullmatch(r"cuda(?:-\d+(?:\.\d+)*|[-_]?toolkit)?", part))
# <toolkit>/lib64
if len(parts) >= 2 and cuda_named(parts[-2]):
return True
# <toolkit>/targets/<arch>/lib
return len(parts) >= 4 and parts[-3] == "targets" and cuda_named(parts[-4])
def _package_relative_depth(library: Path) -> int:
"""How many directories separate a shipped library from the installed package root.
Searched from the END of the path. At build time the path is absolute and a source checkout is
often named after the package too, so taking the first match found the checkout instead of the
package inside the build output and produced a hop that climbs out of the install directory.
"""
parts = list(Path(library).parts)
if "executorch" not in parts:
return 1
index = len(parts) - 1 - parts[::-1].index("executorch")
return max(len(parts) - index - 2, 0)
def _base_dependencies() -> List[str]:
"""Runtime dependencies for the full wheel.
Declared here rather than in pyproject.toml (where `dependencies` is marked
dynamic) so the minimal build can ship a slimmer set. Keep in sync with the
project's runtime needs.
"""
return [
"expecttest",
"flatbuffers",
"hypothesis",
"kgb",
"mpmath==1.3.0",
"numpy>=2.0.0; python_version >= '3.10'",
"packaging",
"pandas>=2.2.2; python_version >= '3.10'",
"parameterized",
# backends/qualcomm/__init__.py cannot be imported from a clean install
# without both of these. It reads the CPU vendor to disable an mkldnn path on
# AMD, and the module it imports first does a module-scope `import requests`,
# so declaring only the cpuinfo half leaves the import failing on the line
# before.
"py-cpuinfo",
"requests",
"pytorch-tokenizers",
"pyyaml",
"ruamel.yaml",
"sympy",
"tabulate",
# See also third-party/TARGETS for buck's typing-extensions version.
"typing-extensions>=4.10.0",
# Keep this version in sync with: ./backends/apple/coreml/scripts/install_requirements.sh
"coremltools==9.0; (platform_system == 'Darwin' or platform_system == 'Linux') and python_version < '3.14'",
# scikit-learn is used to support palettization in the coreml backend.
"scikit-learn>=1.7.1",
"hydra-core>=1.3.0",
"omegaconf>=2.3.0",
]
def _minimal_dependencies() -> List[str]:
"""Runtime dependencies for the minimal (AOT export only) wheel.
Derived as the subset of _base_dependencies() that executorch.exir needs to
lower and serialize a .pte, so version pins and markers stay in sync with the
full set. torch is intentionally absent from both (consumers bring their own).
mpmath is intentionally dropped too: it is pulled transitively by sympy, whose
"mpmath<1.4" cap resolves to the same 1.3.0 the full wheel pins. Keep the name
set below in sync with the `expected` set in .ci/scripts/test_minimal_wheel.sh.
"""
keep = {
"flatbuffers",
"numpy",
"packaging",
"pyyaml",
"ruamel-yaml",
"sympy",
"tabulate",
"typing-extensions",
}
def _name(dep: str) -> str:
# PEP 503 normalized distribution name, e.g. "ruamel.yaml" -> "ruamel-yaml".
return re.sub(
r"[-_.]+", "-", re.split(r"[ ;\[<>=!~(]", dep, maxsplit=1)[0]
).lower()
minimal = [dep for dep in _base_dependencies() if _name(dep) in keep]
# Fail the build loudly if a name in `keep` no longer matches a full-wheel dep
# (e.g. renamed or removed in _base_dependencies()), instead of silently
# shipping a minimal wheel that is missing a required dependency.
unmatched = keep - {_name(dep) for dep in minimal}
assert not unmatched, f"minimal keep-set names not found in base deps: {unmatched}"
return minimal
class Version:
"""Static strings that describe the version of the pip package."""
# Cached values returned by the properties.
__root_dir_attr: Optional[str] = None
__string_attr: Optional[str] = None
__git_hash_attr: Optional[str] = None
@classmethod
def _root_dir(cls) -> str:
"""The path to the root of the git repo."""
if cls.__root_dir_attr is None:
# This setup.py file lives in the root of the repo.
cls.__root_dir_attr = str(Path(__file__).parent.resolve())
return str(cls.__root_dir_attr)
@classmethod
def git_hash(cls) -> Optional[str]:
"""The current git hash, if known."""
if cls.__git_hash_attr is None:
import subprocess
try:
cls.__git_hash_attr = (
subprocess.check_output(
["git", "rev-parse", "HEAD"], cwd=cls._root_dir()
)
.decode("ascii")
.strip()
)
except subprocess.CalledProcessError:
cls.__git_hash_attr = "" # Non-None but empty.
# A non-None but empty value indicates that we don't know it.
return cls.__git_hash_attr if cls.__git_hash_attr else None
@classmethod
def string(cls) -> str:
"""The version string."""
if cls.__string_attr is None:
# If set, BUILD_VERSION should override any local version
# information. CI will use this to manage, e.g., release vs. nightly
# versions.
version = os.getenv("BUILD_VERSION", "").strip()
if not version:
# Otherwise, read the version from a local file and add the git
# commit if available.
version = (
open(os.path.join(cls._root_dir(), "version.txt")).read().strip()
)
if cls.git_hash():
version += "+" + cls.git_hash()[:7] # type: ignore[index]
cls.__string_attr = version
return cls.__string_attr
@classmethod
def write_to_python_file(cls, path: str) -> None:
"""Creates a file similar to PyTorch core's `torch/version.py`."""
lines = [
"from typing import Optional",
'__all__ = ["__version__", "git_version"]',
f'__version__ = "{cls.string()}"',
# A string or None.
f"git_version: Optional[str] = {repr(cls.git_hash())}",
]
with open(path, "w") as fp:
fp.write("\n".join(lines) + "\n")
# The build type is determined by the DEBUG environment variable. If DEBUG is
# set to a non-empty value, the build type is Debug. Otherwise, the build type
# is Release.
def get_build_type(is_debug=None) -> str:
debug = int(os.environ.get("DEBUG", 0) or 0) if is_debug is None else is_debug
return "Debug" if debug else "Release"
def get_dynamic_lib_name(name: str) -> str:
if _is_windows():
return f"{name}.dll"
elif _is_macos():
return f"lib{name}.dylib"
else:
return f"lib{name}.so"
def _dynamic_lib_suffix() -> str:
"""The loadable-library suffix on this platform, including the dot.
Separate from get_dynamic_lib_name because a file whose prefix is not known
ahead of time still needs the suffix named: globbing the suffix as well would
also match an import library, an exports file, or a soname's versioned links.
"""
if _is_windows():
return ".dll"
if _is_macos():
return ".dylib"
return ".so"
def get_executable_name(name: str) -> str:
if _is_windows():
return name + ".exe"
else:
return name
class _BaseExtension(Extension):
"""A base class that maps an abstract source to an abstract destination."""
def __init__(
self,
src: str,
dst: str,
name: str,
dependent_cmake_flags: List[str],
):
# Source path; semantics defined by the subclass.
self.src: str = src
# Destination path relative to a namespace defined elsewhere. If this ends
# in "/", it is treated as a directory. If this is "", it is treated as the
# root of the namespace.
# Destination path; semantics defined by the subclass.
self.dst: str = dst
# Other parts of setuptools expects .name to exist. For actual extensions
# this can be the module path, but otherwise it should be somehing unique
# that doesn't look like a module path.
self.name: str = name
self.dependent_cmake_flags = dependent_cmake_flags
self.cmake_cache: Optional[CMakeCache] = None
super().__init__(name=self.name, sources=[])
def _get_build_dir(self, installer: "InstallerBuildExt") -> Path:
# Share the cmake-out location with CustomBuild.
build_cmd = installer.get_finalized_command("build")
if "%CMAKE_CACHE_DIR%" in self.src:
if not hasattr(build_cmd, "cmake_cache_dir"):
raise RuntimeError(
f"Extension {self.name} has a src {self.src} that contains"
" %CMAKE_CACHE_DIR% but CMake does not run in the `build` "
"command. Please double check if the command is correct."
)
else:
return Path(build_cmd.cmake_cache_dir)
else:
# If the src path doesn't contain %CMAKE_CACHE_DIR% placeholder,
# try to find it under the current directory.
return Path(".")
def is_cmake_artifact_used(self, installer: "InstallerBuildExt") -> bool:
cache_path = str(self._get_build_dir(installer) / "CMakeCache.txt")
if not os.path.exists(cache_path):
# If this is not a CMake folder, then assume it's used.
return True
elif self.cmake_cache is None:
self.cmake_cache = CMakeCache(cache_path=cache_path)
return all(
self.cmake_cache.is_enabled(flag) for flag in self.dependent_cmake_flags
)
def src_path(self, installer: "InstallerBuildExt") -> Path:
"""Returns the path to the source file, resolving globs.
Args:
installer: The InstallerBuildExt instance that is installing the
file.
"""
build_dir = self._get_build_dir(installer)
src_path = self.src.replace("%CMAKE_CACHE_DIR%/", "")
cfg = get_build_type(installer.debug)
if os.name == "nt":
# Replace %BUILD_TYPE% with the current build type.
src_path = src_path.replace("%BUILD_TYPE%", cfg)
else:
# Remove %BUILD_TYPE% from the path.
src_path = src_path.replace("/%BUILD_TYPE%", "")
# Construct the full source path, resolving globs. If there are no glob
# pattern characters, this will just ensure that the source file exists.
srcs = tuple(build_dir.glob(src_path))
if len(srcs) != 1:
raise ValueError(
f"Expecting exactly 1 file matching {self.src} in {build_dir}, "
f"found {repr(srcs)}. Resolved src pattern: {src_path}."
)
return srcs[0]
def inplace_dir(self, installer: "InstallerBuildExt") -> Path:
"""Returns the path of this file to be installed to, under inplace mode.
It will be a relative path to the project root directory. For more info
related to inplace/editable mode, please checkout this doc:
https://setuptools.pypa.io/en/latest/userguide/development_mode.html
"""
raise NotImplementedError()
class BuiltFile(_BaseExtension):
"""An extension that installs a single file that was built by cmake.
This isn't technically a `build_ext` style python extension, but there's no
dedicated command for installing arbitrary data. It's convenient to use
this, though, because it lets us manage the files to install as entries in
`ext_modules`.
"""
def __init__(
self,
src_dir: str,
src_name: str,
dst: str,
dependent_cmake_flags: List[str],
is_executable: bool = False,
is_dynamic_lib: bool = False,
):
"""Initializes a BuiltFile.
Args:
src_dir: The directory of the file to install, relative to the cmake-out
directory. A placeholder %BUILD_TYPE% will be replaced with the build
type for multi-config generators (like Visual Studio) where the build
output is in a subdirectory named after the build type. For single-
config generators (like Makefile Generators or Ninja), this placeholder
will be removed.
src_name: The name of the file to install
dst: The path to install to, relative to the root of the pip
package. If dst ends in "/", it is treated as a directory.
Otherwise it is treated as a filename.
is_executable: If True, the file is an executable. This is used to
determine the destination filename for executable.
is_dynamic_lib: If True, the file is a dynamic library. This is used
to determine the destination filename for dynamic library.
"""
if is_executable and is_dynamic_lib:
raise ValueError("is_executable and is_dynamic_lib cannot be both True.")
if is_executable:
src_name = get_executable_name(src_name)
elif is_dynamic_lib:
src_name = get_dynamic_lib_name(src_name)
src = os.path.join(src_dir, src_name)
# This is not a real extension, so use a unique name that doesn't look
# like a module path. Some of setuptools's autodiscovery will look for
# extension names with prefixes that match certain module paths.
super().__init__(
src=src,
dst=dst,
name=f"@EXECUTORCH_BuiltFile_{src}:{dst}",
dependent_cmake_flags=dependent_cmake_flags,
)
def dst_path(self, installer: "InstallerBuildExt") -> Path:
"""Returns the path to the destination file.
Args:
installer: The InstallerBuildExt instance that is installing the
file.
"""
dst_root = Path(installer.build_lib).resolve()
if self.dst.endswith("/"):
# Destination looks like a directory. Use the basename of the source
# file for its final component.
return dst_root / Path(self.dst) / self.src_path(installer).name
else:
# Destination looks like a file.
return dst_root / Path(self.dst)
def inplace_dir(self, installer: "InstallerBuildExt") -> Path:
"""For a `BuiltFile`, we use self.dst as its inplace directory path.
Need to handle directory vs file.
"""
# The destination is relative to the installed package, so resolve it against the same
# package directory an extension uses. Anchoring at the repo root instead only worked for
# destinations that already had a directory under src/executorch, and silently scattered
# the rest, which left the CMake package searching a directory nothing was copied into.
relative = self.dst.removeprefix("executorch/")
if not relative.endswith("/"):
relative = os.path.dirname(relative)
build_py = installer.get_finalized_command("build_py")
package_dir = os.path.abspath(build_py.get_package_dir("executorch"))
return Path(package_dir) / relative
class BuiltExtension(_BaseExtension):
"""An extension that installs a python extension that was built by cmake."""
def __init__(
self,
src: str,
modpath: str,
dependent_cmake_flags: List[str],
src_dir: Optional[str] = None,
):
"""Initializes a BuiltExtension.
Args:
src_dir: The directory of the file to install, relative to the cmake-out
directory. A placeholder %BUILD_TYPE% will be replaced with the build
type for multi-config generators (like Visual Studio) where the build
output is in a subdirectory named after the build type. For single-