Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
300 lines (256 loc) · 10.9 KB
/
Copy pathsetup.py
File metadata and controls
300 lines (256 loc) · 10.9 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
"""setup python file for edsger."""
import os
import platform
import sys
import sysconfig
import numpy as np
from Cython.Build import cythonize
from setuptools import Extension, setup
def is_mingw():
"""Check if we're using MinGW/GCC on Windows."""
if platform.system() != "Windows":
return False
# Check if GCC is mentioned in sys.version (common for MinGW builds)
if "GCC" in sys.version:
return True
# Check platform string for mingw
platform_str = sysconfig.get_platform()
if "mingw" in platform_str.lower():
return True
return False
def is_portable_build():
"""Check if the binaries are built to be distributed.
Such binaries must run on any CPU of the target architecture, so they must
not be tuned for the build machine with -march=native: the 0.1.7 Linux
wheels were built on an AVX-512 machine and crashed at import time
(illegal instruction) on the CPUs without AVX-512.
This is the case of the wheels (cibuildwheel sets CIBUILDWHEEL), of the
conda packages (conda-build and rattler-build set CONDA_BUILD), and of any
build with EDSGER_PORTABLE=1, e.g. by a Linux distribution.
"""
return any(
os.environ.get(name, "0") == "1"
for name in ("CIBUILDWHEEL", "CONDA_BUILD", "EDSGER_PORTABLE")
)
def is_arm64():
"""Check if the target architecture is 64-bit ARM."""
return platform.machine().lower() in ("arm64", "aarch64")
def is_coverage_build():
"""Check if the extensions are built for the coverage of the Cython code."""
return os.environ.get("CYTHON_TRACE", "0") == "1"
# Windows macros for better performance
WINDOWS_MACROS = [
("WIN32_LEAN_AND_MEAN", None), # Exclude rarely-used APIs
("NOMINMAX", None), # Prevent min/max macro conflicts
("_USE_MATH_DEFINES", None), # Enable math constants
("NDEBUG", None), # Disable debug assertions
]
def mingw_flags():
"""Flags of MinGW/GCC on Windows: aggressive, matching the Linux ones."""
print("Building with MinGW/GCC optimizations on Windows (aggressive)")
compile_args = [
"-Ofast", # Maximum optimization with fast-math
"-flto", # Link-time optimization
"-funroll-loops", # Unroll loops for better performance
"-ftree-vectorize", # Enable auto-vectorization
"-fno-semantic-interposition", # Allow more aggressive inlining
]
if not is_portable_build():
# Tune for the CPU of the build machine: local builds only
compile_args += ["-march=native", "-mtune=native"]
link_args = [
"-flto", # Link-time optimization
"-Wl,-O1", # Optimize linker output
]
return compile_args, link_args, WINDOWS_MACROS
def msvc_flags():
"""Flags of MSVC on Windows: aggressive optimizations."""
print("Building with MSVC optimizations on Windows (aggressive)")
compile_args = [
"/O2", # Maximum speed optimization
"/Ob2", # Inline function expansion
"/Oi", # Enable intrinsic functions
"/Ot", # Favor fast code
"/Oy", # Omit frame pointers
"/GL", # Whole program optimization
"/fp:fast", # Fast floating-point model
"/GS-", # Disable security checks for performance
"/Gw", # Optimize global data
"/Qspectre-", # Disable Spectre mitigations for performance
]
if not is_arm64():
# x64 only flags, which cl rejects for ARM64
compile_args.append("/favor:INTEL64") # Optimize for 64-bit Intel/AMD
if not is_portable_build():
# Local builds only: the distributed binaries use the baseline
# instruction set (SSE2), as the 0.1.7 wheels crashed without AVX2
compile_args.append("/arch:AVX2")
link_args = [
"/LTCG", # Link-time code generation
"/OPT:REF", # Eliminate unreferenced functions/data
"/OPT:ICF", # Enable COMDAT folding
]
macros = WINDOWS_MACROS + [("_CRT_SECURE_NO_WARNINGS", None)]
return compile_args, link_args, macros
def is_universal_macos_build():
"""Check if a universal binary (arm64 and x86_64) is built on macOS."""
platform_str = sysconfig.get_platform()
archflags = os.environ.get("ARCHFLAGS", "")
host_platform = os.environ.get("_PYTHON_HOST_PLATFORM", "")
print("macOS build detection:")
print(f" sysconfig.get_platform(): {platform_str}")
print(f" ARCHFLAGS: {archflags or '(not set)'}")
print(f" _PYTHON_HOST_PLATFORM: {host_platform or '(not set)'}")
# sysconfig.get_platform() is the most reliable for pip builds, ARCHFLAGS
# is used by pip/setuptools, _PYTHON_HOST_PLATFORM by cibuildwheel
universal = (
"universal2" in platform_str
or archflags.count("-arch") > 1
or "universal2" in archflags
or "universal2" in host_platform
)
print(f" -> {'Universal' if universal else 'Native'} binary")
return universal
def is_emscripten():
"""Cross-compilation to WebAssembly for Pyodide: platform.system() is the
one of the build machine, the target is in the sysconfig platform."""
targets = (sysconfig.get_platform(), os.environ.get("_PYTHON_HOST_PLATFORM", ""))
return any("emscripten" in target.lower() for target in targets)
def unix_flags(system):
"""Flags of GCC/Clang on Linux and macOS."""
compiler_name = "GCC/Clang" if system == "Linux" else "Clang"
if system == "Darwin" and is_universal_macos_build():
print(f"Building with {compiler_name} optimizations on {system} (universal)")
# No -march=native: incompatible with cross-compilation
return ["-Ofast", "-flto"], ["-flto"], []
compile_args = [
"-Ofast",
"-flto",
"-fno-plt", # Avoid PLT indirection for faster calls
"-fno-semantic-interposition", # Allow more aggressive inlining
"-funroll-loops", # More aggressive loop unrolling
]
link_args = ["-flto"]
if is_portable_build():
print(
f"Building with {compiler_name} optimizations on {system} "
"(portable binary, baseline instruction set)"
)
if system == "Linux":
# The Python of the manylinux images is configured with -g: without
# these flags, the debug information makes the binaries 4 times
# larger (1.2 MB instead of 0.3 MB per module)
compile_args.append("-g0")
link_args.append("-s")
else:
print(f"Building with {compiler_name} optimizations on {system}")
# Tune for the CPU of the build machine: local builds only
compile_args.append("-march=native")
return compile_args, link_args, []
def get_compiler_flags():
"""Get platform and compiler specific optimization flags."""
system = platform.system()
if is_coverage_build():
print("Building with coverage support (CYTHON_TRACE=1)")
if system == "Windows" and not is_mingw():
return ["/Od"], [], []
return ["-O0", "-g"], [], [] # Debug flags for accurate coverage
if is_emscripten():
print("Building for WebAssembly (Pyodide)")
# no LTO or PLT options for the side modules loaded by Pyodide
return ["-O3", "-g0"], [], []
if system == "Windows":
return mingw_flags() if is_mingw() else msvc_flags()
if system in ("Linux", "Darwin"):
return unix_flags(system)
print(f"Building on unknown platform {system}, using conservative optimizations")
return ["-O2"], [], []
# Get platform-specific compiler flags
extra_compile_args, extra_link_args, platform_macros = get_compiler_flags()
# -Ofast implies -ffinite-math-only, with which the glibc headers of the
# manylinux images (2.28) redirect the math functions to their *_finite
# variants, e.g. asin to __asin_finite, which recent glibc versions do not
# export anymore: the A* module, which calls asin for the haversine distance,
# then fails to import. MSVC does not use these flags: see make_extension for
# its /fp:fast flag.
no_finite_math_only = (
["-fno-finite-math-only"]
if any(flag in ("-Ofast", "-ffast-math") for flag in extra_compile_args)
else []
)
# Combine numpy macros with platform-specific macros
# Large Pages / THP support is always enabled
define_macros = [("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")] + platform_macros
define_macros_with_thp = define_macros + [("USE_LARGE_PAGES", None)]
# The Windows large pages allocator enables SeLockMemoryPrivilege (Advapi32)
thp_libraries = ["advapi32"] if platform.system() == "Windows" else []
# The modules with a priority queue use the large pages allocator
THP_MODULES = {
"pq_4ary_dec_0b",
"dijkstra",
"dijkstra_nodec",
"astar",
"bidirectional_dijkstra",
}
MODULES = [
"commons",
"pq_4ary_dec_0b",
"dijkstra",
"dijkstra_nodec",
"spiess_florian",
"star",
"path_tracking",
"bellman_ford",
"bfs",
"dfs",
"components_core",
"kruskal",
"power_iteration",
"astar",
"bidirectional_dijkstra",
]
# A* calls asin, see no_finite_math_only.
# The NaN checks of the power iterations need finite math semantics: under
# -ffinite-math-only, the compiler may assume that x != x is always false
NO_FINITE_MATH_MODULES = {"astar", "power_iteration"}
# The macro of the line tracing of the Cython code, for the coverage
trace_macros = [("CYTHON_TRACE_NOGIL", "1")] if is_coverage_build() else []
def make_extension(name):
"""Extension of the Cython module `name`, with the flags defined above."""
# WebAssembly has no huge pages, and its mmap is emulated with malloc
thp = name in THP_MODULES and not is_emscripten()
compile_args = list(extra_compile_args)
if name in NO_FINITE_MATH_MODULES:
# /fp:fast lets MSVC fold the NaN checks (isfinite, x != x) away
compile_args = [
"/fp:precise" if arg == "/fp:fast" else arg for arg in compile_args
]
compile_args += no_finite_math_only
return Extension(
f"edsger.{name}",
[f"src/edsger/{name}.pyx"],
extra_compile_args=compile_args,
extra_link_args=extra_link_args,
define_macros=(define_macros_with_thp if thp else define_macros) + trace_macros,
libraries=thp_libraries if thp else [],
)
extensions = [make_extension(name) for name in MODULES]
def setup_package():
"""Configure and run the package setup with Cython extensions."""
# The other compiler directives are defined at the top of each .pyx file.
# The modules hold no global mutable state, and the workspaces of the
# kernels refuse a concurrent use: they can run without the GIL on the
# free-threaded builds of CPython.
directives = {"freethreading_compatible": True}
if is_coverage_build():
directives["linetrace"] = True
setup(
ext_modules=cythonize(
extensions,
include_path=["src/edsger/"],
compiler_directives=directives,
),
include_dirs=[np.get_include()],
)
if __name__ == "__main__":
setup_package()