quocbao747's picture
Code folders renamed to harness-v1 / harness
e4e58e8 verified
Raw History Blame Contribute Delete
3.55 kB
"""Correctness gate: must pass before timing/quality runs."""
import json, sys, time, gc, numpy as np, torch
from common import RES, tg
import models
PAIRS = [
("What causes the northern lights?", "The northern lights are caused by charged particles from the sun colliding with the atmosphere."),
("How do vaccines train the immune system?", "Vaccines expose the immune system to a harmless antigen so it can build memory cells."),
("Thời hạn nộp thuế thu nhập cá nhân là khi nào?", "Người nộp thuế phải quyết toán thuế thu nhập cá nhân chậm nhất là ngày cuối cùng của tháng thứ tư kể từ ngày kết thúc năm dương lịch."),
("Mức phạt khi vượt đèn đỏ đối với xe máy là bao nhiêu?", "Người điều khiển xe mô tô không chấp hành hiệu lệnh của đèn tín hiệu giao thông bị phạt tiền từ 4.000.000 đồng đến 6.000.000 đồng."),
("Phở bò Hà Nội được nấu như thế nào?", "Nước dùng phở bò được ninh từ xương bò cùng quế, hồi, gừng nướng và hành nướng trong nhiều giờ."),
("What is the capital of Australia?", "Canberra is the capital city of Australia, located in the Australian Capital Territory."),
]
def check(spec, ref=None):
t0 = time.time()
m = models.load(spec)
load_s = time.time() - t0
q = [p[0] for p in PAIRS] * 6
d = [{"title": "", "text": p[1]} for p in PAIRS] * 6
qe = m.encode_queries(q, "ZacLegalTextRetrieval")
qe = qe[0] if isinstance(qe, tuple) else qe
de = m.encode_docs(d)["dense"]
nan = int(np.isnan(qe).sum() + np.isnan(de).sum())
n = len(PAIRS)
S = qe[:n] @ de[:n].T
top1 = float((S.argmax(1) == np.arange(n)).mean())
rec = {"spec": spec, "load_s": load_s, "nan": nan, "top1_pairs": top1,
"diag_mean": float(np.diag(S).mean()), "offdiag_mean": float((S.sum() - np.trace(S)) / (n * n - n)),
"peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30}
if spec.startswith("qwen"):
enc = m.tok(["short", "a much longer piece of text here"], padding=True)
rec["left_pad_ok"] = enc["input_ids"][0][-1] == enc["input_ids"][1][-1] # both end in EOS
rec["ends_with_eos"] = m.tok.decode(enc["input_ids"][0][-1:])
if ref is not None:
cos = (qe * ref[0]).sum(1).tolist() + (de * ref[1]).sum(1).tolist()
rec["cos_vs_fp32_min"] = float(np.nanmin(cos)) if not np.all(np.isnan(cos)) else None
rec["cos_vs_fp32_mean"] = float(np.nanmean(cos)) if not np.all(np.isnan(cos)) else None
print(json.dumps(rec), flush=True)
del m; gc.collect(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
return rec, (qe, de)
if __name__ == "__main__":
out = []
r, ref = check("eg2-fp32"); out.append(r)
r, _ = check("eg2-fp16", ref); out.append(r)
r, _ = check("qwen-fp16"); out.append(r)
r, _ = check("bgem3-fp16"); out.append(r)
json.dump(out, open(RES / "gate" / "gate.json", "w"), indent=1)
ok = all(x["nan"] == 0 and x["top1_pairs"] == 1.0 for x in out if x["spec"] != "eg2-fp16")
ok = ok and out[2].get("left_pad_ok", False)
lines = [f" {x['spec']}: NaN={x['nan']} top1={x['top1_pairs']:.2f} load={x['load_s']:.0f}s VRAM={x['peak_vram_gib']:.1f}GiB"
+ (f" cos_vs_fp32 min={x['cos_vs_fp32_min']}" if 'cos_vs_fp32_min' in x else "") for x in out]
tg(("✅" if ok else "❌") + " Step 1: correctness gate\n" + "\n".join(lines))
sys.exit(0 if ok else 1)