BIaoo's picture
Publish LCA retrieval benchmark and reproducible scorer
2b73ac6 verified
Raw History Blame Contribute Delete
2.63 kB
"""Score full-query LCA Retrieval Benchmark Top10 rankings using frozen weights."""
import argparse
import json
import math
from pathlib import Path
def rows(path):
return [json.loads(s) for s in path.read_text(encoding='utf-8').splitlines() if s.strip()]
def evaluate(root, rankings):
queries=rows(root/'queries.jsonl'); docs=rows(root/'corpus.jsonl'); refs=rows(root/'qrels.jsonl')
qids={r['query_id'] for r in queries}; dids={r['document_id'] for r in docs}
if len(qids)!=100 or len(dids)!=15671: raise ValueError('Unexpected benchmark dimensions')
probs={q:{} for q in qids}
for r in refs:
q,d,p=r['query_id'],r['document_id'],r['relevance']
if q not in qids or d not in dids or d in probs[q] or not math.isfinite(p) or not 0<=p<=1:
raise ValueError('Invalid reference')
probs[q][d]=p
if any(abs(sum(v.values())-5)>1e-9 for v in probs.values()):raise ValueError('Reference mass must equal five')
if len(rankings)!=100 or {r['query_id'] for r in rankings}!=qids:raise ValueError('Exactly one ranking per query required')
per=[]
for r in rankings:
ids=r['document_ids']; q=probs[r['query_id']]
if len(ids)!=10 or len(set(ids))!=10 or not set(ids)<=dids:raise ValueError('Ten unique corpus IDs required')
v={'query_id':r['query_id']}
for k in (5,10):
v[f'coverage_at_{k}']=sum(q.get(d,0.) for d in ids[:k])/5
v[f'ndcg_at_{k}']=sum(q.get(d,0.)/math.log2(i+1) for i,d in enumerate(ids[:k],1))/sum(1/math.log2(i+1) for i in range(1,min(k,5)+1))
v[f'unjudged_at_{k}']=sum(d not in q for d in ids[:k])
per.append(v)
names=['coverage_at_5','coverage_at_10','ndcg_at_5','ndcg_at_10']
return dict(queries=100,metrics={k:sum(v[k] for v in per)/100 for k in names},
unjudged_returns={str(k):sum(v[f'unjudged_at_{k}'] for v in per) for k in (5,10)})
def main():
ap=argparse.ArgumentParser(description=__doc__)
ap.add_argument('--data-dir',type=Path,default=Path(__file__).resolve().parent)
ap.add_argument('--rankings',type=Path,required=True)
ap.add_argument('--verify-model-results',action='store_true')
a=ap.parse_args(); result=evaluate(a.data_dir,rows(a.rankings))
if a.verify_model_results:
expected=json.loads((a.data_dir/'model-results.json').read_text())['metrics']
if any(abs(result['metrics'][k]-v)>1e-12 for k,v in expected.items()):raise ValueError('Published model score mismatch')
result['published_model_metrics_verified']=True
print(json.dumps(result,indent=2))
if __name__=='__main__':main()