Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
712 lines (636 loc) · 27.3 KB
/
Copy pathsetup.py
File metadata and controls
712 lines (636 loc) · 27.3 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
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
import platform
import shutil
import subprocess
import sys
import time
from importlib.metadata import PackageNotFoundError, distribution
from pathlib import Path
root = Path(__file__).parent.resolve()
sys.path.insert(0, str(root))
from setuptools import setup # noqa: E402
from setuptools.command.build_py import build_py # noqa: E402
from build_utils.build_info import write_build_info # noqa: E402
from build_utils.bundle_vllm import ( # noqa: E402
bundle_vllm_package,
find_prebuilt_extensions,
)
from build_utils.ccache import configure_compiler_cache # noqa: E402
from build_utils.git_proxy import ( # noqa: E402
PROXY_ENV,
candidate_commands,
resolve_proxy,
resolve_stall_s,
)
third_party = Path("third_party")
arch = platform.machine().lower()
def _read_pins():
"""Read third_party/PINS (KEY=VALUE, no parser dependency). Shared with
Makefile.sync so the build and patch-gen pins can't desync."""
pins = {}
pins_path = root / "third_party" / "PINS"
for line in pins_path.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
pins[key.strip()] = value.split("#", 1)[0].strip()
return pins
_PINS = _read_pins()
def _read_requirements(filename, seen=None):
"""Read pip requirements files with local -r includes."""
requirements_dir = root / "requirements"
path = requirements_dir / filename
seen = set() if seen is None else seen
if path in seen:
return []
seen.add(path)
requirements = []
for raw_line in path.read_text().splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if " #" in line:
line = line.split(" #", 1)[0].strip()
if line.startswith("--"):
continue
if line.startswith("-r "):
requirements.extend(_read_requirements(line.split(maxsplit=1)[1], seen))
else:
requirements.append(line)
return requirements
def _runtime_requirements() -> list[str]:
return _read_requirements("common.txt") + _read_requirements(
"vllm_runtime_transitive.txt"
)
# The sdist frontend runs egg_info before sdist. Both commands can use the
# public build-system dependencies and MANIFEST.in without loading Torch.
if sys.argv[1:2] in (["egg_info"], ["sdist"]) and not {
"build",
"build_ext",
"bdist_wheel",
"editable_wheel",
"install",
"develop",
}.intersection(sys.argv[2:]):
setup(include_package_data=False, install_requires=_runtime_requirements())
sys.exit(0)
# isort: off
# Activate MUSA patches before importing Torch's extension machinery.
import torchada # noqa: E402, F401
from torch.utils.cpp_extension import BuildExtension, CUDAExtension # noqa: E402
# isort: on
configure_compiler_cache(root)
# Detect editable install (pip install -e .) or develop mode
_is_editable_install = (
"develop" in sys.argv
or "editable_wheel" in sys.argv
or any("--editable" in arg or "-e" in arg for arg in sys.argv)
)
if _is_editable_install:
Path("vllm").mkdir(exist_ok=True)
def develop_dynamic_library(package_name, source_dir="./", target_override=None):
"""Copy the built vllm.* .so into the editable vLLM clone -- setuptools writes
them to repo/vllm/ or build/lib*/vllm/, not the clone, so without this
`import vllm._C` breaks. No-op until the clone + .so exist."""
try:
if target_override is not None:
target_dir = Path(target_override)
else:
target_dir = Path(distribution(package_name).locate_file(package_name))
if not target_dir.is_dir():
return
src_dir = Path(source_dir)
candidates = sorted(
(
d
for d in (src_dir / "vllm", *src_dir.glob("build/lib*/vllm"))
if d.is_dir() and d.resolve() != target_dir.resolve()
),
key=lambda d: d.stat().st_mtime,
reverse=True,
)
for src in candidates:
sos = list(src.glob("*.so"))
if sos:
for so in sos:
shutil.copy2(so, target_dir)
break
except PackageNotFoundError:
print(f"vLLM is not installed '{package_name}'")
class _RepoInfo:
"""Configuration for a third-party git repository."""
def __init__(self, name, git_repository, git_tag):
self.name = name
self.git_repository = git_repository
self.git_tag = git_tag
self.source_dir = third_party / name
_VLLM_REPO = _RepoInfo(
name="vllm",
git_repository="https://github.com/vllm-project/vllm.git",
git_tag=_PINS.get("VLLM_COMMIT", _PINS["VLLM_TAG"]),
)
_FLASHINFER_REPO = _RepoInfo(
name="flashinfer",
git_repository="https://github.com/flashinfer-ai/flashinfer.git",
git_tag=_PINS["FLASHINFER_COMMIT"],
)
INCLUDE_DIRS = [
root / "csrc",
root / _VLLM_REPO.source_dir / "csrc",
root / _FLASHINFER_REPO.source_dir / "include",
root / _FLASHINFER_REPO.source_dir / "csrc",
]
# =============================================================================
# C/C++ Source Files for Extension Modules
# =============================================================================
VLLM_CSRC_SOURCES = [
# vllm._C carries the regular-ABI CPU-to-device view op; the other _C ops
# are registered by _C_stable_libtorch.
str(_VLLM_REPO.source_dir / "csrc/musa_cuda_view.cu"),
str(_VLLM_REPO.source_dir / "csrc/musa_torch_bindings.cpp"),
]
VLLM_STABLE_CSRC_SOURCES = [
str(_VLLM_REPO.source_dir / "csrc/torch_bindings.cpp"),
# The stable bindings register _C_cuda_utils, so its implementation is
# linked into _C_stable_libtorch as upstream does.
str(_VLLM_REPO.source_dir / "csrc/cuda_utils_kernels.cu"),
# gptq q_gemm: GPTQ is unused by the FP8/bf16 model matrix and its CUDA half2
# path does not port cleanly to mcc; its gptq_gemm/gptq_shuffle impls are
# dropped from the stable bindings to match.
str(_VLLM_REPO.source_dir / "csrc/activation_kernels.cu"),
str(_VLLM_REPO.source_dir / "csrc/layernorm_kernels.cu"),
str(_VLLM_REPO.source_dir / "csrc/pos_encoding_kernels.cu"),
# FP8 and INT8 per-token-group quant kernels.
str(_VLLM_REPO.source_dir / "csrc/quantization/w8a8/fp8/per_token_group_quant.cu"),
# Scaled FP8/INT8 quant kernels (dynamic_scaled_fp8_quant,
# dynamic_per_token_scaled_fp8_quant, static/dynamic_scaled_int8_quant): the
# dynamic paths back _custom_ops.scaled_fp8_quant / scaled_int8_quant, used by
# FP8/INT8 activation quantization. static_scaled_fp8_quant is also built here
# but stays CUDA-only (its int[] group_shape arg is unboxable on the stable ABI).
str(_VLLM_REPO.source_dir / "csrc/quantization/w8a8/fp8/common.cu"),
str(_VLLM_REPO.source_dir / "csrc/quantization/w8a8/int8/scaled_quant.cu"),
str(_VLLM_REPO.source_dir / "csrc/mamba/selective_scan_fwd.cu"),
str(_VLLM_REPO.source_dir / "csrc/cache_kernels.cu"),
str(_VLLM_REPO.source_dir / "csrc/cache_kernels_fused.cu"),
str(_VLLM_REPO.source_dir / "csrc/musa_cache_ops_reg.cu"),
str(_VLLM_REPO.source_dir / "csrc/attention/merge_attn_states.cu"),
str(_VLLM_REPO.source_dir / "csrc/sampler.cu"),
str(_VLLM_REPO.source_dir / "csrc/topk.cu"),
str(
_VLLM_REPO.source_dir
/ "csrc/quantization/fused_kernels/fused_silu_mul_block_quant.cu"
),
# Layernorm+quant fusion kernels (rms_norm_static_fp8_quant,
# fused_add_rms_norm_static_fp8_quant, rms_norm_dynamic_per_token_quant,
# rms_norm_per_block_quant): emitted by the rms_quant_fusion compile pass.
str(_VLLM_REPO.source_dir / "csrc/layernorm_quant_kernels.cu"),
str(
_VLLM_REPO.source_dir
/ "csrc/quantization/fused_kernels/fused_layernorm_dynamic_per_token_quant.cu"
),
str(_VLLM_REPO.source_dir / "csrc/quantization/activation_kernels.cu"),
str(_VLLM_REPO.source_dir / "csrc/custom_all_reduce.cu"),
str(_VLLM_REPO.source_dir / "csrc/minimax_reduce_rms_kernel.cu"),
]
VLLM_MUSA_CSRC_SOURCES = [
"csrc/musa/torch_bindings.cpp",
"csrc/musa/gemv.mu",
"csrc/musa/fused_add_rmsnorm.mu",
"csrc/musa/cache_kernels.mu",
"csrc/musa/attention/deepseek_v4_cache_store.mu",
"csrc/musa/attention/deepseek_v4_c4_indexer_compressor.mu",
"csrc/musa/attention/deepseek_v4_sparse_compressor.mu",
"csrc/musa/attention/deepseek_v4_fused_qkv_rmsnorm.mu",
"csrc/musa/attention/deepseek_v4_cache_utils.mu",
"csrc/musa/attention/deepseek_v4_indexer_topk.mu",
"csrc/musa/attention/deepseek_v4_sparse_indexer_topk.mu",
"csrc/musa/attention/glm52_indexer_topk.mu",
"csrc/musa/attention/deepseek_v4_sparse_flashmla.mu",
"csrc/musa/attention/deepseek_v4_inv_rope_fp8_quant.mu",
"csrc/musa/mhc/deepseek_v4_mhc_pre.mu",
"csrc/musa/moe/deepseek_v4_topk_softplus_sqrt.mu",
"csrc/musa/quantization/silu_and_mul_per_token_group_fp8_quant.cu",
"csrc/musa/quantization/fused_add_rms_norm_per_token_group_fp8_quant.cu",
"csrc/musa/quantization/per_token_group_quant_8bit_vec.cu",
"csrc/musa/sampler.mu",
"csrc/musa/min_p_sampler.mu",
"csrc/musa/top_k_renorm.mu",
"csrc/musa/top_k_mask_logits.mu",
"csrc/musa/top_p_mask_logits.mu",
str(_FLASHINFER_REPO.source_dir / "csrc/norm.cu"),
str(_FLASHINFER_REPO.source_dir / "csrc/renorm.cu"),
str(_FLASHINFER_REPO.source_dir / "csrc/sampling.cu"),
]
VLLM_MOE_CSRC_SOURCES = [
# On MUSA the MoE kernels are built as a regular (at::Tensor) extension: the
# stable path needs torch::stable::sum_out with an int[] dim that torch_musa
# 2.9 cannot box, so the kernels use the ATen API, the bindings are a regular
# TORCH_LIBRARY, and moe_ops.h is at::Tensor.
str(_VLLM_REPO.source_dir / "csrc/moe/moe_align_sum_kernels.cu"),
str(_VLLM_REPO.source_dir / "csrc/moe/topk_softmax_kernels.cu"),
str(_VLLM_REPO.source_dir / "csrc/moe/topk_softplus_sqrt_kernels.cu"),
str(_VLLM_REPO.source_dir / "csrc/moe/torch_bindings.cpp"),
]
# =============================================================================
# Compiler and Linker Configuration
# =============================================================================
CXX_FLAGS = ["force_mcc"]
LINK_LIBRARIES = ["c10", "torch", "torch_python", "musart"]
EXTRA_LINK_ARGS = [
"-Wl,-rpath,$ORIGIN/../../torch/lib",
f"-L/usr/lib/{arch}-linux-gnu",
"-lmublasLt",
]
# `arch` is the host CPU architecture in this file.
from torchada import arch as musa_arch # noqa: E402
# MTGPU_TARGET, then TORCH_MUSA_ARCH_LIST, then the visible devices, then mp_31.
# No device check: a build may target an arch other than the build host's.
MUSA_ARCHS = musa_arch.target_archs(env=("MTGPU_TARGET", "TORCH_MUSA_ARCH_LIST"))
if len(MUSA_ARCHS) != 1:
print(
"vllm-musa builds for one MUSA arch per build; "
f"got {[a.name for a in MUSA_ARCHS]}"
)
sys.exit(1)
MUSA_ARCH = MUSA_ARCHS[0]
if MUSA_ARCH not in musa_arch.ARCHS:
print(
f"Unsupported GPU architecture '{MUSA_ARCH.name}'. "
f"Expected one of: {[a.name for a in musa_arch.ARCHS]}"
)
sys.exit(1)
print(f"Building for MUSA arch {MUSA_ARCH.name}")
# torch_musa's MUSAExtension takes --offload-arch from TORCH_MUSA_ARCH_LIST.
os.environ["TORCH_MUSA_ARCH_LIST"] = musa_arch.torch_arch_list(MUSA_ARCHS)
MCC_FLAGS = [
"-DNDEBUG",
"-O3",
"-fPIC",
"-std=c++17",
"-x",
"musa",
"-mtgpu",
"-Od3",
"-ffast-math",
"-fmusa-flush-denormals-to-zero",
"-fno-strict-aliasing",
"-fno-signed-zeros",
"-DUSE_MUSA",
]
if MUSA_ARCH.fp8:
MCC_FLAGS.append("-DENABLE_FP8")
COMPILE_ARGS = {
"mcc": MCC_FLAGS,
"cxx": CXX_FLAGS,
}
# The libtorch-stable kernels need torchada's stable-ABI compat: force-include
# the TORCH_BOX boxer header, define CUDA_VERSION=0 (the sm100/Blackwell fast
# paths compile out on MUSA), and link torch_cpu (the AOTI stable-ABI shims live
# in libtorch_cpu.so). torchada's include_paths() auto-appends the stable_compat
# include dir, and its import patches torch_musa's stable::Tensor accessors.
from torchada.utils.cpp_extension import ( # noqa: E402
stable_compat_box_header as _ta_stable_box,
)
from torchada.utils.cpp_extension import ( # noqa: E402
stable_compat_include_dir as _ta_stable_inc,
)
_STABLE_BOX_HEADER = _ta_stable_box()
# Explicitly add torchada's stable_compat include dir (the include_paths()
# auto-append does not reach the torch_musa MUSAExtension compile path).
STABLE_INCLUDE_DIRS = INCLUDE_DIRS + [_ta_stable_inc()]
# Shared quantization headers use TORCH_CHECK, which torch 2.13's stable headers
# do not provide; STD_TORCH_CHECK is the stable-ABI spelling.
_STABLE_TORCH_CHECK = "-DTORCH_CHECK=STD_TORCH_CHECK"
STABLE_COMPILE_ARGS = {
"mcc": MCC_FLAGS
+ ["-DCUDA_VERSION=0", _STABLE_TORCH_CHECK, "-include", _STABLE_BOX_HEADER],
"cxx": CXX_FLAGS + [_STABLE_TORCH_CHECK, "-include", _STABLE_BOX_HEADER],
}
STABLE_LINK_LIBRARIES = LINK_LIBRARIES + ["torch_cpu"]
# =============================================================================
# Extension Modules
# =============================================================================
EXT_MODULES = [
CUDAExtension(
name="vllm._C",
sources=VLLM_CSRC_SOURCES,
include_dirs=INCLUDE_DIRS,
extra_compile_args=COMPILE_ARGS,
libraries=LINK_LIBRARIES,
extra_link_args=EXTRA_LINK_ARGS,
py_limited_api=False,
),
CUDAExtension(
name="vllm._C_stable_libtorch",
sources=VLLM_STABLE_CSRC_SOURCES,
include_dirs=STABLE_INCLUDE_DIRS,
extra_compile_args=STABLE_COMPILE_ARGS,
libraries=STABLE_LINK_LIBRARIES,
extra_link_args=EXTRA_LINK_ARGS,
py_limited_api=False,
),
CUDAExtension(
name="vllm_musa._C",
sources=VLLM_MUSA_CSRC_SOURCES,
include_dirs=INCLUDE_DIRS,
extra_compile_args=COMPILE_ARGS,
libraries=LINK_LIBRARIES,
extra_link_args=EXTRA_LINK_ARGS,
py_limited_api=False,
),
CUDAExtension(
name="vllm._moe_C",
sources=VLLM_MOE_CSRC_SOURCES,
include_dirs=INCLUDE_DIRS,
extra_compile_args=COMPILE_ARGS,
libraries=LINK_LIBRARIES,
extra_link_args=EXTRA_LINK_ARGS,
py_limited_api=False,
),
]
class _CustomBuildExt(BuildExtension):
"""Custom build extension that clones third-party repositories before building."""
_SLOW_CONNECT_FAIL_S = 120
_third_party_prepared = False
def build_extensions(self):
if os.environ.get("VLLM_MUSA_REUSE_PREBUILT") == "1":
build_lib = Path(self.build_lib)
extension_paths = [
Path(self.get_ext_fullpath(extension.name)).relative_to(build_lib)
for extension in self.extensions
]
sources = find_prebuilt_extensions(
extension_paths, (root / _VLLM_REPO.source_dir, root)
)
print("Reusing native extensions from the prepared source tree")
for extension_path, source in sources.items():
output = build_lib / extension_path
output.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, output)
else:
super().build_extensions()
package_dirs = {root / "vllm_musa"}
if self.build_lib and (Path(self.build_lib) / "vllm_musa").is_dir():
package_dirs.add(Path(self.build_lib) / "vllm_musa")
for package_dir in package_dirs:
path = write_build_info(package_dir, [a.capability for a in MUSA_ARCHS])
print(f"Recorded MUSA arch {MUSA_ARCH.name} in {path}")
@staticmethod
def _git_dir_bytes(cwd):
"""Bytes held by the checkout's git directory, 0 without one."""
total = 0
for dirpath, _dirnames, filenames in os.walk(Path(cwd or ".") / ".git"):
for name in filenames:
try:
total += os.path.getsize(os.path.join(dirpath, name))
except OSError:
continue
return total
@staticmethod
def _retry_git_call(cmd, cwd, attempts, delay_s, slow_fail_s=None):
"""Run one git command variant, retrying transient failures."""
if slow_fail_s is None:
slow_fail_s = _CustomBuildExt._SLOW_CONNECT_FAIL_S
for attempt in range(1, attempts + 1):
started = time.monotonic()
received = _CustomBuildExt._git_dir_bytes(cwd)
try:
subprocess.check_call(cmd, cwd=cwd)
return
except subprocess.CalledProcessError:
if attempt == attempts:
raise
if (
time.monotonic() - started >= slow_fail_s
and _CustomBuildExt._git_dir_bytes(cwd) == received
):
raise
sleep_s = delay_s * attempt
print(
f"Git command failed (attempt {attempt}/{attempts}); "
f"retrying in {sleep_s}s: {' '.join(map(str, cmd))}",
flush=True,
)
time.sleep(sleep_s)
@staticmethod
def _mirror_attempts(attempts):
"""Attempts the mirror gets before the direct fallback runs."""
# Enough to ride out a flaky link (a handshake that fails now may work on
# the next try), but not the whole budget: a mirror that is really down
# must not delay the direct fetch for the entire retry schedule.
return max(2, attempts // 2)
@staticmethod
def _git_check_call_with_retries(cmd, cwd=None):
"""Run a network git command, through the GitHub mirror when enabled.
The mirror is tried first and a direct connection last, so a mirror that
fails costs time instead of breaking the build. Set
``VLLM_MUSA_GIT_PROXY=0`` to skip the mirror. A mirrored attempt carries
git's low-speed guard (``VLLM_MUSA_GIT_PROXY_STALL_S``), so a mirror that
accepts the connection and then stops transferring fails the attempt
instead of hanging the build; the direct attempt keeps no guard, like any
plain ``git fetch``. The mirror gets half of the retry budget, because a
link that drops one connection often serves the next one. An attempt that
fails after the whole stall window without receiving anything is not
retried: an unreachable host answers nothing the second time either.
"""
attempts = max(1, int(os.environ.get("VLLM_MUSA_GIT_RETRY_ATTEMPTS") or "8"))
delay_s = max(0, int(os.environ.get("VLLM_MUSA_GIT_RETRY_DELAY_S") or "10"))
stall_s = resolve_stall_s()
candidates = candidate_commands(cmd, stall_s=str(stall_s))
for candidate in candidates[:-1]:
try:
_CustomBuildExt._retry_git_call(
candidate,
cwd,
_CustomBuildExt._mirror_attempts(attempts),
delay_s,
slow_fail_s=stall_s or _CustomBuildExt._SLOW_CONNECT_FAIL_S,
)
return
except subprocess.CalledProcessError:
print(
f"Git command failed through {resolve_proxy()}; retrying "
f"directly (set {PROXY_ENV}=0 to skip the mirror).",
flush=True,
)
_CustomBuildExt._retry_git_call(candidates[-1], cwd, attempts, delay_s)
@staticmethod
def _clone_and_checkout(repo_path, repo_url, git_tag):
"""Materialize a repository at exactly ``git_tag``, without its history.
Both pins are immutable commits, so fetching that one commit is all the
build needs. A full clone transfers the whole history -- several times
the size of the commit being built -- and that transfer is what stalls or
dies first on a slow link.
"""
repo_path.parent.mkdir(exist_ok=True)
if not (repo_path / ".git").exists():
if repo_path.exists():
# git init in a populated directory would make every file
# untracked, and the `git clean -fdx` below would delete them.
raise RuntimeError(
f"{repo_path} exists but is not a git checkout: remove it, or "
"stage the pinned tree and build with SKIP_THIRD_PARTY=1"
)
repo_path.mkdir()
subprocess.check_call(["git", "init", "-q", str(repo_path)])
subprocess.check_call(
["git", "remote", "add", "origin", repo_url], cwd=repo_path
)
# Skip the network entirely when the pin is already in the object store.
if subprocess.call(
["git", "cat-file", "-e", f"{git_tag}^{{commit}}"],
cwd=repo_path,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
):
_CustomBuildExt._git_check_call_with_retries(
["git", "fetch", "--depth", "1", "origin", git_tag],
cwd=repo_path,
)
subprocess.check_call(
["git", "checkout", "-f", "--detach", git_tag], cwd=repo_path
)
subprocess.check_call(["git", "reset", "--hard", git_tag], cwd=repo_path)
subprocess.check_call(["git", "clean", "-fdx"], cwd=repo_path)
@staticmethod
def _install_vllm(repo_path):
"""Install the cloned + patched vLLM (editable) against the existing torch."""
source_dir = Path(repo_path)
subprocess.check_call(
[sys.executable, "tools/use_existing_torch.py"], cwd=source_dir
)
# Keep the editable distribution on the same dependency policy as the wheel.
(source_dir / "requirements" / "common.txt").write_text(
"\n".join(_runtime_requirements()) + "\n", encoding="utf-8"
)
env = os.environ.copy()
env["VLLM_TARGET_DEVICE"] = "empty"
# The exact upstream release commit is pinned in third_party/PINS, but
# its local Git object set may not contain the corresponding tag.
# Always provide the pinned release version so setuptools-scm does not
# derive a stale development version from the nearest available tag.
env.setdefault("VLLM_VERSION_OVERRIDE", _PINS["VLLM_TAG"].lstrip("v"))
# always editable; compat (path-based .pth) -- the default PEP 660 finder
# mis-resolves vLLM's submodules and loses to a system vLLM.
vllm_install_cmd = [
sys.executable,
"-m",
"pip",
"install",
"-e",
str(source_dir),
"--config-settings",
"editable_mode=compat",
"--no-build-isolation",
# MUSA: install against the in-container torch_musa. Without --no-deps
# pip resolves transitive deps (compressed-tensors -> torch>=2.10) and
# downloads the CUDA torch wheel, clobbering torch_musa.
"--no-deps",
"-v",
]
subprocess.check_call(
[
sys.executable,
"-m",
"pip",
"install",
"-r",
str(source_dir / "requirements" / "build" / "cuda.txt"),
]
)
subprocess.check_call(vllm_install_cmd, env=env)
@staticmethod
def _apply_musa_patch_series(repo_path):
"""Apply the vLLM-MUSA diff series to the clone at build time (the only
source-patch mechanism). ``strict`` fails loudly on drift -- regenerate
via ``make -f Makefile.sync``."""
if os.environ.get("VLLM_MUSA_NO_BUILD_PATCH", "0") == "1":
return
repo = Path(repo_path)
series = Path(root) / "vllm_musa" / "patches" / "series"
if not repo.is_dir() or not series.is_dir():
return
import importlib.util as _ilu
ba_path = Path(root) / "vllm_musa" / "patches" / "build_apply.py"
spec = _ilu.spec_from_file_location("_musa_build_apply", ba_path)
ba = _ilu.module_from_spec(spec)
spec.loader.exec_module(ba)
for name, status in ba.apply_patch_series(repo, series, strict=True):
print(f"MUSA build patch: {status:16} {name}")
@classmethod
def prepare_third_party(cls):
"""Materialize the exact patched sources consumed by every build path."""
if cls._third_party_prepared:
return
if os.environ.get("VLLM_MUSA_REUSE_PREBUILT") == "1":
# This tree was already patched and compiled by the source stage.
# Later patches can overlap earlier hunks, so replaying the series
# on the final tree is not a valid substitute for preparing it once.
for repo in (_VLLM_REPO, _FLASHINFER_REPO):
if not repo.source_dir.is_dir():
raise RuntimeError(
f"missing prepared source tree: {repo.source_dir}"
)
cls._third_party_prepared = True
return
if os.environ.get("SKIP_THIRD_PARTY") == "1":
print("Using prepared third-party source trees")
else:
proxy = resolve_proxy()
via = f" through {proxy}" if proxy else ""
print(f"Fetching pinned third-party sources{via}...")
cls._clone_and_checkout(
_VLLM_REPO.source_dir,
_VLLM_REPO.git_repository,
_VLLM_REPO.git_tag,
)
cls._clone_and_checkout(
_FLASHINFER_REPO.source_dir,
_FLASHINFER_REPO.git_repository,
_FLASHINFER_REPO.git_tag,
)
print("Third-party repositories ready.")
# Patch the clone before either copying it into a wheel or exposing it
# through the existing editable development install.
cls._apply_musa_patch_series(_VLLM_REPO.source_dir)
cls._third_party_prepared = True
def run(self):
self.prepare_third_party()
if _is_editable_install:
self._install_vllm(_VLLM_REPO.source_dir)
super().run()
class _CustomBuildPy(build_py):
"""Bundle the pinned, patched upstream vLLM package in non-editable wheels."""
def run(self):
super().run()
if _is_editable_install:
return
_CustomBuildExt.prepare_third_party()
repo = root / _VLLM_REPO.source_dir
source = repo / "vllm"
destination = Path(self.build_lib) / "vllm"
result = bundle_vllm_package(
source, destination, tag=_PINS["VLLM_TAG"], revision=_PINS["VLLM_COMMIT"]
)
print(
"Bundled patched vLLM package: "
f"files={result.files} metadata_rewrites={result.metadata_rewrites}"
)
setup(
ext_modules=EXT_MODULES,
cmdclass={
"build_ext": _CustomBuildExt.with_options(use_ninja=True),
"build_py": _CustomBuildPy,
},
include_package_data=False,
# Keep the default wheel installable from public indexes. Hardware-private
# wheels are an explicit extra because torch_musa, MATE, and FlashInfer
# must come from the matching MUSA index.
install_requires=_runtime_requirements(),
)
# Place built vllm.* extensions into the editable vLLM checkout.
if _is_editable_install:
develop_dynamic_library("vllm", target_override=_VLLM_REPO.source_dir / "vllm")