File size: 7,698 Bytes
bb76a65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Driver for the AWS Steam GPU Launch Kit.

Artifacts are pulled from the Hugging Face Hub, so a runner that has only
`huggingface_hub` plus the AWS CLI can deploy without a git checkout.

  validate   static checks only - no AWS credentials, no network beyond the Hub
  plan       validate, then show the exact CloudFormation call that would run
  deploy     validate, then run launch.sh against your AWS account
  job        print the equivalent Hugging Face Job command (and optionally submit)

Examples:
  python launch.py validate
  python launch.py plan --instance-type g6.xlarge
  python launch.py deploy --key-name my-keypair --volume-gib 600
  python launch.py job --mode deploy --key-name my-keypair
"""

from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path

DEFAULT_REPO = "Allszn/aws-steam-gpu-launchkit"

ALLOW = [
    "cloudformation/*",
    "scripts/*",
    "iam/*",
    "ssm/*",
    "launch.sh",
    "launch.py",
    "README.md",
]


def log(msg: str) -> None:
    print(f"[launch] {msg}", flush=True)


def die(msg: str, code: int = 1) -> None:
    print(f"[fail] {msg}", file=sys.stderr, flush=True)
    raise SystemExit(code)


def resolve_root(args: argparse.Namespace) -> Path:
    """Use a local checkout when we are inside one, otherwise fetch from the Hub."""
    if args.local:
        root = Path(args.local).resolve()
    elif Path("cloudformation/steam-gpu-host.yaml").exists():
        root = Path.cwd()
    else:
        try:
            from huggingface_hub import snapshot_download
        except ImportError:
            die("huggingface_hub is required to fetch the kit: pip install huggingface_hub")
        log(f"no local checkout; fetching {args.repo}@{args.revision} from the Hub")
        root = Path(
            snapshot_download(
                repo_id=args.repo,
                repo_type="dataset",
                revision=args.revision,
                token=os.environ.get("HF_TOKEN"),
                allow_patterns=ALLOW,
            )
        )

    if not (root / "cloudformation" / "steam-gpu-host.yaml").exists():
        die(f"{root} does not look like a launch kit")
    return root


def run(cmd: list[str], cwd: Path | None = None, env: dict | None = None) -> int:
    log("$ " + " ".join(cmd))
    return subprocess.run(cmd, cwd=str(cwd) if cwd else None, env=env).returncode


def cmd_validate(args: argparse.Namespace, root: Path) -> int:
    return run([sys.executable, "scripts/validate.py", "--root", ".", "--pretty"], root)


def build_env(args: argparse.Namespace) -> dict:
    env = dict(os.environ)
    env["AWS_REGION"] = args.region
    env["STACK_NAME"] = args.stack_name
    env["INSTANCE_TYPE"] = args.instance_type
    env["GAME_VOLUME_GIB"] = str(args.volume_gib)
    if args.key_name:
        env["KEY_NAME"] = args.key_name
    if args.admin_cidr:
        env["ADMIN_CIDR"] = args.admin_cidr
    if args.artifact_bucket:
        env["ARTIFACT_BUCKET"] = args.artifact_bucket
    if args.dry_run:
        env["DRY_RUN"] = "1"
    return env


def cmd_plan(args: argparse.Namespace, root: Path) -> int:
    if cmd_validate(args, root) != 0:
        die("validation failed; not producing a plan")
    env = build_env(args)
    env["DRY_RUN"] = "1"
    launch = root / "launch.sh"
    launch.chmod(0o755)
    return run(["bash", str(launch)], root, env)


def cmd_deploy(args: argparse.Namespace, root: Path) -> int:
    if shutil.which("aws") is None:
        die("the AWS CLI is required for deploy")
    if cmd_validate(args, root) != 0:
        die("validation failed; refusing to touch AWS")
    launch = root / "launch.sh"
    launch.chmod(0o755)
    return run(["bash", str(launch)], root, build_env(args))


def cmd_job(args: argparse.Namespace, root: Path) -> int:
    """Build (or submit) the Hugging Face Job that performs the same deploy."""
    deps = ["huggingface_hub", "pyyaml", "awscli", "boto3"]
    with_flags = " ".join(f"--with {d}" for d in deps)

    secrets = [
        "AWS_ACCESS_KEY_ID",
        "AWS_SECRET_ACCESS_KEY",
        "AWS_REGION",
    ]
    secret_flags = " ".join(f"--secrets {s}" for s in secrets)

    env_pairs = {
        "MODE": args.mode,
        "INSTANCE_TYPE": args.instance_type,
        "GAME_VOLUME_GIB": str(args.volume_gib),
        "STACK_NAME": args.stack_name,
    }
    if args.key_name:
        env_pairs["KEY_NAME"] = args.key_name
    if args.admin_cidr:
        env_pairs["ADMIN_CIDR"] = args.admin_cidr
    env_flags = " ".join(f"--env {k}={v}" for k, v in env_pairs.items())

    command = (
        f"hf jobs uv run \\\n"
        f"  --name steam-gpu-{args.mode} \\\n"
        f"  --flavor cpu-basic \\\n"
        f"  --timeout {args.timeout} \\\n"
        f"  {with_flags} \\\n"
        f"  {secret_flags} \\\n"
        f"  {env_flags} \\\n"
        f"  scripts/hf_job.py"
    )

    print()
    log("Hugging Face Job command (credentials travel as Hub secrets, never as files):")
    print()
    print(command)
    print()
    print("  MODE=validate needs no AWS credentials at all and is a safe first run:")
    print(f"  MODE=diagnose additionally needs INSTANCE_ID=<id>.")
    print("  Confirm flag names against `hf jobs run --help` for your CLI version.")
    print()

    if args.submit:
        job_env = build_env(args)
        job_env["MODE"] = args.mode
        shell = command.replace("\\\n", " ").replace("  ", " ")
        log(f"submitting: {shell}")
        return run(["/bin/sh", "-lc", shell], root, job_env)

    log("dry run: not submitted. Re-run with --submit to send it to Hub compute.")
    return 0


def common(p: argparse.ArgumentParser) -> None:
    p.add_argument("--repo", default=DEFAULT_REPO, help=f"Hub dataset repo (default: {DEFAULT_REPO})")
    p.add_argument("--revision", default=None, help="branch, tag or commit on the Hub")
    p.add_argument("--local", default=None, help="use this local checkout instead of fetching")
    p.add_argument("--region", default=os.environ.get("AWS_REGION", "us-east-1"))
    p.add_argument("--stack-name", default="steam-gpu")
    p.add_argument("--instance-type", default="g6.xlarge")
    p.add_argument("--volume-gib", type=int, default=600)
    p.add_argument("--key-name", default=os.environ.get("KEY_NAME"))
    p.add_argument("--admin-cidr", default=os.environ.get("ADMIN_CIDR"))
    p.add_argument("--artifact-bucket", default=os.environ.get("ARTIFACT_BUCKET"))
    p.add_argument("--dry-run", action="store_true")


def main() -> int:
    ap = argparse.ArgumentParser(
        description="AWS Steam GPU Launch Kit driver",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    sub = ap.add_subparsers(dest="command", required=True)

    p_val = sub.add_parser("validate", help="static checks only")
    common(p_val)

    p_plan = sub.add_parser("plan", help="validate, then print the deploy plan")
    common(p_plan)

    p_dep = sub.add_parser("deploy", help="validate, then deploy to AWS")
    common(p_dep)

    p_job = sub.add_parser("job", help="print or submit the equivalent Hugging Face Job")
    common(p_job)
    p_job.add_argument("--mode", default="validate", choices=["validate", "deploy", "diagnose"])
    p_job.add_argument("--timeout", default="40m")
    p_job.add_argument("--submit", action="store_true", help="actually submit the job")

    args = ap.parse_args()
    root = resolve_root(args)

    handlers = {
        "validate": cmd_validate,
        "plan": cmd_plan,
        "deploy": cmd_deploy,
        "job": cmd_job,
    }
    return handlers[args.command](args, root)


if __name__ == "__main__":
    sys.exit(main())