forked from eugr/spark-vllm-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-recipe.py
More file actions
executable file
·1467 lines (1265 loc) · 51.3 KB
/
Copy pathrun-recipe.py
File metadata and controls
executable file
·1467 lines (1265 loc) · 51.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
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
"""
run-recipe.py - One-click model deployment using YAML recipes
This script provides a high-level interface for deploying models with
pre-configured settings. It handles:
- Model download from HuggingFace (optional)
- Container building and distribution to worker nodes
- Mod application
- Launch script generation
- Both solo (single node) and cluster deployments
Usage:
./run-recipe.py recipes/glm-4.7-nvfp4.yaml
./run-recipe.py glm-4.7-nvfp4 --port 9000 --solo
./run-recipe.py minimax-m2-awq --setup # Full setup: build + download + run
./run-recipe.py --list
================================================================================
ARCHITECTURE OVERVIEW (for developers extending this script)
================================================================================
DEPLOYMENT PIPELINE:
┌─────────────────────────────────────────────────────────────────────────────┐
│ CLI Args → Load Recipe → Resolve Nodes → Build → Download → Run │
└─────────────────────────────────────────────────────────────────────────┘
KEY ABSTRACTIONS:
- Recipe (YAML): Declarative model configuration (see load_recipe docstring)
- Phases: Build, Download, Run - each can run independently (--build-only, etc.)
- Nodes: Head (first) + Workers (rest) - images/models copied to workers
EXTENSION POINTS:
1. ADD NEW RECIPE FIELDS:
- Update load_recipe() to validate/set defaults
- Use the field in generate_launch_script() or main()
- Document in recipe YAML schema below
2. ADD NEW CLI OPTIONS:
- Add to appropriate argument group in main()
- Handle in the corresponding phase (build/download/run)
- Pass to generate_launch_script() via overrides dict if needed
3. ADD NEW DEPLOYMENT PHASES:
- Follow the pattern: check if needed → dry-run print → execute
- Insert between existing phases in main()
- Add corresponding --phase-only flag
4. SUPPORT NEW MODEL SOURCES:
- Add detection logic in download_model() or check_model_exists()
- Create new download script or handle inline
5. SUPPORT NEW CONTAINER RUNTIMES:
- Modify check_image_exists() and build_image()
- May need to update launch-cluster.sh as well
RECIPE YAML SCHEMA:
name: str # Required: Human-readable name
recipe_version: str # Required: Recipe schema version (e.g., '1'). Used by run-recipe.py
# to check compatibility and available features.
container: str # Required: Docker image tag
command: str # Required: vLLM serve command with {placeholders}
description: str # Optional: Brief description
model: str # Optional: HuggingFace model ID for --setup
mods: list[str] # Optional: Mod directories to apply
defaults: dict # Optional: Default values for command placeholders
env: dict # Optional: Environment variables
build_args: list[str] # Optional: Args for build-and-copy.sh
cluster_only: bool # Optional: Require cluster mode (default: false)
solo_only: bool # Optional: Require solo mode (default: false)
RECIPE VERSION HISTORY:
Version 1 (default): Initial schema with all fields above supported.
RELATED FILES:
- run-recipe.sh: Bash wrapper that ensures Python deps are installed
- recipes/*.yaml: Recipe definitions
- examples/: Example launch scripts for direct use with launch-cluster.sh
- launch-cluster.sh: Low-level container orchestration
- build-and-copy.sh: Docker build and distribution
- hf-download.sh: HuggingFace model download and sync
- autodiscover.sh: Network topology detection
"""
import argparse
import os
import re
import subprocess
import shlex
import sys
import tempfile
from pathlib import Path
from typing import Any
try:
import yaml
except ImportError:
print("Error: PyYAML is required. Install with: pip install pyyaml")
sys.exit(1)
SCRIPT_DIR = Path(__file__).parent.resolve()
RECIPES_DIR = SCRIPT_DIR / "recipes"
LAUNCH_SCRIPT = SCRIPT_DIR / "launch-cluster.sh"
BUILD_SCRIPT = SCRIPT_DIR / "build-and-copy.sh"
DOWNLOAD_SCRIPT = SCRIPT_DIR / "hf-download.sh"
AUTODISCOVER_SCRIPT = SCRIPT_DIR / "autodiscover.sh"
ENV_FILE = None # Will be set from CLI argument or default
DISTRIBUTED_EXECUTOR_RE = re.compile(
r"--distributed-executor-backend(?:=|\s+)\S+"
)
def strip_distributed_executor_backend(command: str) -> str:
"""Remove vLLM distributed executor backend flags from a command."""
command = DISTRIBUTED_EXECUTOR_RE.sub("", command)
lines = command.split("\n")
filtered_lines = [line for line in lines if line.strip() not in ("", "\\")]
return "\n".join(filtered_lines)
def ensure_ray_backend(command: str) -> str:
"""Append the Ray executor backend for vLLM serve commands that omit it."""
if "vllm serve" not in command:
return command
if DISTRIBUTED_EXECUTOR_RE.search(command):
return command
return command.rstrip() + " --distributed-executor-backend ray"
def load_recipe(recipe_path: Path) -> dict[str, Any]:
"""
Load and validate a recipe YAML file.
This function handles recipe resolution from multiple locations and validates
required fields. Recipes are the core configuration format for deployments.
EXTENSIBILITY:
- To add new required fields: Add to the 'required' list below
- To add new optional fields with defaults: Add to the setdefault() calls at the end
- Recipe search order: exact path -> recipes/ dir -> with .yaml -> with .yml
RECIPE SCHEMA:
name (str, required): Human-readable name for the recipe
recipe_version (str, required): Schema version for compatibility checking.
Used by run-recipe.py to determine which features are available.
Current version: '1'. Bump when adding new recipe fields.
container (str, required): Docker image tag to use (e.g., 'vllm-node-mxfp4')
command (str, required): vLLM serve command template with {placeholders}
description (str, optional): Brief description shown in --list
model (str, optional): HuggingFace model ID for --setup downloads
mods (list[str], optional): List of mod directories to apply (e.g., 'mods/fix-glm')
defaults (dict, optional): Default values for command placeholders
env (dict, optional): Environment variables to export before running
build_args (list[str], optional): Extra args for build-and-copy.sh (e.g., ['-f', 'Dockerfile.mxfp4'])
cluster_only (bool, optional): If True, recipe cannot run in solo mode
solo_only (bool, optional): If True, recipe cannot run in cluster mode
Args:
recipe_path: Path object pointing to YAML file or just recipe name
Returns:
Validated recipe dictionary with all fields populated (defaults applied)
Raises:
SystemExit: If recipe not found or validation fails
"""
if not recipe_path.exists():
# Try candidates in order: add extension to original path first,
# then fall back to flat recipes/ directory (for bare recipe names)
candidates = [
Path(str(recipe_path) + ".yaml"),
Path(str(recipe_path) + ".yml"),
RECIPES_DIR / recipe_path.name,
RECIPES_DIR / f"{recipe_path.name}.yaml",
RECIPES_DIR / f"{recipe_path.name}.yml",
RECIPES_DIR / f"{recipe_path.stem}.yaml",
]
for candidate in candidates:
if candidate.exists():
recipe_path = candidate
break
else:
print(f"Error: Recipe not found: {recipe_path}")
print(f"Searched in: {recipe_path}, {RECIPES_DIR}")
sys.exit(1)
with open(recipe_path) as f:
recipe = yaml.safe_load(f)
# Validate required fields
required = ["name", "recipe_version", "container", "command"]
for field in required:
if field not in recipe:
print(f"Error: Recipe missing required field: {field}")
sys.exit(1)
# Set defaults for optional fields
recipe.setdefault("description", "")
recipe.setdefault("model", None)
recipe.setdefault("mods", [])
recipe.setdefault("defaults", {})
recipe.setdefault("env", {})
recipe.setdefault("cluster_only", False)
recipe.setdefault("solo_only", False)
# Validate recipe version compatibility
# EXTENSIBILITY: When adding new schema versions, update SUPPORTED_VERSIONS
# and add migration/compatibility logic below
SUPPORTED_VERSIONS = ["1"]
recipe_ver = str(recipe["recipe_version"])
if recipe_ver not in SUPPORTED_VERSIONS:
print(
f"Warning: Recipe uses schema version '{recipe_ver}', but this run-recipe.py supports: {SUPPORTED_VERSIONS}"
)
print("Some features may not work correctly. Consider updating run-recipe.py.")
return recipe
def list_recipes() -> None:
"""
List all available recipes with their metadata.
Scans the recipes/ directory for YAML files and displays key information.
Used by the --list CLI option.
EXTENSIBILITY:
- To show additional fields: Add them to the print statements in the loop
- To support different output formats (e.g., JSON): Add a format parameter
- Recipe directory is defined by RECIPES_DIR constant at module level
"""
if not RECIPES_DIR.exists():
print("No recipes directory found.")
return
recipes = sorted(RECIPES_DIR.glob("*.yaml"))
if not recipes:
print("No recipes found in recipes/ directory.")
return
print("Available recipes:\n")
for recipe_path in recipes:
try:
recipe = load_recipe(recipe_path)
name = recipe.get("name", recipe_path.stem)
recipe_version = recipe.get("recipe_version", "1")
desc = recipe.get("description", "")
container = recipe.get("container", "vllm-node")
build_args = recipe.get("build_args", [])
model = recipe.get("model", "")
mods = recipe.get("mods", [])
cluster_only = recipe.get("cluster_only", False)
solo_only = recipe.get("solo_only", False)
print(f" {recipe_path.name}")
print(f" Name: {name}")
if desc:
print(f" Description: {desc}")
if model:
print(f" Model: {model}")
if cluster_only:
print(" Cluster only: Yes")
if solo_only:
print(" Solo only: Yes")
print(f" Container: {container}")
if build_args:
print(f" Build args: {' '.join(build_args)}")
if mods:
print(f" Mods: {', '.join(mods)}")
print()
except Exception as e:
print(f" {recipe_path.name} (error loading: {e})")
print()
def check_image_exists(image: str, host: str | None = None) -> bool:
"""
Check if a Docker image exists locally or on a remote host.
Used to avoid redundant builds and to verify cluster nodes have the image.
EXTENSIBILITY:
- To support other container runtimes (podman): Modify the docker command
- To add image version/digest checking: Parse 'docker image inspect' JSON output
- For custom SSH options: Modify the ssh command array
Args:
image: Docker image tag to check (e.g., 'vllm-node-mxfp4')
host: Optional remote hostname/IP. If None, checks locally.
Returns:
True if image exists, False otherwise
"""
if host:
result = subprocess.run(
[
"ssh",
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=no",
host,
f"docker image inspect '{image}'",
],
capture_output=True,
)
else:
result = subprocess.run(
["docker", "image", "inspect", image], capture_output=True
)
return result.returncode == 0
def build_image(
image: str, copy_to: list[str] | None = None, build_args: list[str] | None = None
) -> bool:
"""
Build the container image using build-and-copy.sh.
Delegates to the build-and-copy.sh script which handles multi-stage builds,
cache optimization, and distribution to worker nodes.
EXTENSIBILITY:
- To add new build options: Add them to build_args in the recipe's build_args field
- To support different Dockerfiles: Use build_args = ['-f', 'Dockerfile.custom']
- To add build-time secrets: Modify cmd array to include --secret flags
- To add progress callbacks: Capture subprocess output line-by-line
BUILD_ARGS EXAMPLES:
['-f', 'Dockerfile.mxfp4'] - Use alternate Dockerfile
['--no-cache'] - Force full rebuild
['--build-arg', 'VAR=value'] - Pass build-time variables
Args:
image: Target image tag
copy_to: List of worker hostnames to copy image to after build
build_args: Extra arguments passed to build-and-copy.sh
Returns:
True if build (and copy) succeeded, False otherwise
"""
if not BUILD_SCRIPT.exists():
print(f"Error: Build script not found: {BUILD_SCRIPT}")
return False
cmd = [str(BUILD_SCRIPT), "-t", image]
if build_args:
cmd.extend(build_args)
if copy_to:
cmd.extend(["--copy-to", ",".join(copy_to), "--copy-parallel"])
print(f"Building image '{image}'...")
if build_args:
print(f"Build args: {' '.join(build_args)}")
if copy_to:
print(f"Will copy to: {', '.join(copy_to)}")
result = subprocess.run(cmd)
return result.returncode == 0
def download_model(model: str, copy_to: list[str] | None = None) -> bool:
"""
Download model from HuggingFace using hf-download.sh.
Delegates to hf-download.sh which handles HF authentication, caching,
and rsync to worker nodes.
EXTENSIBILITY:
- To support other model sources: Create a new download script and switch based on model URL
- To add download progress: Capture subprocess output
- To support private models: hf-download.sh uses HF_TOKEN env var
- To add model verification: Check sha256 of downloaded files
Args:
model: HuggingFace model ID (e.g., 'Salyut1/GLM-4.7-NVFP4')
copy_to: List of worker hostnames to copy model cache to
Returns:
True if download (and copy) succeeded, False otherwise
"""
if not DOWNLOAD_SCRIPT.exists():
print(f"Error: Download script not found: {DOWNLOAD_SCRIPT}")
return False
cmd = [str(DOWNLOAD_SCRIPT), model]
if copy_to:
cmd.extend(["--copy-to", ",".join(copy_to), "--copy-parallel"])
print(f"Downloading model '{model}'...")
if copy_to:
print(f"Will copy to: {', '.join(copy_to)}")
result = subprocess.run(cmd)
return result.returncode == 0
def check_model_exists(model: str) -> bool:
"""
Check if a model exists in the HuggingFace cache.
Checks the standard HF cache location for completed downloads.
EXTENSIBILITY:
- To support custom cache locations: Add HF_HOME env var support
- To verify model integrity: Check for complete snapshot with config.json
- To support other model sources: Add URL/path prefix detection
Args:
model: HuggingFace model ID (e.g., 'org/model-name')
Returns:
True if model appears to be fully downloaded, False otherwise
"""
# Convert model name to cache directory format
# e.g., "Salyut1/GLM-4.7-NVFP4" -> "models--Salyut1--GLM-4.7-NVFP4"
cache_name = f"models--{model.replace('/', '--')}"
cache_path = Path.home() / ".cache" / "huggingface" / "hub" / cache_name
if cache_path.exists():
# Check for snapshots directory which indicates complete download
snapshots = cache_path / "snapshots"
if snapshots.exists() and any(snapshots.iterdir()):
return True
return False
def generate_launch_script(
recipe: dict[str, Any],
overrides: dict[str, Any],
is_solo: bool = False,
extra_args: list[str] | None = None,
use_ray: bool = False,
) -> str:
"""
Generate a bash launch script from the recipe.
Creates a self-contained bash script that runs inside the container.
Handles template substitution, environment variables, and solo mode adjustments.
EXTENSIBILITY:
- To add new template variables: Add them to recipe['defaults'] or CLI overrides
- To add pre/post hooks: Add 'pre_command'/'post_command' fields to recipe schema
- To add conditional logic: Use Jinja2 templating instead of str.format()
- To support GPU selection: Add CUDA_VISIBLE_DEVICES to env handling
TEMPLATE VARIABLES (use {variable_name} in recipe command):
port: API server port (default from recipe)
host: API server bind address
tensor_parallel: Number of GPUs for tensor parallelism
gpu_memory_utilization: Fraction of GPU memory to use
max_model_len: Maximum sequence length
(custom variables can be added via recipe defaults)
SOLO BEHAVIOR:
- Strips distributed executor configuration
- Typically sets tensor_parallel=1 (handled by caller)
MULTI-NODE BACKEND BEHAVIOR:
- No-Ray is the default
- --ray preserves or adds Ray distributed executor configuration
EXTRA ARGS:
- Appended verbatim to the end of the vLLM command
- Allows passing any vLLM argument not covered by template variables
- vLLM uses "last wins" semantics for duplicate arguments
Args:
recipe: Loaded recipe dictionary
overrides: CLI-provided parameter overrides (take precedence over defaults)
is_solo: If True, generate a single-node launch script
extra_args: Additional arguments to append to vLLM command (after --)
use_ray: If True, preserve/add Ray distributed executor configuration
Returns:
Complete bash script content as string
Raises:
SystemExit: If required template variables are missing
"""
# Merge defaults with overrides
params = {**recipe.get("defaults", {}), **overrides}
# Build the script
lines = ["#!/bin/bash", f"# Generated from recipe: {recipe['name']}", ""]
# Add environment variables
env_vars = recipe.get("env", {})
if env_vars:
lines.append("# Environment variables")
for key, value in env_vars.items():
lines.append(f'export {key}="{value}"')
lines.append("")
# Format the command with parameters
command = recipe["command"]
try:
command = command.format(**params)
except KeyError as e:
print(f"Error: Missing parameter in recipe command: {e}")
print(f"Available parameters: {list(params.keys())}")
sys.exit(1)
# Remove trailing backslash if present before appending extra args.
command = command.rstrip()
if command.endswith("\\"):
command = command.rstrip("\\\n").rstrip()
# Append extra args if provided (after --)
if extra_args:
# Join extra args and append to command
extra_args_str = " ".join(shlex.quote(a) for a in extra_args)
command = command + " " + extra_args_str
# Normalize distributed backend after CLI passthrough. No-Ray is default.
if is_solo or not use_ray:
command = strip_distributed_executor_backend(command)
else:
command = ensure_ray_backend(command)
lines.append("# Run the model")
lines.append(command.strip())
lines.append("")
return "\n".join(lines)
def parse_nodes(nodes_arg: str | None) -> list[str]:
"""
Parse comma-separated node list.
Simple utility to split node specifications. The first node is
always treated as the head node for cluster deployments.
Args:
nodes_arg: Comma-separated string like '192.168.1.1,192.168.1.2'
Returns:
List of stripped node identifiers, empty list if input is None/empty
"""
if not nodes_arg:
return []
return [n.strip() for n in nodes_arg.split(",") if n.strip()]
def get_worker_nodes(nodes: list[str]) -> list[str]:
"""
Get worker nodes (all nodes except the first/head node).
In a Ray cluster, the first node runs the head process.
Workers are all subsequent nodes that join the cluster.
Args:
nodes: Full list of nodes (head first, then workers)
Returns:
List of worker nodes (excluding head), empty if single node
"""
if len(nodes) <= 1:
return []
return nodes[1:]
def load_env_file() -> dict[str, str]:
"""
Load environment variables from .env file.
Reads the .env file created by --discover for persistent cluster configuration.
EXTENSIBILITY:
- To support multiple .env files: Add a --env-file CLI argument
- To add validation: Check for required keys after loading
SUPPORTED KEYS (set by --discover):
CLUSTER_NODES: Comma-separated list of node IPs
LOCAL_IP: This machine's IP address
ETH_IF: Ethernet interface name
IB_IF: InfiniBand interface name (if available)
Returns:
Dictionary of key=value pairs from .env file
"""
env = {}
if ENV_FILE.exists():
with open(ENV_FILE) as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, _, value = line.partition("=")
# Remove quotes if present
value = value.strip().strip('"').strip("'")
env[key.strip()] = value
return env
def run_autodiscover() -> dict[str, str] | None:
"""
Run autodiscover.sh interactively and return discovered configuration.
Executes the autodiscover.sh script to detect cluster topology,
including interactive per-node confirmation and .env saving.
After autodiscover.sh completes, reads configuration from .env file.
Returns:
Dictionary with discovered configuration from .env, or None if discovery failed
"""
if not AUTODISCOVER_SCRIPT.exists():
print(f"Error: Autodiscover script not found: {AUTODISCOVER_SCRIPT}")
return None
print("Running autodiscover...")
print()
# Pass CONFIG_FILE so autodiscover.sh knows where to save the config.
# Do NOT set CONFIG_FILE_SET=true — that would cause an error if the file
# doesn't exist yet (it's the file we're about to create).
env_vars = os.environ.copy()
env_vars["CONFIG_FILE"] = str(ENV_FILE)
env_vars["FORCE_DISCOVER"] = "true"
env_vars.pop("CONFIG_FILE_SET", None)
# Run autodiscover interactively so its prompts are shown to the user
script = f"""
source '{AUTODISCOVER_SCRIPT}'
run_autodiscover
"""
result = subprocess.run(["bash", "-c", script], env=env_vars)
if result.returncode != 0:
print("Error: Autodiscover failed")
return None
# Read configuration from the .env file that autodiscover.sh wrote
env = load_env_file()
if not env.get("CLUSTER_NODES"):
print("Autodiscover completed but no CLUSTER_NODES found in .env")
return None
return env
def main():
"""
Main entry point for the recipe runner.
Orchestrates the full deployment pipeline:
1. Parse CLI arguments and load recipe
2. Resolve cluster nodes (CLI -> .env -> autodiscover)
3. Build phase: Build container if missing, copy to workers
4. Download phase: Download model if missing, copy to workers
5. Run phase: Generate launch script and execute via launch-cluster.sh
EXTENSIBILITY:
- To add new CLI options: Add to the appropriate argument group
- To add new phases: Insert between existing phases with similar pattern
- To add pre/post hooks: Add hook execution before/after subprocess calls
- To add logging: Replace print() with logging module calls
- To add config file support: Load defaults from ~/.config/vllm-recipes.yaml
EXIT CODES:
0: Success
1: Error (recipe not found, build failed, validation error, etc.)
Returns:
Exit code for sys.exit()
"""
parser = argparse.ArgumentParser(
description="Run a model using a YAML recipe",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Basic usage
%(prog)s glm-4.7-nvfp4
%(prog)s glm-4.7-nvfp4 --port 9000 --solo
# Full setup (build container + download model + run)
%(prog)s glm-4.7-nvfp4 --setup
# Cluster deployment (manual)
%(prog)s glm-4.7-nvfp4 -n 192.168.1.1,192.168.1.2 --setup
# Cluster deployment (auto-discover)
%(prog)s --discover # Detect nodes and save to .env
%(prog)s glm-4.7-nvfp4 --setup # Uses nodes from .env
# Just build/download without running
%(prog)s glm-4.7-nvfp4 --build-only
%(prog)s glm-4.7-nvfp4 --download-only
# Pass extra arguments to vLLM (after --)
%(prog)s glm-4.7-nvfp4 --solo -- --load-format safetensors
%(prog)s glm-4.7-nvfp4 --solo -- --served-model-name my-api
# Apply additional launch-cluster mods
%(prog)s glm-4.7-nvfp4 --apply-mod mods/use-official-vllm
# Publish ports in solo mode
%(prog)s glm-4.7-nvfp4 --solo -p 8000:8000
# List available recipes
%(prog)s --list
# Show current .env configuration
%(prog)s --show-env
""",
)
parser.add_argument(
"recipe",
nargs="?",
help="Path to recipe YAML file (or just the name without .yaml)",
)
parser.add_argument(
"--list", "-l", action="store_true", help="List available recipes"
)
# Setup options
setup_group = parser.add_argument_group("Setup options")
setup_group.add_argument(
"--setup",
action="store_true",
help="Full setup: build container (if missing) + download model (if missing) + run",
)
setup_group.add_argument(
"--build-only",
action="store_true",
help="Only build/copy the container image, don't run",
)
setup_group.add_argument(
"--download-only",
action="store_true",
help="Only download/copy the model, don't run",
)
setup_group.add_argument(
"--force-build", action="store_true", help="Force rebuild even if image exists"
)
setup_group.add_argument(
"--force-download",
action="store_true",
help="Force re-download even if model exists",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be executed without running",
)
# Override options
override_group = parser.add_argument_group("Recipe overrides")
override_group.add_argument("--port", type=int, help="Override port")
override_group.add_argument("--host", help="Override host")
override_group.add_argument(
"--tensor-parallel",
"--tp",
type=int,
dest="tensor_parallel",
help="Override tensor parallelism",
)
override_group.add_argument(
"--gpu-memory-utilization",
"--gpu-mem",
type=float,
dest="gpu_memory_utilization",
help="Override GPU memory utilization",
)
override_group.add_argument(
"--max-model-len",
type=int,
dest="max_model_len",
help="Override max model length",
)
# Launch options (passed to launch-cluster.sh)
launch_group = parser.add_argument_group(
"Launch options (passed to launch-cluster.sh)"
)
launch_group.add_argument(
"--solo", action="store_true", help="Run in solo mode (single node, no Ray)"
)
launch_group.add_argument(
"-n", "--nodes", help="Comma-separated list of node IPs (first is head node)"
)
launch_group.add_argument(
"-d", "--daemon", action="store_true", help="Run in daemon mode"
)
launch_group.add_argument(
"-t",
"--container",
dest="container_override",
help="Override container image from recipe",
)
launch_group.add_argument(
"--nccl-debug",
choices=["VERSION", "WARN", "INFO", "TRACE"],
help="NCCL debug level",
)
launch_group.add_argument(
"-e",
"--env",
action="append",
dest="env_vars",
default=[],
metavar="VAR=VALUE",
help="Environment variable to pass to container (e.g. -e HF_TOKEN=xxx). Can be used multiple times.",
)
launch_group.add_argument(
"--apply-mod",
action="append",
dest="apply_mods",
default=[],
metavar="PATH",
help="Mod directory or zip to pass to launch-cluster.sh. Can be used multiple times.",
)
launch_group.add_argument(
"-p",
"--publish",
action="append",
dest="port_mappings",
default=[],
metavar="HOST:CONTAINER",
help="Publish a container port in solo mode, e.g. -p 8000:8000. Can be used multiple times.",
)
backend_group = launch_group.add_mutually_exclusive_group()
backend_group.add_argument(
"--ray",
action="store_true",
dest="ray",
help="Use Ray for multi-node vLLM and ensure --distributed-executor-backend ray is present",
)
backend_group.add_argument(
"--no-ray",
action="store_true",
dest="no_ray",
help="Default for multi-node vLLM without Ray (accepted for compatibility)",
)
launch_group.add_argument(
"--master-port",
"--head-port",
type=int,
dest="master_port",
help="Port for cluster coordination (Ray head port or PyTorch distributed master port, default: 29501)",
)
launch_group.add_argument(
"--name",
dest="container_name",
help="Override container name (default: vllm_node)",
)
launch_group.add_argument(
"--eth-if",
dest="eth_if",
help="Ethernet interface (overrides .env and auto-detection)",
)
launch_group.add_argument(
"--ib-if",
dest="ib_if",
help="InfiniBand interface (overrides .env and auto-detection)",
)
launch_group.add_argument(
"-j",
dest="build_jobs",
type=int,
metavar="N",
help="Number of parallel build jobs inside container",
)
launch_group.add_argument(
"--no-cache-dirs",
action="store_true",
dest="no_cache_dirs",
help="Do not mount ~/.cache/vllm, ~/.cache/flashinfer, ~/.triton",
)
launch_group.add_argument(
"--keep-entrypoint",
action="store_true",
dest="keep_entrypoint",
help="Keep the Docker image entrypoint instead of clearing it before launch",
)
launch_group.add_argument(
"--earlyoom",
action="store_true",
dest="earlyoom",
help="Run earlyoom as the container foreground process instead of sleep infinity",
)
launch_group.add_argument(
"--earlyoom-args",
dest="earlyoom_args",
metavar="ARGS",
help="Arguments passed to earlyoom (default: '-M 524288,102400 -s 100 -r 60')",
)
launch_group.add_argument(
"--non-privileged",
action="store_true",
dest="non_privileged",
help="Run in non-privileged mode (removes --privileged and --ipc=host)",
)
launch_group.add_argument(
"--mem-limit-gb",
type=int,
dest="mem_limit_gb",
help="Memory limit in GB (only with --non-privileged)",
)
launch_group.add_argument(
"--mem-swap-limit-gb",
type=int,
dest="mem_swap_limit_gb",
help="Memory+swap limit in GB (only with --non-privileged)",
)
launch_group.add_argument(
"--pids-limit",
type=int,
dest="pids_limit",
help="Process limit (only with --non-privileged, default: 4096)",
)
launch_group.add_argument(
"--shm-size-gb",
type=int,
dest="shm_size_gb",
help="Shared memory size in GB (only with --non-privileged, default: 64)",
)
# Config file option
parser.add_argument(
"--config",
dest="config_file",
metavar="FILE",
help="Path to .env configuration file (default: .env in script directory)",
)
# Cluster discovery options
discover_group = parser.add_argument_group("Cluster discovery")
discover_group.add_argument(
"--discover",
action="store_true",
help="Auto-detect cluster nodes and save to .env file",
)
discover_group.add_argument(
"--show-env", action="store_true", help="Show current .env configuration"
)
# Use parse_known_args to allow extra vLLM arguments after --
args, extra_args = parser.parse_known_args()
# Set .env file path (use default if not specified)
global ENV_FILE
if args.config_file:
ENV_FILE = Path(args.config_file).resolve()
else:
ENV_FILE = SCRIPT_DIR / ".env"
# Filter out the -- separator if present
if extra_args and extra_args[0] == "--":
extra_args = extra_args[1:]
# Handle --discover (can be run with or without a recipe)
if args.discover:
env = run_autodiscover()
if env is None:
return 1
print("Discovered configuration:")
for key, value in sorted(env.items()):
print(f" {key}={value}")
print()
if not args.recipe:
return 0
# Handle --show-env
if args.show_env:
env = load_env_file()
if env:
print(f"Current .env configuration ({ENV_FILE}):")
for key, value in sorted(env.items()):
print(f" {key}={value}")
else:
print(f"No .env file found at {ENV_FILE}")
print("Run with --discover to auto-detect cluster nodes.")
if not args.recipe:
return 0
print()
if args.list:
list_recipes()
return 0
if not args.recipe:
parser.print_help()
return 1
# Load recipe
recipe_path = Path(args.recipe)
recipe = load_recipe(recipe_path)
print(f"Recipe: {recipe['name']}")
if recipe.get("description"):