Tarakeshwaran's picture
Add ps09
045aa44 verified
Raw History Blame Contribute Delete
1.65 kB
"""PS-09 reference: BAAI/bge-base-en-v1.5, FP32, every input padded to 512 tokens, batch size 32, CLS pooling, L2 norm.
Usage: python reference.py --model PATH_OR_HF_ID --passages practice_passages.jsonl --out ref.npy [--limit N]
The output is a float32 array [N, 768] in file order. Runs on CUDA when available, else CPU.
"""
import argparse, json, time
import numpy as np, torch
from transformers import AutoModel, AutoTokenizer
MAX_LEN, BATCH = 512, 32
def load(model):
tok = AutoTokenizer.from_pretrained(model)
m = AutoModel.from_pretrained(model, torch_dtype=torch.float32).eval()
return tok, m.to("cuda" if torch.cuda.is_available() else "cpu")
@torch.inference_mode()
def encode(tok, m, texts, batch=BATCH):
out = []
for i in range(0, len(texts), batch):
x = tok(texts[i:i + batch], padding="max_length", truncation=True, max_length=MAX_LEN, return_tensors="pt").to(m.device)
cls = m(**x).last_hidden_state[:, 0]
out.append(torch.nn.functional.normalize(cls, dim=-1).float().cpu().numpy())
return np.concatenate(out)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="BAAI/bge-base-en-v1.5"); ap.add_argument("--passages", required=True)
ap.add_argument("--out", required=True); ap.add_argument("--limit", type=int)
a = ap.parse_args()
texts = [json.loads(l)["text"] for l in open(a.passages)][: a.limit]
tok, m = load(a.model)
t = time.time(); emb = encode(tok, m, texts); dt = time.time() - t
np.save(a.out, emb)
print(json.dumps({"n": len(texts), "seconds": dt, "passages_per_second": len(texts) / dt}))