Angshul commited on
Commit
f7b6133
·
verified ·
1 Parent(s): 00f7555

Upload 18 files

Browse files
geomretrieval/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen sparse geometric retrieval package."""
2
+ from .config import FrozenConfig
3
+ from .index import GeometricIndex
4
+ from .beir import load_beir_zip, load_beir_directory
5
+ from .metrics import evaluate_run
6
+
7
+ __all__ = ["FrozenConfig", "GeometricIndex", "load_beir_zip", "load_beir_directory", "evaluate_run"]
8
+ __version__ = "0.1.0"
9
+
10
+ from .rag_top10 import RAGTop10Config, RAGTop10Ranker
geomretrieval/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (583 Bytes). View file
 
geomretrieval/__pycache__/beir.cpython-313.pyc ADDED
Binary file (5.46 kB). View file
 
geomretrieval/__pycache__/config.cpython-313.pyc ADDED
Binary file (2.51 kB). View file
 
geomretrieval/__pycache__/geometry.cpython-313.pyc ADDED
Binary file (6.58 kB). View file
 
geomretrieval/__pycache__/index.cpython-313.pyc ADDED
Binary file (33.4 kB). View file
 
geomretrieval/__pycache__/metrics.cpython-313.pyc ADDED
Binary file (3.99 kB). View file
 
geomretrieval/__pycache__/rag_top10.cpython-313.pyc ADDED
Binary file (24.6 kB). View file
 
geomretrieval/__pycache__/utils.cpython-313.pyc ADDED
Binary file (5.64 kB). View file
 
geomretrieval/baselines.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional dense ANN baseline helpers.
2
+
3
+ These deliberately accept PRECOMPUTED embeddings. They never run a transformer.
4
+ Install with: pip install 'geomretrieval[ann]'
5
+ """
6
+ from __future__ import annotations
7
+ import time
8
+ import numpy as np
9
+
10
+
11
+ def faiss_flat_ip(corpus: np.ndarray, queries: np.ndarray, k: int = 100):
12
+ import faiss
13
+ xb = np.ascontiguousarray(corpus.astype(np.float32))
14
+ xq = np.ascontiguousarray(queries.astype(np.float32))
15
+ index = faiss.IndexFlatIP(xb.shape[1])
16
+ index.add(xb)
17
+ t0 = time.perf_counter()
18
+ D, I = index.search(xq, k)
19
+ ms = (time.perf_counter() - t0) * 1000.0 / len(xq)
20
+ return I, D, ms
21
+
22
+
23
+ def faiss_hnsw_ip(corpus: np.ndarray, queries: np.ndarray, k: int = 100, M: int = 32, ef_search: int = 128):
24
+ import faiss
25
+ xb = np.ascontiguousarray(corpus.astype(np.float32))
26
+ xq = np.ascontiguousarray(queries.astype(np.float32))
27
+ index = faiss.IndexHNSWFlat(xb.shape[1], M, faiss.METRIC_INNER_PRODUCT)
28
+ index.hnsw.efSearch = ef_search
29
+ index.add(xb)
30
+ t0 = time.perf_counter()
31
+ D, I = index.search(xq, k)
32
+ ms = (time.perf_counter() - t0) * 1000.0 / len(xq)
33
+ return I, D, ms
34
+
35
+
36
+ def faiss_ivf_flat_ip(corpus: np.ndarray, queries: np.ndarray, k: int = 100, nlist: int = 4096, nprobe: int = 64):
37
+ import faiss
38
+ xb = np.ascontiguousarray(corpus.astype(np.float32))
39
+ xq = np.ascontiguousarray(queries.astype(np.float32))
40
+ quant = faiss.IndexFlatIP(xb.shape[1])
41
+ index = faiss.IndexIVFFlat(quant, xb.shape[1], nlist, faiss.METRIC_INNER_PRODUCT)
42
+ index.train(xb)
43
+ index.add(xb)
44
+ index.nprobe = nprobe
45
+ t0 = time.perf_counter()
46
+ D, I = index.search(xq, k)
47
+ ms = (time.perf_counter() - t0) * 1000.0 / len(xq)
48
+ return I, D, ms
geomretrieval/beir.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import csv
3
+ import json
4
+ import os
5
+ import tempfile
6
+ import zipfile
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+
11
+ @dataclass
12
+ class BEIRDataset:
13
+ corpus_ids: list[str]
14
+ corpus_texts: list[str]
15
+ queries: dict[str, str]
16
+ qrels: dict[str, dict[str, float]]
17
+ name: str = "dataset"
18
+
19
+
20
+ def _find(root: Path, basename: str) -> Path:
21
+ hits = list(root.rglob(basename))
22
+ if not hits:
23
+ raise FileNotFoundError(f"Could not find {basename!r} under {root}")
24
+ if len(hits) > 1:
25
+ # Prefer the shallowest path, which is normally the dataset root.
26
+ hits.sort(key=lambda p: len(p.parts))
27
+ return hits[0]
28
+
29
+
30
+ def load_beir_directory(path: str | os.PathLike, split: str = "test") -> BEIRDataset:
31
+ root = Path(path)
32
+ corpus_path = _find(root, "corpus.jsonl")
33
+ queries_path = _find(root, "queries.jsonl")
34
+ qrels_hits = list(root.rglob(f"qrels/{split}.tsv"))
35
+ if not qrels_hits:
36
+ # Some archives flatten qrels paths.
37
+ qrels_hits = [p for p in root.rglob(f"{split}.tsv") if p.parent.name == "qrels"]
38
+ if not qrels_hits:
39
+ raise FileNotFoundError(f"Could not find qrels/{split}.tsv under {root}")
40
+ qrels_path = qrels_hits[0]
41
+
42
+ corpus_ids, corpus_texts = [], []
43
+ with corpus_path.open("r", encoding="utf-8") as f:
44
+ for line in f:
45
+ if not line.strip():
46
+ continue
47
+ obj = json.loads(line)
48
+ did = str(obj.get("_id", obj.get("id")))
49
+ title = obj.get("title", "") or ""
50
+ text = obj.get("text", "") or ""
51
+ merged = (title + " " + text).strip()
52
+ corpus_ids.append(did)
53
+ corpus_texts.append(merged)
54
+
55
+ queries = {}
56
+ with queries_path.open("r", encoding="utf-8") as f:
57
+ for line in f:
58
+ if not line.strip():
59
+ continue
60
+ obj = json.loads(line)
61
+ qid = str(obj.get("_id", obj.get("id")))
62
+ queries[qid] = obj.get("text", "") or ""
63
+
64
+ qrels: dict[str, dict[str, float]] = {}
65
+ with qrels_path.open("r", encoding="utf-8") as f:
66
+ reader = csv.DictReader(f, delimiter="\t")
67
+ for row in reader:
68
+ # BEIR normally uses query-id, corpus-id, score.
69
+ qid = str(row.get("query-id", row.get("query_id", row.get("qid"))))
70
+ did = str(row.get("corpus-id", row.get("corpus_id", row.get("docid"))))
71
+ score = float(row.get("score", row.get("relevance", row.get("rel", 0))))
72
+ qrels.setdefault(qid, {})[did] = score
73
+
74
+ name = corpus_path.parent.name
75
+ return BEIRDataset(corpus_ids, corpus_texts, queries, qrels, name=name)
76
+
77
+
78
+ def load_beir_zip(path: str | os.PathLike, split: str = "test") -> BEIRDataset:
79
+ """Load a standard BEIR zip without requiring internet access."""
80
+ with tempfile.TemporaryDirectory(prefix="geomretrieval_beir_") as td:
81
+ with zipfile.ZipFile(path, "r") as zf:
82
+ zf.extractall(td)
83
+ return load_beir_directory(td, split=split)
geomretrieval/cli.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from .beir import load_beir_zip, load_beir_directory
7
+ from .config import FrozenConfig
8
+ from .index import GeometricIndex
9
+ from .metrics import evaluate_run
10
+
11
+
12
+ def _dataset(path: str, split: str):
13
+ return load_beir_zip(path, split) if str(path).lower().endswith(".zip") else load_beir_directory(path, split)
14
+
15
+
16
+ def cmd_build(args):
17
+ ds = _dataset(args.dataset, args.split)
18
+ cfg = FrozenConfig(max_features=args.max_features, min_df=args.min_df)
19
+ idx = GeometricIndex.build(ds.corpus_texts, ds.corpus_ids, cfg, verbose=True)
20
+ idx.save(args.output)
21
+ print(f"saved index -> {args.output}")
22
+
23
+
24
+ def cmd_eval(args):
25
+ ds = _dataset(args.dataset, args.split)
26
+ idx = GeometricIndex.load(args.index)
27
+ # Evaluate only qrels-bearing queries.
28
+ queries = {qid: ds.queries[qid] for qid in ds.qrels if qid in ds.queries}
29
+ run, timing = idx.batch_search(queries, k=args.k, timing=True)
30
+ metrics = evaluate_run(run, ds.qrels, ks=(10, 100), ndcg_k=10, mrr_k=10)
31
+ out = {"dataset": ds.name, **metrics, **timing}
32
+ print(json.dumps(out, indent=2, sort_keys=True))
33
+ if args.run_json:
34
+ Path(args.run_json).write_text(json.dumps(run, indent=1))
35
+
36
+
37
+ def cmd_search(args):
38
+ idx = GeometricIndex.load(args.index)
39
+ ids, scores = idx.search(args.query, k=args.k, return_scores=True)
40
+ for r, (d, s) in enumerate(zip(ids, scores), start=1):
41
+ print(f"{r:3d}\t{d}\t{s:.6f}")
42
+
43
+
44
+ def main():
45
+ p = argparse.ArgumentParser(prog="geomretrieval")
46
+ sp = p.add_subparsers(dest="cmd", required=True)
47
+
48
+ b = sp.add_parser("build", help="Build frozen sparse index from a BEIR dataset/archive")
49
+ b.add_argument("dataset")
50
+ b.add_argument("output")
51
+ b.add_argument("--split", default="test")
52
+ b.add_argument("--max-features", type=int, default=50_000)
53
+ b.add_argument("--min-df", type=int, default=1)
54
+ b.set_defaults(func=cmd_build)
55
+
56
+ e = sp.add_parser("eval", help="Evaluate an existing index on BEIR qrels")
57
+ e.add_argument("dataset")
58
+ e.add_argument("index")
59
+ e.add_argument("--split", default="test")
60
+ e.add_argument("--k", type=int, default=100)
61
+ e.add_argument("--run-json", default=None)
62
+ e.set_defaults(func=cmd_eval)
63
+
64
+ s = sp.add_parser("search", help="Search an existing index")
65
+ s.add_argument("index")
66
+ s.add_argument("query")
67
+ s.add_argument("--k", type=int, default=10)
68
+ s.set_defaults(func=cmd_search)
69
+
70
+ args = p.parse_args()
71
+ args.func(args)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
geomretrieval/config.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, asdict
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class FrozenConfig:
7
+ """Frozen MS-MARCO-developed configuration.
8
+
9
+ The point of the six-dataset campaign is transfer, not per-dataset tuning.
10
+ Only corpus-mechanical settings such as max_features/min_df should be changed
11
+ when a dataset physically requires it.
12
+ """
13
+
14
+ # Sparse lexical representation
15
+ max_features: int = 50_000
16
+ min_df: int = 1
17
+ lowercase: bool = True
18
+ token_pattern: str = r"(?u)\b\w\w+\b"
19
+
20
+ # Fuzzy index
21
+ F: int = 4 # fuzzy memberships/document
22
+ B: int = 64 # sparse center support
23
+ S: int = 16 # signed residual support/membership
24
+
25
+ # Reliability
26
+ tau: float = 20.0
27
+ beta: float = -0.2
28
+ reliability_eps: float = 1e-6
29
+
30
+ # Corpus term geometry
31
+ L: int = 12 # top terms/document used to estimate graph
32
+ graph_significance_tau: float = 10.0
33
+ assoc_k: int = 64 # first-order PPMI neighbors retained
34
+ route_k: int = 32 # second-order context neighbors retained
35
+ graph_block_size: int = 128
36
+
37
+ # Query routing
38
+ route_alpha: float = 0.10
39
+ route_budget: int = 32 # strongest total route coordinates; original terms preserved
40
+
41
+ # Head / tail scoring
42
+ head_k: int = 10
43
+ gamma_head: float = 0.5
44
+ gamma_tail: float = 1.0
45
+ lambda_membership: float = 2.0
46
+
47
+ # Final binary-support reranker
48
+ rerank_pool: int = 2_000
49
+ lambda_lex: float = 2.5
50
+ length_b: float = 0.2
51
+ semantic_k: int = 16
52
+ lambda_sem: float = 0.05
53
+
54
+ # Requested output depth
55
+ output_k: int = 100
56
+
57
+ def to_dict(self) -> dict:
58
+ return asdict(self)
59
+
60
+ @classmethod
61
+ def from_dict(cls, d: dict) -> "FrozenConfig":
62
+ return cls(**d)
geomretrieval/geometry.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import numpy as np
3
+ from scipy import sparse
4
+ from sklearn.preprocessing import normalize
5
+
6
+ from .config import FrozenConfig
7
+ from .utils import csr_row_topk_matrix
8
+
9
+
10
+ def _keep_top_sparse_rows(mat: sparse.csr_matrix, k: int, exclude_diagonal_offset: int | None = None) -> sparse.csr_matrix:
11
+ rows, cols, vals = [], [], []
12
+ for r in range(mat.shape[0]):
13
+ a, b = mat.indptr[r], mat.indptr[r + 1]
14
+ idx, dat = mat.indices[a:b], mat.data[a:b]
15
+ if exclude_diagonal_offset is not None:
16
+ diag = exclude_diagonal_offset + r
17
+ mask = idx != diag
18
+ idx, dat = idx[mask], dat[mask]
19
+ if len(dat) == 0:
20
+ continue
21
+ kk = min(k, len(dat))
22
+ pick = np.argpartition(dat, -kk)[-kk:]
23
+ pick = pick[np.argsort(dat[pick])[::-1]]
24
+ rows.extend([r] * kk)
25
+ cols.extend(idx[pick].tolist())
26
+ vals.extend(dat[pick].astype(np.float32).tolist())
27
+ return sparse.csr_matrix((np.asarray(vals, np.float32), (rows, cols)), shape=mat.shape)
28
+
29
+
30
+ def build_term_graphs(X: sparse.csr_matrix, cfg: FrozenConfig) -> tuple[sparse.csr_matrix, sparse.csr_matrix]:
31
+ """Build first-order significance-shrunk PPMI A and second-order context graph G.
32
+
33
+ Both are built blockwise; a dense vocabulary x vocabulary matrix is never
34
+ instantiated.
35
+ """
36
+ N, M = X.shape
37
+ T = csr_row_topk_matrix(X, cfg.L, binary=True)
38
+ n_i = np.asarray(T.sum(axis=0)).ravel().astype(np.float64)
39
+
40
+ A_rows, A_cols, A_vals = [], [], []
41
+ bs = cfg.graph_block_size
42
+ for start in range(0, M, bs):
43
+ end = min(M, start + bs)
44
+ # co[r,j] = number of documents in which term start+r and j both appear
45
+ # among the document's top-L TF-IDF coordinates.
46
+ co = (T[:, start:end].T @ T).tocsr()
47
+ for local in range(end - start):
48
+ i = start + local
49
+ a, b = co.indptr[local], co.indptr[local + 1]
50
+ js = co.indices[a:b]
51
+ nij = co.data[a:b].astype(np.float64)
52
+ mask = (js != i) & (nij > 0) & (n_i[js] > 0) & (n_i[i] > 0)
53
+ js, nij = js[mask], nij[mask]
54
+ if not len(js):
55
+ continue
56
+ ppmi = np.log((nij * float(N) + 1e-12) / (n_i[i] * n_i[js] + 1e-12))
57
+ ppmi = np.maximum(ppmi, 0.0)
58
+ score = (nij / (nij + cfg.graph_significance_tau)) * ppmi
59
+ pos = score > 0
60
+ js, score = js[pos], score[pos]
61
+ if not len(score):
62
+ continue
63
+ kk = min(cfg.assoc_k, len(score))
64
+ pick = np.argpartition(score, -kk)[-kk:]
65
+ pick = pick[np.argsort(score[pick])[::-1]]
66
+ A_rows.extend([i] * kk)
67
+ A_cols.extend(js[pick].tolist())
68
+ A_vals.extend(score[pick].astype(np.float32).tolist())
69
+
70
+ A = sparse.csr_matrix((np.asarray(A_vals, np.float32), (A_rows, A_cols)), shape=(M, M))
71
+ A.eliminate_zeros()
72
+
73
+ An = normalize(A, norm="l2", axis=1, copy=True)
74
+ G_rows, G_cols, G_vals = [], [], []
75
+ for start in range(0, M, bs):
76
+ end = min(M, start + bs)
77
+ sim = (An[start:end] @ An.T).tocsr()
78
+ for local in range(end - start):
79
+ i = start + local
80
+ a, b = sim.indptr[local], sim.indptr[local + 1]
81
+ js = sim.indices[a:b]
82
+ vv = sim.data[a:b]
83
+ mask = (js != i) & (vv > 0)
84
+ js, vv = js[mask], vv[mask]
85
+ if not len(vv):
86
+ continue
87
+ kk = min(cfg.route_k, len(vv))
88
+ pick = np.argpartition(vv, -kk)[-kk:]
89
+ pick = pick[np.argsort(vv[pick])[::-1]]
90
+ G_rows.extend([i] * kk)
91
+ G_cols.extend(js[pick].tolist())
92
+ G_vals.extend(vv[pick].astype(np.float32).tolist())
93
+ G = sparse.csr_matrix((np.asarray(G_vals, np.float32), (G_rows, G_cols)), shape=(M, M))
94
+ G.eliminate_zeros()
95
+ return A, G
geomretrieval/index.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ import os
4
+ import time
5
+ from pathlib import Path
6
+ from typing import Iterable
7
+
8
+ import joblib
9
+ import numpy as np
10
+ from scipy import sparse
11
+ from sklearn.feature_extraction.text import TfidfVectorizer
12
+
13
+ from .config import FrozenConfig
14
+ from .geometry import build_term_graphs
15
+ from .utils import topk_sparse_row, zscore
16
+
17
+
18
+ class GeometricIndex:
19
+ """Frozen sparse geometric retrieval index.
20
+
21
+ The implementation follows the final handoff architecture:
22
+ TF-IDF -> F=4 fuzzy routing -> B=64 sparse centers -> S=16 signed
23
+ residuals -> inverse local sign-variance reliability -> significance
24
+ scoring -> second-order vocabulary routing -> binary whole-document
25
+ support reranking.
26
+ """
27
+
28
+ def __init__(self, config: FrozenConfig | None = None):
29
+ self.config = config or FrozenConfig()
30
+ self.vectorizer: TfidfVectorizer | None = None
31
+ self.doc_ids: np.ndarray | None = None
32
+ self.X: sparse.csr_matrix | None = None
33
+
34
+ # ------------------------------------------------------------------
35
+ # BUILD
36
+ # ------------------------------------------------------------------
37
+ @classmethod
38
+ def build(
39
+ cls,
40
+ texts: list[str],
41
+ doc_ids: list[str] | None = None,
42
+ config: FrozenConfig | None = None,
43
+ verbose: bool = True,
44
+ ) -> "GeometricIndex":
45
+ self = cls(config)
46
+ cfg = self.config
47
+ N = len(texts)
48
+ if doc_ids is None:
49
+ doc_ids = [str(i) for i in range(N)]
50
+ if len(doc_ids) != N:
51
+ raise ValueError("doc_ids and texts must have identical length")
52
+ self.doc_ids = np.asarray(doc_ids, dtype=object)
53
+
54
+ def log(msg):
55
+ if verbose:
56
+ print(msg, flush=True)
57
+
58
+ t0 = time.perf_counter()
59
+ log(f"[1/8] TF-IDF: N={N:,}, max_features={cfg.max_features:,}")
60
+ self.vectorizer = TfidfVectorizer(
61
+ max_features=cfg.max_features,
62
+ min_df=cfg.min_df,
63
+ lowercase=cfg.lowercase,
64
+ token_pattern=cfg.token_pattern,
65
+ norm="l2",
66
+ dtype=np.float32,
67
+ smooth_idf=True,
68
+ sublinear_tf=False,
69
+ )
70
+ X = self.vectorizer.fit_transform(texts).tocsr().astype(np.float32)
71
+ X.sort_indices()
72
+ self.X = X
73
+ self.idf = np.asarray(self.vectorizer.idf_, dtype=np.float32)
74
+ self.vocab_size = X.shape[1]
75
+ M = self.vocab_size
76
+ log(f" shape={X.shape}, nnz={X.nnz:,}, {time.perf_counter()-t0:.2f}s")
77
+
78
+ # Whole-document binary support is simply the CSR sparsity pattern.
79
+ # Keep a separate compact CSR with uint8 data so query reranking never
80
+ # needs the TF-IDF amplitudes.
81
+ self.support_indptr = X.indptr.astype(np.int64, copy=True)
82
+ self.support_indices = X.indices.astype(np.int32, copy=True)
83
+
84
+ analyzer = self.vectorizer.build_analyzer()
85
+ self.doc_lengths = np.asarray([len(analyzer(t)) for t in texts], dtype=np.int32)
86
+ self.avg_doc_length = float(max(1.0, self.doc_lengths.mean()))
87
+
88
+ # ---------------- Fuzzy memberships ----------------
89
+ log(f"[2/8] Fuzzy memberships F={cfg.F}")
90
+ branches = np.full((N, cfg.F), -1, dtype=np.int32)
91
+ memberships = np.zeros((N, cfg.F), dtype=np.float32)
92
+ for d in range(N):
93
+ a, b = X.indptr[d], X.indptr[d+1]
94
+ idx, dat = X.indices[a:b], X.data[a:b]
95
+ if not len(idx):
96
+ continue
97
+ ii, vv = topk_sparse_row(idx, dat, cfg.F)
98
+ n = len(ii)
99
+ branches[d, :n] = ii
100
+ den = float(vv.sum())
101
+ memberships[d, :n] = vv / den if den > 0 else 1.0 / n
102
+ self.branches = branches
103
+ self.memberships = memberships
104
+
105
+ # Flatten memberships and sort by branch. This one structure serves as
106
+ # the branch inverted index while preserving the document/slot identity.
107
+ flat_branch = branches.ravel()
108
+ valid_flat = np.flatnonzero(flat_branch >= 0).astype(np.int64)
109
+ order = np.argsort(flat_branch[valid_flat], kind="stable")
110
+ self.branch_order = valid_flat[order]
111
+ sorted_br = flat_branch[self.branch_order]
112
+ counts = np.bincount(sorted_br, minlength=M)
113
+ self.branch_offsets = np.zeros(M + 1, dtype=np.int64)
114
+ np.cumsum(counts, out=self.branch_offsets[1:])
115
+
116
+ # ---------------- Sparse shared centers ----------------
117
+ log(f"[3/8] Sparse branch centers B={cfg.B}")
118
+ wr = np.repeat(np.arange(N, dtype=np.int32), cfg.F)
119
+ wc = branches.ravel()
120
+ wd = memberships.ravel()
121
+ valid = wc >= 0
122
+ W = sparse.csr_matrix((wd[valid], (wr[valid], wc[valid])), shape=(N, M), dtype=np.float32)
123
+ branch_mass = np.asarray(W.sum(axis=0)).ravel().astype(np.float32)
124
+ center_terms = np.full((M, cfg.B), -1, dtype=np.int32)
125
+ center_values = np.zeros((M, cfg.B), dtype=np.float32)
126
+ block = 256
127
+ for start in range(0, M, block):
128
+ end = min(M, start + block)
129
+ C = (W[:, start:end].T @ X).tocsr()
130
+ for local in range(end-start):
131
+ j = start + local
132
+ if branch_mass[j] <= 0:
133
+ continue
134
+ a, b = C.indptr[local], C.indptr[local+1]
135
+ idx = C.indices[a:b]
136
+ dat = C.data[a:b] / branch_mass[j]
137
+ if not len(dat):
138
+ continue
139
+ kk = min(cfg.B, len(dat))
140
+ pick = np.argpartition(dat, -kk)[-kk:]
141
+ ii, vv = idx[pick], dat[pick]
142
+ # Sorted term IDs make residual construction and later lookup cheap.
143
+ oo = np.argsort(ii)
144
+ ii, vv = ii[oo], vv[oo]
145
+ center_terms[j, :kk] = ii
146
+ center_values[j, :kk] = vv
147
+ self.center_terms = center_terms
148
+ self.center_values = center_values
149
+ del W
150
+
151
+ # ---------------- Signed residual codes ----------------
152
+ log(f"[4/8] Signed residuals S={cfg.S} (document-present coordinates only)")
153
+ res_terms = np.full((N, cfg.F, cfg.S), -1, dtype=np.int32)
154
+ res_signs = np.zeros((N, cfg.F, cfg.S), dtype=np.int8)
155
+ res_center = np.zeros((N, cfg.F, cfg.S), dtype=np.float32)
156
+
157
+ for d in range(N):
158
+ a, b = X.indptr[d], X.indptr[d+1]
159
+ didx, dval = X.indices[a:b], X.data[a:b]
160
+ if not len(didx):
161
+ continue
162
+ for s in range(cfg.F):
163
+ j = int(branches[d, s])
164
+ if j < 0:
165
+ continue
166
+ cidx = center_terms[j]
167
+ cval = center_values[j]
168
+ maskc = cidx >= 0
169
+ ck, cv = cidx[maskc], cval[maskc]
170
+ c_at_doc = np.zeros(len(didx), dtype=np.float32)
171
+ if len(ck):
172
+ pos = np.searchsorted(ck, didx)
173
+ ok = pos < len(ck)
174
+ oi = np.flatnonzero(ok)
175
+ if len(oi):
176
+ p = pos[oi]
177
+ same = ck[p] == didx[oi]
178
+ chosen = oi[same]
179
+ c_at_doc[chosen] = cv[pos[chosen]]
180
+ residual = dval - c_at_doc
181
+ kk = min(cfg.S, len(residual))
182
+ pick = np.argpartition(np.abs(residual), -kk)[-kk:]
183
+ pick = pick[np.argsort(np.abs(residual[pick]))[::-1]]
184
+ res_terms[d, s, :kk] = didx[pick]
185
+ res_signs[d, s, :kk] = np.where(residual[pick] >= 0, 1, -1).astype(np.int8)
186
+ res_center[d, s, :kk] = c_at_doc[pick]
187
+ self.res_terms = res_terms
188
+ self.res_signs = res_signs
189
+ self.res_center_values = res_center
190
+
191
+ # ---------------- Reliability ----------------
192
+ log("[5/8] Zero-inclusive local sign reliability")
193
+ rel = np.ones((N, cfg.F, cfg.S), dtype=np.float16)
194
+ # Global sign variance: zeros are implicit over all valid memberships.
195
+ n_memberships_total = max(1, len(self.branch_order))
196
+ global_count = np.zeros(M, dtype=np.float64)
197
+ global_sum = np.zeros(M, dtype=np.float64)
198
+ for d0 in range(0, N, 50_000):
199
+ tt = res_terms[d0:d0+50_000].ravel()
200
+ zz = res_signs[d0:d0+50_000].ravel().astype(np.float64)
201
+ ok = tt >= 0
202
+ global_count += np.bincount(tt[ok], minlength=M)
203
+ global_sum += np.bincount(tt[ok], weights=zz[ok], minlength=M)
204
+ g_e2 = global_count / n_memberships_total
205
+ g_e1 = global_sum / n_memberships_total
206
+ global_var = np.maximum(g_e2 - g_e1 * g_e1, 0.0)
207
+ self.global_sign_var = global_var.astype(np.float32)
208
+
209
+ # Process one branch at a time. Each branch sees only its own memberships,
210
+ # so np.unique operates on a small local residual set rather than a giant
211
+ # vocabulary x vocabulary table.
212
+ flat_rel = rel.reshape(N * cfg.F, cfg.S)
213
+ flat_terms = res_terms.reshape(N * cfg.F, cfg.S)
214
+ flat_signs = res_signs.reshape(N * cfg.F, cfg.S)
215
+ for j in range(M):
216
+ a, b = self.branch_offsets[j], self.branch_offsets[j+1]
217
+ mpos = self.branch_order[a:b]
218
+ nj = len(mpos)
219
+ if nj == 0:
220
+ continue
221
+ terms_j = flat_terms[mpos].ravel()
222
+ signs_j = flat_signs[mpos].ravel().astype(np.float64)
223
+ ok = terms_j >= 0
224
+ if not np.any(ok):
225
+ continue
226
+ u, inv = np.unique(terms_j[ok], return_inverse=True)
227
+ cnt = np.bincount(inv).astype(np.float64)
228
+ sm = np.bincount(inv, weights=signs_j[ok]).astype(np.float64)
229
+ e2 = cnt / nj
230
+ e1 = sm / nj
231
+ lv = np.maximum(e2 - e1 * e1, 0.0)
232
+ shr = (cnt / (cnt + cfg.tau)) * lv + (cfg.tau / (cnt + cfg.tau)) * global_var[u]
233
+ w = np.power(shr + cfg.reliability_eps, cfg.beta)
234
+ # Keep the mean branch weight near one to avoid branch-scale artifacts.
235
+ if len(w) and np.isfinite(w).all() and w.mean() > 0:
236
+ w = w / w.mean()
237
+ lookup = {int(t): float(v) for t, v in zip(u, w)}
238
+ # Offline dictionary use is acceptable; query-time retrieval remains vectorized.
239
+ for p in mpos:
240
+ for r in range(cfg.S):
241
+ t = int(flat_terms[p, r])
242
+ if t >= 0:
243
+ flat_rel[p, r] = np.float16(lookup.get(t, 1.0))
244
+ self.res_reliability = rel
245
+
246
+ # ---------------- Term geometry ----------------
247
+ log(f"[6/8] Term geometry L={cfg.L}, PPMI top={cfg.assoc_k}, context top={cfg.route_k}")
248
+ self.A, self.G = build_term_graphs(X, cfg)
249
+
250
+ # Index no longer requires TF-IDF corpus amplitudes for normal querying.
251
+ # Retain X only in-memory for diagnostics; save() omits it by default.
252
+ log("[7/8] Finalizing compact index")
253
+ self._fitted = True
254
+ self.build_seconds = time.perf_counter() - t0
255
+ log(f"[8/8] DONE in {self.build_seconds:.2f}s")
256
+ return self
257
+
258
+ # ------------------------------------------------------------------
259
+ # QUERY
260
+ # ------------------------------------------------------------------
261
+ def _query_vector(self, text: str) -> sparse.csr_matrix:
262
+ if self.vectorizer is None:
263
+ raise RuntimeError("Index is not fitted")
264
+ q = self.vectorizer.transform([text]).tocsr().astype(np.float32)
265
+ q.sort_indices()
266
+ return q
267
+
268
+ def _expanded_route(self, q: sparse.csr_matrix) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
269
+ cfg = self.config
270
+ M = self.vocab_size
271
+ qa, qb = q.indptr[0], q.indptr[1]
272
+ q_terms = q.indices[qa:qb]
273
+ q_vals = q.data[qa:qb]
274
+ route = np.zeros(M, dtype=np.float32)
275
+ route[q_terms] = q_vals
276
+
277
+ # Weak second-order semantic routing. Original coordinates are preserved.
278
+ for t, qv in zip(q_terms, q_vals):
279
+ a, b = self.G.indptr[t], self.G.indptr[t+1]
280
+ nb = self.G.indices[a:b]
281
+ sv = self.G.data[a:b]
282
+ route[nb] += cfg.route_alpha * float(qv) * sv
283
+
284
+ nonzero = np.flatnonzero(route > 0)
285
+ originals = set(map(int, q_terms.tolist()))
286
+ if len(nonzero) > cfg.route_budget:
287
+ # Preserve every literal query term; fill the remaining budget with
288
+ # strongest inferred coordinates.
289
+ inferred = np.asarray([i for i in nonzero if int(i) not in originals], dtype=np.int32)
290
+ budget = max(0, cfg.route_budget - len(originals))
291
+ if budget and len(inferred) > budget:
292
+ pick = np.argpartition(route[inferred], -budget)[-budget:]
293
+ inferred = inferred[pick]
294
+ elif budget == 0:
295
+ inferred = np.empty(0, dtype=np.int32)
296
+ chosen = np.asarray(sorted(originals), dtype=np.int32)
297
+ nonzero = np.concatenate([chosen, inferred])
298
+ # strongest first is convenient but not required for union routing
299
+ order = np.argsort(route[nonzero])[::-1]
300
+ return nonzero[order].astype(np.int32), route[nonzero[order]], q_terms
301
+
302
+ def search(self, text: str, k: int | None = None, return_scores: bool = False):
303
+ cfg = self.config
304
+ k = int(k or cfg.output_k)
305
+ q = self._query_vector(text)
306
+ q_dense = np.zeros(self.vocab_size, dtype=np.float32)
307
+ q_dense[q.indices] = q.data
308
+ route_terms, route_vals, q_terms = self._expanded_route(q)
309
+ if len(route_terms) == 0:
310
+ return ([], np.empty(0, np.float32)) if return_scores else []
311
+
312
+ route_dense = np.zeros(self.vocab_size, dtype=np.float32)
313
+ route_dense[route_terms] = route_vals
314
+
315
+ # Retrieve matching membership positions, not just docs, because fuzzy
316
+ # multi-branch evidence is part of the score.
317
+ pieces = []
318
+ for j in route_terms:
319
+ a, b = self.branch_offsets[j], self.branch_offsets[j+1]
320
+ if b > a:
321
+ pieces.append(self.branch_order[a:b])
322
+ if not pieces:
323
+ return ([], np.empty(0, np.float32)) if return_scores else []
324
+ flatpos = np.concatenate(pieces).astype(np.int64, copy=False)
325
+ docs = (flatpos // cfg.F).astype(np.int64)
326
+ slots = (flatpos % cfg.F).astype(np.int64)
327
+ br = self.branches[docs, slots]
328
+
329
+ terms = self.res_terms[docs, slots]
330
+ valid = terms >= 0
331
+ safe_terms = np.where(valid, terms, 0)
332
+ qv = q_dense[safe_terms]
333
+ local = np.sum(
334
+ self.res_reliability[docs, slots].astype(np.float32)
335
+ * (qv - self.res_center_values[docs, slots])
336
+ * self.res_signs[docs, slots].astype(np.float32)
337
+ * valid,
338
+ axis=1,
339
+ )
340
+ significance = np.sum((qv * qv) * valid, axis=1)
341
+ m = self.memberships[docs, slots]
342
+ rho = route_dense[br]
343
+
344
+ unique_docs, inv = np.unique(docs, return_inverse=True)
345
+ head_contrib = m * rho * local * np.power(np.maximum(significance, 0.0), cfg.gamma_head)
346
+ tail_contrib = m * rho * local * np.power(np.maximum(significance, 0.0), cfg.gamma_tail)
347
+ consensus_contrib = m * rho
348
+ head = np.bincount(inv, weights=head_contrib, minlength=len(unique_docs)).astype(np.float32)
349
+ tail = np.bincount(inv, weights=tail_contrib, minlength=len(unique_docs)).astype(np.float32)
350
+ consensus = np.bincount(inv, weights=consensus_contrib, minlength=len(unique_docs)).astype(np.float32)
351
+ tail = tail + cfg.lambda_membership * consensus
352
+
353
+ # Freeze precision head.
354
+ hk = min(cfg.head_k, len(unique_docs))
355
+ hidx = np.argpartition(head, -hk)[-hk:]
356
+ hidx = hidx[np.argsort(head[hidx])[::-1]]
357
+ frozen_docs = unique_docs[hidx]
358
+ frozen_set = set(map(int, frozen_docs.tolist()))
359
+
360
+ # Recall-oriented tail shortlist.
361
+ mask_tail = np.asarray([int(d) not in frozen_set for d in unique_docs], dtype=bool)
362
+ td = unique_docs[mask_tail]
363
+ ts = tail[mask_tail]
364
+ if len(td):
365
+ P = min(cfg.rerank_pool, len(td))
366
+ pidx = np.argpartition(ts, -P)[-P:]
367
+ shortlist_docs = td[pidx]
368
+ shortlist_tail = ts[pidx]
369
+
370
+ # Whole-document binary lexical support. This is deliberately term
371
+ # presence only; exact within-document TF was found unnecessary.
372
+ lex_vec = np.zeros(self.vocab_size, dtype=np.float32)
373
+ lex_vec[q.indices] = self.idf[q.indices]
374
+ lex = np.zeros(P, dtype=np.float32)
375
+
376
+ sem_vec = np.zeros(self.vocab_size, dtype=np.float32)
377
+ for t, qamp in zip(q.indices, q.data):
378
+ a, b = self.A.indptr[t], self.A.indptr[t+1]
379
+ nb = self.A.indices[a:b][:cfg.semantic_k]
380
+ sv = self.A.data[a:b][:cfg.semantic_k]
381
+ if len(nb):
382
+ sem_vec[nb] += float(qamp) * sv * self.idf[nb]
383
+ sem = np.zeros(P, dtype=np.float32)
384
+
385
+ for i, d in enumerate(shortlist_docs):
386
+ a, b = self.support_indptr[d], self.support_indptr[d+1]
387
+ support = self.support_indices[a:b]
388
+ lex[i] = float(lex_vec[support].sum())
389
+ if cfg.length_b != 0:
390
+ denom = (1.0 - cfg.length_b) + cfg.length_b * (float(self.doc_lengths[d]) / self.avg_doc_length)
391
+ if denom > 0:
392
+ lex[i] /= denom
393
+ sem[i] = float(sem_vec[support].sum())
394
+
395
+ final = zscore(shortlist_tail) + cfg.lambda_lex * zscore(lex) + cfg.lambda_sem * zscore(sem)
396
+ oo = np.argsort(final)[::-1]
397
+ ranked_tail = shortlist_docs[oo]
398
+ ranked_tail_scores = final[oo]
399
+
400
+ # If caller asks beyond the reranking pool, append remaining tail by
401
+ # the cheap score. This does not affect the usual top-100 evaluation.
402
+ shortlist_set = set(map(int, shortlist_docs.tolist()))
403
+ rest_mask = np.asarray([int(d) not in shortlist_set for d in td], dtype=bool)
404
+ rest_docs = td[rest_mask]
405
+ rest_scores = ts[rest_mask]
406
+ if len(rest_docs):
407
+ ro = np.argsort(rest_scores)[::-1]
408
+ ranked_tail = np.concatenate([ranked_tail, rest_docs[ro]])
409
+ ranked_tail_scores = np.concatenate([ranked_tail_scores, rest_scores[ro]])
410
+ else:
411
+ ranked_tail = np.empty(0, dtype=np.int64)
412
+ ranked_tail_scores = np.empty(0, dtype=np.float32)
413
+
414
+ ranked = np.concatenate([frozen_docs, ranked_tail])[:k]
415
+ # Head and tail score scales differ; scores are only for diagnostics.
416
+ hs = head[hidx]
417
+ scores = np.concatenate([hs, ranked_tail_scores])[:k]
418
+ ids = self.doc_ids[ranked].tolist()
419
+ if return_scores:
420
+ return ids, scores
421
+ return ids
422
+
423
+ def batch_search(self, queries: dict[str, str], k: int | None = None, timing: bool = False):
424
+ run: dict[str, list[str]] = {}
425
+ times_ms = []
426
+ for qid, text in queries.items():
427
+ t0 = time.perf_counter()
428
+ run[str(qid)] = self.search(text, k=k)
429
+ times_ms.append((time.perf_counter() - t0) * 1000.0)
430
+ if timing:
431
+ arr = np.asarray(times_ms, dtype=np.float64)
432
+ return run, {
433
+ "median_ms": float(np.median(arr)),
434
+ "mean_ms": float(np.mean(arr)),
435
+ "p95_ms": float(np.percentile(arr, 95)),
436
+ "qps": float(1000.0 / np.mean(arr)) if np.mean(arr) > 0 else float("inf"),
437
+ }
438
+ return run
439
+
440
+ # ------------------------------------------------------------------
441
+ # SERIALIZATION
442
+ # ------------------------------------------------------------------
443
+ def save(self, path: str | os.PathLike, include_tfidf_matrix: bool = False):
444
+ p = Path(path)
445
+ p.mkdir(parents=True, exist_ok=True)
446
+ joblib.dump(self.vectorizer, p / "vectorizer.joblib")
447
+ with (p / "config.json").open("w") as f:
448
+ json.dump(self.config.to_dict(), f, indent=2)
449
+ meta = {
450
+ "vocab_size": int(self.vocab_size),
451
+ "avg_doc_length": float(self.avg_doc_length),
452
+ "build_seconds": float(getattr(self, "build_seconds", 0.0)),
453
+ }
454
+ with (p / "meta.json").open("w") as f:
455
+ json.dump(meta, f, indent=2)
456
+ np.savez_compressed(
457
+ p / "arrays.npz",
458
+ doc_ids=self.doc_ids,
459
+ idf=self.idf,
460
+ support_indptr=self.support_indptr,
461
+ support_indices=self.support_indices,
462
+ doc_lengths=self.doc_lengths,
463
+ branches=self.branches,
464
+ memberships=self.memberships,
465
+ branch_order=self.branch_order,
466
+ branch_offsets=self.branch_offsets,
467
+ center_terms=self.center_terms,
468
+ center_values=self.center_values,
469
+ res_terms=self.res_terms,
470
+ res_signs=self.res_signs,
471
+ res_center_values=self.res_center_values,
472
+ res_reliability=self.res_reliability,
473
+ global_sign_var=self.global_sign_var,
474
+ )
475
+ sparse.save_npz(p / "assoc_ppmi.npz", self.A)
476
+ sparse.save_npz(p / "context_similarity.npz", self.G)
477
+ if include_tfidf_matrix and self.X is not None:
478
+ sparse.save_npz(p / "tfidf_corpus.npz", self.X)
479
+
480
+ @classmethod
481
+ def load(cls, path: str | os.PathLike) -> "GeometricIndex":
482
+ p = Path(path)
483
+ with (p / "config.json").open() as f:
484
+ cfg = FrozenConfig.from_dict(json.load(f))
485
+ self = cls(cfg)
486
+ self.vectorizer = joblib.load(p / "vectorizer.joblib")
487
+ with (p / "meta.json").open() as f:
488
+ meta = json.load(f)
489
+ a = np.load(p / "arrays.npz", allow_pickle=True)
490
+ for name in a.files:
491
+ setattr(self, name, a[name])
492
+ self.vocab_size = int(meta["vocab_size"])
493
+ self.avg_doc_length = float(meta["avg_doc_length"])
494
+ self.build_seconds = float(meta.get("build_seconds", 0.0))
495
+ self.A = sparse.load_npz(p / "assoc_ppmi.npz").tocsr()
496
+ self.G = sparse.load_npz(p / "context_similarity.npz").tocsr()
497
+ tfidf = p / "tfidf_corpus.npz"
498
+ self.X = sparse.load_npz(tfidf).tocsr() if tfidf.exists() else None
499
+ self._fitted = True
500
+ return self
geomretrieval/metrics.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import math
3
+ import numpy as np
4
+
5
+
6
+ def _dcg(rels: list[float], exp_gain: bool = True) -> float:
7
+ total = 0.0
8
+ for rank, rel in enumerate(rels, start=1):
9
+ gain = (2.0 ** rel - 1.0) if exp_gain else rel
10
+ total += gain / math.log2(rank + 1.0)
11
+ return total
12
+
13
+
14
+ def evaluate_run(
15
+ run: dict[str, list[str]],
16
+ qrels: dict[str, dict[str, float]],
17
+ ks: tuple[int, ...] = (10, 100),
18
+ ndcg_k: int = 10,
19
+ mrr_k: int = 10,
20
+ exp_gain: bool = True,
21
+ ) -> dict[str, float]:
22
+ """Binary top-K metrics plus graded nDCG.
23
+
24
+ 'Accuracy' for retrieval is reported as Hit@K rather than ordinary
25
+ classification accuracy, which is meaningless with millions of negatives.
26
+ """
27
+ qids = [q for q in qrels if q in run]
28
+ if not qids:
29
+ raise ValueError("No query IDs overlap between run and qrels")
30
+
31
+ vals: dict[str, list[float]] = {}
32
+ for k in ks:
33
+ vals[f"P@{k}"] = []
34
+ vals[f"R@{k}"] = []
35
+ vals[f"Hit@{k}"] = []
36
+ vals[f"MRR@{mrr_k}"] = []
37
+ vals[f"nDCG@{ndcg_k}"] = []
38
+
39
+ for qid in qids:
40
+ ranked = run[qid]
41
+ qr = qrels[qid]
42
+ positive = {d for d, r in qr.items() if r > 0}
43
+ npos = max(1, len(positive))
44
+
45
+ for k in ks:
46
+ top = ranked[:k]
47
+ hits = sum(1 for d in top if d in positive)
48
+ vals[f"P@{k}"].append(hits / float(k))
49
+ vals[f"R@{k}"].append(hits / float(npos))
50
+ vals[f"Hit@{k}"].append(float(hits > 0))
51
+
52
+ rr = 0.0
53
+ for rank, d in enumerate(ranked[:mrr_k], start=1):
54
+ if d in positive:
55
+ rr = 1.0 / rank
56
+ break
57
+ vals[f"MRR@{mrr_k}"].append(rr)
58
+
59
+ observed = [float(qr.get(d, 0.0)) for d in ranked[:ndcg_k]]
60
+ ideal = sorted((float(r) for r in qr.values()), reverse=True)[:ndcg_k]
61
+ idcg = _dcg(ideal, exp_gain=exp_gain)
62
+ vals[f"nDCG@{ndcg_k}"].append(_dcg(observed, exp_gain=exp_gain) / idcg if idcg > 0 else 0.0)
63
+
64
+ out = {k: float(np.mean(v)) for k, v in vals.items()}
65
+ out["n_queries"] = float(len(qids))
66
+ return out
geomretrieval/rag_top10.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ """Top-10 RAG ranking layer for the sparse geometric index.
4
+
5
+ This module is the cleaned, path-independent version of the exact SciFact and
6
+ TREC-COVID experiment scripts preserved under ``experiments/beir/*history.py``.
7
+ It keeps the geometric index fixed and changes only the shortlist size P and
8
+ the final top-10 set construction.
9
+
10
+ Important implementation choices
11
+ --------------------------------
12
+ * Early rescue: binary whole-chunk IDF^1 support.
13
+ * Final lexical signal: binary whole-chunk IDF^2 support, not TF^2.
14
+ * Final components retain the validated per-query z-normalization.
15
+ * Branch quality H_j is the mean of the top three branch-specific evidences.
16
+ * Diversity is available only to the ten highest-quality branches.
17
+ * Rank 1 is pure relevance; ranks 2..10 receive a soft diversity correction.
18
+ * Repeated branches are allowed. There is no one-document-per-branch rule.
19
+ """
20
+
21
+ from dataclasses import dataclass
22
+ import time
23
+ import numpy as np
24
+
25
+ from .metrics import evaluate_run
26
+
27
+
28
+ def _zscore(x):
29
+ x = np.asarray(x, np.float32)
30
+ if not len(x):
31
+ return x
32
+ sd = float(x.std())
33
+ return np.zeros_like(x) if sd < 1e-8 else (x - float(x.mean())) / sd
34
+
35
+
36
+ def _minmax_hi(x):
37
+ """Map scores monotonically to [0, 1], high remains good."""
38
+ x = np.asarray(x, np.float32)
39
+ if not len(x):
40
+ return x
41
+ lo, hi = float(x.min()), float(x.max())
42
+ den = hi - lo
43
+ return np.ones_like(x) if den < 1e-8 else (x - lo) / den
44
+
45
+
46
+ def _topk_large(score, k):
47
+ score = np.asarray(score)
48
+ n = len(score)
49
+ k = min(int(k), n)
50
+ if k <= 0:
51
+ return np.empty(0, np.int64)
52
+ if n <= k:
53
+ return np.argsort(score)[::-1]
54
+ ii = np.argpartition(score, -k)[-k:]
55
+ return ii[np.argsort(score[ii])[::-1]]
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class RAGTop10Config:
60
+ pool_size: int = 100
61
+ gamma: float = 0.25
62
+ lambda_membership: float = 0.125
63
+ pre_length_b: float = 0.2
64
+ final_length_b: float = 0.1
65
+ coordination_alpha: float = 0.25
66
+ lambda_lex: float = 4.0
67
+ lambda_sem: float = 0.3
68
+ lambda_rare: float = 1.0
69
+ semantic_k: int = 16
70
+ rare_topk: int = 3
71
+ hq_top_branches: int = 10
72
+ branch_quality_top_docs: int = 3
73
+ lambda_diversity: float = 0.1
74
+
75
+
76
+ class RAGTop10Ranker:
77
+ """RAG-oriented shortlist and top-10 set selector.
78
+
79
+ ``GeometricIndex`` performs corpus indexing and stores the compact geometry.
80
+ This class consumes that frozen representation. It does not train a model,
81
+ rebuild centers, or alter residual codes.
82
+ """
83
+
84
+ def __init__(self, index, config: RAGTop10Config | None = None):
85
+ self.idx = index
86
+ self.cfg = config or RAGTop10Config()
87
+ self.M = int(index.vocab_size)
88
+
89
+ def _center_sparse(self, branch):
90
+ t = self.idx.center_terms[branch]
91
+ v = self.idx.center_values[branch]
92
+ ok = t >= 0
93
+ t = t[ok].astype(np.int32)
94
+ v = v[ok].astype(np.float32)
95
+ n = float(np.linalg.norm(v))
96
+ if n > 0:
97
+ v = v / n
98
+ order = np.argsort(t)
99
+ return t[order], v[order]
100
+
101
+ @staticmethod
102
+ def _spdot(a_t, a_v, b_t, b_v):
103
+ i = j = 0
104
+ s = 0.0
105
+ while i < len(a_t) and j < len(b_t):
106
+ if a_t[i] == b_t[j]:
107
+ s += float(a_v[i]) * float(b_v[j]); i += 1; j += 1
108
+ elif a_t[i] < b_t[j]:
109
+ i += 1
110
+ else:
111
+ j += 1
112
+ return s
113
+
114
+ def prepare(self, text: str):
115
+ """Retrieve geometric candidates and create the P-sized chunk shortlist."""
116
+ idx, cfg, M = self.idx, self.cfg, self.M
117
+ q = idx._query_vector(text)
118
+ if q.nnz == 0:
119
+ return None
120
+
121
+ q_dense = np.zeros(M, np.float32)
122
+ q_dense[q.indices] = q.data
123
+ route_terms, route_values, _ = idx._expanded_route(q)
124
+ if not len(route_terms):
125
+ return None
126
+ route_dense = np.zeros(M, np.float32)
127
+ route_dense[route_terms] = route_values
128
+
129
+ pieces = []
130
+ for j in route_terms:
131
+ a, b = idx.branch_offsets[j], idx.branch_offsets[j + 1]
132
+ if b > a:
133
+ pieces.append(idx.branch_order[a:b])
134
+ if not pieces:
135
+ return None
136
+
137
+ flat_pos = np.concatenate(pieces).astype(np.int64, copy=False)
138
+ docs = (flat_pos // idx.config.F).astype(np.int64)
139
+ slots = (flat_pos % idx.config.F).astype(np.int64)
140
+ branches = idx.branches[docs, slots]
141
+
142
+ terms = idx.res_terms[docs, slots]
143
+ valid = terms >= 0
144
+ safe_terms = np.where(valid, terms, 0)
145
+ qv = q_dense[safe_terms]
146
+ local = np.sum(
147
+ idx.res_reliability[docs, slots].astype(np.float32)
148
+ * (qv - idx.res_center_values[docs, slots])
149
+ * idx.res_signs[docs, slots].astype(np.float32)
150
+ * valid,
151
+ axis=1,
152
+ )
153
+ significance = np.sum((qv * qv) * valid, axis=1)
154
+ consensus = idx.memberships[docs, slots] * route_dense[branches]
155
+ branch_ev = (
156
+ consensus * local * np.power(np.maximum(significance, 0), cfg.gamma)
157
+ ).astype(np.float32)
158
+
159
+ unique_docs, inverse = np.unique(docs, return_inverse=True)
160
+ tail = np.bincount(inverse, weights=branch_ev, minlength=len(unique_docs)).astype(np.float32)
161
+ tail += cfg.lambda_membership * np.bincount(
162
+ inverse, weights=consensus, minlength=len(unique_docs)
163
+ ).astype(np.float32)
164
+
165
+ # Stage 1: cheap whole-chunk binary IDF^1 rescue before expensive final scoring.
166
+ qlex = np.zeros(M, np.float32)
167
+ qlex[q.indices] = idx.idf[q.indices]
168
+ lex1 = np.zeros(len(unique_docs), np.float32)
169
+ for i, d in enumerate(unique_docs):
170
+ a, b = idx.support_indptr[d], idx.support_indptr[d + 1]
171
+ support = idx.support_indices[a:b]
172
+ raw = float(qlex[support].sum())
173
+ den = (1 - cfg.pre_length_b) + cfg.pre_length_b * (
174
+ float(idx.doc_lengths[d]) / idx.avg_doc_length
175
+ )
176
+ lex1[i] = raw / (den if den > 0 else 1.0)
177
+
178
+ pre = _zscore(tail) + _zscore(lex1)
179
+ selected = _topk_large(pre, cfg.pool_size)
180
+ pool_docs = unique_docs[selected]
181
+ pool_tail = tail[selected]
182
+
183
+ # Preserve branch-specific evidence for robust branch-quality estimation.
184
+ pool_position = np.full(len(unique_docs), -1, np.int32)
185
+ pool_position[selected] = np.arange(len(selected), dtype=np.int32)
186
+ mapped = pool_position[inverse]
187
+ keep = mapped >= 0
188
+ mem_pool = mapped[keep].astype(np.int32)
189
+ mem_branch = branches[keep].astype(np.int32)
190
+ mem_ev = branch_ev[keep].astype(np.float32)
191
+
192
+ # Stage 2: final chunk evidence. No document TF is used here.
193
+ semvec = np.zeros(M, np.float32)
194
+ for t, amp in zip(q.indices, q.data):
195
+ a, b = idx.A.indptr[t], idx.A.indptr[t + 1]
196
+ nb = idx.A.indices[a:b][: cfg.semantic_k]
197
+ sv = idx.A.data[a:b][: cfg.semantic_k]
198
+ if len(nb):
199
+ semvec[nb] += float(amp) * sv * idx.idf[nb]
200
+
201
+ qset = set(map(int, q.indices))
202
+ rare = set(map(int, q.indices[np.argsort(idx.idf[q.indices])[::-1]][: cfg.rare_topk]))
203
+ nq = max(1, len(q.indices))
204
+ lex2 = np.zeros(len(pool_docs), np.float32)
205
+ sem = np.zeros(len(pool_docs), np.float32)
206
+ matched_count = np.zeros(len(pool_docs), np.float32)
207
+ rare_count = np.zeros(len(pool_docs), np.float32)
208
+
209
+ for i, d in enumerate(pool_docs):
210
+ a, b = idx.support_indptr[d], idx.support_indptr[d + 1]
211
+ support = idx.support_indices[a:b]
212
+ sem[i] = float(semvec[support].sum())
213
+ match = [int(t) for t in support if int(t) in qset]
214
+ raw = sum(float(idx.idf[t]) ** 2 for t in match)
215
+ den = (1 - cfg.final_length_b) + cfg.final_length_b * (
216
+ float(idx.doc_lengths[d]) / idx.avg_doc_length
217
+ )
218
+ lex2[i] = raw / (den if den > 0 else 1.0)
219
+ matched_count[i] = len(match)
220
+ rare_count[i] = sum(t in rare for t in match)
221
+
222
+ coverage = matched_count / nq
223
+ lex_adjusted = lex2 * np.power(np.maximum(coverage, 1e-6), cfg.coordination_alpha)
224
+ rare_coverage = rare_count / max(1, min(cfg.rare_topk, nq))
225
+ relevance = (
226
+ _zscore(pool_tail)
227
+ + cfg.lambda_lex * _zscore(lex_adjusted)
228
+ + cfg.lambda_sem * _zscore(sem)
229
+ + cfg.lambda_rare * _zscore(rare_coverage)
230
+ )
231
+
232
+ # Robust high-quality branch score H_j: mean top-r branch-specific evidence.
233
+ branch_pairs = {}
234
+ for pi, b, e in zip(mem_pool, mem_branch, mem_ev):
235
+ key = (int(b), int(pi))
236
+ if key not in branch_pairs or e > branch_pairs[key]:
237
+ branch_pairs[key] = float(e)
238
+ by_branch = {}
239
+ for (b, pi), e in branch_pairs.items():
240
+ by_branch.setdefault(b, []).append((e, pi))
241
+
242
+ H, docs_by_branch = {}, {}
243
+ for b, vals in by_branch.items():
244
+ vals.sort(key=lambda x: x[0], reverse=True)
245
+ r = min(cfg.branch_quality_top_docs, len(vals))
246
+ H[b] = float(np.mean([e for e, _ in vals[:r]]))
247
+ docs_by_branch[b] = np.asarray([pi for _, pi in vals], dtype=np.int32)
248
+
249
+ unique_branches = np.asarray(sorted(H.keys()), dtype=np.int32)
250
+ h = np.asarray([H[int(b)] for b in unique_branches], dtype=np.float32)
251
+ centers = [self._center_sparse(int(b)) for b in unique_branches]
252
+ cosine = np.eye(len(unique_branches), dtype=np.float32)
253
+ for i in range(len(unique_branches)):
254
+ for j in range(i + 1, len(unique_branches)):
255
+ cosine[i, j] = cosine[j, i] = self._spdot(*centers[i], *centers[j])
256
+
257
+ return {
258
+ "docs": pool_docs,
259
+ "relevance": relevance,
260
+ "route_docs": unique_docs,
261
+ "branches": unique_branches,
262
+ "branch_quality": h,
263
+ "cosine": cosine,
264
+ "docs_by_branch": docs_by_branch,
265
+ }
266
+
267
+ @staticmethod
268
+ def _deviation(cosine, selected_branch_indices):
269
+ """Squared distance of each unit branch center from selected-center centroid."""
270
+ if not selected_branch_indices:
271
+ return np.zeros(len(cosine), np.float32)
272
+ si = np.asarray(selected_branch_indices, np.int32)
273
+ centroid_norm_sq = float(np.mean(cosine[np.ix_(si, si)]))
274
+ return 1.0 + centroid_norm_sq - 2.0 * np.mean(cosine[:, si], axis=1)
275
+
276
+ def rank(self, packet, k: int = 10):
277
+ """Construct top-k; branch diversity affects only the first ten ranks."""
278
+ if packet is None or not len(packet["docs"]):
279
+ return []
280
+ cfg = self.cfg
281
+ base = packet["relevance"]
282
+ n = len(base)
283
+ order = np.argsort(base)[::-1]
284
+ first = int(order[0])
285
+ chosen = [first]
286
+ used = {first}
287
+
288
+ # Only top query-specific branches are eligible to receive a diversity bonus.
289
+ h = packet["branch_quality"]
290
+ eligible = np.argsort(h)[::-1][: min(cfg.hq_top_branches, len(h))]
291
+ doc_hq = [[] for _ in range(n)]
292
+ branch_to_index = {int(b): i for i, b in enumerate(packet["branches"])}
293
+ for bi in eligible:
294
+ b = int(packet["branches"][bi])
295
+ for pi in packet["docs_by_branch"].get(b, []):
296
+ doc_hq[int(pi)].append(int(bi))
297
+
298
+ selected_branches = []
299
+ if doc_hq[first]:
300
+ selected_branches = [max(doc_hq[first], key=lambda bi: float(h[bi]))]
301
+
302
+ # Ranks 2..10: relevance plus soft central-deviation bonus.
303
+ for _ in range(1, min(10, k, n)):
304
+ rem = np.asarray([i for i in range(n) if i not in used], dtype=np.int32)
305
+ if not len(rem):
306
+ break
307
+ dev = self._deviation(packet["cosine"], selected_branches)
308
+ if len(eligible):
309
+ dev_values = _minmax_hi(dev[eligible])
310
+ dev_map = {int(bi): float(v) for bi, v in zip(eligible, dev_values)}
311
+ else:
312
+ dev_map = {}
313
+ rel = _minmax_hi(base[rem])
314
+ bonus = np.zeros(len(rem), np.float32)
315
+ for ii, pi in enumerate(rem):
316
+ if doc_hq[int(pi)]:
317
+ bonus[ii] = max(dev_map.get(bi, 0.0) for bi in doc_hq[int(pi)])
318
+ value = rel + cfg.lambda_diversity * bonus
319
+ pi = int(rem[int(np.argmax(value))])
320
+ chosen.append(pi)
321
+ used.add(pi)
322
+ if doc_hq[pi]:
323
+ bi = max(doc_hq[pi], key=lambda x: (dev_map.get(x, 0.0), float(h[x])))
324
+ selected_branches.append(int(bi))
325
+
326
+ # Beyond rank 10, ordinary relevance. This keeps the top-10 RAG mechanism isolated.
327
+ for pi in order:
328
+ pi = int(pi)
329
+ if len(chosen) >= min(k, n):
330
+ break
331
+ if pi not in used:
332
+ chosen.append(pi)
333
+ used.add(pi)
334
+ return packet["docs"][np.asarray(chosen[:k], dtype=np.int64)].tolist()
335
+
336
+ def search(self, text: str, k: int = 10, timing: bool = False):
337
+ t0 = time.perf_counter()
338
+ packet = self.prepare(text)
339
+ t1 = time.perf_counter()
340
+ local_ids = self.rank(packet, k=k)
341
+ t2 = time.perf_counter()
342
+ doc_ids = [str(self.idx.doc_ids[int(d)]) for d in local_ids]
343
+ if not timing:
344
+ return doc_ids
345
+ return doc_ids, {
346
+ "prepare_ms": (t1 - t0) * 1000.0,
347
+ "rank_ms": (t2 - t1) * 1000.0,
348
+ "total_ms": (t2 - t0) * 1000.0,
349
+ "route_size": 0 if packet is None else len(packet["route_docs"]),
350
+ "pool_size": 0 if packet is None else len(packet["docs"]),
351
+ }
352
+
353
+ def evaluate(self, dataset, k: int = 10):
354
+ run = {}
355
+ times = []
356
+ for qid in dataset.qrels:
357
+ docs, timing = self.search(dataset.queries[qid], k=k, timing=True)
358
+ run[str(qid)] = docs
359
+ times.append(timing)
360
+ metrics = evaluate_run(run, dataset.qrels, ks=(10,), ndcg_k=10, mrr_k=10, exp_gain=False)
361
+ metrics.update({
362
+ "median_total_ms": float(np.median([x["total_ms"] for x in times])),
363
+ "p95_total_ms": float(np.percentile([x["total_ms"] for x in times], 95)),
364
+ "median_rank_ms": float(np.median([x["rank_ms"] for x in times])),
365
+ "median_route_size": float(np.median([x["route_size"] for x in times])),
366
+ "median_pool_size": float(np.median([x["pool_size"] for x in times])),
367
+ })
368
+ return metrics, run
geomretrieval/utils.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import numpy as np
3
+ from scipy import sparse
4
+
5
+
6
+ def topk_sparse_row(indices: np.ndarray, values: np.ndarray, k: int) -> tuple[np.ndarray, np.ndarray]:
7
+ """Return up to k largest values from one CSR row, descending by value."""
8
+ if len(values) <= k:
9
+ order = np.argsort(values)[::-1]
10
+ else:
11
+ pick = np.argpartition(values, -k)[-k:]
12
+ order = pick[np.argsort(values[pick])[::-1]]
13
+ return indices[order], values[order]
14
+
15
+
16
+ def topk_abs_sparse_row(indices: np.ndarray, values: np.ndarray, k: int) -> tuple[np.ndarray, np.ndarray]:
17
+ """Return up to k largest absolute values from one sparse row."""
18
+ av = np.abs(values)
19
+ if len(values) <= k:
20
+ order = np.argsort(av)[::-1]
21
+ else:
22
+ pick = np.argpartition(av, -k)[-k:]
23
+ order = pick[np.argsort(av[pick])[::-1]]
24
+ return indices[order], values[order]
25
+
26
+
27
+ def csr_row_topk_matrix(X: sparse.csr_matrix, k: int, binary: bool = False) -> sparse.csr_matrix:
28
+ """Keep top-k entries in every CSR row.
29
+
30
+ Used only offline to construct the term-geometry estimation matrix.
31
+ """
32
+ rows, cols, vals = [], [], []
33
+ for r in range(X.shape[0]):
34
+ a, b = X.indptr[r], X.indptr[r + 1]
35
+ idx, dat = X.indices[a:b], X.data[a:b]
36
+ if len(idx) == 0:
37
+ continue
38
+ ii, vv = topk_sparse_row(idx, dat, k)
39
+ rows.extend([r] * len(ii))
40
+ cols.extend(ii.tolist())
41
+ vals.extend(([1.0] * len(ii)) if binary else vv.tolist())
42
+ return sparse.csr_matrix((np.asarray(vals, np.float32), (rows, cols)), shape=X.shape)
43
+
44
+
45
+ def zscore(x: np.ndarray, eps: float = 1e-8) -> np.ndarray:
46
+ x = np.asarray(x, dtype=np.float32)
47
+ s = float(x.std())
48
+ if s < eps:
49
+ return np.zeros_like(x)
50
+ return (x - float(x.mean())) / (s + eps)
51
+
52
+
53
+ def padded_topk_dense_from_csr_row(row: sparse.csr_matrix, k: int, width: int | None = None):
54
+ """Top-k of a single CSR row, returned padded and term-id sorted.
55
+
56
+ Sorting term IDs rather than scores is useful for fast center lookup later.
57
+ """
58
+ width = width or k
59
+ idx, dat = row.indices, row.data
60
+ if len(dat):
61
+ ii, vv = topk_sparse_row(idx, dat, k)
62
+ order = np.argsort(ii)
63
+ ii, vv = ii[order], vv[order]
64
+ else:
65
+ ii = np.empty(0, dtype=np.int32)
66
+ vv = np.empty(0, dtype=np.float32)
67
+ out_i = np.full(width, -1, dtype=np.int32)
68
+ out_v = np.zeros(width, dtype=np.float32)
69
+ n = min(width, len(ii))
70
+ out_i[:n] = ii[:n]
71
+ out_v[:n] = vv[:n]
72
+ return out_i, out_v
73
+
74
+
75
+ def lookup_sorted(keys: np.ndarray, vals: np.ndarray, query_keys: np.ndarray) -> np.ndarray:
76
+ """Lookup query keys in sorted padded key/value arrays; absent -> 0."""
77
+ valid = keys >= 0
78
+ k = keys[valid]
79
+ v = vals[valid]
80
+ if len(k) == 0 or len(query_keys) == 0:
81
+ return np.zeros(len(query_keys), dtype=np.float32)
82
+ pos = np.searchsorted(k, query_keys)
83
+ out = np.zeros(len(query_keys), dtype=np.float32)
84
+ ok = pos < len(k)
85
+ ok_idx = np.flatnonzero(ok)
86
+ if len(ok_idx):
87
+ p = pos[ok_idx]
88
+ same = k[p] == query_keys[ok_idx]
89
+ chosen = ok_idx[same]
90
+ out[chosen] = v[pos[chosen]]
91
+ return out