Allszn commited on
Commit
bb76a65
·
verified ·
1 Parent(s): f471034

Add Python driver

Browse files
Files changed (1) hide show
  1. launch.py +229 -0
launch.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Driver for the AWS Steam GPU Launch Kit.
3
+
4
+ Artifacts are pulled from the Hugging Face Hub, so a runner that has only
5
+ `huggingface_hub` plus the AWS CLI can deploy without a git checkout.
6
+
7
+ validate static checks only - no AWS credentials, no network beyond the Hub
8
+ plan validate, then show the exact CloudFormation call that would run
9
+ deploy validate, then run launch.sh against your AWS account
10
+ job print the equivalent Hugging Face Job command (and optionally submit)
11
+
12
+ Examples:
13
+ python launch.py validate
14
+ python launch.py plan --instance-type g6.xlarge
15
+ python launch.py deploy --key-name my-keypair --volume-gib 600
16
+ python launch.py job --mode deploy --key-name my-keypair
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ DEFAULT_REPO = "Allszn/aws-steam-gpu-launchkit"
30
+
31
+ ALLOW = [
32
+ "cloudformation/*",
33
+ "scripts/*",
34
+ "iam/*",
35
+ "ssm/*",
36
+ "launch.sh",
37
+ "launch.py",
38
+ "README.md",
39
+ ]
40
+
41
+
42
+ def log(msg: str) -> None:
43
+ print(f"[launch] {msg}", flush=True)
44
+
45
+
46
+ def die(msg: str, code: int = 1) -> None:
47
+ print(f"[fail] {msg}", file=sys.stderr, flush=True)
48
+ raise SystemExit(code)
49
+
50
+
51
+ def resolve_root(args: argparse.Namespace) -> Path:
52
+ """Use a local checkout when we are inside one, otherwise fetch from the Hub."""
53
+ if args.local:
54
+ root = Path(args.local).resolve()
55
+ elif Path("cloudformation/steam-gpu-host.yaml").exists():
56
+ root = Path.cwd()
57
+ else:
58
+ try:
59
+ from huggingface_hub import snapshot_download
60
+ except ImportError:
61
+ die("huggingface_hub is required to fetch the kit: pip install huggingface_hub")
62
+ log(f"no local checkout; fetching {args.repo}@{args.revision} from the Hub")
63
+ root = Path(
64
+ snapshot_download(
65
+ repo_id=args.repo,
66
+ repo_type="dataset",
67
+ revision=args.revision,
68
+ token=os.environ.get("HF_TOKEN"),
69
+ allow_patterns=ALLOW,
70
+ )
71
+ )
72
+
73
+ if not (root / "cloudformation" / "steam-gpu-host.yaml").exists():
74
+ die(f"{root} does not look like a launch kit")
75
+ return root
76
+
77
+
78
+ def run(cmd: list[str], cwd: Path | None = None, env: dict | None = None) -> int:
79
+ log("$ " + " ".join(cmd))
80
+ return subprocess.run(cmd, cwd=str(cwd) if cwd else None, env=env).returncode
81
+
82
+
83
+ def cmd_validate(args: argparse.Namespace, root: Path) -> int:
84
+ return run([sys.executable, "scripts/validate.py", "--root", ".", "--pretty"], root)
85
+
86
+
87
+ def build_env(args: argparse.Namespace) -> dict:
88
+ env = dict(os.environ)
89
+ env["AWS_REGION"] = args.region
90
+ env["STACK_NAME"] = args.stack_name
91
+ env["INSTANCE_TYPE"] = args.instance_type
92
+ env["GAME_VOLUME_GIB"] = str(args.volume_gib)
93
+ if args.key_name:
94
+ env["KEY_NAME"] = args.key_name
95
+ if args.admin_cidr:
96
+ env["ADMIN_CIDR"] = args.admin_cidr
97
+ if args.artifact_bucket:
98
+ env["ARTIFACT_BUCKET"] = args.artifact_bucket
99
+ if args.dry_run:
100
+ env["DRY_RUN"] = "1"
101
+ return env
102
+
103
+
104
+ def cmd_plan(args: argparse.Namespace, root: Path) -> int:
105
+ if cmd_validate(args, root) != 0:
106
+ die("validation failed; not producing a plan")
107
+ env = build_env(args)
108
+ env["DRY_RUN"] = "1"
109
+ launch = root / "launch.sh"
110
+ launch.chmod(0o755)
111
+ return run(["bash", str(launch)], root, env)
112
+
113
+
114
+ def cmd_deploy(args: argparse.Namespace, root: Path) -> int:
115
+ if shutil.which("aws") is None:
116
+ die("the AWS CLI is required for deploy")
117
+ if cmd_validate(args, root) != 0:
118
+ die("validation failed; refusing to touch AWS")
119
+ launch = root / "launch.sh"
120
+ launch.chmod(0o755)
121
+ return run(["bash", str(launch)], root, build_env(args))
122
+
123
+
124
+ def cmd_job(args: argparse.Namespace, root: Path) -> int:
125
+ """Build (or submit) the Hugging Face Job that performs the same deploy."""
126
+ deps = ["huggingface_hub", "pyyaml", "awscli", "boto3"]
127
+ with_flags = " ".join(f"--with {d}" for d in deps)
128
+
129
+ secrets = [
130
+ "AWS_ACCESS_KEY_ID",
131
+ "AWS_SECRET_ACCESS_KEY",
132
+ "AWS_REGION",
133
+ ]
134
+ secret_flags = " ".join(f"--secrets {s}" for s in secrets)
135
+
136
+ env_pairs = {
137
+ "MODE": args.mode,
138
+ "INSTANCE_TYPE": args.instance_type,
139
+ "GAME_VOLUME_GIB": str(args.volume_gib),
140
+ "STACK_NAME": args.stack_name,
141
+ }
142
+ if args.key_name:
143
+ env_pairs["KEY_NAME"] = args.key_name
144
+ if args.admin_cidr:
145
+ env_pairs["ADMIN_CIDR"] = args.admin_cidr
146
+ env_flags = " ".join(f"--env {k}={v}" for k, v in env_pairs.items())
147
+
148
+ command = (
149
+ f"hf jobs uv run \\\n"
150
+ f" --name steam-gpu-{args.mode} \\\n"
151
+ f" --flavor cpu-basic \\\n"
152
+ f" --timeout {args.timeout} \\\n"
153
+ f" {with_flags} \\\n"
154
+ f" {secret_flags} \\\n"
155
+ f" {env_flags} \\\n"
156
+ f" scripts/hf_job.py"
157
+ )
158
+
159
+ print()
160
+ log("Hugging Face Job command (credentials travel as Hub secrets, never as files):")
161
+ print()
162
+ print(command)
163
+ print()
164
+ print(" MODE=validate needs no AWS credentials at all and is a safe first run:")
165
+ print(f" MODE=diagnose additionally needs INSTANCE_ID=<id>.")
166
+ print(" Confirm flag names against `hf jobs run --help` for your CLI version.")
167
+ print()
168
+
169
+ if args.submit:
170
+ job_env = build_env(args)
171
+ job_env["MODE"] = args.mode
172
+ shell = command.replace("\\\n", " ").replace(" ", " ")
173
+ log(f"submitting: {shell}")
174
+ return run(["/bin/sh", "-lc", shell], root, job_env)
175
+
176
+ log("dry run: not submitted. Re-run with --submit to send it to Hub compute.")
177
+ return 0
178
+
179
+
180
+ def common(p: argparse.ArgumentParser) -> None:
181
+ p.add_argument("--repo", default=DEFAULT_REPO, help=f"Hub dataset repo (default: {DEFAULT_REPO})")
182
+ p.add_argument("--revision", default=None, help="branch, tag or commit on the Hub")
183
+ p.add_argument("--local", default=None, help="use this local checkout instead of fetching")
184
+ p.add_argument("--region", default=os.environ.get("AWS_REGION", "us-east-1"))
185
+ p.add_argument("--stack-name", default="steam-gpu")
186
+ p.add_argument("--instance-type", default="g6.xlarge")
187
+ p.add_argument("--volume-gib", type=int, default=600)
188
+ p.add_argument("--key-name", default=os.environ.get("KEY_NAME"))
189
+ p.add_argument("--admin-cidr", default=os.environ.get("ADMIN_CIDR"))
190
+ p.add_argument("--artifact-bucket", default=os.environ.get("ARTIFACT_BUCKET"))
191
+ p.add_argument("--dry-run", action="store_true")
192
+
193
+
194
+ def main() -> int:
195
+ ap = argparse.ArgumentParser(
196
+ description="AWS Steam GPU Launch Kit driver",
197
+ formatter_class=argparse.RawDescriptionHelpFormatter,
198
+ )
199
+ sub = ap.add_subparsers(dest="command", required=True)
200
+
201
+ p_val = sub.add_parser("validate", help="static checks only")
202
+ common(p_val)
203
+
204
+ p_plan = sub.add_parser("plan", help="validate, then print the deploy plan")
205
+ common(p_plan)
206
+
207
+ p_dep = sub.add_parser("deploy", help="validate, then deploy to AWS")
208
+ common(p_dep)
209
+
210
+ p_job = sub.add_parser("job", help="print or submit the equivalent Hugging Face Job")
211
+ common(p_job)
212
+ p_job.add_argument("--mode", default="validate", choices=["validate", "deploy", "diagnose"])
213
+ p_job.add_argument("--timeout", default="40m")
214
+ p_job.add_argument("--submit", action="store_true", help="actually submit the job")
215
+
216
+ args = ap.parse_args()
217
+ root = resolve_root(args)
218
+
219
+ handlers = {
220
+ "validate": cmd_validate,
221
+ "plan": cmd_plan,
222
+ "deploy": cmd_deploy,
223
+ "job": cmd_job,
224
+ }
225
+ return handlers[args.command](args, root)
226
+
227
+
228
+ if __name__ == "__main__":
229
+ sys.exit(main())