File size: 9,725 Bytes
4ef198a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env bash
# R2-1 policy server bootstrap: a FRESH g6e.2xlarge (1 x L40S) from the pinned Deep Learning Base GPU AMI -> the pinned
# ScaleCUA checkpoint served by the pinned vLLM image, with the same flags for both arms. Run as root on the GPU host:
#     sudo bash /opt/r2/src/experiments/bench-r2/model/gpu-bootstrap.sh
# Env: HF_TOKEN optional (public repo); MODEL_FALLBACK=1 serves the SFT fallback of pins.json instead (pre-freeze rule only).
# Writes /opt/r2/gpu-receipt.json (revision, shard sha256 checks, overlay file sha256, vLLM image digest, GPU, driver, flags).
# Network: the server listens on 0.0.0.0:8000 and the security group admits only the env host's group; the API key in
# /opt/r2/api-key (0600) is required by vLLM (--api-key) and is passed to the env host out of band, never logged.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
R=/opt/r2; mkdir -p $R/logs; LOG=$R/logs/gpu-bootstrap.log
exec > >(tee -a "$LOG") 2>&1
ts() { date -u +%FT%TZ; }
say() { echo "$(ts) [r2-gpu] $*"; }
die() { say "FAILED: $*"; exit 1; }
pin() { python3 -c "import json,sys; d=json.load(open('$HERE/pins.json')); [d:=d[k] for k in sys.argv[1].split('.')]; print(d if not isinstance(d,(list,dict)) else json.dumps(d))" "$1"; }
[ "$(id -u)" = 0 ] || die "run as root"
# the auto-stop guard FIRST, so a failed bootstrap never leaves an unguarded GPU host running (pair 1 attempt 1, 2026-11-12:
# pip refused under PEP 668, the script died before the guard step and the host idled 2 h)
HARD_H=${HARD_H:-16}; IDLE_MIN=${IDLE_MIN:-60}; export HARD_H IDLE_MIN
bash "$HERE/../../sota-t1/guard-userdata.sh"
say "guard installed (idle $IDLE_MIN min, hard ${HARD_H} h)"
nvidia-smi -L > /dev/null || die "no GPU driver (use the pinned Deep Learning Base GPU AMI)"
command -v docker > /dev/null || die "docker missing"
docker info 2>/dev/null | grep -qi nvidia || die "nvidia container runtime missing"

# ---------------------------------------------------------------------------------------------------- 1. weights, pinned revision
if [ "${MODEL_FALLBACK:-0}" = 1 ]; then REPO=$(pin model.fallback.repo); REV=$(pin model.fallback.revision); SHAS=$(pin model.fallback.shards_sha256)
else REPO=$(pin model.repo); REV=$(pin model.revision); SHAS=$(pin model.shards_sha256); fi
export HF_HOME=/opt/hf; mkdir -p /opt/hf
# Ubuntu 24.04 python is externally managed (PEP 668): a private venv for the download tool
[ -x /opt/r2/venv/bin/pip ] || python3 -m venv /opt/r2/venv > $R/logs/venv.log 2>&1 || die "python3 -m venv (python3-venv missing?)"
/opt/r2/venv/bin/pip -q install "huggingface_hub[cli]" > $R/logs/pip.log 2>&1 || die "pip install huggingface_hub (see $R/logs/pip.log)"
HF=/opt/r2/venv/bin/hf; [ -x $HF ] || HF="/opt/r2/venv/bin/huggingface-cli"
SNAP=/opt/hf/snap/$(basename $REPO)-${REV:0:8}
if [ ! -f $SNAP/.complete ]; then
  say "downloading $REPO@$REV"
  $HF download "$REPO" --revision "$REV" --local-dir "$SNAP" > $R/logs/hf-download.log 2>&1 || die "hf download (see $R/logs/hf-download.log)"
  touch $SNAP/.complete
fi
say "checking shard sha256 against pins.json"
python3 - "$SNAP" "$SHAS" <<'PY' || die "shard sha256 mismatch"
import hashlib, json, sys, os
snap, shas = sys.argv[1], json.loads(sys.argv[2])
bad = []
for f, want in shas.items():
    h = hashlib.sha256()
    with open(os.path.join(snap, f), "rb") as fh:
        for b in iter(lambda: fh.read(1 << 24), b""): h.update(b)
    got = h.hexdigest(); print(f, got, "OK" if got == want else "MISMATCH"); bad += [f] if got != want else []
json.dump({"snapshot": snap, "checked": shas, "mismatch": bad}, open("/opt/r2/model-sha256.json", "w"), indent=1)
sys.exit(1 if bad else 0)
PY

# ---------------------------------------------------------------------------------------------------- 2. overlay (vLLM 0.19 / transformers 4.57)
# lab-scale-gpu deviation O7 (2026-10-29): only tokenizer_class and a 4.x-named video processor file; weights/tokenizer.json/template untouched.
OV=/opt/hf/overlay/$(basename $SNAP)
mkdir -p $OV
for f in $SNAP/*; do ln -sfn "$f" "$OV/$(basename $f)"; done
python3 - "$SNAP" "$OV" <<'PY'
import json, sys, os, hashlib
snap, ov = sys.argv[1], sys.argv[2]
tc = json.load(open(os.path.join(snap, "tokenizer_config.json")))
orig_cls = tc.get("tokenizer_class"); tc["tokenizer_class"] = "Qwen2TokenizerFast"
os.remove(os.path.join(ov, "tokenizer_config.json")); json.dump(tc, open(os.path.join(ov, "tokenizer_config.json"), "w"), indent=2)
pc = json.load(open(os.path.join(snap, "processor_config.json")))
vp = pc.get("video_processor")
if vp is not None and not os.path.exists(os.path.join(snap, "video_preprocessor_config.json")):
    json.dump(vp, open(os.path.join(ov, "video_preprocessor_config.json"), "w"), indent=2)
sha = lambda p: hashlib.sha256(open(p, "rb").read()).hexdigest()
rec = {"orig_tokenizer_class": orig_cls, "tokenizer_config_orig_sha256": sha(os.path.join(snap, "tokenizer_config.json")),
       "tokenizer_config_overlay_sha256": sha(os.path.join(ov, "tokenizer_config.json")),
       "video_preprocessor_config_sha256": sha(os.path.join(ov, "video_preprocessor_config.json")) if os.path.exists(os.path.join(ov, "video_preprocessor_config.json")) else None}
json.dump(rec, open("/opt/r2/overlay.json", "w"), indent=1); print(rec)
PY

# ---------------------------------------------------------------------------------------------------- 3. serve
IMG=$(pin serving.image)
docker pull -q "$IMG" > $R/logs/docker-pull.log 2>&1 || die "docker pull $IMG"
[ -f $R/api-key ] || { umask 077; head -c 32 /dev/urandom | base64 | tr -d '/+=' | head -c 40 > $R/api-key; }
KEY=$(cat $R/api-key)
docker rm -f vllm > /dev/null 2>&1 || true
ARGS=$(python3 -c "import json; print(' '.join(json.load(open('$HERE/pins.json'))['serving']['args']))")
# shellcheck disable=SC2086
docker run -d --name vllm --restart unless-stopped --gpus all --ipc=host -p 8000:8000 -v /opt/hf:/opt/hf -e VLLM_API_KEY="$KEY" "$IMG" \
  --model "$OV" $ARGS > $R/logs/docker-run.log 2>&1 || die "docker run vllm"
say "waiting for the server (model load: a few minutes)"
for i in $(seq 1 180); do
  curl -sf -H "Authorization: Bearer $KEY" localhost:8000/v1/models 2>/dev/null | grep -q '"scalecua"' && break; sleep 5
  [ "$i" = 180 ] && { docker logs vllm 2>&1 | tail -40; die "vllm did not come up in 15 min"; }
done
curl -sf -H "Authorization: Bearer $KEY" localhost:8000/metrics > $R/metrics-check.txt; grep -q "vllm:prefix_cache_queries" $R/metrics-check.txt || die "prefix caching metrics missing"   # hf-repro Q1-D7: no grep -q on the pipe (pipefail + SIGPIPE), as r2bench.sh
# one text call (recorded; not a benchmark request) to confirm usage.prompt_tokens_details is present
curl -sf -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' localhost:8000/v1/chat/completions \
  -d '{"model":"scalecua","messages":[{"role":"user","content":"Say OK."}],"max_tokens":4}' > $R/preflight-call.json
grep -q prompt_tokens_details $R/preflight-call.json || die "usage.prompt_tokens_details missing"
docker logs vllm 2>&1 | grep -E "GPU KV cache size|Maximum concurrency" | tail -2 | tee $R/kv-cache.txt

# ---------------------------------------------------------------------------------------------------- 4. GPU sampler + auto-stop guard
cp "$HERE/../../labbench/gpusampler.py" $R/gpusampler.py 2>/dev/null || true
pkill -f gpusampler.py || true
nohup python3 $R/gpusampler.py --out $R/gpu-samples.jsonl > /dev/null 2>&1 &
# the guard's idle rule reads /run/t1-busy: mark the host busy while the server is answering requests (the request counter moves)
cat > /usr/local/sbin/r2-busy <<'B'
#!/bin/bash
k=$(cat /opt/r2/api-key); n=$(curl -sf -m 5 -H "Authorization: Bearer $k" localhost:8000/metrics | awk '/^vllm:request_success_total/{s+=$2} END{print int(s)}')
last=$(cat /run/r2-req-count 2>/dev/null || echo -1); echo "$n" > /run/r2-req-count
[ "$n" != "$last" ] && touch /run/t1-busy
exit 0
B
chmod 755 /usr/local/sbin/r2-busy
printf '[Unit]\nDescription=R2 busy marker\n[Service]\nType=oneshot\nExecStart=/usr/local/sbin/r2-busy\n' > /etc/systemd/system/r2-busy.service
printf '[Unit]\nDescription=R2 busy marker every minute\n[Timer]\nOnBootSec=2min\nOnUnitActiveSec=1min\n[Install]\nWantedBy=timers.target\n' > /etc/systemd/system/r2-busy.timer
systemctl daemon-reload; systemctl enable --now r2-busy.timer > /dev/null 2>&1

# ---------------------------------------------------------------------------------------------------- receipt
python3 - "$R/gpu-receipt.json" "$REPO" "$REV" "$IMG" "$OV" <<'PY'
import json, subprocess, sys, platform
def sh(c): return subprocess.run(c, shell=True, capture_output=True, text=True).stdout.strip()
out, repo, rev, img, ov = sys.argv[1:]
r = {"utc": sh("date -u +%FT%TZ"), "kernel": platform.release(), "model_repo": repo, "model_revision": rev, "serve_dir": ov,
     "model_sha256": json.load(open("/opt/r2/model-sha256.json")), "overlay": json.load(open("/opt/r2/overlay.json")),
     "vllm_image": img, "vllm_image_digest": sh(f"docker image inspect --format '{{{{index .RepoDigests 0}}}}' {img}"),
     "vllm_args": sh("docker inspect --format '{{json .Args}}' vllm"), "kv_cache": open("/opt/r2/kv-cache.txt").read().strip(),
     "gpu": sh("nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv,noheader"), "cuda": sh("nvidia-smi | grep -o 'CUDA Version: [0-9.]*'"),
     "instance": sh("curl -s -m 2 -H \"X-aws-ec2-metadata-token: $(curl -s -m 2 -X PUT http://169.254.169.254/latest/api/token -H 'X-aws-ec2-metadata-token-ttl-seconds: 60')\" http://169.254.169.254/latest/dynamic/instance-identity/document")}
json.dump(r, open(out, "w"), indent=1)
PY
say "GPU_BOOTSTRAP_DONE receipt $R/gpu-receipt.json (api key in $R/api-key, 0600; never print it)"