Download code/scripts/05_ce_score.py from Jyo-K/PopTurk: direct link, hf CLI and curl.
- Browser
- Download file 4.29 kB
-
https://huggingface.co/datasets/Jyo-K/PopTurk/resolve/main/code/scripts/05_ce_score.py
- Command line
-
hf download hf://datasets/Jyo-K/PopTurk/code/scripts/05_ce_score.py
-
curl -L -o 05_ce_score.py https://huggingface.co/datasets/Jyo-K/PopTurk/resolve/main/code/scripts/05_ce_score.py
4.29 kB
| """Step D. Score one shard with one or both cross-encoders. Identical on the box and on Colab. | |
| CUDA_VISIBLE_DEVICES=1 python scripts/05_ce_score.py \ | |
| --shard work/shards/test_shard1of4.parquet \ | |
| --model work/ce_model_A --out work/scored/shard1_bge.parquet | |
| The Colab notebook calls exactly this code path through the berx package, so a bug found on | |
| one lane is fixed for all four. | |
| --batch defaults to 0, meaning "probe it". A shared card has an unpredictable amount of free | |
| memory, and a fixed batch size is either too small (wasting the card) or too large (an OOM an | |
| hour into the run). The probe doubles the batch until it OOMs, then backs off one step. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import sys | |
| import time | |
| import numpy as np | |
| import pandas as pd | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from berx import ce_score as CE # noqa: E402 | |
| def probe_batch(tok, model, texts_a, texts_b, device, max_len, cap=1024): | |
| """Find a batch size that fits, using the LONGEST pairs so the answer is safe for all.""" | |
| import torch | |
| lens = np.fromiter((len(a) + len(b) for a, b in zip(texts_a, texts_b)), np.int32, | |
| len(texts_a)) | |
| worst = np.argsort(lens)[-cap:] | |
| b, best = 16, 16 | |
| while b <= cap: | |
| idx = worst[-b:] | |
| try: | |
| with torch.inference_mode(): | |
| enc = tok([texts_a[i] for i in idx], [texts_b[i] for i in idx], padding=True, | |
| truncation=True, max_length=max_len, return_tensors="pt").to(device) | |
| with torch.autocast("cuda", dtype=torch.float16, | |
| enabled=device.startswith("cuda")): | |
| model(**enc) | |
| best = b | |
| b *= 2 | |
| except RuntimeError as e: | |
| if "out of memory" not in str(e).lower(): | |
| raise | |
| torch.cuda.empty_cache() | |
| break | |
| torch.cuda.empty_cache() | |
| return max(16, best // 2) # one step back: leave the card headroom | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--shard", required=True) | |
| ap.add_argument("--model", required=True, help="local dir or HF id") | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--score-col", default="ce") | |
| ap.add_argument("--device", default="cuda") | |
| ap.add_argument("--batch", type=int, default=0, help="0 = probe") | |
| ap.add_argument("--max-len", type=int, default=160) | |
| ap.add_argument("--ckpt", default="", help="checkpoint prefix; on Colab put it on Drive") | |
| ap.add_argument("--ckpt-every", type=int, default=200_000) | |
| ap.add_argument("--compile", action="store_true") | |
| ap.add_argument("--output", default="logit", choices=["logit", "prob"], | |
| help="MUST be 'logit' to match model-4's stored ce column") | |
| a = ap.parse_args() | |
| df = pd.read_parquet(a.shard) | |
| ta, tb = df["text_a"].tolist(), df["text_b"].tolist() | |
| print(f"shard {a.shard}: {len(df):,} pairs") | |
| tok, model = CE.load_model(a.model, a.device, compile_model=a.compile) | |
| batch = a.batch or probe_batch(tok, model, ta, tb, a.device, a.max_len) | |
| print(f"batch={batch} max_len={a.max_len} model={a.model}") | |
| t0 = time.time() | |
| s = CE.score_pairs(ta, tb, tok, model, a.device, batch=batch, max_len=a.max_len, | |
| ckpt=a.ckpt or None, ckpt_every=a.ckpt_every, | |
| output=a.output) | |
| el = time.time() - t0 | |
| out = df[["q", "c"]].copy() | |
| out[a.score_col] = s | |
| os.makedirs(os.path.dirname(os.path.abspath(a.out)) or ".", exist_ok=True) | |
| out.to_parquet(a.out, index=False, compression="zstd") | |
| print(f"wrote {a.out} {el/60:.1f} min {len(df)/max(el,1e-9):,.0f} pairs/s") | |
| print(f" score mean {s.mean():.4f} min {s.min():.3f} max {s.max():.3f} " | |
| f">0 {(s > 0).mean():.2%}") | |
| if a.output == "logit" and s.min() >= 0.0 and s.max() <= 1.0: | |
| print(" WARNING: every score is in [0,1]. That is a probability, not a logit - " | |
| "check the model head before merging into model-4's ce column.") | |
| if __name__ == "__main__": | |
| main() | |