Upload 103 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- docs/BASELINE_SUITE.md +30 -0
- docs/LITERATURE_AND_SPEED.md +41 -0
- docs/METHOD.md +37 -0
- docs/RAG_PROTOCOL.md +34 -0
- docs/REPRODUCIBILITY.md +46 -0
- docs/images/scifact_pool_sweep.png +3 -0
- docs/images/treccovid_pool_sweep.png +3 -0
- docs/images/treccovid_speed_pool.png +3 -0
- experiments/beir/run_pool_sweep.py +22 -0
- experiments/beir/run_rag_top10.py +32 -0
- experiments/beir/scifact_pool_sweep_exact_history.py +265 -0
- experiments/beir/treccovid_collision_diag_exact_history.py +188 -0
- experiments/beir/treccovid_hq_branch_exact_history.py +268 -0
- experiments/beir/treccovid_idf_power_exact_history.py +261 -0
- experiments/beir/treccovid_local_baselines_exact_history.py +40 -0
- experiments/beir/treccovid_pool_sweep_exact_history.py +265 -0
- experiments/msmarco_scale/bench_fast.py +7 -0
- experiments/msmarco_scale/bench_post.py +11 -0
- experiments/msmarco_scale/build_branch_sorted_layout.py +13 -0
- experiments/msmarco_scale/build_global_support.py +18 -0
- experiments/msmarco_scale/compare_fast_post.py +14 -0
- experiments/msmarco_scale/msmarco_allroute_diag.py +20 -0
- experiments/msmarco_scale/msmarco_amplitude_diag_stage1.py +58 -0
- experiments/msmarco_scale/msmarco_amplitude_diag_stage2.py +68 -0
- experiments/msmarco_scale/msmarco_amplitude_diag_stage3.py +144 -0
- experiments/msmarco_scale/msmarco_best_all_dev.py +30 -0
- experiments/msmarco_scale/msmarco_best_tail_core.py +58 -0
- experiments/msmarco_scale/msmarco_best_tail_dev.py +24 -0
- experiments/msmarco_scale/msmarco_best_tail_eval.py +77 -0
- experiments/msmarco_scale/msmarco_branch_coherence_multifold.py +133 -0
- experiments/msmarco_scale/msmarco_branch_features.py +50 -0
- experiments/msmarco_scale/msmarco_branch_fusion_sweep.py +34 -0
- experiments/msmarco_scale/msmarco_build_geometry.py +214 -0
- experiments/msmarco_scale/msmarco_build_geometry_uniform1m.py +133 -0
- experiments/msmarco_scale/msmarco_build_s32_reliability.py +36 -0
- experiments/msmarco_scale/msmarco_coordination_features.py +30 -0
- experiments/msmarco_scale/msmarco_coordination_sweep.py +63 -0
- experiments/msmarco_scale/msmarco_covbonus_sweep.py +25 -0
- experiments/msmarco_scale/msmarco_dev_fast.py +27 -0
- experiments/msmarco_scale/msmarco_early_lex_dev.py +82 -0
- experiments/msmarco_scale/msmarco_early_lex_direct.py +69 -0
- experiments/msmarco_scale/msmarco_early_lex_quota.py +88 -0
- experiments/msmarco_scale/msmarco_early_lex_validation.py +113 -0
- experiments/msmarco_scale/msmarco_early_lex_validation_fast.py +90 -0
- experiments/msmarco_scale/msmarco_encode_full.py +111 -0
- experiments/msmarco_scale/msmarco_encode_resume.py +58 -0
- experiments/msmarco_scale/msmarco_encode_s32.py +78 -0
- experiments/msmarco_scale/msmarco_encode_s32_1w.py +78 -0
- experiments/msmarco_scale/msmarco_encode_s32_1w5t.py +78 -0
- experiments/msmarco_scale/msmarco_encode_s32_2w.py +78 -0
docs/BASELINE_SUITE.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Full baseline suite and provenance policy
|
| 2 |
+
|
| 3 |
+
Every benchmark table in this project keeps the complete comparison suite visible, even when a particular baseline has not yet been rerun on the current dataset.
|
| 4 |
+
|
| 5 |
+
| Baseline | Representation / search | Speed quantity that must be reported |
|
| 6 |
+
|---|---|---|
|
| 7 |
+
| TF-IDF | sparse lexical, exact scan or inverted index | end-to-end query + search |
|
| 8 |
+
| BM25 | sparse lexical inverted index | end-to-end query + postings traversal |
|
| 9 |
+
| FAISS Flat | fixed dense embeddings, exact inner product/cosine | query encoder + exact vector search |
|
| 10 |
+
| FAISS HNSW | fixed dense embeddings, HNSW | query encoder + ANN search |
|
| 11 |
+
| FAISS IVF-Flat | fixed dense embeddings, IVF | query encoder + ANN search |
|
| 12 |
+
| FAISS IVF-PQ | fixed dense embeddings, IVF + product quantization | query encoder + ANN search |
|
| 13 |
+
| hnswlib HNSW | fixed dense embeddings, HNSW | query encoder + ANN search |
|
| 14 |
+
| ScaNN | fixed dense embeddings, pruning/quantization | query encoder + ANN search |
|
| 15 |
+
| Contriever | neural dense retrieval + ANN | query encoder + ANN search |
|
| 16 |
+
| SPLADE++ | neural sparse expansion + inverted index | sparse query encoder + search |
|
| 17 |
+
| BGE-base | neural dense retrieval + ANN | query encoder + ANN search |
|
| 18 |
+
| Modern ColBERT | neural multi-vector late interaction | query encoder + candidate generation + late interaction |
|
| 19 |
+
| OURS | sparse TF-IDF geometry + signed residuals | TF-IDF query construction + routing + shortlist + top-10 selection |
|
| 20 |
+
|
| 21 |
+
## Missing values are shown, not hidden
|
| 22 |
+
|
| 23 |
+
A dash in a result table means the baseline has not yet been rerun under the same representation/hardware/protocol. It is intentionally left visible. We do not fill missing latency with a number from a different CPU/GPU and we do not compare ANN-only latency against our end-to-end latency.
|
| 24 |
+
|
| 25 |
+
## Current provenance classes
|
| 26 |
+
|
| 27 |
+
- **local**: executed on the current dataset by the code in this repository/session;
|
| 28 |
+
- **historical local**: executed in an earlier frozen version of the same project;
|
| 29 |
+
- **published/context ledger**: retained from the baseline ledger used during the experimental campaign; not presented as a same-hardware speed result;
|
| 30 |
+
- **pending same-representation rerun**: part of the required suite but deliberately blank until a controlled experiment exists.
|
docs/LITERATURE_AND_SPEED.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Retrieval literature through the speed lens
|
| 2 |
+
|
| 3 |
+
Speed is not a secondary metric in this project. A retriever that produces an excellent rank at a cost incompatible with interactive RAG has solved a different problem.
|
| 4 |
+
|
| 5 |
+
## The computational boundary we measure
|
| 6 |
+
|
| 7 |
+
A RAG request pays for **query representation + retrieval + shortlist scoring + top-10 selection**. For ANN baselines, the literature often reports ANN search after the dense query embedding has already been computed. We therefore keep two latency columns whenever possible:
|
| 8 |
+
|
| 9 |
+
1. **ANN/search-only latency** — useful for comparing indexes.
|
| 10 |
+
2. **End-to-end query latency** — the number relevant to an actual RAG request.
|
| 11 |
+
|
| 12 |
+
The two must never be silently mixed.
|
| 13 |
+
|
| 14 |
+
| Family | Query-time representation | Search object | Speed implication |
|
| 15 |
+
|---|---|---|---|
|
| 16 |
+
| BM25 | tokenization only | inverted postings | no neural query inference; strong classical latency reference |
|
| 17 |
+
| FAISS Flat / IVF / PQ | dense query embedding | dense vectors / quantized vectors | optimized vector search; encoder cost is normally outside ANN timing |
|
| 18 |
+
| HNSW | dense query embedding | graph over dense vectors | very fast ANN search, but memory-heavy graph and query encoder remain |
|
| 19 |
+
| ScaNN | dense query embedding | partitioned/quantized dense vectors | search is optimized around MIPS/quantization; encoder cost is separate |
|
| 20 |
+
| Contriever / BGE | neural dense encoder | ANN dense index | representation quality is strong, but query inference is part of deployed RAG cost |
|
| 21 |
+
| SPLADE | neural sparse encoder | sparse inverted index | sparse search, but query sparse vector is produced by a transformer |
|
| 22 |
+
| ColBERTv2 | neural token encoder | compressed multi-vector index + late interaction | excellent quality, but multiple query vectors and late interaction increase work |
|
| 23 |
+
| **Sparse Geometric RAG (this repo)** | **TF-IDF query vector; no neural inference** | **fuzzy sparse branches + 16-coordinate signed residuals** | **query formation is cheap; routing and local scoring touch tiny sparse structures; only a small shortlist reaches chunk-level scoring** |
|
| 24 |
+
|
| 25 |
+
## Primary references
|
| 26 |
+
|
| 27 |
+
- Johnson, Douze, Jégou, *Billion-scale similarity search with GPUs* (FAISS): https://arxiv.org/abs/1702.08734
|
| 28 |
+
- Douze et al., *The Faiss Library*: https://arxiv.org/abs/2401.08281
|
| 29 |
+
- Malkov and Yashunin, *Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs*: https://arxiv.org/abs/1603.09320
|
| 30 |
+
- Guo et al., *Accelerating Large-Scale Inference with Anisotropic Vector Quantization* (ScaNN): https://arxiv.org/abs/1908.10396
|
| 31 |
+
- Izacard et al., *Unsupervised Dense Information Retrieval with Contrastive Learning* (Contriever): https://arxiv.org/abs/2112.09118
|
| 32 |
+
- Formal et al., *SPLADE v2*: https://arxiv.org/abs/2109.10086
|
| 33 |
+
- Santhanam et al., *ColBERTv2: Effective and Efficient Retrieval via Lightweight Late Interaction*: https://arxiv.org/abs/2112.01488
|
| 34 |
+
- Xiao et al., *C-Pack: Packaged Resources To Advance General Chinese Embedding* (BGE family): https://arxiv.org/abs/2309.07597
|
| 35 |
+
- Thakur et al., *BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models*: https://arxiv.org/abs/2104.08663
|
| 36 |
+
|
| 37 |
+
## Why this method is different computationally
|
| 38 |
+
|
| 39 |
+
FAISS, HNSW, and ScaNN solve the problem “search a database of dense vectors quickly.” This project asks a prior question: **does the retrieval database need a dense vector per chunk at all?** The stored object is instead a coarse fuzzy location plus a very small signed departure from its local center. Query-time work follows that sparse geometry.
|
| 40 |
+
|
| 41 |
+
The intended speed story is therefore not “we wrote a faster HNSW.” It is: **avoid most of the arithmetic and memory traffic that make ANN necessary in the first place.**
|
docs/METHOD.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Method
|
| 2 |
+
|
| 3 |
+
## Offline representation
|
| 4 |
+
|
| 5 |
+
For each chunk, construct a sparse normalized TF-IDF vector. Keep its top `F=4` coordinates as fuzzy branch memberships. For branch `j`, keep a sparse `B=64` membership-weighted center. For every chunk-branch membership, retain only `S=16` residual coordinates chosen from terms actually present in the chunk and store their **signs**, not document-specific residual amplitudes.
|
| 6 |
+
|
| 7 |
+
A zero-inclusive branch-local sign variance is shrunk toward the global term variance and converted to a mild inverse reliability weight, approximately `variance^-0.2`. The corpus also produces a sparse PPMI association graph and a second-order context graph for query routing.
|
| 8 |
+
|
| 9 |
+
## Query routing and local scoring
|
| 10 |
+
|
| 11 |
+
The query retains real TF-IDF amplitudes. Weak second-order expansion exposes nearby branches. A branch-local signed score evaluates only the 16 stored residual coordinates and is weighted by fuzzy membership, route strength, query-mass significance, and inverse local sign variance.
|
| 12 |
+
|
| 13 |
+
## Early rescue and chunk shortlist
|
| 14 |
+
|
| 15 |
+
The routed representations are cheaply ordered using geometric evidence plus whole-chunk **binary IDF^1** support. The best `P` representations are mapped to their corresponding chunks. No dense 384/768-dimensional embedding is required at this stage.
|
| 16 |
+
|
| 17 |
+
## Final chunk score
|
| 18 |
+
|
| 19 |
+
For each shortlisted chunk, the final lexical statistic is binary presence weighted by **IDF squared**:
|
| 20 |
+
|
| 21 |
+
```text
|
| 22 |
+
sum_{t in query ∩ chunk} IDF(t)^2
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
It is combined with a weak length correction, query coordination, sparse semantic presence, and coverage of the three rarest query terms. The validated score components retain their per-query z-normalization.
|
| 26 |
+
|
| 27 |
+
## High-quality branches and soft diversity
|
| 28 |
+
|
| 29 |
+
Branch quality is query-specific. For branch `j`, define branch-specific evidence `E_dj` using the geometric membership contribution. The quality score is the mean of the top three evidences in that branch:
|
| 30 |
+
|
| 31 |
+
```text
|
| 32 |
+
H_j = mean(top3_d E_dj)
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Only the ten branches with largest `H_j` are eligible for a diversity bonus. Rank 1 is pure relevance. For ranks 2–10, a candidate can receive a small bonus if one of its high-quality supporting branch centers deviates from the centroid of branches already represented. Repeated branches are allowed.
|
| 36 |
+
|
| 37 |
+
This is **not blind diversification** and it is **not one-document-per-branch**.
|
docs/RAG_PROTOCOL.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Practical RAG evaluation protocol: measure the first ten chunks
|
| 2 |
+
|
| 3 |
+
## Why K=10 is the deployment target
|
| 4 |
+
|
| 5 |
+
A RAG system does not consume an abstract recall curve. It consumes a small context set. Chunks ranked at 100, 500, or 1000 are normally never passed to the generator. Optimizing deep recall can therefore reward a retriever for spending CPU, memory bandwidth, and storage on results that have zero downstream utility.
|
| 6 |
+
|
| 7 |
+
For this repository, the primary protocol is deliberately strict:
|
| 8 |
+
|
| 9 |
+
- retrieve a ranked **top 10**;
|
| 10 |
+
- report **nDCG@10, MRR@10, Precision@10, Recall@10, Hit@10**;
|
| 11 |
+
- measure **CPU median latency, p95 latency, and QPS**;
|
| 12 |
+
- report the number of routed candidates and the chunk shortlist size `P`;
|
| 13 |
+
- use deep-recall metrics only as diagnostics, never as the main optimization objective.
|
| 14 |
+
|
| 15 |
+
This is the only protocol in the repository used to decide whether a change helps practical RAG.
|
| 16 |
+
|
| 17 |
+
## Why shortlist size P is a RAG parameter
|
| 18 |
+
|
| 19 |
+
The historical system used `P=2000` because it was selected for Recall@100. Once the objective became top-10 RAG quality, the relevant question changed to:
|
| 20 |
+
|
| 21 |
+
> How many retrieved geometric representations should be exposed to chunk-level scoring before choosing ten chunks?
|
| 22 |
+
|
| 23 |
+
The current sweep is therefore `P in {25, 50, 100, 200, 500}` plus the historical `P=2000` reference. TREC-COVID has a large route and peaks sharply at `P=100`; SciFact has a tiny route (~157 candidates/query) and improves as the artificial pruning is removed. The lesson is not that 100 is universal. The lesson is that **the shortlist must be evaluated for the top-10 deployment objective rather than inherited from a deep-recall benchmark.**
|
| 24 |
+
|
| 25 |
+
## Timing discipline
|
| 26 |
+
|
| 27 |
+
Speed is a first-class result.
|
| 28 |
+
|
| 29 |
+
1. CPU is the principal deployment regime.
|
| 30 |
+
2. Warm the index before timing.
|
| 31 |
+
3. Record median and p95, not only an average.
|
| 32 |
+
4. Report query representation time separately when a baseline uses a neural encoder.
|
| 33 |
+
5. Never compare our end-to-end latency with an ANN-only latency that silently excludes dense query encoding.
|
| 34 |
+
6. Mark diagnostic Python implementations as diagnostic; do not present them as optimized production latency.
|
docs/REPRODUCIBILITY.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reproducibility
|
| 2 |
+
|
| 3 |
+
## Environment
|
| 4 |
+
|
| 5 |
+
```bash
|
| 6 |
+
python -m venv .venv
|
| 7 |
+
source .venv/bin/activate
|
| 8 |
+
pip install -U pip
|
| 9 |
+
pip install -e .
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
Optional ANN/neural baselines:
|
| 13 |
+
|
| 14 |
+
```bash
|
| 15 |
+
pip install -r requirements-baselines.txt
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
## SciFact
|
| 19 |
+
|
| 20 |
+
Place a standard BEIR archive at `data/scifact.zip` and run:
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
./scripts/reproduce_scifact.sh data/scifact.zip artifacts/scifact_index
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
## TREC-COVID
|
| 27 |
+
|
| 28 |
+
Place a standard BEIR archive at `data/trec-covid.zip` and run:
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
./scripts/reproduce_treccovid.sh data/trec-covid.zip artifacts/treccovid_index
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
## One configuration
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
python experiments/beir/run_rag_top10.py data/trec-covid.zip artifacts/treccovid_index --pool 100 --hq-branches 10 --lambda-diversity 0.1 --output results/reproduced/treccovid_p100.json
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
## Full MS MARCO
|
| 41 |
+
|
| 42 |
+
The exact historical full-scale scripts are preserved under `experiments/msmarco_scale/`. They are intentionally kept close to the scripts that produced the recorded JSON files. The 8.84M corpus shards and multi-GB generated arrays are not in this repository. Use `manifests/msmarco_manifest.json` to verify the shard set, then follow the build order described in the root README.
|
| 43 |
+
|
| 44 |
+
## Exact experiment history vs cleaned runner
|
| 45 |
+
|
| 46 |
+
`experiments/beir/*exact_history.py` contains the scripts as executed in the current session, including their original local paths. `experiments/beir/run_rag_top10.py` and `run_pool_sweep.py` are cleaned path-independent runners using the same formulas.
|
docs/images/scifact_pool_sweep.png
ADDED
|
Git LFS Details
|
docs/images/treccovid_pool_sweep.png
ADDED
|
Git LFS Details
|
docs/images/treccovid_speed_pool.png
ADDED
|
Git LFS Details
|
experiments/beir/run_pool_sweep.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import argparse,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from geomretrieval import GeometricIndex,RAGTop10Config,RAGTop10Ranker,load_beir_zip,load_beir_directory
|
| 5 |
+
|
| 6 |
+
def load_dataset(path,split):
|
| 7 |
+
return load_beir_zip(path,split) if str(path).lower().endswith('.zip') else load_beir_directory(path,split)
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
p=argparse.ArgumentParser(description='Top-10 RAG shortlist sweep. Deep-recall metrics are intentionally not used for model selection.')
|
| 11 |
+
p.add_argument('dataset'); p.add_argument('index'); p.add_argument('--split',default='test')
|
| 12 |
+
p.add_argument('--pools',type=int,nargs='+',default=[25,50,100,200,500])
|
| 13 |
+
p.add_argument('--output',default='pool_sweep.json')
|
| 14 |
+
a=p.parse_args(); ds=load_dataset(a.dataset,a.split); idx=GeometricIndex.load(a.index)
|
| 15 |
+
out={'dataset':ds.name,'split':a.split,'protocol':'top-10 RAG only','pools':{}}
|
| 16 |
+
for P in a.pools:
|
| 17 |
+
ranker=RAGTop10Ranker(idx,RAGTop10Config(pool_size=P))
|
| 18 |
+
metrics,_=ranker.evaluate(ds,k=10)
|
| 19 |
+
out['pools'][str(P)]=metrics
|
| 20 |
+
print('P=',P,json.dumps(metrics,sort_keys=True))
|
| 21 |
+
Path(a.output).write_text(json.dumps(out,indent=2))
|
| 22 |
+
if __name__=='__main__':main()
|
experiments/beir/run_rag_top10.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import argparse, json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from geomretrieval import GeometricIndex, RAGTop10Config, RAGTop10Ranker, load_beir_zip, load_beir_directory
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def load_dataset(path, split):
|
| 9 |
+
return load_beir_zip(path, split) if str(path).lower().endswith('.zip') else load_beir_directory(path, split)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
p=argparse.ArgumentParser(description='Evaluate the current top-10 RAG protocol on a BEIR dataset.')
|
| 14 |
+
p.add_argument('dataset', help='BEIR zip or extracted dataset directory')
|
| 15 |
+
p.add_argument('index', help='saved GeometricIndex directory')
|
| 16 |
+
p.add_argument('--split', default='test')
|
| 17 |
+
p.add_argument('--pool', type=int, default=100)
|
| 18 |
+
p.add_argument('--hq-branches', type=int, default=10)
|
| 19 |
+
p.add_argument('--lambda-diversity', type=float, default=0.1)
|
| 20 |
+
p.add_argument('--output', default=None)
|
| 21 |
+
a=p.parse_args()
|
| 22 |
+
ds=load_dataset(a.dataset,a.split)
|
| 23 |
+
idx=GeometricIndex.load(a.index)
|
| 24 |
+
cfg=RAGTop10Config(pool_size=a.pool,hq_top_branches=a.hq_branches,lambda_diversity=a.lambda_diversity)
|
| 25 |
+
ranker=RAGTop10Ranker(idx,cfg)
|
| 26 |
+
metrics,run=ranker.evaluate(ds,k=10)
|
| 27 |
+
result={'dataset':ds.name,'split':a.split,'config':cfg.__dict__,'metrics':metrics}
|
| 28 |
+
print(json.dumps(result,indent=2))
|
| 29 |
+
if a.output:
|
| 30 |
+
Path(a.output).write_text(json.dumps({'summary':result,'run':run},indent=2))
|
| 31 |
+
|
| 32 |
+
if __name__=='__main__': main()
|
experiments/beir/scifact_pool_sweep_exact_history.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json,math,os
|
| 3 |
+
import numpy as np
|
| 4 |
+
sys.path.insert(0,'/mnt/data/work_code/geomretrieval_msmarco_scale_codebase/original_v0')
|
| 5 |
+
from geomretrieval import GeometricIndex, load_beir_directory, evaluate_run
|
| 6 |
+
|
| 7 |
+
IDX='/mnt/data/scifact_geom_index'
|
| 8 |
+
ROOT='/mnt/data/work_scifact/scifact'
|
| 9 |
+
idx=GeometricIndex.load(IDX); M=idx.vocab_size
|
| 10 |
+
P=int(os.environ.get("POOL_P","100")); GAMMA=.25; LAM_M=.125; PRE_B=.2; FINAL_B=.1; ALPHA=.25
|
| 11 |
+
WLEX=4.0; WSEM=.3; WRARE=1.0; SEMK=16; EPS=1e-8
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def zscore(x):
|
| 15 |
+
x=np.asarray(x,np.float32)
|
| 16 |
+
if not len(x): return x
|
| 17 |
+
sd=float(x.std())
|
| 18 |
+
return np.zeros_like(x) if sd<1e-8 else (x-float(x.mean()))/sd
|
| 19 |
+
|
| 20 |
+
def minmax_hi(x):
|
| 21 |
+
x=np.asarray(x,np.float32)
|
| 22 |
+
if not len(x): return x
|
| 23 |
+
mn=float(x.min()); mx=float(x.max()); den=mx-mn
|
| 24 |
+
return np.ones_like(x) if den<1e-8 else (x-mn)/den
|
| 25 |
+
|
| 26 |
+
def topk_large(score,k):
|
| 27 |
+
n=len(score); k=min(k,n)
|
| 28 |
+
if k<=0:return np.empty(0,np.int64)
|
| 29 |
+
if n<=k:return np.argsort(score)[::-1]
|
| 30 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 31 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 32 |
+
|
| 33 |
+
def center_sparse(j):
|
| 34 |
+
t=idx.center_terms[j]; v=idx.center_values[j]; ok=t>=0
|
| 35 |
+
t=t[ok].astype(np.int32); v=v[ok].astype(np.float32)
|
| 36 |
+
n=float(np.linalg.norm(v))
|
| 37 |
+
if n>0:v=v/n
|
| 38 |
+
oo=np.argsort(t)
|
| 39 |
+
return t[oo],v[oo]
|
| 40 |
+
|
| 41 |
+
def spdot(a_t,a_v,b_t,b_v):
|
| 42 |
+
i=j=0;s=0.0
|
| 43 |
+
while i<len(a_t) and j<len(b_t):
|
| 44 |
+
if a_t[i]==b_t[j]:s+=float(a_v[i])*float(b_v[j]);i+=1;j+=1
|
| 45 |
+
elif a_t[i]<b_t[j]:i+=1
|
| 46 |
+
else:j+=1
|
| 47 |
+
return s
|
| 48 |
+
|
| 49 |
+
def prepare(text):
|
| 50 |
+
q=idx._query_vector(text)
|
| 51 |
+
if q.nnz==0:return None
|
| 52 |
+
qd=np.zeros(M,np.float32); qd[q.indices]=q.data
|
| 53 |
+
rt,rv,qt=idx._expanded_route(q)
|
| 54 |
+
if not len(rt):return None
|
| 55 |
+
rd=np.zeros(M,np.float32);rd[rt]=rv
|
| 56 |
+
pieces=[]
|
| 57 |
+
for j in rt:
|
| 58 |
+
a,b=idx.branch_offsets[j],idx.branch_offsets[j+1]
|
| 59 |
+
if b>a:pieces.append(idx.branch_order[a:b])
|
| 60 |
+
if not pieces:return None
|
| 61 |
+
fp=np.concatenate(pieces).astype(np.int64,copy=False)
|
| 62 |
+
docs=(fp//idx.config.F).astype(np.int64); slots=(fp%idx.config.F).astype(np.int64)
|
| 63 |
+
br=idx.branches[docs,slots]
|
| 64 |
+
terms=idx.res_terms[docs,slots];valid=terms>=0;safe=np.where(valid,terms,0);qv=qd[safe]
|
| 65 |
+
local=np.sum(idx.res_reliability[docs,slots].astype(np.float32)*(qv-idx.res_center_values[docs,slots])*idx.res_signs[docs,slots].astype(np.float32)*valid,axis=1)
|
| 66 |
+
sig=np.sum((qv*qv)*valid,axis=1)
|
| 67 |
+
cons=idx.memberships[docs,slots]*rd[br]
|
| 68 |
+
branch_ev=(cons*local*np.power(np.maximum(sig,0),GAMMA)).astype(np.float32) # E_dj exactly
|
| 69 |
+
base=cons*local
|
| 70 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 71 |
+
tail=np.bincount(inv,weights=branch_ev,minlength=len(ud)).astype(np.float32)
|
| 72 |
+
tail += LAM_M*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 73 |
+
# dominant routed branch retained for diagnostics
|
| 74 |
+
bestv=np.full(len(ud),-1e30,np.float32);db=np.full(len(ud),-1,np.int32)
|
| 75 |
+
for p,u in enumerate(inv):
|
| 76 |
+
if cons[p]>bestv[u]:bestv[u]=cons[p];db[u]=int(br[p])
|
| 77 |
+
# frozen early lexical rescue
|
| 78 |
+
qlex=np.zeros(M,np.float32);qlex[q.indices]=idx.idf[q.indices]
|
| 79 |
+
lex1=np.zeros(len(ud),np.float32)
|
| 80 |
+
for i,d in enumerate(ud):
|
| 81 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1];sup=idx.support_indices[a:b]
|
| 82 |
+
raw=float(qlex[sup].sum());den=(1-PRE_B)+PRE_B*(float(idx.doc_lengths[d])/idx.avg_doc_length)
|
| 83 |
+
lex1[i]=raw/(den if den>0 else 1.)
|
| 84 |
+
pre=zscore(tail)+zscore(lex1)
|
| 85 |
+
sel=topk_large(pre,P)
|
| 86 |
+
dd=ud[sel];ts=tail[sel];db=db[sel]
|
| 87 |
+
# mapping routed-doc local index -> pool local index
|
| 88 |
+
poolpos=np.full(len(ud),-1,np.int32); poolpos[sel]=np.arange(len(sel),dtype=np.int32)
|
| 89 |
+
mp=poolpos[inv]
|
| 90 |
+
keep=mp>=0
|
| 91 |
+
mem_pool=mp[keep].astype(np.int32)
|
| 92 |
+
mem_br=br[keep].astype(np.int32)
|
| 93 |
+
mem_ev=branch_ev[keep].astype(np.float32)
|
| 94 |
+
# final current features
|
| 95 |
+
semvec=np.zeros(M,np.float32)
|
| 96 |
+
for t,amp in zip(q.indices,q.data):
|
| 97 |
+
a,b=idx.A.indptr[t],idx.A.indptr[t+1];nb=idx.A.indices[a:b][:SEMK];sv=idx.A.data[a:b][:SEMK]
|
| 98 |
+
if len(nb):semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 99 |
+
qset=set(map(int,q.indices));rare=set(map(int,q.indices[np.argsort(idx.idf[q.indices])[::-1]][:3]));nq=max(1,len(q.indices))
|
| 100 |
+
lx=np.zeros(len(dd),np.float32);sm=np.zeros(len(dd),np.float32);qc=np.zeros(len(dd),np.float32);r3=np.zeros(len(dd),np.float32)
|
| 101 |
+
for i,d in enumerate(dd):
|
| 102 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1];sup=idx.support_indices[a:b]
|
| 103 |
+
sm[i]=float(semvec[sup].sum())
|
| 104 |
+
match=[int(t) for t in sup if int(t) in qset]
|
| 105 |
+
raw=sum(float(idx.idf[t])**2 for t in match);den=(1-FINAL_B)+FINAL_B*(float(idx.doc_lengths[d])/idx.avg_doc_length)
|
| 106 |
+
lx[i]=raw/(den if den>0 else 1.);qc[i]=len(match);r3[i]=sum(t in rare for t in match)
|
| 107 |
+
cov=qc/nq;ladj=lx*np.power(np.maximum(cov,1e-6),ALPHA);rarecov=r3/max(1,min(3,nq))
|
| 108 |
+
base_score=zscore(ts)+WLEX*zscore(ladj)+WSEM*zscore(sm)+WRARE*zscore(rarecov)
|
| 109 |
+
|
| 110 |
+
# Build H_j = mean of top 3 E_dj among selected pool documents for branch j.
|
| 111 |
+
# Multiple memberships of same doc+branch should not occur; if they do, keep max.
|
| 112 |
+
branch_pairs={}
|
| 113 |
+
for pi,b,e in zip(mem_pool,mem_br,mem_ev):
|
| 114 |
+
key=(int(b),int(pi))
|
| 115 |
+
if key not in branch_pairs or e>branch_pairs[key]: branch_pairs[key]=float(e)
|
| 116 |
+
byb={}
|
| 117 |
+
for (b,pi),e in branch_pairs.items(): byb.setdefault(b,[]).append((e,pi))
|
| 118 |
+
H={}; bestdoc={}; docs_by_branch={}
|
| 119 |
+
for b,vals in byb.items():
|
| 120 |
+
vals.sort(key=lambda x:x[0],reverse=True)
|
| 121 |
+
top=vals[:3]
|
| 122 |
+
H[b]=float(np.mean([e for e,_ in top]))
|
| 123 |
+
bestdoc[b]=int(max(vals,key=lambda x: float(base_score[x[1]]))[1]) # best final-relevance doc in branch
|
| 124 |
+
docs_by_branch[b]=np.asarray([pi for _,pi in vals],dtype=np.int32)
|
| 125 |
+
ub=np.asarray(sorted(H.keys()),dtype=np.int32)
|
| 126 |
+
h=np.asarray([H[int(b)] for b in ub],dtype=np.float32)
|
| 127 |
+
hnorm=minmax_hi(h)
|
| 128 |
+
bmap={int(b):i for i,b in enumerate(ub)}
|
| 129 |
+
reps=[center_sparse(int(b)) for b in ub]
|
| 130 |
+
C=np.eye(len(ub),dtype=np.float32)
|
| 131 |
+
for i in range(len(ub)):
|
| 132 |
+
for j in range(i+1,len(ub)):
|
| 133 |
+
C[i,j]=C[j,i]=spdot(*reps[i],*reps[j])
|
| 134 |
+
return {'docs':dd,'base':base_score,'tail':ts,'lex':ladj,'sem':sm,'rare':rarecov,
|
| 135 |
+
'route_docs':ud,'branches_dom':db,'ub':ub,'H':h,'Hn':hnorm,'bmap':bmap,'cos':C,
|
| 136 |
+
'bestdoc':bestdoc,'docs_by_branch':docs_by_branch}
|
| 137 |
+
|
| 138 |
+
def plain(p,k=100):
|
| 139 |
+
oo=np.argsort(p['base'])[::-1][:k]
|
| 140 |
+
return p['docs'][oo].tolist()
|
| 141 |
+
|
| 142 |
+
def Dvec(p, selected_bidx):
|
| 143 |
+
C=p['cos']
|
| 144 |
+
if not selected_bidx:return np.zeros(len(C),np.float32)
|
| 145 |
+
si=np.asarray(selected_bidx,np.int32)
|
| 146 |
+
mumun=float(np.mean(C[np.ix_(si,si)]))
|
| 147 |
+
return 1.0+mumun-2.0*np.mean(C[:,si],axis=1)
|
| 148 |
+
|
| 149 |
+
def select_hq_branches(p, topN=20, lam=1.0, nsel=10, pure_div=False):
|
| 150 |
+
if len(p['ub'])==0:return []
|
| 151 |
+
# eligible branches are the top-N robust-quality H_j branches
|
| 152 |
+
order=np.argsort(p['H'])[::-1]
|
| 153 |
+
elig=order[:min(topN,len(order))]
|
| 154 |
+
# first branch = highest H_j
|
| 155 |
+
selected=[int(elig[0])]
|
| 156 |
+
remaining=set(map(int,elig[1:]))
|
| 157 |
+
while remaining and len(selected)<min(nsel,len(elig)):
|
| 158 |
+
rem=np.asarray(sorted(remaining),dtype=np.int32)
|
| 159 |
+
D=Dvec(p,selected)
|
| 160 |
+
dnorm=minmax_hi(D[rem])
|
| 161 |
+
if pure_div:
|
| 162 |
+
val=dnorm
|
| 163 |
+
else:
|
| 164 |
+
h=p['Hn'][rem]
|
| 165 |
+
val=h+float(lam)*dnorm
|
| 166 |
+
pick=int(rem[int(np.argmax(val))])
|
| 167 |
+
selected.append(pick); remaining.remove(pick)
|
| 168 |
+
return selected
|
| 169 |
+
|
| 170 |
+
def rank_hq_oneper(p,topN=20,lam=1.0,pure_div=False,k=100):
|
| 171 |
+
# one best final-score document from each selected high-quality/diverse branch for top 10
|
| 172 |
+
sb=select_hq_branches(p,topN,lam,10,pure_div)
|
| 173 |
+
chosen=[]; used=set()
|
| 174 |
+
for bi in sb:
|
| 175 |
+
b=int(p['ub'][bi]); pi=int(p['bestdoc'][b])
|
| 176 |
+
if pi not in used: chosen.append(pi); used.add(pi)
|
| 177 |
+
# if fewer than 10, fill by ordinary score
|
| 178 |
+
for pi in np.argsort(p['base'])[::-1]:
|
| 179 |
+
pi=int(pi)
|
| 180 |
+
if len(chosen)>=10:break
|
| 181 |
+
if pi not in used: chosen.append(pi);used.add(pi)
|
| 182 |
+
# rest by ordinary score
|
| 183 |
+
for pi in np.argsort(p['base'])[::-1]:
|
| 184 |
+
pi=int(pi)
|
| 185 |
+
if len(chosen)>=k:break
|
| 186 |
+
if pi not in used: chosen.append(pi);used.add(pi)
|
| 187 |
+
return p['docs'][np.asarray(chosen[:k],dtype=np.int64)].tolist()
|
| 188 |
+
|
| 189 |
+
def rank_hq_softdoc(p,topN=20,lam=.25,k=100):
|
| 190 |
+
# restrict diversity bonus to high-quality branches; repeated branches allowed.
|
| 191 |
+
# docs outside HQ set retain pure relevance and are still eligible.
|
| 192 |
+
base=p['base']; n=len(base); order=np.argsort(base)[::-1]
|
| 193 |
+
first=int(order[0]); chosen=[first]; used={first}
|
| 194 |
+
elig_order=np.argsort(p['H'])[::-1][:min(topN,len(p['H']))]
|
| 195 |
+
eligset=set(map(int,elig_order))
|
| 196 |
+
# branch memberships for each pool doc: use all high-quality branches the doc belongs to
|
| 197 |
+
doc_hq=[[] for _ in range(n)]
|
| 198 |
+
for bi in elig_order:
|
| 199 |
+
b=int(p['ub'][bi])
|
| 200 |
+
for pi in p['docs_by_branch'][b]: doc_hq[int(pi)].append(int(bi))
|
| 201 |
+
# selected branch representation starts with highest-quality HQ branch supporting first, if any
|
| 202 |
+
selected=[]
|
| 203 |
+
if doc_hq[first]:
|
| 204 |
+
selected=[max(doc_hq[first], key=lambda bi: float(p['H'][bi]))]
|
| 205 |
+
for _ in range(1,min(10,k,n)):
|
| 206 |
+
rem=np.asarray([i for i in range(n) if i not in used],dtype=np.int32)
|
| 207 |
+
if not len(rem):break
|
| 208 |
+
D=Dvec(p,selected) if selected else np.zeros(len(p['ub']),np.float32)
|
| 209 |
+
# normalize only across eligible branches
|
| 210 |
+
if len(elig_order):
|
| 211 |
+
ed=minmax_hi(D[elig_order]); dn={int(bi):float(v) for bi,v in zip(elig_order,ed)}
|
| 212 |
+
else: dn={}
|
| 213 |
+
# relevance minmax across remaining top pool; high = good
|
| 214 |
+
rn=minmax_hi(base[rem])
|
| 215 |
+
bonus=np.zeros(len(rem),np.float32)
|
| 216 |
+
for k2,pi in enumerate(rem):
|
| 217 |
+
if doc_hq[int(pi)]: bonus[k2]=max(dn.get(bi,0.0) for bi in doc_hq[int(pi)])
|
| 218 |
+
val=rn+float(lam)*bonus
|
| 219 |
+
pi=int(rem[int(np.argmax(val))]); chosen.append(pi); used.add(pi)
|
| 220 |
+
if doc_hq[pi]:
|
| 221 |
+
# add the supporting HQ branch with max diversity, ties quality
|
| 222 |
+
bi=max(doc_hq[pi],key=lambda x:(dn.get(x,0.0),float(p['H'][x])))
|
| 223 |
+
selected.append(int(bi))
|
| 224 |
+
for pi in order:
|
| 225 |
+
pi=int(pi)
|
| 226 |
+
if len(chosen)>=k:break
|
| 227 |
+
if pi not in used:chosen.append(pi);used.add(pi)
|
| 228 |
+
return p['docs'][np.asarray(chosen[:k],dtype=np.int64)].tolist()
|
| 229 |
+
|
| 230 |
+
def evaluate(ds,packs,ranker,**kw):
|
| 231 |
+
run={};route_num=pool_num=den=0;cands=[]
|
| 232 |
+
for qid,p in packs.items():
|
| 233 |
+
rr=[] if p is None else ranker(p,**kw)
|
| 234 |
+
run[str(qid)]=[str(idx.doc_ids[int(d)]) for d in rr]
|
| 235 |
+
if p is not None:
|
| 236 |
+
route={str(idx.doc_ids[int(d)]) for d in p['route_docs']};pool={str(idx.doc_ids[int(d)]) for d in p['docs']}
|
| 237 |
+
pos={str(d) for d,v in ds.qrels[qid].items() if v>0};den+=len(pos);route_num+=sum(d in route for d in pos);pool_num+=sum(d in pool for d in pos);cands.append(len(route))
|
| 238 |
+
m=evaluate_run(run,ds.qrels,ks=(10,100),ndcg_k=10,mrr_k=10,exp_gain=False)
|
| 239 |
+
m['route_recall_micro']=route_num/max(1,den);m['pool_recall_micro']=pool_num/max(1,den);m['avg_candidates']=float(np.mean(cands)) if cands else 0
|
| 240 |
+
return m
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
ds=load_beir_directory(ROOT,'test')
|
| 244 |
+
packs={}; prep=[]
|
| 245 |
+
for i,qid in enumerate(ds.qrels):
|
| 246 |
+
t=time.perf_counter(); packs[qid]=prepare(ds.queries[qid]); prep.append((time.perf_counter()-t)*1000)
|
| 247 |
+
if (i+1)%10==0: print('prepared',i+1,flush=True)
|
| 248 |
+
|
| 249 |
+
def eval_timed(name,fn,**kw):
|
| 250 |
+
# rank timing only on prepared packs
|
| 251 |
+
rt=[]
|
| 252 |
+
for qid,p in packs.items():
|
| 253 |
+
t=time.perf_counter(); _=[] if p is None else fn(p,**kw); rt.append((time.perf_counter()-t)*1000)
|
| 254 |
+
m=evaluate(ds,packs,fn,**kw)
|
| 255 |
+
m['rank_median_ms']=float(np.median(rt)); m['rank_p95_ms']=float(np.percentile(rt,95))
|
| 256 |
+
print(name,m,flush=True); return m
|
| 257 |
+
|
| 258 |
+
res={'dataset':'SciFact','P':P,'branch_quality':'mean top-3 E_dj among P pool docs; E_dj=m_dj*rho_q(j)*L_dj*C_dj^gamma',
|
| 259 |
+
'selection':'top-10 branches by H_j; soft document diversity lambda_D=0.1; IDF^2 final lexical term',
|
| 260 |
+
'timing':{'prepare_median_ms':float(np.median(prep)),'prepare_p95_ms':float(np.percentile(prep,95))},'variants':{}}
|
| 261 |
+
res['variants']['current_z']=eval_timed('current_z',plain)
|
| 262 |
+
res['variants']['hq10_softdoc_l0.1']=eval_timed('hq10_softdoc_l0.1',rank_hq_softdoc,topN=10,lam=0.1)
|
| 263 |
+
out=f'/mnt/data/scifact_p{P}_sweep_result.json'
|
| 264 |
+
json.dump(res,open(out,'w'),indent=2)
|
| 265 |
+
print('saved',out,flush=True)
|
experiments/beir/treccovid_collision_diag_exact_history.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import json, sys, math
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scipy.spatial import cKDTree
|
| 6 |
+
|
| 7 |
+
# Load function definitions only, avoiding the experiment main block.
|
| 8 |
+
path='/mnt/data/treccovid_hq_branch_compact.py'
|
| 9 |
+
src=open(path,'r',encoding='utf-8').read()
|
| 10 |
+
prefix=src.split("ds=load_beir_directory(ROOT,'test')",1)[0]
|
| 11 |
+
ns={}
|
| 12 |
+
exec(compile(prefix,path,'exec'),ns)
|
| 13 |
+
idx=ns['idx']; ROOT=ns['ROOT']; prepare=ns['prepare']; rank_hq_softdoc=ns['rank_hq_softdoc']; load_beir_directory=ns['load_beir_directory']
|
| 14 |
+
|
| 15 |
+
ds=load_beir_directory(ROOT,'test')
|
| 16 |
+
|
| 17 |
+
def minmax_cols(X):
|
| 18 |
+
X=np.asarray(X,np.float64)
|
| 19 |
+
mn=X.min(axis=0); mx=X.max(axis=0); den=mx-mn
|
| 20 |
+
den=np.where(den<1e-12,1.0,den)
|
| 21 |
+
return (X-mn)/den
|
| 22 |
+
|
| 23 |
+
def doc_support_mask(d, qids, qpos):
|
| 24 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1]
|
| 25 |
+
sup=idx.support_indices[a:b]
|
| 26 |
+
mask=0
|
| 27 |
+
# qpos dict is tiny
|
| 28 |
+
for t in sup:
|
| 29 |
+
p=qpos.get(int(t))
|
| 30 |
+
if p is not None: mask |= (1<<p)
|
| 31 |
+
return int(mask)
|
| 32 |
+
|
| 33 |
+
def dom_slot(d, b):
|
| 34 |
+
slots=np.where(idx.branches[int(d)]==int(b))[0]
|
| 35 |
+
return int(slots[0]) if len(slots) else -1
|
| 36 |
+
|
| 37 |
+
def residual_keys(d, b, qpos):
|
| 38 |
+
sl=dom_slot(d,b)
|
| 39 |
+
if sl<0: return (),()
|
| 40 |
+
terms=idx.res_terms[int(d),sl]
|
| 41 |
+
signs=idx.res_signs[int(d),sl]
|
| 42 |
+
full=[]; proj=[]
|
| 43 |
+
for t,s in zip(terms,signs):
|
| 44 |
+
ti=int(t)
|
| 45 |
+
if ti<0: continue
|
| 46 |
+
si=int(s)
|
| 47 |
+
full.append((ti,si))
|
| 48 |
+
p=qpos.get(ti)
|
| 49 |
+
if p is not None: proj.append((int(p),si))
|
| 50 |
+
return tuple(full),tuple(proj)
|
| 51 |
+
|
| 52 |
+
def mixed_class_stats(keys, labels):
|
| 53 |
+
groups=defaultdict(lambda:[0,0])
|
| 54 |
+
for k,y in zip(keys,labels): groups[k][int(y)]+=1
|
| 55 |
+
mixed={k:v for k,v in groups.items() if v[0]>0 and v[1]>0}
|
| 56 |
+
n=len(keys); nrel=int(np.sum(labels)); nnon=n-nrel
|
| 57 |
+
rel_mixed=sum(v[1] for v in mixed.values()); non_mixed=sum(v[0] for v in mixed.values())
|
| 58 |
+
docs_mixed=rel_mixed+non_mixed
|
| 59 |
+
return {
|
| 60 |
+
'n_docs':n,'n_classes':len(groups),'n_mixed_classes':len(mixed),
|
| 61 |
+
'docs_in_mixed_classes':docs_mixed,
|
| 62 |
+
'doc_mixed_fraction':docs_mixed/max(1,n),
|
| 63 |
+
'relevant_docs':nrel,'relevant_in_mixed_classes':rel_mixed,
|
| 64 |
+
'relevant_mixed_fraction':rel_mixed/max(1,nrel),
|
| 65 |
+
'nonrelevant_in_mixed_classes':non_mixed,
|
| 66 |
+
'largest_class':max((sum(v) for v in groups.values()), default=0),
|
| 67 |
+
'largest_mixed_class':max((sum(v) for v in mixed.values()), default=0),
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
def near_stats(X,y):
|
| 71 |
+
X=np.asarray(X,np.float64); y=np.asarray(y,np.int8)
|
| 72 |
+
rel=np.where(y==1)[0]; non=np.where(y==0)[0]
|
| 73 |
+
if len(rel)==0 or len(non)==0:
|
| 74 |
+
return {'n_rel':len(rel),'n_nonrel':len(non)}
|
| 75 |
+
tree=cKDTree(X[non])
|
| 76 |
+
dist,_=tree.query(X[rel],k=1)
|
| 77 |
+
out={'n_rel':int(len(rel)),'n_nonrel':int(len(non)),
|
| 78 |
+
'nearest_nonrel_median':float(np.median(dist)),
|
| 79 |
+
'nearest_nonrel_p25':float(np.percentile(dist,25)),
|
| 80 |
+
'nearest_nonrel_p75':float(np.percentile(dist,75)),
|
| 81 |
+
'nearest_nonrel_p90':float(np.percentile(dist,90))}
|
| 82 |
+
for th in [0.005,0.01,0.02,0.05,0.10,0.20]:
|
| 83 |
+
out[f'frac_rel_nn_le_{th:g}']=float(np.mean(dist<=th))
|
| 84 |
+
return out
|
| 85 |
+
|
| 86 |
+
def quantized_mixed(X,y,bins):
|
| 87 |
+
# X already in [0,1]; map each dimension into 0..bins-1
|
| 88 |
+
Q=np.minimum(bins-1,np.floor(np.asarray(X)*bins).astype(np.int16))
|
| 89 |
+
keys=[tuple(row.tolist()) for row in Q]
|
| 90 |
+
return mixed_class_stats(keys,y)
|
| 91 |
+
|
| 92 |
+
perq={}
|
| 93 |
+
agg_light=[]; agg_full=[]
|
| 94 |
+
# aggregate counters manually by concatenating keys with qid prefix to avoid cross-query collisions
|
| 95 |
+
all_light_keys=[]; all_full_keys=[]; all_labels=[]
|
| 96 |
+
all_X=[]; all_y=[]
|
| 97 |
+
all_pool_X=[]; all_pool_y=[]
|
| 98 |
+
q_oracle=[]
|
| 99 |
+
actual_top10_rel=[]
|
| 100 |
+
base_top10_rel=[]
|
| 101 |
+
rel_pool_total=rel_hq_total=0
|
| 102 |
+
|
| 103 |
+
for qi,qid in enumerate(ds.qrels):
|
| 104 |
+
p=prepare(ds.queries[qid])
|
| 105 |
+
if p is None: continue
|
| 106 |
+
q=idx._query_vector(ds.queries[qid])
|
| 107 |
+
qids=list(map(int,q.indices)); qpos={t:i for i,t in enumerate(qids)}
|
| 108 |
+
rare_ids=set(map(int,q.indices[np.argsort(idx.idf[q.indices])[::-1]][:3]))
|
| 109 |
+
# labels for 2k
|
| 110 |
+
pos={str(d) for d,v in ds.qrels[qid].items() if v>0}
|
| 111 |
+
labels=np.asarray([1 if str(idx.doc_ids[int(d)]) in pos else 0 for d in p['docs']],dtype=np.int8)
|
| 112 |
+
# high-quality top10 branches
|
| 113 |
+
elig_order=np.argsort(p['H'])[::-1][:min(10,len(p['H']))]
|
| 114 |
+
hq_positions=set()
|
| 115 |
+
for bi in elig_order:
|
| 116 |
+
b=int(p['ub'][int(bi)])
|
| 117 |
+
hq_positions.update(map(int,p['docs_by_branch'][b]))
|
| 118 |
+
hq=np.asarray(sorted(hq_positions),dtype=np.int32)
|
| 119 |
+
if len(hq)==0: continue
|
| 120 |
+
yh=labels[hq]
|
| 121 |
+
# feature vectors: tail, lex, sem, rare. normalize over full 2k, then subset HQ
|
| 122 |
+
V=np.column_stack([p['tail'],p['lex'],p['sem'],p['rare']]).astype(np.float64)
|
| 123 |
+
Vn=minmax_cols(V)
|
| 124 |
+
Xh=Vn[hq]
|
| 125 |
+
# symbolic keys
|
| 126 |
+
light=[]; full=[]
|
| 127 |
+
for pi in hq:
|
| 128 |
+
d=int(p['docs'][pi]); b=int(p['branches_dom'][pi])
|
| 129 |
+
smask=doc_support_mask(d,qids,qpos)
|
| 130 |
+
rmask=0
|
| 131 |
+
for t in rare_ids:
|
| 132 |
+
qp=qpos.get(t)
|
| 133 |
+
if qp is not None and (smask & (1<<qp)): rmask |= (1<<qp)
|
| 134 |
+
fkey,pkey=residual_keys(d,b,qpos)
|
| 135 |
+
light.append((smask,rmask,b,pkey))
|
| 136 |
+
full.append((smask,rmask,b,fkey))
|
| 137 |
+
ls=mixed_class_stats(light,yh); fs=mixed_class_stats(full,yh); ns4=near_stats(Xh,yh)
|
| 138 |
+
qmix={str(b):quantized_mixed(Xh,yh,b) for b in [10,20,50,100]}
|
| 139 |
+
# ceilings
|
| 140 |
+
nrel_pool=int(labels.sum()); nrel_hq=int(yh.sum())
|
| 141 |
+
rel_pool_total += nrel_pool; rel_hq_total += nrel_hq
|
| 142 |
+
oracle_top10=min(10,nrel_hq)
|
| 143 |
+
q_oracle.append(oracle_top10)
|
| 144 |
+
# current HQ-div rank and plain rank rel count
|
| 145 |
+
rr=rank_hq_softdoc(p,topN=10,lam=.1,k=10)
|
| 146 |
+
rr_ext={str(idx.doc_ids[int(d)]) for d in rr}
|
| 147 |
+
ar=sum(d in pos for d in rr_ext); actual_top10_rel.append(ar)
|
| 148 |
+
bo=np.argsort(p['base'])[::-1][:10]
|
| 149 |
+
br=sum(labels[bo]); base_top10_rel.append(int(br))
|
| 150 |
+
perq[str(qid)]={'pool_rel':nrel_pool,'hq_docs':int(len(hq)),'hq_rel':nrel_hq,
|
| 151 |
+
'actual_hqdiv_rel10':int(ar),'plain_rel10':int(br),'oracle_rel10_hq':int(oracle_top10),
|
| 152 |
+
'light_collision':ls,'full_collision':fs,'near4d':ns4,'quantized4d':qmix}
|
| 153 |
+
# aggregate with qid prefix
|
| 154 |
+
all_light_keys.extend([(str(qid),)+tuple(k) for k in light])
|
| 155 |
+
all_full_keys.extend([(str(qid),)+tuple(k) for k in full])
|
| 156 |
+
all_labels.extend(yh.tolist())
|
| 157 |
+
all_X.append(Xh); all_y.append(yh)
|
| 158 |
+
all_pool_X.append(Vn); all_pool_y.append(labels)
|
| 159 |
+
|
| 160 |
+
Y=np.asarray(all_labels,np.int8); X=np.vstack(all_X); PY=np.concatenate(all_pool_y); PX=np.vstack(all_pool_X)
|
| 161 |
+
result={
|
| 162 |
+
'dataset':'TREC-COVID',
|
| 163 |
+
'diagnostic':'2k -> 10 discrimination inside top-10 high-quality branches',
|
| 164 |
+
'definitions':{
|
| 165 |
+
'hq_branches':'top 10 branches by H_j = mean top-3 branch-specific E_dj',
|
| 166 |
+
'light_collision':'same whole-query binary support mask + same rare-term mask + same dominant branch + same query-projected residual sign signature',
|
| 167 |
+
'full_collision':'same support/rare masks + same dominant branch + identical full 16-coordinate residual (term,sign) code',
|
| 168 |
+
'near4d':'Euclidean distance after per-query min-max normalization of [tail, IDF^2 lexical+coordination, semantic support, rare3 coverage]',
|
| 169 |
+
},
|
| 170 |
+
'aggregate':{
|
| 171 |
+
'queries':len(perq),'pool_relevant_total':int(rel_pool_total),'hq_relevant_total':int(rel_hq_total),
|
| 172 |
+
'hq_share_of_pool_relevant':float(rel_hq_total/max(1,rel_pool_total)),
|
| 173 |
+
'mean_plain_relevant_at10':float(np.mean(base_top10_rel)),
|
| 174 |
+
'mean_hqdiv_relevant_at10':float(np.mean(actual_top10_rel)),
|
| 175 |
+
'mean_oracle_relevant_at10_if_perfect_inside_hq':float(np.mean(q_oracle)),
|
| 176 |
+
'light_collision':mixed_class_stats(all_light_keys,Y),
|
| 177 |
+
'full_collision':mixed_class_stats(all_full_keys,Y),
|
| 178 |
+
'near4d_hq':near_stats(X,Y),
|
| 179 |
+
'near4d_full_pool':near_stats(PX,PY),
|
| 180 |
+
'quantized4d_hq':{str(b):quantized_mixed(X,Y,b) for b in [10,20,50,100]},
|
| 181 |
+
'quantized4d_full_pool':{str(b):quantized_mixed(PX,PY,b) for b in [10,20,50,100]},
|
| 182 |
+
},
|
| 183 |
+
'per_query':perq,
|
| 184 |
+
}
|
| 185 |
+
out='/mnt/data/treccovid_collision_diagnostic.json'
|
| 186 |
+
json.dump(result,open(out,'w'),indent=2)
|
| 187 |
+
print(json.dumps(result['aggregate'],indent=2))
|
| 188 |
+
print('saved',out)
|
experiments/beir/treccovid_hq_branch_exact_history.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json,math,os
|
| 3 |
+
import numpy as np
|
| 4 |
+
sys.path.insert(0,'/mnt/data/work_code/geomretrieval_msmarco_scale_codebase/original_v0')
|
| 5 |
+
from geomretrieval import GeometricIndex, load_beir_directory, evaluate_run
|
| 6 |
+
|
| 7 |
+
IDX='/mnt/data/treccovid_geom_index'
|
| 8 |
+
ROOT='/mnt/data/work_treccovid/trec-covid'
|
| 9 |
+
idx=GeometricIndex.load(IDX); M=idx.vocab_size
|
| 10 |
+
P=2000; GAMMA=.25; LAM_M=.125; PRE_B=.2; FINAL_B=.1; ALPHA=.25
|
| 11 |
+
WLEX=4.0; WSEM=.3; WRARE=1.0; SEMK=16; EPS=1e-8
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def zscore(x):
|
| 15 |
+
x=np.asarray(x,np.float32)
|
| 16 |
+
if not len(x): return x
|
| 17 |
+
sd=float(x.std())
|
| 18 |
+
return np.zeros_like(x) if sd<1e-8 else (x-float(x.mean()))/sd
|
| 19 |
+
|
| 20 |
+
def minmax_hi(x):
|
| 21 |
+
x=np.asarray(x,np.float32)
|
| 22 |
+
if not len(x): return x
|
| 23 |
+
mn=float(x.min()); mx=float(x.max()); den=mx-mn
|
| 24 |
+
return np.ones_like(x) if den<1e-8 else (x-mn)/den
|
| 25 |
+
|
| 26 |
+
def topk_large(score,k):
|
| 27 |
+
n=len(score); k=min(k,n)
|
| 28 |
+
if k<=0:return np.empty(0,np.int64)
|
| 29 |
+
if n<=k:return np.argsort(score)[::-1]
|
| 30 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 31 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 32 |
+
|
| 33 |
+
def center_sparse(j):
|
| 34 |
+
t=idx.center_terms[j]; v=idx.center_values[j]; ok=t>=0
|
| 35 |
+
t=t[ok].astype(np.int32); v=v[ok].astype(np.float32)
|
| 36 |
+
n=float(np.linalg.norm(v))
|
| 37 |
+
if n>0:v=v/n
|
| 38 |
+
oo=np.argsort(t)
|
| 39 |
+
return t[oo],v[oo]
|
| 40 |
+
|
| 41 |
+
def spdot(a_t,a_v,b_t,b_v):
|
| 42 |
+
i=j=0;s=0.0
|
| 43 |
+
while i<len(a_t) and j<len(b_t):
|
| 44 |
+
if a_t[i]==b_t[j]:s+=float(a_v[i])*float(b_v[j]);i+=1;j+=1
|
| 45 |
+
elif a_t[i]<b_t[j]:i+=1
|
| 46 |
+
else:j+=1
|
| 47 |
+
return s
|
| 48 |
+
|
| 49 |
+
def prepare(text):
|
| 50 |
+
q=idx._query_vector(text)
|
| 51 |
+
if q.nnz==0:return None
|
| 52 |
+
qd=np.zeros(M,np.float32); qd[q.indices]=q.data
|
| 53 |
+
rt,rv,qt=idx._expanded_route(q)
|
| 54 |
+
if not len(rt):return None
|
| 55 |
+
rd=np.zeros(M,np.float32);rd[rt]=rv
|
| 56 |
+
pieces=[]
|
| 57 |
+
for j in rt:
|
| 58 |
+
a,b=idx.branch_offsets[j],idx.branch_offsets[j+1]
|
| 59 |
+
if b>a:pieces.append(idx.branch_order[a:b])
|
| 60 |
+
if not pieces:return None
|
| 61 |
+
fp=np.concatenate(pieces).astype(np.int64,copy=False)
|
| 62 |
+
docs=(fp//idx.config.F).astype(np.int64); slots=(fp%idx.config.F).astype(np.int64)
|
| 63 |
+
br=idx.branches[docs,slots]
|
| 64 |
+
terms=idx.res_terms[docs,slots];valid=terms>=0;safe=np.where(valid,terms,0);qv=qd[safe]
|
| 65 |
+
local=np.sum(idx.res_reliability[docs,slots].astype(np.float32)*(qv-idx.res_center_values[docs,slots])*idx.res_signs[docs,slots].astype(np.float32)*valid,axis=1)
|
| 66 |
+
sig=np.sum((qv*qv)*valid,axis=1)
|
| 67 |
+
cons=idx.memberships[docs,slots]*rd[br]
|
| 68 |
+
branch_ev=(cons*local*np.power(np.maximum(sig,0),GAMMA)).astype(np.float32) # E_dj exactly
|
| 69 |
+
base=cons*local
|
| 70 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 71 |
+
tail=np.bincount(inv,weights=branch_ev,minlength=len(ud)).astype(np.float32)
|
| 72 |
+
tail += LAM_M*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 73 |
+
# dominant routed branch retained for diagnostics
|
| 74 |
+
bestv=np.full(len(ud),-1e30,np.float32);db=np.full(len(ud),-1,np.int32)
|
| 75 |
+
for p,u in enumerate(inv):
|
| 76 |
+
if cons[p]>bestv[u]:bestv[u]=cons[p];db[u]=int(br[p])
|
| 77 |
+
# frozen early lexical rescue
|
| 78 |
+
qlex=np.zeros(M,np.float32);qlex[q.indices]=idx.idf[q.indices]
|
| 79 |
+
lex1=np.zeros(len(ud),np.float32)
|
| 80 |
+
for i,d in enumerate(ud):
|
| 81 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1];sup=idx.support_indices[a:b]
|
| 82 |
+
raw=float(qlex[sup].sum());den=(1-PRE_B)+PRE_B*(float(idx.doc_lengths[d])/idx.avg_doc_length)
|
| 83 |
+
lex1[i]=raw/(den if den>0 else 1.)
|
| 84 |
+
pre=zscore(tail)+zscore(lex1)
|
| 85 |
+
sel=topk_large(pre,P)
|
| 86 |
+
dd=ud[sel];ts=tail[sel];db=db[sel]
|
| 87 |
+
# mapping routed-doc local index -> pool local index
|
| 88 |
+
poolpos=np.full(len(ud),-1,np.int32); poolpos[sel]=np.arange(len(sel),dtype=np.int32)
|
| 89 |
+
mp=poolpos[inv]
|
| 90 |
+
keep=mp>=0
|
| 91 |
+
mem_pool=mp[keep].astype(np.int32)
|
| 92 |
+
mem_br=br[keep].astype(np.int32)
|
| 93 |
+
mem_ev=branch_ev[keep].astype(np.float32)
|
| 94 |
+
# final current features
|
| 95 |
+
semvec=np.zeros(M,np.float32)
|
| 96 |
+
for t,amp in zip(q.indices,q.data):
|
| 97 |
+
a,b=idx.A.indptr[t],idx.A.indptr[t+1];nb=idx.A.indices[a:b][:SEMK];sv=idx.A.data[a:b][:SEMK]
|
| 98 |
+
if len(nb):semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 99 |
+
qset=set(map(int,q.indices));rare=set(map(int,q.indices[np.argsort(idx.idf[q.indices])[::-1]][:3]));nq=max(1,len(q.indices))
|
| 100 |
+
lx=np.zeros(len(dd),np.float32);sm=np.zeros(len(dd),np.float32);qc=np.zeros(len(dd),np.float32);r3=np.zeros(len(dd),np.float32)
|
| 101 |
+
for i,d in enumerate(dd):
|
| 102 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1];sup=idx.support_indices[a:b]
|
| 103 |
+
sm[i]=float(semvec[sup].sum())
|
| 104 |
+
match=[int(t) for t in sup if int(t) in qset]
|
| 105 |
+
raw=sum(float(idx.idf[t])**2 for t in match);den=(1-FINAL_B)+FINAL_B*(float(idx.doc_lengths[d])/idx.avg_doc_length)
|
| 106 |
+
lx[i]=raw/(den if den>0 else 1.);qc[i]=len(match);r3[i]=sum(t in rare for t in match)
|
| 107 |
+
cov=qc/nq;ladj=lx*np.power(np.maximum(cov,1e-6),ALPHA);rarecov=r3/max(1,min(3,nq))
|
| 108 |
+
base_score=zscore(ts)+WLEX*zscore(ladj)+WSEM*zscore(sm)+WRARE*zscore(rarecov)
|
| 109 |
+
|
| 110 |
+
# Build H_j = mean of top 3 E_dj among selected pool documents for branch j.
|
| 111 |
+
# Multiple memberships of same doc+branch should not occur; if they do, keep max.
|
| 112 |
+
branch_pairs={}
|
| 113 |
+
for pi,b,e in zip(mem_pool,mem_br,mem_ev):
|
| 114 |
+
key=(int(b),int(pi))
|
| 115 |
+
if key not in branch_pairs or e>branch_pairs[key]: branch_pairs[key]=float(e)
|
| 116 |
+
byb={}
|
| 117 |
+
for (b,pi),e in branch_pairs.items(): byb.setdefault(b,[]).append((e,pi))
|
| 118 |
+
H={}; bestdoc={}; docs_by_branch={}
|
| 119 |
+
for b,vals in byb.items():
|
| 120 |
+
vals.sort(key=lambda x:x[0],reverse=True)
|
| 121 |
+
top=vals[:3]
|
| 122 |
+
H[b]=float(np.mean([e for e,_ in top]))
|
| 123 |
+
bestdoc[b]=int(max(vals,key=lambda x: float(base_score[x[1]]))[1]) # best final-relevance doc in branch
|
| 124 |
+
docs_by_branch[b]=np.asarray([pi for _,pi in vals],dtype=np.int32)
|
| 125 |
+
ub=np.asarray(sorted(H.keys()),dtype=np.int32)
|
| 126 |
+
h=np.asarray([H[int(b)] for b in ub],dtype=np.float32)
|
| 127 |
+
hnorm=minmax_hi(h)
|
| 128 |
+
bmap={int(b):i for i,b in enumerate(ub)}
|
| 129 |
+
reps=[center_sparse(int(b)) for b in ub]
|
| 130 |
+
C=np.eye(len(ub),dtype=np.float32)
|
| 131 |
+
for i in range(len(ub)):
|
| 132 |
+
for j in range(i+1,len(ub)):
|
| 133 |
+
C[i,j]=C[j,i]=spdot(*reps[i],*reps[j])
|
| 134 |
+
return {'docs':dd,'base':base_score,'tail':ts,'lex':ladj,'sem':sm,'rare':rarecov,
|
| 135 |
+
'route_docs':ud,'branches_dom':db,'ub':ub,'H':h,'Hn':hnorm,'bmap':bmap,'cos':C,
|
| 136 |
+
'bestdoc':bestdoc,'docs_by_branch':docs_by_branch}
|
| 137 |
+
|
| 138 |
+
def plain(p,k=100):
|
| 139 |
+
oo=np.argsort(p['base'])[::-1][:k]
|
| 140 |
+
return p['docs'][oo].tolist()
|
| 141 |
+
|
| 142 |
+
def Dvec(p, selected_bidx):
|
| 143 |
+
C=p['cos']
|
| 144 |
+
if not selected_bidx:return np.zeros(len(C),np.float32)
|
| 145 |
+
si=np.asarray(selected_bidx,np.int32)
|
| 146 |
+
mumun=float(np.mean(C[np.ix_(si,si)]))
|
| 147 |
+
return 1.0+mumun-2.0*np.mean(C[:,si],axis=1)
|
| 148 |
+
|
| 149 |
+
def select_hq_branches(p, topN=20, lam=1.0, nsel=10, pure_div=False):
|
| 150 |
+
if len(p['ub'])==0:return []
|
| 151 |
+
# eligible branches are the top-N robust-quality H_j branches
|
| 152 |
+
order=np.argsort(p['H'])[::-1]
|
| 153 |
+
elig=order[:min(topN,len(order))]
|
| 154 |
+
# first branch = highest H_j
|
| 155 |
+
selected=[int(elig[0])]
|
| 156 |
+
remaining=set(map(int,elig[1:]))
|
| 157 |
+
while remaining and len(selected)<min(nsel,len(elig)):
|
| 158 |
+
rem=np.asarray(sorted(remaining),dtype=np.int32)
|
| 159 |
+
D=Dvec(p,selected)
|
| 160 |
+
dnorm=minmax_hi(D[rem])
|
| 161 |
+
if pure_div:
|
| 162 |
+
val=dnorm
|
| 163 |
+
else:
|
| 164 |
+
h=p['Hn'][rem]
|
| 165 |
+
val=h+float(lam)*dnorm
|
| 166 |
+
pick=int(rem[int(np.argmax(val))])
|
| 167 |
+
selected.append(pick); remaining.remove(pick)
|
| 168 |
+
return selected
|
| 169 |
+
|
| 170 |
+
def rank_hq_oneper(p,topN=20,lam=1.0,pure_div=False,k=100):
|
| 171 |
+
# one best final-score document from each selected high-quality/diverse branch for top 10
|
| 172 |
+
sb=select_hq_branches(p,topN,lam,10,pure_div)
|
| 173 |
+
chosen=[]; used=set()
|
| 174 |
+
for bi in sb:
|
| 175 |
+
b=int(p['ub'][bi]); pi=int(p['bestdoc'][b])
|
| 176 |
+
if pi not in used: chosen.append(pi); used.add(pi)
|
| 177 |
+
# if fewer than 10, fill by ordinary score
|
| 178 |
+
for pi in np.argsort(p['base'])[::-1]:
|
| 179 |
+
pi=int(pi)
|
| 180 |
+
if len(chosen)>=10:break
|
| 181 |
+
if pi not in used: chosen.append(pi);used.add(pi)
|
| 182 |
+
# rest by ordinary score
|
| 183 |
+
for pi in np.argsort(p['base'])[::-1]:
|
| 184 |
+
pi=int(pi)
|
| 185 |
+
if len(chosen)>=k:break
|
| 186 |
+
if pi not in used: chosen.append(pi);used.add(pi)
|
| 187 |
+
return p['docs'][np.asarray(chosen[:k],dtype=np.int64)].tolist()
|
| 188 |
+
|
| 189 |
+
def rank_hq_softdoc(p,topN=20,lam=.25,k=100):
|
| 190 |
+
# restrict diversity bonus to high-quality branches; repeated branches allowed.
|
| 191 |
+
# docs outside HQ set retain pure relevance and are still eligible.
|
| 192 |
+
base=p['base']; n=len(base); order=np.argsort(base)[::-1]
|
| 193 |
+
first=int(order[0]); chosen=[first]; used={first}
|
| 194 |
+
elig_order=np.argsort(p['H'])[::-1][:min(topN,len(p['H']))]
|
| 195 |
+
eligset=set(map(int,elig_order))
|
| 196 |
+
# branch memberships for each pool doc: use all high-quality branches the doc belongs to
|
| 197 |
+
doc_hq=[[] for _ in range(n)]
|
| 198 |
+
for bi in elig_order:
|
| 199 |
+
b=int(p['ub'][bi])
|
| 200 |
+
for pi in p['docs_by_branch'][b]: doc_hq[int(pi)].append(int(bi))
|
| 201 |
+
# selected branch representation starts with highest-quality HQ branch supporting first, if any
|
| 202 |
+
selected=[]
|
| 203 |
+
if doc_hq[first]:
|
| 204 |
+
selected=[max(doc_hq[first], key=lambda bi: float(p['H'][bi]))]
|
| 205 |
+
for _ in range(1,min(10,k,n)):
|
| 206 |
+
rem=np.asarray([i for i in range(n) if i not in used],dtype=np.int32)
|
| 207 |
+
if not len(rem):break
|
| 208 |
+
D=Dvec(p,selected) if selected else np.zeros(len(p['ub']),np.float32)
|
| 209 |
+
# normalize only across eligible branches
|
| 210 |
+
if len(elig_order):
|
| 211 |
+
ed=minmax_hi(D[elig_order]); dn={int(bi):float(v) for bi,v in zip(elig_order,ed)}
|
| 212 |
+
else: dn={}
|
| 213 |
+
# relevance minmax across remaining top pool; high = good
|
| 214 |
+
rn=minmax_hi(base[rem])
|
| 215 |
+
bonus=np.zeros(len(rem),np.float32)
|
| 216 |
+
for k2,pi in enumerate(rem):
|
| 217 |
+
if doc_hq[int(pi)]: bonus[k2]=max(dn.get(bi,0.0) for bi in doc_hq[int(pi)])
|
| 218 |
+
val=rn+float(lam)*bonus
|
| 219 |
+
pi=int(rem[int(np.argmax(val))]); chosen.append(pi); used.add(pi)
|
| 220 |
+
if doc_hq[pi]:
|
| 221 |
+
# add the supporting HQ branch with max diversity, ties quality
|
| 222 |
+
bi=max(doc_hq[pi],key=lambda x:(dn.get(x,0.0),float(p['H'][x])))
|
| 223 |
+
selected.append(int(bi))
|
| 224 |
+
for pi in order:
|
| 225 |
+
pi=int(pi)
|
| 226 |
+
if len(chosen)>=k:break
|
| 227 |
+
if pi not in used:chosen.append(pi);used.add(pi)
|
| 228 |
+
return p['docs'][np.asarray(chosen[:k],dtype=np.int64)].tolist()
|
| 229 |
+
|
| 230 |
+
def evaluate(ds,packs,ranker,**kw):
|
| 231 |
+
run={};route_num=pool_num=den=0;cands=[]
|
| 232 |
+
for qid,p in packs.items():
|
| 233 |
+
rr=[] if p is None else ranker(p,**kw)
|
| 234 |
+
run[str(qid)]=[str(idx.doc_ids[int(d)]) for d in rr]
|
| 235 |
+
if p is not None:
|
| 236 |
+
route={str(idx.doc_ids[int(d)]) for d in p['route_docs']};pool={str(idx.doc_ids[int(d)]) for d in p['docs']}
|
| 237 |
+
pos={str(d) for d,v in ds.qrels[qid].items() if v>0};den+=len(pos);route_num+=sum(d in route for d in pos);pool_num+=sum(d in pool for d in pos);cands.append(len(route))
|
| 238 |
+
m=evaluate_run(run,ds.qrels,ks=(10,100),ndcg_k=10,mrr_k=10,exp_gain=False)
|
| 239 |
+
m['route_recall_micro']=route_num/max(1,den);m['pool_recall_micro']=pool_num/max(1,den);m['avg_candidates']=float(np.mean(cands)) if cands else 0
|
| 240 |
+
return m
|
| 241 |
+
|
| 242 |
+
ds=load_beir_directory(ROOT,'test')
|
| 243 |
+
packs={};times=[]
|
| 244 |
+
for i,qid in enumerate(ds.qrels):
|
| 245 |
+
t=time.perf_counter();packs[qid]=prepare(ds.queries[qid]);times.append((time.perf_counter()-t)*1000)
|
| 246 |
+
if (i+1)%10==0:print('prepared',i+1,'/',len(ds.qrels),flush=True)
|
| 247 |
+
res={'dataset':'TREC-COVID','timing':{'prepare_median_ms':float(np.median(times)),'prepare_p95_ms':float(np.percentile(times,95))},'variants':{}}
|
| 248 |
+
res['variants']['current_z']=evaluate(ds,packs,plain)
|
| 249 |
+
print('current_z',res['variants']['current_z'],flush=True)
|
| 250 |
+
# high-quality branch diagnostics
|
| 251 |
+
for topN in [10,20,30,50]:
|
| 252 |
+
for pure in [True,False]:
|
| 253 |
+
if pure:
|
| 254 |
+
name=f'hq{topN}_purediv_oneper'; kw={'topN':topN,'lam':1.0,'pure_div':True}
|
| 255 |
+
m=evaluate(ds,packs,rank_hq_oneper,**kw);res['variants'][name]=m;print(name,m,flush=True)
|
| 256 |
+
else:
|
| 257 |
+
for lam in [0.1,0.25,0.5,1.0]:
|
| 258 |
+
name=f'hq{topN}_qplusdiv_l{lam:g}_oneper';kw={'topN':topN,'lam':lam,'pure_div':False}
|
| 259 |
+
m=evaluate(ds,packs,rank_hq_oneper,**kw);res['variants'][name]=m;print(name,m,flush=True)
|
| 260 |
+
# soft doc selection, diversity bonus only from HQ branches
|
| 261 |
+
for topN in [10,20,30,50]:
|
| 262 |
+
for lam in [0.05,0.1,0.25,0.5,1.0]:
|
| 263 |
+
name=f'hq{topN}_softdoc_l{lam:g}'
|
| 264 |
+
m=evaluate(ds,packs,rank_hq_softdoc,topN=topN,lam=lam);res['variants'][name]=m;print(name,m,flush=True)
|
| 265 |
+
|
| 266 |
+
out='/mnt/data/treccovid_hq_branch_results.json'
|
| 267 |
+
json.dump(res,open(out,'w'),indent=2)
|
| 268 |
+
print('saved',out,flush=True)
|
experiments/beir/treccovid_idf_power_exact_history.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json,math,os
|
| 3 |
+
import numpy as np
|
| 4 |
+
sys.path.insert(0,'/mnt/data/work_code/geomretrieval_msmarco_scale_codebase/original_v0')
|
| 5 |
+
from geomretrieval import GeometricIndex, load_beir_directory, evaluate_run
|
| 6 |
+
|
| 7 |
+
IDX='/mnt/data/treccovid_geom_index'
|
| 8 |
+
ROOT='/mnt/data/work_treccovid/trec-covid'
|
| 9 |
+
idx=GeometricIndex.load(IDX); M=idx.vocab_size
|
| 10 |
+
P=2000; GAMMA=.25; LAM_M=.125; PRE_B=.2; FINAL_B=.1; ALPHA=.25
|
| 11 |
+
WLEX=4.0; WSEM=.3; WRARE=1.0; SEMK=16; EPS=1e-8
|
| 12 |
+
IDF_POWER=2
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def zscore(x):
|
| 16 |
+
x=np.asarray(x,np.float32)
|
| 17 |
+
if not len(x): return x
|
| 18 |
+
sd=float(x.std())
|
| 19 |
+
return np.zeros_like(x) if sd<1e-8 else (x-float(x.mean()))/sd
|
| 20 |
+
|
| 21 |
+
def minmax_hi(x):
|
| 22 |
+
x=np.asarray(x,np.float32)
|
| 23 |
+
if not len(x): return x
|
| 24 |
+
mn=float(x.min()); mx=float(x.max()); den=mx-mn
|
| 25 |
+
return np.ones_like(x) if den<1e-8 else (x-mn)/den
|
| 26 |
+
|
| 27 |
+
def topk_large(score,k):
|
| 28 |
+
n=len(score); k=min(k,n)
|
| 29 |
+
if k<=0:return np.empty(0,np.int64)
|
| 30 |
+
if n<=k:return np.argsort(score)[::-1]
|
| 31 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 32 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 33 |
+
|
| 34 |
+
def center_sparse(j):
|
| 35 |
+
t=idx.center_terms[j]; v=idx.center_values[j]; ok=t>=0
|
| 36 |
+
t=t[ok].astype(np.int32); v=v[ok].astype(np.float32)
|
| 37 |
+
n=float(np.linalg.norm(v))
|
| 38 |
+
if n>0:v=v/n
|
| 39 |
+
oo=np.argsort(t)
|
| 40 |
+
return t[oo],v[oo]
|
| 41 |
+
|
| 42 |
+
def spdot(a_t,a_v,b_t,b_v):
|
| 43 |
+
i=j=0;s=0.0
|
| 44 |
+
while i<len(a_t) and j<len(b_t):
|
| 45 |
+
if a_t[i]==b_t[j]:s+=float(a_v[i])*float(b_v[j]);i+=1;j+=1
|
| 46 |
+
elif a_t[i]<b_t[j]:i+=1
|
| 47 |
+
else:j+=1
|
| 48 |
+
return s
|
| 49 |
+
|
| 50 |
+
def prepare(text):
|
| 51 |
+
q=idx._query_vector(text)
|
| 52 |
+
if q.nnz==0:return None
|
| 53 |
+
qd=np.zeros(M,np.float32); qd[q.indices]=q.data
|
| 54 |
+
rt,rv,qt=idx._expanded_route(q)
|
| 55 |
+
if not len(rt):return None
|
| 56 |
+
rd=np.zeros(M,np.float32);rd[rt]=rv
|
| 57 |
+
pieces=[]
|
| 58 |
+
for j in rt:
|
| 59 |
+
a,b=idx.branch_offsets[j],idx.branch_offsets[j+1]
|
| 60 |
+
if b>a:pieces.append(idx.branch_order[a:b])
|
| 61 |
+
if not pieces:return None
|
| 62 |
+
fp=np.concatenate(pieces).astype(np.int64,copy=False)
|
| 63 |
+
docs=(fp//idx.config.F).astype(np.int64); slots=(fp%idx.config.F).astype(np.int64)
|
| 64 |
+
br=idx.branches[docs,slots]
|
| 65 |
+
terms=idx.res_terms[docs,slots];valid=terms>=0;safe=np.where(valid,terms,0);qv=qd[safe]
|
| 66 |
+
local=np.sum(idx.res_reliability[docs,slots].astype(np.float32)*(qv-idx.res_center_values[docs,slots])*idx.res_signs[docs,slots].astype(np.float32)*valid,axis=1)
|
| 67 |
+
sig=np.sum((qv*qv)*valid,axis=1)
|
| 68 |
+
cons=idx.memberships[docs,slots]*rd[br]
|
| 69 |
+
branch_ev=(cons*local*np.power(np.maximum(sig,0),GAMMA)).astype(np.float32) # E_dj exactly
|
| 70 |
+
base=cons*local
|
| 71 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 72 |
+
tail=np.bincount(inv,weights=branch_ev,minlength=len(ud)).astype(np.float32)
|
| 73 |
+
tail += LAM_M*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 74 |
+
# dominant routed branch retained for diagnostics
|
| 75 |
+
bestv=np.full(len(ud),-1e30,np.float32);db=np.full(len(ud),-1,np.int32)
|
| 76 |
+
for p,u in enumerate(inv):
|
| 77 |
+
if cons[p]>bestv[u]:bestv[u]=cons[p];db[u]=int(br[p])
|
| 78 |
+
# frozen early lexical rescue
|
| 79 |
+
qlex=np.zeros(M,np.float32);qlex[q.indices]=idx.idf[q.indices]
|
| 80 |
+
lex1=np.zeros(len(ud),np.float32)
|
| 81 |
+
for i,d in enumerate(ud):
|
| 82 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1];sup=idx.support_indices[a:b]
|
| 83 |
+
raw=float(qlex[sup].sum());den=(1-PRE_B)+PRE_B*(float(idx.doc_lengths[d])/idx.avg_doc_length)
|
| 84 |
+
lex1[i]=raw/(den if den>0 else 1.)
|
| 85 |
+
pre=zscore(tail)+zscore(lex1)
|
| 86 |
+
sel=topk_large(pre,P)
|
| 87 |
+
dd=ud[sel];ts=tail[sel];db=db[sel]
|
| 88 |
+
# mapping routed-doc local index -> pool local index
|
| 89 |
+
poolpos=np.full(len(ud),-1,np.int32); poolpos[sel]=np.arange(len(sel),dtype=np.int32)
|
| 90 |
+
mp=poolpos[inv]
|
| 91 |
+
keep=mp>=0
|
| 92 |
+
mem_pool=mp[keep].astype(np.int32)
|
| 93 |
+
mem_br=br[keep].astype(np.int32)
|
| 94 |
+
mem_ev=branch_ev[keep].astype(np.float32)
|
| 95 |
+
# final current features
|
| 96 |
+
semvec=np.zeros(M,np.float32)
|
| 97 |
+
for t,amp in zip(q.indices,q.data):
|
| 98 |
+
a,b=idx.A.indptr[t],idx.A.indptr[t+1];nb=idx.A.indices[a:b][:SEMK];sv=idx.A.data[a:b][:SEMK]
|
| 99 |
+
if len(nb):semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 100 |
+
qset=set(map(int,q.indices));rare=set(map(int,q.indices[np.argsort(idx.idf[q.indices])[::-1]][:3]));nq=max(1,len(q.indices))
|
| 101 |
+
lx=np.zeros(len(dd),np.float32);sm=np.zeros(len(dd),np.float32);qc=np.zeros(len(dd),np.float32);r3=np.zeros(len(dd),np.float32)
|
| 102 |
+
for i,d in enumerate(dd):
|
| 103 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1];sup=idx.support_indices[a:b]
|
| 104 |
+
sm[i]=float(semvec[sup].sum())
|
| 105 |
+
match=[int(t) for t in sup if int(t) in qset]
|
| 106 |
+
raw=sum(float(idx.idf[t])**IDF_POWER for t in match);den=(1-FINAL_B)+FINAL_B*(float(idx.doc_lengths[d])/idx.avg_doc_length)
|
| 107 |
+
lx[i]=raw/(den if den>0 else 1.);qc[i]=len(match);r3[i]=sum(t in rare for t in match)
|
| 108 |
+
cov=qc/nq;ladj=lx*np.power(np.maximum(cov,1e-6),ALPHA);rarecov=r3/max(1,min(3,nq))
|
| 109 |
+
base_score=zscore(ts)+WLEX*zscore(ladj)+WSEM*zscore(sm)+WRARE*zscore(rarecov)
|
| 110 |
+
|
| 111 |
+
# Build H_j = mean of top 3 E_dj among selected pool documents for branch j.
|
| 112 |
+
# Multiple memberships of same doc+branch should not occur; if they do, keep max.
|
| 113 |
+
branch_pairs={}
|
| 114 |
+
for pi,b,e in zip(mem_pool,mem_br,mem_ev):
|
| 115 |
+
key=(int(b),int(pi))
|
| 116 |
+
if key not in branch_pairs or e>branch_pairs[key]: branch_pairs[key]=float(e)
|
| 117 |
+
byb={}
|
| 118 |
+
for (b,pi),e in branch_pairs.items(): byb.setdefault(b,[]).append((e,pi))
|
| 119 |
+
H={}; bestdoc={}; docs_by_branch={}
|
| 120 |
+
for b,vals in byb.items():
|
| 121 |
+
vals.sort(key=lambda x:x[0],reverse=True)
|
| 122 |
+
top=vals[:3]
|
| 123 |
+
H[b]=float(np.mean([e for e,_ in top]))
|
| 124 |
+
bestdoc[b]=int(max(vals,key=lambda x: float(base_score[x[1]]))[1]) # best final-relevance doc in branch
|
| 125 |
+
docs_by_branch[b]=np.asarray([pi for _,pi in vals],dtype=np.int32)
|
| 126 |
+
ub=np.asarray(sorted(H.keys()),dtype=np.int32)
|
| 127 |
+
h=np.asarray([H[int(b)] for b in ub],dtype=np.float32)
|
| 128 |
+
hnorm=minmax_hi(h)
|
| 129 |
+
bmap={int(b):i for i,b in enumerate(ub)}
|
| 130 |
+
reps=[center_sparse(int(b)) for b in ub]
|
| 131 |
+
C=np.eye(len(ub),dtype=np.float32)
|
| 132 |
+
for i in range(len(ub)):
|
| 133 |
+
for j in range(i+1,len(ub)):
|
| 134 |
+
C[i,j]=C[j,i]=spdot(*reps[i],*reps[j])
|
| 135 |
+
return {'docs':dd,'base':base_score,'tail':ts,'lex':ladj,'sem':sm,'rare':rarecov,
|
| 136 |
+
'route_docs':ud,'branches_dom':db,'ub':ub,'H':h,'Hn':hnorm,'bmap':bmap,'cos':C,
|
| 137 |
+
'bestdoc':bestdoc,'docs_by_branch':docs_by_branch}
|
| 138 |
+
|
| 139 |
+
def plain(p,k=100):
|
| 140 |
+
oo=np.argsort(p['base'])[::-1][:k]
|
| 141 |
+
return p['docs'][oo].tolist()
|
| 142 |
+
|
| 143 |
+
def Dvec(p, selected_bidx):
|
| 144 |
+
C=p['cos']
|
| 145 |
+
if not selected_bidx:return np.zeros(len(C),np.float32)
|
| 146 |
+
si=np.asarray(selected_bidx,np.int32)
|
| 147 |
+
mumun=float(np.mean(C[np.ix_(si,si)]))
|
| 148 |
+
return 1.0+mumun-2.0*np.mean(C[:,si],axis=1)
|
| 149 |
+
|
| 150 |
+
def select_hq_branches(p, topN=20, lam=1.0, nsel=10, pure_div=False):
|
| 151 |
+
if len(p['ub'])==0:return []
|
| 152 |
+
# eligible branches are the top-N robust-quality H_j branches
|
| 153 |
+
order=np.argsort(p['H'])[::-1]
|
| 154 |
+
elig=order[:min(topN,len(order))]
|
| 155 |
+
# first branch = highest H_j
|
| 156 |
+
selected=[int(elig[0])]
|
| 157 |
+
remaining=set(map(int,elig[1:]))
|
| 158 |
+
while remaining and len(selected)<min(nsel,len(elig)):
|
| 159 |
+
rem=np.asarray(sorted(remaining),dtype=np.int32)
|
| 160 |
+
D=Dvec(p,selected)
|
| 161 |
+
dnorm=minmax_hi(D[rem])
|
| 162 |
+
if pure_div:
|
| 163 |
+
val=dnorm
|
| 164 |
+
else:
|
| 165 |
+
h=p['Hn'][rem]
|
| 166 |
+
val=h+float(lam)*dnorm
|
| 167 |
+
pick=int(rem[int(np.argmax(val))])
|
| 168 |
+
selected.append(pick); remaining.remove(pick)
|
| 169 |
+
return selected
|
| 170 |
+
|
| 171 |
+
def rank_hq_oneper(p,topN=20,lam=1.0,pure_div=False,k=100):
|
| 172 |
+
# one best final-score document from each selected high-quality/diverse branch for top 10
|
| 173 |
+
sb=select_hq_branches(p,topN,lam,10,pure_div)
|
| 174 |
+
chosen=[]; used=set()
|
| 175 |
+
for bi in sb:
|
| 176 |
+
b=int(p['ub'][bi]); pi=int(p['bestdoc'][b])
|
| 177 |
+
if pi not in used: chosen.append(pi); used.add(pi)
|
| 178 |
+
# if fewer than 10, fill by ordinary score
|
| 179 |
+
for pi in np.argsort(p['base'])[::-1]:
|
| 180 |
+
pi=int(pi)
|
| 181 |
+
if len(chosen)>=10:break
|
| 182 |
+
if pi not in used: chosen.append(pi);used.add(pi)
|
| 183 |
+
# rest by ordinary score
|
| 184 |
+
for pi in np.argsort(p['base'])[::-1]:
|
| 185 |
+
pi=int(pi)
|
| 186 |
+
if len(chosen)>=k:break
|
| 187 |
+
if pi not in used: chosen.append(pi);used.add(pi)
|
| 188 |
+
return p['docs'][np.asarray(chosen[:k],dtype=np.int64)].tolist()
|
| 189 |
+
|
| 190 |
+
def rank_hq_softdoc(p,topN=20,lam=.25,k=100):
|
| 191 |
+
# restrict diversity bonus to high-quality branches; repeated branches allowed.
|
| 192 |
+
# docs outside HQ set retain pure relevance and are still eligible.
|
| 193 |
+
base=p['base']; n=len(base); order=np.argsort(base)[::-1]
|
| 194 |
+
first=int(order[0]); chosen=[first]; used={first}
|
| 195 |
+
elig_order=np.argsort(p['H'])[::-1][:min(topN,len(p['H']))]
|
| 196 |
+
eligset=set(map(int,elig_order))
|
| 197 |
+
# branch memberships for each pool doc: use all high-quality branches the doc belongs to
|
| 198 |
+
doc_hq=[[] for _ in range(n)]
|
| 199 |
+
for bi in elig_order:
|
| 200 |
+
b=int(p['ub'][bi])
|
| 201 |
+
for pi in p['docs_by_branch'][b]: doc_hq[int(pi)].append(int(bi))
|
| 202 |
+
# selected branch representation starts with highest-quality HQ branch supporting first, if any
|
| 203 |
+
selected=[]
|
| 204 |
+
if doc_hq[first]:
|
| 205 |
+
selected=[max(doc_hq[first], key=lambda bi: float(p['H'][bi]))]
|
| 206 |
+
for _ in range(1,min(10,k,n)):
|
| 207 |
+
rem=np.asarray([i for i in range(n) if i not in used],dtype=np.int32)
|
| 208 |
+
if not len(rem):break
|
| 209 |
+
D=Dvec(p,selected) if selected else np.zeros(len(p['ub']),np.float32)
|
| 210 |
+
# normalize only across eligible branches
|
| 211 |
+
if len(elig_order):
|
| 212 |
+
ed=minmax_hi(D[elig_order]); dn={int(bi):float(v) for bi,v in zip(elig_order,ed)}
|
| 213 |
+
else: dn={}
|
| 214 |
+
# relevance minmax across remaining top pool; high = good
|
| 215 |
+
rn=minmax_hi(base[rem])
|
| 216 |
+
bonus=np.zeros(len(rem),np.float32)
|
| 217 |
+
for k2,pi in enumerate(rem):
|
| 218 |
+
if doc_hq[int(pi)]: bonus[k2]=max(dn.get(bi,0.0) for bi in doc_hq[int(pi)])
|
| 219 |
+
val=rn+float(lam)*bonus
|
| 220 |
+
pi=int(rem[int(np.argmax(val))]); chosen.append(pi); used.add(pi)
|
| 221 |
+
if doc_hq[pi]:
|
| 222 |
+
# add the supporting HQ branch with max diversity, ties quality
|
| 223 |
+
bi=max(doc_hq[pi],key=lambda x:(dn.get(x,0.0),float(p['H'][x])))
|
| 224 |
+
selected.append(int(bi))
|
| 225 |
+
for pi in order:
|
| 226 |
+
pi=int(pi)
|
| 227 |
+
if len(chosen)>=k:break
|
| 228 |
+
if pi not in used:chosen.append(pi);used.add(pi)
|
| 229 |
+
return p['docs'][np.asarray(chosen[:k],dtype=np.int64)].tolist()
|
| 230 |
+
|
| 231 |
+
def evaluate(ds,packs,ranker,**kw):
|
| 232 |
+
run={};route_num=pool_num=den=0;cands=[]
|
| 233 |
+
for qid,p in packs.items():
|
| 234 |
+
rr=[] if p is None else ranker(p,**kw)
|
| 235 |
+
run[str(qid)]=[str(idx.doc_ids[int(d)]) for d in rr]
|
| 236 |
+
if p is not None:
|
| 237 |
+
route={str(idx.doc_ids[int(d)]) for d in p['route_docs']};pool={str(idx.doc_ids[int(d)]) for d in p['docs']}
|
| 238 |
+
pos={str(d) for d,v in ds.qrels[qid].items() if v>0};den+=len(pos);route_num+=sum(d in route for d in pos);pool_num+=sum(d in pool for d in pos);cands.append(len(route))
|
| 239 |
+
m=evaluate_run(run,ds.qrels,ks=(10,100),ndcg_k=10,mrr_k=10,exp_gain=False)
|
| 240 |
+
m['route_recall_micro']=route_num/max(1,den);m['pool_recall_micro']=pool_num/max(1,den);m['avg_candidates']=float(np.mean(cands)) if cands else 0
|
| 241 |
+
return m
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
ds=load_beir_directory(ROOT,'test')
|
| 245 |
+
allres={'dataset':'TREC-COVID','experiment':'Final whole-document binary lexical IDF power; all else fixed','variants':{}}
|
| 246 |
+
for power in [2,3,4]:
|
| 247 |
+
IDF_POWER=power
|
| 248 |
+
packs={};times=[]
|
| 249 |
+
for i,qid in enumerate(ds.qrels):
|
| 250 |
+
t=time.perf_counter(); packs[qid]=prepare(ds.queries[qid]); times.append((time.perf_counter()-t)*1000)
|
| 251 |
+
plain_m=evaluate(ds,packs,plain)
|
| 252 |
+
hq_m=evaluate(ds,packs,rank_hq_softdoc,topN=10,lam=.1)
|
| 253 |
+
allres['variants'][f'idf{power}_plain']=plain_m
|
| 254 |
+
allres['variants'][f'idf{power}_hqdiv']=hq_m
|
| 255 |
+
allres.setdefault('timing',{})[f'idf{power}_prepare_median_ms']=float(np.median(times))
|
| 256 |
+
allres['timing'][f'idf{power}_prepare_p95_ms']=float(np.percentile(times,95))
|
| 257 |
+
print('POWER',power,'PLAIN',plain_m,flush=True)
|
| 258 |
+
print('POWER',power,'HQDIV',hq_m,flush=True)
|
| 259 |
+
out='/mnt/data/treccovid_idf_power_2_3_4.json'
|
| 260 |
+
json.dump(allres,open(out,'w'),indent=2)
|
| 261 |
+
print('saved',out,flush=True)
|
experiments/beir/treccovid_local_baselines_exact_history.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,time,json,math
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy import sparse
|
| 4 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 5 |
+
sys.path.insert(0,'/mnt/data/work_code/geomretrieval_msmarco_scale_codebase/original_v0')
|
| 6 |
+
from geomretrieval import GeometricIndex, load_beir_directory, evaluate_run
|
| 7 |
+
ROOT='/mnt/data/work_treccovid/trec-covid'; IDX='/mnt/data/treccovid_geom_index'
|
| 8 |
+
ds=load_beir_directory(ROOT,'test'); idx=GeometricIndex.load(IDX)
|
| 9 |
+
# Exact TF-IDF cosine
|
| 10 |
+
run={}; times=[]
|
| 11 |
+
for qid in ds.qrels:
|
| 12 |
+
q=idx._query_vector(ds.queries[qid])
|
| 13 |
+
t=time.perf_counter(); s=np.asarray(idx.X @ q.T).ravel(); times.append((time.perf_counter()-t)*1000)
|
| 14 |
+
k=min(100,len(s)); ii=np.argpartition(s,-k)[-k:]; ii=ii[np.argsort(s[ii])[::-1]]
|
| 15 |
+
run[str(qid)]=[str(idx.doc_ids[int(i)]) for i in ii]
|
| 16 |
+
mtf=evaluate_run(run,ds.qrels,ks=(10,100),ndcg_k=10,mrr_k=10,exp_gain=False)
|
| 17 |
+
mtf['median_ms']=float(np.median(times)); mtf['p95_ms']=float(np.percentile(times,95))
|
| 18 |
+
print('TFIDF',mtf,flush=True)
|
| 19 |
+
# Count matrix with frozen vocabulary/tokenizer
|
| 20 |
+
vec=CountVectorizer(vocabulary=idx.vectorizer.vocabulary_,lowercase=idx.config.lowercase,token_pattern=idx.config.token_pattern,dtype=np.float32)
|
| 21 |
+
t=time.perf_counter(); C=vec.transform(ds.corpus_texts).tocsr(); build=time.perf_counter()-t
|
| 22 |
+
length=np.asarray(C.sum(axis=1)).ravel().astype(np.float32); avdl=float(length.mean()); Cc=C.tocsc(); N=C.shape[0]
|
| 23 |
+
df=np.diff(Cc.indptr).astype(np.float64); idf=np.log((N-df+0.5)/(df+0.5)+1.0).astype(np.float32)
|
| 24 |
+
k1=.9;b=.4
|
| 25 |
+
run={};times=[]
|
| 26 |
+
for qid in ds.qrels:
|
| 27 |
+
q=vec.transform([ds.queries[qid]]).tocsr(); terms=q.indices
|
| 28 |
+
t=time.perf_counter(); score=np.zeros(N,np.float32)
|
| 29 |
+
for term in terms:
|
| 30 |
+
a,bb=Cc.indptr[term],Cc.indptr[term+1]; docs=Cc.indices[a:bb]; tf=Cc.data[a:bb]
|
| 31 |
+
den=tf+k1*(1-b+b*length[docs]/avdl)
|
| 32 |
+
score[docs]+=idf[term]*(tf*(k1+1)/den)
|
| 33 |
+
times.append((time.perf_counter()-t)*1000)
|
| 34 |
+
k=min(100,N);ii=np.argpartition(score,-k)[-k:];ii=ii[np.argsort(score[ii])[::-1]]
|
| 35 |
+
run[str(qid)]=[str(idx.doc_ids[int(i)]) for i in ii]
|
| 36 |
+
mb=evaluate_run(run,ds.qrels,ks=(10,100),ndcg_k=10,mrr_k=10,exp_gain=False)
|
| 37 |
+
mb['median_ms_effectiveness_impl']=float(np.median(times));mb['p95_ms_effectiveness_impl']=float(np.percentile(times,95));mb['count_build_s']=build
|
| 38 |
+
print('BM25',mb,flush=True)
|
| 39 |
+
out={'tfidf':mtf,'bm25':mb}
|
| 40 |
+
json.dump(out,open('/mnt/data/treccovid_local_baselines.json','w'),indent=2)
|
experiments/beir/treccovid_pool_sweep_exact_history.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json,math,os
|
| 3 |
+
import numpy as np
|
| 4 |
+
sys.path.insert(0,'/mnt/data/work_code/geomretrieval_msmarco_scale_codebase/original_v0')
|
| 5 |
+
from geomretrieval import GeometricIndex, load_beir_directory, evaluate_run
|
| 6 |
+
|
| 7 |
+
IDX='/mnt/data/treccovid_geom_index'
|
| 8 |
+
ROOT='/mnt/data/work_treccovid/trec-covid'
|
| 9 |
+
idx=GeometricIndex.load(IDX); M=idx.vocab_size
|
| 10 |
+
P=int(os.environ.get("POOL_P","100")); GAMMA=.25; LAM_M=.125; PRE_B=.2; FINAL_B=.1; ALPHA=.25
|
| 11 |
+
WLEX=4.0; WSEM=.3; WRARE=1.0; SEMK=16; EPS=1e-8
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def zscore(x):
|
| 15 |
+
x=np.asarray(x,np.float32)
|
| 16 |
+
if not len(x): return x
|
| 17 |
+
sd=float(x.std())
|
| 18 |
+
return np.zeros_like(x) if sd<1e-8 else (x-float(x.mean()))/sd
|
| 19 |
+
|
| 20 |
+
def minmax_hi(x):
|
| 21 |
+
x=np.asarray(x,np.float32)
|
| 22 |
+
if not len(x): return x
|
| 23 |
+
mn=float(x.min()); mx=float(x.max()); den=mx-mn
|
| 24 |
+
return np.ones_like(x) if den<1e-8 else (x-mn)/den
|
| 25 |
+
|
| 26 |
+
def topk_large(score,k):
|
| 27 |
+
n=len(score); k=min(k,n)
|
| 28 |
+
if k<=0:return np.empty(0,np.int64)
|
| 29 |
+
if n<=k:return np.argsort(score)[::-1]
|
| 30 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 31 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 32 |
+
|
| 33 |
+
def center_sparse(j):
|
| 34 |
+
t=idx.center_terms[j]; v=idx.center_values[j]; ok=t>=0
|
| 35 |
+
t=t[ok].astype(np.int32); v=v[ok].astype(np.float32)
|
| 36 |
+
n=float(np.linalg.norm(v))
|
| 37 |
+
if n>0:v=v/n
|
| 38 |
+
oo=np.argsort(t)
|
| 39 |
+
return t[oo],v[oo]
|
| 40 |
+
|
| 41 |
+
def spdot(a_t,a_v,b_t,b_v):
|
| 42 |
+
i=j=0;s=0.0
|
| 43 |
+
while i<len(a_t) and j<len(b_t):
|
| 44 |
+
if a_t[i]==b_t[j]:s+=float(a_v[i])*float(b_v[j]);i+=1;j+=1
|
| 45 |
+
elif a_t[i]<b_t[j]:i+=1
|
| 46 |
+
else:j+=1
|
| 47 |
+
return s
|
| 48 |
+
|
| 49 |
+
def prepare(text):
|
| 50 |
+
q=idx._query_vector(text)
|
| 51 |
+
if q.nnz==0:return None
|
| 52 |
+
qd=np.zeros(M,np.float32); qd[q.indices]=q.data
|
| 53 |
+
rt,rv,qt=idx._expanded_route(q)
|
| 54 |
+
if not len(rt):return None
|
| 55 |
+
rd=np.zeros(M,np.float32);rd[rt]=rv
|
| 56 |
+
pieces=[]
|
| 57 |
+
for j in rt:
|
| 58 |
+
a,b=idx.branch_offsets[j],idx.branch_offsets[j+1]
|
| 59 |
+
if b>a:pieces.append(idx.branch_order[a:b])
|
| 60 |
+
if not pieces:return None
|
| 61 |
+
fp=np.concatenate(pieces).astype(np.int64,copy=False)
|
| 62 |
+
docs=(fp//idx.config.F).astype(np.int64); slots=(fp%idx.config.F).astype(np.int64)
|
| 63 |
+
br=idx.branches[docs,slots]
|
| 64 |
+
terms=idx.res_terms[docs,slots];valid=terms>=0;safe=np.where(valid,terms,0);qv=qd[safe]
|
| 65 |
+
local=np.sum(idx.res_reliability[docs,slots].astype(np.float32)*(qv-idx.res_center_values[docs,slots])*idx.res_signs[docs,slots].astype(np.float32)*valid,axis=1)
|
| 66 |
+
sig=np.sum((qv*qv)*valid,axis=1)
|
| 67 |
+
cons=idx.memberships[docs,slots]*rd[br]
|
| 68 |
+
branch_ev=(cons*local*np.power(np.maximum(sig,0),GAMMA)).astype(np.float32) # E_dj exactly
|
| 69 |
+
base=cons*local
|
| 70 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 71 |
+
tail=np.bincount(inv,weights=branch_ev,minlength=len(ud)).astype(np.float32)
|
| 72 |
+
tail += LAM_M*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 73 |
+
# dominant routed branch retained for diagnostics
|
| 74 |
+
bestv=np.full(len(ud),-1e30,np.float32);db=np.full(len(ud),-1,np.int32)
|
| 75 |
+
for p,u in enumerate(inv):
|
| 76 |
+
if cons[p]>bestv[u]:bestv[u]=cons[p];db[u]=int(br[p])
|
| 77 |
+
# frozen early lexical rescue
|
| 78 |
+
qlex=np.zeros(M,np.float32);qlex[q.indices]=idx.idf[q.indices]
|
| 79 |
+
lex1=np.zeros(len(ud),np.float32)
|
| 80 |
+
for i,d in enumerate(ud):
|
| 81 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1];sup=idx.support_indices[a:b]
|
| 82 |
+
raw=float(qlex[sup].sum());den=(1-PRE_B)+PRE_B*(float(idx.doc_lengths[d])/idx.avg_doc_length)
|
| 83 |
+
lex1[i]=raw/(den if den>0 else 1.)
|
| 84 |
+
pre=zscore(tail)+zscore(lex1)
|
| 85 |
+
sel=topk_large(pre,P)
|
| 86 |
+
dd=ud[sel];ts=tail[sel];db=db[sel]
|
| 87 |
+
# mapping routed-doc local index -> pool local index
|
| 88 |
+
poolpos=np.full(len(ud),-1,np.int32); poolpos[sel]=np.arange(len(sel),dtype=np.int32)
|
| 89 |
+
mp=poolpos[inv]
|
| 90 |
+
keep=mp>=0
|
| 91 |
+
mem_pool=mp[keep].astype(np.int32)
|
| 92 |
+
mem_br=br[keep].astype(np.int32)
|
| 93 |
+
mem_ev=branch_ev[keep].astype(np.float32)
|
| 94 |
+
# final current features
|
| 95 |
+
semvec=np.zeros(M,np.float32)
|
| 96 |
+
for t,amp in zip(q.indices,q.data):
|
| 97 |
+
a,b=idx.A.indptr[t],idx.A.indptr[t+1];nb=idx.A.indices[a:b][:SEMK];sv=idx.A.data[a:b][:SEMK]
|
| 98 |
+
if len(nb):semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 99 |
+
qset=set(map(int,q.indices));rare=set(map(int,q.indices[np.argsort(idx.idf[q.indices])[::-1]][:3]));nq=max(1,len(q.indices))
|
| 100 |
+
lx=np.zeros(len(dd),np.float32);sm=np.zeros(len(dd),np.float32);qc=np.zeros(len(dd),np.float32);r3=np.zeros(len(dd),np.float32)
|
| 101 |
+
for i,d in enumerate(dd):
|
| 102 |
+
a,b=idx.support_indptr[d],idx.support_indptr[d+1];sup=idx.support_indices[a:b]
|
| 103 |
+
sm[i]=float(semvec[sup].sum())
|
| 104 |
+
match=[int(t) for t in sup if int(t) in qset]
|
| 105 |
+
raw=sum(float(idx.idf[t])**2 for t in match);den=(1-FINAL_B)+FINAL_B*(float(idx.doc_lengths[d])/idx.avg_doc_length)
|
| 106 |
+
lx[i]=raw/(den if den>0 else 1.);qc[i]=len(match);r3[i]=sum(t in rare for t in match)
|
| 107 |
+
cov=qc/nq;ladj=lx*np.power(np.maximum(cov,1e-6),ALPHA);rarecov=r3/max(1,min(3,nq))
|
| 108 |
+
base_score=zscore(ts)+WLEX*zscore(ladj)+WSEM*zscore(sm)+WRARE*zscore(rarecov)
|
| 109 |
+
|
| 110 |
+
# Build H_j = mean of top 3 E_dj among selected pool documents for branch j.
|
| 111 |
+
# Multiple memberships of same doc+branch should not occur; if they do, keep max.
|
| 112 |
+
branch_pairs={}
|
| 113 |
+
for pi,b,e in zip(mem_pool,mem_br,mem_ev):
|
| 114 |
+
key=(int(b),int(pi))
|
| 115 |
+
if key not in branch_pairs or e>branch_pairs[key]: branch_pairs[key]=float(e)
|
| 116 |
+
byb={}
|
| 117 |
+
for (b,pi),e in branch_pairs.items(): byb.setdefault(b,[]).append((e,pi))
|
| 118 |
+
H={}; bestdoc={}; docs_by_branch={}
|
| 119 |
+
for b,vals in byb.items():
|
| 120 |
+
vals.sort(key=lambda x:x[0],reverse=True)
|
| 121 |
+
top=vals[:3]
|
| 122 |
+
H[b]=float(np.mean([e for e,_ in top]))
|
| 123 |
+
bestdoc[b]=int(max(vals,key=lambda x: float(base_score[x[1]]))[1]) # best final-relevance doc in branch
|
| 124 |
+
docs_by_branch[b]=np.asarray([pi for _,pi in vals],dtype=np.int32)
|
| 125 |
+
ub=np.asarray(sorted(H.keys()),dtype=np.int32)
|
| 126 |
+
h=np.asarray([H[int(b)] for b in ub],dtype=np.float32)
|
| 127 |
+
hnorm=minmax_hi(h)
|
| 128 |
+
bmap={int(b):i for i,b in enumerate(ub)}
|
| 129 |
+
reps=[center_sparse(int(b)) for b in ub]
|
| 130 |
+
C=np.eye(len(ub),dtype=np.float32)
|
| 131 |
+
for i in range(len(ub)):
|
| 132 |
+
for j in range(i+1,len(ub)):
|
| 133 |
+
C[i,j]=C[j,i]=spdot(*reps[i],*reps[j])
|
| 134 |
+
return {'docs':dd,'base':base_score,'tail':ts,'lex':ladj,'sem':sm,'rare':rarecov,
|
| 135 |
+
'route_docs':ud,'branches_dom':db,'ub':ub,'H':h,'Hn':hnorm,'bmap':bmap,'cos':C,
|
| 136 |
+
'bestdoc':bestdoc,'docs_by_branch':docs_by_branch}
|
| 137 |
+
|
| 138 |
+
def plain(p,k=100):
|
| 139 |
+
oo=np.argsort(p['base'])[::-1][:k]
|
| 140 |
+
return p['docs'][oo].tolist()
|
| 141 |
+
|
| 142 |
+
def Dvec(p, selected_bidx):
|
| 143 |
+
C=p['cos']
|
| 144 |
+
if not selected_bidx:return np.zeros(len(C),np.float32)
|
| 145 |
+
si=np.asarray(selected_bidx,np.int32)
|
| 146 |
+
mumun=float(np.mean(C[np.ix_(si,si)]))
|
| 147 |
+
return 1.0+mumun-2.0*np.mean(C[:,si],axis=1)
|
| 148 |
+
|
| 149 |
+
def select_hq_branches(p, topN=20, lam=1.0, nsel=10, pure_div=False):
|
| 150 |
+
if len(p['ub'])==0:return []
|
| 151 |
+
# eligible branches are the top-N robust-quality H_j branches
|
| 152 |
+
order=np.argsort(p['H'])[::-1]
|
| 153 |
+
elig=order[:min(topN,len(order))]
|
| 154 |
+
# first branch = highest H_j
|
| 155 |
+
selected=[int(elig[0])]
|
| 156 |
+
remaining=set(map(int,elig[1:]))
|
| 157 |
+
while remaining and len(selected)<min(nsel,len(elig)):
|
| 158 |
+
rem=np.asarray(sorted(remaining),dtype=np.int32)
|
| 159 |
+
D=Dvec(p,selected)
|
| 160 |
+
dnorm=minmax_hi(D[rem])
|
| 161 |
+
if pure_div:
|
| 162 |
+
val=dnorm
|
| 163 |
+
else:
|
| 164 |
+
h=p['Hn'][rem]
|
| 165 |
+
val=h+float(lam)*dnorm
|
| 166 |
+
pick=int(rem[int(np.argmax(val))])
|
| 167 |
+
selected.append(pick); remaining.remove(pick)
|
| 168 |
+
return selected
|
| 169 |
+
|
| 170 |
+
def rank_hq_oneper(p,topN=20,lam=1.0,pure_div=False,k=100):
|
| 171 |
+
# one best final-score document from each selected high-quality/diverse branch for top 10
|
| 172 |
+
sb=select_hq_branches(p,topN,lam,10,pure_div)
|
| 173 |
+
chosen=[]; used=set()
|
| 174 |
+
for bi in sb:
|
| 175 |
+
b=int(p['ub'][bi]); pi=int(p['bestdoc'][b])
|
| 176 |
+
if pi not in used: chosen.append(pi); used.add(pi)
|
| 177 |
+
# if fewer than 10, fill by ordinary score
|
| 178 |
+
for pi in np.argsort(p['base'])[::-1]:
|
| 179 |
+
pi=int(pi)
|
| 180 |
+
if len(chosen)>=10:break
|
| 181 |
+
if pi not in used: chosen.append(pi);used.add(pi)
|
| 182 |
+
# rest by ordinary score
|
| 183 |
+
for pi in np.argsort(p['base'])[::-1]:
|
| 184 |
+
pi=int(pi)
|
| 185 |
+
if len(chosen)>=k:break
|
| 186 |
+
if pi not in used: chosen.append(pi);used.add(pi)
|
| 187 |
+
return p['docs'][np.asarray(chosen[:k],dtype=np.int64)].tolist()
|
| 188 |
+
|
| 189 |
+
def rank_hq_softdoc(p,topN=20,lam=.25,k=100):
|
| 190 |
+
# restrict diversity bonus to high-quality branches; repeated branches allowed.
|
| 191 |
+
# docs outside HQ set retain pure relevance and are still eligible.
|
| 192 |
+
base=p['base']; n=len(base); order=np.argsort(base)[::-1]
|
| 193 |
+
first=int(order[0]); chosen=[first]; used={first}
|
| 194 |
+
elig_order=np.argsort(p['H'])[::-1][:min(topN,len(p['H']))]
|
| 195 |
+
eligset=set(map(int,elig_order))
|
| 196 |
+
# branch memberships for each pool doc: use all high-quality branches the doc belongs to
|
| 197 |
+
doc_hq=[[] for _ in range(n)]
|
| 198 |
+
for bi in elig_order:
|
| 199 |
+
b=int(p['ub'][bi])
|
| 200 |
+
for pi in p['docs_by_branch'][b]: doc_hq[int(pi)].append(int(bi))
|
| 201 |
+
# selected branch representation starts with highest-quality HQ branch supporting first, if any
|
| 202 |
+
selected=[]
|
| 203 |
+
if doc_hq[first]:
|
| 204 |
+
selected=[max(doc_hq[first], key=lambda bi: float(p['H'][bi]))]
|
| 205 |
+
for _ in range(1,min(10,k,n)):
|
| 206 |
+
rem=np.asarray([i for i in range(n) if i not in used],dtype=np.int32)
|
| 207 |
+
if not len(rem):break
|
| 208 |
+
D=Dvec(p,selected) if selected else np.zeros(len(p['ub']),np.float32)
|
| 209 |
+
# normalize only across eligible branches
|
| 210 |
+
if len(elig_order):
|
| 211 |
+
ed=minmax_hi(D[elig_order]); dn={int(bi):float(v) for bi,v in zip(elig_order,ed)}
|
| 212 |
+
else: dn={}
|
| 213 |
+
# relevance minmax across remaining top pool; high = good
|
| 214 |
+
rn=minmax_hi(base[rem])
|
| 215 |
+
bonus=np.zeros(len(rem),np.float32)
|
| 216 |
+
for k2,pi in enumerate(rem):
|
| 217 |
+
if doc_hq[int(pi)]: bonus[k2]=max(dn.get(bi,0.0) for bi in doc_hq[int(pi)])
|
| 218 |
+
val=rn+float(lam)*bonus
|
| 219 |
+
pi=int(rem[int(np.argmax(val))]); chosen.append(pi); used.add(pi)
|
| 220 |
+
if doc_hq[pi]:
|
| 221 |
+
# add the supporting HQ branch with max diversity, ties quality
|
| 222 |
+
bi=max(doc_hq[pi],key=lambda x:(dn.get(x,0.0),float(p['H'][x])))
|
| 223 |
+
selected.append(int(bi))
|
| 224 |
+
for pi in order:
|
| 225 |
+
pi=int(pi)
|
| 226 |
+
if len(chosen)>=k:break
|
| 227 |
+
if pi not in used:chosen.append(pi);used.add(pi)
|
| 228 |
+
return p['docs'][np.asarray(chosen[:k],dtype=np.int64)].tolist()
|
| 229 |
+
|
| 230 |
+
def evaluate(ds,packs,ranker,**kw):
|
| 231 |
+
run={};route_num=pool_num=den=0;cands=[]
|
| 232 |
+
for qid,p in packs.items():
|
| 233 |
+
rr=[] if p is None else ranker(p,**kw)
|
| 234 |
+
run[str(qid)]=[str(idx.doc_ids[int(d)]) for d in rr]
|
| 235 |
+
if p is not None:
|
| 236 |
+
route={str(idx.doc_ids[int(d)]) for d in p['route_docs']};pool={str(idx.doc_ids[int(d)]) for d in p['docs']}
|
| 237 |
+
pos={str(d) for d,v in ds.qrels[qid].items() if v>0};den+=len(pos);route_num+=sum(d in route for d in pos);pool_num+=sum(d in pool for d in pos);cands.append(len(route))
|
| 238 |
+
m=evaluate_run(run,ds.qrels,ks=(10,100),ndcg_k=10,mrr_k=10,exp_gain=False)
|
| 239 |
+
m['route_recall_micro']=route_num/max(1,den);m['pool_recall_micro']=pool_num/max(1,den);m['avg_candidates']=float(np.mean(cands)) if cands else 0
|
| 240 |
+
return m
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
ds=load_beir_directory(ROOT,'test')
|
| 244 |
+
packs={}; prep=[]
|
| 245 |
+
for i,qid in enumerate(ds.qrels):
|
| 246 |
+
t=time.perf_counter(); packs[qid]=prepare(ds.queries[qid]); prep.append((time.perf_counter()-t)*1000)
|
| 247 |
+
if (i+1)%10==0: print('prepared',i+1,flush=True)
|
| 248 |
+
|
| 249 |
+
def eval_timed(name,fn,**kw):
|
| 250 |
+
# rank timing only on prepared packs
|
| 251 |
+
rt=[]
|
| 252 |
+
for qid,p in packs.items():
|
| 253 |
+
t=time.perf_counter(); _=[] if p is None else fn(p,**kw); rt.append((time.perf_counter()-t)*1000)
|
| 254 |
+
m=evaluate(ds,packs,fn,**kw)
|
| 255 |
+
m['rank_median_ms']=float(np.median(rt)); m['rank_p95_ms']=float(np.percentile(rt,95))
|
| 256 |
+
print(name,m,flush=True); return m
|
| 257 |
+
|
| 258 |
+
res={'dataset':'TREC-COVID','P':P,'branch_quality':'mean top-3 E_dj among P pool docs; E_dj=m_dj*rho_q(j)*L_dj*C_dj^gamma',
|
| 259 |
+
'selection':'top-10 branches by H_j; soft document diversity lambda_D=0.1; IDF^2 final lexical term',
|
| 260 |
+
'timing':{'prepare_median_ms':float(np.median(prep)),'prepare_p95_ms':float(np.percentile(prep,95))},'variants':{}}
|
| 261 |
+
res['variants']['current_z']=eval_timed('current_z',plain)
|
| 262 |
+
res['variants']['hq10_softdoc_l0.1']=eval_timed('hq10_softdoc_l0.1',rank_hq_softdoc,topN=10,lam=0.1)
|
| 263 |
+
out=f'/mnt/data/treccovid_p{P}_sweep_result.json'
|
| 264 |
+
json.dump(res,open(out,'w'),indent=2)
|
| 265 |
+
print('saved',out,flush=True)
|
experiments/msmarco_scale/bench_fast.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,time
|
| 2 |
+
sys.path.insert(0,'/mnt/data')
|
| 3 |
+
from msmarco_full_search_fast import FullIndex,load_query_texts
|
| 4 |
+
ids=['300674','125705','94798','9083','174249']; txt=load_query_texts(ids); idx=FullIndex(); print('loaded')
|
| 5 |
+
for rep in range(2):
|
| 6 |
+
for q in ids:
|
| 7 |
+
t=time.perf_counter(); p=idx.prepare(txt[q],20); r=idx.rank_h(p,0,100); print(rep,q,(time.perf_counter()-t)*1000,p['candidate_memberships'],p['candidate_docs'],r[:5],flush=True)
|
experiments/msmarco_scale/bench_post.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,time,json, numpy as np
|
| 2 |
+
sys.path.insert(0,'/mnt/data')
|
| 3 |
+
from msmarco_full_search_post import FullIndex, load_query_texts
|
| 4 |
+
ids=['300674','125705','94798','9083','174249']
|
| 5 |
+
txt=load_query_texts(ids)
|
| 6 |
+
idx=FullIndex(); print('loaded')
|
| 7 |
+
# compile/warm
|
| 8 |
+
for rep in range(2):
|
| 9 |
+
for q in ids:
|
| 10 |
+
t=time.perf_counter(); p=idx.prepare(txt[q],hmax=20); r=idx.rank_h(p,0,100); dt=(time.perf_counter()-t)*1000
|
| 11 |
+
print(rep,q,dt,p['candidate_memberships'],p['candidate_docs'],r[:5],flush=True)
|
experiments/msmarco_scale/build_branch_sorted_layout.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import numpy as np,time,json,os
|
| 3 |
+
IDX=Path('/mnt/data/msmarco_scale_work/full_index'); N=8_841_823; F=4; S=16
|
| 4 |
+
bo=np.memmap(IDX/'branch_order.u32',np.uint32,'r'); n=len(bo)
|
| 5 |
+
mem=np.memmap(IDX/'memberships.f32',np.float32,'r',shape=(N,F)); rt=np.memmap(IDX/'res_terms.u16',np.uint16,'r',shape=(N,F,S)); sb=np.memmap(IDX/'signbits.u16',np.uint16,'r',shape=(N,F))
|
| 6 |
+
pd=np.memmap(IDX/'post_doc.u32',np.uint32,'w+',shape=(n,)); pm=np.memmap(IDX/'post_membership.f32',np.float32,'w+',shape=(n,)); pr=np.memmap(IDX/'post_res_terms.u16',np.uint16,'w+',shape=(n,S)); ps=np.memmap(IDX/'post_signbits.u16',np.uint16,'w+',shape=(n,))
|
| 7 |
+
t=time.time(); block=500_000
|
| 8 |
+
for a in range(0,n,block):
|
| 9 |
+
b=min(n,a+block); fp=np.asarray(bo[a:b],np.uint32); docs=fp//F; slots=(fp%F).astype(np.uint8)
|
| 10 |
+
pd[a:b]=docs; pm[a:b]=mem[docs,slots]; pr[a:b]=rt[docs,slots]; ps[a:b]=sb[docs,slots]
|
| 11 |
+
if (a//block)%10==0: print(a,b,'/',n,'sec',time.time()-t,flush=True)
|
| 12 |
+
pd.flush();pm.flush();pr.flush();ps.flush()
|
| 13 |
+
print('DONE',n,'seconds',time.time()-t,flush=True)
|
experiments/msmarco_scale/build_global_support.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import numpy as np, json, time, os
|
| 3 |
+
I=Path('/mnt/data/msmarco_scale_work/full_index'); N=8841823
|
| 4 |
+
total=0; metas=[]
|
| 5 |
+
for sid in range(36):
|
| 6 |
+
m=json.load(open(I/f'shard_{sid:04d}.json')); metas.append(m); total+=int(m['nnz'])
|
| 7 |
+
print('total',total,flush=True)
|
| 8 |
+
ids=np.memmap(I/'support_all.u16',np.uint16,'w+',shape=(total,))
|
| 9 |
+
ip=np.memmap(I/'support_all_indptr.u32',np.uint32,'w+',shape=(N+1,))
|
| 10 |
+
pos=0; dpos=0; t=time.time(); ip[0]=0
|
| 11 |
+
for sid,m in enumerate(metas):
|
| 12 |
+
n=int(m['n']); nn=int(m['nnz'])
|
| 13 |
+
si=np.memmap(I/f'support_{sid:04d}.u16',np.uint16,'r',shape=(nn,)); sp=np.memmap(I/f'support_indptr_{sid:04d}.u32',np.uint32,'r',shape=(n+1,))
|
| 14 |
+
ids[pos:pos+nn]=si
|
| 15 |
+
ip[dpos+1:dpos+n+1]=np.asarray(sp[1:],np.uint64)+pos
|
| 16 |
+
pos+=nn; dpos+=n
|
| 17 |
+
print(sid,n,nn,pos,dpos,time.time()-t,flush=True)
|
| 18 |
+
ids.flush();ip.flush(); print('done',pos,dpos,time.time()-t,flush=True)
|
experiments/msmarco_scale/compare_fast_post.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,numpy as np,pandas as pd
|
| 2 |
+
sys.path.insert(0,'/mnt/data')
|
| 3 |
+
import msmarco_full_search_post as slow
|
| 4 |
+
import msmarco_full_search_fast as fast
|
| 5 |
+
tr=pd.read_csv('/mnt/data/dev.tsv',sep='\t',usecols=['query-id']); ids=[str(x) for x in np.unique(tr['query-id'].to_numpy())[:10]]; del tr
|
| 6 |
+
txt=fast.load_query_texts(ids)
|
| 7 |
+
a=slow.FullIndex(); b=fast.FullIndex()
|
| 8 |
+
for q in ids:
|
| 9 |
+
pa=a.prepare(txt[q],20); pb=b.prepare(txt[q],20)
|
| 10 |
+
for h in [0,1,5,10,20]:
|
| 11 |
+
ra=a.rank_h(pa,h,100); rb=b.rank_h(pb,h,100)
|
| 12 |
+
if ra!=rb:
|
| 13 |
+
print('MISMATCH',q,h,next((i for i,(x,y) in enumerate(zip(ra,rb)) if x!=y),None)); break
|
| 14 |
+
else: print('OK',q)
|
experiments/msmarco_scale/msmarco_allroute_diag.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,time,numpy as np,pandas as pd,json
|
| 2 |
+
sys.path.insert(0,'/mnt/data')
|
| 3 |
+
from msmarco_full_search_fastp import FullIndex,load_query_texts,qrels_from_tsv,eval_run,ROOT,WORK,zscore
|
| 4 |
+
NS=500; BIG=1_000_000
|
| 5 |
+
LAM=[2.5,5.0]
|
| 6 |
+
idx=FullIndex(); print('loaded',flush=True)
|
| 7 |
+
tr=pd.read_csv(ROOT/'train.tsv',sep='\t',usecols=['query-id']); uq=np.unique(tr['query-id'].to_numpy()); rng=np.random.default_rng(20260815); ids=[str(x) for x in rng.choice(uq,size=1000,replace=False)[:NS]]; del tr
|
| 8 |
+
texts=load_query_texts(ids); qrels=qrels_from_tsv(ROOT/'train.tsv',ids,positive_only=True)
|
| 9 |
+
w=idx.prepare(texts[ids[0]],hmax=1,pool_max=BIG); del w
|
| 10 |
+
runs={l:{} for l in LAM}; times=[]; cands=[]
|
| 11 |
+
for z,qid in enumerate(ids):
|
| 12 |
+
t=time.perf_counter(); pp=idx.prepare(texts[qid],hmax=1,pool_max=BIG); times.append((time.perf_counter()-t)*1000)
|
| 13 |
+
if pp is None:
|
| 14 |
+
for l in LAM:runs[l][qid]=[]
|
| 15 |
+
else:
|
| 16 |
+
docs=pp['cand_docs']; cands.append(len(docs)); zt=zscore(pp['cand_tail']); zl=zscore(pp['lex']); zs=zscore(pp['sem'])
|
| 17 |
+
for l in LAM:
|
| 18 |
+
sc=zt+l*zl+0.05*zs; ix=np.argpartition(sc,-min(100,len(sc)))[-min(100,len(sc)):]; ix=ix[np.argsort(sc[ix])[::-1]]; runs[l][qid]=[int(x) for x in docs[ix]]
|
| 19 |
+
if (z+1)%50==0: print(z+1,'median_ms',np.median(times),'p95',np.percentile(times,95),'avgcand',np.mean(cands),flush=True)
|
| 20 |
+
for l in LAM: print('LAM',l,eval_run(runs[l],qrels),flush=True)
|
experiments/msmarco_scale/msmarco_amplitude_diag_stage1.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json,gzip,pickle
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np,pandas as pd
|
| 5 |
+
from numba import set_num_threads
|
| 6 |
+
sys.path.insert(0,'/mnt/data')
|
| 7 |
+
import msmarco_early_lex_validation_fast as e
|
| 8 |
+
import msmarco_full_search_uniform1m as m
|
| 9 |
+
|
| 10 |
+
ROOT=m.ROOT; WORK=m.WORK; idx=e.idx; P=2000; M=m.M
|
| 11 |
+
set_num_threads(5)
|
| 12 |
+
OUT=WORK/'amplitude_diag'; OUT.mkdir(exist_ok=True)
|
| 13 |
+
|
| 14 |
+
def topk_desc(score,k):
|
| 15 |
+
n=len(score); k=min(k,n)
|
| 16 |
+
if n<=k: return np.argsort(score)[::-1]
|
| 17 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 18 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 19 |
+
|
| 20 |
+
# exact same deterministic validation query IDs
|
| 21 |
+
tr=pd.read_csv(ROOT/'train.tsv',sep='\t',usecols=['query-id'])
|
| 22 |
+
uq=np.unique(tr['query-id'].to_numpy()); del tr
|
| 23 |
+
rng=np.random.default_rng(20260815)
|
| 24 |
+
ids=[str(x) for x in rng.choice(uq,size=1000,replace=False)]
|
| 25 |
+
texts=m.load_query_texts(ids)
|
| 26 |
+
qrels=m.qrels_from_tsv(ROOT/'train.tsv',ids,positive_only=True)
|
| 27 |
+
|
| 28 |
+
# Warm up
|
| 29 |
+
p=e.prepare_all(texts[ids[0]]); del p
|
| 30 |
+
|
| 31 |
+
# Freeze current direct eta=1 pools. Store the existing final-score components too.
|
| 32 |
+
docs2k=np.empty((len(ids),P),np.uint32)
|
| 33 |
+
tail2k=np.empty((len(ids),P),np.float32)
|
| 34 |
+
lex2k=np.empty((len(ids),P),np.float32)
|
| 35 |
+
sem2k=np.empty((len(ids),P),np.float32)
|
| 36 |
+
valid=np.zeros(len(ids),np.int32)
|
| 37 |
+
route_relhit=pool_relhit=den=0
|
| 38 |
+
start=time.time(); prep=[]
|
| 39 |
+
for qi,qid in enumerate(ids):
|
| 40 |
+
t=time.perf_counter(); p=e.prepare_all(texts[qid]); prep.append((time.perf_counter()-t)*1000)
|
| 41 |
+
if p is None: continue
|
| 42 |
+
sel=topk_desc(m.zscore(p['tail']) + m.zscore(p['lex']), P) # eta=1
|
| 43 |
+
k=len(sel); valid[qi]=k
|
| 44 |
+
docs2k[qi,:k]=p['ud'][sel]; tail2k[qi,:k]=p['tail'][sel]; lex2k[qi,:k]=p['lex'][sel]; sem2k[qi,:k]=p['sem'][sel]
|
| 45 |
+
if k<P:
|
| 46 |
+
docs2k[qi,k:]=np.uint32(0); tail2k[qi,k:]=0; lex2k[qi,k:]=0; sem2k[qi,k:]=0
|
| 47 |
+
rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels)
|
| 48 |
+
ud=p['ud']; poolset=set(map(int,p['ud'][sel].tolist()))
|
| 49 |
+
for d in rels:
|
| 50 |
+
kk=np.searchsorted(ud,d); route_relhit += int(kk<len(ud) and int(ud[kk])==d); pool_relhit += int(d in poolset)
|
| 51 |
+
if (qi+1)%100==0: print('pool',qi+1,'median_ms',float(np.median(prep)),'route',route_relhit/den,'pool',pool_relhit/den,flush=True)
|
| 52 |
+
|
| 53 |
+
np.savez_compressed(OUT/'fixed_eta1_pools.npz', qids=np.asarray(ids), valid=valid, docs=docs2k, tail=tail2k, lex=lex2k, sem=sem2k)
|
| 54 |
+
union=np.unique(np.concatenate([docs2k[i,:valid[i]] for i in range(len(ids))]))
|
| 55 |
+
np.save(OUT/'union_docs.npy',union)
|
| 56 |
+
meta={'n_queries':len(ids),'P':P,'union_docs':int(len(union)),'route_relevant_recall':route_relhit/den,'pool_relevant_recall':pool_relhit/den,'median_prepare_ms':float(np.median(prep)),'seconds':time.time()-start}
|
| 57 |
+
json.dump(meta,open(OUT/'stage1_meta.json','w'),indent=2)
|
| 58 |
+
print('DONE',meta,flush=True)
|
experiments/msmarco_scale/msmarco_amplitude_diag_stage2.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json,gzip
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 6 |
+
from sklearn.preprocessing import normalize
|
| 7 |
+
sys.path.insert(0,'/mnt/data')
|
| 8 |
+
import msmarco_full_search_uniform1m as m
|
| 9 |
+
ROOT=m.ROOT; WORK=m.WORK; OUT=WORK/'amplitude_diag'; IDX=m.IDX
|
| 10 |
+
idx=m.FullIndex()
|
| 11 |
+
union=np.load(OUT/'union_docs.npy',mmap_mode='r')
|
| 12 |
+
# exact support counts from existing binary support index
|
| 13 |
+
sup_ip=idx.sup_ip; sup_ids=idx.sup_ids
|
| 14 |
+
counts=(np.asarray(sup_ip[union.astype(np.int64)+1],dtype=np.uint64)-np.asarray(sup_ip[union.astype(np.int64)],dtype=np.uint64))
|
| 15 |
+
uip=np.empty(len(union)+1,np.uint64); uip[0]=0; np.cumsum(counts,out=uip[1:]); nnz=int(uip[-1])
|
| 16 |
+
np.save(OUT/'exact_tfidf_indptr.npy',uip)
|
| 17 |
+
data=np.memmap(OUT/'exact_tfidf_data.f32',np.float32,'w+',shape=(nnz,))
|
| 18 |
+
cv=idx.cvq; idf=idx.idf
|
| 19 |
+
# Locate all 36 uploaded shards
|
| 20 |
+
shards=[]
|
| 21 |
+
for sid in range(36):
|
| 22 |
+
a=ROOT/f'corpus_{sid:04d}.jsonl.gz'; b=ROOT/f'corpus_{sid:04d}.jsonl(1).gz'
|
| 23 |
+
p=a if a.exists() else b
|
| 24 |
+
if not p.exists(): raise FileNotFoundError((a,b))
|
| 25 |
+
shards.append(p)
|
| 26 |
+
|
| 27 |
+
BATCH=5000; texts=[]; rows=[]; start=time.time(); found=0; verified=0
|
| 28 |
+
|
| 29 |
+
def flush():
|
| 30 |
+
global texts,rows,found,verified
|
| 31 |
+
if not rows:return
|
| 32 |
+
X=cv.transform(texts).tocsr().astype(np.float32)
|
| 33 |
+
X.data*=idf[X.indices]; normalize(X,norm='l2',axis=1,copy=False)
|
| 34 |
+
for bi,ur in enumerate(rows):
|
| 35 |
+
doc=int(union[ur]); ga=int(sup_ip[doc]); gb=int(sup_ip[doc+1]); expected=np.asarray(sup_ids[ga:gb],dtype=np.int32)
|
| 36 |
+
a=int(X.indptr[bi]); b=int(X.indptr[bi+1]); got=X.indices[a:b]
|
| 37 |
+
if len(got)!=len(expected) or not np.array_equal(got,expected):
|
| 38 |
+
raise RuntimeError(f'support mismatch doc={doc} expected={len(expected)} got={len(got)}')
|
| 39 |
+
ua=int(uip[ur]); ub=int(uip[ur+1]); data[ua:ub]=X.data[a:b]
|
| 40 |
+
verified+=1
|
| 41 |
+
found+=len(rows); texts=[]; rows=[]
|
| 42 |
+
|
| 43 |
+
p_union=0
|
| 44 |
+
for sid,path in enumerate(shards):
|
| 45 |
+
lo=sid*250000; hi=min((sid+1)*250000,m.N)
|
| 46 |
+
# target union row range for this shard
|
| 47 |
+
r0=int(np.searchsorted(union,lo)); r1=int(np.searchsorted(union,hi))
|
| 48 |
+
if r0==r1:
|
| 49 |
+
continue
|
| 50 |
+
targets=np.asarray(union[r0:r1],dtype=np.uint32); ti=0
|
| 51 |
+
with gzip.open(path,'rt',encoding='utf-8') as f:
|
| 52 |
+
for local,line in enumerate(f):
|
| 53 |
+
d=lo+local
|
| 54 |
+
if ti>=len(targets): break
|
| 55 |
+
td=int(targets[ti])
|
| 56 |
+
if d<td: continue
|
| 57 |
+
if d!=td: raise RuntimeError((sid,d,td))
|
| 58 |
+
o=json.loads(line); oid=int(o['_id'])
|
| 59 |
+
if oid!=d: raise RuntimeError(f'id mismatch line {d} json {oid}')
|
| 60 |
+
texts.append(((o.get('title') or '')+' '+(o.get('text') or '')).strip()); rows.append(r0+ti); ti+=1
|
| 61 |
+
if len(rows)>=BATCH: flush()
|
| 62 |
+
if ti!=len(targets): raise RuntimeError(f'shard {sid} found {ti}/{len(targets)}')
|
| 63 |
+
flush(); data.flush()
|
| 64 |
+
print('shard',sid,'selected',len(targets),'total_found',found,'elapsed',time.time()-start,flush=True)
|
| 65 |
+
flush(); data.flush()
|
| 66 |
+
meta={'union_docs':int(len(union)),'nnz':nnz,'avg_nnz':float(nnz/len(union)),'verified_docs':verified,'seconds':time.time()-start}
|
| 67 |
+
json.dump(meta,open(OUT/'stage2_meta.json','w'),indent=2)
|
| 68 |
+
print('DONE',meta,flush=True)
|
experiments/msmarco_scale/msmarco_amplitude_diag_stage3.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,json,math,time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np,pandas as pd
|
| 5 |
+
from numba import njit,set_num_threads
|
| 6 |
+
sys.path.insert(0,'/mnt/data')
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
|
| 9 |
+
ROOT=m.ROOT; WORK=m.WORK; OUT=WORK/'amplitude_diag'; IDX=m.IDX; GEOM=m.GEOM
|
| 10 |
+
N=m.N; M=m.M; F=4; S=16; P=2000
|
| 11 |
+
set_num_threads(5)
|
| 12 |
+
idx=m.FullIndex()
|
| 13 |
+
|
| 14 |
+
z=np.load(OUT/'fixed_eta1_pools.npz',allow_pickle=False)
|
| 15 |
+
qids=[str(x) for x in z['qids'].tolist()]; valid=z['valid'].astype(np.int32); docs=z['docs']; tail=z['tail']; lex=z['lex']; sem=z['sem']
|
| 16 |
+
union=np.load(OUT/'union_docs.npy',mmap_mode='r'); uip=np.load(OUT/'exact_tfidf_indptr.npy',mmap_mode='r'); exact=np.memmap(OUT/'exact_tfidf_data.f32',np.float32,'r',shape=(int(uip[-1]),))
|
| 17 |
+
# document-order geometry arrays
|
| 18 |
+
base=WORK/'full_index'
|
| 19 |
+
branches=np.memmap(base/'branches.u16',np.uint16,'r',shape=(N,F))
|
| 20 |
+
memberships=np.memmap(base/'memberships.f32',np.float32,'r',shape=(N,F))
|
| 21 |
+
res_terms=np.memmap(IDX/'res_terms.u16',np.uint16,'r',shape=(N,F,S))
|
| 22 |
+
# query texts/qrels
|
| 23 |
+
texts=m.load_query_texts(qids); qrels=m.qrels_from_tsv(ROOT/'train.tsv',qids,positive_only=True)
|
| 24 |
+
|
| 25 |
+
@njit(cache=False)
|
| 26 |
+
def bsearch_u16(arr,a,b,t):
|
| 27 |
+
lo=np.int64(a); hi=np.int64(b)
|
| 28 |
+
while lo<hi:
|
| 29 |
+
mid=np.int64((lo+hi)//2)
|
| 30 |
+
x=int(arr[mid])
|
| 31 |
+
if x<t: lo=mid+1
|
| 32 |
+
else: hi=mid
|
| 33 |
+
if lo<b and int(arr[lo])==t:return lo
|
| 34 |
+
return -1
|
| 35 |
+
|
| 36 |
+
@njit(cache=False)
|
| 37 |
+
def center_lookup(ctrow,cvrow,t):
|
| 38 |
+
lo=0; hi=len(ctrow)
|
| 39 |
+
while lo<hi:
|
| 40 |
+
md=(lo+hi)//2; x=int(ctrow[md])
|
| 41 |
+
if x==65535 or x>=t: hi=md
|
| 42 |
+
else: lo=md+1
|
| 43 |
+
if lo<len(ctrow) and int(ctrow[lo])==t:return float(cvrow[lo])
|
| 44 |
+
return 0.0
|
| 45 |
+
|
| 46 |
+
@njit(cache=False)
|
| 47 |
+
def rel_lookup(rp,ri,rv,j,t):
|
| 48 |
+
lo=np.int64(rp[j]); hi=np.int64(rp[j+1]); end=hi
|
| 49 |
+
while lo<hi:
|
| 50 |
+
md=np.int64((lo+hi)//2); x=int(ri[md])
|
| 51 |
+
if x<t: lo=md+1
|
| 52 |
+
else: hi=md
|
| 53 |
+
if lo<end and int(ri[lo])==t:return float(rv[lo])
|
| 54 |
+
return 1.0
|
| 55 |
+
|
| 56 |
+
@njit(cache=False)
|
| 57 |
+
def score_pool(cdocs, union, uip, exact, sup_ip, sup_ids, branches, memberships, res_terms,
|
| 58 |
+
qdense, route_dense, ct, cv, rp, ri, rv):
|
| 59 |
+
n=len(cdocs); tfcos=np.zeros(n,np.float32); amp_tail=np.zeros(n,np.float32)
|
| 60 |
+
for zz in range(n):
|
| 61 |
+
d=int(cdocs[zz])
|
| 62 |
+
ur=np.searchsorted(union,np.uint32(d))
|
| 63 |
+
if ur>=len(union) or int(union[ur])!=d: continue
|
| 64 |
+
ga=int(sup_ip[d]); gb=int(sup_ip[d+1]); ua=int(uip[ur])
|
| 65 |
+
# exact normalized tf-idf cosine
|
| 66 |
+
s=0.0
|
| 67 |
+
for kk in range(ga,gb):
|
| 68 |
+
t=int(sup_ids[kk]); s += float(exact[ua+(kk-ga)])*float(qdense[t])
|
| 69 |
+
tfcos[zz]=s
|
| 70 |
+
# exact retained residual amplitudes, same current gamma=.25 and lambdaM=.125
|
| 71 |
+
tsum=0.0; csum=0.0
|
| 72 |
+
for f in range(F):
|
| 73 |
+
j=int(branches[d,f])
|
| 74 |
+
if j==65535: continue
|
| 75 |
+
rho=float(route_dense[j])
|
| 76 |
+
if rho<=0.0: continue
|
| 77 |
+
mem=float(memberships[d,f]); local=0.0; sig=0.0
|
| 78 |
+
for r in range(S):
|
| 79 |
+
t=int(res_terms[d,f,r])
|
| 80 |
+
if t==65535: continue
|
| 81 |
+
pos=bsearch_u16(sup_ids,ga,gb,t)
|
| 82 |
+
if pos<0: continue
|
| 83 |
+
xv=float(exact[ua+(pos-ga)])
|
| 84 |
+
cen=center_lookup(ct[j],cv[j],t)
|
| 85 |
+
rel=rel_lookup(rp,ri,rv,j,t)
|
| 86 |
+
qv=float(qdense[t]); rr=xv-cen
|
| 87 |
+
local += rel*(qv-cen)*rr
|
| 88 |
+
sig += qv*qv
|
| 89 |
+
c=mem*rho
|
| 90 |
+
tsum += c*local*(sig**0.25 if sig>0 else 0.0)
|
| 91 |
+
csum += c
|
| 92 |
+
amp_tail[zz]=tsum + 0.125*csum
|
| 93 |
+
return tfcos,amp_tail
|
| 94 |
+
|
| 95 |
+
# feature matrices for reproducibility
|
| 96 |
+
TF=np.zeros((len(qids),P),np.float32); AMP=np.zeros((len(qids),P),np.float32)
|
| 97 |
+
start=time.time()
|
| 98 |
+
for qi,qid in enumerate(qids):
|
| 99 |
+
k=int(valid[qi]); q=idx.query_vec(texts[qid]); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; _,rd=idx.route(q)
|
| 100 |
+
tf,amp=score_pool(docs[qi,:k],union,uip,exact,idx.sup_ip,idx.sup_ids,branches,memberships,res_terms,qd,rd,idx.ct,idx.cv,idx.rp,idx.ri,idx.rv)
|
| 101 |
+
TF[qi,:k]=tf; AMP[qi,:k]=amp
|
| 102 |
+
if (qi+1)%100==0: print('features',qi+1,'elapsed',time.time()-start,flush=True)
|
| 103 |
+
np.save(OUT/'exact_tfidf_cos.npy',TF); np.save(OUT/'exact_residual_amp_tail.npy',AMP)
|
| 104 |
+
|
| 105 |
+
def rank_score(score,k=100):
|
| 106 |
+
if len(score)<=k:return np.argsort(score)[::-1]
|
| 107 |
+
ii=np.argpartition(score,-k)[-k:]; return ii[np.argsort(score[ii])[::-1]]
|
| 108 |
+
|
| 109 |
+
def evaluate(kind, a=0.0, x=0.0, use_cur=True, use_amp=False):
|
| 110 |
+
run={}
|
| 111 |
+
for qi,qid in enumerate(qids):
|
| 112 |
+
k=int(valid[qi]); dd=docs[qi,:k]
|
| 113 |
+
if kind=='tfidf_only': sc=TF[qi,:k]
|
| 114 |
+
elif kind=='amp_only': sc=AMP[qi,:k]
|
| 115 |
+
elif kind=='binary_only': sc=lex[qi,:k]
|
| 116 |
+
else:
|
| 117 |
+
sc=np.zeros(k,np.float32)
|
| 118 |
+
if use_cur: sc += m.zscore(tail[qi,:k])
|
| 119 |
+
if use_amp: sc += np.float32(a)*m.zscore(AMP[qi,:k])
|
| 120 |
+
sc += np.float32(4.0)*m.zscore(lex[qi,:k]) + np.float32(.1)*m.zscore(sem[qi,:k])
|
| 121 |
+
if x!=0: sc += np.float32(x)*m.zscore(TF[qi,:k])
|
| 122 |
+
oo=rank_score(sc,100); run[qid]=[int(v) for v in dd[oo]]
|
| 123 |
+
return m.eval_run(run,qrels)
|
| 124 |
+
|
| 125 |
+
rows=[]
|
| 126 |
+
for kind in ['binary_only','tfidf_only','amp_only']:
|
| 127 |
+
met=evaluate(kind); rows.append({'model':kind,**met}); print(kind,met,flush=True)
|
| 128 |
+
# Baseline locked final score and additions of exact tfidf
|
| 129 |
+
met=evaluate('fusion',0,0,True,False); rows.append({'model':'current_final','amp_coef':0,'tfidf_coef':0,**met}); print('current',met,flush=True)
|
| 130 |
+
for x in [0.125,0.25,0.5,1.0,2.0,4.0,8.0]:
|
| 131 |
+
met=evaluate('fusion',0,x,True,False); rows.append({'model':'current_plus_tfidf','amp_coef':0,'tfidf_coef':x,**met}); print('tf',x,met,flush=True)
|
| 132 |
+
# Replace current sign-tail by amplitude-tail
|
| 133 |
+
for x in [0.0,0.25,0.5,1.0,2.0,4.0]:
|
| 134 |
+
met=evaluate('fusion',1.0,x,False,True); rows.append({'model':'amp_tail_plus_final','amp_coef':1.0,'tfidf_coef':x,**met}); print('amp_replace tf',x,met,flush=True)
|
| 135 |
+
# retain current tail and add amplitude as extra feature, plus optional exact tfidf
|
| 136 |
+
for a in [0.125,0.25,0.5,1.0,2.0,4.0]:
|
| 137 |
+
for x in [0.0,0.25,0.5,1.0,2.0]:
|
| 138 |
+
met=evaluate('fusion',a,x,True,True); rows.append({'model':'current_plus_amp_plus_tfidf','amp_coef':a,'tfidf_coef':x,**met})
|
| 139 |
+
rows_sorted=sorted(rows,key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True)
|
| 140 |
+
out={'protocol':'same fixed eta=1 P=2000 pools from deterministic 1000 TRAIN validation; raw corpus reread only to reconstruct exact amplitudes; no candidate-generation changes','rows':rows_sorted,'best':rows_sorted[0],'feature_seconds':time.time()-start}
|
| 141 |
+
json.dump(out,open(OUT/'amplitude_diagnostic_results.json','w'),indent=2)
|
| 142 |
+
print('BEST',rows_sorted[0],flush=True)
|
| 143 |
+
print('TOP10')
|
| 144 |
+
for r in rows_sorted[:10]:print(r,flush=True)
|
experiments/msmarco_scale/msmarco_best_all_dev.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
import numpy as np,pandas as pd
|
| 4 |
+
sys.path.insert(0,'/mnt/data')
|
| 5 |
+
import msmarco_best_tail_core as b
|
| 6 |
+
import msmarco_full_search_uniform1m as m
|
| 7 |
+
ROOT=m.ROOT; WORK=m.WORK; idx=b.idx
|
| 8 |
+
LLEX=np.float32(4.0); LSEM=np.float32(0.1)
|
| 9 |
+
|
| 10 |
+
def rank(p,k=100):
|
| 11 |
+
if p is None:return []
|
| 12 |
+
docs=p['cand_docs'][:b.P]; ts=p['cand_tail'][:b.P]; lx=p['lex'][:b.P]; sm=p['sem'][:b.P]
|
| 13 |
+
fin=m.zscore(ts)+LLEX*m.zscore(lx)+LSEM*m.zscore(sm); oo=np.argsort(fin)[::-1][:k]
|
| 14 |
+
return [int(x) for x in docs[oo]]
|
| 15 |
+
|
| 16 |
+
df=pd.read_csv(ROOT/'dev.tsv',sep='\t',usecols=['query-id']); ids=[str(x) for x in np.unique(df['query-id'].to_numpy())]; del df
|
| 17 |
+
texts=m.load_query_texts(ids); qrels=m.qrels_from_tsv(ROOT/'dev.tsv',ids,positive_only=True)
|
| 18 |
+
_=b.prepare(texts[ids[0]])
|
| 19 |
+
run={}; times=[]; routehit=0; poolhit=0; den=0; cands=[]
|
| 20 |
+
for z,qid in enumerate(ids):
|
| 21 |
+
t=time.perf_counter(); p=b.prepare(texts[qid]); run[qid]=rank(p); times.append((time.perf_counter()-t)*1000)
|
| 22 |
+
rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels)
|
| 23 |
+
if p:
|
| 24 |
+
cands.append(p['candidate_docs']); ud=p['ud']; pool=p['cand_docs'][:b.P]
|
| 25 |
+
for d in rels:
|
| 26 |
+
kk=np.searchsorted(ud,d); routehit+=int(kk<len(ud) and int(ud[kk])==d); poolhit+=int(np.any(pool==d))
|
| 27 |
+
if (z+1)%500==0: print('dev',z+1,'median',float(np.median(times)),'p95',float(np.percentile(times,95)),flush=True)
|
| 28 |
+
met=m.eval_run(run,qrels)
|
| 29 |
+
out={'protocol':'all params locked from TRAIN validation: gamma_tail=.25 lambda_M=.125 h=0 lambda_lex=4 lambda_sem=.1 P=2000; full DEV untouched','params':{'gamma_tail':0.25,'lambda_M':0.125,'h':0,'lambda_lex':4.0,'lambda_sem':0.1,'P':2000,'S':16},'dev_metrics':met,'route_relevant_recall':routehit/den,'pool_relevant_recall':poolhit/den,'timing':{'median_ms':float(np.median(times)),'p95_ms':float(np.percentile(times,95)),'mean_ms':float(np.mean(times)),'qps':1000/float(np.mean(times)),'avg_candidate_docs':float(np.mean(cands))}}
|
| 30 |
+
json.dump(out,open(WORK/'best_all_dev_results.json','w'),indent=2); print('DEV',met,flush=True); print('SUMMARY',out,flush=True)
|
experiments/msmarco_scale/msmarco_best_tail_core.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json,math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np,pandas as pd
|
| 5 |
+
from numba import njit,prange,set_num_threads
|
| 6 |
+
sys.path.insert(0,'/mnt/data')
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
ROOT=m.ROOT; WORK=m.WORK; M=m.M; S=m.S; P=2000
|
| 9 |
+
GAMMA=np.float32(0.25); LAM=np.float32(0.125); HGRID=list(range(0,11))
|
| 10 |
+
set_num_threads(5); idx=m.FullIndex(); print('loaded',idx.meta,flush=True)
|
| 11 |
+
|
| 12 |
+
@njit(parallel=True,cache=False)
|
| 13 |
+
def score_components(rslot,mem,rt,sbits,q_dense,rho,cent_local,rel_local):
|
| 14 |
+
K=len(rslot); base=np.zeros(K,np.float32); sig=np.zeros(K,np.float32); cons=np.zeros(K,np.float32)
|
| 15 |
+
for z in prange(K):
|
| 16 |
+
u=int(rslot[z]); local=0.0; sg=0.0; bits=sbits[z]
|
| 17 |
+
for r in range(S):
|
| 18 |
+
t=int(rt[z,r])
|
| 19 |
+
if t==65535: continue
|
| 20 |
+
qv=q_dense[t]; cen=cent_local[u,t]; rel=rel_local[u,t]; rel=1.0 if rel==0.0 else rel
|
| 21 |
+
sgn=1.0 if ((bits>>r)&1)!=0 else -1.0
|
| 22 |
+
local += rel*(qv-cen)*sgn; sg += qv*qv
|
| 23 |
+
c=mem[z]*rho[u]; base[z]=c*local; sig[z]=sg; cons[z]=c
|
| 24 |
+
return base,sig,cons
|
| 25 |
+
|
| 26 |
+
def prepare(text):
|
| 27 |
+
q=idx.query_vec(text); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rterms,rd=idx.route(q)
|
| 28 |
+
spans=[(int(j),int(idx.offs[j]),int(idx.offs[j+1])) for j in rterms if idx.offs[j+1]>idx.offs[j]]
|
| 29 |
+
if not spans:return None
|
| 30 |
+
docs=np.concatenate([np.asarray(idx.pd[a:b]) for j,a,b in spans]).astype(np.uint32,copy=False)
|
| 31 |
+
mm=np.concatenate([np.asarray(idx.pm[a:b]) for j,a,b in spans]).astype(np.float32,copy=False)
|
| 32 |
+
rt=np.concatenate([np.asarray(idx.pr[a:b]) for j,a,b in spans]).astype(np.uint16,copy=False)
|
| 33 |
+
sb=np.concatenate([np.asarray(idx.ps[a:b]) for j,a,b in spans]).astype(np.uint16,copy=False)
|
| 34 |
+
nr=len(spans); cent=np.zeros((nr,M),np.float32); rel=np.zeros((nr,M),np.float32); rho=np.empty(nr,np.float32)
|
| 35 |
+
for u,(j,a,b) in enumerate(spans):
|
| 36 |
+
rowt=np.asarray(idx.ct[j]); ok=rowt!=65535; tids=rowt[ok].astype(np.int32,copy=False); cent[u,tids]=np.asarray(idx.cv[j])[ok]
|
| 37 |
+
ra=int(idx.rp[j]); rb=int(idx.rp[j+1]); rel[u,np.asarray(idx.ri[ra:rb],np.int32)]=np.asarray(idx.rv[ra:rb]); rho[u]=rd[j]
|
| 38 |
+
rslot=np.concatenate([np.full(b-a,u,dtype=np.uint8) for u,(j,a,b) in enumerate(spans)])
|
| 39 |
+
base,sig,cons=score_components(rslot,mm,rt,sb,qd,rho,cent,rel)
|
| 40 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 41 |
+
head=np.bincount(inv,weights=base*np.sqrt(sig),minlength=len(ud)).astype(np.float32)
|
| 42 |
+
tail=np.bincount(inv,weights=base*np.power(sig,GAMMA,dtype=np.float32),minlength=len(ud)).astype(np.float32)+LAM*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 43 |
+
hmax=max(HGRID); hw=min(len(head),max(1,hmax)); hi=np.argpartition(head,-hw)[-hw:] if len(head)>hw else np.arange(len(head)); ho=hi[np.argsort(head[hi])[::-1]]
|
| 44 |
+
want=min(len(tail),P+hmax+8); ci=np.argpartition(tail,-want)[-want:] if len(tail)>want else np.arange(len(tail)); co=ci[np.argsort(tail[ci])[::-1]]
|
| 45 |
+
cand_docs=ud[co]; cand_tail=tail[co]
|
| 46 |
+
lexvec=np.zeros(M,np.float32); lexvec[q.indices]=idx.idf[q.indices]; semvec=np.zeros(M,np.float32)
|
| 47 |
+
for t,amp in zip(q.indices,q.data):
|
| 48 |
+
a,b=idx.A.indptr[t],idx.A.indptr[t+1]; nb=idx.A.indices[a:b][:m.SEMK]; sv=idx.A.data[a:b][:m.SEMK]; semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 49 |
+
lex,sem=m.score_support_pool(cand_docs,idx.sup_ip,idx.sup_ids,lexvec,semvec,idx.dl,idx.avgdl)
|
| 50 |
+
return {'ud':ud,'head_order':ho,'cand_docs':cand_docs,'cand_tail':cand_tail,'lex':lex,'sem':sem,'candidate_docs':len(ud),'candidate_memberships':len(docs)}
|
| 51 |
+
|
| 52 |
+
def rank_h(p,h,k=100):
|
| 53 |
+
if p is None:return []
|
| 54 |
+
ud=p['ud']; frozen=ud[p['head_order'][:min(h,len(ud))]] if h else np.empty(0,np.uint32); fs=set(map(int,frozen.tolist()))
|
| 55 |
+
keep=np.asarray([int(d) not in fs for d in p['cand_docs']],bool); docs=p['cand_docs'][keep][:P]; ts=p['cand_tail'][keep][:P]; lx=p['lex'][keep][:P]; sm=p['sem'][keep][:P]
|
| 56 |
+
final=m.zscore(ts)+m.LAMBDA_LEX*m.zscore(lx)+m.LAMBDA_SEM*m.zscore(sm); oo=np.argsort(final)[::-1]
|
| 57 |
+
return [int(x) for x in np.concatenate([frozen,docs[oo]])[:k]]
|
| 58 |
+
|
experiments/msmarco_scale/msmarco_best_tail_dev.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
import numpy as np,pandas as pd
|
| 4 |
+
sys.path.insert(0,'/mnt/data')
|
| 5 |
+
import msmarco_best_tail_core as b
|
| 6 |
+
import msmarco_full_search_uniform1m as m
|
| 7 |
+
ROOT=m.ROOT; WORK=m.WORK
|
| 8 |
+
idx=b.idx
|
| 9 |
+
|
| 10 |
+
df=pd.read_csv(ROOT/'dev.tsv',sep='\t',usecols=['query-id']); ids=[str(x) for x in np.unique(df['query-id'].to_numpy())]; del df
|
| 11 |
+
texts=m.load_query_texts(ids); qrels=m.qrels_from_tsv(ROOT/'dev.tsv',ids,positive_only=True)
|
| 12 |
+
_=b.prepare(texts[ids[0]])
|
| 13 |
+
run={}; times=[]; cands=[]; routehit=0; poolhit=0; den=0
|
| 14 |
+
for z,qid in enumerate(ids):
|
| 15 |
+
t=time.perf_counter(); p=b.prepare(texts[qid]); run[qid]=b.rank_h(p,0,100); times.append((time.perf_counter()-t)*1000)
|
| 16 |
+
rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels)
|
| 17 |
+
if p:
|
| 18 |
+
cands.append(p['candidate_docs']); ud=p['ud']; pool=p['cand_docs'][:b.P]
|
| 19 |
+
for d in rels:
|
| 20 |
+
k=np.searchsorted(ud,d); routehit+=int(k<len(ud) and int(ud[k])==d); poolhit+=int(np.any(pool==d))
|
| 21 |
+
if (z+1)%250==0: print('dev',z+1,'median',float(np.median(times)),'p95',float(np.percentile(times,95)),'route',routehit/max(1,den),'pool',poolhit/max(1,den),flush=True)
|
| 22 |
+
met=m.eval_run(run,qrels)
|
| 23 |
+
out={'protocol':'gamma_tail=0.25, lambda_M=0.125, h=0 locked from deterministic 1000-query TRAIN validation; full DEV untouched','gamma_tail':0.25,'lambda_M':0.125,'h':0,'P':b.P,'dev_metrics':met,'route_relevant_recall':routehit/den,'pool_relevant_recall':poolhit/den,'timing':{'median_ms':float(np.median(times)),'p95_ms':float(np.percentile(times,95)),'mean_ms':float(np.mean(times)),'qps':1000/float(np.mean(times)),'avg_candidate_docs':float(np.mean(cands))}}
|
| 24 |
+
json.dump(out,open(WORK/'best_tail_dev_results.json','w'),indent=2); print('DEV',met,flush=True); print('SUMMARY',out,flush=True)
|
experiments/msmarco_scale/msmarco_best_tail_eval.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json,math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np,pandas as pd
|
| 5 |
+
from numba import njit,prange,set_num_threads
|
| 6 |
+
sys.path.insert(0,'/mnt/data')
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
ROOT=m.ROOT; WORK=m.WORK; M=m.M; S=m.S; P=2000
|
| 9 |
+
GAMMA=np.float32(0.25); LAM=np.float32(0.125); HGRID=list(range(0,11))
|
| 10 |
+
set_num_threads(5); idx=m.FullIndex(); print('loaded',idx.meta,flush=True)
|
| 11 |
+
|
| 12 |
+
@njit(parallel=True,cache=False)
|
| 13 |
+
def score_components(rslot,mem,rt,sbits,q_dense,rho,cent_local,rel_local):
|
| 14 |
+
K=len(rslot); base=np.zeros(K,np.float32); sig=np.zeros(K,np.float32); cons=np.zeros(K,np.float32)
|
| 15 |
+
for z in prange(K):
|
| 16 |
+
u=int(rslot[z]); local=0.0; sg=0.0; bits=sbits[z]
|
| 17 |
+
for r in range(S):
|
| 18 |
+
t=int(rt[z,r])
|
| 19 |
+
if t==65535: continue
|
| 20 |
+
qv=q_dense[t]; cen=cent_local[u,t]; rel=rel_local[u,t]; rel=1.0 if rel==0.0 else rel
|
| 21 |
+
sgn=1.0 if ((bits>>r)&1)!=0 else -1.0
|
| 22 |
+
local += rel*(qv-cen)*sgn; sg += qv*qv
|
| 23 |
+
c=mem[z]*rho[u]; base[z]=c*local; sig[z]=sg; cons[z]=c
|
| 24 |
+
return base,sig,cons
|
| 25 |
+
|
| 26 |
+
def prepare(text):
|
| 27 |
+
q=idx.query_vec(text); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rterms,rd=idx.route(q)
|
| 28 |
+
spans=[(int(j),int(idx.offs[j]),int(idx.offs[j+1])) for j in rterms if idx.offs[j+1]>idx.offs[j]]
|
| 29 |
+
if not spans:return None
|
| 30 |
+
docs=np.concatenate([np.asarray(idx.pd[a:b]) for j,a,b in spans]).astype(np.uint32,copy=False)
|
| 31 |
+
mm=np.concatenate([np.asarray(idx.pm[a:b]) for j,a,b in spans]).astype(np.float32,copy=False)
|
| 32 |
+
rt=np.concatenate([np.asarray(idx.pr[a:b]) for j,a,b in spans]).astype(np.uint16,copy=False)
|
| 33 |
+
sb=np.concatenate([np.asarray(idx.ps[a:b]) for j,a,b in spans]).astype(np.uint16,copy=False)
|
| 34 |
+
nr=len(spans); cent=np.zeros((nr,M),np.float32); rel=np.zeros((nr,M),np.float32); rho=np.empty(nr,np.float32)
|
| 35 |
+
for u,(j,a,b) in enumerate(spans):
|
| 36 |
+
rowt=np.asarray(idx.ct[j]); ok=rowt!=65535; tids=rowt[ok].astype(np.int32,copy=False); cent[u,tids]=np.asarray(idx.cv[j])[ok]
|
| 37 |
+
ra=int(idx.rp[j]); rb=int(idx.rp[j+1]); rel[u,np.asarray(idx.ri[ra:rb],np.int32)]=np.asarray(idx.rv[ra:rb]); rho[u]=rd[j]
|
| 38 |
+
rslot=np.concatenate([np.full(b-a,u,dtype=np.uint8) for u,(j,a,b) in enumerate(spans)])
|
| 39 |
+
base,sig,cons=score_components(rslot,mm,rt,sb,qd,rho,cent,rel)
|
| 40 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 41 |
+
head=np.bincount(inv,weights=base*np.sqrt(sig),minlength=len(ud)).astype(np.float32)
|
| 42 |
+
tail=np.bincount(inv,weights=base*np.power(sig,GAMMA,dtype=np.float32),minlength=len(ud)).astype(np.float32)+LAM*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 43 |
+
hmax=max(HGRID); hw=min(len(head),max(1,hmax)); hi=np.argpartition(head,-hw)[-hw:] if len(head)>hw else np.arange(len(head)); ho=hi[np.argsort(head[hi])[::-1]]
|
| 44 |
+
want=min(len(tail),P+hmax+8); ci=np.argpartition(tail,-want)[-want:] if len(tail)>want else np.arange(len(tail)); co=ci[np.argsort(tail[ci])[::-1]]
|
| 45 |
+
cand_docs=ud[co]; cand_tail=tail[co]
|
| 46 |
+
lexvec=np.zeros(M,np.float32); lexvec[q.indices]=idx.idf[q.indices]; semvec=np.zeros(M,np.float32)
|
| 47 |
+
for t,amp in zip(q.indices,q.data):
|
| 48 |
+
a,b=idx.A.indptr[t],idx.A.indptr[t+1]; nb=idx.A.indices[a:b][:m.SEMK]; sv=idx.A.data[a:b][:m.SEMK]; semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 49 |
+
lex,sem=m.score_support_pool(cand_docs,idx.sup_ip,idx.sup_ids,lexvec,semvec,idx.dl,idx.avgdl)
|
| 50 |
+
return {'ud':ud,'head_order':ho,'cand_docs':cand_docs,'cand_tail':cand_tail,'lex':lex,'sem':sem,'candidate_docs':len(ud),'candidate_memberships':len(docs)}
|
| 51 |
+
|
| 52 |
+
def rank_h(p,h,k=100):
|
| 53 |
+
if p is None:return []
|
| 54 |
+
ud=p['ud']; frozen=ud[p['head_order'][:min(h,len(ud))]] if h else np.empty(0,np.uint32); fs=set(map(int,frozen.tolist()))
|
| 55 |
+
keep=np.asarray([int(d) not in fs for d in p['cand_docs']],bool); docs=p['cand_docs'][keep][:P]; ts=p['cand_tail'][keep][:P]; lx=p['lex'][keep][:P]; sm=p['sem'][keep][:P]
|
| 56 |
+
final=m.zscore(ts)+m.LAMBDA_LEX*m.zscore(lx)+m.LAMBDA_SEM*m.zscore(sm); oo=np.argsort(final)[::-1]
|
| 57 |
+
return [int(x) for x in np.concatenate([frozen,docs[oo]])[:k]]
|
| 58 |
+
|
| 59 |
+
tr=pd.read_csv(ROOT/'train.tsv',sep='\t',usecols=['query-id']); uq=np.unique(tr['query-id'].to_numpy()); rng=np.random.default_rng(20260815); ids=[str(x) for x in rng.choice(uq,size=1000,replace=False)]; del tr
|
| 60 |
+
texts=m.load_query_texts(ids); qrels=m.qrels_from_tsv(ROOT/'train.tsv',ids,positive_only=True)
|
| 61 |
+
_=prepare(texts[ids[0]])
|
| 62 |
+
runs={h:{} for h in HGRID}; times=[]; cands=[]; poolhit=0; routehit=0; den=0
|
| 63 |
+
for z,qid in enumerate(ids):
|
| 64 |
+
t=time.perf_counter(); p=prepare(texts[qid]); times.append((time.perf_counter()-t)*1000)
|
| 65 |
+
rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels)
|
| 66 |
+
if p:
|
| 67 |
+
cands.append(p['candidate_docs']); ud=p['ud']; pool=p['cand_docs'][:P]
|
| 68 |
+
for d in rels:
|
| 69 |
+
k=np.searchsorted(ud,d); routehit+=int(k<len(ud) and int(ud[k])==d); poolhit+=int(np.any(pool==d))
|
| 70 |
+
for h in HGRID:runs[h][qid]=rank_h(p,h,100)
|
| 71 |
+
if (z+1)%100==0: print('q',z+1,'median',float(np.median(times)),'route',routehit/max(1,den),'pool',poolhit/max(1,den),flush=True)
|
| 72 |
+
rows={}
|
| 73 |
+
for h in HGRID:
|
| 74 |
+
met=m.eval_run(runs[h],qrels); rows[h]=met; print('H',h,met,flush=True)
|
| 75 |
+
best=max(rows,key=lambda h:(rows[h]['nDCG@10'],rows[h]['MRR@10'],rows[h]['R@100']))
|
| 76 |
+
out={'gamma_tail':float(GAMMA),'lambda_M':float(LAM),'P':P,'hgrid':rows,'best_h':int(best),'route_relevant_recall':routehit/den,'pool_relevant_recall':poolhit/den,'median_ms':float(np.median(times)),'p95_ms':float(np.percentile(times,95)),'avg_candidate_docs':float(np.mean(cands))}
|
| 77 |
+
json.dump(out,open(WORK/'best_tail_validation.json','w'),indent=2); print('BEST',best,rows[best],flush=True); print('summary',out,flush=True)
|
experiments/msmarco_scale/msmarco_branch_coherence_multifold.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
import numpy as np,pandas as pd
|
| 4 |
+
from numba import njit,prange,set_num_threads
|
| 5 |
+
sys.path.insert(0,'/mnt/data')
|
| 6 |
+
import msmarco_early_lex_validation_fast as e
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
import msmarco_best_tail_core as b
|
| 9 |
+
|
| 10 |
+
ROOT=m.ROOT; WORK=m.WORK; idx=e.idx; M=m.M; P=2000; S=m.S
|
| 11 |
+
set_num_threads(5)
|
| 12 |
+
WEIGHTS=[-2.0,-1.0,-0.5,-0.25,0.0,0.25,0.5,1.0]
|
| 13 |
+
FINAL_B=np.float32(0.1); LEX_ALPHA=np.float32(0.25); WLEX=np.float32(4.0); WSEM=np.float32(0.3)
|
| 14 |
+
|
| 15 |
+
def topk_desc(score,k):
|
| 16 |
+
n=len(score); k=min(k,n)
|
| 17 |
+
if n<=k:return np.argsort(score)[::-1]
|
| 18 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 19 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 20 |
+
|
| 21 |
+
@njit(parallel=True,cache=False)
|
| 22 |
+
def selected_lex_features(dd,ip,ids,lexvec,dl,avgdl):
|
| 23 |
+
n=len(dd); lx=np.zeros(n,np.float32); qc=np.zeros(n,np.float32)
|
| 24 |
+
for z in prange(n):
|
| 25 |
+
d=int(dd[z]); a=int(ip[d]); bb=int(ip[d+1]); raw=0.0; c=0.0
|
| 26 |
+
for k in range(a,bb):
|
| 27 |
+
t=int(ids[k]); v=lexvec[t]
|
| 28 |
+
if v>0:
|
| 29 |
+
raw += v; c += 1.0
|
| 30 |
+
ratio=float(dl[d])/avgdl; den=(1.0-FINAL_B)+FINAL_B*ratio
|
| 31 |
+
lx[z]=raw/(den if den>0 else 1.0); qc[z]=c
|
| 32 |
+
return lx,qc
|
| 33 |
+
|
| 34 |
+
@njit(cache=False)
|
| 35 |
+
def find_doc(pd,a,bb,d):
|
| 36 |
+
lo=np.int64(a); hi=np.int64(bb)
|
| 37 |
+
while lo<hi:
|
| 38 |
+
md=(lo+hi)//2; x=int(pd[md])
|
| 39 |
+
if x<d: lo=md+1
|
| 40 |
+
else: hi=md
|
| 41 |
+
if lo<bb and int(pd[lo])==d:return lo
|
| 42 |
+
return -1
|
| 43 |
+
|
| 44 |
+
@njit(parallel=True,cache=False)
|
| 45 |
+
def coherence_features(dd,rterms,rd,offs,pd,pm,pr,ps,qd,ct,cv,rp,ri,rv):
|
| 46 |
+
n=len(dd); geom=np.zeros(n,np.float32); gabs=np.zeros(n,np.float32)
|
| 47 |
+
for zz in prange(n):
|
| 48 |
+
d=int(dd[zz]); gs=0.0; ab=0.0
|
| 49 |
+
for jj in range(len(rterms)):
|
| 50 |
+
j=int(rterms[jj]); a=int(offs[j]); bb=int(offs[j+1]); p=find_doc(pd,a,bb,d)
|
| 51 |
+
if p<0: continue
|
| 52 |
+
c=float(pm[p])*float(rd[j]); local=0.0; sig=0.0; bits=int(ps[p])
|
| 53 |
+
for r in range(S):
|
| 54 |
+
t=int(pr[p,r])
|
| 55 |
+
if t==65535: continue
|
| 56 |
+
qv=float(qd[t]); cen=float(m.lookup_center(ct[j],cv[j],t)); rel=float(m.lookup_rel(rp,ri,rv,j,t)); sgn=1.0 if ((bits>>r)&1) else -1.0
|
| 57 |
+
local += rel*(qv-cen)*sgn; sig += qv*qv
|
| 58 |
+
g=c*local*(sig**0.25 if sig>0 else 0.0)
|
| 59 |
+
gs += g; ab += abs(g)
|
| 60 |
+
geom[zz]=gs; gabs[zz]=ab
|
| 61 |
+
return geom,gabs
|
| 62 |
+
|
| 63 |
+
def rank100(score):
|
| 64 |
+
n=len(score); k=min(100,n)
|
| 65 |
+
if n<=k: oo=np.argsort(score)[::-1]
|
| 66 |
+
else:
|
| 67 |
+
ii=np.argpartition(score,-k)[-k:]; oo=ii[np.argsort(score[ii])[::-1]]
|
| 68 |
+
return oo
|
| 69 |
+
|
| 70 |
+
# Exact original fold-0 IDs, plus four new disjoint deterministic folds.
|
| 71 |
+
z0=np.load(WORK/'amplitude_diag'/'fixed_eta1_pools.npz',allow_pickle=False)
|
| 72 |
+
fold0=[str(x) for x in z0['qids'].tolist()]
|
| 73 |
+
tr=pd.read_csv(ROOT/'train.tsv',sep='\t',usecols=['query-id'])
|
| 74 |
+
uq=np.unique(tr['query-id'].to_numpy()); del tr
|
| 75 |
+
f0set=set(int(x) for x in fold0)
|
| 76 |
+
remaining=np.asarray([x for x in uq if int(x) not in f0set])
|
| 77 |
+
rng=np.random.default_rng(20260816)
|
| 78 |
+
extra=rng.choice(remaining,size=4000,replace=False)
|
| 79 |
+
folds=[fold0]+[[str(x) for x in extra[i*1000:(i+1)*1000]] for i in range(4)]
|
| 80 |
+
allids=[q for f in folds for q in f]
|
| 81 |
+
texts=m.load_query_texts(allids)
|
| 82 |
+
qrels_all=m.qrels_from_tsv(ROOT/'train.tsv',allids,positive_only=True)
|
| 83 |
+
|
| 84 |
+
# warmup
|
| 85 |
+
_=selected_lex_features(np.array([0],np.uint32),idx.sup_ip,idx.sup_ids,np.zeros(M,np.float32),idx.dl,idx.avgdl)
|
| 86 |
+
q0=idx.query_vec(texts[allids[0]]); qd0=np.zeros(M,np.float32); qd0[q0.indices]=q0.data; rt0,rd0=idx.route(q0)
|
| 87 |
+
_=coherence_features(np.array([0],np.uint32),rt0,rd0,idx.offs,idx.pd,idx.pm,idx.pr,idx.ps,qd0,idx.ct,idx.cv,idx.rp,idx.ri,idx.rv)
|
| 88 |
+
_=e.prepare_all(texts[allids[0]])
|
| 89 |
+
|
| 90 |
+
runs=[{w:{} for w in WEIGHTS} for _ in folds]
|
| 91 |
+
times=[]
|
| 92 |
+
start=time.time()
|
| 93 |
+
for fi,ids in enumerate(folds):
|
| 94 |
+
print('FOLD',fi,'START',flush=True)
|
| 95 |
+
for qi,qid in enumerate(ids):
|
| 96 |
+
t0=time.perf_counter(); p=e.prepare_all(texts[qid])
|
| 97 |
+
if p is None:
|
| 98 |
+
for w in WEIGHTS:runs[fi][w][qid]=[]
|
| 99 |
+
continue
|
| 100 |
+
sel=topk_desc(m.zscore(p['tail'])+m.zscore(p['lex']),P)
|
| 101 |
+
dd=p['ud'][sel]; ts=p['tail'][sel]; sm=p['sem'][sel]
|
| 102 |
+
q=idx.query_vec(texts[qid]); lexvec=np.zeros(M,np.float32); lexvec[q.indices]=idx.idf[q.indices]
|
| 103 |
+
lx,qc=selected_lex_features(dd,idx.sup_ip,idx.sup_ids,lexvec,idx.dl,idx.avgdl)
|
| 104 |
+
cov=qc/max(1,len(q.indices)); ladj=lx*np.power(np.maximum(cov,1e-6),LEX_ALPHA)
|
| 105 |
+
qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rterms,rd=idx.route(q)
|
| 106 |
+
geom,gabs=coherence_features(dd,rterms,rd,idx.offs,idx.pd,idx.pm,idx.pr,idx.ps,qd,idx.ct,idx.cv,idx.rp,idx.ri,idx.rv)
|
| 107 |
+
coh=geom/np.maximum(gabs,1e-6)
|
| 108 |
+
base=m.zscore(ts)+WLEX*m.zscore(ladj)+WSEM*m.zscore(sm)
|
| 109 |
+
for w in WEIGHTS:
|
| 110 |
+
sc=base+np.float32(w)*coh
|
| 111 |
+
oo=rank100(sc); runs[fi][w][qid]=[int(x) for x in dd[oo]]
|
| 112 |
+
times.append((time.perf_counter()-t0)*1000)
|
| 113 |
+
if (qi+1)%250==0:
|
| 114 |
+
print('fold',fi,'q',qi+1,'median_ms',float(np.median(times[-250:])),flush=True)
|
| 115 |
+
|
| 116 |
+
rows=[]
|
| 117 |
+
for fi,ids in enumerate(folds):
|
| 118 |
+
qr={q:qrels_all[q] for q in ids}
|
| 119 |
+
for w in WEIGHTS:
|
| 120 |
+
met=m.eval_run(runs[fi][w],qr); rows.append({'fold':fi,'weight':w,**met})
|
| 121 |
+
print('METRIC fold',fi,'w',w,'ndcg',met['nDCG@10'],'mrr',met['MRR@10'],'r100',met['R@100'],flush=True)
|
| 122 |
+
summary=[]
|
| 123 |
+
for w in WEIGHTS:
|
| 124 |
+
rr=[r for r in rows if r['weight']==w]
|
| 125 |
+
nd=np.asarray([r['nDCG@10'] for r in rr]); mr=np.asarray([r['MRR@10'] for r in rr]); r100=np.asarray([r['R@100'] for r in rr])
|
| 126 |
+
# Improvement relative to w=0 computed fold-wise.
|
| 127 |
+
base=[next(x for x in rows if x['fold']==fi and x['weight']==0.0) for fi in range(5)]
|
| 128 |
+
delta=np.asarray([rr[fi]['nDCG@10']-base[fi]['nDCG@10'] for fi in range(5)])
|
| 129 |
+
summary.append({'weight':w,'mean_nDCG@10':float(nd.mean()),'std_nDCG@10':float(nd.std(ddof=1)),'mean_MRR@10':float(mr.mean()),'mean_R@100':float(r100.mean()),'mean_delta_nDCG_vs_base':float(delta.mean()),'min_delta_nDCG_vs_base':float(delta.min()),'positive_folds':int(np.sum(delta>0)),'fold_deltas':delta.tolist()})
|
| 130 |
+
summary.sort(key=lambda x:(x['positive_folds'],x['min_delta_nDCG_vs_base'],x['mean_delta_nDCG_vs_base']),reverse=True)
|
| 131 |
+
out={'protocol':'5 disjoint 1000-query TRAIN folds; fold0 is original validation; folds1-4 are new deterministic samples; same eta=1 P=2000 pools and structural lexical b=.1 alpha=.25 wl4 raw-sem .3; branch coherence only','weights':WEIGHTS,'fold_rows':rows,'summary_ranked_for_robustness':summary,'timing':{'median_ms':float(np.median(times)),'p95_ms':float(np.percentile(times,95)),'seconds':time.time()-start}}
|
| 132 |
+
path=WORK/'branch_coherence_multifold.json'; json.dump(out,open(path,'w'),indent=2)
|
| 133 |
+
print('SUMMARY'); [print(x) for x in summary]; print('SAVED',path,flush=True)
|
experiments/msmarco_scale/msmarco_branch_features.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numba import njit,prange,set_num_threads
|
| 6 |
+
sys.path.insert(0,'/mnt/data')
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
import msmarco_best_tail_core as b
|
| 9 |
+
ROOT=m.ROOT; WORK=m.WORK; OUT=WORK/'structural_fusion'; OUT.mkdir(exist_ok=True); idx=b.idx; set_num_threads(5); M=m.M; S=m.S
|
| 10 |
+
z=np.load(WORK/'amplitude_diag'/'fixed_eta1_pools.npz',allow_pickle=False); qids=[str(x) for x in z['qids'].tolist()]; valid=z['valid'].astype(np.int32); docs=z['docs']; texts=m.load_query_texts(qids)
|
| 11 |
+
@njit(cache=False)
|
| 12 |
+
def find_doc(pd,a,bb,d):
|
| 13 |
+
lo=np.int64(a); hi=np.int64(bb)
|
| 14 |
+
while lo<hi:
|
| 15 |
+
md=(lo+hi)//2; x=int(pd[md])
|
| 16 |
+
if x<d: lo=md+1
|
| 17 |
+
else: hi=md
|
| 18 |
+
if lo<bb and int(pd[lo])==d:return lo
|
| 19 |
+
return -1
|
| 20 |
+
@njit(parallel=True,cache=False)
|
| 21 |
+
def pool_features(dd,rterms,rd,offs,pd,pm,pr,ps,qd,ct,cv,rp,ri,rv):
|
| 22 |
+
n=len(dd); geom=np.zeros(n,np.float32); cons=np.zeros(n,np.float32); bc=np.zeros(n,np.float32); gabs=np.zeros(n,np.float32); gmax=np.zeros(n,np.float32); cmax=np.zeros(n,np.float32); pos=np.zeros(n,np.float32); neg=np.zeros(n,np.float32)
|
| 23 |
+
for zz in prange(n):
|
| 24 |
+
d=int(dd[zz]); gs=0.; cs=0.; cnt=0.; ab=0.; mx=-1e30; cm=0.; pp=0.; nn=0.
|
| 25 |
+
for jj in range(len(rterms)):
|
| 26 |
+
j=int(rterms[jj]); a=int(offs[j]); bb=int(offs[j+1]); p=find_doc(pd,a,bb,d)
|
| 27 |
+
if p<0: continue
|
| 28 |
+
cnt+=1.; c=float(pm[p])*float(rd[j]); local=0.; sig=0.; bits=int(ps[p])
|
| 29 |
+
for r in range(S):
|
| 30 |
+
t=int(pr[p,r])
|
| 31 |
+
if t==65535: continue
|
| 32 |
+
qv=float(qd[t]); cen=float(m.lookup_center(ct[j],cv[j],t)); rel=float(m.lookup_rel(rp,ri,rv,j,t)); sgn=1. if ((bits>>r)&1) else -1.
|
| 33 |
+
local += rel*(qv-cen)*sgn; sig += qv*qv
|
| 34 |
+
g=c*local*(sig**0.25 if sig>0 else 0.)
|
| 35 |
+
gs+=g; cs+=c; ab+=abs(g); mx=max(mx,g); cm=max(cm,c); pp+=1. if g>0 else 0.; nn+=1. if g<0 else 0.
|
| 36 |
+
geom[zz]=gs; cons[zz]=cs; bc[zz]=cnt; gabs[zz]=ab; gmax[zz]=0 if mx<-1e20 else mx; cmax[zz]=cm; pos[zz]=pp; neg[zz]=nn
|
| 37 |
+
return geom,cons,bc,gabs,gmax,cmax,pos,neg
|
| 38 |
+
# warmup
|
| 39 |
+
q=idx.query_vec(texts[qids[0]]); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rt,rd=idx.route(q); _=pool_features(docs[0,:1],rt,rd,idx.offs,idx.pd,idx.pm,idx.pr,idx.ps,qd,idx.ct,idx.cv,idx.rp,idx.ri,idx.rv)
|
| 40 |
+
shape=docs.shape; names=['geom','cons','branch_count','geom_abs','geom_max','cons_max','pos_count','neg_count']; arr={n:np.zeros(shape,np.float32) for n in names}; times=[]; errs=[]
|
| 41 |
+
for i,qid in enumerate(qids):
|
| 42 |
+
k=int(valid[i]);
|
| 43 |
+
if not k:continue
|
| 44 |
+
q=idx.query_vec(texts[qid]); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rt,rd=idx.route(q); t=time.perf_counter(); vals=pool_features(docs[i,:k],rt,rd,idx.offs,idx.pd,idx.pm,idx.pr,idx.ps,qd,idx.ct,idx.cv,idx.rp,idx.ri,idx.rv); times.append((time.perf_counter()-t)*1000)
|
| 45 |
+
for nm,v in zip(names,vals): arr[nm][i,:k]=v
|
| 46 |
+
# reconstructed tail consistency
|
| 47 |
+
recon=vals[0]+.125*vals[1]; errs.append(float(np.max(np.abs(recon-z['tail'][i,:k]))))
|
| 48 |
+
if (i+1)%200==0:print(i+1,'median_ms',float(np.median(times)),'max_tail_err',max(errs),flush=True)
|
| 49 |
+
np.savez_compressed(OUT/'branch_features.npz',qids=np.asarray(qids),valid=valid,**arr)
|
| 50 |
+
meta={'protocol':'fixed eta=1 P=2000 validation pools; branch-level features recovered from current sorted branch postings only','features':names,'median_ms':float(np.median(times)),'p95_ms':float(np.percentile(times,95)),'max_tail_reconstruction_error':max(errs)}; json.dump(meta,open(OUT/'branch_feature_meta.json','w'),indent=2); print('DONE',meta,flush=True)
|
experiments/msmarco_scale/msmarco_branch_fusion_sweep.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,json
|
| 3 |
+
import numpy as np
|
| 4 |
+
sys.path.insert(0,'/mnt/data')
|
| 5 |
+
import msmarco_full_search_uniform1m as m
|
| 6 |
+
ROOT=m.ROOT; WORK=m.WORK; OUT=WORK/'structural_fusion'
|
| 7 |
+
z=np.load(WORK/'amplitude_diag'/'fixed_eta1_pools.npz',allow_pickle=False); c=np.load(OUT/'coordination_features.npz',allow_pickle=False); g=np.load(OUT/'branch_features.npz',allow_pickle=False)
|
| 8 |
+
qids=[str(x) for x in z['qids'].tolist()]; valid=z['valid'].astype(int); docs=z['docs']; T=z['tail']; SM=z['sem']; RAW=c['rawlex']; LF=c['lenfac']; QC=c['qcount']; QT=c['qterms'].astype(int)
|
| 9 |
+
G=g['geom']; C=g['cons']; BC=g['branch_count']; GA=g['geom_abs']; GM=g['geom_max']; CM=g['cons_max']; PC=g['pos_count']; NC=g['neg_count']; qrels=m.qrels_from_tsv(ROOT/'train.tsv',qids,positive_only=True)
|
| 10 |
+
def Z(x):return m.zscore(x)
|
| 11 |
+
def top100(sc):
|
| 12 |
+
n=len(sc); k=min(100,n); ii=np.argpartition(sc,-k)[-k:] if n>k else np.arange(n); return ii[np.argsort(sc[ii])[::-1]]
|
| 13 |
+
def common(i,k):
|
| 14 |
+
ratio=(LF[i,:k]-.8)/.2; lx=RAW[i,:k]/np.maximum(.9+.1*ratio,1e-6); cov=QC[i,:k]/max(1,QT[i]); ladj=lx*np.power(np.maximum(cov,1e-6),.25); return 4*Z(ladj)+.3*Z(SM[i,:k])
|
| 15 |
+
def evalx(name,fn):
|
| 16 |
+
run={}
|
| 17 |
+
for i,qid in enumerate(qids):
|
| 18 |
+
k=valid[i]; sc=fn(i,k); oo=top100(sc); run[qid]=[int(x) for x in docs[i,oo]]
|
| 19 |
+
r={'name':name,**m.eval_run(run,qrels)}; print(name,round(r['nDCG@10'],6),round(r['MRR@10'],6),round(r['R@100'],6),flush=True); return r
|
| 20 |
+
rows=[]; rows.append(evalx('struct_base',lambda i,k:Z(T[i,:k])+common(i,k)))
|
| 21 |
+
# separate geometry and consensus
|
| 22 |
+
for wc in [-2.,-1.,-.5,-.25,0.,.0625,.125,.25,.5,1.,2.,4.]: rows.append(evalx(f'split_wc{wc}',lambda i,k,wc=wc: Z(G[i,:k])+wc*Z(C[i,:k])+common(i,k)))
|
| 23 |
+
# add extra consensus to current tail
|
| 24 |
+
for w in [-2.,-1.,-.5,-.25,.25,.5,1.,2.]: rows.append(evalx(f'base_plus_cons{w}',lambda i,k,w=w: Z(T[i,:k])+common(i,k)+w*Z(C[i,:k])))
|
| 25 |
+
# branch-count/diversity one-at-a-time
|
| 26 |
+
for nm,X in [('bc',BC),('gabs',GA),('gmax',GM),('cmax',CM)]:
|
| 27 |
+
for w in [-1.,-.5,-.25,.25,.5,1.]: rows.append(evalx(f'base_{nm}_{w}',lambda i,k,w=w,X=X: Z(T[i,:k])+common(i,k)+w*Z(X[i,:k])))
|
| 28 |
+
# coherence and positive fraction, bounded structural signals
|
| 29 |
+
for w in [-2.,-1.,-.5,-.25,.25,.5,1.,2.]:
|
| 30 |
+
rows.append(evalx(f'coherence_{w}',lambda i,k,w=w: Z(T[i,:k])+common(i,k)+w*(G[i,:k]/np.maximum(GA[i,:k],1e-6))))
|
| 31 |
+
rows.append(evalx(f'posfrac_{w}',lambda i,k,w=w: Z(T[i,:k])+common(i,k)+w*(PC[i,:k]/np.maximum(PC[i,:k]+NC[i,:k],1.0))))
|
| 32 |
+
# concentration penalty/bonus: max branch / total absolute evidence
|
| 33 |
+
for w in [-1.,-.5,-.25,.25,.5,1.]: rows.append(evalx(f'concentration_{w}',lambda i,k,w=w: Z(T[i,:k])+common(i,k)+w*(GM[i,:k]/np.maximum(GA[i,:k],1e-6))))
|
| 34 |
+
rows.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True); out={'protocol':'fixed eta=1 P=2000 TRAIN validation; branch-level structure from current index only; structural lexical base b=.1 alpha=.25 wl4 ws=.3','baseline':next(r for r in rows if r['name']=='struct_base'),'best':rows[0],'top25':rows[:25],'n_models':len(rows)}; json.dump(out,open(OUT/'branch_fusion_sweep.json','w'),indent=2); print('BEST',rows[0]); print('TOP10'); [print(r) for r in rows[:10]]
|
experiments/msmarco_scale/msmarco_build_geometry.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import gzip,json,pickle,time,re,gc,os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scipy import sparse
|
| 6 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 7 |
+
from sklearn.preprocessing import normalize
|
| 8 |
+
from numba import njit, prange, set_num_threads
|
| 9 |
+
|
| 10 |
+
ROOT=Path('/mnt/data'); WORK=ROOT/'msmarco_scale_work'; GEOM=WORK/'geometry_1m'; GEOM.mkdir(parents=True,exist_ok=True)
|
| 11 |
+
N_CAL=1_000_000; M=50_000; F=4; B=64; S=16; L=12; TAU=20.; BETA=-.2; EPS=1e-6
|
| 12 |
+
GRAPH_TAU=10.; ASSOC_K=64; ROUTE_K=32
|
| 13 |
+
SENT=np.uint16(65535)
|
| 14 |
+
set_num_threads(5)
|
| 15 |
+
|
| 16 |
+
def load_vocab():
|
| 17 |
+
with gzip.open(WORK/'final_vocab_50k.pkl.gz','rb') as g: z=pickle.load(g)
|
| 18 |
+
terms=z['terms'].tolist(); idf=np.asarray(z['idf'],np.float32)
|
| 19 |
+
return terms,idf,{t:i for i,t in enumerate(terms)}
|
| 20 |
+
|
| 21 |
+
def shard_path(i):
|
| 22 |
+
hits=list(ROOT.glob(f'corpus_{i:04d}.jsonl*.gz')); assert len(hits)==1,(i,hits); return hits[0]
|
| 23 |
+
|
| 24 |
+
def tfidf_shard(p,vocab,idf):
|
| 25 |
+
texts=[]
|
| 26 |
+
with gzip.open(p,'rt',encoding='utf-8') as f:
|
| 27 |
+
for line in f:
|
| 28 |
+
o=json.loads(line); texts.append(((o.get('title') or '')+' '+(o.get('text') or '')).strip())
|
| 29 |
+
cv=CountVectorizer(vocabulary=vocab,lowercase=True,token_pattern=r'(?u)\b\w\w+\b',dtype=np.int32)
|
| 30 |
+
X=cv.transform(texts).tocsr().astype(np.float32)
|
| 31 |
+
X.data *= idf[X.indices]
|
| 32 |
+
normalize(X,norm='l2',axis=1,copy=False)
|
| 33 |
+
X.sort_indices()
|
| 34 |
+
return X
|
| 35 |
+
|
| 36 |
+
@njit(parallel=True,cache=False)
|
| 37 |
+
def topk_memberships(indptr,indices,data,F):
|
| 38 |
+
N=indptr.size-1
|
| 39 |
+
branches=np.full((N,F),np.uint16(65535),np.uint16)
|
| 40 |
+
mem=np.zeros((N,F),np.float32)
|
| 41 |
+
topL=np.full((N,12),np.uint16(65535),np.uint16)
|
| 42 |
+
for d in prange(N):
|
| 43 |
+
a=indptr[d]; b=indptr[d+1]
|
| 44 |
+
# top 12 descending insertion
|
| 45 |
+
vals=np.zeros(12,np.float32); tids=np.full(12,np.uint16(65535),np.uint16)
|
| 46 |
+
for p in range(a,b):
|
| 47 |
+
v=data[p]; t=np.uint16(indices[p])
|
| 48 |
+
# locate insertion descending
|
| 49 |
+
pos=12
|
| 50 |
+
for r in range(12):
|
| 51 |
+
if v>vals[r]: pos=r; break
|
| 52 |
+
if pos<12:
|
| 53 |
+
for r in range(11,pos,-1): vals[r]=vals[r-1]; tids[r]=tids[r-1]
|
| 54 |
+
vals[pos]=v; tids[pos]=t
|
| 55 |
+
den=0.0
|
| 56 |
+
for s in range(F): den += vals[s]
|
| 57 |
+
if den>0:
|
| 58 |
+
for s in range(F):
|
| 59 |
+
branches[d,s]=tids[s]; mem[d,s]=vals[s]/den
|
| 60 |
+
for s in range(12): topL[d,s]=tids[s]
|
| 61 |
+
return branches,mem,topL
|
| 62 |
+
|
| 63 |
+
@njit(cache=False)
|
| 64 |
+
def lookup_center(ct,cv,t):
|
| 65 |
+
lo=0; hi=ct.size
|
| 66 |
+
while lo<hi:
|
| 67 |
+
mid=(lo+hi)//2; x=ct[mid]
|
| 68 |
+
if x==65535 or x>=t: hi=mid
|
| 69 |
+
else: lo=mid+1
|
| 70 |
+
if lo<ct.size and ct[lo]==t: return cv[lo]
|
| 71 |
+
return 0.0
|
| 72 |
+
|
| 73 |
+
@njit(parallel=True,cache=False)
|
| 74 |
+
def residual_codes(indptr,indices,data,branches,center_terms,center_values,S):
|
| 75 |
+
N=indptr.size-1; F=branches.shape[1]
|
| 76 |
+
rt=np.full((N,F,S),np.uint16(65535),np.uint16)
|
| 77 |
+
rs=np.zeros((N,F,S),np.int8)
|
| 78 |
+
for d in prange(N):
|
| 79 |
+
a=indptr[d]; b=indptr[d+1]
|
| 80 |
+
for sl in range(F):
|
| 81 |
+
j=int(branches[d,sl])
|
| 82 |
+
if j==65535: continue
|
| 83 |
+
best=np.zeros(S,np.float32); bt=np.full(S,np.uint16(65535),np.uint16); bs=np.zeros(S,np.int8)
|
| 84 |
+
for p in range(a,b):
|
| 85 |
+
t=np.uint16(indices[p]); r=data[p]-lookup_center(center_terms[j],center_values[j],t); ar=abs(r)
|
| 86 |
+
# replace current minimum
|
| 87 |
+
mi=0; mv=best[0]
|
| 88 |
+
for q in range(1,S):
|
| 89 |
+
if best[q]<mv: mi=q; mv=best[q]
|
| 90 |
+
if ar>mv:
|
| 91 |
+
best[mi]=ar; bt[mi]=t; bs[mi]=1 if r>=0 else -1
|
| 92 |
+
# sort retained residuals descending by magnitude for determinism
|
| 93 |
+
for x in range(S):
|
| 94 |
+
mx=x
|
| 95 |
+
for y in range(x+1,S):
|
| 96 |
+
if best[y]>best[mx]: mx=y
|
| 97 |
+
if mx!=x:
|
| 98 |
+
tv=best[x]; best[x]=best[mx]; best[mx]=tv
|
| 99 |
+
tt=bt[x]; bt[x]=bt[mx]; bt[mx]=tt
|
| 100 |
+
ss=bs[x]; bs[x]=bs[mx]; bs[mx]=ss
|
| 101 |
+
for q in range(S): rt[d,sl,q]=bt[q]; rs[d,sl,q]=bs[q]
|
| 102 |
+
return rt,rs
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def prune_rows(mat,k):
|
| 106 |
+
rows=[]; cols=[]; vals=[]; mat=mat.tocsr()
|
| 107 |
+
for r in range(mat.shape[0]):
|
| 108 |
+
a,b=mat.indptr[r],mat.indptr[r+1]; idx=mat.indices[a:b]; dat=mat.data[a:b]
|
| 109 |
+
if len(dat)==0: continue
|
| 110 |
+
kk=min(k,len(dat)); pick=np.argpartition(dat,-kk)[-kk:]; pick=pick[np.argsort(dat[pick])[::-1]]
|
| 111 |
+
rows.extend([r]*kk); cols.extend(idx[pick].tolist()); vals.extend(dat[pick].astype(np.float32).tolist())
|
| 112 |
+
return sparse.csr_matrix((np.asarray(vals,np.float32),(np.asarray(rows,np.int32),np.asarray(cols,np.int32))),shape=mat.shape)
|
| 113 |
+
|
| 114 |
+
if __name__=='__main__':
|
| 115 |
+
t_all=time.time(); terms,idf,vocab=load_vocab(); np.save(GEOM/'idf.npy',idf);
|
| 116 |
+
with gzip.open(GEOM/'terms.pkl.gz','wb',compresslevel=1) as g: pickle.dump(terms,g,protocol=5)
|
| 117 |
+
print('GEOMETRY calibration on first 1,000,000 passages; lexical basis from all 8.84M',flush=True)
|
| 118 |
+
# X calibration
|
| 119 |
+
xcache=GEOM/'cal_X.npz'
|
| 120 |
+
if xcache.exists():
|
| 121 |
+
X=sparse.load_npz(xcache).tocsr(); print(' X checkpoint loaded',X.shape,X.nnz,flush=True)
|
| 122 |
+
else:
|
| 123 |
+
xs=[]
|
| 124 |
+
for sid in range(4):
|
| 125 |
+
t=time.time(); Xs=tfidf_shard(shard_path(sid),vocab,idf); xs.append(Xs); print(' tfidf shard',sid,Xs.shape,Xs.nnz,'sec',time.time()-t,flush=True)
|
| 126 |
+
X=sparse.vstack(xs,format='csr'); del xs; gc.collect(); print(' X',X.shape,X.nnz,flush=True); sparse.save_npz(xcache,X,compressed=False); print(' X checkpoint saved',flush=True)
|
| 127 |
+
# branches/topL
|
| 128 |
+
if (GEOM/'cal_branches.npy').exists() and (GEOM/'cal_memberships.npy').exists() and (GEOM/'cal_topL.npy').exists():
|
| 129 |
+
branches=np.load(GEOM/'cal_branches.npy'); mem=np.load(GEOM/'cal_memberships.npy'); topL=np.load(GEOM/'cal_topL.npy'); print(' membership checkpoint loaded',flush=True)
|
| 130 |
+
else:
|
| 131 |
+
t=time.time(); branches,mem,topL=topk_memberships(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),F); print(' memberships sec',time.time()-t,flush=True)
|
| 132 |
+
np.save(GEOM/'cal_branches.npy',branches); np.save(GEOM/'cal_memberships.npy',mem); np.save(GEOM/'cal_topL.npy',topL); print(' membership checkpoint saved',flush=True)
|
| 133 |
+
# centers exact using sparse algebra
|
| 134 |
+
if (GEOM/'center_terms.npy').exists() and (GEOM/'center_values.npy').exists():
|
| 135 |
+
center_terms=np.load(GEOM/'center_terms.npy'); center_values=np.load(GEOM/'center_values.npy'); print(' centers checkpoint loaded',flush=True)
|
| 136 |
+
else:
|
| 137 |
+
t=time.time(); wr=np.repeat(np.arange(N_CAL,dtype=np.int32),F); wc=branches.ravel().astype(np.int32); wd=mem.ravel(); valid=wc!=65535
|
| 138 |
+
W=sparse.csr_matrix((wd[valid],(wr[valid],wc[valid])),shape=(N_CAL,M),dtype=np.float32); del wr,wc,wd,valid
|
| 139 |
+
mass=np.asarray(W.sum(axis=0)).ravel().astype(np.float32)
|
| 140 |
+
center_terms=np.full((M,B),SENT,np.uint16); center_values=np.zeros((M,B),np.float32)
|
| 141 |
+
block=512
|
| 142 |
+
for start in range(0,M,block):
|
| 143 |
+
end=min(M,start+block); C=(W[:,start:end].T@X).tocsr()
|
| 144 |
+
for local in range(end-start):
|
| 145 |
+
j=start+local
|
| 146 |
+
if mass[j]<=0: continue
|
| 147 |
+
a,b=C.indptr[local],C.indptr[local+1]; idx=C.indices[a:b]; dat=C.data[a:b]/mass[j]
|
| 148 |
+
if len(dat)==0: continue
|
| 149 |
+
kk=min(B,len(dat)); pick=np.argpartition(dat,-kk)[-kk:]; ii=idx[pick]; vv=dat[pick]; oo=np.argsort(ii); ii=ii[oo]; vv=vv[oo]
|
| 150 |
+
center_terms[j,:kk]=ii.astype(np.uint16); center_values[j,:kk]=vv.astype(np.float32)
|
| 151 |
+
if start%4096==0: print(' centers',end,'/',M,flush=True)
|
| 152 |
+
np.save(GEOM/'center_terms.npy',center_terms); np.save(GEOM/'center_values.npy',center_values); del W,mass,C; gc.collect(); print(' centers sec',time.time()-t,flush=True)
|
| 153 |
+
# residuals
|
| 154 |
+
if (GEOM/'cal_res_terms.npy').exists() and (GEOM/'cal_res_signs.npy').exists():
|
| 155 |
+
rt=np.load(GEOM/'cal_res_terms.npy',mmap_mode='r'); rs=np.load(GEOM/'cal_res_signs.npy',mmap_mode='r'); print(' residual checkpoint loaded',flush=True)
|
| 156 |
+
else:
|
| 157 |
+
t=time.time(); rt,rs=residual_codes(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),branches,center_terms,center_values,S); print(' residual sec',time.time()-t,flush=True); np.save(GEOM/'cal_res_terms.npy',rt); np.save(GEOM/'cal_res_signs.npy',rs); print(' residual checkpoint saved',flush=True)
|
| 158 |
+
# reliability global
|
| 159 |
+
total_memberships=int(np.sum(branches!=SENT)); gcnt=np.zeros(M,np.float64); gsum=np.zeros(M,np.float64)
|
| 160 |
+
for d0 in range(0,N_CAL,50_000):
|
| 161 |
+
tt=rt[d0:d0+50_000].ravel(); zz=rs[d0:d0+50_000].ravel().astype(np.float64); ok=tt!=SENT
|
| 162 |
+
gcnt += np.bincount(tt[ok].astype(np.int64),minlength=M)
|
| 163 |
+
gsum += np.bincount(tt[ok].astype(np.int64),weights=zz[ok],minlength=M)
|
| 164 |
+
ge2=gcnt/max(1,total_memberships); ge1=gsum/max(1,total_memberships); gvar=np.maximum(ge2-ge1*ge1,0.)
|
| 165 |
+
# branch order calibration
|
| 166 |
+
flat=branches.ravel(); valid=np.flatnonzero(flat!=SENT); order=valid[np.argsort(flat[valid],kind='stable')]; sorted_br=flat[order].astype(np.int64); counts=np.bincount(sorted_br,minlength=M); offs=np.zeros(M+1,np.int64); np.cumsum(counts,out=offs[1:])
|
| 167 |
+
f_rt=rt.reshape(N_CAL*F,S); f_rs=rs.reshape(N_CAL*F,S)
|
| 168 |
+
# Memory-bounded reliability CSR. Upper bound is one entry per residual occurrence.
|
| 169 |
+
max_rel=N_CAL*F*S
|
| 170 |
+
rel_i=np.memmap(GEOM/'rel_indices.u16',dtype=np.uint16,mode='w+',shape=(max_rel,))
|
| 171 |
+
rel_v=np.memmap(GEOM/'rel_data.f32',dtype=np.float32,mode='w+',shape=(max_rel,))
|
| 172 |
+
rel_p=np.zeros(M+1,np.uint64); pos_rel=0
|
| 173 |
+
t=time.time()
|
| 174 |
+
for j in range(M):
|
| 175 |
+
a,b=offs[j],offs[j+1]; mpos=order[a:b]; nj=len(mpos)
|
| 176 |
+
if nj>0:
|
| 177 |
+
tj=f_rt[mpos].ravel(); sj=f_rs[mpos].ravel().astype(np.float64); ok=tj!=SENT
|
| 178 |
+
if np.any(ok):
|
| 179 |
+
u,inv=np.unique(tj[ok],return_inverse=True); cnt=np.bincount(inv).astype(np.float64); sm=np.bincount(inv,weights=sj[ok]).astype(np.float64)
|
| 180 |
+
e2=cnt/nj; e1=sm/nj; lv=np.maximum(e2-e1*e1,0.); shr=(cnt/(cnt+TAU))*lv+(TAU/(cnt+TAU))*gvar[u.astype(np.int64)]; w=np.power(shr+EPS,BETA)
|
| 181 |
+
if len(w) and np.isfinite(w).all() and w.mean()>0: w=w/w.mean()
|
| 182 |
+
nrel=len(u); rel_i[pos_rel:pos_rel+nrel]=u.astype(np.uint16); rel_v[pos_rel:pos_rel+nrel]=w.astype(np.float32); pos_rel+=nrel
|
| 183 |
+
rel_p[j+1]=pos_rel
|
| 184 |
+
if j%5000==0 and j: print(' reliability branch',j,'pairs',pos_rel,flush=True)
|
| 185 |
+
rel_i.flush(); rel_v.flush(); np.save(GEOM/'rel_indptr.npy',rel_p); np.save(GEOM/'global_sign_var.npy',gvar.astype(np.float32));
|
| 186 |
+
with open(GEOM/'rel_meta.json','w') as f: json.dump({'nnz':int(pos_rel),'max_entries':int(max_rel)},f)
|
| 187 |
+
print(' reliability nnz',pos_rel,'sec',time.time()-t,flush=True)
|
| 188 |
+
del rt,rs,order,flat,valid,sorted_br,counts,offs,f_rt,f_rs,rel_i,rel_v,rel_p; gc.collect()
|
| 189 |
+
# graph exact from calibration topL: n_i and unordered pair counts
|
| 190 |
+
t=time.time(); flatL=topL.ravel(); good=flatL!=SENT; ni=np.bincount(flatL[good].astype(np.int64),minlength=M).astype(np.float64); del flatL,good
|
| 191 |
+
maxpairs=N_CAL*66; pairkeys=np.full(maxpairs,np.uint32(0xffffffff),np.uint32); pos=0
|
| 192 |
+
# vectorized per pair position across documents: only 66 loops, each handles 1m rows
|
| 193 |
+
for a in range(L):
|
| 194 |
+
ia=topL[:,a]
|
| 195 |
+
for b in range(a+1,L):
|
| 196 |
+
ib=topL[:,b]; ok=(ia!=SENT)&(ib!=SENT); n=int(ok.sum())
|
| 197 |
+
x=ia[ok].astype(np.uint32); y=ib[ok].astype(np.uint32); lo=np.minimum(x,y); hi=np.maximum(x,y); pairkeys[pos:pos+n]=(lo<<16)|hi; pos+=n
|
| 198 |
+
print(' pair occurrences',pos,'sorting...',flush=True); keys=pairkeys[:pos]; keys.sort(); del pairkeys,topL; gc.collect()
|
| 199 |
+
# run-length encode sorted keys without np.unique's large extra sort
|
| 200 |
+
change=np.empty(len(keys),dtype=bool); change[0]=True; change[1:]=keys[1:]!=keys[:-1]; starts=np.flatnonzero(change); ukeys=keys[starts].copy(); cnt=np.diff(np.append(starts,len(keys))).astype(np.float32); del keys,change,starts; gc.collect(); print(' unique pairs',len(ukeys),flush=True)
|
| 201 |
+
ii=(ukeys>>16).astype(np.int32); jj=(ukeys & np.uint32(65535)).astype(np.int32); nij=cnt.astype(np.float64); ppmi=np.log((nij*float(N_CAL)+1e-12)/(ni[ii]*ni[jj]+1e-12)); ppmi=np.maximum(ppmi,0.); score=(nij/(nij+GRAPH_TAU))*ppmi; mask=score>0; ii=ii[mask]; jj=jj[mask]; sv=score[mask].astype(np.float32); del ukeys,cnt,nij,ppmi,score,mask; gc.collect(); print(' positive pair edges',len(sv),flush=True)
|
| 202 |
+
rows=np.concatenate([ii,jj]); cols=np.concatenate([jj,ii]); vals=np.concatenate([sv,sv]); del ii,jj,sv; Afull=sparse.csr_matrix((vals,(rows,cols)),shape=(M,M)); del rows,cols,vals; gc.collect(); A=prune_rows(Afull,ASSOC_K); del Afull; gc.collect(); sparse.save_npz(GEOM/'assoc_ppmi.npz',A,compressed=True); print(' A nnz',A.nnz,flush=True)
|
| 203 |
+
An=normalize(A,norm='l2',axis=1,copy=True); gr=[]; gc2=[]; gv=[]; bs=256
|
| 204 |
+
for start in range(0,M,bs):
|
| 205 |
+
end=min(M,start+bs); sim=(An[start:end]@An.T).tocsr()
|
| 206 |
+
for local in range(end-start):
|
| 207 |
+
i=start+local; a,b=sim.indptr[local],sim.indptr[local+1]; js=sim.indices[a:b]; vv2=sim.data[a:b]; mk=(js!=i)&(vv2>0); js=js[mk]; vv2=vv2[mk]
|
| 208 |
+
if len(vv2)==0: continue
|
| 209 |
+
kk=min(ROUTE_K,len(vv2)); pk=np.argpartition(vv2,-kk)[-kk:]; pk=pk[np.argsort(vv2[pk])[::-1]]; gr.extend([i]*kk); gc2.extend(js[pk].tolist()); gv.extend(vv2[pk].astype(np.float32).tolist())
|
| 210 |
+
if start%4096==0: print(' G',end,'/',M,flush=True)
|
| 211 |
+
G=sparse.csr_matrix((np.asarray(gv,np.float32),(np.asarray(gr,np.int32),np.asarray(gc2,np.int32))),shape=(M,M)); sparse.save_npz(GEOM/'context_similarity.npz',G,compressed=True); print(' G nnz',G.nnz,'graph sec',time.time()-t,flush=True)
|
| 212 |
+
# Save metadata
|
| 213 |
+
with open(GEOM/'meta.json','w') as f: json.dump({'calibration_docs':N_CAL,'full_corpus_docs':8_841_823,'F':F,'B':B,'S':S,'L':L,'tau':TAU,'beta':BETA,'graph_tau':GRAPH_TAU,'assoc_k':ASSOC_K,'route_k':ROUTE_K,'build_seconds':time.time()-t_all},f,indent=2)
|
| 214 |
+
print('GEOMETRY DONE total sec',time.time()-t_all,flush=True)
|
experiments/msmarco_scale/msmarco_build_geometry_uniform1m.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import gzip,json,pickle,time,gc
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scipy import sparse
|
| 6 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 7 |
+
from sklearn.preprocessing import normalize
|
| 8 |
+
from numba import set_num_threads
|
| 9 |
+
import sys
|
| 10 |
+
sys.path.insert(0,'/mnt/data')
|
| 11 |
+
import msmarco_build_geometry as base
|
| 12 |
+
|
| 13 |
+
ROOT=Path('/mnt/data'); WORK=ROOT/'msmarco_scale_work'; GEOM=WORK/'geometry_uniform1m'; GEOM.mkdir(parents=True,exist_ok=True)
|
| 14 |
+
N=8_841_823; N_CAL=1_000_000; M=50_000; F=4; B=64; S=16; L=12
|
| 15 |
+
TAU=20.; BETA=-.2; EPS=1e-6; GRAPH_TAU=10.; ASSOC_K=64; ROUTE_K=32
|
| 16 |
+
SENT=np.uint16(65535); SEED=20260815
|
| 17 |
+
set_num_threads(5)
|
| 18 |
+
|
| 19 |
+
def load_vocab():
|
| 20 |
+
with gzip.open(WORK/'final_vocab_50k.pkl.gz','rb') as g: z=pickle.load(g)
|
| 21 |
+
terms=z['terms'].tolist(); idf=np.asarray(z['idf'],np.float32)
|
| 22 |
+
return terms,idf,{t:i for i,t in enumerate(terms)}
|
| 23 |
+
|
| 24 |
+
def shard_path(i):
|
| 25 |
+
hits=list(ROOT.glob(f'corpus_{i:04d}.jsonl*.gz')); assert len(hits)==1,(i,hits); return hits[0]
|
| 26 |
+
|
| 27 |
+
def selected_tfidf_shard(sid, wanted_local, vocab, idf):
|
| 28 |
+
wanted=np.asarray(wanted_local,np.int64)
|
| 29 |
+
texts=[]; p=0
|
| 30 |
+
if wanted.size==0:
|
| 31 |
+
return sparse.csr_matrix((0,M),dtype=np.float32)
|
| 32 |
+
with gzip.open(shard_path(sid),'rt',encoding='utf-8') as f:
|
| 33 |
+
for i,line in enumerate(f):
|
| 34 |
+
if p>=wanted.size: break
|
| 35 |
+
if i==wanted[p]:
|
| 36 |
+
o=json.loads(line); texts.append(((o.get('title') or '')+' '+(o.get('text') or '')).strip()); p+=1
|
| 37 |
+
assert p==wanted.size,(sid,p,wanted.size)
|
| 38 |
+
cv=CountVectorizer(vocabulary=vocab,lowercase=True,token_pattern=r'(?u)\b\w\w+\b',dtype=np.int32)
|
| 39 |
+
X=cv.transform(texts).tocsr().astype(np.float32); X.data*=idf[X.indices]; normalize(X,norm='l2',axis=1,copy=False); X.sort_indices()
|
| 40 |
+
return X
|
| 41 |
+
|
| 42 |
+
def prune_rows(mat,k): return base.prune_rows(mat,k)
|
| 43 |
+
|
| 44 |
+
if __name__=='__main__':
|
| 45 |
+
t_all=time.time(); terms,idf,vocab=load_vocab(); np.save(GEOM/'idf.npy',idf)
|
| 46 |
+
with gzip.open(GEOM/'terms.pkl.gz','wb',compresslevel=1) as g: pickle.dump(terms,g,protocol=5)
|
| 47 |
+
sp=GEOM/'sample_ids.npy'
|
| 48 |
+
if sp.exists(): sample=np.load(sp)
|
| 49 |
+
else:
|
| 50 |
+
rng=np.random.default_rng(SEED); sample=np.sort(rng.choice(N,size=N_CAL,replace=False).astype(np.int64)); np.save(sp,sample)
|
| 51 |
+
assert len(sample)==N_CAL and sample[0]>=0 and sample[-1]<N
|
| 52 |
+
print('UNIFORM GEOMETRY calibration: deterministic 1,000,000-sample across 8,841,823 passages; seed',SEED,flush=True)
|
| 53 |
+
print(' sample id range',int(sample[0]),int(sample[-1]),'mean',float(sample.mean()),flush=True)
|
| 54 |
+
xcache=GEOM/'cal_X.npz'
|
| 55 |
+
if xcache.exists():
|
| 56 |
+
X=sparse.load_npz(xcache).tocsr(); print(' X checkpoint loaded',X.shape,X.nnz,flush=True)
|
| 57 |
+
else:
|
| 58 |
+
xs=[]
|
| 59 |
+
for sid in range(36):
|
| 60 |
+
lo=sid*250_000; hi=min(N,lo+250_000); a=np.searchsorted(sample,lo); b=np.searchsorted(sample,hi); local=sample[a:b]-lo
|
| 61 |
+
t=time.time(); Xs=selected_tfidf_shard(sid,local,vocab,idf); xs.append(Xs)
|
| 62 |
+
print(' tfidf selected shard',sid,'n',Xs.shape[0],'nnz',Xs.nnz,'sec',time.time()-t,flush=True)
|
| 63 |
+
X=sparse.vstack(xs,format='csr'); del xs; gc.collect(); assert X.shape[0]==N_CAL
|
| 64 |
+
print(' X',X.shape,X.nnz,flush=True); sparse.save_npz(xcache,X,compressed=False); print(' X checkpoint saved',flush=True)
|
| 65 |
+
# memberships and topL
|
| 66 |
+
t=time.time(); branches,mem,topL=base.topk_memberships(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),F)
|
| 67 |
+
print(' memberships sec',time.time()-t,flush=True); np.save(GEOM/'cal_branches.npy',branches); np.save(GEOM/'cal_memberships.npy',mem); np.save(GEOM/'cal_topL.npy',topL)
|
| 68 |
+
# centers
|
| 69 |
+
t=time.time(); wr=np.repeat(np.arange(N_CAL,dtype=np.int32),F); wc=branches.ravel().astype(np.int32); wd=mem.ravel(); valid=wc!=65535
|
| 70 |
+
W=sparse.csr_matrix((wd[valid],(wr[valid],wc[valid])),shape=(N_CAL,M),dtype=np.float32); del wr,wc,wd,valid
|
| 71 |
+
mass=np.asarray(W.sum(axis=0)).ravel().astype(np.float32)
|
| 72 |
+
center_terms=np.full((M,B),SENT,np.uint16); center_values=np.zeros((M,B),np.float32)
|
| 73 |
+
block=512
|
| 74 |
+
for start in range(0,M,block):
|
| 75 |
+
end=min(M,start+block); C=(W[:,start:end].T@X).tocsr()
|
| 76 |
+
for local in range(end-start):
|
| 77 |
+
j=start+local
|
| 78 |
+
if mass[j]<=0: continue
|
| 79 |
+
a,b=C.indptr[local],C.indptr[local+1]; idx=C.indices[a:b]; dat=C.data[a:b]/mass[j]
|
| 80 |
+
if len(dat)==0: continue
|
| 81 |
+
kk=min(B,len(dat)); pick=np.argpartition(dat,-kk)[-kk:]; ii=idx[pick]; vv=dat[pick]; oo=np.argsort(ii); ii=ii[oo]; vv=vv[oo]
|
| 82 |
+
center_terms[j,:kk]=ii.astype(np.uint16); center_values[j,:kk]=vv.astype(np.float32)
|
| 83 |
+
if start%4096==0: print(' centers',end,'/',M,flush=True)
|
| 84 |
+
np.save(GEOM/'center_terms.npy',center_terms); np.save(GEOM/'center_values.npy',center_values); del W,mass,C; gc.collect(); print(' centers sec',time.time()-t,flush=True)
|
| 85 |
+
# calibration residuals
|
| 86 |
+
t=time.time(); rt,rs=base.residual_codes(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),branches,center_terms,center_values,S)
|
| 87 |
+
print(' residual sec',time.time()-t,flush=True); np.save(GEOM/'cal_res_terms.npy',rt); np.save(GEOM/'cal_res_signs.npy',rs)
|
| 88 |
+
# reliability
|
| 89 |
+
total_memberships=int(np.sum(branches!=SENT)); gcnt=np.zeros(M,np.float64); gsum=np.zeros(M,np.float64)
|
| 90 |
+
for d0 in range(0,N_CAL,50_000):
|
| 91 |
+
tt=rt[d0:d0+50_000].ravel(); zz=rs[d0:d0+50_000].ravel().astype(np.float64); ok=tt!=SENT
|
| 92 |
+
gcnt += np.bincount(tt[ok].astype(np.int64),minlength=M); gsum += np.bincount(tt[ok].astype(np.int64),weights=zz[ok],minlength=M)
|
| 93 |
+
ge2=gcnt/max(1,total_memberships); ge1=gsum/max(1,total_memberships); gvar=np.maximum(ge2-ge1*ge1,0.)
|
| 94 |
+
flat=branches.ravel(); valid=np.flatnonzero(flat!=SENT); order=valid[np.argsort(flat[valid],kind='stable')]; sorted_br=flat[order].astype(np.int64); counts=np.bincount(sorted_br,minlength=M); offs=np.zeros(M+1,np.int64); np.cumsum(counts,out=offs[1:])
|
| 95 |
+
f_rt=rt.reshape(N_CAL*F,S); f_rs=rs.reshape(N_CAL*F,S)
|
| 96 |
+
max_rel=N_CAL*F*S; rel_i=np.memmap(GEOM/'rel_indices.u16',dtype=np.uint16,mode='w+',shape=(max_rel,)); rel_v=np.memmap(GEOM/'rel_data.f32',dtype=np.float32,mode='w+',shape=(max_rel,)); rel_p=np.zeros(M+1,np.uint64); pos_rel=0; t=time.time()
|
| 97 |
+
for j in range(M):
|
| 98 |
+
a,b=offs[j],offs[j+1]; mpos=order[a:b]; nj=len(mpos)
|
| 99 |
+
if nj>0:
|
| 100 |
+
tj=f_rt[mpos].ravel(); sj=f_rs[mpos].ravel().astype(np.float64); ok=tj!=SENT
|
| 101 |
+
if np.any(ok):
|
| 102 |
+
u,inv=np.unique(tj[ok],return_inverse=True); cnt=np.bincount(inv).astype(np.float64); sm=np.bincount(inv,weights=sj[ok]).astype(np.float64)
|
| 103 |
+
e2=cnt/nj; e1=sm/nj; lv=np.maximum(e2-e1*e1,0.); shr=(cnt/(cnt+TAU))*lv+(TAU/(cnt+TAU))*gvar[u.astype(np.int64)]; w=np.power(shr+EPS,BETA)
|
| 104 |
+
if len(w) and np.isfinite(w).all() and w.mean()>0: w=w/w.mean()
|
| 105 |
+
nrel=len(u); rel_i[pos_rel:pos_rel+nrel]=u.astype(np.uint16); rel_v[pos_rel:pos_rel+nrel]=w.astype(np.float32); pos_rel+=nrel
|
| 106 |
+
rel_p[j+1]=pos_rel
|
| 107 |
+
if j%5000==0 and j: print(' reliability branch',j,'pairs',pos_rel,flush=True)
|
| 108 |
+
rel_i.flush(); rel_v.flush(); np.save(GEOM/'rel_indptr.npy',rel_p); np.save(GEOM/'global_sign_var.npy',gvar.astype(np.float32))
|
| 109 |
+
with open(GEOM/'rel_meta.json','w') as f: json.dump({'nnz':int(pos_rel),'max_entries':int(max_rel)},f)
|
| 110 |
+
print(' reliability nnz',pos_rel,'sec',time.time()-t,flush=True)
|
| 111 |
+
del rt,rs,order,flat,valid,sorted_br,counts,offs,f_rt,f_rs,rel_i,rel_v,rel_p; gc.collect()
|
| 112 |
+
# graph from same uniform calibration sample
|
| 113 |
+
t=time.time(); flatL=topL.ravel(); good=flatL!=SENT; ni=np.bincount(flatL[good].astype(np.int64),minlength=M).astype(np.float64); del flatL,good
|
| 114 |
+
maxpairs=N_CAL*66; pairkeys=np.full(maxpairs,np.uint32(0xffffffff),np.uint32); pos=0
|
| 115 |
+
for a in range(L):
|
| 116 |
+
ia=topL[:,a]
|
| 117 |
+
for b in range(a+1,L):
|
| 118 |
+
ib=topL[:,b]; ok=(ia!=SENT)&(ib!=SENT); n=int(ok.sum()); x=ia[ok].astype(np.uint32); y=ib[ok].astype(np.uint32); lo=np.minimum(x,y); hi=np.maximum(x,y); pairkeys[pos:pos+n]=(lo<<16)|hi; pos+=n
|
| 119 |
+
print(' pair occurrences',pos,'sorting...',flush=True); keys=pairkeys[:pos]; keys.sort(); del pairkeys,topL; gc.collect()
|
| 120 |
+
change=np.empty(len(keys),dtype=bool); change[0]=True; change[1:]=keys[1:]!=keys[:-1]; starts=np.flatnonzero(change); ukeys=keys[starts].copy(); cnt=np.diff(np.append(starts,len(keys))).astype(np.float32); del keys,change,starts; gc.collect(); print(' unique pairs',len(ukeys),flush=True)
|
| 121 |
+
ii=(ukeys>>16).astype(np.int32); jj=(ukeys & np.uint32(65535)).astype(np.int32); nij=cnt.astype(np.float64); ppmi=np.log((nij*float(N_CAL)+1e-12)/(ni[ii]*ni[jj]+1e-12)); ppmi=np.maximum(ppmi,0.); score=(nij/(nij+GRAPH_TAU))*ppmi; mask=score>0; ii=ii[mask]; jj=jj[mask]; sv=score[mask].astype(np.float32); del ukeys,cnt,nij,ppmi,score,mask; gc.collect(); print(' positive pair edges',len(sv),flush=True)
|
| 122 |
+
rows=np.concatenate([ii,jj]); cols=np.concatenate([jj,ii]); vals=np.concatenate([sv,sv]); del ii,jj,sv; Afull=sparse.csr_matrix((vals,(rows,cols)),shape=(M,M)); del rows,cols,vals; gc.collect(); A=prune_rows(Afull,ASSOC_K); del Afull; gc.collect(); sparse.save_npz(GEOM/'assoc_ppmi.npz',A,compressed=True); print(' A nnz',A.nnz,flush=True)
|
| 123 |
+
An=normalize(A,norm='l2',axis=1,copy=True); gr=[]; gc2=[]; gv=[]; bs=256
|
| 124 |
+
for start in range(0,M,bs):
|
| 125 |
+
end=min(M,start+bs); sim=(An[start:end]@An.T).tocsr()
|
| 126 |
+
for local in range(end-start):
|
| 127 |
+
i=start+local; a,b=sim.indptr[local],sim.indptr[local+1]; js=sim.indices[a:b]; vv2=sim.data[a:b]; mk=(js!=i)&(vv2>0); js=js[mk]; vv2=vv2[mk]
|
| 128 |
+
if len(vv2)==0: continue
|
| 129 |
+
kk=min(ROUTE_K,len(vv2)); pk=np.argpartition(vv2,-kk)[-kk:]; pk=pk[np.argsort(vv2[pk])[::-1]]; gr.extend([i]*kk); gc2.extend(js[pk].tolist()); gv.extend(vv2[pk].astype(np.float32).tolist())
|
| 130 |
+
if start%4096==0: print(' G',end,'/',M,flush=True)
|
| 131 |
+
G=sparse.csr_matrix((np.asarray(gv,np.float32),(np.asarray(gr,np.int32),np.asarray(gc2,np.int32))),shape=(M,M)); sparse.save_npz(GEOM/'context_similarity.npz',G,compressed=True); print(' G nnz',G.nnz,'graph sec',time.time()-t,flush=True)
|
| 132 |
+
with open(GEOM/'meta.json','w') as f: json.dump({'calibration_docs':N_CAL,'calibration':'deterministic uniform sample without replacement','seed':SEED,'full_corpus_docs':N,'F':F,'B':B,'S':S,'L':L,'tau':TAU,'beta':BETA,'graph_tau':GRAPH_TAU,'assoc_k':ASSOC_K,'route_k':ROUTE_K,'build_seconds':time.time()-t_all},f,indent=2)
|
| 133 |
+
print('UNIFORM GEOMETRY DONE total sec',time.time()-t_all,flush=True)
|
experiments/msmarco_scale/msmarco_build_s32_reliability.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import json,time,gc,os
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy import sparse
|
| 5 |
+
import sys
|
| 6 |
+
sys.path.insert(0,'/mnt/data')
|
| 7 |
+
import msmarco_build_geometry as base
|
| 8 |
+
W=Path('/mnt/data/msmarco_scale_work'); SRC=W/'geometry_uniform1m'; G=W/'geometry_uniform1m_s32'; G.mkdir(exist_ok=True)
|
| 9 |
+
N=1_000_000; M=50_000; F=4; S=32; TAU=20.; BETA=-.2; EPS=1e-6; SENT=np.uint16(65535)
|
| 10 |
+
# geometry-independent files are symlinked
|
| 11 |
+
for name in ['idf.npy','terms.pkl.gz','center_terms.npy','center_values.npy','assoc_ppmi.npz','context_similarity.npz','sample_ids.npy','cal_X.npz','cal_branches.npy','cal_memberships.npy','cal_topL.npy']:
|
| 12 |
+
p=G/name
|
| 13 |
+
if not p.exists(): p.symlink_to(SRC/name)
|
| 14 |
+
X=sparse.load_npz(SRC/'cal_X.npz').tocsr(); branches=np.load(SRC/'cal_branches.npy'); ct=np.load(SRC/'center_terms.npy',mmap_mode='r'); cv=np.load(SRC/'center_values.npy',mmap_mode='r')
|
| 15 |
+
t=time.time(); rt,rs=base.residual_codes(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),branches,ct,cv,S); print('s32 residual sec',time.time()-t,flush=True); np.save(G/'cal_res_terms.npy',rt); np.save(G/'cal_res_signs.npy',rs)
|
| 16 |
+
# reliability exact same estimator with S32 observations
|
| 17 |
+
total_memberships=int(np.sum(branches!=SENT)); gcnt=np.zeros(M,np.float64); gsum=np.zeros(M,np.float64)
|
| 18 |
+
for d0 in range(0,N,50_000):
|
| 19 |
+
tt=rt[d0:d0+50_000].ravel(); zz=rs[d0:d0+50_000].ravel().astype(np.float64); ok=tt!=SENT
|
| 20 |
+
gcnt += np.bincount(tt[ok].astype(np.int64),minlength=M); gsum += np.bincount(tt[ok].astype(np.int64),weights=zz[ok],minlength=M)
|
| 21 |
+
ge2=gcnt/max(1,total_memberships); ge1=gsum/max(1,total_memberships); gvar=np.maximum(ge2-ge1*ge1,0.)
|
| 22 |
+
flat=branches.ravel(); valid=np.flatnonzero(flat!=SENT); order=valid[np.argsort(flat[valid],kind='stable')]; sorted_br=flat[order].astype(np.int64); counts=np.bincount(sorted_br,minlength=M); offs=np.zeros(M+1,np.int64); np.cumsum(counts,out=offs[1:]); f_rt=rt.reshape(N*F,S); f_rs=rs.reshape(N*F,S)
|
| 23 |
+
max_rel=N*F*S; rel_i=np.memmap(G/'rel_indices.u16',np.uint16,'w+',shape=(max_rel,)); rel_v=np.memmap(G/'rel_data.f32',np.float32,'w+',shape=(max_rel,)); rel_p=np.zeros(M+1,np.uint64); pos=0; t=time.time()
|
| 24 |
+
for j in range(M):
|
| 25 |
+
a,b=offs[j],offs[j+1]; mpos=order[a:b]; nj=len(mpos)
|
| 26 |
+
if nj:
|
| 27 |
+
tj=f_rt[mpos].ravel(); sj=f_rs[mpos].ravel().astype(np.float64); ok=tj!=SENT
|
| 28 |
+
if np.any(ok):
|
| 29 |
+
u,inv=np.unique(tj[ok],return_inverse=True); cnt=np.bincount(inv).astype(np.float64); sm=np.bincount(inv,weights=sj[ok]).astype(np.float64); e2=cnt/nj; e1=sm/nj; lv=np.maximum(e2-e1*e1,0.); shr=(cnt/(cnt+TAU))*lv+(TAU/(cnt+TAU))*gvar[u.astype(np.int64)]; ww=np.power(shr+EPS,BETA)
|
| 30 |
+
if len(ww) and np.isfinite(ww).all() and ww.mean()>0: ww=ww/ww.mean()
|
| 31 |
+
n=len(u); rel_i[pos:pos+n]=u.astype(np.uint16); rel_v[pos:pos+n]=ww.astype(np.float32); pos+=n
|
| 32 |
+
rel_p[j+1]=pos
|
| 33 |
+
if j and j%5000==0: print('rel',j,pos,flush=True)
|
| 34 |
+
rel_i.flush(); rel_v.flush(); np.save(G/'rel_indptr.npy',rel_p); np.save(G/'global_sign_var.npy',gvar.astype(np.float32)); json.dump({'nnz':int(pos),'max_entries':int(max_rel)},open(G/'rel_meta.json','w'))
|
| 35 |
+
meta=json.load(open(SRC/'meta.json')); meta['S']=32; meta['capacity_test']='same uniform1m centers and graph; only residual width/reliability changed 16->32'; json.dump(meta,open(G/'meta.json','w'),indent=2)
|
| 36 |
+
print('S32 REL DONE nnz',pos,'sec',time.time()-t,flush=True)
|
experiments/msmarco_scale/msmarco_coordination_features.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numba import njit,prange,set_num_threads
|
| 6 |
+
sys.path.insert(0,'/mnt/data')
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
ROOT=m.ROOT; WORK=m.WORK; OUT=WORK/'structural_fusion'; OUT.mkdir(exist_ok=True); set_num_threads(5)
|
| 9 |
+
z=np.load(WORK/'amplitude_diag'/'fixed_eta1_pools.npz',allow_pickle=False); qids=[str(x) for x in z['qids'].tolist()]; valid=z['valid'].astype(np.int32); docs=z['docs']; idx=m.FullIndex(); M=m.M
|
| 10 |
+
texts=m.load_query_texts(qids)
|
| 11 |
+
@njit(parallel=True,cache=False)
|
| 12 |
+
def extras(dd,ip,ids,lexvec,dl,avgdl):
|
| 13 |
+
n=len(dd); cnt=np.zeros(n,np.float32); raw=np.zeros(n,np.float32); lf=np.zeros(n,np.float32)
|
| 14 |
+
for z in prange(n):
|
| 15 |
+
d=int(dd[z]); a=int(ip[d]); b=int(ip[d+1]); c=0.0; r=0.0
|
| 16 |
+
for k in range(a,b):
|
| 17 |
+
t=int(ids[k]); v=lexvec[t]
|
| 18 |
+
if v>0: c+=1.; r+=v
|
| 19 |
+
cnt[z]=c; raw[z]=r; lf[z]=(1.0-m.LENGTH_B)+m.LENGTH_B*(float(dl[d])/avgdl)
|
| 20 |
+
return cnt,raw,lf
|
| 21 |
+
_=extras(np.array([0],np.uint32),idx.sup_ip,idx.sup_ids,np.zeros(M,np.float32),idx.dl,idx.avgdl)
|
| 22 |
+
COUNT=np.zeros_like(z['tail'],np.float32); RAW=np.zeros_like(COUNT); LF=np.zeros_like(COUNT); QTERMS=np.zeros(len(qids),np.int16); times=[]
|
| 23 |
+
for i,qid in enumerate(qids):
|
| 24 |
+
k=int(valid[i]);
|
| 25 |
+
if not k:continue
|
| 26 |
+
q=idx.query_vec(texts[qid]); QTERMS[i]=len(q.indices); lv=np.zeros(M,np.float32); lv[q.indices]=idx.idf[q.indices]
|
| 27 |
+
t=time.perf_counter(); c,r,l=extras(docs[i,:k],idx.sup_ip,idx.sup_ids,lv,idx.dl,idx.avgdl); times.append((time.perf_counter()-t)*1000); COUNT[i,:k]=c; RAW[i,:k]=r; LF[i,:k]=l
|
| 28 |
+
if (i+1)%200==0: print(i+1,float(np.median(times)),flush=True)
|
| 29 |
+
np.savez_compressed(OUT/'coordination_features.npz',qids=np.asarray(qids),valid=valid,qcount=COUNT,rawlex=RAW,lenfac=LF,qterms=QTERMS)
|
| 30 |
+
print('DONE',float(np.median(times)),float(np.percentile(times,95)),flush=True)
|
experiments/msmarco_scale/msmarco_coordination_sweep.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,json,math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
sys.path.insert(0,'/mnt/data')
|
| 6 |
+
import msmarco_full_search_uniform1m as m
|
| 7 |
+
ROOT=m.ROOT; WORK=m.WORK; OUT=WORK/'structural_fusion'; OUT.mkdir(exist_ok=True)
|
| 8 |
+
z=np.load(WORK/'amplitude_diag'/'fixed_eta1_pools.npz',allow_pickle=False); c=np.load(OUT/'coordination_features.npz',allow_pickle=False)
|
| 9 |
+
qids=[str(x) for x in z['qids'].tolist()]; valid=z['valid'].astype(int); docs=z['docs']; T=z['tail']; L=z['lex']; S=z['sem']; QC=c['qcount']; RAW=c['rawlex']; LF=c['lenfac']; QT=c['qterms'].astype(int)
|
| 10 |
+
qrels=m.qrels_from_tsv(ROOT/'train.tsv',qids,positive_only=True)
|
| 11 |
+
|
| 12 |
+
def top100(sc):
|
| 13 |
+
n=len(sc); kk=min(100,n)
|
| 14 |
+
if n<=kk:return np.argsort(sc)[::-1]
|
| 15 |
+
ii=np.argpartition(sc,-kk)[-kk:]; return ii[np.argsort(sc[ii])[::-1]]
|
| 16 |
+
|
| 17 |
+
def eval_model(name, scorer):
|
| 18 |
+
run={}
|
| 19 |
+
for i,qid in enumerate(qids):
|
| 20 |
+
k=valid[i]
|
| 21 |
+
if k<=0: run[qid]=[]; continue
|
| 22 |
+
sc=scorer(i,k); oo=top100(sc); run[qid]=[int(x) for x in docs[i,oo]]
|
| 23 |
+
met=m.eval_run(run,qrels); row={'name':name,**met}; print(name,round(met['nDCG@10'],6),round(met['MRR@10'],6),round(met['R@100'],6),flush=True); return row
|
| 24 |
+
|
| 25 |
+
def Z(x): return m.zscore(x)
|
| 26 |
+
rows=[]
|
| 27 |
+
rows.append(eval_model('baseline',lambda i,k:Z(T[i,:k])+4*Z(L[i,:k])+.1*Z(S[i,:k])))
|
| 28 |
+
# recover doc length ratio from current b=.2 denominator LF=.8+.2*r
|
| 29 |
+
# stage 1: length correction b only, current fusion weights
|
| 30 |
+
for bb in [0.,.05,.1,.15,.2,.3,.4,.5,.75,1.]:
|
| 31 |
+
def f(i,k,bb=bb):
|
| 32 |
+
r=(LF[i,:k]-.8)/.2; den=(1-bb)+bb*r; lx=RAW[i,:k]/np.maximum(den,1e-6); return Z(T[i,:k])+4*Z(lx)+.1*Z(S[i,:k])
|
| 33 |
+
rows.append(eval_model(f'length_b{bb}',f))
|
| 34 |
+
# choose best length b by nDCG
|
| 35 |
+
lenrows=[r for r in rows if r['name'].startswith('length_b')]; bestb=float(max(lenrows,key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']))['name'].split('length_b')[1]); print('BEST_B',bestb,flush=True)
|
| 36 |
+
# stage 2: weights at best b
|
| 37 |
+
for wl in [2.,3.,4.,5.,6.,8.,10.,12.]:
|
| 38 |
+
for ws in [0.,.05,.1,.2,.3]:
|
| 39 |
+
def f(i,k,bb=bestb,wl=wl,ws=ws):
|
| 40 |
+
r=(LF[i,:k]-.8)/.2; lx=RAW[i,:k]/np.maximum((1-bb)+bb*r,1e-6); return Z(T[i,:k])+wl*Z(lx)+ws*Z(S[i,:k])
|
| 41 |
+
rows.append(eval_model(f'bestb_wl{wl}_ws{ws}',f))
|
| 42 |
+
weightrows=[r for r in rows if r['name'].startswith('bestb_')]; bestw=max(weightrows,key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100'])); import re
|
| 43 |
+
mt=re.search(r'wl([0-9.]+)_ws([0-9.]+)',bestw['name']); bestwl=float(mt.group(1)); bestws=float(mt.group(2)); print('BEST_W',bestwl,bestws,flush=True)
|
| 44 |
+
# stage 3: add coordination count z-score
|
| 45 |
+
for wc in [-2.,-1.,-.5,-.25,0.,.125,.25,.5,1.,2.,4.]:
|
| 46 |
+
def f(i,k,wc=wc,bb=bestb,wl=bestwl,ws=bestws):
|
| 47 |
+
r=(LF[i,:k]-.8)/.2; lx=RAW[i,:k]/np.maximum((1-bb)+bb*r,1e-6); return Z(T[i,:k])+wl*Z(lx)+ws*Z(S[i,:k])+wc*Z(QC[i,:k])
|
| 48 |
+
rows.append(eval_model(f'coord_wc{wc}',f))
|
| 49 |
+
# stage 4: coordination-adjusted lexical score lx*(coverage)^alpha; keep weights and also tune lex weight modestly
|
| 50 |
+
for alpha in [.125,.25,.5,1.,1.5,2.]:
|
| 51 |
+
for wl in [bestwl*.75,bestwl,bestwl*1.25]:
|
| 52 |
+
def f(i,k,alpha=alpha,wl=wl,bb=bestb,ws=bestws):
|
| 53 |
+
r=(LF[i,:k]-.8)/.2; lx=RAW[i,:k]/np.maximum((1-bb)+bb*r,1e-6); cov=QC[i,:k]/max(1,QT[i]); ladj=lx*np.power(np.maximum(cov,1e-6),alpha); return Z(T[i,:k])+wl*Z(ladj)+ws*Z(S[i,:k])
|
| 54 |
+
rows.append(eval_model(f'coordlex_a{alpha}_wl{wl}',f))
|
| 55 |
+
# stage 5: exact all-query-terms and high-coverage bonuses (z of binary masks)
|
| 56 |
+
for thr in [.5,.67,.75,.8,1.0]:
|
| 57 |
+
for wb in [.125,.25,.5,1.,2.]:
|
| 58 |
+
def f(i,k,thr=thr,wb=wb,bb=bestb,wl=bestwl,ws=bestws):
|
| 59 |
+
r=(LF[i,:k]-.8)/.2; lx=RAW[i,:k]/np.maximum((1-bb)+bb*r,1e-6); cov=QC[i,:k]/max(1,QT[i]); bonus=(cov>=thr).astype(np.float32); return Z(T[i,:k])+wl*Z(lx)+ws*Z(S[i,:k])+wb*bonus
|
| 60 |
+
rows.append(eval_model(f'covbonus_thr{thr}_wb{wb}',f))
|
| 61 |
+
rows.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True)
|
| 62 |
+
out={'protocol':'same fixed eta=1 P=2000 TRAIN validation pools; only existing-index lexical/coordination structure; no candidate changes','baseline':next(r for r in rows if r['name']=='baseline'),'best':rows[0],'top30':rows[:30],'best_length_b':bestb,'best_weight_base':bestw,'n_models':len(rows)}
|
| 63 |
+
json.dump(out,open(OUT/'coordination_sweep.json','w'),indent=2); print('===BEST==='); print(json.dumps(rows[0],indent=2)); print('TOP10'); [print(r) for r in rows[:10]]
|
experiments/msmarco_scale/msmarco_covbonus_sweep.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
sys.path.insert(0,'/mnt/data')
|
| 6 |
+
import msmarco_full_search_uniform1m as m
|
| 7 |
+
ROOT=m.ROOT; WORK=m.WORK; OUT=WORK/'structural_fusion'
|
| 8 |
+
z=np.load(WORK/'amplitude_diag'/'fixed_eta1_pools.npz',allow_pickle=False); c=np.load(OUT/'coordination_features.npz',allow_pickle=False)
|
| 9 |
+
qids=[str(x) for x in z['qids'].tolist()]; valid=z['valid'].astype(int); docs=z['docs']; T=z['tail']; S=z['sem']; RAW=c['rawlex']; LF=c['lenfac']; QC=c['qcount']; QT=c['qterms'].astype(int); qrels=m.qrels_from_tsv(ROOT/'train.tsv',qids,positive_only=True)
|
| 10 |
+
def top100(sc):
|
| 11 |
+
n=len(sc); kk=min(100,n); ii=np.argpartition(sc,-kk)[-kk:] if n>kk else np.arange(n); return ii[np.argsort(sc[ii])[::-1]]
|
| 12 |
+
def evalx(name,fn):
|
| 13 |
+
run={}
|
| 14 |
+
for i,qid in enumerate(qids):
|
| 15 |
+
k=valid[i]; sc=fn(i,k); oo=top100(sc); run[qid]=[int(x) for x in docs[i,oo]]
|
| 16 |
+
r={'name':name,**m.eval_run(run,qrels)}; print(name,r['nDCG@10'],r['MRR@10'],r['R@100'],flush=True); return r
|
| 17 |
+
def Z(x):return m.zscore(x)
|
| 18 |
+
def base(i,k,alpha=.25):
|
| 19 |
+
ratio=(LF[i,:k]-.8)/.2; lx=RAW[i,:k]/np.maximum(.9+.1*ratio,1e-6); cov=QC[i,:k]/max(1,QT[i]); ladj=lx*np.power(np.maximum(cov,1e-6),alpha); return Z(T[i,:k])+4*Z(ladj)+.3*Z(S[i,:k]),cov
|
| 20 |
+
rows=[]
|
| 21 |
+
rows.append(evalx('struct_base',lambda i,k:base(i,k)[0]))
|
| 22 |
+
for thr in [.4,.5,.6,.67,.75,.8,.9,1.0]:
|
| 23 |
+
for wb in [.05,.1,.2,.3,.5,.75,1.0]:
|
| 24 |
+
rows.append(evalx(f'bonus_t{thr}_w{wb}',lambda i,k,thr=thr,wb=wb: base(i,k)[0]+wb*(base(i,k)[1]>=thr).astype(np.float32)))
|
| 25 |
+
rows.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True); out={'protocol':'fixed direct eta=1 P=2000 validation pool; structural base b=.1 alpha=.25 wl=4 ws=.3 plus coverage threshold bonus','best':rows[0],'top20':rows[:20]}; json.dump(out,open(OUT/'coverage_bonus_sweep.json','w'),indent=2); print('BEST',rows[0])
|
experiments/msmarco_scale/msmarco_dev_fast.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,time,json,numpy as np,pandas as pd
|
| 2 |
+
sys.path.insert(0,'/mnt/data')
|
| 3 |
+
from msmarco_full_search_fast import FullIndex,load_query_texts,qrels_from_tsv,eval_run,ROOT,WORK,P
|
| 4 |
+
BEST_H=0
|
| 5 |
+
idx=FullIndex(); print('loaded',idx.meta,flush=True)
|
| 6 |
+
df=pd.read_csv(ROOT/'dev.tsv',sep='\t',usecols=['query-id']); ids=[str(x) for x in np.unique(df['query-id'].to_numpy())]; del df
|
| 7 |
+
texts=load_query_texts(ids); qrels=qrels_from_tsv(ROOT/'dev.tsv',ids,positive_only=True)
|
| 8 |
+
# warm compile/pages, not timed
|
| 9 |
+
w=idx.prepare(texts[ids[0]],hmax=1); idx.rank_h(w,0,100); del w
|
| 10 |
+
run={}; times=[]; cands=[]; mems=[]
|
| 11 |
+
route_num=pool_num=rel_den=0
|
| 12 |
+
for z,qid in enumerate(ids):
|
| 13 |
+
t=time.perf_counter(); pp=idx.prepare(texts[qid],hmax=1); rank=idx.rank_h(pp,BEST_H,100); dt=(time.perf_counter()-t)*1000
|
| 14 |
+
run[qid]=rank; times.append(dt); cands.append(pp['candidate_docs'] if pp else 0); mems.append(pp['candidate_memberships'] if pp else 0)
|
| 15 |
+
rel=[int(d) for d,r in qrels[qid].items() if r>0]; rel_den+=len(rel)
|
| 16 |
+
if pp is not None:
|
| 17 |
+
ud=pp['ud']; pool=pp['cand_docs'][:P]
|
| 18 |
+
for d in rel:
|
| 19 |
+
k=np.searchsorted(ud,d); route_num += int(k<len(ud) and int(ud[k])==d); pool_num += int(np.any(pool==d))
|
| 20 |
+
if (z+1)%500==0:
|
| 21 |
+
print('dev',z+1,'median_ms',float(np.median(times)),'p95_ms',float(np.percentile(times,95)),'avgcand',float(np.mean(cands)),'route_rel',route_num/rel_den,'pool_rel',pool_num/rel_den,flush=True)
|
| 22 |
+
m=eval_run(run,qrels)
|
| 23 |
+
timing={'median_ms':float(np.median(times)),'p95_ms':float(np.percentile(times,95)),'mean_ms':float(np.mean(times)),'qps':1000/float(np.mean(times)),'avg_candidate_docs':float(np.mean(cands)),'median_candidate_docs':float(np.median(cands)),'avg_candidate_memberships':float(np.mean(mems))}
|
| 24 |
+
stages={'routed_relevant_recall':route_num/rel_den,'pool_P2000_relevant_recall':pool_num/rel_den,'final_R100':m['R@100'],'total_positive_qrels':rel_den}
|
| 25 |
+
out={'protocol':'h=0 selected on deterministic 1000-query TRAIN validation sweep; full 6980-query DEV untouched','best_h':0,'dev_metrics':m,'timing':timing,'stage_diagnostics':stages,'index_meta':idx.meta,'geometry_note':'full 8.84M vocabulary/IDF; geometric codebook calibrated on first 1M passages','physical_optimizations':'branch-sorted postings; query-local dense center/reliability lookup; global compact support CSR; ranking verified identical on regression queries'}
|
| 26 |
+
with open(WORK/'full_msmarco_dev_fast_results.json','w') as f: json.dump(out,f,indent=2)
|
| 27 |
+
print('DEV_METRICS',m,flush=True); print('TIMING',timing,flush=True); print('STAGES',stages,flush=True); print('saved',WORK/'full_msmarco_dev_fast_results.json',flush=True)
|
experiments/msmarco_scale/msmarco_early_lex_dev.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
import numpy as np,pandas as pd
|
| 4 |
+
from numba import set_num_threads
|
| 5 |
+
sys.path.insert(0,'/mnt/data')
|
| 6 |
+
import msmarco_best_tail_core as b
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
ROOT=m.ROOT; WORK=m.WORK; idx=b.idx; M=m.M; P=2000
|
| 9 |
+
ETA=np.float32(1.0); QUOTA=500; LLEX=np.float32(4.0); LSEM=np.float32(0.1)
|
| 10 |
+
set_num_threads(5)
|
| 11 |
+
|
| 12 |
+
def topk_desc(score,k):
|
| 13 |
+
n=len(score); k=min(k,n)
|
| 14 |
+
if k<=0:return np.empty(0,np.int64)
|
| 15 |
+
if n>k:
|
| 16 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 17 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 18 |
+
return np.argsort(score)[::-1]
|
| 19 |
+
|
| 20 |
+
def quota_select(tail,lex,lq=500):
|
| 21 |
+
n=len(tail); k=min(P,n); gq=k-min(lq,k); gt=topk_desc(tail,gq)
|
| 22 |
+
if gq==k:return gt
|
| 23 |
+
lex_order=topk_desc(lex,min(n,2*P)); chosen=np.zeros(n,np.uint8); chosen[gt]=1; out=np.empty(k,np.int64); out[:gq]=gt; z=gq
|
| 24 |
+
for ii in lex_order:
|
| 25 |
+
if chosen[ii]==0:
|
| 26 |
+
chosen[ii]=1; out[z]=ii; z+=1
|
| 27 |
+
if z==k:return out
|
| 28 |
+
# fallback
|
| 29 |
+
for ii in np.argsort(lex)[::-1]:
|
| 30 |
+
if chosen[ii]==0:
|
| 31 |
+
out[z]=ii; z+=1
|
| 32 |
+
if z==k:return out
|
| 33 |
+
return out[:z]
|
| 34 |
+
|
| 35 |
+
def prepare_geometry_lex(text):
|
| 36 |
+
q=idx.query_vec(text); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rterms,rd=idx.route(q)
|
| 37 |
+
spans=[(int(j),int(idx.offs[j]),int(idx.offs[j+1])) for j in rterms if idx.offs[j+1]>idx.offs[j]]
|
| 38 |
+
if not spans:return None
|
| 39 |
+
docs=np.concatenate([np.asarray(idx.pd[a:bb]) for j,a,bb in spans]).astype(np.uint32,copy=False)
|
| 40 |
+
mm=np.concatenate([np.asarray(idx.pm[a:bb]) for j,a,bb in spans]).astype(np.float32,copy=False)
|
| 41 |
+
rt=np.concatenate([np.asarray(idx.pr[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 42 |
+
sb=np.concatenate([np.asarray(idx.ps[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 43 |
+
nr=len(spans); cent=np.zeros((nr,M),np.float32); rel=np.zeros((nr,M),np.float32); rho=np.empty(nr,np.float32)
|
| 44 |
+
for u,(j,a,bb) in enumerate(spans):
|
| 45 |
+
rowt=np.asarray(idx.ct[j]); ok=rowt!=65535; tids=rowt[ok].astype(np.int32,copy=False); cent[u,tids]=np.asarray(idx.cv[j])[ok]
|
| 46 |
+
ra=int(idx.rp[j]); rb=int(idx.rp[j+1]); rel[u,np.asarray(idx.ri[ra:rb],np.int32)]=np.asarray(idx.rv[ra:rb]); rho[u]=rd[j]
|
| 47 |
+
rslot=np.concatenate([np.full(bb-a,u,dtype=np.uint8) for u,(j,a,bb) in enumerate(spans)])
|
| 48 |
+
base,sig,cons=b.score_components(rslot,mm,rt,sb,qd,rho,cent,rel)
|
| 49 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 50 |
+
tail=np.bincount(inv,weights=base*np.power(sig,b.GAMMA,dtype=np.float32),minlength=len(ud)).astype(np.float32)+b.LAM*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 51 |
+
lexvec=np.zeros(M,np.float32); lexvec[q.indices]=idx.idf[q.indices]; zero=np.zeros(M,np.float32)
|
| 52 |
+
lex,_=m.score_support_pool(ud,idx.sup_ip,idx.sup_ids,lexvec,zero,idx.dl,idx.avgdl)
|
| 53 |
+
semvec=np.zeros(M,np.float32)
|
| 54 |
+
for t,amp in zip(q.indices,q.data):
|
| 55 |
+
a,bb=idx.A.indptr[t],idx.A.indptr[t+1]; nb=idx.A.indices[a:bb][:m.SEMK]; sv=idx.A.data[a:bb][:m.SEMK]; semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 56 |
+
return {'ud':ud,'tail':tail,'lex':lex,'semvec':semvec,'candidate_memberships':len(docs)}
|
| 57 |
+
|
| 58 |
+
def rank_selected(p,sel):
|
| 59 |
+
docs=p['ud'][sel]; ts=p['tail'][sel]; lx=p['lex'][sel]; zero=np.zeros(M,np.float32)
|
| 60 |
+
_,sem=m.score_support_pool(docs,idx.sup_ip,idx.sup_ids,zero,p['semvec'],idx.dl,idx.avgdl)
|
| 61 |
+
fin=m.zscore(ts)+LLEX*m.zscore(lx)+LSEM*m.zscore(sem); oo=np.argsort(fin)[::-1][:100]
|
| 62 |
+
return [int(x) for x in docs[oo]]
|
| 63 |
+
|
| 64 |
+
def select_direct(p):return topk_desc(m.zscore(p['tail'])+ETA*m.zscore(p['lex']),P)
|
| 65 |
+
|
| 66 |
+
df=pd.read_csv(ROOT/'dev.tsv',sep='\t',usecols=['query-id']); ids=[str(x) for x in np.unique(df['query-id'].to_numpy())]; del df
|
| 67 |
+
texts=m.load_query_texts(ids); qrels=m.qrels_from_tsv(ROOT/'dev.tsv',ids,positive_only=True)
|
| 68 |
+
p=prepare_geometry_lex(texts[ids[0]]); sd=select_direct(p); _=rank_selected(p,sd); del p
|
| 69 |
+
runD={}; runQ={}; timesD=[]; routehit=poolD=poolQ=den=0; cands=[]
|
| 70 |
+
for z,qid in enumerate(ids):
|
| 71 |
+
t=time.perf_counter(); p=prepare_geometry_lex(texts[qid])
|
| 72 |
+
if p is None: runD[qid]=[]; runQ[qid]=[]; continue
|
| 73 |
+
sd=select_direct(p); rd=rank_selected(p,sd); timesD.append((time.perf_counter()-t)*1000); runD[qid]=rd
|
| 74 |
+
sq=quota_select(p['tail'],p['lex'],QUOTA); runQ[qid]=rank_selected(p,sq)
|
| 75 |
+
ud=p['ud']; cands.append(len(ud)); rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels); setD=set(map(int,sd)); setQ=set(map(int,sq))
|
| 76 |
+
for d in rels:
|
| 77 |
+
kk=np.searchsorted(ud,d); ok=kk<len(ud) and int(ud[kk])==d; routehit+=int(ok)
|
| 78 |
+
if ok: poolD+=int(int(kk) in setD); poolQ+=int(int(kk) in setQ)
|
| 79 |
+
if (z+1)%500==0:print('dev',z+1,'median_direct_ms',float(np.median(timesD)),'route',routehit/max(1,den),'poolD',poolD/max(1,den),'poolQ',poolQ/max(1,den),flush=True)
|
| 80 |
+
metD=m.eval_run(runD,qrels); metQ=m.eval_run(runQ,qrels)
|
| 81 |
+
out={'protocol':'shortlist strategy locked on deterministic TRAIN validation; DEV untouched','selected':{'strategy':'direct early lexical fusion','eta':1.0,'P':2000,'gamma_tail':0.25,'lambda_M':0.125,'lambda_lex_final':4.0,'lambda_sem_final':0.1,'h':0},'secondary_validation_fixed_comparator':{'strategy':'quota rescue','lex_quota':500},'direct_dev_metrics':metD,'quota500_dev_metrics':metQ,'route_relevant_recall':routehit/den,'direct_pool_relevant_recall':poolD/den,'quota_pool_relevant_recall':poolQ/den,'direct_timing':{'median_ms':float(np.median(timesD)),'p95_ms':float(np.percentile(timesD,95)),'mean_ms':float(np.mean(timesD)),'qps':1000/float(np.mean(timesD)),'avg_candidate_docs':float(np.mean(cands))}}
|
| 82 |
+
json.dump(out,open(WORK/'early_lex_dev_results.json','w'),indent=2); print('DIRECT_DEV',metD,flush=True); print('QUOTA_DEV',metQ,flush=True); print('SUMMARY',out,flush=True)
|
experiments/msmarco_scale/msmarco_early_lex_direct.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
import numpy as np,pandas as pd
|
| 4 |
+
from numba import set_num_threads
|
| 5 |
+
sys.path.insert(0,'/mnt/data')
|
| 6 |
+
import msmarco_best_tail_core as b
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
ROOT=m.ROOT; WORK=m.WORK; idx=b.idx; M=m.M; P=2000
|
| 9 |
+
LLEX=np.float32(4.0); LSEM=np.float32(0.1)
|
| 10 |
+
ETAS=[0.0,0.125,0.25,0.5,1.0,2.0,4.0]
|
| 11 |
+
set_num_threads(5)
|
| 12 |
+
|
| 13 |
+
def topk_desc(score,k):
|
| 14 |
+
n=len(score); k=min(k,n)
|
| 15 |
+
if n>k:
|
| 16 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 17 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 18 |
+
return np.argsort(score)[::-1]
|
| 19 |
+
|
| 20 |
+
def prepare_all(text):
|
| 21 |
+
q=idx.query_vec(text); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rterms,rd=idx.route(q)
|
| 22 |
+
spans=[(int(j),int(idx.offs[j]),int(idx.offs[j+1])) for j in rterms if idx.offs[j+1]>idx.offs[j]]
|
| 23 |
+
if not spans:return None
|
| 24 |
+
docs=np.concatenate([np.asarray(idx.pd[a:bb]) for j,a,bb in spans]).astype(np.uint32,copy=False)
|
| 25 |
+
mm=np.concatenate([np.asarray(idx.pm[a:bb]) for j,a,bb in spans]).astype(np.float32,copy=False)
|
| 26 |
+
rt=np.concatenate([np.asarray(idx.pr[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 27 |
+
sb=np.concatenate([np.asarray(idx.ps[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 28 |
+
nr=len(spans); cent=np.zeros((nr,M),np.float32); rel=np.zeros((nr,M),np.float32); rho=np.empty(nr,np.float32)
|
| 29 |
+
for u,(j,a,bb) in enumerate(spans):
|
| 30 |
+
rowt=np.asarray(idx.ct[j]); ok=rowt!=65535; tids=rowt[ok].astype(np.int32,copy=False); cent[u,tids]=np.asarray(idx.cv[j])[ok]
|
| 31 |
+
ra=int(idx.rp[j]); rb=int(idx.rp[j+1]); rel[u,np.asarray(idx.ri[ra:rb],np.int32)]=np.asarray(idx.rv[ra:rb]); rho[u]=rd[j]
|
| 32 |
+
rslot=np.concatenate([np.full(bb-a,u,dtype=np.uint8) for u,(j,a,bb) in enumerate(spans)])
|
| 33 |
+
base,sig,cons=b.score_components(rslot,mm,rt,sb,qd,rho,cent,rel)
|
| 34 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 35 |
+
tail=np.bincount(inv,weights=base*np.power(sig,b.GAMMA,dtype=np.float32),minlength=len(ud)).astype(np.float32)+b.LAM*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 36 |
+
lexvec=np.zeros(M,np.float32); lexvec[q.indices]=idx.idf[q.indices]; semvec=np.zeros(M,np.float32)
|
| 37 |
+
for t,amp in zip(q.indices,q.data):
|
| 38 |
+
a,bb=idx.A.indptr[t],idx.A.indptr[t+1]; nb=idx.A.indices[a:bb][:m.SEMK]; sv=idx.A.data[a:bb][:m.SEMK]; semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 39 |
+
lex,sem=m.score_support_pool(ud,idx.sup_ip,idx.sup_ids,lexvec,semvec,idx.dl,idx.avgdl)
|
| 40 |
+
return ud,tail,lex,sem
|
| 41 |
+
|
| 42 |
+
def rank(ud,tail,lex,sem,sel):
|
| 43 |
+
fin=m.zscore(tail[sel])+LLEX*m.zscore(lex[sel])+LSEM*m.zscore(sem[sel]); oo=np.argsort(fin)[::-1][:100]; return [int(x) for x in ud[sel[oo]]]
|
| 44 |
+
|
| 45 |
+
tr=pd.read_csv(ROOT/'train.tsv',sep='\t',usecols=['query-id']); uq=np.unique(tr['query-id'].to_numpy()); rng=np.random.default_rng(20260815); ids=[str(x) for x in rng.choice(uq,size=1000,replace=False)]; del tr
|
| 46 |
+
texts=m.load_query_texts(ids); qrels=m.qrels_from_tsv(ROOT/'train.tsv',ids,positive_only=True)
|
| 47 |
+
_=prepare_all(texts[ids[0]])
|
| 48 |
+
runs={e:{} for e in ETAS}; pool={e:0 for e in ETAS}; den=route=0; times=[]; strategy_times=[]
|
| 49 |
+
for z,qid in enumerate(ids):
|
| 50 |
+
t=time.perf_counter(); p=prepare_all(texts[qid]); times.append((time.perf_counter()-t)*1000)
|
| 51 |
+
if p is None:
|
| 52 |
+
for e in ETAS:runs[e][qid]=[]
|
| 53 |
+
continue
|
| 54 |
+
ud,tail,lex,sem=p; rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels); relset=set()
|
| 55 |
+
for d in rels:
|
| 56 |
+
kk=np.searchsorted(ud,d); ok=kk<len(ud) and int(ud[kk])==d; route+=int(ok)
|
| 57 |
+
if ok:relset.add(int(kk))
|
| 58 |
+
zt=m.zscore(tail); zl=m.zscore(lex)
|
| 59 |
+
st=time.perf_counter()
|
| 60 |
+
for e in ETAS:
|
| 61 |
+
sel=topk_desc(zt+np.float32(e)*zl,P); pool[e]+=sum(int(i) in relset for i in sel); runs[e][qid]=rank(ud,tail,lex,sem,sel)
|
| 62 |
+
strategy_times.append((time.perf_counter()-st)*1000)
|
| 63 |
+
if (z+1)%100==0:print('q',z+1,'prepare',float(np.median(times)),'strategies',float(np.median(strategy_times)),flush=True)
|
| 64 |
+
rows=[]
|
| 65 |
+
for e in ETAS:
|
| 66 |
+
met=m.eval_run(runs[e],qrels); row={'eta':e,'pool_relevant_recall':pool[e]/den,**met}; rows.append(row); print('DIRECT',row,flush=True)
|
| 67 |
+
rows.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True)
|
| 68 |
+
out={'rows':rows,'best':rows[0],'route_relevant_recall':route/den,'timing':{'median_prepare_alllexsem_ms':float(np.median(times)),'p95_prepare_ms':float(np.percentile(times,95)),'median_all_eta_strategy_ms':float(np.median(strategy_times))}}
|
| 69 |
+
json.dump(out,open(WORK/'early_lex_direct_validation.json','w'),indent=2); print('BEST',rows[0]); print('TIMING',out['timing'])
|
experiments/msmarco_scale/msmarco_early_lex_quota.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
import numpy as np,pandas as pd
|
| 4 |
+
from numba import set_num_threads
|
| 5 |
+
sys.path.insert(0,'/mnt/data')
|
| 6 |
+
import msmarco_best_tail_core as b
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
ROOT=m.ROOT; WORK=m.WORK; idx=b.idx; M=m.M; P=2000
|
| 9 |
+
LLEX=np.float32(4.0); LSEM=np.float32(0.1)
|
| 10 |
+
QUOTAS=[0,100,250,500,750,1000,1250,1500,1750,2000]
|
| 11 |
+
set_num_threads(5)
|
| 12 |
+
|
| 13 |
+
def topk_desc(score,k):
|
| 14 |
+
n=len(score); k=min(k,n)
|
| 15 |
+
if k<=0:return np.empty(0,np.int64)
|
| 16 |
+
if n>k:
|
| 17 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 18 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 19 |
+
return np.argsort(score)[::-1]
|
| 20 |
+
|
| 21 |
+
def prepare_all(text):
|
| 22 |
+
q=idx.query_vec(text); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rterms,rd=idx.route(q)
|
| 23 |
+
spans=[(int(j),int(idx.offs[j]),int(idx.offs[j+1])) for j in rterms if idx.offs[j+1]>idx.offs[j]]
|
| 24 |
+
if not spans:return None
|
| 25 |
+
docs=np.concatenate([np.asarray(idx.pd[a:bb]) for j,a,bb in spans]).astype(np.uint32,copy=False)
|
| 26 |
+
mm=np.concatenate([np.asarray(idx.pm[a:bb]) for j,a,bb in spans]).astype(np.float32,copy=False)
|
| 27 |
+
rt=np.concatenate([np.asarray(idx.pr[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 28 |
+
sb=np.concatenate([np.asarray(idx.ps[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 29 |
+
nr=len(spans); cent=np.zeros((nr,M),np.float32); rel=np.zeros((nr,M),np.float32); rho=np.empty(nr,np.float32)
|
| 30 |
+
for u,(j,a,bb) in enumerate(spans):
|
| 31 |
+
rowt=np.asarray(idx.ct[j]); ok=rowt!=65535; tids=rowt[ok].astype(np.int32,copy=False); cent[u,tids]=np.asarray(idx.cv[j])[ok]
|
| 32 |
+
ra=int(idx.rp[j]); rb=int(idx.rp[j+1]); rel[u,np.asarray(idx.ri[ra:rb],np.int32)]=np.asarray(idx.rv[ra:rb]); rho[u]=rd[j]
|
| 33 |
+
rslot=np.concatenate([np.full(bb-a,u,dtype=np.uint8) for u,(j,a,bb) in enumerate(spans)])
|
| 34 |
+
base,sig,cons=b.score_components(rslot,mm,rt,sb,qd,rho,cent,rel)
|
| 35 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 36 |
+
tail=np.bincount(inv,weights=base*np.power(sig,b.GAMMA,dtype=np.float32),minlength=len(ud)).astype(np.float32)+b.LAM*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 37 |
+
lexvec=np.zeros(M,np.float32); lexvec[q.indices]=idx.idf[q.indices]; semvec=np.zeros(M,np.float32)
|
| 38 |
+
for t,amp in zip(q.indices,q.data):
|
| 39 |
+
a,bb=idx.A.indptr[t],idx.A.indptr[t+1]; nb=idx.A.indices[a:bb][:m.SEMK]; sv=idx.A.data[a:bb][:m.SEMK]; semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 40 |
+
lex,sem=m.score_support_pool(ud,idx.sup_ip,idx.sup_ids,lexvec,semvec,idx.dl,idx.avgdl)
|
| 41 |
+
return ud,tail,lex,sem
|
| 42 |
+
|
| 43 |
+
def rank(ud,tail,lex,sem,sel):
|
| 44 |
+
fin=m.zscore(tail[sel])+LLEX*m.zscore(lex[sel])+LSEM*m.zscore(sem[sel]); oo=np.argsort(fin)[::-1][:100]; return [int(x) for x in ud[sel[oo]]]
|
| 45 |
+
|
| 46 |
+
def quota_select(tail_order,lex_order,n,lq):
|
| 47 |
+
k=min(P,n); lq=min(lq,k); gq=k-lq
|
| 48 |
+
if lq==0:return tail_order[:k]
|
| 49 |
+
out=np.empty(k,np.int64); chosen=np.zeros(n,np.uint8); z=0
|
| 50 |
+
if gq:
|
| 51 |
+
g=tail_order[:gq]; out[:gq]=g; chosen[g]=1; z=gq
|
| 52 |
+
# lex_order contains at least 2P top lexical docs; this is enough unless overlap is pathological.
|
| 53 |
+
for ii in lex_order:
|
| 54 |
+
if chosen[ii]==0:
|
| 55 |
+
out[z]=ii; chosen[ii]=1; z+=1
|
| 56 |
+
if z==k:return out
|
| 57 |
+
# Fallback should essentially never fire; preserve exactness if it does.
|
| 58 |
+
full=np.argsort(lex)[::-1]
|
| 59 |
+
for ii in full:
|
| 60 |
+
if chosen[ii]==0:
|
| 61 |
+
out[z]=ii; chosen[ii]=1; z+=1
|
| 62 |
+
if z==k:return out
|
| 63 |
+
return out[:z]
|
| 64 |
+
|
| 65 |
+
tr=pd.read_csv(ROOT/'train.tsv',sep='\t',usecols=['query-id']); uq=np.unique(tr['query-id'].to_numpy()); rng=np.random.default_rng(20260815); ids=[str(x) for x in rng.choice(uq,size=1000,replace=False)]; del tr
|
| 66 |
+
texts=m.load_query_texts(ids); qrels=m.qrels_from_tsv(ROOT/'train.tsv',ids,positive_only=True)
|
| 67 |
+
_=prepare_all(texts[ids[0]])
|
| 68 |
+
runs={q:{} for q in QUOTAS}; pool={q:0 for q in QUOTAS}; den=route=0; times=[]; stimes=[]
|
| 69 |
+
for z,qid in enumerate(ids):
|
| 70 |
+
t=time.perf_counter(); p=prepare_all(texts[qid]); times.append((time.perf_counter()-t)*1000)
|
| 71 |
+
if p is None:
|
| 72 |
+
for qv in QUOTAS:runs[qv][qid]=[]
|
| 73 |
+
continue
|
| 74 |
+
ud,tail,lex,sem=p; rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels); relset=set()
|
| 75 |
+
for d in rels:
|
| 76 |
+
kk=np.searchsorted(ud,d); ok=kk<len(ud) and int(ud[kk])==d; route+=int(ok)
|
| 77 |
+
if ok:relset.add(int(kk))
|
| 78 |
+
st=time.perf_counter(); tail_order=topk_desc(tail,P); lex_order=topk_desc(lex,min(len(lex),2*P))
|
| 79 |
+
for qv in QUOTAS:
|
| 80 |
+
sel=quota_select(tail_order,lex_order,len(ud),qv); pool[qv]+=sum(int(i) in relset for i in sel); runs[qv][qid]=rank(ud,tail,lex,sem,sel)
|
| 81 |
+
stimes.append((time.perf_counter()-st)*1000)
|
| 82 |
+
if (z+1)%100==0:print('q',z+1,'prepare',float(np.median(times)),'strategies',float(np.median(stimes)),flush=True)
|
| 83 |
+
rows=[]
|
| 84 |
+
for qv in QUOTAS:
|
| 85 |
+
met=m.eval_run(runs[qv],qrels); row={'lex_quota':qv,'pool_relevant_recall':pool[qv]/den,**met}; rows.append(row); print('QUOTA',row,flush=True)
|
| 86 |
+
rows.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True)
|
| 87 |
+
out={'rows':rows,'best':rows[0],'route_relevant_recall':route/den,'timing':{'median_prepare_alllexsem_ms':float(np.median(times)),'p95_prepare_ms':float(np.percentile(times,95)),'median_all_quota_strategy_ms':float(np.median(stimes))}}
|
| 88 |
+
json.dump(out,open(WORK/'early_lex_quota_validation.json','w'),indent=2); print('BEST',rows[0]); print('TIMING',out['timing'])
|
experiments/msmarco_scale/msmarco_early_lex_validation.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
import numpy as np, pandas as pd
|
| 4 |
+
from numba import set_num_threads
|
| 5 |
+
sys.path.insert(0,'/mnt/data')
|
| 6 |
+
import msmarco_best_tail_core as b
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
|
| 9 |
+
ROOT=m.ROOT; WORK=m.WORK; idx=b.idx; M=m.M; P=2000
|
| 10 |
+
LLEX=np.float32(4.0); LSEM=np.float32(0.1)
|
| 11 |
+
ETAS=[0.0,0.0625,0.125,0.25,0.5,1.0,2.0,4.0,8.0]
|
| 12 |
+
LEX_QUOTAS=[0,100,250,500,750,1000,1250,1500,1750,2000]
|
| 13 |
+
set_num_threads(5)
|
| 14 |
+
|
| 15 |
+
def topk_desc(score,k):
|
| 16 |
+
n=len(score); k=min(k,n)
|
| 17 |
+
if k<=0:return np.empty(0,np.int64)
|
| 18 |
+
if n>k:
|
| 19 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 20 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 21 |
+
return np.argsort(score)[::-1]
|
| 22 |
+
|
| 23 |
+
def prepare_all(text):
|
| 24 |
+
q=idx.query_vec(text); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rterms,rd=idx.route(q)
|
| 25 |
+
spans=[(int(j),int(idx.offs[j]),int(idx.offs[j+1])) for j in rterms if idx.offs[j+1]>idx.offs[j]]
|
| 26 |
+
if not spans:return None
|
| 27 |
+
docs=np.concatenate([np.asarray(idx.pd[a:bb]) for j,a,bb in spans]).astype(np.uint32,copy=False)
|
| 28 |
+
mm=np.concatenate([np.asarray(idx.pm[a:bb]) for j,a,bb in spans]).astype(np.float32,copy=False)
|
| 29 |
+
rt=np.concatenate([np.asarray(idx.pr[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 30 |
+
sb=np.concatenate([np.asarray(idx.ps[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 31 |
+
nr=len(spans); cent=np.zeros((nr,M),np.float32); rel=np.zeros((nr,M),np.float32); rho=np.empty(nr,np.float32)
|
| 32 |
+
for u,(j,a,bb) in enumerate(spans):
|
| 33 |
+
rowt=np.asarray(idx.ct[j]); ok=rowt!=65535; tids=rowt[ok].astype(np.int32,copy=False); cent[u,tids]=np.asarray(idx.cv[j])[ok]
|
| 34 |
+
ra=int(idx.rp[j]); rb=int(idx.rp[j+1]); rel[u,np.asarray(idx.ri[ra:rb],np.int32)]=np.asarray(idx.rv[ra:rb]); rho[u]=rd[j]
|
| 35 |
+
rslot=np.concatenate([np.full(bb-a,u,dtype=np.uint8) for u,(j,a,bb) in enumerate(spans)])
|
| 36 |
+
base,sig,cons=b.score_components(rslot,mm,rt,sb,qd,rho,cent,rel)
|
| 37 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 38 |
+
tail=np.bincount(inv,weights=base*np.power(sig,b.GAMMA,dtype=np.float32),minlength=len(ud)).astype(np.float32)+b.LAM*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 39 |
+
lexvec=np.zeros(M,np.float32); lexvec[q.indices]=idx.idf[q.indices]
|
| 40 |
+
# Whole-document lexical + tiny semantic score for every routed document.
|
| 41 |
+
# This is used only to amortize the validation sweep; the locked deployable
|
| 42 |
+
# implementation below computes semantics only for the selected P.
|
| 43 |
+
semvec=np.zeros(M,np.float32)
|
| 44 |
+
for t,amp in zip(q.indices,q.data):
|
| 45 |
+
a,bb=idx.A.indptr[t],idx.A.indptr[t+1]; nb=idx.A.indices[a:bb][:m.SEMK]; sv=idx.A.data[a:bb][:m.SEMK]
|
| 46 |
+
semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 47 |
+
lex,sem=m.score_support_pool(ud,idx.sup_ip,idx.sup_ids,lexvec,semvec,idx.dl,idx.avgdl)
|
| 48 |
+
return {'ud':ud,'tail':tail,'lex':lex,'sem':sem,'candidate_docs':len(ud),'candidate_memberships':len(docs)}
|
| 49 |
+
|
| 50 |
+
def final_rank(p, sel_idx, k=100):
|
| 51 |
+
docs=p['ud'][sel_idx]; ts=p['tail'][sel_idx]; lx=p['lex'][sel_idx]; sm=p['sem'][sel_idx]
|
| 52 |
+
fin=m.zscore(ts)+LLEX*m.zscore(lx)+LSEM*m.zscore(sm)
|
| 53 |
+
oo=np.argsort(fin)[::-1][:k]
|
| 54 |
+
return [int(x) for x in docs[oo]]
|
| 55 |
+
|
| 56 |
+
def select_direct(p,eta):
|
| 57 |
+
zt=m.zscore(p['tail']); zl=m.zscore(p['lex']); return topk_desc(zt+np.float32(eta)*zl,P)
|
| 58 |
+
|
| 59 |
+
def select_quota(p,lq):
|
| 60 |
+
# Exactly P slots: preserve P-lq strongest geometric docs, then add strongest
|
| 61 |
+
# lexical docs not already admitted. If duplicates cause shortage, continue
|
| 62 |
+
# down the lexical ordering until P unique docs are selected.
|
| 63 |
+
n=len(p['ud']); k=min(P,n); gq=max(0,k-min(int(lq),k))
|
| 64 |
+
gt=topk_desc(p['tail'],gq)
|
| 65 |
+
if len(gt)==k:return gt
|
| 66 |
+
chosen=np.zeros(n,np.uint8); chosen[gt]=1
|
| 67 |
+
lo=np.argsort(p['lex'])[::-1]
|
| 68 |
+
out=np.empty(k,np.int64); out[:len(gt)]=gt; z=len(gt)
|
| 69 |
+
for ii in lo:
|
| 70 |
+
if chosen[ii]==0:
|
| 71 |
+
chosen[ii]=1; out[z]=ii; z+=1
|
| 72 |
+
if z==k:break
|
| 73 |
+
return out[:z]
|
| 74 |
+
|
| 75 |
+
# deterministic validation split already used elsewhere
|
| 76 |
+
tr=pd.read_csv(ROOT/'train.tsv',sep='\t',usecols=['query-id']); uq=np.unique(tr['query-id'].to_numpy()); rng=np.random.default_rng(20260815); ids=[str(x) for x in rng.choice(uq,size=1000,replace=False)]; del tr
|
| 77 |
+
texts=m.load_query_texts(ids); qrels=m.qrels_from_tsv(ROOT/'train.tsv',ids,positive_only=True)
|
| 78 |
+
# warm up both support kernels and geometric kernel
|
| 79 |
+
pp=prepare_all(texts[ids[0]]); _=final_rank(pp,select_direct(pp,0.0)); del pp
|
| 80 |
+
runsD={e:{} for e in ETAS}; runsQ={q:{} for q in LEX_QUOTAS}
|
| 81 |
+
poolhitD={e:0 for e in ETAS}; poolhitQ={q:0 for q in LEX_QUOTAS}; den=0; routehit=0
|
| 82 |
+
times=[]; cands=[]
|
| 83 |
+
for z,qid in enumerate(ids):
|
| 84 |
+
t=time.perf_counter(); p=prepare_all(texts[qid]); prepms=(time.perf_counter()-t)*1000; times.append(prepms)
|
| 85 |
+
rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels)
|
| 86 |
+
if p is None:
|
| 87 |
+
for e in ETAS:runsD[e][qid]=[]
|
| 88 |
+
for q in LEX_QUOTAS:runsQ[q][qid]=[]
|
| 89 |
+
continue
|
| 90 |
+
cands.append(p['candidate_docs']); ud=p['ud']
|
| 91 |
+
rel_idx=[]
|
| 92 |
+
for d in rels:
|
| 93 |
+
kk=np.searchsorted(ud,d); ok=(kk<len(ud) and int(ud[kk])==d); routehit+=int(ok)
|
| 94 |
+
if ok: rel_idx.append(int(kk))
|
| 95 |
+
relset=set(rel_idx)
|
| 96 |
+
for e in ETAS:
|
| 97 |
+
sel=select_direct(p,e); poolhitD[e]+=sum(int(i) in relset for i in sel); runsD[e][qid]=final_rank(p,sel)
|
| 98 |
+
for qv in LEX_QUOTAS:
|
| 99 |
+
sel=select_quota(p,qv); poolhitQ[qv]+=sum(int(i) in relset for i in sel); runsQ[qv][qid]=final_rank(p,sel)
|
| 100 |
+
if (z+1)%100==0:
|
| 101 |
+
print('q',z+1,'median_prepare_ms',float(np.median(times)),'route',routehit/max(1,den),flush=True)
|
| 102 |
+
|
| 103 |
+
rowsD=[]
|
| 104 |
+
for e in ETAS:
|
| 105 |
+
met=m.eval_run(runsD[e],qrels); row={'eta':e,'pool_relevant_recall':poolhitD[e]/den,**met}; rowsD.append(row); print('DIRECT',row,flush=True)
|
| 106 |
+
rowsQ=[]
|
| 107 |
+
for qv in LEX_QUOTAS:
|
| 108 |
+
met=m.eval_run(runsQ[qv],qrels); row={'lex_quota':qv,'pool_relevant_recall':poolhitQ[qv]/den,**met}; rowsQ.append(row); print('QUOTA',row,flush=True)
|
| 109 |
+
rowsD.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True)
|
| 110 |
+
rowsQ.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True)
|
| 111 |
+
out={'protocol':'deterministic 1000 TRAIN validation; geometry/tail fixed gamma=.25 lambdaM=.125 S=16 P=2000 h=0; final lambda_lex=4 lambda_sem=.1 locked; whole-document lexical enters routed->P selection','direct_rows':rowsD,'quota_rows':rowsQ,'best_direct':rowsD[0],'best_quota':rowsQ[0],'route_relevant_recall':routehit/den,'timing_prepare_alllex':{'median_ms':float(np.median(times)),'p95_ms':float(np.percentile(times,95)),'mean_ms':float(np.mean(times)),'avg_candidate_docs':float(np.mean(cands))}}
|
| 112 |
+
json.dump(out,open(WORK/'early_lex_validation.json','w'),indent=2)
|
| 113 |
+
print('BEST_DIRECT',rowsD[0],flush=True); print('BEST_QUOTA',rowsQ[0],flush=True); print('TIMING',out['timing_prepare_alllex'],flush=True)
|
experiments/msmarco_scale/msmarco_early_lex_validation_fast.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys,time,json
|
| 3 |
+
import numpy as np,pandas as pd
|
| 4 |
+
from numba import set_num_threads
|
| 5 |
+
sys.path.insert(0,'/mnt/data')
|
| 6 |
+
import msmarco_best_tail_core as b
|
| 7 |
+
import msmarco_full_search_uniform1m as m
|
| 8 |
+
ROOT=m.ROOT; WORK=m.WORK; idx=b.idx; M=m.M; P=2000
|
| 9 |
+
LLEX=np.float32(4.0); LSEM=np.float32(0.1)
|
| 10 |
+
ETAS=[0.0,0.0625,0.125,0.25,0.5,1.0,2.0,4.0,8.0]
|
| 11 |
+
LEX_QUOTAS=[0,100,250,500,750,1000,1250,1500,1750,2000]
|
| 12 |
+
set_num_threads(5)
|
| 13 |
+
|
| 14 |
+
def topk_desc(score,k):
|
| 15 |
+
n=len(score); k=min(k,n)
|
| 16 |
+
if k<=0:return np.empty(0,np.int64)
|
| 17 |
+
if n>k:
|
| 18 |
+
ii=np.argpartition(score,-k)[-k:]
|
| 19 |
+
return ii[np.argsort(score[ii])[::-1]]
|
| 20 |
+
return np.argsort(score)[::-1]
|
| 21 |
+
|
| 22 |
+
def prepare_all(text):
|
| 23 |
+
q=idx.query_vec(text); qd=np.zeros(M,np.float32); qd[q.indices]=q.data; rterms,rd=idx.route(q)
|
| 24 |
+
spans=[(int(j),int(idx.offs[j]),int(idx.offs[j+1])) for j in rterms if idx.offs[j+1]>idx.offs[j]]
|
| 25 |
+
if not spans:return None
|
| 26 |
+
docs=np.concatenate([np.asarray(idx.pd[a:bb]) for j,a,bb in spans]).astype(np.uint32,copy=False)
|
| 27 |
+
mm=np.concatenate([np.asarray(idx.pm[a:bb]) for j,a,bb in spans]).astype(np.float32,copy=False)
|
| 28 |
+
rt=np.concatenate([np.asarray(idx.pr[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 29 |
+
sb=np.concatenate([np.asarray(idx.ps[a:bb]) for j,a,bb in spans]).astype(np.uint16,copy=False)
|
| 30 |
+
nr=len(spans); cent=np.zeros((nr,M),np.float32); rel=np.zeros((nr,M),np.float32); rho=np.empty(nr,np.float32)
|
| 31 |
+
for u,(j,a,bb) in enumerate(spans):
|
| 32 |
+
rowt=np.asarray(idx.ct[j]); ok=rowt!=65535; tids=rowt[ok].astype(np.int32,copy=False); cent[u,tids]=np.asarray(idx.cv[j])[ok]
|
| 33 |
+
ra=int(idx.rp[j]); rb=int(idx.rp[j+1]); rel[u,np.asarray(idx.ri[ra:rb],np.int32)]=np.asarray(idx.rv[ra:rb]); rho[u]=rd[j]
|
| 34 |
+
rslot=np.concatenate([np.full(bb-a,u,dtype=np.uint8) for u,(j,a,bb) in enumerate(spans)])
|
| 35 |
+
base,sig,cons=b.score_components(rslot,mm,rt,sb,qd,rho,cent,rel)
|
| 36 |
+
ud,inv=np.unique(docs,return_inverse=True)
|
| 37 |
+
tail=np.bincount(inv,weights=base*np.power(sig,b.GAMMA,dtype=np.float32),minlength=len(ud)).astype(np.float32)+b.LAM*np.bincount(inv,weights=cons,minlength=len(ud)).astype(np.float32)
|
| 38 |
+
lexvec=np.zeros(M,np.float32); lexvec[q.indices]=idx.idf[q.indices]
|
| 39 |
+
semvec=np.zeros(M,np.float32)
|
| 40 |
+
for t,amp in zip(q.indices,q.data):
|
| 41 |
+
a,bb=idx.A.indptr[t],idx.A.indptr[t+1]; nb=idx.A.indices[a:bb][:m.SEMK]; sv=idx.A.data[a:bb][:m.SEMK]; semvec[nb]+=float(amp)*sv*idx.idf[nb]
|
| 42 |
+
# One CSR scan per routed doc supplies both validation features.
|
| 43 |
+
lex,sem=m.score_support_pool(ud,idx.sup_ip,idx.sup_ids,lexvec,semvec,idx.dl,idx.avgdl)
|
| 44 |
+
return {'ud':ud,'tail':tail,'lex':lex,'sem':sem,'candidate_docs':len(ud),'candidate_memberships':len(docs)}
|
| 45 |
+
|
| 46 |
+
def final_rank(p,sel,k=100):
|
| 47 |
+
docs=p['ud'][sel]; fin=m.zscore(p['tail'][sel])+LLEX*m.zscore(p['lex'][sel])+LSEM*m.zscore(p['sem'][sel]); oo=np.argsort(fin)[::-1][:k]; return [int(x) for x in docs[oo]]
|
| 48 |
+
|
| 49 |
+
def quota_from_orders(tail_order,lex_order,n,lq):
|
| 50 |
+
k=min(P,n); gq=max(0,k-min(lq,k)); out=np.empty(k,np.int64); z=0; chosen=np.zeros(n,np.uint8)
|
| 51 |
+
if gq:
|
| 52 |
+
g=tail_order[:gq]; out[:gq]=g; chosen[g]=1; z=gq
|
| 53 |
+
if z==k: return out
|
| 54 |
+
for ii in lex_order:
|
| 55 |
+
if chosen[ii]==0:
|
| 56 |
+
chosen[ii]=1; out[z]=ii; z+=1
|
| 57 |
+
if z==k:break
|
| 58 |
+
return out[:z]
|
| 59 |
+
|
| 60 |
+
tr=pd.read_csv(ROOT/'train.tsv',sep='\t',usecols=['query-id']); uq=np.unique(tr['query-id'].to_numpy()); rng=np.random.default_rng(20260815); ids=[str(x) for x in rng.choice(uq,size=1000,replace=False)]; del tr
|
| 61 |
+
texts=m.load_query_texts(ids); qrels=m.qrels_from_tsv(ROOT/'train.tsv',ids,positive_only=True)
|
| 62 |
+
p=prepare_all(texts[ids[0]]); _=final_rank(p,topk_desc(p['tail'],P)); del p
|
| 63 |
+
runsD={e:{} for e in ETAS}; runsQ={q:{} for q in LEX_QUOTAS}; poolD={e:0 for e in ETAS}; poolQ={q:0 for q in LEX_QUOTAS}; den=routehit=0; times=[]; cands=[]
|
| 64 |
+
for z,qid in enumerate(ids):
|
| 65 |
+
t=time.perf_counter(); p=prepare_all(texts[qid]); times.append((time.perf_counter()-t)*1000)
|
| 66 |
+
rels=[int(d) for d,r in qrels[qid].items() if r>0]; den+=len(rels)
|
| 67 |
+
if p is None:
|
| 68 |
+
for e in ETAS:runsD[e][qid]=[]
|
| 69 |
+
for qv in LEX_QUOTAS:runsQ[qv][qid]=[]
|
| 70 |
+
continue
|
| 71 |
+
cands.append(p['candidate_docs']); ud=p['ud']; relset=set()
|
| 72 |
+
for d in rels:
|
| 73 |
+
kk=np.searchsorted(ud,d); ok=(kk<len(ud) and int(ud[kk])==d); routehit+=int(ok)
|
| 74 |
+
if ok: relset.add(int(kk))
|
| 75 |
+
zt=m.zscore(p['tail']); zl=m.zscore(p['lex'])
|
| 76 |
+
for e in ETAS:
|
| 77 |
+
sel=topk_desc(zt+np.float32(e)*zl,P); poolD[e]+=sum(int(i) in relset for i in sel); runsD[e][qid]=final_rank(p,sel)
|
| 78 |
+
tail_order=topk_desc(p['tail'],P); lex_order=np.argsort(p['lex'])[::-1]
|
| 79 |
+
for qv in LEX_QUOTAS:
|
| 80 |
+
sel=quota_from_orders(tail_order,lex_order,len(ud),qv); poolQ[qv]+=sum(int(i) in relset for i in sel); runsQ[qv][qid]=final_rank(p,sel)
|
| 81 |
+
if (z+1)%100==0:print('q',z+1,'median_prepare',float(np.median(times)),'route',routehit/den,flush=True)
|
| 82 |
+
rowsD=[]
|
| 83 |
+
for e in ETAS:
|
| 84 |
+
met=m.eval_run(runsD[e],qrels); row={'eta':e,'pool_relevant_recall':poolD[e]/den,**met}; rowsD.append(row); print('DIRECT',row,flush=True)
|
| 85 |
+
rowsQ=[]
|
| 86 |
+
for qv in LEX_QUOTAS:
|
| 87 |
+
met=m.eval_run(runsQ[qv],qrels); row={'lex_quota':qv,'pool_relevant_recall':poolQ[qv]/den,**met}; rowsQ.append(row); print('QUOTA',row,flush=True)
|
| 88 |
+
rowsD.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True); rowsQ.sort(key=lambda r:(r['nDCG@10'],r['MRR@10'],r['R@100']),reverse=True)
|
| 89 |
+
out={'protocol':'same deterministic 1000 TRAIN validation; gamma=.25 lambdaM=.125 S=16 P=2000 h=0; final lambda_lex=4 lambda_sem=.1 locked; lexical support injected before P selection','direct_rows':rowsD,'quota_rows':rowsQ,'best_direct':rowsD[0],'best_quota':rowsQ[0],'route_relevant_recall':routehit/den,'timing_validation_amortized':{'median_prepare_ms':float(np.median(times)),'p95_prepare_ms':float(np.percentile(times,95)),'avg_candidate_docs':float(np.mean(cands))}}
|
| 90 |
+
json.dump(out,open(WORK/'early_lex_validation.json','w'),indent=2); print('BEST_DIRECT',rowsD[0],flush=True); print('BEST_QUOTA',rowsQ[0],flush=True); print('TIMING',out['timing_validation_amortized'],flush=True)
|
experiments/msmarco_scale/msmarco_encode_full.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import gzip,json,pickle,time,re,gc,os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scipy import sparse
|
| 6 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 7 |
+
from sklearn.preprocessing import normalize
|
| 8 |
+
from numba import njit, prange, set_num_threads
|
| 9 |
+
|
| 10 |
+
ROOT=Path('/mnt/data'); WORK=ROOT/'msmarco_scale_work'; GEOM=WORK/'geometry_1m'; IDX=WORK/'full_index'; IDX.mkdir(parents=True,exist_ok=True)
|
| 11 |
+
N=8_841_823; M=50_000; F=4; S=16; SENT=np.uint16(65535)
|
| 12 |
+
set_num_threads(5)
|
| 13 |
+
TOKEN_RE=re.compile(r'(?u)\b\w\w+\b')
|
| 14 |
+
|
| 15 |
+
def shard_path(i):
|
| 16 |
+
hits=list(ROOT.glob(f'corpus_{i:04d}.jsonl*.gz')); assert len(hits)==1,(i,hits); return hits[0]
|
| 17 |
+
|
| 18 |
+
def load_vocab():
|
| 19 |
+
with gzip.open(WORK/'final_vocab_50k.pkl.gz','rb') as g: z=pickle.load(g)
|
| 20 |
+
terms=z['terms'].tolist(); idf=np.asarray(z['idf'],np.float32); return terms,idf,{t:i for i,t in enumerate(terms)}
|
| 21 |
+
|
| 22 |
+
@njit(cache=False)
|
| 23 |
+
def lookup_center(ct,cv,t):
|
| 24 |
+
lo=0; hi=ct.size
|
| 25 |
+
while lo<hi:
|
| 26 |
+
mid=(lo+hi)//2; x=ct[mid]
|
| 27 |
+
if x==65535 or x>=t: hi=mid
|
| 28 |
+
else: lo=mid+1
|
| 29 |
+
if lo<ct.size and ct[lo]==t: return cv[lo]
|
| 30 |
+
return 0.0
|
| 31 |
+
|
| 32 |
+
@njit(parallel=True,cache=False)
|
| 33 |
+
def encode_kernel(indptr,indices,data,center_terms,center_values):
|
| 34 |
+
n=indptr.size-1
|
| 35 |
+
branches=np.full((n,F),SENT,np.uint16); mem=np.zeros((n,F),np.float32)
|
| 36 |
+
rt=np.full((n,F,S),SENT,np.uint16); signbits=np.zeros((n,F),np.uint16)
|
| 37 |
+
for d in prange(n):
|
| 38 |
+
a=indptr[d]; b=indptr[d+1]
|
| 39 |
+
# top4 document coordinates
|
| 40 |
+
tv=np.zeros(F,np.float32); tt=np.full(F,SENT,np.uint16)
|
| 41 |
+
for p in range(a,b):
|
| 42 |
+
v=data[p]; t=np.uint16(indices[p]); pos=F
|
| 43 |
+
for r in range(F):
|
| 44 |
+
if v>tv[r]: pos=r; break
|
| 45 |
+
if pos<F:
|
| 46 |
+
for r in range(F-1,pos,-1): tv[r]=tv[r-1]; tt[r]=tt[r-1]
|
| 47 |
+
tv[pos]=v; tt[pos]=t
|
| 48 |
+
den=0.0
|
| 49 |
+
for s in range(F): den+=tv[s]
|
| 50 |
+
if den<=0: continue
|
| 51 |
+
for s in range(F): branches[d,s]=tt[s]; mem[d,s]=tv[s]/den
|
| 52 |
+
# residual codes per fuzzy branch
|
| 53 |
+
for sl in range(F):
|
| 54 |
+
j=int(tt[sl])
|
| 55 |
+
if j==65535: continue
|
| 56 |
+
best=np.zeros(S,np.float32); bt=np.full(S,SENT,np.uint16); bp=np.zeros(S,np.uint8)
|
| 57 |
+
for p in range(a,b):
|
| 58 |
+
t=np.uint16(indices[p]); r=data[p]-lookup_center(center_terms[j],center_values[j],t); ar=abs(r)
|
| 59 |
+
mi=0; mv=best[0]
|
| 60 |
+
for q in range(1,S):
|
| 61 |
+
if best[q]<mv: mi=q; mv=best[q]
|
| 62 |
+
if ar>mv:
|
| 63 |
+
best[mi]=ar; bt[mi]=t; bp[mi]=1 if r>=0 else 0
|
| 64 |
+
# sort descending to stabilize
|
| 65 |
+
for x in range(S):
|
| 66 |
+
mx=x
|
| 67 |
+
for y in range(x+1,S):
|
| 68 |
+
if best[y]>best[mx]: mx=y
|
| 69 |
+
if mx!=x:
|
| 70 |
+
z=best[x]; best[x]=best[mx]; best[mx]=z
|
| 71 |
+
zt=bt[x]; bt[x]=bt[mx]; bt[mx]=zt
|
| 72 |
+
zp=bp[x]; bp[x]=bp[mx]; bp[mx]=zp
|
| 73 |
+
bits=np.uint16(0)
|
| 74 |
+
for q in range(S):
|
| 75 |
+
rt[d,sl,q]=bt[q]
|
| 76 |
+
if bt[q]!=SENT and bp[q]: bits |= np.uint16(1<<q)
|
| 77 |
+
signbits[d,sl]=bits
|
| 78 |
+
return branches,mem,rt,signbits
|
| 79 |
+
|
| 80 |
+
if __name__=='__main__':
|
| 81 |
+
terms,idf,vocab=load_vocab(); center_terms=np.load(GEOM/'center_terms.npy',mmap_mode='r'); center_values=np.load(GEOM/'center_values.npy',mmap_mode='r')
|
| 82 |
+
# Global disk-backed arrays
|
| 83 |
+
branches=np.memmap(IDX/'branches.u16',dtype=np.uint16,mode='w+',shape=(N,F)); branches[:]=SENT
|
| 84 |
+
memberships=np.memmap(IDX/'memberships.f32',dtype=np.float32,mode='w+',shape=(N,F)); memberships[:]=0
|
| 85 |
+
res_terms=np.memmap(IDX/'res_terms.u16',dtype=np.uint16,mode='w+',shape=(N,F,S)); res_terms[:]=SENT
|
| 86 |
+
signbits=np.memmap(IDX/'signbits.u16',dtype=np.uint16,mode='w+',shape=(N,F)); signbits[:]=0
|
| 87 |
+
doc_lengths=np.memmap(IDX/'doc_lengths.u16',dtype=np.uint16,mode='w+',shape=(N,)); doc_lengths[:]=0
|
| 88 |
+
cv=CountVectorizer(vocabulary=vocab,lowercase=True,token_pattern=r'(?u)\b\w\w+\b',dtype=np.int32)
|
| 89 |
+
total_len=0; t_all=time.time(); offset=0
|
| 90 |
+
for sid in range(36):
|
| 91 |
+
t=time.time(); texts=[]; lens=[]
|
| 92 |
+
with gzip.open(shard_path(sid),'rt',encoding='utf-8') as f:
|
| 93 |
+
for line in f:
|
| 94 |
+
o=json.loads(line); tx=((o.get('title') or '')+' '+(o.get('text') or '')).strip(); texts.append(tx); lens.append(min(65535,len(TOKEN_RE.findall(tx.lower()))))
|
| 95 |
+
n=len(texts); X=cv.transform(texts).tocsr().astype(np.float32); X.data *= idf[X.indices]; normalize(X,norm='l2',axis=1,copy=False); X.sort_indices()
|
| 96 |
+
br,mm,rt,sb=encode_kernel(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),center_terms,center_values)
|
| 97 |
+
sl=slice(offset,offset+n); branches[sl]=br; memberships[sl]=mm; res_terms[sl]=rt; signbits[sl]=sb; doc_lengths[sl]=np.asarray(lens,np.uint16); total_len += int(np.sum(lens,dtype=np.int64))
|
| 98 |
+
# whole-document binary support, one pair of files per corpus shard
|
| 99 |
+
X.indices.astype(np.uint16).tofile(IDX/f'support_{sid:04d}.u16')
|
| 100 |
+
X.indptr.astype(np.uint32).tofile(IDX/f'support_indptr_{sid:04d}.u32')
|
| 101 |
+
with open(IDX/f'shard_{sid:04d}.json','w') as f: json.dump({'offset':offset,'n':n,'nnz':int(X.nnz),'seconds':time.time()-t},f)
|
| 102 |
+
offset+=n; branches.flush(); memberships.flush(); res_terms.flush(); signbits.flush(); doc_lengths.flush()
|
| 103 |
+
print(f'[{sid+1:02d}/36] n={n:,} nnz={X.nnz:,} offset={offset:,} sec={time.time()-t:.1f}',flush=True)
|
| 104 |
+
del texts,lens,X,br,mm,rt,sb; gc.collect()
|
| 105 |
+
assert offset==N,(offset,N)
|
| 106 |
+
avg=total_len/N
|
| 107 |
+
# Build branch postings by a global stable sort over 35.4M uint16 branch IDs.
|
| 108 |
+
print('building branch postings...',flush=True); t=time.time(); flat=np.memmap(IDX/'branches.u16',dtype=np.uint16,mode='r',shape=(N*F,)); order=np.argsort(flat,kind='stable'); sorted_br=flat[order]; nvalid=int(np.searchsorted(sorted_br,SENT,side='left'))
|
| 109 |
+
bo=np.memmap(IDX/'branch_order.u32',dtype=np.uint32,mode='w+',shape=(nvalid,)); bo[:]=order[:nvalid].astype(np.uint32); bo.flush(); counts=np.bincount(sorted_br[:nvalid].astype(np.int64),minlength=M); offsets=np.zeros(M+1,np.uint64); np.cumsum(counts,dtype=np.uint64,out=offsets[1:]); np.save(IDX/'branch_offsets.npy',offsets); print('postings valid memberships',nvalid,'sec',time.time()-t,flush=True)
|
| 110 |
+
with open(IDX/'meta.json','w') as f: json.dump({'N':N,'M':M,'F':F,'S':S,'avg_doc_length':avg,'build_seconds':time.time()-t_all,'geometry':'geometry_1m_fullcorpus_vocab'},f,indent=2)
|
| 111 |
+
print('FULL INDEX DONE avgdl',avg,'total sec',time.time()-t_all,flush=True)
|
experiments/msmarco_scale/msmarco_encode_resume.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import sys, gzip, json, pickle, time, re, gc, os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 5 |
+
import multiprocessing as mp
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 8 |
+
from sklearn.preprocessing import normalize
|
| 9 |
+
from numba import set_num_threads
|
| 10 |
+
sys.path.insert(0,'/mnt/data')
|
| 11 |
+
import msmarco_encode_full as base
|
| 12 |
+
|
| 13 |
+
ROOT=Path('/mnt/data'); WORK=ROOT/'msmarco_scale_work'; GEOM=WORK/'geometry_1m'; IDX=WORK/'full_index'
|
| 14 |
+
N=8_841_823; M=50_000; F=4; S=16
|
| 15 |
+
TOKEN_RE=re.compile(r'(?u)\b\w\w+\b')
|
| 16 |
+
|
| 17 |
+
def shard_path(i):
|
| 18 |
+
hits=list(ROOT.glob(f'corpus_{i:04d}.jsonl*.gz')); assert len(hits)==1,(i,hits); return hits[0]
|
| 19 |
+
|
| 20 |
+
def load_vocab():
|
| 21 |
+
with gzip.open(WORK/'final_vocab_50k.pkl.gz','rb') as g:z=pickle.load(g)
|
| 22 |
+
terms=z['terms'].tolist(); idf=np.asarray(z['idf'],np.float32); return idf,{t:i for i,t in enumerate(terms)}
|
| 23 |
+
|
| 24 |
+
def work(sid):
|
| 25 |
+
set_num_threads(1)
|
| 26 |
+
t=time.time(); idf,vocab=load_vocab(); center_terms=np.load(GEOM/'center_terms.npy',mmap_mode='r'); center_values=np.load(GEOM/'center_values.npy',mmap_mode='r')
|
| 27 |
+
branches=np.memmap(IDX/'branches.u16',np.uint16,'r+',shape=(N,F)); memberships=np.memmap(IDX/'memberships.f32',np.float32,'r+',shape=(N,F)); rtg=np.memmap(IDX/'res_terms.u16',np.uint16,'r+',shape=(N,F,S)); sbg=np.memmap(IDX/'signbits.u16',np.uint16,'r+',shape=(N,F)); dlg=np.memmap(IDX/'doc_lengths.u16',np.uint16,'r+',shape=(N,))
|
| 28 |
+
texts=[]; lens=[]
|
| 29 |
+
with gzip.open(shard_path(sid),'rt',encoding='utf-8') as f:
|
| 30 |
+
for line in f:
|
| 31 |
+
o=json.loads(line); tx=((o.get('title') or '')+' '+(o.get('text') or '')).strip(); texts.append(tx); lens.append(min(65535,len(TOKEN_RE.findall(tx.lower()))))
|
| 32 |
+
n=len(texts); cv=CountVectorizer(vocabulary=vocab,lowercase=True,token_pattern=r'(?u)\b\w\w+\b',dtype=np.int32); X=cv.transform(texts).tocsr().astype(np.float32); X.data*=idf[X.indices]; normalize(X,norm='l2',axis=1,copy=False); X.sort_indices()
|
| 33 |
+
br,mm,rt,sb=base.encode_kernel(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),center_terms,center_values)
|
| 34 |
+
offset=sid*250_000; sl=slice(offset,offset+n); branches[sl]=br; memberships[sl]=mm; rtg[sl]=rt; sbg[sl]=sb; dlg[sl]=np.asarray(lens,np.uint16)
|
| 35 |
+
X.indices.astype(np.uint16).tofile(IDX/f'support_{sid:04d}.u16'); X.indptr.astype(np.uint32).tofile(IDX/f'support_indptr_{sid:04d}.u32')
|
| 36 |
+
branches.flush(); memberships.flush(); rtg.flush(); sbg.flush(); dlg.flush()
|
| 37 |
+
secs=time.time()-t
|
| 38 |
+
with open(IDX/f'shard_{sid:04d}.json','w') as f:json.dump({'offset':offset,'n':n,'nnz':int(X.nnz),'seconds':secs},f)
|
| 39 |
+
return sid,n,int(X.nnz),secs
|
| 40 |
+
|
| 41 |
+
if __name__=='__main__':
|
| 42 |
+
missing=[i for i in range(36) if not (IDX/f'shard_{i:04d}.json').exists()]
|
| 43 |
+
print('missing',missing,flush=True); t0=time.time()
|
| 44 |
+
with ProcessPoolExecutor(max_workers=3, mp_context=mp.get_context('spawn')) as ex:
|
| 45 |
+
fs={ex.submit(work,i):i for i in missing}; done=0
|
| 46 |
+
for f in as_completed(fs):
|
| 47 |
+
sid,n,nnz,sec=f.result(); done+=1; print(f'[{done:02d}/{len(missing):02d}] shard {sid:04d} n={n:,} nnz={nnz:,} sec={sec:.1f}',flush=True)
|
| 48 |
+
print('encoding complete sec',time.time()-t0,flush=True)
|
| 49 |
+
# validate all shards and calculate avg dl
|
| 50 |
+
metas=[]
|
| 51 |
+
for i in range(36):
|
| 52 |
+
with open(IDX/f'shard_{i:04d}.json') as f:metas.append(json.load(f))
|
| 53 |
+
assert sum(x['n'] for x in metas)==N
|
| 54 |
+
dl=np.memmap(IDX/'doc_lengths.u16',np.uint16,'r',shape=(N,)); avg=float(np.mean(dl,dtype=np.float64));
|
| 55 |
+
# postings
|
| 56 |
+
print('building postings',flush=True); t=time.time(); flat=np.memmap(IDX/'branches.u16',np.uint16,'r',shape=(N*F,)); order=np.argsort(flat,kind='stable'); sorted_br=flat[order]; nvalid=int(np.searchsorted(sorted_br,np.uint16(65535),side='left')); bo=np.memmap(IDX/'branch_order.u32',np.uint32,'w+',shape=(nvalid,)); bo[:]=order[:nvalid].astype(np.uint32); bo.flush(); counts=np.bincount(sorted_br[:nvalid].astype(np.int64),minlength=M); offs=np.zeros(M+1,np.uint64); np.cumsum(counts,dtype=np.uint64,out=offs[1:]); np.save(IDX/'branch_offsets.npy',offs); print('postings',nvalid,'sec',time.time()-t,flush=True)
|
| 57 |
+
with open(IDX/'meta.json','w') as f:json.dump({'N':N,'M':M,'F':F,'S':S,'avg_doc_length':avg,'build_seconds_resume':time.time()-t0,'geometry':'geometry_1m_fullcorpus_vocab'},f,indent=2)
|
| 58 |
+
print('FULL INDEX DONE avgdl',avg,'total sec',time.time()-t0,flush=True)
|
experiments/msmarco_scale/msmarco_encode_s32.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import gzip,json,pickle,time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from concurrent.futures import ProcessPoolExecutor,as_completed
|
| 5 |
+
import multiprocessing as mp
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 8 |
+
from sklearn.preprocessing import normalize
|
| 9 |
+
from numba import njit,prange,set_num_threads
|
| 10 |
+
ROOT=Path('/mnt/data'); W=ROOT/'msmarco_scale_work'; G=W/'geometry_uniform1m_s32'; OLD=W/'full_index'; NEW=W/'full_index_uniform1m_s32'; NEW.mkdir(exist_ok=True)
|
| 11 |
+
N=8_841_823; M=50_000; F=4; S=32; SENT=np.uint16(65535)
|
| 12 |
+
|
| 13 |
+
def shard_path(i):
|
| 14 |
+
hits=list(ROOT.glob(f'corpus_{i:04d}.jsonl*.gz')); assert len(hits)==1; return hits[0]
|
| 15 |
+
def load_vocab():
|
| 16 |
+
with gzip.open(W/'final_vocab_50k.pkl.gz','rb') as g:z=pickle.load(g)
|
| 17 |
+
terms=z['terms'].tolist(); idf=np.asarray(z['idf'],np.float32); return idf,{t:i for i,t in enumerate(terms)}
|
| 18 |
+
@njit(cache=False)
|
| 19 |
+
def lookup(ct,cv,t):
|
| 20 |
+
lo=0; hi=ct.size
|
| 21 |
+
while lo<hi:
|
| 22 |
+
mid=(lo+hi)//2; x=ct[mid]
|
| 23 |
+
if x==65535 or x>=t: hi=mid
|
| 24 |
+
else: lo=mid+1
|
| 25 |
+
if lo<ct.size and ct[lo]==t:return cv[lo]
|
| 26 |
+
return 0.0
|
| 27 |
+
@njit(parallel=True,cache=False)
|
| 28 |
+
def kernel(indptr,indices,data,ct,cv):
|
| 29 |
+
n=indptr.size-1; br=np.full((n,F),SENT,np.uint16); rt=np.full((n,F,S),SENT,np.uint16); sb=np.zeros((n,F),np.uint32)
|
| 30 |
+
for d in prange(n):
|
| 31 |
+
a=indptr[d]; b=indptr[d+1]; tv=np.zeros(F,np.float32); tt=np.full(F,SENT,np.uint16)
|
| 32 |
+
for p in range(a,b):
|
| 33 |
+
v=data[p]; t=np.uint16(indices[p]); pos=F
|
| 34 |
+
for r in range(F):
|
| 35 |
+
if v>tv[r]:pos=r;break
|
| 36 |
+
if pos<F:
|
| 37 |
+
for r in range(F-1,pos,-1):tv[r]=tv[r-1];tt[r]=tt[r-1]
|
| 38 |
+
tv[pos]=v;tt[pos]=t
|
| 39 |
+
den=0.0
|
| 40 |
+
for s in range(F):den+=tv[s]
|
| 41 |
+
if den<=0:continue
|
| 42 |
+
for s in range(F):br[d,s]=tt[s]
|
| 43 |
+
for sl in range(F):
|
| 44 |
+
j=int(tt[sl]); best=np.zeros(S,np.float32); bt=np.full(S,SENT,np.uint16); bp=np.zeros(S,np.uint8)
|
| 45 |
+
for p in range(a,b):
|
| 46 |
+
t=np.uint16(indices[p]); rr=data[p]-lookup(ct[j],cv[j],t); ar=abs(rr); mi=0; mv=best[0]
|
| 47 |
+
for q in range(1,S):
|
| 48 |
+
if best[q]<mv:mi=q;mv=best[q]
|
| 49 |
+
if ar>mv:best[mi]=ar;bt[mi]=t;bp[mi]=1 if rr>=0 else 0
|
| 50 |
+
for x in range(S):
|
| 51 |
+
mx=x
|
| 52 |
+
for y in range(x+1,S):
|
| 53 |
+
if best[y]>best[mx]:mx=y
|
| 54 |
+
if mx!=x:
|
| 55 |
+
zz=best[x];best[x]=best[mx];best[mx]=zz; zt=bt[x];bt[x]=bt[mx];bt[mx]=zt; zp=bp[x];bp[x]=bp[mx];bp[mx]=zp
|
| 56 |
+
bits=np.uint32(0)
|
| 57 |
+
for q in range(S):
|
| 58 |
+
rt[d,sl,q]=bt[q]
|
| 59 |
+
if bt[q]!=SENT and bp[q]:bits|=np.uint32(1)<<np.uint32(q)
|
| 60 |
+
sb[d,sl]=bits
|
| 61 |
+
return br,rt,sb
|
| 62 |
+
|
| 63 |
+
def work(sid):
|
| 64 |
+
set_num_threads(1); t=time.time(); idf,vocab=load_vocab(); ct=np.load(G/'center_terms.npy',mmap_mode='r'); cvv=np.load(G/'center_values.npy',mmap_mode='r'); oldbr=np.memmap(OLD/'branches.u16',np.uint16,'r',shape=(N,F)); rtg=np.memmap(NEW/'res_terms.u16',np.uint16,'r+',shape=(N,F,S)); sbg=np.memmap(NEW/'signbits.u32',np.uint32,'r+',shape=(N,F))
|
| 65 |
+
texts=[]
|
| 66 |
+
with gzip.open(shard_path(sid),'rt',encoding='utf-8') as f:
|
| 67 |
+
for line in f:
|
| 68 |
+
o=json.loads(line);texts.append(((o.get('title') or '')+' '+(o.get('text') or '')).strip())
|
| 69 |
+
cv=CountVectorizer(vocabulary=vocab,lowercase=True,token_pattern=r'(?u)\b\w\w+\b',dtype=np.int32);X=cv.transform(texts).tocsr().astype(np.float32);X.data*=idf[X.indices];normalize(X,norm='l2',axis=1,copy=False);X.sort_indices(); br,rt,sb=kernel(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),ct,cvv)
|
| 70 |
+
n=len(texts);off=sid*250_000;sl=slice(off,off+n);mism=int(np.sum(br!=np.asarray(oldbr[sl])));assert mism==0,(sid,mism);rtg[sl]=rt;sbg[sl]=sb;rtg.flush();sbg.flush();sec=time.time()-t;json.dump({'offset':off,'n':n,'nnz':int(X.nnz),'seconds':sec,'branch_mismatches':mism},open(NEW/f'shard_{sid:04d}.json','w'));return sid,n,sec
|
| 71 |
+
if __name__=='__main__':
|
| 72 |
+
if not (NEW/'res_terms.u16').exists():a=np.memmap(NEW/'res_terms.u16',np.uint16,'w+',shape=(N,F,S));a[:]=SENT;a.flush();del a
|
| 73 |
+
if not (NEW/'signbits.u32').exists():a=np.memmap(NEW/'signbits.u32',np.uint32,'w+',shape=(N,F));a[:]=0;a.flush();del a
|
| 74 |
+
done={int(p.stem.split('_')[1]) for p in NEW.glob('shard_*.json')};missing=[i for i in range(36) if i not in done];print('missing',missing,flush=True);t=time.time()
|
| 75 |
+
with ProcessPoolExecutor(max_workers=3,mp_context=mp.get_context('spawn')) as ex:
|
| 76 |
+
fs=[ex.submit(work,i) for i in missing]
|
| 77 |
+
for k,fu in enumerate(as_completed(fs),1):sid,n,sec=fu.result();print(f'[{k:02d}/{len(missing):02d}] shard {sid:04d} n={n:,} sec={sec:.1f}',flush=True)
|
| 78 |
+
print('S32 ENCODE DONE',time.time()-t,flush=True)
|
experiments/msmarco_scale/msmarco_encode_s32_1w.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import gzip,json,pickle,time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from concurrent.futures import ProcessPoolExecutor,as_completed
|
| 5 |
+
import multiprocessing as mp
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 8 |
+
from sklearn.preprocessing import normalize
|
| 9 |
+
from numba import njit,prange,set_num_threads
|
| 10 |
+
ROOT=Path('/mnt/data'); W=ROOT/'msmarco_scale_work'; G=W/'geometry_uniform1m_s32'; OLD=W/'full_index'; NEW=W/'full_index_uniform1m_s32'; NEW.mkdir(exist_ok=True)
|
| 11 |
+
N=8_841_823; M=50_000; F=4; S=32; SENT=np.uint16(65535)
|
| 12 |
+
|
| 13 |
+
def shard_path(i):
|
| 14 |
+
hits=list(ROOT.glob(f'corpus_{i:04d}.jsonl*.gz')); assert len(hits)==1; return hits[0]
|
| 15 |
+
def load_vocab():
|
| 16 |
+
with gzip.open(W/'final_vocab_50k.pkl.gz','rb') as g:z=pickle.load(g)
|
| 17 |
+
terms=z['terms'].tolist(); idf=np.asarray(z['idf'],np.float32); return idf,{t:i for i,t in enumerate(terms)}
|
| 18 |
+
@njit(cache=False)
|
| 19 |
+
def lookup(ct,cv,t):
|
| 20 |
+
lo=0; hi=ct.size
|
| 21 |
+
while lo<hi:
|
| 22 |
+
mid=(lo+hi)//2; x=ct[mid]
|
| 23 |
+
if x==65535 or x>=t: hi=mid
|
| 24 |
+
else: lo=mid+1
|
| 25 |
+
if lo<ct.size and ct[lo]==t:return cv[lo]
|
| 26 |
+
return 0.0
|
| 27 |
+
@njit(parallel=True,cache=False)
|
| 28 |
+
def kernel(indptr,indices,data,ct,cv):
|
| 29 |
+
n=indptr.size-1; br=np.full((n,F),SENT,np.uint16); rt=np.full((n,F,S),SENT,np.uint16); sb=np.zeros((n,F),np.uint32)
|
| 30 |
+
for d in prange(n):
|
| 31 |
+
a=indptr[d]; b=indptr[d+1]; tv=np.zeros(F,np.float32); tt=np.full(F,SENT,np.uint16)
|
| 32 |
+
for p in range(a,b):
|
| 33 |
+
v=data[p]; t=np.uint16(indices[p]); pos=F
|
| 34 |
+
for r in range(F):
|
| 35 |
+
if v>tv[r]:pos=r;break
|
| 36 |
+
if pos<F:
|
| 37 |
+
for r in range(F-1,pos,-1):tv[r]=tv[r-1];tt[r]=tt[r-1]
|
| 38 |
+
tv[pos]=v;tt[pos]=t
|
| 39 |
+
den=0.0
|
| 40 |
+
for s in range(F):den+=tv[s]
|
| 41 |
+
if den<=0:continue
|
| 42 |
+
for s in range(F):br[d,s]=tt[s]
|
| 43 |
+
for sl in range(F):
|
| 44 |
+
j=int(tt[sl]); best=np.zeros(S,np.float32); bt=np.full(S,SENT,np.uint16); bp=np.zeros(S,np.uint8)
|
| 45 |
+
for p in range(a,b):
|
| 46 |
+
t=np.uint16(indices[p]); rr=data[p]-lookup(ct[j],cv[j],t); ar=abs(rr); mi=0; mv=best[0]
|
| 47 |
+
for q in range(1,S):
|
| 48 |
+
if best[q]<mv:mi=q;mv=best[q]
|
| 49 |
+
if ar>mv:best[mi]=ar;bt[mi]=t;bp[mi]=1 if rr>=0 else 0
|
| 50 |
+
for x in range(S):
|
| 51 |
+
mx=x
|
| 52 |
+
for y in range(x+1,S):
|
| 53 |
+
if best[y]>best[mx]:mx=y
|
| 54 |
+
if mx!=x:
|
| 55 |
+
zz=best[x];best[x]=best[mx];best[mx]=zz; zt=bt[x];bt[x]=bt[mx];bt[mx]=zt; zp=bp[x];bp[x]=bp[mx];bp[mx]=zp
|
| 56 |
+
bits=np.uint32(0)
|
| 57 |
+
for q in range(S):
|
| 58 |
+
rt[d,sl,q]=bt[q]
|
| 59 |
+
if bt[q]!=SENT and bp[q]:bits|=np.uint32(1)<<np.uint32(q)
|
| 60 |
+
sb[d,sl]=bits
|
| 61 |
+
return br,rt,sb
|
| 62 |
+
|
| 63 |
+
def work(sid):
|
| 64 |
+
set_num_threads(1); t=time.time(); idf,vocab=load_vocab(); ct=np.load(G/'center_terms.npy',mmap_mode='r'); cvv=np.load(G/'center_values.npy',mmap_mode='r'); oldbr=np.memmap(OLD/'branches.u16',np.uint16,'r',shape=(N,F)); rtg=np.memmap(NEW/'res_terms.u16',np.uint16,'r+',shape=(N,F,S)); sbg=np.memmap(NEW/'signbits.u32',np.uint32,'r+',shape=(N,F))
|
| 65 |
+
texts=[]
|
| 66 |
+
with gzip.open(shard_path(sid),'rt',encoding='utf-8') as f:
|
| 67 |
+
for line in f:
|
| 68 |
+
o=json.loads(line);texts.append(((o.get('title') or '')+' '+(o.get('text') or '')).strip())
|
| 69 |
+
cv=CountVectorizer(vocabulary=vocab,lowercase=True,token_pattern=r'(?u)\b\w\w+\b',dtype=np.int32);X=cv.transform(texts).tocsr().astype(np.float32);X.data*=idf[X.indices];normalize(X,norm='l2',axis=1,copy=False);X.sort_indices(); br,rt,sb=kernel(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),ct,cvv)
|
| 70 |
+
n=len(texts);off=sid*250_000;sl=slice(off,off+n);mism=int(np.sum(br!=np.asarray(oldbr[sl])));assert mism==0,(sid,mism);rtg[sl]=rt;sbg[sl]=sb;rtg.flush();sbg.flush();sec=time.time()-t;json.dump({'offset':off,'n':n,'nnz':int(X.nnz),'seconds':sec,'branch_mismatches':mism},open(NEW/f'shard_{sid:04d}.json','w'));return sid,n,sec
|
| 71 |
+
if __name__=='__main__':
|
| 72 |
+
if not (NEW/'res_terms.u16').exists():a=np.memmap(NEW/'res_terms.u16',np.uint16,'w+',shape=(N,F,S));a[:]=SENT;a.flush();del a
|
| 73 |
+
if not (NEW/'signbits.u32').exists():a=np.memmap(NEW/'signbits.u32',np.uint32,'w+',shape=(N,F));a[:]=0;a.flush();del a
|
| 74 |
+
done={int(p.stem.split('_')[1]) for p in NEW.glob('shard_*.json')};missing=[i for i in range(36) if i not in done];print('missing',missing,flush=True);t=time.time()
|
| 75 |
+
with ProcessPoolExecutor(max_workers=1,mp_context=mp.get_context('spawn')) as ex:
|
| 76 |
+
fs=[ex.submit(work,i) for i in missing]
|
| 77 |
+
for k,fu in enumerate(as_completed(fs),1):sid,n,sec=fu.result();print(f'[{k:02d}/{len(missing):02d}] shard {sid:04d} n={n:,} sec={sec:.1f}',flush=True)
|
| 78 |
+
print('S32 ENCODE DONE',time.time()-t,flush=True)
|
experiments/msmarco_scale/msmarco_encode_s32_1w5t.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import gzip,json,pickle,time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from concurrent.futures import ProcessPoolExecutor,as_completed
|
| 5 |
+
import multiprocessing as mp
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 8 |
+
from sklearn.preprocessing import normalize
|
| 9 |
+
from numba import njit,prange,set_num_threads
|
| 10 |
+
ROOT=Path('/mnt/data'); W=ROOT/'msmarco_scale_work'; G=W/'geometry_uniform1m_s32'; OLD=W/'full_index'; NEW=W/'full_index_uniform1m_s32'; NEW.mkdir(exist_ok=True)
|
| 11 |
+
N=8_841_823; M=50_000; F=4; S=32; SENT=np.uint16(65535)
|
| 12 |
+
|
| 13 |
+
def shard_path(i):
|
| 14 |
+
hits=list(ROOT.glob(f'corpus_{i:04d}.jsonl*.gz')); assert len(hits)==1; return hits[0]
|
| 15 |
+
def load_vocab():
|
| 16 |
+
with gzip.open(W/'final_vocab_50k.pkl.gz','rb') as g:z=pickle.load(g)
|
| 17 |
+
terms=z['terms'].tolist(); idf=np.asarray(z['idf'],np.float32); return idf,{t:i for i,t in enumerate(terms)}
|
| 18 |
+
@njit(cache=False)
|
| 19 |
+
def lookup(ct,cv,t):
|
| 20 |
+
lo=0; hi=ct.size
|
| 21 |
+
while lo<hi:
|
| 22 |
+
mid=(lo+hi)//2; x=ct[mid]
|
| 23 |
+
if x==65535 or x>=t: hi=mid
|
| 24 |
+
else: lo=mid+1
|
| 25 |
+
if lo<ct.size and ct[lo]==t:return cv[lo]
|
| 26 |
+
return 0.0
|
| 27 |
+
@njit(parallel=True,cache=False)
|
| 28 |
+
def kernel(indptr,indices,data,ct,cv):
|
| 29 |
+
n=indptr.size-1; br=np.full((n,F),SENT,np.uint16); rt=np.full((n,F,S),SENT,np.uint16); sb=np.zeros((n,F),np.uint32)
|
| 30 |
+
for d in prange(n):
|
| 31 |
+
a=indptr[d]; b=indptr[d+1]; tv=np.zeros(F,np.float32); tt=np.full(F,SENT,np.uint16)
|
| 32 |
+
for p in range(a,b):
|
| 33 |
+
v=data[p]; t=np.uint16(indices[p]); pos=F
|
| 34 |
+
for r in range(F):
|
| 35 |
+
if v>tv[r]:pos=r;break
|
| 36 |
+
if pos<F:
|
| 37 |
+
for r in range(F-1,pos,-1):tv[r]=tv[r-1];tt[r]=tt[r-1]
|
| 38 |
+
tv[pos]=v;tt[pos]=t
|
| 39 |
+
den=0.0
|
| 40 |
+
for s in range(F):den+=tv[s]
|
| 41 |
+
if den<=0:continue
|
| 42 |
+
for s in range(F):br[d,s]=tt[s]
|
| 43 |
+
for sl in range(F):
|
| 44 |
+
j=int(tt[sl]); best=np.zeros(S,np.float32); bt=np.full(S,SENT,np.uint16); bp=np.zeros(S,np.uint8)
|
| 45 |
+
for p in range(a,b):
|
| 46 |
+
t=np.uint16(indices[p]); rr=data[p]-lookup(ct[j],cv[j],t); ar=abs(rr); mi=0; mv=best[0]
|
| 47 |
+
for q in range(1,S):
|
| 48 |
+
if best[q]<mv:mi=q;mv=best[q]
|
| 49 |
+
if ar>mv:best[mi]=ar;bt[mi]=t;bp[mi]=1 if rr>=0 else 0
|
| 50 |
+
for x in range(S):
|
| 51 |
+
mx=x
|
| 52 |
+
for y in range(x+1,S):
|
| 53 |
+
if best[y]>best[mx]:mx=y
|
| 54 |
+
if mx!=x:
|
| 55 |
+
zz=best[x];best[x]=best[mx];best[mx]=zz; zt=bt[x];bt[x]=bt[mx];bt[mx]=zt; zp=bp[x];bp[x]=bp[mx];bp[mx]=zp
|
| 56 |
+
bits=np.uint32(0)
|
| 57 |
+
for q in range(S):
|
| 58 |
+
rt[d,sl,q]=bt[q]
|
| 59 |
+
if bt[q]!=SENT and bp[q]:bits|=np.uint32(1)<<np.uint32(q)
|
| 60 |
+
sb[d,sl]=bits
|
| 61 |
+
return br,rt,sb
|
| 62 |
+
|
| 63 |
+
def work(sid):
|
| 64 |
+
set_num_threads(5); t=time.time(); idf,vocab=load_vocab(); ct=np.load(G/'center_terms.npy',mmap_mode='r'); cvv=np.load(G/'center_values.npy',mmap_mode='r'); oldbr=np.memmap(OLD/'branches.u16',np.uint16,'r',shape=(N,F)); rtg=np.memmap(NEW/'res_terms.u16',np.uint16,'r+',shape=(N,F,S)); sbg=np.memmap(NEW/'signbits.u32',np.uint32,'r+',shape=(N,F))
|
| 65 |
+
texts=[]
|
| 66 |
+
with gzip.open(shard_path(sid),'rt',encoding='utf-8') as f:
|
| 67 |
+
for line in f:
|
| 68 |
+
o=json.loads(line);texts.append(((o.get('title') or '')+' '+(o.get('text') or '')).strip())
|
| 69 |
+
cv=CountVectorizer(vocabulary=vocab,lowercase=True,token_pattern=r'(?u)\b\w\w+\b',dtype=np.int32);X=cv.transform(texts).tocsr().astype(np.float32);X.data*=idf[X.indices];normalize(X,norm='l2',axis=1,copy=False);X.sort_indices(); br,rt,sb=kernel(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),ct,cvv)
|
| 70 |
+
n=len(texts);off=sid*250_000;sl=slice(off,off+n);mism=int(np.sum(br!=np.asarray(oldbr[sl])));assert mism==0,(sid,mism);rtg[sl]=rt;sbg[sl]=sb;rtg.flush();sbg.flush();sec=time.time()-t;json.dump({'offset':off,'n':n,'nnz':int(X.nnz),'seconds':sec,'branch_mismatches':mism},open(NEW/f'shard_{sid:04d}.json','w'));return sid,n,sec
|
| 71 |
+
if __name__=='__main__':
|
| 72 |
+
if not (NEW/'res_terms.u16').exists():a=np.memmap(NEW/'res_terms.u16',np.uint16,'w+',shape=(N,F,S));a[:]=SENT;a.flush();del a
|
| 73 |
+
if not (NEW/'signbits.u32').exists():a=np.memmap(NEW/'signbits.u32',np.uint32,'w+',shape=(N,F));a[:]=0;a.flush();del a
|
| 74 |
+
done={int(p.stem.split('_')[1]) for p in NEW.glob('shard_*.json')};missing=[i for i in range(36) if i not in done];print('missing',missing,flush=True);t=time.time()
|
| 75 |
+
with ProcessPoolExecutor(max_workers=1,mp_context=mp.get_context('spawn')) as ex:
|
| 76 |
+
fs=[ex.submit(work,i) for i in missing]
|
| 77 |
+
for k,fu in enumerate(as_completed(fs),1):sid,n,sec=fu.result();print(f'[{k:02d}/{len(missing):02d}] shard {sid:04d} n={n:,} sec={sec:.1f}',flush=True)
|
| 78 |
+
print('S32 ENCODE DONE',time.time()-t,flush=True)
|
experiments/msmarco_scale/msmarco_encode_s32_2w.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import gzip,json,pickle,time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from concurrent.futures import ProcessPoolExecutor,as_completed
|
| 5 |
+
import multiprocessing as mp
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 8 |
+
from sklearn.preprocessing import normalize
|
| 9 |
+
from numba import njit,prange,set_num_threads
|
| 10 |
+
ROOT=Path('/mnt/data'); W=ROOT/'msmarco_scale_work'; G=W/'geometry_uniform1m_s32'; OLD=W/'full_index'; NEW=W/'full_index_uniform1m_s32'; NEW.mkdir(exist_ok=True)
|
| 11 |
+
N=8_841_823; M=50_000; F=4; S=32; SENT=np.uint16(65535)
|
| 12 |
+
|
| 13 |
+
def shard_path(i):
|
| 14 |
+
hits=list(ROOT.glob(f'corpus_{i:04d}.jsonl*.gz')); assert len(hits)==1; return hits[0]
|
| 15 |
+
def load_vocab():
|
| 16 |
+
with gzip.open(W/'final_vocab_50k.pkl.gz','rb') as g:z=pickle.load(g)
|
| 17 |
+
terms=z['terms'].tolist(); idf=np.asarray(z['idf'],np.float32); return idf,{t:i for i,t in enumerate(terms)}
|
| 18 |
+
@njit(cache=False)
|
| 19 |
+
def lookup(ct,cv,t):
|
| 20 |
+
lo=0; hi=ct.size
|
| 21 |
+
while lo<hi:
|
| 22 |
+
mid=(lo+hi)//2; x=ct[mid]
|
| 23 |
+
if x==65535 or x>=t: hi=mid
|
| 24 |
+
else: lo=mid+1
|
| 25 |
+
if lo<ct.size and ct[lo]==t:return cv[lo]
|
| 26 |
+
return 0.0
|
| 27 |
+
@njit(parallel=True,cache=False)
|
| 28 |
+
def kernel(indptr,indices,data,ct,cv):
|
| 29 |
+
n=indptr.size-1; br=np.full((n,F),SENT,np.uint16); rt=np.full((n,F,S),SENT,np.uint16); sb=np.zeros((n,F),np.uint32)
|
| 30 |
+
for d in prange(n):
|
| 31 |
+
a=indptr[d]; b=indptr[d+1]; tv=np.zeros(F,np.float32); tt=np.full(F,SENT,np.uint16)
|
| 32 |
+
for p in range(a,b):
|
| 33 |
+
v=data[p]; t=np.uint16(indices[p]); pos=F
|
| 34 |
+
for r in range(F):
|
| 35 |
+
if v>tv[r]:pos=r;break
|
| 36 |
+
if pos<F:
|
| 37 |
+
for r in range(F-1,pos,-1):tv[r]=tv[r-1];tt[r]=tt[r-1]
|
| 38 |
+
tv[pos]=v;tt[pos]=t
|
| 39 |
+
den=0.0
|
| 40 |
+
for s in range(F):den+=tv[s]
|
| 41 |
+
if den<=0:continue
|
| 42 |
+
for s in range(F):br[d,s]=tt[s]
|
| 43 |
+
for sl in range(F):
|
| 44 |
+
j=int(tt[sl]); best=np.zeros(S,np.float32); bt=np.full(S,SENT,np.uint16); bp=np.zeros(S,np.uint8)
|
| 45 |
+
for p in range(a,b):
|
| 46 |
+
t=np.uint16(indices[p]); rr=data[p]-lookup(ct[j],cv[j],t); ar=abs(rr); mi=0; mv=best[0]
|
| 47 |
+
for q in range(1,S):
|
| 48 |
+
if best[q]<mv:mi=q;mv=best[q]
|
| 49 |
+
if ar>mv:best[mi]=ar;bt[mi]=t;bp[mi]=1 if rr>=0 else 0
|
| 50 |
+
for x in range(S):
|
| 51 |
+
mx=x
|
| 52 |
+
for y in range(x+1,S):
|
| 53 |
+
if best[y]>best[mx]:mx=y
|
| 54 |
+
if mx!=x:
|
| 55 |
+
zz=best[x];best[x]=best[mx];best[mx]=zz; zt=bt[x];bt[x]=bt[mx];bt[mx]=zt; zp=bp[x];bp[x]=bp[mx];bp[mx]=zp
|
| 56 |
+
bits=np.uint32(0)
|
| 57 |
+
for q in range(S):
|
| 58 |
+
rt[d,sl,q]=bt[q]
|
| 59 |
+
if bt[q]!=SENT and bp[q]:bits|=np.uint32(1)<<np.uint32(q)
|
| 60 |
+
sb[d,sl]=bits
|
| 61 |
+
return br,rt,sb
|
| 62 |
+
|
| 63 |
+
def work(sid):
|
| 64 |
+
set_num_threads(1); t=time.time(); idf,vocab=load_vocab(); ct=np.load(G/'center_terms.npy',mmap_mode='r'); cvv=np.load(G/'center_values.npy',mmap_mode='r'); oldbr=np.memmap(OLD/'branches.u16',np.uint16,'r',shape=(N,F)); rtg=np.memmap(NEW/'res_terms.u16',np.uint16,'r+',shape=(N,F,S)); sbg=np.memmap(NEW/'signbits.u32',np.uint32,'r+',shape=(N,F))
|
| 65 |
+
texts=[]
|
| 66 |
+
with gzip.open(shard_path(sid),'rt',encoding='utf-8') as f:
|
| 67 |
+
for line in f:
|
| 68 |
+
o=json.loads(line);texts.append(((o.get('title') or '')+' '+(o.get('text') or '')).strip())
|
| 69 |
+
cv=CountVectorizer(vocabulary=vocab,lowercase=True,token_pattern=r'(?u)\b\w\w+\b',dtype=np.int32);X=cv.transform(texts).tocsr().astype(np.float32);X.data*=idf[X.indices];normalize(X,norm='l2',axis=1,copy=False);X.sort_indices(); br,rt,sb=kernel(X.indptr.astype(np.int64),X.indices.astype(np.int32),X.data.astype(np.float32),ct,cvv)
|
| 70 |
+
n=len(texts);off=sid*250_000;sl=slice(off,off+n);mism=int(np.sum(br!=np.asarray(oldbr[sl])));assert mism==0,(sid,mism);rtg[sl]=rt;sbg[sl]=sb;rtg.flush();sbg.flush();sec=time.time()-t;json.dump({'offset':off,'n':n,'nnz':int(X.nnz),'seconds':sec,'branch_mismatches':mism},open(NEW/f'shard_{sid:04d}.json','w'));return sid,n,sec
|
| 71 |
+
if __name__=='__main__':
|
| 72 |
+
if not (NEW/'res_terms.u16').exists():a=np.memmap(NEW/'res_terms.u16',np.uint16,'w+',shape=(N,F,S));a[:]=SENT;a.flush();del a
|
| 73 |
+
if not (NEW/'signbits.u32').exists():a=np.memmap(NEW/'signbits.u32',np.uint32,'w+',shape=(N,F));a[:]=0;a.flush();del a
|
| 74 |
+
done={int(p.stem.split('_')[1]) for p in NEW.glob('shard_*.json')};missing=[i for i in range(36) if i not in done];print('missing',missing,flush=True);t=time.time()
|
| 75 |
+
with ProcessPoolExecutor(max_workers=2,mp_context=mp.get_context('spawn')) as ex:
|
| 76 |
+
fs=[ex.submit(work,i) for i in missing]
|
| 77 |
+
for k,fu in enumerate(as_completed(fs),1):sid,n,sec=fu.result();print(f'[{k:02d}/{len(missing):02d}] shard {sid:04d} n={n:,} sec={sec:.1f}',flush=True)
|
| 78 |
+
print('S32 ENCODE DONE',time.time()-t,flush=True)
|