quocbao747's picture
Code folders renamed to harness-v1 / harness
e4e58e8 verified
Raw History Blame Contribute Delete
4.15 kB
"""Qwen3-8B sharded encoding (option B).
GPU: python shard8b.py worker <wid> -> claims jobs from $R8/jobs.json under $R8/queue.lock
gpu-b: python shard8b.py runner <wid> -> takes jobs from $R8/inbox/<wid>/job.json (written by the local driver)
Job: {"id","type":"docs"|"queries","task","L","start","end","sec","prio"} -> $R8/emb/L<L>/<task>/docs_<start>.npy | queries.npy"""
import os, sys, json, time, fcntl, traceback
from pathlib import Path
import numpy as np, torch
import zoo, data
MODE, WID = sys.argv[1], sys.argv[2]
R8 = Path(os.path.expanduser(os.environ.get("R8", "~/embed/r8b")))
for d in ("claimed", "done", "logs", "emb"):
(R8 / d).mkdir(parents=True, exist_ok=True)
LOG = open(R8 / "logs" / f"w{WID}.log", "a")
def log(m):
line = f"{time.strftime('%H:%M:%S')} [w{WID}] {m}"; print(line, flush=True); LOG.write(line + "\n"); LOG.flush()
def out_path(j):
d = R8 / "emb" / f"L{j['L']}" / j["task"].replace(":", "_"); d.mkdir(parents=True, exist_ok=True)
return d / ("queries.npy" if j["type"] == "queries" else f"docs_{j['start']:07d}.npy")
def claim():
with open(R8 / "queue.lock", "w") as lk:
fcntl.flock(lk, fcntl.LOCK_EX)
jobs = json.load(open(R8 / "jobs.json"))
taken = {f.stem for f in (R8 / "claimed").glob("*.claim")}
rem = [j for j in jobs if j["id"] not in taken]
if not rem:
return None
p = min(j.get("prio", 0) for j in rem)
j = max([x for x in rem if x.get("prio", 0) == p], key=lambda x: x["sec"])
(R8 / "claimed" / f"{j['id']}.claim").write_text(WID)
return j
ENC, CACHE = None, {}
def run(j):
global ENC
if ENC is None:
t = time.time(); ENC = zoo.Enc("qwen3-8b"); log(f"loaded qwen3-8b in {time.time()-t:.0f}s bs={ENC.bs}")
ENC.max_len = j["L"]; ENC.m.max_seq_length = j["L"]
bs0 = int(os.environ.get("EMBED_BS", zoo.MODELS["qwen3-8b"][3]))
ENC.bs = max(2, bs0 * 512 // j["L"])
if j["task"] not in CACHE:
CACHE.clear(); CACHE[j["task"]] = data.load_task(j["task"])
corpus, queries, _ = CACHE[j["task"]]
t = time.time()
if j["type"] == "queries":
E = ENC.encode_queries([q["text"] for q in queries], j["task"])
else:
E = ENC.encode_docs(corpus[j["start"]:j["end"]])
torch.cuda.synchronize(); dt = time.time() - t
nan = int(np.isnan(E).any(1).sum())
tmp = out_path(j).with_suffix(".tmp.npy"); np.save(tmp, E.astype(np.float16)); tmp.rename(out_path(j))
(R8 / "done" / f"{j['id']}.done").write_text(json.dumps({"s": dt, "n": len(E), "nan": nan, "gpu": WID,
"vram": torch.cuda.max_memory_allocated() / 2**30}))
log(f"DONE {j['id']} n={len(E)} {dt:.0f}s ({len(E)/dt:.1f}/s) nan={nan}")
def main():
if MODE == "worker":
for f in (R8 / "claimed").glob("*.claim"): # release own stale claims
if f.read_text().strip() == WID and not (R8 / "done" / f"{f.stem}.done").exists():
f.unlink()
while True:
j = claim()
if j is None:
log("QUEUE_EMPTY"); return
try:
run(j)
except Exception as e:
(R8 / "done" / f"{j['id']}.failed").write_text(traceback.format_exc())
(R8 / "claimed" / f"{j['id']}.claim").unlink(missing_ok=True) # let another GPU retry it
log(f"FAILED {j['id']}: {type(e).__name__}: {str(e)[:200]}"); torch.cuda.empty_cache(); time.sleep(10)
else:
inbox = R8 / "inbox" / WID; inbox.mkdir(parents=True, exist_ok=True)
log("runner ready")
while True:
jf = inbox / "job.json"
if not jf.exists():
time.sleep(1); continue
j = json.loads(jf.read_text())
try:
run(j)
except Exception as e:
(R8 / "done" / f"{j['id']}.failed").write_text(traceback.format_exc())
log(f"FAILED {j['id']}: {type(e).__name__}: {str(e)[:200]}"); torch.cuda.empty_cache()
jf.unlink()
if __name__ == "__main__":
main()