Tarakeshwaran commited on
Commit
045aa44
·
verified ·
1 Parent(s): 04a78c3
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ practice_passages.jsonl filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ pretty_name: "PS09 Kernel Optimisation for Encoders (student data)"
4
+ tags: [hackathon, encoder]
5
+ ---
6
+ # PS09: Kernel Optimisation for Encoders
7
+
8
+ **Theme:** Pipeline Building | 24-hour hackathon, teams of two, AI coding tools allowed.
9
+
10
+ ## What you build
11
+ Make the BAAI/bge-base-en-v1.5 encoder much faster on one GPU while keeping every embedding within cosine 0.999 of the reference.
12
+
13
+ ## What is in this repository
14
+ `reference.py` (FP32, padded to 512), `bench.py`, 100,000 practice Wikipedia passages, a 1,500-query trace with bursts, and reference embeddings for part of the data.
15
+
16
+ ## Output format
17
+ A Python file with `encode(texts) -> [N,768]` and an optional `setup()`; `bench.py` times and checks it.
18
+
19
+ ## Source and licence
20
+ Wikipedia (CC BY-SA 3.0), Natural Questions queries (CC BY-SA 3.0), model licence MIT. Use this data only for the event and for non-commercial work, with attribution. Hidden test data and answer keys are not included.
21
+ Read the student problem statement document for the full task, scoring and rules.
bench.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PS-09 benchmark harness: runs a team's encode(), measures throughput, checks cosine tolerance, replays a query trace.
2
+
3
+ Team file contract: define `encode(texts: list[str]) -> numpy.ndarray` of shape [len(texts), 768], L2-normalised, in
4
+ input order. Optional `setup()` is called once before timing (load weights, compile, warm up; not timed).
5
+ The same `encode` is called with the whole passage list (batch run) and with one query at a time (live trace).
6
+
7
+ Usage: python bench.py --team team.py --passages practice_passages.jsonl --ref ref.npy
8
+ [--trace practice_trace.jsonl --ref-queries ref_queries.npy] [--ref-throughput FILE] --out result.json
9
+ """
10
+ import argparse, hashlib, importlib.util, json, sys, time
11
+ from pathlib import Path
12
+ import numpy as np
13
+
14
+ TOLERANCE = 0.999
15
+
16
+
17
+ def sha(p):
18
+ return hashlib.sha256(Path(p).read_bytes()).hexdigest()
19
+
20
+
21
+ def cos_check(got, ref, tol):
22
+ got = np.asarray(got, dtype=np.float32); ref = np.asarray(ref, dtype=np.float32)
23
+ if got.shape != ref.shape or not np.isfinite(got).all():
24
+ return {"shape_ok": False, "n_violations": int(len(ref)), "min_cosine": None}
25
+ c = (got * ref).sum(1) / (np.linalg.norm(got, axis=1) * np.linalg.norm(ref, axis=1))
26
+ return {"shape_ok": True, "n_violations": int((c < tol).sum()), "min_cosine": float(c.min())}
27
+
28
+
29
+ def live(encode, trace, ref_q, tol):
30
+ """Replay arrivals in real time; one query at a time, FIFO, so a burst makes later queries wait."""
31
+ lat, outs, start = [], [], time.perf_counter()
32
+ for r in trace:
33
+ wait = r["t"] - (time.perf_counter() - start)
34
+ if wait > 0:
35
+ time.sleep(wait)
36
+ outs.append(np.asarray(encode([r["text"]]))[0])
37
+ lat.append((time.perf_counter() - start - r["t"]) * 1000)
38
+ res = {"n": len(lat), "p50_ms": float(np.percentile(lat, 50)), "p99_ms": float(np.percentile(lat, 99))}
39
+ if ref_q is not None:
40
+ res.update(cos_check(np.stack(outs), ref_q, tol))
41
+ return res
42
+
43
+
44
+ if __name__ == "__main__":
45
+ ap = argparse.ArgumentParser()
46
+ ap.add_argument("--team", required=True); ap.add_argument("--passages", required=True)
47
+ ap.add_argument("--ref", required=True, help="reference embeddings .npy for the passages (or first K of them)")
48
+ ap.add_argument("--trace"); ap.add_argument("--ref-queries")
49
+ ap.add_argument("--ref-throughput", help="JSON with passages_per_second of reference.py on this machine")
50
+ ap.add_argument("--limit", type=int, help="use only the first N passages (smoke test)")
51
+ ap.add_argument("--tolerance", type=float, default=TOLERANCE); ap.add_argument("--out", required=True)
52
+ a = ap.parse_args()
53
+ sys.path.insert(0, str(Path(a.team).resolve().parent))
54
+ spec = importlib.util.spec_from_file_location("team_encode", a.team)
55
+ mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
56
+ t = time.time()
57
+ if hasattr(mod, "setup"):
58
+ mod.setup()
59
+ setup_s = time.time() - t
60
+ texts = [json.loads(l)["text"] for l in open(a.passages)][: a.limit]
61
+ ref = np.load(a.ref)[: a.limit]
62
+ t = time.perf_counter(); emb = mod.encode(texts); secs = time.perf_counter() - t
63
+ res = {"n_passages": len(texts), "seconds": secs, "passages_per_second": len(texts) / secs, "setup_seconds": setup_s,
64
+ "tolerance": a.tolerance, "passages_sha256": sha(a.passages)}
65
+ # Reference may cover only the first K passages (a subset); throughput still uses all of them.
66
+ res.update(cos_check(np.asarray(emb)[: len(ref)], ref, a.tolerance) if len(emb) >= len(ref)
67
+ else {"shape_ok": False, "n_violations": len(ref), "min_cosine": None})
68
+ res["n_checked"] = int(len(ref))
69
+ if a.ref_throughput:
70
+ res["reference_passages_per_second"] = json.load(open(a.ref_throughput))["passages_per_second"]
71
+ res["speedup"] = res["passages_per_second"] / res["reference_passages_per_second"]
72
+ if a.trace:
73
+ trace = [json.loads(l) for l in open(a.trace)]
74
+ res["live"] = live(mod.encode, trace, np.load(a.ref_queries) if a.ref_queries else None, a.tolerance)
75
+ json.dump(res, open(a.out, "w"), indent=1)
76
+ print(json.dumps(res, indent=1))
practice_passages.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f29fa2730d8f90c801b876a56fc36735fcc2397a763b3962f20eed17f618f9d6
3
+ size 49644343
practice_ref_first2000.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2efc56cb58eaf0c871688d3263fbafbdf6b5a5348b6f141f20fa3b13d35cd37
3
+ size 6144128
practice_ref_queries.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8856a0e6fa757f4de1d2fa57973cacfa6380cbdbfb9a60f2f6aec0b57eac6b13
3
+ size 4608128
practice_trace.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
reference.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PS-09 reference: BAAI/bge-base-en-v1.5, FP32, every input padded to 512 tokens, batch size 32, CLS pooling, L2 norm.
2
+
3
+ Usage: python reference.py --model PATH_OR_HF_ID --passages practice_passages.jsonl --out ref.npy [--limit N]
4
+ The output is a float32 array [N, 768] in file order. Runs on CUDA when available, else CPU.
5
+ """
6
+ import argparse, json, time
7
+ import numpy as np, torch
8
+ from transformers import AutoModel, AutoTokenizer
9
+
10
+ MAX_LEN, BATCH = 512, 32
11
+
12
+
13
+ def load(model):
14
+ tok = AutoTokenizer.from_pretrained(model)
15
+ m = AutoModel.from_pretrained(model, torch_dtype=torch.float32).eval()
16
+ return tok, m.to("cuda" if torch.cuda.is_available() else "cpu")
17
+
18
+
19
+ @torch.inference_mode()
20
+ def encode(tok, m, texts, batch=BATCH):
21
+ out = []
22
+ for i in range(0, len(texts), batch):
23
+ x = tok(texts[i:i + batch], padding="max_length", truncation=True, max_length=MAX_LEN, return_tensors="pt").to(m.device)
24
+ cls = m(**x).last_hidden_state[:, 0]
25
+ out.append(torch.nn.functional.normalize(cls, dim=-1).float().cpu().numpy())
26
+ return np.concatenate(out)
27
+
28
+
29
+ if __name__ == "__main__":
30
+ ap = argparse.ArgumentParser()
31
+ ap.add_argument("--model", default="BAAI/bge-base-en-v1.5"); ap.add_argument("--passages", required=True)
32
+ ap.add_argument("--out", required=True); ap.add_argument("--limit", type=int)
33
+ a = ap.parse_args()
34
+ texts = [json.loads(l)["text"] for l in open(a.passages)][: a.limit]
35
+ tok, m = load(a.model)
36
+ t = time.time(); emb = encode(tok, m, texts); dt = time.time() - t
37
+ np.save(a.out, emb)
38
+ print(json.dumps({"n": len(texts), "seconds": dt, "passages_per_second": len(texts) / dt}))