Upload lu-replication/run-003/code/worker_shard0.py with huggingface_hub
Browse files
lu-replication/run-003/code/worker_shard0.py
CHANGED
|
@@ -2,135 +2,84 @@ import json, os, subprocess, sys, hashlib, random, time, gc, collections
|
|
| 2 |
from pathlib import Path
|
| 3 |
|
| 4 |
CFG = json.loads(Path(sys.argv[1]).read_text("utf-8"))
|
| 5 |
-
ROOT = Path(CFG["OUT_ROOT"])
|
| 6 |
-
|
| 7 |
-
SEED, TIER = CFG["SEED"], CFG["TIER"]
|
| 8 |
MODEL_ID = "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
N_PANEL, N_PROMPTS = 80, 5
|
| 12 |
-
RESERVE_GIB, MIN_WORK_GIB = 4.0, 20.0
|
| 13 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 14 |
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 15 |
-
assert 0 <= SHARD < NSH
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
# ---- device ---------------------------------------------------------------
|
| 20 |
q = subprocess.run(["nvidia-smi",
|
| 21 |
"--query-gpu=index,name,memory.total,memory.free,utilization.gpu",
|
| 22 |
"--format=csv,noheader,nounits"], capture_output=True, text=True, check=True).stdout
|
| 23 |
gpus = []
|
| 24 |
for line in q.strip().splitlines():
|
| 25 |
-
i, n, tot, free,
|
| 26 |
gpus.append({"index": int(i), "name": n, "total": int(tot)/1024,
|
| 27 |
-
"free": int(free)/1024, "util": int(
|
| 28 |
-
print("devices: " + " ".join(
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
if
|
| 32 |
-
d = max(gpus, key=lambda g: g["free"])
|
| 33 |
-
print(f"auto-picked device {d['index']} (pin DEVICE_ID on a shared box)")
|
| 34 |
-
else:
|
| 35 |
-
d = next(g for g in gpus if g["index"] == CFG["DEVICE_ID"])
|
| 36 |
os.environ["CUDA_VISIBLE_DEVICES"] = str(d["index"])
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
usable
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
f"DEVICE_ID from the list above, or run this shard on Colab.")
|
| 46 |
-
UTIL = round(max(0.0, min(0.92, usable / d["total"])), 3)
|
| 47 |
MAXLEN = 4096 if usable >= 26 else 2560
|
| 48 |
MAX_TOK = min(CFG["MAX_TOK"], MAXLEN - 640)
|
| 49 |
|
| 50 |
import torch
|
| 51 |
cap = torch.cuda.get_device_capability(0)
|
| 52 |
-
DTYPE = "bfloat16" if cap[0] >= 8 else "float16"
|
| 53 |
-
print(f"shard {SHARD}/{NSH}
|
| 54 |
-
f"
|
| 55 |
-
f"max_model_len={MAXLEN} max_tokens={MAX_TOK} {DTYPE}")
|
| 56 |
if MAX_TOK < CFG["MAX_TOK"]:
|
| 57 |
-
print(f" NOTE
|
| 58 |
-
f"
|
| 59 |
|
| 60 |
-
# ---- Lu
|
| 61 |
vend = ROOT / "vendor" / "assistant-axis"
|
| 62 |
-
if not (vend / "data").exists():
|
| 63 |
-
vend.parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
-
sh("git", "init", "-q", str(vend))
|
| 65 |
-
sh("git", "-C", str(vend), "remote", "add", "origin", LU_REPO)
|
| 66 |
-
sh("git", "-C", str(vend), "fetch", "-q", "--depth", "1", "origin", LU_SHA)
|
| 67 |
-
sh("git", "-C", str(vend), "checkout", "-q", "FETCH_HEAD")
|
| 68 |
head = subprocess.run(["git", "-C", str(vend), "rev-parse", "HEAD"],
|
| 69 |
capture_output=True, text=True, check=True).stdout.strip()
|
| 70 |
assert head == LU_SHA, f"vendor at {head}, expected {LU_SHA}"
|
| 71 |
D = vend / "data"
|
| 72 |
-
role_list = json.loads((D
|
| 73 |
questions = [json.loads(l) for l in
|
| 74 |
(D/"extraction_questions.jsonl").read_text("utf-8").splitlines() if l.strip()]
|
| 75 |
-
assert len(role_list) == 275 and len(questions) == 240
|
| 76 |
-
|
| 77 |
_ro = {}
|
| 78 |
def role_obj(n):
|
| 79 |
if n not in _ro:
|
| 80 |
_ro[n] = json.loads((D/"roles"/"instructions"/f"{n}.json").read_text("utf-8"))
|
| 81 |
return _ro[n]
|
| 82 |
|
| 83 |
-
# ----
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# derivable. If T16 lands a semantic categorisation, delete panel.json and rerun.
|
| 87 |
-
pf = ROOT / "design" / "panel.json"; pf.parent.mkdir(parents=True, exist_ok=True)
|
| 88 |
-
if pf.exists():
|
| 89 |
-
panel = json.loads(pf.read_text("utf-8"))
|
| 90 |
-
else:
|
| 91 |
-
qs = sorted(questions, key=lambda x: len(x["question"]))
|
| 92 |
-
strata = [qs[i::4] for i in range(4)]
|
| 93 |
-
rng = random.Random(SEED); chosen = []
|
| 94 |
-
for s in strata: chosen += rng.sample(s, N_PANEL // 4)
|
| 95 |
-
chosen.sort(key=lambda x: x["id"])
|
| 96 |
-
ha, hb = [], []
|
| 97 |
-
for i in range(4):
|
| 98 |
-
blk = [x for x in chosen if x in strata[i]]; rng.shuffle(blk)
|
| 99 |
-
ha += blk[:len(blk)//2]; hb += blk[len(blk)//2:]
|
| 100 |
-
panel = {"seed": SEED, "n": len(chosen),
|
| 101 |
-
"strategy": "length-quartile stratified; semantic categories pending T16",
|
| 102 |
-
"question_ids": [x["id"] for x in chosen],
|
| 103 |
-
"half_a_ids": sorted(x["id"] for x in ha),
|
| 104 |
-
"half_b_ids": sorted(x["id"] for x in hb)}
|
| 105 |
-
pf.write_text(json.dumps(panel, indent=2), "utf-8")
|
| 106 |
PANEL = panel["question_ids"]
|
| 107 |
-
FP = hashlib.sha256(json.dumps(
|
| 108 |
-
|
| 109 |
print(f"panel fingerprint: {FP}")
|
| 110 |
-
if CFG["EXPECT_PANEL_FP"]
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
elif FP != CFG["EXPECT_PANEL_FP"]:
|
| 114 |
-
sys.exit(f"PANEL MISMATCH: have {FP}, expected {CFG['EXPECT_PANEL_FP']}. Your "
|
| 115 |
-
f"panels differ so outputs are NOT comparable. Delete {pf} and copy "
|
| 116 |
-
f"shard 0's panel.json.")
|
| 117 |
-
assert len(PANEL) == N_PANEL
|
| 118 |
-
QT = {x["id"]: x["question"] for x in questions}
|
| 119 |
|
| 120 |
-
# ---- roles ---------------------------------------------------------------
|
| 121 |
roles = (sorted(role_list) if TIER == "A"
|
| 122 |
else sorted(random.Random(SEED).sample(sorted(role_list), 150)))
|
| 123 |
|
| 124 |
-
# ---- prompt channel ------------------------------------------------------
|
| 125 |
-
# The chat template DOES render system content, as a bare prefix after BOS with
|
| 126 |
-
# no role delimiter. So user-turn delivery is a CHOICE, not a necessity - both
|
| 127 |
-
# conditions below are user-turn as the plan pre-declared.
|
| 128 |
WRAP = ("Stay in character for your entire reply. Answer in the first person. "
|
| 129 |
"Never mention being an AI, a language model, or an assistant.")
|
| 130 |
def build(role, pi, qid, cond):
|
| 131 |
ins = role_obj(role)["instruction"][pi]["pos"]
|
| 132 |
-
if role == "default":
|
| 133 |
-
ins = ins.replace("{model_name}", "DeepSeek-R1") # the only template var
|
| 134 |
qq = QT[qid]
|
| 135 |
if not ins: return qq
|
| 136 |
return f"{ins}\n\n{qq}" if cond == "USER_TRANSLATED_LU" else f"{ins}\n\n{WRAP}\n\n{qq}"
|
|
@@ -138,34 +87,14 @@ def build(role, pi, qid, cond):
|
|
| 138 |
from transformers import AutoTokenizer
|
| 139 |
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 140 |
def render(u):
|
| 141 |
-
# add_special_tokens=False: the template emits BOS and add_bos_token is True
|
| 142 |
-
# so a second BOS shifts every activation by one position.
|
| 143 |
return tok.apply_chat_template([{"role": "user", "content": u}],
|
| 144 |
tokenize=False, add_generation_prompt=True)
|
| 145 |
|
| 146 |
-
# ---- manifest
|
| 147 |
-
conds = (["USER_TRANSLATED_LU", "USER_EXPLICIT"]
|
| 148 |
-
if CFG["CONDITION"] == "BOTH" else [CFG["CONDITION"]])
|
| 149 |
def uid(*p): return hashlib.sha256("|".join(map(str, p)).encode()).hexdigest()[:16]
|
| 150 |
-
|
| 151 |
units = []
|
| 152 |
-
if MODE == "
|
| 153 |
-
# Split by QUESTION index, not role: every shard covers all 275 roles, so a
|
| 154 |
-
# lost shard costs all roles the same questions rather than deleting ~92
|
| 155 |
-
# roles and failing the 180-retained-vector gate outright. 3 and 5 are
|
| 156 |
-
# coprime, so prompt balance survives the split.
|
| 157 |
-
for r in roles:
|
| 158 |
-
for i, qid in enumerate(PANEL):
|
| 159 |
-
if i % NSH != SHARD: continue
|
| 160 |
-
for c in conds: units.append((uid(r, i % N_PROMPTS, qid, c), r, i % N_PROMPTS, qid, c))
|
| 161 |
-
elif MODE == "DEFAULT":
|
| 162 |
-
for pi in range(N_PROMPTS):
|
| 163 |
-
for i, qid in enumerate(PANEL):
|
| 164 |
-
if i % NSH != SHARD: continue
|
| 165 |
-
for c in conds: units.append((uid("default", pi, qid, c), "default", pi, qid, c))
|
| 166 |
-
elif MODE == "CALIBRATION":
|
| 167 |
-
# Splits by ROLE here: only 2,400 outputs, and role coverage matters more
|
| 168 |
-
# than question coverage for choosing a prompt condition.
|
| 169 |
cal = sorted(random.Random(SEED + 1).sample(roles, 120 if TIER == "A" else 80))
|
| 170 |
for ri, r in enumerate(cal):
|
| 171 |
if ri % NSH != SHARD: continue
|
|
@@ -173,29 +102,41 @@ elif MODE == "CALIBRATION":
|
|
| 173 |
for qid in PANEL[:2]:
|
| 174 |
for c in ["USER_TRANSLATED_LU", "USER_EXPLICIT"]:
|
| 175 |
units.append((uid(r, pi, qid, c), r, pi, qid, c))
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
pc = collections.Counter(u[2] for u in units)
|
| 180 |
print(f"{MODE} shard {SHARD}: {len(units)} units | {len(set(u[1] for u in units))} roles"
|
| 181 |
-
f" |
|
| 182 |
|
| 183 |
-
# ---- resume --------------------------------------------------------------
|
| 184 |
od = ROOT / MODE.lower(); od.mkdir(parents=True, exist_ok=True)
|
| 185 |
sf = od / f"rollouts_shard{SHARD}.jsonl"
|
| 186 |
done = set()
|
| 187 |
if sf.exists():
|
| 188 |
for line in sf.read_text("utf-8").splitlines():
|
| 189 |
try: done.add(json.loads(line)["uid"])
|
| 190 |
-
except Exception: pass
|
| 191 |
todo = [u for u in units if u[0] not in done]
|
| 192 |
print(f"resume: {len(done)} done, {len(todo)} to go")
|
| 193 |
|
| 194 |
-
# ---- generate ---------------------------------------------------------
|
| 195 |
if todo:
|
| 196 |
from vllm import LLM, SamplingParams
|
| 197 |
llm = LLM(model=MODEL_ID, dtype=DTYPE, gpu_memory_utilization=UTIL,
|
| 198 |
-
max_model_len=MAXLEN, seed=SEED
|
| 199 |
sp = SamplingParams(temperature=CFG["TEMP"], top_p=CFG["TOP_P"],
|
| 200 |
max_tokens=MAX_TOK, seed=SEED)
|
| 201 |
t0 = time.time()
|
|
@@ -211,23 +152,36 @@ if todo:
|
|
| 211 |
"question_id": qid, "condition": c, "rendered_prompt": rp,
|
| 212 |
"completion": t, "n_out_tokens": len(o.outputs[0].token_ids),
|
| 213 |
"finish_reason": o.outputs[0].finish_reason,
|
| 214 |
-
"closed_think": "</think>" in t
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
n, el = min(s + len(chunk), len(todo)), time.time() - t0
|
| 216 |
print(f" {n}/{len(todo)} {n/max(el,1)*3600:.0f} outputs/h "
|
| 217 |
-
f"eta {(len(todo)-n)/max(n,1)*el/3600:.
|
| 218 |
del llm; gc.collect(); torch.cuda.empty_cache()
|
| 219 |
|
| 220 |
-
# ---- report --------------------------
|
| 221 |
rows = [json.loads(l) for l in sf.read_text("utf-8").splitlines() if l.strip()]
|
| 222 |
N = max(len(rows), 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
rep = {"mode": MODE, "shard": SHARD, "n_shards": NSH, "tier": TIER,
|
| 224 |
-
"condition": CFG["CONDITION"], "n_outputs": len(rows),
|
| 225 |
-
"complete": len(rows) >= len(units),
|
| 226 |
-
"
|
| 227 |
-
"
|
| 228 |
-
"gpu_memory_utilization": UTIL,
|
| 229 |
-
"
|
| 230 |
-
|
| 231 |
"closed_think_rate": round(sum(r["closed_think"] for r in rows)/N, 4),
|
| 232 |
"truncated_rate": round(sum(r["finish_reason"] == "length" for r in rows)/N, 4),
|
| 233 |
"mean_out_tokens": round(sum(r["n_out_tokens"] for r in rows)/N, 1)}
|
|
@@ -235,41 +189,35 @@ rf = od / f"run_report_shard{SHARD}.json"
|
|
| 235 |
rf.write_text(json.dumps(rep, indent=2), "utf-8")
|
| 236 |
print("\n" + json.dumps(rep, indent=2))
|
| 237 |
|
| 238 |
-
# ----
|
| 239 |
if CFG["HF_PUSH"]:
|
| 240 |
try:
|
| 241 |
from huggingface_hub import HfApi, whoami
|
| 242 |
-
api = HfApi();
|
| 243 |
-
api.create_repo(
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
| 246 |
api.upload_file(path_or_fileobj=str(local), path_in_repo=f"{base}/{dest}",
|
| 247 |
repo_id=R, repo_type="dataset")
|
| 248 |
print(f" pushed {dest}")
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
api.upload_file(path_or_fileobj=content.encode("utf-8"),
|
| 251 |
path_in_repo=f"{base}/{dest}", repo_id=R, repo_type="dataset")
|
| 252 |
print(f" pushed {dest}")
|
| 253 |
-
print(
|
| 254 |
-
up(sf, f"{MODE.lower()}/{sf.name}")
|
| 255 |
-
up(rf, f"{MODE.lower()}/{rf.name}")
|
| 256 |
-
up(pf, "design/panel.json")
|
| 257 |
-
up(ROOT / "config.json", f"code/config_shard{SHARD}.json")
|
| 258 |
-
# The exact source that produced these artifacts, stored beside them.
|
| 259 |
-
upb(Path(sys.argv[0]).read_text("utf-8"), f"code/worker_shard{SHARD}.py")
|
| 260 |
-
upb(subprocess.run([sys.executable, "-m", "pip", "freeze"],
|
| 261 |
-
capture_output=True, text=True).stdout, "env/pip_freeze.txt")
|
| 262 |
-
upb(subprocess.run(["nvidia-smi"], capture_output=True, text=True).stdout,
|
| 263 |
-
"env/nvidia_smi.txt")
|
| 264 |
-
print("artifacts + code + env on the Hub. Safe to lose this box.")
|
| 265 |
except Exception as e:
|
| 266 |
print(f"\nWARNING HF push failed: {type(e).__name__}: {e}")
|
| 267 |
-
print(f"Outputs are on disk at {sf}
|
| 268 |
-
f"TERMINAL (not a cell - the token would be saved into notebook "
|
| 269 |
-
f"output) and re-run this cell; it resumes and only pushes.")
|
| 270 |
|
| 271 |
if rep["closed_think_rate"] < 0.90:
|
| 272 |
-
print(f"\nWARNING closed_think_rate={rep['closed_think_rate']:.3f} < 0.90
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
print(f"\nDONE shard {SHARD}: {rep['n_outputs']}/{rep['n_expected']} outputs")
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
|
| 4 |
CFG = json.loads(Path(sys.argv[1]).read_text("utf-8"))
|
| 5 |
+
ROOT = Path(CFG["OUT_ROOT"]); SHARD, NSH = CFG["SHARD_ID"], CFG["N_SHARDS"]
|
| 6 |
+
MODE, SEED, TIER = CFG["MODE"], CFG["SEED"], CFG["TIER"]
|
|
|
|
| 7 |
MODEL_ID = "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
|
| 8 |
+
LU_SHA = "a98961956072224eaf244eb289d6c01700b63795"
|
| 9 |
+
N_PANEL, N_PROMPTS, RESERVE, MINWORK = 80, 5, 4.0, 20.0
|
|
|
|
|
|
|
| 10 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 11 |
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
|
|
|
| 12 |
|
| 13 |
+
# ---- device -------------------------------------------------------------
|
|
|
|
|
|
|
| 14 |
q = subprocess.run(["nvidia-smi",
|
| 15 |
"--query-gpu=index,name,memory.total,memory.free,utilization.gpu",
|
| 16 |
"--format=csv,noheader,nounits"], capture_output=True, text=True, check=True).stdout
|
| 17 |
gpus = []
|
| 18 |
for line in q.strip().splitlines():
|
| 19 |
+
i, n, tot, free, u = [x.strip() for x in line.split(",")]
|
| 20 |
gpus.append({"index": int(i), "name": n, "total": int(tot)/1024,
|
| 21 |
+
"free": int(free)/1024, "util": int(u)})
|
| 22 |
+
print("devices: " + " ".join(f"[{g['index']}] {g['free']:.0f}/{g['total']:.0f}G {g['util']}%"
|
| 23 |
+
for g in gpus))
|
| 24 |
+
d = (max(gpus, key=lambda g: g["free"]) if CFG["DEVICE_ID"] is None
|
| 25 |
+
else next(g for g in gpus if g["index"] == CFG["DEVICE_ID"]))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
os.environ["CUDA_VISIBLE_DEVICES"] = str(d["index"])
|
| 27 |
|
| 28 |
+
# gpu_memory_utilization is a fraction of TOTAL, not free. Derive it from free
|
| 29 |
+
# memory and leave a reserve so we do not evict another user's job.
|
| 30 |
+
usable = d["free"] - RESERVE
|
| 31 |
+
if usable < MINWORK:
|
| 32 |
+
sys.exit(f"device {d['index']}: {usable:.1f} GiB usable after a {RESERVE} GiB "
|
| 33 |
+
f"reserve, need {MINWORK}. Pick another DEVICE_ID from the list above.")
|
| 34 |
+
UTIL = round(max(0.0, min(0.92, usable / d["total"])), 3)
|
|
|
|
|
|
|
| 35 |
MAXLEN = 4096 if usable >= 26 else 2560
|
| 36 |
MAX_TOK = min(CFG["MAX_TOK"], MAXLEN - 640)
|
| 37 |
|
| 38 |
import torch
|
| 39 |
cap = torch.cuda.get_device_capability(0)
|
| 40 |
+
DTYPE = "bfloat16" if cap[0] >= 8 else "float16"
|
| 41 |
+
print(f"shard {SHARD}/{NSH} device {d['index']} sm_{cap[0]}{cap[1]} | usable "
|
| 42 |
+
f"{usable:.1f} GiB -> util={UTIL} max_model_len={MAXLEN} max_tokens={MAX_TOK}")
|
|
|
|
| 43 |
if MAX_TOK < CFG["MAX_TOK"]:
|
| 44 |
+
print(f" NOTE capped at {MAX_TOK} by memory, not {CFG['MAX_TOK']}. Truncation "
|
| 45 |
+
f"will stay higher than intended; record it.")
|
| 46 |
|
| 47 |
+
# ---- Lu materials (already cloned; verify the pin) ---------------------
|
| 48 |
vend = ROOT / "vendor" / "assistant-axis"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
head = subprocess.run(["git", "-C", str(vend), "rev-parse", "HEAD"],
|
| 50 |
capture_output=True, text=True, check=True).stdout.strip()
|
| 51 |
assert head == LU_SHA, f"vendor at {head}, expected {LU_SHA}"
|
| 52 |
D = vend / "data"
|
| 53 |
+
role_list = json.loads((D/"roles"/"role_list.json").read_text("utf-8"))
|
| 54 |
questions = [json.loads(l) for l in
|
| 55 |
(D/"extraction_questions.jsonl").read_text("utf-8").splitlines() if l.strip()]
|
| 56 |
+
assert len(role_list) == 275 and len(questions) == 240
|
| 57 |
+
QT = {x["id"]: x["question"] for x in questions}
|
| 58 |
_ro = {}
|
| 59 |
def role_obj(n):
|
| 60 |
if n not in _ro:
|
| 61 |
_ro[n] = json.loads((D/"roles"/"instructions"/f"{n}.json").read_text("utf-8"))
|
| 62 |
return _ro[n]
|
| 63 |
|
| 64 |
+
# ---- panel (already frozen; verify the fingerprint) -------------------
|
| 65 |
+
pf = ROOT / "design" / "panel.json"
|
| 66 |
+
panel = json.loads(pf.read_text("utf-8"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
PANEL = panel["question_ids"]
|
| 68 |
+
FP = hashlib.sha256(json.dumps([PANEL, panel["half_a_ids"],
|
| 69 |
+
panel["half_b_ids"]]).encode()).hexdigest()[:16]
|
| 70 |
print(f"panel fingerprint: {FP}")
|
| 71 |
+
if CFG["EXPECT_PANEL_FP"] and FP != CFG["EXPECT_PANEL_FP"]:
|
| 72 |
+
sys.exit(f"PANEL MISMATCH: {FP} != {CFG['EXPECT_PANEL_FP']}. Outputs would not "
|
| 73 |
+
f"be comparable across shards.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
|
|
|
| 75 |
roles = (sorted(role_list) if TIER == "A"
|
| 76 |
else sorted(random.Random(SEED).sample(sorted(role_list), 150)))
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
WRAP = ("Stay in character for your entire reply. Answer in the first person. "
|
| 79 |
"Never mention being an AI, a language model, or an assistant.")
|
| 80 |
def build(role, pi, qid, cond):
|
| 81 |
ins = role_obj(role)["instruction"][pi]["pos"]
|
| 82 |
+
if role == "default": ins = ins.replace("{model_name}", "DeepSeek-R1")
|
|
|
|
| 83 |
qq = QT[qid]
|
| 84 |
if not ins: return qq
|
| 85 |
return f"{ins}\n\n{qq}" if cond == "USER_TRANSLATED_LU" else f"{ins}\n\n{WRAP}\n\n{qq}"
|
|
|
|
| 87 |
from transformers import AutoTokenizer
|
| 88 |
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 89 |
def render(u):
|
| 90 |
+
# add_special_tokens=False: the template emits BOS and add_bos_token is True.
|
|
|
|
| 91 |
return tok.apply_chat_template([{"role": "user", "content": u}],
|
| 92 |
tokenize=False, add_generation_prompt=True)
|
| 93 |
|
| 94 |
+
# ---- manifest ---------------------------------------------------------
|
|
|
|
|
|
|
| 95 |
def uid(*p): return hashlib.sha256("|".join(map(str, p)).encode()).hexdigest()[:16]
|
|
|
|
| 96 |
units = []
|
| 97 |
+
if MODE == "CALIBRATION":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
cal = sorted(random.Random(SEED + 1).sample(roles, 120 if TIER == "A" else 80))
|
| 99 |
for ri, r in enumerate(cal):
|
| 100 |
if ri % NSH != SHARD: continue
|
|
|
|
| 102 |
for qid in PANEL[:2]:
|
| 103 |
for c in ["USER_TRANSLATED_LU", "USER_EXPLICIT"]:
|
| 104 |
units.append((uid(r, pi, qid, c), r, pi, qid, c))
|
| 105 |
+
elif MODE == "EXTRACTION":
|
| 106 |
+
conds = (["USER_TRANSLATED_LU", "USER_EXPLICIT"]
|
| 107 |
+
if CFG["CONDITION"] == "BOTH" else [CFG["CONDITION"]])
|
| 108 |
+
for r in roles:
|
| 109 |
+
for i, qid in enumerate(PANEL):
|
| 110 |
+
if i % NSH != SHARD: continue
|
| 111 |
+
for c in conds:
|
| 112 |
+
units.append((uid(r, i % N_PROMPTS, qid, c), r, i % N_PROMPTS, qid, c))
|
| 113 |
+
elif MODE == "DEFAULT":
|
| 114 |
+
conds = (["USER_TRANSLATED_LU", "USER_EXPLICIT"]
|
| 115 |
+
if CFG["CONDITION"] == "BOTH" else [CFG["CONDITION"]])
|
| 116 |
+
for pi in range(N_PROMPTS):
|
| 117 |
+
for i, qid in enumerate(PANEL):
|
| 118 |
+
if i % NSH != SHARD: continue
|
| 119 |
+
for c in conds:
|
| 120 |
+
units.append((uid("default", pi, qid, c), "default", pi, qid, c))
|
| 121 |
pc = collections.Counter(u[2] for u in units)
|
| 122 |
print(f"{MODE} shard {SHARD}: {len(units)} units | {len(set(u[1] for u in units))} roles"
|
| 123 |
+
f" | prompt balance {dict(sorted(pc.items()))}")
|
| 124 |
|
|
|
|
| 125 |
od = ROOT / MODE.lower(); od.mkdir(parents=True, exist_ok=True)
|
| 126 |
sf = od / f"rollouts_shard{SHARD}.jsonl"
|
| 127 |
done = set()
|
| 128 |
if sf.exists():
|
| 129 |
for line in sf.read_text("utf-8").splitlines():
|
| 130 |
try: done.add(json.loads(line)["uid"])
|
| 131 |
+
except Exception: pass
|
| 132 |
todo = [u for u in units if u[0] not in done]
|
| 133 |
print(f"resume: {len(done)} done, {len(todo)} to go")
|
| 134 |
|
| 135 |
+
# ---- generate ---------------------------------------------------------
|
| 136 |
if todo:
|
| 137 |
from vllm import LLM, SamplingParams
|
| 138 |
llm = LLM(model=MODEL_ID, dtype=DTYPE, gpu_memory_utilization=UTIL,
|
| 139 |
+
max_model_len=MAXLEN, seed=SEED)
|
| 140 |
sp = SamplingParams(temperature=CFG["TEMP"], top_p=CFG["TOP_P"],
|
| 141 |
max_tokens=MAX_TOK, seed=SEED)
|
| 142 |
t0 = time.time()
|
|
|
|
| 152 |
"question_id": qid, "condition": c, "rendered_prompt": rp,
|
| 153 |
"completion": t, "n_out_tokens": len(o.outputs[0].token_ids),
|
| 154 |
"finish_reason": o.outputs[0].finish_reason,
|
| 155 |
+
"closed_think": "</think>" in t,
|
| 156 |
+
# Stamp the config on every ROW. A resumed run recomputes the
|
| 157 |
+
# report from rows that may predate a config change, so a
|
| 158 |
+
# report-level field alone can misdescribe its own data.
|
| 159 |
+
"gen_max_tokens": MAX_TOK, "gen_temperature": CFG["TEMP"],
|
| 160 |
+
"gen_top_p": CFG["TOP_P"], "gen_seed": SEED,
|
| 161 |
+
}, ensure_ascii=False) + "\n")
|
| 162 |
n, el = min(s + len(chunk), len(todo)), time.time() - t0
|
| 163 |
print(f" {n}/{len(todo)} {n/max(el,1)*3600:.0f} outputs/h "
|
| 164 |
+
f"eta {(len(todo)-n)/max(n,1)*el/3600:.2f}h", flush=True)
|
| 165 |
del llm; gc.collect(); torch.cuda.empty_cache()
|
| 166 |
|
| 167 |
+
# ---- report, derived from what the DATA says --------------------------
|
| 168 |
rows = [json.loads(l) for l in sf.read_text("utf-8").splitlines() if l.strip()]
|
| 169 |
N = max(len(rows), 1)
|
| 170 |
+
cfgs = collections.Counter((r.get("gen_max_tokens"), r.get("gen_temperature"),
|
| 171 |
+
r.get("gen_top_p")) for r in rows)
|
| 172 |
+
mixed = len(cfgs) > 1 or (None, None, None) in cfgs
|
| 173 |
+
if mixed:
|
| 174 |
+
print("\n!! MIXED/UNKNOWN GENERATION CONFIG ACROSS ROWS:")
|
| 175 |
+
for k, v in cfgs.items():
|
| 176 |
+
print(f" max_tokens={k[0]} temp={k[1]} top_p={k[2]} -> {v} rollouts")
|
| 177 |
rep = {"mode": MODE, "shard": SHARD, "n_shards": NSH, "tier": TIER,
|
| 178 |
+
"condition": CFG["CONDITION"], "n_outputs": len(rows),
|
| 179 |
+
"n_expected": len(units), "complete": len(rows) >= len(units),
|
| 180 |
+
"panel_fingerprint": FP, "lu_commit": LU_SHA, "model": MODEL_ID,
|
| 181 |
+
"device": d["name"], "device_index": d["index"], "dtype": DTYPE,
|
| 182 |
+
"max_model_len": MAXLEN, "gpu_memory_utilization": UTIL,
|
| 183 |
+
"generation_configs_in_data": {str(k): v for k, v in cfgs.items()},
|
| 184 |
+
"config_homogeneous": not mixed,
|
| 185 |
"closed_think_rate": round(sum(r["closed_think"] for r in rows)/N, 4),
|
| 186 |
"truncated_rate": round(sum(r["finish_reason"] == "length" for r in rows)/N, 4),
|
| 187 |
"mean_out_tokens": round(sum(r["n_out_tokens"] for r in rows)/N, 1)}
|
|
|
|
| 189 |
rf.write_text(json.dumps(rep, indent=2), "utf-8")
|
| 190 |
print("\n" + json.dumps(rep, indent=2))
|
| 191 |
|
| 192 |
+
# ---- push -------------------------------------------------------------
|
| 193 |
if CFG["HF_PUSH"]:
|
| 194 |
try:
|
| 195 |
from huggingface_hub import HfApi, whoami
|
| 196 |
+
api = HfApi(); R, base = CFG["HF_REPO"], CFG["RUN_ID"]
|
| 197 |
+
api.create_repo(R, repo_type="dataset", exist_ok=True, private=True)
|
| 198 |
+
print(f"\npushing to {R} as {whoami().get('name')}")
|
| 199 |
+
for local, dest in ((sf, f"{MODE.lower()}/{sf.name}"),
|
| 200 |
+
(rf, f"{MODE.lower()}/{rf.name}"),
|
| 201 |
+
(pf, "design/panel.json"),
|
| 202 |
+
(ROOT/"config.json", f"code/config_shard{SHARD}.json")):
|
| 203 |
api.upload_file(path_or_fileobj=str(local), path_in_repo=f"{base}/{dest}",
|
| 204 |
repo_id=R, repo_type="dataset")
|
| 205 |
print(f" pushed {dest}")
|
| 206 |
+
for content, dest in (
|
| 207 |
+
(Path(sys.argv[0]).read_text("utf-8"), f"code/worker_shard{SHARD}.py"),
|
| 208 |
+
(subprocess.run([sys.executable, "-m", "pip", "freeze"],
|
| 209 |
+
capture_output=True, text=True).stdout, "env/pip_freeze.txt"),
|
| 210 |
+
(subprocess.run(["nvidia-smi"], capture_output=True, text=True).stdout,
|
| 211 |
+
"env/nvidia_smi.txt")):
|
| 212 |
api.upload_file(path_or_fileobj=content.encode("utf-8"),
|
| 213 |
path_in_repo=f"{base}/{dest}", repo_id=R, repo_type="dataset")
|
| 214 |
print(f" pushed {dest}")
|
| 215 |
+
print("artifacts + code + env on the Hub.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
except Exception as e:
|
| 217 |
print(f"\nWARNING HF push failed: {type(e).__name__}: {e}")
|
| 218 |
+
print(f"Outputs are safe on disk at {sf}")
|
|
|
|
|
|
|
| 219 |
|
| 220 |
if rep["closed_think_rate"] < 0.90:
|
| 221 |
+
print(f"\nWARNING closed_think_rate={rep['closed_think_rate']:.3f} < 0.90")
|
| 222 |
+
print(f"\nDONE shard {SHARD}: {rep['n_outputs']}/{rep['n_expected']} "
|
| 223 |
+
f"truncated {rep['truncated_rate']:.3%} mean_tokens {rep['mean_out_tokens']}")
|
|
|