v41-quant-worker / worker /launch.py
apetersson's picture
v41: volume-selectable CPU create + idempotent fetch
7fcf248 verified
Raw History Blame Contribute Delete
8.28 kB
#!/usr/bin/env python3
"""Create or inspect the headless v41-quant CPU worker pod.
The worker runs bootstrap.sh at container start and pushes evidence to Hugging Face, so no
SSH access is required. The network volume holding the source checkpoint and the safetensors
artifact is attached read-write at /workspace.
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import sys
import time
from pathlib import Path
import requests
REST = "https://rest.runpod.io/v1"
IMAGE = "python@sha256:b1add8a6f2aca6bcfcf0b9c9b522352f7ce0d62a3d556a2f2f32511aa0cca250"
CUDA_DEVEL_IMAGE = "nvidia/cuda:13.0.0-devel-ubuntu24.04"
SGLANG_IMAGE = "lmsysorg/sglang:dev-dsv41"
VOLUME = os.environ.get("V41_QUANT_VOLUME", "uxd6kl9m1g")
EVIDENCE_REPO = "apetersson/v41-quant-worker"
def api_key() -> str:
key = os.environ.get("RUNPOD_API_KEY")
if key:
return key
import tomllib
with open(Path.home() / ".runpod/config.toml", "rb") as fh:
return tomllib.load(fh)["apikey"]
def headers() -> dict[str, str]:
return {"Authorization": "Bearer " + api_key(), "User-Agent": "abliteration-v41-quant/1.0"}
def create_gpu(name: str, gpu_id: str, image: str, disk: int, ceiling: float,
hf_token: str | None, script: str, arch: str | None = None,
attach_volume: bool = True, volume: str | None = None) -> dict:
"""Create a single-GPU lease running the headless worker.
A Runpod network volume is datacenter-local and single-attach, so when the only GPU with
stock sits in another DC the volume cannot be used and the worker falls back to the
published GGUF on Hugging Face (pass attach_volume=False).
"""
bootstrap_url = f"https://huggingface.co/datasets/{EVIDENCE_REPO}/resolve/main/{script}"
# CUDA devel images ship without python3/curl, so the fetch step bootstraps its own tooling
# before the worker script runs.
runner = (
"set -e; "
"if ! command -v python3 >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1; then "
"apt-get update -qq && apt-get install -y -qq --no-install-recommends "
"python3 curl ca-certificates; fi; "
f"curl -fsSL --retry 6 --retry-delay 5 --retry-all-errors "
f'-H "Authorization: Bearer ${{HF_TOKEN:-}}" -o /tmp/worker.sh {bootstrap_url}; '
"exec bash /tmp/worker.sh"
)
body = {
"name": name,
"computeType": "GPU",
"cloudType": "SECURE",
"gpuTypeIds": [gpu_id],
"gpuCount": 1,
"containerDiskInGb": disk,
"volumeInGb": 0 if attach_volume else disk,
"volumeMountPath": "/workspace",
"imageName": image,
"interruptible": False,
"ports": ["22/tcp"],
"dockerEntrypoint": ["/bin/sh", "-lc"],
"dockerStartCmd": [runner],
"env": {"EVIDENCE_REPO": EVIDENCE_REPO, **({"CUDA_ARCH": arch} if arch else {}),
**({"HF_TOKEN": hf_token} if hf_token else {})},
}
if attach_volume:
body["networkVolumeId"] = volume or VOLUME
response = requests.post(REST + "/pods", headers=headers(), json=body, timeout=90)
if response.status_code >= 400:
message = response.text
if hf_token:
message = message.replace(hf_token, "[redacted]")
raise SystemExit(f"gpu create failed {response.status_code}: {message[:500]}")
pod = response.json()
if float(pod.get("costPerHr", 0)) > ceiling:
requests.delete(REST + f"/pods/{pod['id']}", headers=headers(), timeout=30)
raise SystemExit(f"GPU quote {pod['costPerHr']} exceeds ceiling {ceiling}; pod removed")
return pod
def create(name: str, vcpu: int, disk: int, ceiling: float, hf_token: str | None,
script: str = "worker/bootstrap.sh", volume: str | None = None) -> dict:
bootstrap_url = f"https://huggingface.co/datasets/{EVIDENCE_REPO}/resolve/main/{script}"
# fetch the bootstrap, then run it; keeps the pod command short and shell-quote free
runner = (
"import base64,subprocess,sys,urllib.request;"
f"u={bootstrap_url!r};"
"d=urllib.request.urlopen(u).read();open('/tmp/bootstrap.sh','wb').write(d);"
"sys.exit(subprocess.call(['bash','/tmp/bootstrap.sh']))"
)
body = {
"name": name,
"computeType": "CPU",
"cloudType": "SECURE",
"vcpuCount": vcpu,
"cpuFlavorIds": ["cpu5g", "cpu5m", "cpu3g", "cpu3m"],
"containerDiskInGb": disk,
"volumeInGb": 0,
"networkVolumeId": volume or VOLUME,
"volumeMountPath": "/workspace",
"imageName": IMAGE,
"interruptible": False,
"ports": ["22/tcp"],
"dockerEntrypoint": ["/bin/sh", "-lc"],
"dockerStartCmd": [f"python3 -c {json.dumps(runner)}"],
"env": {"EVIDENCE_REPO": EVIDENCE_REPO, **({"HF_TOKEN": hf_token} if hf_token else {})},
}
response = requests.post(REST + "/pods", headers=headers(), json=body, timeout=60)
if response.status_code >= 400:
message = response.text
if hf_token:
message = message.replace(hf_token, "[redacted]")
raise SystemExit(f"create failed {response.status_code}: {message[:600]}")
pod = response.json()
if float(pod.get("costPerHr", 0)) > ceiling:
requests.delete(REST + f"/pods/{pod['id']}", headers=headers(), timeout=30)
raise SystemExit(f"quote {pod['costPerHr']} exceeds ceiling {ceiling}; pod removed")
return pod
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="cmd", required=True)
c = sub.add_parser("create")
c.add_argument("--name", default=f"v41-quant-pack-{int(time.time())}")
c.add_argument("--vcpu", type=int, default=32)
c.add_argument("--disk", type=int, default=150)
c.add_argument("--ceiling", type=float, default=1.6)
c.add_argument("--hf-token-env", default="HF_TOKEN")
c.add_argument("--script", default="worker/bootstrap.sh", help="worker script path in the evidence repo")
c.add_argument("--volume", default=None, help="network volume id (defaults to V41_QUANT_VOLUME)")
gpu = sub.add_parser("create-gpu")
gpu.add_argument("--name", default=f"v41-gpu-{int(time.time())}")
gpu.add_argument("--gpu-id", default="NVIDIA B200")
gpu.add_argument("--image", default=CUDA_DEVEL_IMAGE)
gpu.add_argument("--disk", type=int, default=300)
gpu.add_argument("--ceiling", type=float, default=8.0)
gpu.add_argument("--script", default="worker/gpu-kernel.sh")
gpu.add_argument("--arch", default="100a")
gpu.add_argument("--hf-token-env", default="HF_TOKEN")
gpu.add_argument("--volume", default=None, help="network volume id (defaults to V41_QUANT_VOLUME)")
gpu.add_argument("--no-network-volume", action="store_true",
help="local pod volume instead: required when the only stocked DC differs")
g = sub.add_parser("get")
g.add_argument("id")
for p in (sub.add_parser("terminate"),):
p.add_argument("id")
args = parser.parse_args()
if args.cmd == "create":
pod = create(args.name, args.vcpu, args.disk, args.ceiling, os.environ.get(args.hf_token_env),
args.script, args.volume)
print(json.dumps({k: pod.get(k) for k in ("id", "name", "costPerHr", "cpuFlavorId", "desiredStatus")}, indent=1))
return 0
if args.cmd == "create-gpu":
pod = create_gpu(args.name, args.gpu_id, args.image, args.disk, args.ceiling,
os.environ.get(args.hf_token_env), args.script, args.arch,
attach_volume=not args.no_network_volume, volume=args.volume)
print(json.dumps({k: pod.get(k) for k in ("id", "name", "costPerHr", "gpuTypeId", "desiredStatus")}, indent=1))
return 0
if args.cmd == "get":
print(json.dumps(requests.get(f"{REST}/pods/{args.id}", headers=headers(), timeout=30).json(), indent=1))
return 0
if args.cmd == "terminate":
response = requests.delete(f"{REST}/pods/{args.id}", headers=headers(), timeout=30)
print(f"terminate {args.id}: HTTP {response.status_code}")
return 0
return 2
if __name__ == "__main__":
sys.exit(main())