persona-artifacts / lu-replication /run-003 /code /worker_act_translated.py
Parth4105's picture
Upload lu-replication/run-003/code/worker_act_translated.py with huggingface_hub
30e4bff verified
Raw History Blame Contribute Delete
7.75 kB
import json, os, sys, time, gc, collections, subprocess
from pathlib import Path
CFG=json.loads(Path(sys.argv[1]).read_text("utf-8")); ROOT=Path(CFG["OUT_ROOT"])
MODEL_ID="deepseek-ai/DeepSeek-R1-Distill-Llama-8B"; THINK="</think>"; RESERVE=4.0
os.environ["TOKENIZERS_PARALLELISM"]="false"; os.environ["HF_HUB_ENABLE_HF_TRANSFER"]="1"
q=subprocess.run(["nvidia-smi","--query-gpu=index,memory.total,memory.free,utilization.gpu",
"--format=csv,noheader,nounits"],capture_output=True,text=True,check=True).stdout
gpus=[{"index":int(a),"total":int(b)/1024,"free":int(c)/1024,"util":int(d)}
for a,b,c,d in (x.split(",") for x in q.strip().splitlines())]
print("devices: "+" ".join(f"[{g['index']}] {g['free']:.0f}/{g['total']:.0f}G {g['util']}%" for g in gpus))
NEED=CFG["MIN_ACT_GIB"]
def usable_of(g): return g["free"]-RESERVE
cands=sorted([g for g in gpus if usable_of(g)>=NEED],key=usable_of,reverse=True)
if CFG["DEVICE_ID"] is not None:
d=next(g for g in gpus if g["index"]==CFG["DEVICE_ID"])
if usable_of(d)<NEED:
sys.exit(f"device {d['index']} pinned but only {usable_of(d):.1f} GiB usable, "
f"need {NEED}. Adequate now: {[g['index'] for g in cands] or 'NONE'}")
else:
if not cands: sys.exit(f"no device has {NEED} GiB usable after a {RESERVE} GiB reserve")
d=cands[0]
os.environ["CUDA_VISIBLE_DEVICES"]=str(d["index"])
print(f"device {d['index']} | {d['free']:.1f} GiB free")
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from safetensors.torch import save_file, load_file
tok=AutoTokenizer.from_pretrained(MODEL_ID)
# transformers 4.46.3 takes torch_dtype=, not dtype=
model=AutoModelForCausalLM.from_pretrained(MODEL_ID,torch_dtype=torch.bfloat16,
device_map={"":0}).eval()
NL,H=len(model.model.layers),model.config.hidden_size
print(f"{NL} layers, hidden {H}")
CUR={"ans":None}; ACC={}
def _mk(L):
def hook(_m,_a,out):
h=out[0] if isinstance(out,tuple) else out
sp=CUR["ans"]
if sp is None: return None
ACC[L]=torch.stack([h[i,a:b].float().mean(0) if b>a else torch.zeros(H,device=h.device)
for i,(a,b) in enumerate(sp)]).to(torch.float16).cpu()
return None # read-only: perturb nothing
return hook
handles=[model.model.layers[L].register_forward_hook(_mk(L)) for L in range(NL)]
# Prove the index convention on THIS model before pooling anything. The hook stores
# on CPU, so the reference must be moved to CPU too or allclose raises a device error.
with torch.no_grad():
p=tok("hello world",return_tensors="pt",add_special_tokens=False).to(model.device)
CUR["ans"]=[(0,p.input_ids.shape[1])]
o=model(**p,output_hidden_states=True)
for L in range(NL-1):
ref=o.hidden_states[L+1][0,:].float().mean(0).to(torch.float16).cpu()
assert torch.allclose(ACC[L][0],ref,atol=1e-2), f"layer convention broken at {L}"
lastref=o.hidden_states[NL][0,:].float().mean(0).to(torch.float16).cpu()
assert not torch.allclose(ACC[NL-1][0],lastref,atol=1e-2), \
"expected the last hidden_states entry to be post-final-norm"
print("layer convention verified: our L == layers[L] out == hidden_states[L+1];")
print(" last hidden_states entry IS post-norm and is correctly NOT used")
ACC.clear()
def spans(r):
p=tok(r["rendered_prompt"],add_special_tokens=False).input_ids
c=tok(r["completion"],add_special_tokens=False).input_ids
i=r["completion"].rfind(THINK)
if i<0: return None
n=len(tok(r["completion"][:i+len(THINK)],add_special_tokens=False).input_ids)
return p+c, len(p)+n, len(p)+len(c)
@torch.no_grad()
def run(batch):
seqs=[]
for r in batch:
s=spans(r)
if s is None: continue
ids,a0,a1=s
if a1-a0<5: continue
seqs.append((r,ids,a0,a1))
if not seqs: return []
W=max(len(s[1]) for s in seqs); pad=tok.pad_token_id or tok.eos_token_id
inp=torch.full((len(seqs),W),pad,dtype=torch.long)
att=torch.zeros((len(seqs),W),dtype=torch.long)
for i,(_,ids,*_) in enumerate(seqs):
inp[i,:len(ids)]=torch.tensor(ids); att[i,:len(ids)]=1
CUR["ans"]=[(a0,a1) for _,_,a0,a1 in seqs]
model(input_ids=inp.to(model.device),attention_mask=att.to(model.device))
return [(r,torch.stack([ACC[L2][i] for L2 in range(NL)])) for i,(r,*_) in enumerate(seqs)]
od=ROOT/"translated"
rows=[json.loads(l) for l in (od/"rollouts_shard0.jsonl").read_text("utf-8").splitlines() if l.strip()]
pt=od/"pooled_primary_00.safetensors"; meta_f=od/"pooled_meta.jsonl"
store = load_file(str(pt)) if pt.exists() else {}
seen = set(store)
if meta_f.exists():
keep=[l for l in meta_f.read_text("utf-8").splitlines()
if l.strip() and json.loads(l)["uid"] in seen]
meta_f.write_text("\n".join(keep)+("\n" if keep else ""),"utf-8")
todo=[r for r in rows if r["uid"] not in seen]
print(f"resume: {len(seen)} pooled, {len(todo)} to go of {len(rows)}")
# Adaptive batching by token budget; a fixed batch either wastes memory on short
# sequences or OOMs on long ones. NOTE this sorts short-to-long, so a PARTIAL
# checkpoint is length-biased and must never be analysed as if it were complete.
todo.sort(key=lambda r:r["n_out_tokens"])
skipped=[]; t0=time.time(); i=0; n_new=0
while i<len(todo):
est=todo[i]["n_out_tokens"]+400
bs=max(1,min(CFG["MAX_BATCH"],CFG["TOKEN_BUDGET"]//max(est,1)))
batch=todo[i:i+bs]; i+=bs
try: res=run(batch)
except torch.cuda.OutOfMemoryError:
torch.cuda.empty_cache(); res=[]
for r in batch:
try: res+=run([r])
except Exception as e: skipped.append((r["uid"],type(e).__name__))
got={r["uid"] for r,_ in res}
for r in batch:
if r["uid"] not in got: skipped.append((r["uid"],"no_think_or_short"))
with meta_f.open("a",encoding="utf-8") as fh:
for r,pa in res:
store[r["uid"]]=pa
fh.write(json.dumps({"uid":r["uid"],"role":r["role"],"prompt_idx":r["prompt_idx"],
"question_id":r["question_id"],"condition":r["condition"]})+"\n")
n_new+=len(res)
if n_new and n_new%CFG["CKPT_EVERY"]<bs:
save_file({k:v.contiguous() for k,v in store.items()},str(pt))
el=time.time()-t0
print(f" {n_new}/{len(todo)} {n_new/max(el,1)*3600:.0f}/h "
f"eta {(len(todo)-n_new)/max(n_new,1)*el/3600:.2f}h skipped {len(skipped)}",flush=True)
for h in handles: h.remove()
save_file({k:v.contiguous() for k,v in store.items()},str(pt))
rep={"mode":"translated","n_pooled":len(store),"n_rollouts":len(rows),
"n_skipped":len(skipped),"coverage":round(len(store)/max(len(rows),1),4),
"skip_reasons":dict(collections.Counter(x[1] for x in skipped)),
"n_layers":NL,"hidden":H,"store_dtype":"float16","device":d["index"],
"site":"post-MLP residual, forward hook on model.model.layers[L]",
"layer_convention":"our L == layers[L] output == hidden_states[L+1]",
"pooling_primary":"mean over answer tokens after the last </think>",
"output_hidden_states_used":False}
(od/"activation_report.json").write_text(json.dumps(rep,indent=2),"utf-8")
if skipped: (od/"activation_skipped.json").write_text(json.dumps(skipped,indent=2),"utf-8")
print(json.dumps(rep,indent=2))
if CFG["HF_PUSH"]:
from huggingface_hub import HfApi
api=HfApi()
for f in ["pooled_primary_00.safetensors","pooled_meta.jsonl","activation_report.json"]:
if (od/f).exists():
api.upload_file(path_or_fileobj=str(od/f),repo_id=CFG["HF_REPO"],repo_type="dataset",
path_in_repo=f"{CFG['RUN_ID']}/translated/{f}")
print(f" pushed translated/{f}")