Datasets:
Download evaluation/retrieval.py from leequeue/MIPR: direct link, hf CLI and curl.
- Browser
- Download file 2.75 kB
-
https://huggingface.co/datasets/leequeue/MIPR/resolve/main/evaluation/retrieval.py
- Command line
-
hf download hf://datasets/leequeue/MIPR/evaluation/retrieval.py
-
curl -L -o retrieval.py https://huggingface.co/datasets/leequeue/MIPR/resolve/main/evaluation/retrieval.py
2.75 kB
| """Cosine top-k retrieval from query/product embeddings over the released corpus.""" | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import utils as data | |
| from evaluate import validate_run | |
| def topk(query_embeds, cand_embeds, query_ids, cand_ids, k): | |
| q = query_embeds.astype(np.float32) | |
| c = cand_embeds.astype(np.float32) | |
| if q.ndim != 2 or c.ndim != 2 or q.shape[1] != c.shape[1]: | |
| raise ValueError("Embeddings must be matrices with matching dimensions") | |
| if len(q) != len(query_ids) or len(c) != len(cand_ids): | |
| raise ValueError("Embedding rows and IDs do not match") | |
| if len(set(query_ids)) != len(query_ids) or len(set(cand_ids)) != len(cand_ids): | |
| raise ValueError("Embedding IDs must be unique") | |
| if k <= 0 or not len(c): | |
| raise ValueError("k and candidate count must be positive") | |
| if not all(np.isfinite(x).all() and (np.linalg.norm(x, axis=1) > 0).all() for x in (q, c)): | |
| raise ValueError("Embeddings must be finite and nonzero") | |
| k = min(k, len(c)) | |
| q /= np.linalg.norm(q, axis=1, keepdims=True) + 1e-12 | |
| c /= np.linalg.norm(c, axis=1, keepdims=True) + 1e-12 | |
| results = [] | |
| batch = 256 | |
| for s in range(0, len(q), batch): | |
| sims = q[s : s + batch] @ c.T | |
| for i in range(sims.shape[0]): | |
| row = np.argsort(-sims[i], kind="stable")[:k] | |
| results.append( | |
| { | |
| "qid": query_ids[s + i], | |
| "ranked": [ | |
| {"did": cand_ids[j], "score": round(float(sims[i, j]), 6)} | |
| for j in row | |
| ], | |
| } | |
| ) | |
| return results | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--embed-dir", required=True) | |
| p.add_argument("--top-k", type=int, default=50) | |
| p.add_argument("--output", required=True) | |
| p.add_argument("--data", default=None) | |
| args = p.parse_args() | |
| folder = Path(args.embed_dir) | |
| qids = list(map(str, json.loads((folder / "query_ids.json").read_text()))) | |
| cids = list(map(str, json.loads((folder / "candidate_ids.json").read_text()))) | |
| corpus = data.load_corpus(args.data) | |
| if set(cids) != set(corpus): | |
| raise ValueError("Candidate embeddings must cover the released corpus exactly") | |
| run = topk(np.load(folder / "query_embeds.npy"), np.load(folder / "candidate_embeds.npy"), | |
| qids, cids, args.top_k) | |
| validate_run(run, {str(q["idx"]) for q in data.load_queries(args.data)}, corpus) | |
| out = Path(args.output) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| out.write_text(json.dumps(run)) | |
| print(f"Saved {len(run)} query rankings to {out}") | |
| if __name__ == "__main__": | |
| main() | |