import json, os, subprocess, sys, hashlib, random, time, gc, collections from pathlib import Path CFG = json.loads(Path(sys.argv[1]).read_text("utf-8")) ROOT = Path(CFG["OUT_ROOT"]); SHARD, NSH = CFG["SHARD_ID"], CFG["N_SHARDS"] MODE, SEED, TIER = CFG["MODE"], CFG["SEED"], CFG["TIER"] MODEL_ID = "deepseek-ai/DeepSeek-R1-Distill-Llama-8B" LU_SHA = "a98961956072224eaf244eb289d6c01700b63795" N_PANEL, N_PROMPTS, RESERVE, MINWORK = 80, 5, 4.0, 20.0 os.environ["TOKENIZERS_PARALLELISM"] = "false" os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" # ---- device ------------------------------------------------------------- q = subprocess.run(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free,utilization.gpu", "--format=csv,noheader,nounits"], capture_output=True, text=True, check=True).stdout gpus = [] for line in q.strip().splitlines(): i, n, tot, free, u = [x.strip() for x in line.split(",")] gpus.append({"index": int(i), "name": n, "total": int(tot)/1024, "free": int(free)/1024, "util": int(u)}) print("devices: " + " ".join(f"[{g['index']}] {g['free']:.0f}/{g['total']:.0f}G {g['util']}%" for g in gpus)) d = (max(gpus, key=lambda g: g["free"]) if CFG["DEVICE_ID"] is None else next(g for g in gpus if g["index"] == CFG["DEVICE_ID"])) os.environ["CUDA_VISIBLE_DEVICES"] = str(d["index"]) # gpu_memory_utilization is a fraction of TOTAL, not free. Derive it from free # memory and leave a reserve so we do not evict another user's job. usable = d["free"] - RESERVE if usable < MINWORK: sys.exit(f"device {d['index']}: {usable:.1f} GiB usable after a {RESERVE} GiB " f"reserve, need {MINWORK}. Pick another DEVICE_ID from the list above.") UTIL = round(max(0.0, min(0.92, usable / d["total"])), 3) MAXLEN = 4096 if usable >= 26 else 2560 MAX_TOK = min(CFG["MAX_TOK"], MAXLEN - 640) import torch cap = torch.cuda.get_device_capability(0) DTYPE = "bfloat16" if cap[0] >= 8 else "float16" print(f"shard {SHARD}/{NSH} device {d['index']} sm_{cap[0]}{cap[1]} | usable " f"{usable:.1f} GiB -> util={UTIL} max_model_len={MAXLEN} max_tokens={MAX_TOK}") if MAX_TOK < CFG["MAX_TOK"]: print(f" NOTE capped at {MAX_TOK} by memory, not {CFG['MAX_TOK']}. Truncation " f"will stay higher than intended; record it.") # ---- Lu materials (already cloned; verify the pin) --------------------- vend = ROOT / "vendor" / "assistant-axis" head = subprocess.run(["git", "-C", str(vend), "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() assert head == LU_SHA, f"vendor at {head}, expected {LU_SHA}" D = vend / "data" role_list = json.loads((D/"roles"/"role_list.json").read_text("utf-8")) questions = [json.loads(l) for l in (D/"extraction_questions.jsonl").read_text("utf-8").splitlines() if l.strip()] assert len(role_list) == 275 and len(questions) == 240 QT = {x["id"]: x["question"] for x in questions} _ro = {} def role_obj(n): if n not in _ro: _ro[n] = json.loads((D/"roles"/"instructions"/f"{n}.json").read_text("utf-8")) return _ro[n] # ---- panel (already frozen; verify the fingerprint) ------------------- pf = ROOT / "design" / "panel.json" panel = json.loads(pf.read_text("utf-8")) PANEL = panel["question_ids"] FP = hashlib.sha256(json.dumps([PANEL, panel["half_a_ids"], panel["half_b_ids"]]).encode()).hexdigest()[:16] print(f"panel fingerprint: {FP}") if CFG["EXPECT_PANEL_FP"] and FP != CFG["EXPECT_PANEL_FP"]: sys.exit(f"PANEL MISMATCH: {FP} != {CFG['EXPECT_PANEL_FP']}. Outputs would not " f"be comparable across shards.") roles = (sorted(role_list) if TIER == "A" else sorted(random.Random(SEED).sample(sorted(role_list), 150))) WRAP = ("Stay in character for your entire reply. Answer in the first person. " "Never mention being an AI, a language model, or an assistant.") def build(role, pi, qid, cond): ins = role_obj(role)["instruction"][pi]["pos"] if role == "default": ins = ins.replace("{model_name}", "DeepSeek-R1") qq = QT[qid] if not ins: return qq return f"{ins}\n\n{qq}" if cond == "USER_TRANSLATED_LU" else f"{ins}\n\n{WRAP}\n\n{qq}" from transformers import AutoTokenizer tok = AutoTokenizer.from_pretrained(MODEL_ID) def render(u): # add_special_tokens=False: the template emits BOS and add_bos_token is True. return tok.apply_chat_template([{"role": "user", "content": u}], tokenize=False, add_generation_prompt=True) # ---- manifest --------------------------------------------------------- def uid(*p): return hashlib.sha256("|".join(map(str, p)).encode()).hexdigest()[:16] units = [] if MODE == "CALIBRATION": cal = sorted(random.Random(SEED + 1).sample(roles, 120 if TIER == "A" else 80)) for ri, r in enumerate(cal): if ri % NSH != SHARD: continue for pi in range(N_PROMPTS): for qid in PANEL[:2]: for c in ["USER_TRANSLATED_LU", "USER_EXPLICIT"]: units.append((uid(r, pi, qid, c), r, pi, qid, c)) elif MODE == "EXTRACTION": conds = (["USER_TRANSLATED_LU", "USER_EXPLICIT"] if CFG["CONDITION"] == "BOTH" else [CFG["CONDITION"]]) for r in roles: for i, qid in enumerate(PANEL): if i % NSH != SHARD: continue for c in conds: units.append((uid(r, i % N_PROMPTS, qid, c), r, i % N_PROMPTS, qid, c)) elif MODE == "DEFAULT": conds = (["USER_TRANSLATED_LU", "USER_EXPLICIT"] if CFG["CONDITION"] == "BOTH" else [CFG["CONDITION"]]) for pi in range(N_PROMPTS): for i, qid in enumerate(PANEL): if i % NSH != SHARD: continue for c in conds: units.append((uid("default", pi, qid, c), "default", pi, qid, c)) pc = collections.Counter(u[2] for u in units) print(f"{MODE} shard {SHARD}: {len(units)} units | {len(set(u[1] for u in units))} roles" f" | prompt balance {dict(sorted(pc.items()))}") od = ROOT / MODE.lower(); od.mkdir(parents=True, exist_ok=True) sf = od / f"rollouts_shard{SHARD}.jsonl" done = set() if sf.exists(): for line in sf.read_text("utf-8").splitlines(): try: done.add(json.loads(line)["uid"]) except Exception: pass todo = [u for u in units if u[0] not in done] print(f"resume: {len(done)} done, {len(todo)} to go") # ---- generate --------------------------------------------------------- if todo: from vllm import LLM, SamplingParams llm = LLM(model=MODEL_ID, dtype=DTYPE, gpu_memory_utilization=UTIL, max_model_len=MAXLEN, seed=SEED) sp = SamplingParams(temperature=CFG["TEMP"], top_p=CFG["TOP_P"], max_tokens=MAX_TOK, seed=SEED) t0 = time.time() for s in range(0, len(todo), CFG["CKPT_EVERY"]): chunk = todo[s:s + CFG["CKPT_EVERY"]] prompts = [render(build(r, pi, qid, c)) for _, r, pi, qid, c in chunk] outs = llm.generate(prompts, sp) with sf.open("a", encoding="utf-8") as fh: for (u, r, pi, qid, c), rp, o in zip(chunk, prompts, outs): t = o.outputs[0].text fh.write(json.dumps({ "uid": u, "shard": SHARD, "role": r, "prompt_idx": pi, "question_id": qid, "condition": c, "rendered_prompt": rp, "completion": t, "n_out_tokens": len(o.outputs[0].token_ids), "finish_reason": o.outputs[0].finish_reason, "closed_think": "" in t, # Stamp the config on every ROW. A resumed run recomputes the # report from rows that may predate a config change, so a # report-level field alone can misdescribe its own data. "gen_max_tokens": MAX_TOK, "gen_temperature": CFG["TEMP"], "gen_top_p": CFG["TOP_P"], "gen_seed": SEED, }, ensure_ascii=False) + "\n") n, el = min(s + len(chunk), len(todo)), time.time() - t0 print(f" {n}/{len(todo)} {n/max(el,1)*3600:.0f} outputs/h " f"eta {(len(todo)-n)/max(n,1)*el/3600:.2f}h", flush=True) del llm; gc.collect(); torch.cuda.empty_cache() # ---- report, derived from what the DATA says -------------------------- rows = [json.loads(l) for l in sf.read_text("utf-8").splitlines() if l.strip()] N = max(len(rows), 1) cfgs = collections.Counter((r.get("gen_max_tokens"), r.get("gen_temperature"), r.get("gen_top_p")) for r in rows) mixed = len(cfgs) > 1 or (None, None, None) in cfgs if mixed: print("\n!! MIXED/UNKNOWN GENERATION CONFIG ACROSS ROWS:") for k, v in cfgs.items(): print(f" max_tokens={k[0]} temp={k[1]} top_p={k[2]} -> {v} rollouts") rep = {"mode": MODE, "shard": SHARD, "n_shards": NSH, "tier": TIER, "condition": CFG["CONDITION"], "n_outputs": len(rows), "n_expected": len(units), "complete": len(rows) >= len(units), "panel_fingerprint": FP, "lu_commit": LU_SHA, "model": MODEL_ID, "device": d["name"], "device_index": d["index"], "dtype": DTYPE, "max_model_len": MAXLEN, "gpu_memory_utilization": UTIL, "generation_configs_in_data": {str(k): v for k, v in cfgs.items()}, "config_homogeneous": not mixed, "closed_think_rate": round(sum(r["closed_think"] for r in rows)/N, 4), "truncated_rate": round(sum(r["finish_reason"] == "length" for r in rows)/N, 4), "mean_out_tokens": round(sum(r["n_out_tokens"] for r in rows)/N, 1)} rf = od / f"run_report_shard{SHARD}.json" rf.write_text(json.dumps(rep, indent=2), "utf-8") print("\n" + json.dumps(rep, indent=2)) # ---- push ------------------------------------------------------------- if CFG["HF_PUSH"]: try: from huggingface_hub import HfApi, whoami api = HfApi(); R, base = CFG["HF_REPO"], CFG["RUN_ID"] api.create_repo(R, repo_type="dataset", exist_ok=True, private=True) print(f"\npushing to {R} as {whoami().get('name')}") for local, dest in ((sf, f"{MODE.lower()}/{sf.name}"), (rf, f"{MODE.lower()}/{rf.name}"), (pf, "design/panel.json"), (ROOT/"config.json", f"code/config_shard{SHARD}.json")): api.upload_file(path_or_fileobj=str(local), path_in_repo=f"{base}/{dest}", repo_id=R, repo_type="dataset") print(f" pushed {dest}") for content, dest in ( (Path(sys.argv[0]).read_text("utf-8"), f"code/worker_shard{SHARD}.py"), (subprocess.run([sys.executable, "-m", "pip", "freeze"], capture_output=True, text=True).stdout, "env/pip_freeze.txt"), (subprocess.run(["nvidia-smi"], capture_output=True, text=True).stdout, "env/nvidia_smi.txt")): api.upload_file(path_or_fileobj=content.encode("utf-8"), path_in_repo=f"{base}/{dest}", repo_id=R, repo_type="dataset") print(f" pushed {dest}") print("artifacts + code + env on the Hub.") except Exception as e: print(f"\nWARNING HF push failed: {type(e).__name__}: {e}") print(f"Outputs are safe on disk at {sf}") if rep["closed_think_rate"] < 0.90: print(f"\nWARNING closed_think_rate={rep['closed_think_rate']:.3f} < 0.90") print(f"\nDONE shard {SHARD}: {rep['n_outputs']}/{rep['n_expected']} " f"truncated {rep['truncated_rate']:.3%} mean_tokens {rep['mean_out_tokens']}")