File size: 5,210 Bytes
8510f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""Pure-Python Okapi BM25 lexical baseline for CCRB anti-shortcut gating and scoring."""

from __future__ import annotations

import argparse
import heapq
import json
import math
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path

_REPO_ROOT = Path(__file__).resolve().parent.parent.parent
if str(_REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(_REPO_ROOT))

from scripts.pipeline_utils import TRACKS, load_jsonl

TOKEN_RE = re.compile(r"[a-z0-9]+(?:_[a-z0-9]+)*", re.IGNORECASE)

STOPWORDS: frozenset[str] = frozenset(
    {
        "a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "have",
        "in", "is", "it", "its", "of", "on", "or", "that", "the", "their", "this", "to",
        "was", "were", "which", "with", "via", "into", "when", "can", "may", "not",
    }
)


def tokenize(text: str, *, drop_stopwords: bool = True) -> list[str]:
    """Tokenize prose and code identifiers into lowercase alphanumeric terms."""
    tokens: list[str] = []
    for match in TOKEN_RE.finditer(text.lower()):
        tok = match.group(0)
        if drop_stopwords and tok in STOPWORDS:
            continue
        tokens.append(tok)
        if "_" in tok:
            tokens.extend(
                part
                for part in tok.split("_")
                if len(part) >= 2 and not (drop_stopwords and part in STOPWORDS)
            )
    return tokens


class BM25Index:
    """Inverted-index Okapi BM25 retriever with zero external dependencies."""

    def __init__(self, doc_ids: list[str], corpus_texts: list[str], k1: float = 1.5, b: float = 0.75):
        if len(doc_ids) != len(corpus_texts):
            raise ValueError("doc_ids and corpus_texts must have equal length")
        self.doc_ids = doc_ids
        self.k1 = k1
        self.b = b
        self.num_docs = len(doc_ids)
        self.doc_lengths: list[int] = []
        self.postings: dict[str, list[tuple[int, int]]] = defaultdict(list)

        total_len = 0
        for idx, text in enumerate(corpus_texts):
            tokens = tokenize(text)
            self.doc_lengths.append(len(tokens))
            total_len += len(tokens)
            tf = Counter(tokens)
            for term, freq in tf.items():
                self.postings[term].append((idx, freq))

        self.avg_doc_len = (total_len / self.num_docs) if self.num_docs else 1.0
        self.idf: dict[str, float] = {
            term: math.log(1.0 + (self.num_docs - len(plist) + 0.5) / (len(plist) + 0.5))
            for term, plist in self.postings.items()
        }

    def search(self, query: str, top_k: int = 100) -> list[tuple[str, float]]:
        """Return top-k `(document_id, score)` pairs sorted by descending BM25 score."""
        if self.num_docs == 0:
            return []
        scores: dict[int, float] = defaultdict(float)
        for term in set(tokenize(query)):
            plist = self.postings.get(term)
            if not plist:
                continue
            idf = self.idf[term]
            for doc_idx, tf in plist:
                dl = self.doc_lengths[doc_idx]
                denom = tf + self.k1 * (1.0 - self.b + self.b * (dl / self.avg_doc_len))
                scores[doc_idx] += idf * ((tf * (self.k1 + 1.0)) / denom)

        top = heapq.nlargest(top_k, scores.items(), key=lambda item: item[1])
        return [(self.doc_ids[idx], round(score, 6)) for idx, score in top]


def run_bm25_track(
    data_dir: Path,
    track: str,
    out_path: Path,
    *,
    top_k: int = 100,
) -> int:
    """Run BM25 retrieval for one track and write `<track>.jsonl` run predictions."""
    docs = load_jsonl(data_dir / "documents" / f"{track}.jsonl")
    queries = load_jsonl(data_dir / "queries" / f"{track}.jsonl")
    if not docs or not queries:
        return 0

    doc_ids = [str(obj["document_id"]) for _ln, obj in docs]
    doc_texts = [f"{obj.get('title', '')}\n{obj.get('text', '')}" for _ln, obj in docs]
    index = BM25Index(doc_ids, doc_texts)

    out_path.parent.mkdir(parents=True, exist_ok=True)
    with out_path.open("w", encoding="utf-8") as handle:
        for _ln, qobj in queries:
            qid = str(qobj["query_id"])
            hits = index.search(str(qobj["query"]), top_k=top_k)
            record = {
                "query_id": qid,
                "results": [{"document_id": did, "score": score} for did, score in hits],
            }
            handle.write(json.dumps(record) + "\n")
    return len(queries)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Run BM25 baseline on CCRB tracks.")
    parser.add_argument("--data-dir", type=Path, default=Path("data"))
    parser.add_argument("--runs-dir", type=Path, default=Path("results/bm25_runs"))
    parser.add_argument("--tracks", nargs="+", choices=TRACKS, default=list(TRACKS))
    parser.add_argument("--top-k", type=int, default=100)
    args = parser.parse_args(argv)

    for track in args.tracks:
        n_q = run_bm25_track(args.data_dir, track, args.runs_dir / f"{track}.jsonl", top_k=args.top_k)
        print(f"[bm25] {track}: scored {n_q} queries")
    return 0


if __name__ == "__main__":
    sys.exit(main())