Download lu-replication/run-003/code/worker_queue.py from Parth4105/persona-artifacts: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/datasets/Parth4105/persona-artifacts/resolve/main/lu-replication/run-003/code/worker_queue.py
- Command line
-
hf download hf://datasets/Parth4105/persona-artifacts/lu-replication/run-003/code/worker_queue.py
-
curl -L -o worker_queue.py https://huggingface.co/datasets/Parth4105/persona-artifacts/resolve/main/lu-replication/run-003/code/worker_queue.py
10.9 kB
| 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" | |
| 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"]) | |
| usable = d["free"] - RESERVE | |
| if usable < MINWORK: | |
| sys.exit(f"device {d['index']}: {usable:.1f} GiB usable, need {MINWORK}") | |
| 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"{MODE} shard {SHARD}/{NSH} device {d['index']} | usable {usable:.1f} GiB " | |
| f"-> util={UTIL} maxlen={MAXLEN} max_tokens={MAX_TOK}") | |
| 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] | |
| 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] | |
| if CFG["EXPECT_PANEL_FP"] and FP != CFG["EXPECT_PANEL_FP"]: | |
| sys.exit(f"PANEL MISMATCH {FP} != {CFG['EXPECT_PANEL_FP']}") | |
| print(f"panel {FP} ok") | |
| 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"] | |
| qq = QT[qid] | |
| if role == "default": | |
| # NEVER wrap the default. Lu's five default conditions are identity | |
| # statements ("You are an AI assistant.", "Respond as yourself.", and one | |
| # empty), not characters. Appending a role-adoption instruction here would | |
| # contradict the condition and corrupt mean(default), which is one half of | |
| # the Axis. | |
| ins = ins.replace("{model_name}", "DeepSeek-R1") | |
| return f"{ins}\n\n{qq}" if ins else qq | |
| 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) | |
| def uid(*p): return hashlib.sha256("|".join(map(str, p)).encode()).hexdigest()[:16] | |
| conds = (["USER_TRANSLATED_LU", "USER_EXPLICIT"] | |
| if CFG["CONDITION"] == "BOTH" else [CFG["CONDITION"]]) | |
| if MODE == "DEFAULT" and len(conds) > 1: | |
| # The wrapper never applies to default, so both conditions render IDENTICAL | |
| # prompts. uid includes the condition, so running both would silently | |
| # double-weight the default vector. Collapse to one. | |
| conds = conds[:1] | |
| print("DEFAULT: conditions render identically here; using one to avoid " | |
| "double-weighting mean(default)") | |
| units = [] | |
| if MODE == "EXTRACTION": | |
| for r in roles: | |
| for i, qid in enumerate(PANEL): | |
| if i % NSH != SHARD: continue # split by QUESTION index | |
| for c in conds: | |
| units.append((uid(r, i % N_PROMPTS, qid, c), r, i % N_PROMPTS, qid, c)) | |
| elif MODE == "DEFAULT": | |
| for pi in range(N_PROMPTS): # 5 default conditions | |
| for i, qid in enumerate(PANEL): # x 80 questions = 400 | |
| if i % NSH != SHARD: continue | |
| for c in conds: | |
| units.append((uid("default", pi, qid, c), "default", pi, qid, c)) | |
| else: | |
| sys.exit(f"queue handles EXTRACTION/DEFAULT, not {MODE}") | |
| pc = collections.Counter(u[2] for u in units) | |
| print(f"{len(units)} units | {len({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") | |
| if todo: | |
| print(f" ~{len(todo)/7000:.2f}-{len(todo)/5500:.2f} h at 5,500-7,000/h") | |
| 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) | |
| nc = nt = 0 | |
| 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 | |
| nc += "</think>" in t; nt += o.outputs[0].finish_reason == "length" | |
| 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": "</think>" in t, | |
| "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}/h " | |
| f"eta {(len(todo)-n)/max(n,1)*el/3600:.2f}h " | |
| f"[closed {nc/len(chunk):.1%} trunc {nt/len(chunk):.1%}]", flush=True) | |
| if CFG["HF_PUSH"]: | |
| try: | |
| from huggingface_hub import HfApi | |
| HfApi().upload_file(path_or_fileobj=str(sf), repo_id=CFG["HF_REPO"], | |
| repo_type="dataset", | |
| path_in_repo=f"{CFG['RUN_ID']}/{MODE.lower()}/{sf.name}") | |
| except Exception as e: | |
| print(f" (checkpoint push failed: {type(e).__name__}; disk ok)") | |
| del llm; gc.collect(); torch.cuda.empty_cache() | |
| 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")) for r in rows) | |
| per_role = collections.Counter(r["role"] for r in rows) | |
| rep = {"mode": MODE, "shard": SHARD, "n_shards": NSH, "tier": TIER, | |
| "condition": CFG["CONDITION"], "conditions_used": conds, | |
| "n_outputs": len(rows), "n_expected": len(units), | |
| "complete": len(rows) >= len(units), "panel_fingerprint": FP, | |
| "lu_commit": LU_SHA, "model": MODEL_ID, "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": len(cfgs) == 1, | |
| "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), | |
| "roles_present": len(per_role), | |
| "min_outputs_per_role": min(per_role.values()) if per_role else 0, | |
| "default_wrapper_applied": False if MODE == "DEFAULT" else None} | |
| 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)) | |
| if CFG["HF_PUSH"]: | |
| try: | |
| from huggingface_hub import HfApi | |
| api = HfApi(); R, base = CFG["HF_REPO"], CFG["RUN_ID"] | |
| for local, dest in ((sf, f"{MODE.lower()}/{sf.name}"), | |
| (rf, f"{MODE.lower()}/{rf.name}"), | |
| (pf, "design/panel.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}") | |
| api.upload_file(path_or_fileobj=Path(sys.argv[0]).read_text("utf-8").encode(), | |
| path_in_repo=f"{base}/code/worker_{MODE.lower()}_shard{SHARD}.py", | |
| repo_id=R, repo_type="dataset") | |
| api.upload_file(path_or_fileobj=json.dumps(CFG, indent=2).encode(), | |
| path_in_repo=f"{base}/code/config_{MODE.lower()}_shard{SHARD}.json", | |
| repo_id=R, repo_type="dataset") | |
| print(" pushed code + config") | |
| except Exception as e: | |
| print(f"WARNING HF push failed: {type(e).__name__}: {e}") | |
| print(f"Outputs safe on disk at {sf}") | |
| print(f"JOBDONE {MODE} shard {SHARD}: {rep['n_outputs']}/{rep['n_expected']} " | |
| f"complete={rep['complete']}") | |