File size: 8,280 Bytes
db3e04d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edaba2e
 
de09079
db3e04d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edaba2e
3a006cc
de09079
3a006cc
 
 
 
 
 
edaba2e
8e1730b
 
edaba2e
8e1730b
 
 
 
25e727f
 
8e1730b
edaba2e
 
 
 
 
 
 
 
3a006cc
edaba2e
 
 
 
 
8e1730b
edaba2e
 
 
3a006cc
de09079
edaba2e
 
 
 
 
 
 
 
 
 
 
 
 
7fcf248
 
c48eb0a
db3e04d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fcf248
db3e04d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c48eb0a
7fcf248
edaba2e
 
 
 
 
 
 
 
 
de09079
3a006cc
 
db3e04d
 
 
 
 
 
 
7fcf248
 
db3e04d
 
edaba2e
 
3a006cc
de09079
edaba2e
 
db3e04d
 
 
 
 
 
 
 
 
 
 
 
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
#!/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())