Datasets:
Improve: Rename to USearchWiki + new pipelines + pyproject
Browse filesRename WikiVerse -> USearchWiki throughout (GitHub + HuggingFace at
unum-cloud/USearchWiki, Nebius bucket at s3://usearch-wiki). The
Python module wikiverse.py is kept under its old name so consumer
imports keep working.
Adds three new pipelines:
- embed_sections.py: section-pooled ColBERT via pylate, with
late-chunking margins so attention flows across section boundaries
- build_index.py: USearch HNSW build from per-shard f16bin via
memmap, f16 quantization matching the storage dtype
- eval_recall.py: self-recall@k against the precomputed ground
truth, with an ef_search sweep
Plus:
- late_chunking.py with section-aware windowing primitives (greedy
pack into core <= context_limit - 2*margin, fragments for
oversized sections, weighted-mean recombination)
- wikiverse.py grows resolve_lfs_pointer / discover_collection /
CollectionShard, dedup'ing logic that used to live in ground_truth
- embed.py renamed to embed_articles.py (parallel to embed_sections)
- pyproject.toml with ruff (E F I B UP C4) / mypy / pytest config
and dependency extras (dense, ground, colbert, index, dev)
- tests/test_late_chunking.py covers the windowing invariants
without needing a real model
- .gitignore +4 -0
- README.md +82 -34
- build_index.py +230 -0
- embed.py → embed_articles.py +7 -3
- embed_sections.py +480 -0
- eval_recall.py +220 -0
- ground_truth.py +11 -82
- late_chunking.py +334 -0
- pyproject.toml +39 -0
- tests/test_ground_truth.py +3 -7
- tests/test_late_chunking.py +283 -0
- wikiverse.py +95 -2
|
@@ -211,3 +211,7 @@ data/
|
|
| 211 |
state/
|
| 212 |
benchmarks/results/
|
| 213 |
logs/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
state/
|
| 212 |
benchmarks/results/
|
| 213 |
logs/
|
| 214 |
+
|
| 215 |
+
# Local-only orchestration shell scripts (kept under /home/ubuntu/wikiverse-data/scripts/
|
| 216 |
+
# in this workstation, not part of the published repo).
|
| 217 |
+
*.sh
|
|
@@ -2,14 +2,14 @@
|
|
| 2 |
license: apache-2.0
|
| 3 |
---
|
| 4 |
|
| 5 |
-
#
|
| 6 |
|
| 7 |
Multi-model embedding dataset built on [HuggingFace FineWiki](https://huggingface.co/datasets/HuggingFaceFW/finewiki), designed for approximate nearest neighbor (ANN) search benchmarking with [USearch](https://github.com/unum-cloud/usearch) and other vector search engines.
|
| 8 |
|
| 9 |
-
The same Wikipedia corpus — chunked, cleaned, and enriched with graph metadata — is embedded by multiple models spanning dense encoders, decoder-based LLMs, and late-interaction
|
| 10 |
Each model's embeddings ship with precomputed ground-truth k-nearest neighbors, enabling reproducible recall and throughput benchmarks without re-running expensive exact search.
|
| 11 |
|
| 12 |
-
## Why
|
| 13 |
|
| 14 |
Existing ANN benchmarks suffer from three gaps:
|
| 15 |
|
|
@@ -21,7 +21,7 @@ Existing ANN benchmarks suffer from three gaps:
|
|
| 21 |
3. __No decoder embeddings.__
|
| 22 |
State-of-the-art embedding models (GTE-Qwen, Llama-Embed-Nemotron, Qwen3-Embedding) are decoder-based LLMs, yet no ANN benchmark uses their outputs.
|
| 23 |
|
| 24 |
-
|
| 25 |
|
| 26 |
## Source Corpus
|
| 27 |
|
|
@@ -53,6 +53,41 @@ Long-context models are prioritized and receive the whole document in the origin
|
|
| 53 |
Parquet weight includes both `text` and `wikitext` columns; pure text is roughly half.
|
| 54 |
Average bytes/article drops at wider scope because smaller wikis are dominated by stubs.
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
## Embedding Models
|
| 57 |
|
| 58 |
Each model embeds the same article corpus independently.
|
|
@@ -80,16 +115,21 @@ FP8 quantization can improve throughput ~1.5× with negligible quality loss.
|
|
| 80 |
Token counts vary by tokenizer — CJK text produces ~1 token per 2-3 bytes, Latin/Cyrillic ~1 per 4-5 bytes.
|
| 81 |
Average article length across all languages is ~400 tokens, but this is dragged down by millions of stubs in smaller wikis; English articles average ~2,700 tokens.
|
| 82 |
|
| 83 |
-
| Model
|
| 84 |
-
| :--------------------- | ---------: | -----------: | -----: | ------: | ------: | :----------------------------- |
|
| 85 |
-
| Qwen3-Embedding-0.6B
|
| 86 |
-
| GTE-ModernColBERT-v1
|
| 87 |
-
|
|
| 88 |
-
|
|
| 89 |
-
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
> Single H100 80 GB, full dataset — 61.6M articles, all 325 languages.
|
| 92 |
|
|
|
|
|
|
|
|
|
|
| 93 |
## Metadata Enrichment
|
| 94 |
|
| 95 |
### Compute Estimates
|
|
@@ -105,12 +145,17 @@ Binary format: `u32` rows count, `u32` columns count, then `rows × cols` little
|
|
| 105 |
`.body.f16bin` is the article-body embedding; `.title.f16bin` is the title-only embedding (short-context, useful for title-vs-body retrieval studies).
|
| 106 |
|
| 107 |
```
|
| 108 |
-
unum-cloud/
|
| 109 |
├── README.md
|
| 110 |
├── LICENSE
|
| 111 |
├── .gitattributes
|
| 112 |
-
├── wikiverse.py # consumer module: load_lang, read_bin, ...
|
| 113 |
-
├──
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
│
|
| 115 |
├── qwen3-embedding-0.6b/ # 1024-dim, decoder, float16
|
| 116 |
│ ├── enwiki/
|
|
@@ -138,13 +183,15 @@ unum-cloud/WikiVerse/
|
|
| 138 |
|
| 139 |
## Downloading
|
| 140 |
|
| 141 |
-
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
| Mirror
|
| 144 |
-
| :--------------
|
| 145 |
-
| HuggingFace Hub
|
| 146 |
-
| GitHub
|
| 147 |
-
| Nebius S3
|
| 148 |
|
| 149 |
`.f16bin` files are tracked via [Git LFS](https://git-lfs.com); on GitHub, the LFS server is rerouted to HuggingFace, so GitHub clones receive only ~200-byte pointer files.
|
| 150 |
|
|
@@ -153,13 +200,13 @@ WikiVerse lives on three coordinated mirrors, all sharing the same single-branch
|
|
| 153 |
The default and the simplest path — full code, full data, single command:
|
| 154 |
|
| 155 |
```sh
|
| 156 |
-
git clone https://huggingface.co/datasets/
|
| 157 |
```
|
| 158 |
|
| 159 |
To skip the ~600 GB of binaries and get only code + pointers:
|
| 160 |
|
| 161 |
```sh
|
| 162 |
-
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/
|
| 163 |
```
|
| 164 |
|
| 165 |
### From GitHub
|
|
@@ -167,9 +214,9 @@ GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/ashvardanian/Wik
|
|
| 167 |
The GitHub repo holds only code and LFS pointers; the actual binaries live on HuggingFace. After cloning, point Git LFS at HuggingFace and pull:
|
| 168 |
|
| 169 |
```sh
|
| 170 |
-
git clone https://github.com/
|
| 171 |
-
cd
|
| 172 |
-
git config lfs.url https://huggingface.co/datasets/
|
| 173 |
git lfs pull
|
| 174 |
```
|
| 175 |
|
|
@@ -178,7 +225,7 @@ git lfs pull
|
|
| 178 |
The fastest path for bulk downloads — pulls byte-identical LFS objects directly from object storage, then materializes the `.f16bin` files into the working tree:
|
| 179 |
|
| 180 |
```sh
|
| 181 |
-
aws s3 sync s3://
|
| 182 |
--endpoint-url https://storage.us-central1.nebius.cloud
|
| 183 |
git lfs checkout
|
| 184 |
```
|
|
@@ -194,7 +241,7 @@ matrix = read_bin("qwen3-embedding-0.6b/enwiki/000_00000.body.f16bin", dtype="f1
|
|
| 194 |
Or pull just one model's embeddings for a single language:
|
| 195 |
|
| 196 |
```sh
|
| 197 |
-
hf download
|
| 198 |
--repo-type dataset \
|
| 199 |
--include "qwen3-embedding-0.6b/enwiki/*"
|
| 200 |
```
|
|
@@ -208,11 +255,12 @@ The embedding pipeline is designed for multi-day runs on GPU servers with checkp
|
|
| 208 |
python corpus.py --lang en --output corpus/
|
| 209 |
|
| 210 |
# 2. Embed with each model (resume-safe — rerun after interruptions)
|
| 211 |
-
python
|
| 212 |
-
python
|
| 213 |
-
python
|
| 214 |
-
python
|
| 215 |
-
|
|
|
|
| 216 |
|
| 217 |
# 3. Extract graph metadata
|
| 218 |
python graph.py --lang en --output graph/
|
|
@@ -222,7 +270,7 @@ python ground_truth.py --embeddings embeddings/qwen3-0.6b/ --k 100 --queries 100
|
|
| 222 |
python ground_truth.py --embeddings embeddings/e5-mistral-7b/ --k 100 --queries 10000
|
| 223 |
|
| 224 |
# 5. Upload to HuggingFace
|
| 225 |
-
python upload.py --repo unum-cloud/
|
| 226 |
```
|
| 227 |
|
| 228 |
Each step is idempotent.
|
|
@@ -233,7 +281,7 @@ Adding a new embedding model requires only step 2 + step 4 — the corpus and gr
|
|
| 233 |
|
| 234 |
| Location | Storage/mo (1 TB) | Egress/GB | Notes |
|
| 235 |
| ---------------------------------------------------------------------------------- | ----------------- | --------- | ---------------------------------------------------------------- |
|
| 236 |
-
| [HuggingFace Hub](https://huggingface.co/unum-cloud/
|
| 237 |
| [AWS S3](https://aws.amazon.com/s3/pricing/) Standard | $23.00 | $0.09 | S3-compatible mirror. Egress adds up fast for popular datasets |
|
| 238 |
| [Nebius Object Storage](https://docs.nebius.com/object-storage/resources/pricing/) | $15.05 | $0.015 | S3-compatible. ~35% cheaper storage, ~6× cheaper egress than AWS |
|
| 239 |
|
|
|
|
| 2 |
license: apache-2.0
|
| 3 |
---
|
| 4 |
|
| 5 |
+
# USearchWiki
|
| 6 |
|
| 7 |
Multi-model embedding dataset built on [HuggingFace FineWiki](https://huggingface.co/datasets/HuggingFaceFW/finewiki), designed for approximate nearest neighbor (ANN) search benchmarking with [USearch](https://github.com/unum-cloud/usearch) and other vector search engines.
|
| 8 |
|
| 9 |
+
The same Wikipedia corpus — chunked, cleaned, and enriched with graph metadata — is embedded by multiple models spanning dense BERT-like encoders, GPT-style decoder-based LLMs, and late-interaction ColBERT-style architectures.
|
| 10 |
Each model's embeddings ship with precomputed ground-truth k-nearest neighbors, enabling reproducible recall and throughput benchmarks without re-running expensive exact search.
|
| 11 |
|
| 12 |
+
## Why USearchWiki?
|
| 13 |
|
| 14 |
Existing ANN benchmarks suffer from three gaps:
|
| 15 |
|
|
|
|
| 21 |
3. __No decoder embeddings.__
|
| 22 |
State-of-the-art embedding models (GTE-Qwen, Llama-Embed-Nemotron, Qwen3-Embedding) are decoder-based LLMs, yet no ANN benchmark uses their outputs.
|
| 23 |
|
| 24 |
+
USearchWiki fixes all three: one corpus, multiple models, modern architectures, with graph-structured metadata for filtered search.
|
| 25 |
|
| 26 |
## Source Corpus
|
| 27 |
|
|
|
|
| 53 |
Parquet weight includes both `text` and `wikitext` columns; pure text is roughly half.
|
| 54 |
Average bytes/article drops at wider scope because smaller wikis are dominated by stubs.
|
| 55 |
|
| 56 |
+
### Corpus Structure
|
| 57 |
+
|
| 58 |
+
Measured by scanning every parquet shard (rendered Markdown `text` + raw `wikitext` columns):
|
| 59 |
+
|
| 60 |
+
| Quantity | Total | Per article |
|
| 61 |
+
| :---------------------------------- | -----------: | ----------: |
|
| 62 |
+
| Articles | 61.55M | — |
|
| 63 |
+
| Rendered text bytes (`text` column) | 195.2 GB | 3.2 KB |
|
| 64 |
+
| Wikitext bytes (`wikitext` column) | 337.1 GB | 5.5 KB |
|
| 65 |
+
| Markdown paragraphs (blank-line-separated blocks) | 254.2M | 4.13 |
|
| 66 |
+
| Section headings (`#`/`##`/`###`) | 206.3M | 3.35 |
|
| 67 |
+
|
| 68 |
+
35% of articles have a single paragraph (stubs), 65% have ≤ 3, only 10% have 8+.
|
| 69 |
+
Paragraph length distribution: 12% < 50 bytes (mostly headings or one-liners), 38% in 200–800 bytes (the prose sweet spot), 4% > 3.2 KB (long lists or tables rendered as one block).
|
| 70 |
+
|
| 71 |
+
Annotation density extracted from raw `wikitext` (counts across the full corpus):
|
| 72 |
+
|
| 73 |
+
| Annotation kind | Total | Articles touched |
|
| 74 |
+
| :-------------- | ----: | ---------------: |
|
| 75 |
+
| Plain `[[wikilinks]]` | 1.42 B | 99.4% |
|
| 76 |
+
| Templates `{{...}}` | 0.998 B | 98.6% |
|
| 77 |
+
| Piped links `[[T\|d]]` | 0.648 B | 89.3% |
|
| 78 |
+
| Citations `<ref>...` | 0.400 B | 71.0% |
|
| 79 |
+
| External URLs `[https://...]` | 84M | 41.8% |
|
| 80 |
+
| Categories `[[Category:...]]` | 55M | 16.3% |
|
| 81 |
+
| Tables `{| ... |}` | 19M | 14.6% |
|
| 82 |
+
| Files / images `[[File:...]]` | 14M | 7.2% |
|
| 83 |
+
| **Section anchors `[[Article#Section]]`** | **11.5M** | **6.4%** |
|
| 84 |
+
| Math `<math>...` | 6.4M | 0.5% |
|
| 85 |
+
| Self anchors `[[#Section]]` | 2.6M | 0.7% |
|
| 86 |
+
| Galleries `<gallery>` | 2.5M | 3.2% |
|
| 87 |
+
| Inline interwiki `[[lang:...]]` | 0.83M | 1.1% |
|
| 88 |
+
|
| 89 |
+
Section anchors deserve attention: they form a 11.5M-edge **paragraph-level link graph** already curated by editors — a built-in supervision signal for sub-article retrieval evaluation.
|
| 90 |
+
|
| 91 |
## Embedding Models
|
| 92 |
|
| 93 |
Each model embeds the same article corpus independently.
|
|
|
|
| 115 |
Token counts vary by tokenizer — CJK text produces ~1 token per 2-3 bytes, Latin/Cyrillic ~1 per 4-5 bytes.
|
| 116 |
Average article length across all languages is ~400 tokens, but this is dragged down by millions of stubs in smaller wikis; English articles average ~2,700 tokens.
|
| 117 |
|
| 118 |
+
| Model | Throughput | Total tokens | Time | Vectors | Storage | Notes |
|
| 119 |
+
| :------------------------------------- | ---------: | -----------: | -----: | -------: | ------: | :------------------------------------------------- |
|
| 120 |
+
| Qwen3-Embedding-0.6B | 500 doc/s | 24 B | 1.4 d | 61.6 M | 126 GB | Full articles, one vector per article |
|
| 121 |
+
| GTE-ModernColBERT-v1 (token-level) | 800 doc/s | 24 B | 0.9 d | 24.3 B | 6.2 TB | ~400 token vectors per article |
|
| 122 |
+
| GTE-ModernColBERT-v1 (section-pooled) | 800 doc/s | 24 B | 0.9 d | 206.3 M | 53 GB | Mean-pool tokens within each section, ~3.4 per art |
|
| 123 |
+
| GTE-ModernColBERT-v1 (paragraph-pooled)| 800 doc/s | 24 B | 0.9 d | 254.2 M | 65 GB | Mean-pool tokens within each paragraph |
|
| 124 |
+
| arctic-embed-l-v2.0 | 800 doc/s | 28 B | 0.9 d | 61.6 M | 126 GB | Truncated at 8K tokens |
|
| 125 |
+
| nomic-embed-text-v1.5 | 1200 doc/s | 21 B | 0.6 d | 61.6 M | 95 GB | Truncated at 8K tokens |
|
| 126 |
+
| e5-mistral-7b-instruct | 50 doc/s | 21 B | 14.3 d | 61.6 M | 505 GB | Truncated at 4K tokens |
|
| 127 |
|
| 128 |
> Single H100 80 GB, full dataset — 61.6M articles, all 325 languages.
|
| 129 |
|
| 130 |
+
The two ColBERT-pooled rows trade fine-grained MaxSim resolution (lost) for an indexable single-machine footprint (gained).
|
| 131 |
+
Section-pooled fits in 53 GB at FP16 — small enough for a single 80 GB GPU and trivially served by [USearch](https://github.com/unum-cloud/usearch); paragraph-pooled gives ~25% more granularity for the same throughput cost since the bottleneck is total tokens encoded.
|
| 132 |
+
|
| 133 |
## Metadata Enrichment
|
| 134 |
|
| 135 |
### Compute Estimates
|
|
|
|
| 145 |
`.body.f16bin` is the article-body embedding; `.title.f16bin` is the title-only embedding (short-context, useful for title-vs-body retrieval studies).
|
| 146 |
|
| 147 |
```
|
| 148 |
+
unum-cloud/USearchWiki/
|
| 149 |
├── README.md
|
| 150 |
├── LICENSE
|
| 151 |
├── .gitattributes
|
| 152 |
+
├── wikiverse.py # consumer module: load_lang, read_bin, discover_collection, ...
|
| 153 |
+
├── embed_articles.py # one dense vector per article, via TEI
|
| 154 |
+
├── embed_sections.py # late-chunking ColBERT: one vector per section
|
| 155 |
+
├── late_chunking.py # section-aware windowing primitives
|
| 156 |
+
├── ground_truth.py # exact global k-NN via tiled CuPy GEMMs
|
| 157 |
+
├── build_index.py # build a USearch HNSW index from per-shard f16bin
|
| 158 |
+
├── eval_recall.py # measure recall@k of an index against the ground truth
|
| 159 |
│
|
| 160 |
├── qwen3-embedding-0.6b/ # 1024-dim, decoder, float16
|
| 161 |
│ ├── enwiki/
|
|
|
|
| 183 |
|
| 184 |
## Downloading
|
| 185 |
|
| 186 |
+
USearchWiki uses an unusual distribution policy.
|
| 187 |
+
Single repository, no separation of code and data.
|
| 188 |
+
USearchWiki lives on three coordinated mirrors, all sharing the same single-branch Git history:
|
| 189 |
|
| 190 |
+
| Mirror | Holds | Best for |
|
| 191 |
+
| :-------------- | :----------------------------- | :------------------------------- |
|
| 192 |
+
| HuggingFace Hub | code + LFS bytes (canonical) | `git clone`, `hf` CLI, streaming |
|
| 193 |
+
| GitHub | code + LFS pointers (no bytes) | reading the code, contributing |
|
| 194 |
+
| Nebius S3 | flat byte mirror of LFS blobs | bulk downloads, batch jobs |
|
| 195 |
|
| 196 |
`.f16bin` files are tracked via [Git LFS](https://git-lfs.com); on GitHub, the LFS server is rerouted to HuggingFace, so GitHub clones receive only ~200-byte pointer files.
|
| 197 |
|
|
|
|
| 200 |
The default and the simplest path — full code, full data, single command:
|
| 201 |
|
| 202 |
```sh
|
| 203 |
+
git clone https://huggingface.co/datasets/unum-cloud/USearchWiki
|
| 204 |
```
|
| 205 |
|
| 206 |
To skip the ~600 GB of binaries and get only code + pointers:
|
| 207 |
|
| 208 |
```sh
|
| 209 |
+
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/unum-cloud/USearchWiki
|
| 210 |
```
|
| 211 |
|
| 212 |
### From GitHub
|
|
|
|
| 214 |
The GitHub repo holds only code and LFS pointers; the actual binaries live on HuggingFace. After cloning, point Git LFS at HuggingFace and pull:
|
| 215 |
|
| 216 |
```sh
|
| 217 |
+
git clone https://github.com/unum-cloud/USearchWiki
|
| 218 |
+
cd USearchWiki
|
| 219 |
+
git config lfs.url https://huggingface.co/datasets/unum-cloud/USearchWiki.git/info/lfs
|
| 220 |
git lfs pull
|
| 221 |
```
|
| 222 |
|
|
|
|
| 225 |
The fastest path for bulk downloads — pulls byte-identical LFS objects directly from object storage, then materializes the `.f16bin` files into the working tree:
|
| 226 |
|
| 227 |
```sh
|
| 228 |
+
aws s3 sync s3://usearch-wiki/lfs/ ./.git/lfs/objects/ \
|
| 229 |
--endpoint-url https://storage.us-central1.nebius.cloud
|
| 230 |
git lfs checkout
|
| 231 |
```
|
|
|
|
| 241 |
Or pull just one model's embeddings for a single language:
|
| 242 |
|
| 243 |
```sh
|
| 244 |
+
hf download unum-cloud/USearchWiki \
|
| 245 |
--repo-type dataset \
|
| 246 |
--include "qwen3-embedding-0.6b/enwiki/*"
|
| 247 |
```
|
|
|
|
| 255 |
python corpus.py --lang en --output corpus/
|
| 256 |
|
| 257 |
# 2. Embed with each model (resume-safe — rerun after interruptions)
|
| 258 |
+
python embed_articles.py --model qwen3-0.6b --input corpus/ --output embeddings/ --resume
|
| 259 |
+
python embed_articles.py --model e5-mistral-7b --input corpus/ --output embeddings/ --resume
|
| 260 |
+
python embed_articles.py --model arctic-embed-l-v2 --input corpus/ --output embeddings/ --resume
|
| 261 |
+
python embed_articles.py --model nomic-v1.5 --input corpus/ --output embeddings/ --resume
|
| 262 |
+
# Section-pooled ColBERT uses a different pipeline (late chunking)
|
| 263 |
+
python embed_sections.py --model gte-moderncolbert --input corpus/ --output embeddings/ --resume
|
| 264 |
|
| 265 |
# 3. Extract graph metadata
|
| 266 |
python graph.py --lang en --output graph/
|
|
|
|
| 270 |
python ground_truth.py --embeddings embeddings/e5-mistral-7b/ --k 100 --queries 10000
|
| 271 |
|
| 272 |
# 5. Upload to HuggingFace
|
| 273 |
+
python upload.py --repo unum-cloud/USearchWiki
|
| 274 |
```
|
| 275 |
|
| 276 |
Each step is idempotent.
|
|
|
|
| 281 |
|
| 282 |
| Location | Storage/mo (1 TB) | Egress/GB | Notes |
|
| 283 |
| ---------------------------------------------------------------------------------- | ----------------- | --------- | ---------------------------------------------------------------- |
|
| 284 |
+
| [HuggingFace Hub](https://huggingface.co/unum-cloud/USearchWiki) | Free | Free | Primary. Xet storage, unlimited public downloads |
|
| 285 |
| [AWS S3](https://aws.amazon.com/s3/pricing/) Standard | $23.00 | $0.09 | S3-compatible mirror. Egress adds up fast for popular datasets |
|
| 286 |
| [Nebius Object Storage](https://docs.nebius.com/object-storage/resources/pricing/) | $15.05 | $0.015 | S3-compatible. ~35% cheaper storage, ~6× cheaper egress than AWS |
|
| 287 |
|
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a USearch index from per-shard `.f16bin` files in canonical order.
|
| 2 |
+
|
| 3 |
+
For dense article-level collections (one vector per article, multi=False).
|
| 4 |
+
The ColBERT section-level case (multi=True, vectors keyed by article) will
|
| 5 |
+
be a separate addition once the section embeddings finish computing.
|
| 6 |
+
|
| 7 |
+
Memory-maps the LFS-resolved `.f16bin` blobs so the OS pages vectors in
|
| 8 |
+
lazily — keeps RSS bounded when running multiple builds in parallel.
|
| 9 |
+
|
| 10 |
+
Inspired by ashvardanian/RetriEval's USearch wrapper:
|
| 11 |
+
- reserve capacity up front
|
| 12 |
+
- parallel `add()` with a fixed thread count
|
| 13 |
+
- cosine metric, f16 quantization (matching storage dtype)
|
| 14 |
+
- HNSW hyperparameters connectivity / expansion_add
|
| 15 |
+
- ef_search is a *query-time* knob, not set here
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import os
|
| 22 |
+
import struct
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
REPO_ROOT = Path(__file__).resolve().parent
|
| 30 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 31 |
+
|
| 32 |
+
from wikiverse import ( # noqa: E402
|
| 33 |
+
CollectionShard,
|
| 34 |
+
discover_collection,
|
| 35 |
+
resolve_lfs_pointer,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def memmap_shard(shard: CollectionShard, dimensions: int) -> np.ndarray:
|
| 40 |
+
"""Memory-map a `.f16bin` shard skipping its 8-byte header.
|
| 41 |
+
|
| 42 |
+
Returns a read-only `(rows, dimensions)` float16 view. The OS pages in
|
| 43 |
+
only the bytes actually accessed during `index.add()`.
|
| 44 |
+
"""
|
| 45 |
+
blob = resolve_lfs_pointer(shard.path)
|
| 46 |
+
return np.memmap(
|
| 47 |
+
blob,
|
| 48 |
+
dtype=np.float16,
|
| 49 |
+
mode="r",
|
| 50 |
+
offset=8,
|
| 51 |
+
shape=(shard.row_count, dimensions),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def add_shards(
|
| 56 |
+
index,
|
| 57 |
+
shards: list[CollectionShard],
|
| 58 |
+
dimensions: int,
|
| 59 |
+
threads: int,
|
| 60 |
+
log_every: int,
|
| 61 |
+
) -> int:
|
| 62 |
+
"""Stream every shard's vectors into the index. Keys are sequential
|
| 63 |
+
global row IDs assigned in shard-walk order (== `shard.row_offset + i`).
|
| 64 |
+
"""
|
| 65 |
+
cumulative_rows = 0
|
| 66 |
+
started = time.monotonic()
|
| 67 |
+
bytes_added_since_log = 0
|
| 68 |
+
last_log_at = started
|
| 69 |
+
for shard_index, shard in enumerate(shards):
|
| 70 |
+
vectors = memmap_shard(shard, dimensions)
|
| 71 |
+
keys = np.arange(
|
| 72 |
+
shard.row_offset, shard.row_offset + shard.row_count, dtype=np.uint64
|
| 73 |
+
)
|
| 74 |
+
index.add(keys=keys, vectors=vectors, threads=threads)
|
| 75 |
+
cumulative_rows += shard.row_count
|
| 76 |
+
bytes_added_since_log += vectors.nbytes
|
| 77 |
+
if (shard_index + 1) % log_every == 0 or shard_index == len(shards) - 1:
|
| 78 |
+
now = time.monotonic()
|
| 79 |
+
elapsed = now - started
|
| 80 |
+
interval = now - last_log_at
|
| 81 |
+
rate = cumulative_rows / max(elapsed, 1e-3)
|
| 82 |
+
interval_mb = bytes_added_since_log / 1e6 / max(interval, 1e-3)
|
| 83 |
+
print(
|
| 84 |
+
f" shard {shard_index + 1}/{len(shards)} "
|
| 85 |
+
f"({shard.wikiname}/{shard.stem}): "
|
| 86 |
+
f"{cumulative_rows:,} vectors total, "
|
| 87 |
+
f"{rate:,.0f} vec/s avg, {interval_mb:,.0f} MB/s recent",
|
| 88 |
+
flush=True,
|
| 89 |
+
)
|
| 90 |
+
last_log_at = now
|
| 91 |
+
bytes_added_since_log = 0
|
| 92 |
+
return cumulative_rows
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def main() -> None:
|
| 96 |
+
parser = argparse.ArgumentParser()
|
| 97 |
+
parser.add_argument(
|
| 98 |
+
"--output",
|
| 99 |
+
default="/home/ubuntu/WikiVerse",
|
| 100 |
+
help="root directory holding {model-subdir}/{wiki}/*.f16bin",
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--model-subdir",
|
| 104 |
+
required=True,
|
| 105 |
+
help="e.g. qwen3-embedding-0.6b, nomic-embed-text-v1.5, snowflake-arctic-embed-l-v2.0",
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--output-suffix",
|
| 109 |
+
default="body",
|
| 110 |
+
choices=["body", "title"],
|
| 111 |
+
help="which embedding file flavor to index",
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--output-index",
|
| 115 |
+
type=Path,
|
| 116 |
+
default=None,
|
| 117 |
+
help="destination .usearch file (defaults to {output}/{model-subdir}/{suffix}.usearch)",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--threads",
|
| 121 |
+
type=int,
|
| 122 |
+
default=os.cpu_count() or 1,
|
| 123 |
+
help="parallel insertion threads (default: all logical cores)",
|
| 124 |
+
)
|
| 125 |
+
parser.add_argument(
|
| 126 |
+
"--connectivity",
|
| 127 |
+
type=int,
|
| 128 |
+
default=16,
|
| 129 |
+
help="HNSW M, neighbors per node (16 is the typical floor for ANN)",
|
| 130 |
+
)
|
| 131 |
+
parser.add_argument(
|
| 132 |
+
"--expansion-add",
|
| 133 |
+
type=int,
|
| 134 |
+
default=256,
|
| 135 |
+
help="HNSW efConstruction; bumped from the default 128 to chase >=99% recall@10",
|
| 136 |
+
)
|
| 137 |
+
parser.add_argument(
|
| 138 |
+
"--metric",
|
| 139 |
+
default="cos",
|
| 140 |
+
choices=["cos", "ip", "l2sq"],
|
| 141 |
+
help="similarity metric; cos is right for L2-normalized embeddings",
|
| 142 |
+
)
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--dtype",
|
| 145 |
+
default="f16",
|
| 146 |
+
help="index quantization dtype; f16 matches the on-disk format",
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--log-every",
|
| 150 |
+
type=int,
|
| 151 |
+
default=10,
|
| 152 |
+
help="print a progress line every N shards",
|
| 153 |
+
)
|
| 154 |
+
args = parser.parse_args()
|
| 155 |
+
|
| 156 |
+
from usearch.index import Index # local import: heavy dependency
|
| 157 |
+
|
| 158 |
+
model_root = Path(args.output) / args.model_subdir
|
| 159 |
+
print(f"discovering shards under {model_root} ...", flush=True)
|
| 160 |
+
started = time.monotonic()
|
| 161 |
+
shards = discover_collection(model_root, args.output_suffix)
|
| 162 |
+
if not shards:
|
| 163 |
+
raise SystemExit(f"no .{args.output_suffix}.f16bin shards under {model_root}")
|
| 164 |
+
# Read dimensions from the first shard's header. (Within a model the
|
| 165 |
+
# collection is consistent by construction; if it weren't, `index.add`
|
| 166 |
+
# would raise on the first mismatched shard anyway.)
|
| 167 |
+
first_blob = resolve_lfs_pointer(shards[0].path)
|
| 168 |
+
with open(first_blob, "rb") as file:
|
| 169 |
+
_, dimensions = struct.unpack("<II", file.read(8))
|
| 170 |
+
total_vectors = sum(s.row_count for s in shards)
|
| 171 |
+
elapsed = time.monotonic() - started
|
| 172 |
+
print(
|
| 173 |
+
f" {len(shards)} shards across "
|
| 174 |
+
f"{len({s.wikiname for s in shards})} wikis, "
|
| 175 |
+
f"{total_vectors:,} vectors x {dimensions}d in {elapsed:.1f}s",
|
| 176 |
+
flush=True,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
output_index_path = (
|
| 180 |
+
args.output_index
|
| 181 |
+
if args.output_index is not None
|
| 182 |
+
else model_root / f"{args.output_suffix}.usearch"
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
print(
|
| 186 |
+
f"opening USearch index "
|
| 187 |
+
f"(dim={dimensions}, metric={args.metric}, dtype={args.dtype}, "
|
| 188 |
+
f"M={args.connectivity}, ef_add={args.expansion_add}, "
|
| 189 |
+
f"multi=False, threads={args.threads})",
|
| 190 |
+
flush=True,
|
| 191 |
+
)
|
| 192 |
+
index = Index(
|
| 193 |
+
ndim=dimensions,
|
| 194 |
+
metric=args.metric,
|
| 195 |
+
dtype=args.dtype,
|
| 196 |
+
connectivity=args.connectivity,
|
| 197 |
+
expansion_add=args.expansion_add,
|
| 198 |
+
multi=False,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
print("streaming shards into index ...", flush=True)
|
| 202 |
+
started = time.monotonic()
|
| 203 |
+
added = add_shards(
|
| 204 |
+
index=index,
|
| 205 |
+
shards=shards,
|
| 206 |
+
dimensions=dimensions,
|
| 207 |
+
threads=args.threads,
|
| 208 |
+
log_every=args.log_every,
|
| 209 |
+
)
|
| 210 |
+
elapsed_build = time.monotonic() - started
|
| 211 |
+
rate = added / max(elapsed_build, 1e-3)
|
| 212 |
+
print(
|
| 213 |
+
f"added {added:,} vectors in {elapsed_build:.0f}s "
|
| 214 |
+
f"({rate:,.0f} vec/s), index size now {len(index):,}",
|
| 215 |
+
flush=True,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
output_index_path.parent.mkdir(parents=True, exist_ok=True)
|
| 219 |
+
started = time.monotonic()
|
| 220 |
+
index.save(str(output_index_path))
|
| 221 |
+
elapsed_save = time.monotonic() - started
|
| 222 |
+
file_size_gb = output_index_path.stat().st_size / 1e9
|
| 223 |
+
print(
|
| 224 |
+
f"saved {output_index_path} ({file_size_gb:.2f} GB) in {elapsed_save:.0f}s",
|
| 225 |
+
flush=True,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
if __name__ == "__main__":
|
| 230 |
+
main()
|
|
@@ -1,7 +1,11 @@
|
|
| 1 |
-
"""Embed FineWiki shards via a running TEI server.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
Usage:
|
| 4 |
-
python
|
| 5 |
--wiki enwiki --model-subdir qwen3-embedding-0.6b --dimensions 1024
|
| 6 |
|
| 7 |
For title embeddings, add: --text-column title --output-suffix title --char-cap 256
|
|
@@ -103,7 +107,7 @@ async def run(args: argparse.Namespace) -> None:
|
|
| 103 |
)
|
| 104 |
response.raise_for_status()
|
| 105 |
except Exception as error:
|
| 106 |
-
raise SystemExit(f"TEI not reachable at {args.url}: {error}")
|
| 107 |
|
| 108 |
async with httpx.AsyncClient() as client:
|
| 109 |
for shard in pending:
|
|
|
|
| 1 |
+
"""Embed FineWiki shards via a running TEI server (one dense vector per article).
|
| 2 |
+
|
| 3 |
+
The companion to `embed_sections.py`, which produces one vector per section
|
| 4 |
+
via late-chunking ColBERT. This module is the simpler dense path: each
|
| 5 |
+
article goes to TEI as a truncated document, gets back a single pooled vector.
|
| 6 |
|
| 7 |
Usage:
|
| 8 |
+
python embed_articles.py --cache-dir /path/to/hf-cache --output /path/to/embeddings \\
|
| 9 |
--wiki enwiki --model-subdir qwen3-embedding-0.6b --dimensions 1024
|
| 10 |
|
| 11 |
For title embeddings, add: --text-column title --output-suffix title --char-cap 256
|
|
|
|
| 107 |
)
|
| 108 |
response.raise_for_status()
|
| 109 |
except Exception as error:
|
| 110 |
+
raise SystemExit(f"TEI not reachable at {args.url}: {error}") from error
|
| 111 |
|
| 112 |
async with httpx.AsyncClient() as client:
|
| 113 |
for shard in pending:
|
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Late-chunking section embeddings via GTE-ModernColBERT-v1 (pylate).
|
| 2 |
+
|
| 3 |
+
For each parquet shard:
|
| 4 |
+
1. Load articles (text + id).
|
| 5 |
+
2. For each article: find section char spans, tokenize ("[D] " + text)
|
| 6 |
+
once, plan windows via late_chunking, forward each window through the
|
| 7 |
+
transformer + projection + L2 normalization, mean-pool the core token
|
| 8 |
+
vectors per section.
|
| 9 |
+
3. Write per-shard `{wiki}/{stem}.body.sections.f16bin` (concatenated section
|
| 10 |
+
embeddings) and `{wiki}/{stem}.body.sections.offsets.ibin` (cumulative
|
| 11 |
+
offsets giving each article's section slice).
|
| 12 |
+
|
| 13 |
+
One process per GPU; partition shards by `shard_index % world_size == gpu_id`.
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
CUDA_VISIBLE_DEVICES=0 python embed_sections.py \\
|
| 17 |
+
--cache-dir /home/ubuntu/wikiverse-data/hf-cache \\
|
| 18 |
+
--output /home/ubuntu/WikiVerse \\
|
| 19 |
+
--model-subdir gte-moderncolbert-v1 \\
|
| 20 |
+
--wiki enwiki --gpu-id 0 --world-size 8
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import os
|
| 27 |
+
import struct
|
| 28 |
+
import sys
|
| 29 |
+
import time
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
import pyarrow.parquet as pq
|
| 34 |
+
import torch
|
| 35 |
+
import torch.nn.functional as F
|
| 36 |
+
|
| 37 |
+
REPO_ROOT = Path(__file__).resolve().parent
|
| 38 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 39 |
+
|
| 40 |
+
from late_chunking import ( # noqa: E402
|
| 41 |
+
SectionCharSpan,
|
| 42 |
+
Window,
|
| 43 |
+
find_section_char_spans,
|
| 44 |
+
plan_windows,
|
| 45 |
+
pool_section_vectors,
|
| 46 |
+
section_token_spans_from_offsets,
|
| 47 |
+
)
|
| 48 |
+
from wikiverse import Shard, load_lang # noqa: E402
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def select_shards(all_shards: list[Shard], gpu_id: int, world_size: int) -> list[Shard]:
|
| 52 |
+
return [s for i, s in enumerate(all_shards) if i % world_size == gpu_id]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def load_pylate_model(model_id: str, device: str, document_length: int):
|
| 56 |
+
from pylate import models # local import (heavy)
|
| 57 |
+
|
| 58 |
+
print(f"[gpu] loading {model_id} on {device} ...", flush=True)
|
| 59 |
+
started = time.monotonic()
|
| 60 |
+
model = models.ColBERT(
|
| 61 |
+
model_name_or_path=model_id,
|
| 62 |
+
device=device,
|
| 63 |
+
document_length=document_length,
|
| 64 |
+
)
|
| 65 |
+
# Pylate defaults to fp32; switching to fp16 is ~3x faster with no
|
| 66 |
+
# measurable quality loss for this model. Cast both submodules.
|
| 67 |
+
model[0].auto_model = model[0].auto_model.half()
|
| 68 |
+
model[1].linear = model[1].linear.half()
|
| 69 |
+
model.eval()
|
| 70 |
+
print(
|
| 71 |
+
f"[gpu] loaded in {time.monotonic() - started:.1f}s "
|
| 72 |
+
f"(fp16: transformer={next(model[0].auto_model.parameters()).dtype}, "
|
| 73 |
+
f"dense={next(model[1].linear.parameters()).dtype})",
|
| 74 |
+
flush=True,
|
| 75 |
+
)
|
| 76 |
+
return model
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def plan_articles_batched(
|
| 80 |
+
texts: list[str],
|
| 81 |
+
tokenizer,
|
| 82 |
+
document_prefix: str,
|
| 83 |
+
context_limit: int,
|
| 84 |
+
margin: int,
|
| 85 |
+
) -> tuple[list[list[Window]], list[int]]:
|
| 86 |
+
"""Tokenize all articles in one tokenizer call (fast Rust path), then plan
|
| 87 |
+
windows per article. Returns (per_article_windows, per_article_n_sections).
|
| 88 |
+
"""
|
| 89 |
+
n = len(texts)
|
| 90 |
+
per_article_char_spans: list[list[SectionCharSpan]] = []
|
| 91 |
+
prefixed_texts: list[str] = []
|
| 92 |
+
nonempty_indices: list[int] = []
|
| 93 |
+
for index, text in enumerate(texts):
|
| 94 |
+
if not text:
|
| 95 |
+
per_article_char_spans.append([])
|
| 96 |
+
continue
|
| 97 |
+
char_spans = find_section_char_spans(text)
|
| 98 |
+
if not char_spans:
|
| 99 |
+
per_article_char_spans.append([])
|
| 100 |
+
continue
|
| 101 |
+
per_article_char_spans.append(char_spans)
|
| 102 |
+
prefixed_texts.append(document_prefix + text)
|
| 103 |
+
nonempty_indices.append(index)
|
| 104 |
+
|
| 105 |
+
per_article_windows: list[list[Window]] = [[] for _ in range(n)]
|
| 106 |
+
per_article_n_sections: list[int] = [0] * n
|
| 107 |
+
|
| 108 |
+
if not prefixed_texts:
|
| 109 |
+
return per_article_windows, per_article_n_sections
|
| 110 |
+
|
| 111 |
+
# One Rust-side tokenizer call for the whole batch.
|
| 112 |
+
encodings = tokenizer(
|
| 113 |
+
prefixed_texts,
|
| 114 |
+
add_special_tokens=False,
|
| 115 |
+
return_offsets_mapping=True,
|
| 116 |
+
truncation=False,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
prefix_len = len(document_prefix)
|
| 120 |
+
for batch_index, article_index in enumerate(nonempty_indices):
|
| 121 |
+
token_ids = encodings["input_ids"][batch_index]
|
| 122 |
+
offsets = encodings["offset_mapping"][batch_index]
|
| 123 |
+
char_spans = per_article_char_spans[article_index]
|
| 124 |
+
shifted = [
|
| 125 |
+
SectionCharSpan(
|
| 126 |
+
char_start=s.char_start + prefix_len,
|
| 127 |
+
char_end=s.char_end + prefix_len,
|
| 128 |
+
heading_level=s.heading_level,
|
| 129 |
+
heading_text=s.heading_text,
|
| 130 |
+
)
|
| 131 |
+
for s in char_spans
|
| 132 |
+
]
|
| 133 |
+
section_spans = section_token_spans_from_offsets(shifted, list(offsets))
|
| 134 |
+
if not section_spans:
|
| 135 |
+
continue
|
| 136 |
+
windows = plan_windows(token_ids, section_spans, context_limit, margin)
|
| 137 |
+
per_article_windows[article_index] = windows
|
| 138 |
+
per_article_n_sections[article_index] = len(section_spans)
|
| 139 |
+
|
| 140 |
+
return per_article_windows, per_article_n_sections
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def encode_articles_batch(
|
| 144 |
+
texts: list[str],
|
| 145 |
+
model,
|
| 146 |
+
cls_id: int,
|
| 147 |
+
sep_id: int,
|
| 148 |
+
pad_id: int,
|
| 149 |
+
device: str,
|
| 150 |
+
context_limit: int,
|
| 151 |
+
margin: int,
|
| 152 |
+
document_prefix: str,
|
| 153 |
+
max_batch_tokens: int,
|
| 154 |
+
) -> list[np.ndarray]:
|
| 155 |
+
"""Encode a batch of articles into per-article (n_sections, dim) FP16 arrays.
|
| 156 |
+
|
| 157 |
+
Pads windows from across the batch into one or more padded forward passes,
|
| 158 |
+
splitting into sub-batches whenever the padded total exceeds
|
| 159 |
+
`max_batch_tokens` (so a few very long articles don't blow up GPU memory).
|
| 160 |
+
"""
|
| 161 |
+
embedding_dim = model[1].linear.out_features
|
| 162 |
+
|
| 163 |
+
# Plan windows for every article via a single batched tokenizer call.
|
| 164 |
+
per_article_windows, per_article_n_sections = plan_articles_batched(
|
| 165 |
+
texts=texts,
|
| 166 |
+
tokenizer=model.tokenizer,
|
| 167 |
+
document_prefix=document_prefix,
|
| 168 |
+
context_limit=context_limit,
|
| 169 |
+
margin=margin,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# Flatten window list across articles, tag each with its article index.
|
| 173 |
+
all_windows: list[tuple[int, int, Window]] = []
|
| 174 |
+
for article_index, windows in enumerate(per_article_windows):
|
| 175 |
+
for window_index, window in enumerate(windows):
|
| 176 |
+
all_windows.append((article_index, window_index, window))
|
| 177 |
+
|
| 178 |
+
# Outputs scratch: one numpy array per (article, window) once we have it.
|
| 179 |
+
output_token_arrays: dict[tuple[int, int], np.ndarray] = {}
|
| 180 |
+
|
| 181 |
+
if all_windows:
|
| 182 |
+
# Sort windows by length to keep padding overhead per sub-batch low.
|
| 183 |
+
all_windows.sort(key=lambda triple: triple[2].length)
|
| 184 |
+
|
| 185 |
+
sub_batch: list[tuple[int, int, Window]] = []
|
| 186 |
+
sub_batch_max_len = 0
|
| 187 |
+
|
| 188 |
+
def flush(sub: list[tuple[int, int, Window]]) -> None:
|
| 189 |
+
if not sub:
|
| 190 |
+
return
|
| 191 |
+
wrapped_max = max(triple[2].length for triple in sub) + 2
|
| 192 |
+
input_ids = torch.full(
|
| 193 |
+
(len(sub), wrapped_max), pad_id, dtype=torch.long, device=device
|
| 194 |
+
)
|
| 195 |
+
attention_mask = torch.zeros(
|
| 196 |
+
(len(sub), wrapped_max), dtype=torch.long, device=device
|
| 197 |
+
)
|
| 198 |
+
for row, (_, _, window) in enumerate(sub):
|
| 199 |
+
wrapped = [cls_id] + window.token_ids + [sep_id]
|
| 200 |
+
input_ids[row, : len(wrapped)] = torch.tensor(
|
| 201 |
+
wrapped, dtype=torch.long, device=device
|
| 202 |
+
)
|
| 203 |
+
attention_mask[row, : len(wrapped)] = 1
|
| 204 |
+
with torch.inference_mode():
|
| 205 |
+
hidden = (
|
| 206 |
+
model[0]
|
| 207 |
+
.auto_model(input_ids=input_ids, attention_mask=attention_mask)
|
| 208 |
+
.last_hidden_state
|
| 209 |
+
)
|
| 210 |
+
projected = model[1].linear(hidden)
|
| 211 |
+
normalized = F.normalize(projected, p=2, dim=-1)
|
| 212 |
+
for row, (article_index, window_index, window) in enumerate(sub):
|
| 213 |
+
out = (
|
| 214 |
+
normalized[row, 1 : 1 + window.length, :]
|
| 215 |
+
.to(torch.float32)
|
| 216 |
+
.cpu()
|
| 217 |
+
.numpy()
|
| 218 |
+
)
|
| 219 |
+
output_token_arrays[(article_index, window_index)] = out
|
| 220 |
+
|
| 221 |
+
for triple in all_windows:
|
| 222 |
+
window = triple[2]
|
| 223 |
+
wrapped_len = window.length + 2
|
| 224 |
+
new_max_len = max(sub_batch_max_len, wrapped_len)
|
| 225 |
+
projected_padded_tokens = (len(sub_batch) + 1) * new_max_len
|
| 226 |
+
if sub_batch and projected_padded_tokens > max_batch_tokens:
|
| 227 |
+
flush(sub_batch)
|
| 228 |
+
sub_batch = []
|
| 229 |
+
sub_batch_max_len = 0
|
| 230 |
+
sub_batch.append(triple)
|
| 231 |
+
sub_batch_max_len = max(sub_batch_max_len, wrapped_len)
|
| 232 |
+
flush(sub_batch)
|
| 233 |
+
|
| 234 |
+
# Pool per article.
|
| 235 |
+
section_matrices: list[np.ndarray] = []
|
| 236 |
+
for article_index, (windows, n_sections) in enumerate(
|
| 237 |
+
zip(per_article_windows, per_article_n_sections, strict=True)
|
| 238 |
+
):
|
| 239 |
+
if n_sections == 0:
|
| 240 |
+
section_matrices.append(np.zeros((0, embedding_dim), dtype=np.float16))
|
| 241 |
+
continue
|
| 242 |
+
token_outputs = [
|
| 243 |
+
output_token_arrays[(article_index, window_index)]
|
| 244 |
+
for window_index in range(len(windows))
|
| 245 |
+
]
|
| 246 |
+
section_matrix = pool_section_vectors(
|
| 247 |
+
windows=windows,
|
| 248 |
+
window_token_outputs=token_outputs,
|
| 249 |
+
n_sections=n_sections,
|
| 250 |
+
embedding_dim=embedding_dim,
|
| 251 |
+
)
|
| 252 |
+
norms = np.linalg.norm(section_matrix, axis=1, keepdims=True)
|
| 253 |
+
nonzero = norms[:, 0] > 0
|
| 254 |
+
section_matrix[nonzero] = section_matrix[nonzero] / norms[nonzero]
|
| 255 |
+
section_matrices.append(section_matrix.astype(np.float16))
|
| 256 |
+
return section_matrices
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def write_shard_outputs(
|
| 260 |
+
shard_dir: Path,
|
| 261 |
+
stem: str,
|
| 262 |
+
suffix: str,
|
| 263 |
+
section_matrices: list[np.ndarray],
|
| 264 |
+
embedding_dim: int,
|
| 265 |
+
) -> None:
|
| 266 |
+
shard_dir.mkdir(parents=True, exist_ok=True)
|
| 267 |
+
section_counts = [m.shape[0] for m in section_matrices]
|
| 268 |
+
total_sections = sum(section_counts)
|
| 269 |
+
cumulative_offsets = np.zeros(len(section_matrices) + 1, dtype=np.int32)
|
| 270 |
+
cumulative_offsets[1:] = np.cumsum(section_counts, dtype=np.int32)
|
| 271 |
+
|
| 272 |
+
sections_path = shard_dir / f"{stem}.{suffix}.sections.f16bin"
|
| 273 |
+
offsets_path = shard_dir / f"{stem}.{suffix}.sections.offsets.ibin"
|
| 274 |
+
|
| 275 |
+
with open(sections_path.with_suffix(sections_path.suffix + ".tmp"), "wb") as file:
|
| 276 |
+
file.write(struct.pack("<II", total_sections, embedding_dim))
|
| 277 |
+
if total_sections > 0:
|
| 278 |
+
concatenated = (
|
| 279 |
+
np.vstack(section_matrices)
|
| 280 |
+
if section_matrices
|
| 281 |
+
else np.zeros((0, embedding_dim), dtype=np.float16)
|
| 282 |
+
)
|
| 283 |
+
file.write(concatenated.tobytes(order="C"))
|
| 284 |
+
sections_path.with_suffix(sections_path.suffix + ".tmp").rename(sections_path)
|
| 285 |
+
|
| 286 |
+
with open(offsets_path.with_suffix(offsets_path.suffix + ".tmp"), "wb") as file:
|
| 287 |
+
file.write(struct.pack("<II", len(cumulative_offsets), 1))
|
| 288 |
+
file.write(cumulative_offsets.tobytes(order="C"))
|
| 289 |
+
offsets_path.with_suffix(offsets_path.suffix + ".tmp").rename(offsets_path)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def process_shard(
|
| 293 |
+
shard: Shard,
|
| 294 |
+
output_root: Path,
|
| 295 |
+
model,
|
| 296 |
+
cls_id: int,
|
| 297 |
+
sep_id: int,
|
| 298 |
+
pad_id: int,
|
| 299 |
+
device: str,
|
| 300 |
+
context_limit: int,
|
| 301 |
+
margin: int,
|
| 302 |
+
document_prefix: str,
|
| 303 |
+
suffix: str,
|
| 304 |
+
text_column: str,
|
| 305 |
+
id_column: str,
|
| 306 |
+
article_batch_size: int,
|
| 307 |
+
max_batch_tokens: int,
|
| 308 |
+
) -> dict:
|
| 309 |
+
table = pq.read_table(shard.path, columns=[id_column, text_column])
|
| 310 |
+
ids = table.column(id_column).to_pylist()
|
| 311 |
+
texts = table.column(text_column).to_pylist()
|
| 312 |
+
|
| 313 |
+
section_matrices: list[np.ndarray] = []
|
| 314 |
+
n_sections_total = 0
|
| 315 |
+
n_zero = 0
|
| 316 |
+
started = time.monotonic()
|
| 317 |
+
progress_every = max(article_batch_size, len(ids) // 20)
|
| 318 |
+
embedding_dim = model[1].linear.out_features
|
| 319 |
+
|
| 320 |
+
for batch_start in range(0, len(ids), article_batch_size):
|
| 321 |
+
batch_end = min(batch_start + article_batch_size, len(ids))
|
| 322 |
+
batch_texts = [t or "" for t in texts[batch_start:batch_end]]
|
| 323 |
+
try:
|
| 324 |
+
batch_matrices = encode_articles_batch(
|
| 325 |
+
texts=batch_texts,
|
| 326 |
+
model=model,
|
| 327 |
+
cls_id=cls_id,
|
| 328 |
+
sep_id=sep_id,
|
| 329 |
+
pad_id=pad_id,
|
| 330 |
+
device=device,
|
| 331 |
+
context_limit=context_limit,
|
| 332 |
+
margin=margin,
|
| 333 |
+
document_prefix=document_prefix,
|
| 334 |
+
max_batch_tokens=max_batch_tokens,
|
| 335 |
+
)
|
| 336 |
+
except Exception as exc:
|
| 337 |
+
print(
|
| 338 |
+
f" ! batch [{batch_start},{batch_end}) failed: {exc!r}; "
|
| 339 |
+
f"emitting zero sections for the batch",
|
| 340 |
+
flush=True,
|
| 341 |
+
)
|
| 342 |
+
batch_matrices = [
|
| 343 |
+
np.zeros((0, embedding_dim), dtype=np.float16) for _ in batch_texts
|
| 344 |
+
]
|
| 345 |
+
for matrix in batch_matrices:
|
| 346 |
+
section_matrices.append(matrix)
|
| 347 |
+
n_sections_total += matrix.shape[0]
|
| 348 |
+
if matrix.shape[0] == 0:
|
| 349 |
+
n_zero += 1
|
| 350 |
+
if batch_end % progress_every < article_batch_size or batch_end == len(ids):
|
| 351 |
+
elapsed = time.monotonic() - started
|
| 352 |
+
rate = batch_end / max(elapsed, 1e-3)
|
| 353 |
+
print(
|
| 354 |
+
f" {shard.wikiname}/{shard.stem}: {batch_end}/{len(ids)} articles "
|
| 355 |
+
f"({rate:.1f} doc/s, {n_sections_total:,} sections so far)",
|
| 356 |
+
flush=True,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
elapsed = time.monotonic() - started
|
| 360 |
+
embedding_dim = model[1].linear.out_features
|
| 361 |
+
|
| 362 |
+
write_shard_outputs(
|
| 363 |
+
shard_dir=output_root / shard.wikiname,
|
| 364 |
+
stem=shard.stem,
|
| 365 |
+
suffix=suffix,
|
| 366 |
+
section_matrices=section_matrices,
|
| 367 |
+
embedding_dim=embedding_dim,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
return {
|
| 371 |
+
"n_articles": len(ids),
|
| 372 |
+
"n_zero_articles": n_zero,
|
| 373 |
+
"n_sections_total": n_sections_total,
|
| 374 |
+
"elapsed_seconds": elapsed,
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def main() -> None:
|
| 379 |
+
parser = argparse.ArgumentParser()
|
| 380 |
+
parser.add_argument("--cache-dir", default="/home/ubuntu/wikiverse-data/hf-cache")
|
| 381 |
+
parser.add_argument("--output", default="/home/ubuntu/WikiVerse")
|
| 382 |
+
parser.add_argument("--model-subdir", default="gte-moderncolbert-v1")
|
| 383 |
+
parser.add_argument("--model-id", default="lightonai/GTE-ModernColBERT-v1")
|
| 384 |
+
parser.add_argument(
|
| 385 |
+
"--wiki", required=True, help="single language code (enwiki, dewiki, ...)"
|
| 386 |
+
)
|
| 387 |
+
parser.add_argument("--gpu-id", type=int, default=0)
|
| 388 |
+
parser.add_argument("--world-size", type=int, default=1)
|
| 389 |
+
parser.add_argument("--context-limit", type=int, default=8192)
|
| 390 |
+
parser.add_argument("--margin", type=int, default=256)
|
| 391 |
+
parser.add_argument("--text-column", default="text", choices=["text", "title"])
|
| 392 |
+
parser.add_argument("--output-suffix", default="body")
|
| 393 |
+
parser.add_argument("--id-column", default="id")
|
| 394 |
+
parser.add_argument(
|
| 395 |
+
"--article-batch-size",
|
| 396 |
+
type=int,
|
| 397 |
+
default=64,
|
| 398 |
+
help="number of articles' windows to plan in one cross-article batch",
|
| 399 |
+
)
|
| 400 |
+
parser.add_argument(
|
| 401 |
+
"--max-batch-tokens",
|
| 402 |
+
type=int,
|
| 403 |
+
default=131072,
|
| 404 |
+
help="cap on `padded_batch_size * padded_max_length` per forward pass; "
|
| 405 |
+
"splits the cross-article batch into sub-batches when needed to keep "
|
| 406 |
+
"GPU memory bounded",
|
| 407 |
+
)
|
| 408 |
+
args = parser.parse_args()
|
| 409 |
+
|
| 410 |
+
# Pin to the assigned GPU before importing pylate.
|
| 411 |
+
os.environ.setdefault("CUDA_VISIBLE_DEVICES", str(args.gpu_id))
|
| 412 |
+
device = "cuda:0" # post-CUDA_VISIBLE_DEVICES, our GPU is always cuda:0.
|
| 413 |
+
|
| 414 |
+
output_root = Path(args.output) / args.model_subdir
|
| 415 |
+
output_root.mkdir(parents=True, exist_ok=True)
|
| 416 |
+
|
| 417 |
+
shards = load_lang(args.cache_dir, args.wiki)
|
| 418 |
+
owned = select_shards(shards, args.gpu_id, args.world_size)
|
| 419 |
+
pending = [
|
| 420 |
+
s
|
| 421 |
+
for s in owned
|
| 422 |
+
if not (
|
| 423 |
+
output_root / s.wikiname / f"{s.stem}.{args.output_suffix}.sections.f16bin"
|
| 424 |
+
).exists()
|
| 425 |
+
]
|
| 426 |
+
print(
|
| 427 |
+
f"[gpu{args.gpu_id}] {args.wiki}: {len(owned)} owned, {len(pending)} pending",
|
| 428 |
+
flush=True,
|
| 429 |
+
)
|
| 430 |
+
if not pending:
|
| 431 |
+
return
|
| 432 |
+
|
| 433 |
+
model = load_pylate_model(args.model_id, device, args.context_limit)
|
| 434 |
+
cls_id = model.tokenizer.cls_token_id
|
| 435 |
+
sep_id = model.tokenizer.sep_token_id
|
| 436 |
+
pad_id = model.tokenizer.pad_token_id
|
| 437 |
+
document_prefix = model.document_prefix
|
| 438 |
+
|
| 439 |
+
started_overall = time.monotonic()
|
| 440 |
+
total_articles = 0
|
| 441 |
+
total_sections = 0
|
| 442 |
+
for shard in pending:
|
| 443 |
+
stats = process_shard(
|
| 444 |
+
shard=shard,
|
| 445 |
+
output_root=output_root,
|
| 446 |
+
model=model,
|
| 447 |
+
cls_id=cls_id,
|
| 448 |
+
sep_id=sep_id,
|
| 449 |
+
pad_id=pad_id,
|
| 450 |
+
device=device,
|
| 451 |
+
context_limit=args.context_limit,
|
| 452 |
+
margin=args.margin,
|
| 453 |
+
document_prefix=document_prefix,
|
| 454 |
+
suffix=args.output_suffix,
|
| 455 |
+
text_column=args.text_column,
|
| 456 |
+
id_column=args.id_column,
|
| 457 |
+
article_batch_size=args.article_batch_size,
|
| 458 |
+
max_batch_tokens=args.max_batch_tokens,
|
| 459 |
+
)
|
| 460 |
+
total_articles += stats["n_articles"]
|
| 461 |
+
total_sections += stats["n_sections_total"]
|
| 462 |
+
rate = stats["n_articles"] / max(stats["elapsed_seconds"], 1e-3)
|
| 463 |
+
print(
|
| 464 |
+
f"[gpu{args.gpu_id} pylate] {shard.wikiname}/{shard.stem}: "
|
| 465 |
+
f"{stats['n_articles']} articles ({stats['n_zero_articles']} zero), "
|
| 466 |
+
f"{stats['n_sections_total']:,} sections in {stats['elapsed_seconds']:.1f}s "
|
| 467 |
+
f"-> {rate:.1f} doc/s",
|
| 468 |
+
flush=True,
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
wall = time.monotonic() - started_overall
|
| 472 |
+
print(
|
| 473 |
+
f"[gpu{args.gpu_id} pylate] DONE: {total_articles} articles, "
|
| 474 |
+
f"{total_sections:,} sections in {wall:.0f}s -> {total_articles/max(wall,1):.1f} doc/s",
|
| 475 |
+
flush=True,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
if __name__ == "__main__":
|
| 480 |
+
main()
|
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Measure self-recall@k of a USearch index against the precomputed exact
|
| 2 |
+
ground-truth files (`{wiki}/{stem}.body.ground_truth.ibin`).
|
| 3 |
+
|
| 4 |
+
Samples N article IDs uniformly across the canonical shard walk, queries the
|
| 5 |
+
index with their stored vectors (memory-mapped from the same `.f16bin` files),
|
| 6 |
+
and compares the returned top-k keys against the exact top-k from the ground
|
| 7 |
+
truth. Reports mean recall@k for one or more `ef_search` settings — the
|
| 8 |
+
standard recall-vs-speed sweep.
|
| 9 |
+
|
| 10 |
+
Usage:
|
| 11 |
+
python eval_recall.py \\
|
| 12 |
+
--output /home/ubuntu/WikiVerse \\
|
| 13 |
+
--model-subdir qwen3-embedding-0.6b \\
|
| 14 |
+
--output-suffix body \\
|
| 15 |
+
--index /home/ubuntu/WikiVerse/qwen3-embedding-0.6b/body.usearch \\
|
| 16 |
+
--num-queries 10000 --k 10 \\
|
| 17 |
+
--ef-search 64,128,256,512
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import struct
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
REPO_ROOT = Path(__file__).resolve().parent
|
| 31 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 32 |
+
|
| 33 |
+
from wikiverse import ( # noqa: E402
|
| 34 |
+
CollectionShard,
|
| 35 |
+
discover_collection,
|
| 36 |
+
resolve_lfs_pointer,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def memmap_shard_vectors(shard: CollectionShard, dimensions: int) -> np.ndarray:
|
| 41 |
+
blob = resolve_lfs_pointer(shard.path)
|
| 42 |
+
return np.memmap(
|
| 43 |
+
blob,
|
| 44 |
+
dtype=np.float16,
|
| 45 |
+
mode="r",
|
| 46 |
+
offset=8,
|
| 47 |
+
shape=(shard.row_count, dimensions),
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def gather_query_vectors(
|
| 52 |
+
shards: list[CollectionShard],
|
| 53 |
+
dimensions: int,
|
| 54 |
+
query_global_ids: np.ndarray,
|
| 55 |
+
) -> np.ndarray:
|
| 56 |
+
"""Return a `(len(query_global_ids), dimensions)` FP16 array of the
|
| 57 |
+
embeddings for the given global IDs, drawn via memmap from the canonical
|
| 58 |
+
shard walk.
|
| 59 |
+
"""
|
| 60 |
+
out = np.empty((len(query_global_ids), dimensions), dtype=np.float16)
|
| 61 |
+
# Index of each query within the per-shard offsets — binary search.
|
| 62 |
+
shard_starts = np.array([s.row_offset for s in shards], dtype=np.int64)
|
| 63 |
+
shard_indices = np.searchsorted(shard_starts, query_global_ids, side="right") - 1
|
| 64 |
+
sort_order = np.argsort(shard_indices, kind="stable")
|
| 65 |
+
sorted_query_indices = shard_indices[sort_order]
|
| 66 |
+
sorted_global_ids = query_global_ids[sort_order]
|
| 67 |
+
|
| 68 |
+
cursor = 0
|
| 69 |
+
while cursor < len(sort_order):
|
| 70 |
+
shard_index = int(sorted_query_indices[cursor])
|
| 71 |
+
end = cursor
|
| 72 |
+
while end < len(sort_order) and sorted_query_indices[end] == shard_index:
|
| 73 |
+
end += 1
|
| 74 |
+
shard = shards[shard_index]
|
| 75 |
+
local_rows = sorted_global_ids[cursor:end] - shard.row_offset
|
| 76 |
+
memmap = memmap_shard_vectors(shard, dimensions)
|
| 77 |
+
out[sort_order[cursor:end]] = np.asarray(memmap[local_rows])
|
| 78 |
+
cursor = end
|
| 79 |
+
return out
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def gather_ground_truth(
|
| 83 |
+
model_root: Path,
|
| 84 |
+
suffix: str,
|
| 85 |
+
shards: list[CollectionShard],
|
| 86 |
+
query_global_ids: np.ndarray,
|
| 87 |
+
k: int,
|
| 88 |
+
) -> np.ndarray:
|
| 89 |
+
"""Return `(len(query_global_ids), k)` int32 array of exact top-k indices
|
| 90 |
+
pulled from per-shard `.{suffix}.ground_truth.ibin` files. Assumes the GT
|
| 91 |
+
was stored with at least `k` neighbors per row."""
|
| 92 |
+
out = np.empty((len(query_global_ids), k), dtype=np.int32)
|
| 93 |
+
shard_starts = np.array([s.row_offset for s in shards], dtype=np.int64)
|
| 94 |
+
shard_indices = np.searchsorted(shard_starts, query_global_ids, side="right") - 1
|
| 95 |
+
sort_order = np.argsort(shard_indices, kind="stable")
|
| 96 |
+
sorted_query_indices = shard_indices[sort_order]
|
| 97 |
+
sorted_global_ids = query_global_ids[sort_order]
|
| 98 |
+
cursor = 0
|
| 99 |
+
while cursor < len(sort_order):
|
| 100 |
+
shard_index = int(sorted_query_indices[cursor])
|
| 101 |
+
end = cursor
|
| 102 |
+
while end < len(sort_order) and sorted_query_indices[end] == shard_index:
|
| 103 |
+
end += 1
|
| 104 |
+
shard = shards[shard_index]
|
| 105 |
+
gt_path = (
|
| 106 |
+
model_root / shard.wikiname / f"{shard.stem}.{suffix}.ground_truth.ibin"
|
| 107 |
+
)
|
| 108 |
+
gt_blob = resolve_lfs_pointer(gt_path)
|
| 109 |
+
with open(gt_blob, "rb") as file:
|
| 110 |
+
rows, gt_k = struct.unpack("<II", file.read(8))
|
| 111 |
+
if k > gt_k:
|
| 112 |
+
raise SystemExit(
|
| 113 |
+
f"requested k={k} > stored ground-truth k={gt_k} in {gt_path}"
|
| 114 |
+
)
|
| 115 |
+
gt_memmap = np.memmap(
|
| 116 |
+
gt_blob, dtype=np.int32, mode="r", offset=8, shape=(rows, gt_k)
|
| 117 |
+
)
|
| 118 |
+
local_rows = sorted_global_ids[cursor:end] - shard.row_offset
|
| 119 |
+
out[sort_order[cursor:end]] = np.asarray(gt_memmap[local_rows, :k])
|
| 120 |
+
cursor = end
|
| 121 |
+
return out
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def measure_recall(
|
| 125 |
+
expected: np.ndarray,
|
| 126 |
+
actual: np.ndarray,
|
| 127 |
+
k: int,
|
| 128 |
+
) -> float:
|
| 129 |
+
"""`expected` and `actual` are both `(num_queries, k)` int arrays."""
|
| 130 |
+
matches = 0
|
| 131 |
+
for row in range(expected.shape[0]):
|
| 132 |
+
matches += len(set(expected[row].tolist()) & set(actual[row].tolist()))
|
| 133 |
+
return matches / (expected.shape[0] * k)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main() -> None:
|
| 137 |
+
parser = argparse.ArgumentParser()
|
| 138 |
+
parser.add_argument("--output", default="/home/ubuntu/WikiVerse")
|
| 139 |
+
parser.add_argument("--model-subdir", required=True)
|
| 140 |
+
parser.add_argument("--output-suffix", default="body", choices=["body", "title"])
|
| 141 |
+
parser.add_argument("--index", type=Path, default=None)
|
| 142 |
+
parser.add_argument("--num-queries", type=int, default=10000)
|
| 143 |
+
parser.add_argument("--k", type=int, default=10)
|
| 144 |
+
parser.add_argument(
|
| 145 |
+
"--ef-search",
|
| 146 |
+
default="64,128,256,512",
|
| 147 |
+
help="comma-separated efSearch values to sweep",
|
| 148 |
+
)
|
| 149 |
+
parser.add_argument(
|
| 150 |
+
"--threads",
|
| 151 |
+
type=int,
|
| 152 |
+
default=64,
|
| 153 |
+
help="USearch search thread count",
|
| 154 |
+
)
|
| 155 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 156 |
+
args = parser.parse_args()
|
| 157 |
+
|
| 158 |
+
from usearch.index import Index
|
| 159 |
+
|
| 160 |
+
model_root = Path(args.output) / args.model_subdir
|
| 161 |
+
index_path = (
|
| 162 |
+
args.index
|
| 163 |
+
if args.index is not None
|
| 164 |
+
else model_root / f"{args.output_suffix}.usearch"
|
| 165 |
+
)
|
| 166 |
+
if not index_path.is_file():
|
| 167 |
+
raise SystemExit(f"index not found at {index_path}")
|
| 168 |
+
|
| 169 |
+
print(f"loading index {index_path} ...", flush=True)
|
| 170 |
+
started = time.monotonic()
|
| 171 |
+
index = Index.restore(str(index_path))
|
| 172 |
+
print(
|
| 173 |
+
f" loaded {len(index):,} vectors in {time.monotonic()-started:.1f}s",
|
| 174 |
+
flush=True,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
print(f"discovering shards under {model_root} ...", flush=True)
|
| 178 |
+
shards = discover_collection(model_root, args.output_suffix)
|
| 179 |
+
total_vectors = sum(s.row_count for s in shards)
|
| 180 |
+
if total_vectors != len(index):
|
| 181 |
+
print(
|
| 182 |
+
f" WARN: index size {len(index):,} != collection size {total_vectors:,}",
|
| 183 |
+
flush=True,
|
| 184 |
+
)
|
| 185 |
+
# Read first shard header for dimensions
|
| 186 |
+
first_blob = resolve_lfs_pointer(shards[0].path)
|
| 187 |
+
with open(first_blob, "rb") as file:
|
| 188 |
+
_, dimensions = struct.unpack("<II", file.read(8))
|
| 189 |
+
print(f" {total_vectors:,} vectors x {dimensions}d", flush=True)
|
| 190 |
+
|
| 191 |
+
rng = np.random.default_rng(args.seed)
|
| 192 |
+
query_ids = np.sort(
|
| 193 |
+
rng.choice(total_vectors, size=args.num_queries, replace=False)
|
| 194 |
+
).astype(np.int64)
|
| 195 |
+
print(f"sampled {args.num_queries:,} query IDs", flush=True)
|
| 196 |
+
|
| 197 |
+
print("loading query vectors and exact ground truth ...", flush=True)
|
| 198 |
+
started = time.monotonic()
|
| 199 |
+
query_vectors = gather_query_vectors(shards, dimensions, query_ids)
|
| 200 |
+
expected_keys = gather_ground_truth(
|
| 201 |
+
model_root, args.output_suffix, shards, query_ids, args.k
|
| 202 |
+
)
|
| 203 |
+
print(f" loaded in {time.monotonic()-started:.1f}s", flush=True)
|
| 204 |
+
|
| 205 |
+
ef_values = [int(x) for x in args.ef_search.split(",") if x.strip()]
|
| 206 |
+
print(f"sweeping ef_search over {ef_values} with k={args.k} ...", flush=True)
|
| 207 |
+
print(f"{'ef_search':>10} {'recall@k':>10} {'queries/s':>12}")
|
| 208 |
+
for ef in ef_values:
|
| 209 |
+
index.expansion_search = ef
|
| 210 |
+
started = time.monotonic()
|
| 211 |
+
results = index.search(query_vectors, count=args.k, threads=args.threads)
|
| 212 |
+
elapsed = time.monotonic() - started
|
| 213 |
+
actual_keys = np.asarray(results.keys, dtype=np.int64)
|
| 214 |
+
recall = measure_recall(expected_keys, actual_keys, args.k)
|
| 215 |
+
rate = args.num_queries / max(elapsed, 1e-3)
|
| 216 |
+
print(f"{ef:>10} {recall*100:>9.4f}% {rate:>12,.0f}")
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
if __name__ == "__main__":
|
| 220 |
+
main()
|
|
@@ -17,88 +17,16 @@ import multiprocessing as mp
|
|
| 17 |
import os
|
| 18 |
import struct
|
| 19 |
import time
|
| 20 |
-
from dataclasses import dataclass
|
| 21 |
from pathlib import Path
|
| 22 |
|
| 23 |
import numpy as np
|
| 24 |
|
| 25 |
-
from wikiverse import
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def resolve_lfs_pointer(path: Path) -> Path:
|
| 32 |
-
"""If `path` is a Git-LFS pointer file, return the materialized blob in `.git/lfs/objects`.
|
| 33 |
-
|
| 34 |
-
Pointer files are tiny ASCII stubs (~133 bytes) with an `oid sha256:<hex>` line.
|
| 35 |
-
Repositories cloned with `GIT_LFS_SKIP_SMUDGE=1` (or with `git lfs fetch` only)
|
| 36 |
-
keep the actual binaries under `.git/lfs/objects/<aa>/<bb>/<oid>` while the
|
| 37 |
-
working tree holds pointers. Reading those blobs in place avoids checking out
|
| 38 |
-
a duplicate copy of the dataset.
|
| 39 |
-
"""
|
| 40 |
-
try:
|
| 41 |
-
if path.stat().st_size > 1024:
|
| 42 |
-
return path
|
| 43 |
-
except OSError:
|
| 44 |
-
return path
|
| 45 |
-
with open(path, "rb") as file:
|
| 46 |
-
head = file.read(256)
|
| 47 |
-
if not head.startswith(LFS_POINTER_PREFIX):
|
| 48 |
-
return path
|
| 49 |
-
oid: str | None = None
|
| 50 |
-
for line in head.decode("ascii", errors="ignore").splitlines():
|
| 51 |
-
if line.startswith("oid sha256:"):
|
| 52 |
-
oid = line.split(":", 1)[1].strip()
|
| 53 |
-
break
|
| 54 |
-
if not oid:
|
| 55 |
-
raise ValueError(f"{path}: looks like an LFS pointer but no sha256 oid line")
|
| 56 |
-
# Walk parents of the resolved path (so symlinked working trees still find the
|
| 57 |
-
# original repo's `.git/lfs/objects`).
|
| 58 |
-
for ancestor in path.resolve().parents:
|
| 59 |
-
candidate = ancestor / ".git" / "lfs" / "objects" / oid[:2] / oid[2:4] / oid
|
| 60 |
-
if candidate.is_file():
|
| 61 |
-
return candidate
|
| 62 |
-
raise FileNotFoundError(
|
| 63 |
-
f"{path}: LFS pointer references oid {oid} but no .git/lfs/objects/ contains it; "
|
| 64 |
-
f"run `git lfs fetch` or pass --output to a tree that has the blobs"
|
| 65 |
-
)
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
@dataclass(frozen=True, slots=True)
|
| 69 |
-
class CollectionShard:
|
| 70 |
-
wikiname: str
|
| 71 |
-
stem: str
|
| 72 |
-
row_offset: int
|
| 73 |
-
row_count: int
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def discover_shards(model_root: Path, suffix: str) -> list[CollectionShard]:
|
| 77 |
-
"""Find every {wiki}/{stem}.{suffix}.f16bin under model_root in deterministic order."""
|
| 78 |
-
binaries: list[tuple[str, str, Path, int]] = []
|
| 79 |
-
for wiki_dir in sorted(model_root.iterdir()):
|
| 80 |
-
if not wiki_dir.is_dir():
|
| 81 |
-
continue
|
| 82 |
-
for path in sorted(wiki_dir.glob(f"*.{suffix}.f16bin")):
|
| 83 |
-
stem = path.name[: -len(f".{suffix}.f16bin")]
|
| 84 |
-
blob_path = resolve_lfs_pointer(path)
|
| 85 |
-
with open(blob_path, "rb") as file:
|
| 86 |
-
rows, _columns = struct.unpack("<II", file.read(8))
|
| 87 |
-
binaries.append((wiki_dir.name, stem, path, rows))
|
| 88 |
-
|
| 89 |
-
shards: list[CollectionShard] = []
|
| 90 |
-
offset = 0
|
| 91 |
-
for wikiname, stem, _path, row_count in binaries:
|
| 92 |
-
shards.append(
|
| 93 |
-
CollectionShard(
|
| 94 |
-
wikiname=wikiname,
|
| 95 |
-
stem=stem,
|
| 96 |
-
row_offset=offset,
|
| 97 |
-
row_count=row_count,
|
| 98 |
-
)
|
| 99 |
-
)
|
| 100 |
-
offset += row_count
|
| 101 |
-
return shards
|
| 102 |
|
| 103 |
|
| 104 |
def load_collection(
|
|
@@ -432,9 +360,10 @@ def gather_outputs(
|
|
| 432 |
wiki_dir.mkdir(parents=True, exist_ok=True)
|
| 433 |
indices_path = wiki_dir / f"{shard.stem}.{suffix}.ground_truth.ibin"
|
| 434 |
scores_path = wiki_dir / f"{shard.stem}.{suffix}.ground_truth.fbin"
|
| 435 |
-
with
|
| 436 |
-
|
| 437 |
-
|
|
|
|
| 438 |
out_indices.write(struct.pack("<II", shard.row_count, num_neighbors))
|
| 439 |
out_scores.write(struct.pack("<II", shard.row_count, num_neighbors))
|
| 440 |
cursor = shard.row_offset
|
|
@@ -508,7 +437,7 @@ def main() -> None:
|
|
| 508 |
if not model_root.is_dir():
|
| 509 |
raise SystemExit(f"no collection at {model_root}")
|
| 510 |
|
| 511 |
-
shards =
|
| 512 |
if not shards:
|
| 513 |
raise SystemExit(f"no .{args.output_suffix}.f16bin files under {model_root}")
|
| 514 |
total_vectors = sum(shard.row_count for shard in shards)
|
|
|
|
| 17 |
import os
|
| 18 |
import struct
|
| 19 |
import time
|
|
|
|
| 20 |
from pathlib import Path
|
| 21 |
|
| 22 |
import numpy as np
|
| 23 |
|
| 24 |
+
from wikiverse import (
|
| 25 |
+
CollectionShard,
|
| 26 |
+
discover_collection,
|
| 27 |
+
resolve_lfs_pointer,
|
| 28 |
+
write_bin,
|
| 29 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
def load_collection(
|
|
|
|
| 360 |
wiki_dir.mkdir(parents=True, exist_ok=True)
|
| 361 |
indices_path = wiki_dir / f"{shard.stem}.{suffix}.ground_truth.ibin"
|
| 362 |
scores_path = wiki_dir / f"{shard.stem}.{suffix}.ground_truth.fbin"
|
| 363 |
+
with (
|
| 364 |
+
open(indices_path, "wb") as out_indices,
|
| 365 |
+
open(scores_path, "wb") as out_scores,
|
| 366 |
+
):
|
| 367 |
out_indices.write(struct.pack("<II", shard.row_count, num_neighbors))
|
| 368 |
out_scores.write(struct.pack("<II", shard.row_count, num_neighbors))
|
| 369 |
cursor = shard.row_offset
|
|
|
|
| 437 |
if not model_root.is_dir():
|
| 438 |
raise SystemExit(f"no collection at {model_root}")
|
| 439 |
|
| 440 |
+
shards = discover_collection(model_root, args.output_suffix)
|
| 441 |
if not shards:
|
| 442 |
raise SystemExit(f"no .{args.output_suffix}.f16bin files under {model_root}")
|
| 443 |
total_vectors = sum(shard.row_count for shard in shards)
|
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Late-chunking with section-aware windowing for long-context encoders.
|
| 2 |
+
|
| 3 |
+
The pipeline is:
|
| 4 |
+
|
| 5 |
+
1. Find section spans (character coordinates) in an article's rendered Markdown.
|
| 6 |
+
2. Tokenize the whole article once, with offset mapping, so each section maps
|
| 7 |
+
to a token range.
|
| 8 |
+
3. Greedy-pack consecutive sections into windows of `core` tokens, where
|
| 9 |
+
`core <= context_limit - 2 * margin`. Sections too large for one window
|
| 10 |
+
get split into fragments; fragments live in their own windows.
|
| 11 |
+
4. Surround each window's core with up to `margin` tokens of left- and
|
| 12 |
+
right-context drawn from the surrounding tokens of the same article.
|
| 13 |
+
Margins exist purely so attention can flow between adjacent sections.
|
| 14 |
+
5. Run the model once per window. Mean-pool the *core* token outputs (skip
|
| 15 |
+
the margin) per section. If a section was split, weighted-average its
|
| 16 |
+
fragment vectors by token count to recover one vector per section.
|
| 17 |
+
|
| 18 |
+
The output is one embedding vector per source section, in article order.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import re
|
| 24 |
+
from collections.abc import Sequence
|
| 25 |
+
from dataclasses import dataclass
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
# Markdown heading lines: between 1 and 6 leading hashes followed by whitespace.
|
| 30 |
+
HEADING_LINE = re.compile(r"^(#{1,6})\s+(.*)$", re.MULTILINE)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass(frozen=True, slots=True)
|
| 34 |
+
class SectionCharSpan:
|
| 35 |
+
"""A section's character-coordinate span and its heading metadata."""
|
| 36 |
+
|
| 37 |
+
char_start: int
|
| 38 |
+
char_end: int
|
| 39 |
+
heading_level: int # 0 for the lead section (no heading)
|
| 40 |
+
heading_text: str | None # None for the lead section
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass(frozen=True, slots=True)
|
| 44 |
+
class SectionTokenSpan:
|
| 45 |
+
"""A section's token-coordinate span (after tokenization)."""
|
| 46 |
+
|
| 47 |
+
section_index: int
|
| 48 |
+
token_start: int # inclusive, in article token coordinates
|
| 49 |
+
token_end: int # exclusive
|
| 50 |
+
heading_level: int
|
| 51 |
+
heading_text: str | None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass(frozen=True, slots=True)
|
| 55 |
+
class CoreSegment:
|
| 56 |
+
"""One contiguous range of tokens inside a window's core that pools to part
|
| 57 |
+
of (or all of) a single section's vector.
|
| 58 |
+
|
| 59 |
+
For a section that fits in one window, fragment_count == 1. For a section
|
| 60 |
+
split across N windows, the same section_index produces N CoreSegments,
|
| 61 |
+
each with the same fragment_count == N, but different fragment_index in
|
| 62 |
+
[0, N)."""
|
| 63 |
+
|
| 64 |
+
section_index: int
|
| 65 |
+
fragment_index: int
|
| 66 |
+
fragment_count: int
|
| 67 |
+
article_token_start: int # in article coordinates
|
| 68 |
+
article_token_end: int # exclusive
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@dataclass(frozen=True, slots=True)
|
| 72 |
+
class Window:
|
| 73 |
+
"""One forward-pass through the encoder.
|
| 74 |
+
|
| 75 |
+
`token_ids` is the literal input to the model: left margin (0..core_start),
|
| 76 |
+
then core (core_start..core_end), then right margin (core_end..len).
|
| 77 |
+
`core_segments` describe how to mean-pool the core token outputs into
|
| 78 |
+
section fragments.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
token_ids: list[int]
|
| 82 |
+
core_start: int # offset in token_ids where core begins
|
| 83 |
+
core_end: int # offset where core ends (exclusive)
|
| 84 |
+
core_segments: list[CoreSegment]
|
| 85 |
+
article_left_margin_start: int # in article token coordinates
|
| 86 |
+
article_right_margin_end: int # exclusive
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def length(self) -> int:
|
| 90 |
+
return len(self.token_ids)
|
| 91 |
+
|
| 92 |
+
def core_segment_window_range(self, segment: CoreSegment) -> tuple[int, int]:
|
| 93 |
+
"""Return (start, end) offsets for `segment` in this window's outputs.
|
| 94 |
+
|
| 95 |
+
A window position is just the corresponding article position shifted by
|
| 96 |
+
the left-margin start, since `token_ids` is a contiguous slice of the
|
| 97 |
+
article tokens beginning at `article_left_margin_start`.
|
| 98 |
+
"""
|
| 99 |
+
start = segment.article_token_start - self.article_left_margin_start
|
| 100 |
+
end = segment.article_token_end - self.article_left_margin_start
|
| 101 |
+
return start, end
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def find_section_char_spans(text: str) -> list[SectionCharSpan]:
|
| 105 |
+
"""Split the rendered Markdown text into section spans.
|
| 106 |
+
|
| 107 |
+
A section runs from a heading line to the next heading line (exclusive).
|
| 108 |
+
The lead — anything before the first heading — is its own section with
|
| 109 |
+
`heading_level == 0` and `heading_text is None`.
|
| 110 |
+
"""
|
| 111 |
+
if not text:
|
| 112 |
+
return []
|
| 113 |
+
headings = list(HEADING_LINE.finditer(text))
|
| 114 |
+
if not headings:
|
| 115 |
+
return [SectionCharSpan(0, len(text), 0, None)]
|
| 116 |
+
|
| 117 |
+
spans: list[SectionCharSpan] = []
|
| 118 |
+
if headings[0].start() > 0:
|
| 119 |
+
spans.append(SectionCharSpan(0, headings[0].start(), 0, None))
|
| 120 |
+
for index, match in enumerate(headings):
|
| 121 |
+
next_start = (
|
| 122 |
+
headings[index + 1].start() if index + 1 < len(headings) else len(text)
|
| 123 |
+
)
|
| 124 |
+
spans.append(
|
| 125 |
+
SectionCharSpan(
|
| 126 |
+
char_start=match.start(),
|
| 127 |
+
char_end=next_start,
|
| 128 |
+
heading_level=len(match.group(1)),
|
| 129 |
+
heading_text=match.group(2).strip() or None,
|
| 130 |
+
)
|
| 131 |
+
)
|
| 132 |
+
return spans
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def section_token_spans_from_offsets(
|
| 136 |
+
section_char_spans: Sequence[SectionCharSpan],
|
| 137 |
+
token_offsets: Sequence[tuple[int, int]],
|
| 138 |
+
) -> list[SectionTokenSpan]:
|
| 139 |
+
"""Convert character-coordinate section spans into token-coordinate spans
|
| 140 |
+
using the tokenizer's `offset_mapping` output. Sections that produce zero
|
| 141 |
+
tokens (empty after tokenization) are dropped silently."""
|
| 142 |
+
n_tokens = len(token_offsets)
|
| 143 |
+
spans: list[SectionTokenSpan] = []
|
| 144 |
+
for index, section in enumerate(section_char_spans):
|
| 145 |
+
# First token whose start offset >= section.char_start.
|
| 146 |
+
token_start = n_tokens
|
| 147 |
+
for token_index, (char_start, _) in enumerate(token_offsets):
|
| 148 |
+
if char_start >= section.char_start:
|
| 149 |
+
token_start = token_index
|
| 150 |
+
break
|
| 151 |
+
# First token whose start offset >= section.char_end (exclusive).
|
| 152 |
+
token_end = n_tokens
|
| 153 |
+
for token_index, (char_start, _) in enumerate(token_offsets):
|
| 154 |
+
if char_start >= section.char_end:
|
| 155 |
+
token_end = token_index
|
| 156 |
+
break
|
| 157 |
+
if token_end > token_start:
|
| 158 |
+
spans.append(
|
| 159 |
+
SectionTokenSpan(
|
| 160 |
+
section_index=index,
|
| 161 |
+
token_start=token_start,
|
| 162 |
+
token_end=token_end,
|
| 163 |
+
heading_level=section.heading_level,
|
| 164 |
+
heading_text=section.heading_text,
|
| 165 |
+
)
|
| 166 |
+
)
|
| 167 |
+
return spans
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def plan_windows(
|
| 171 |
+
article_token_ids: Sequence[int],
|
| 172 |
+
section_token_spans: Sequence[SectionTokenSpan],
|
| 173 |
+
context_limit: int,
|
| 174 |
+
margin: int,
|
| 175 |
+
) -> list[Window]:
|
| 176 |
+
"""Greedy-pack sections into windows of `<= context_limit - 2*margin` core
|
| 177 |
+
tokens. Sections that exceed the per-window core limit are split into
|
| 178 |
+
fragments, each fragment getting its own window. Margins are added per
|
| 179 |
+
window from neighboring article tokens.
|
| 180 |
+
"""
|
| 181 |
+
if context_limit <= 2 * margin:
|
| 182 |
+
raise ValueError(
|
| 183 |
+
f"context_limit ({context_limit}) must exceed 2 * margin ({2 * margin})"
|
| 184 |
+
)
|
| 185 |
+
max_core_tokens = context_limit - 2 * margin
|
| 186 |
+
n_article_tokens = len(article_token_ids)
|
| 187 |
+
|
| 188 |
+
# Step 1: build "segments" — each segment is one fragment of one section that
|
| 189 |
+
# fits in a single window. Sections shorter than max_core_tokens become a
|
| 190 |
+
# single segment; longer sections become multiple segments.
|
| 191 |
+
segments: list[CoreSegment] = []
|
| 192 |
+
for span in section_token_spans:
|
| 193 |
+
section_size = span.token_end - span.token_start
|
| 194 |
+
if section_size <= max_core_tokens:
|
| 195 |
+
segments.append(
|
| 196 |
+
CoreSegment(
|
| 197 |
+
section_index=span.section_index,
|
| 198 |
+
fragment_index=0,
|
| 199 |
+
fragment_count=1,
|
| 200 |
+
article_token_start=span.token_start,
|
| 201 |
+
article_token_end=span.token_end,
|
| 202 |
+
)
|
| 203 |
+
)
|
| 204 |
+
continue
|
| 205 |
+
n_fragments = (section_size + max_core_tokens - 1) // max_core_tokens
|
| 206 |
+
# Even-sized fragments (last one may be slightly smaller).
|
| 207 |
+
base = section_size // n_fragments
|
| 208 |
+
remainder = section_size - base * n_fragments
|
| 209 |
+
cursor = span.token_start
|
| 210 |
+
for fragment_index in range(n_fragments):
|
| 211 |
+
this_size = base + (1 if fragment_index < remainder else 0)
|
| 212 |
+
segments.append(
|
| 213 |
+
CoreSegment(
|
| 214 |
+
section_index=span.section_index,
|
| 215 |
+
fragment_index=fragment_index,
|
| 216 |
+
fragment_count=n_fragments,
|
| 217 |
+
article_token_start=cursor,
|
| 218 |
+
article_token_end=cursor + this_size,
|
| 219 |
+
)
|
| 220 |
+
)
|
| 221 |
+
cursor += this_size
|
| 222 |
+
|
| 223 |
+
# Step 2: greedy-pack segments into windows. A multi-fragment section never
|
| 224 |
+
# shares a window with anything else: its segments are already exactly
|
| 225 |
+
# max_core_tokens (or smaller, for the last fragment), so packing them
|
| 226 |
+
# alongside other sections would risk overflow.
|
| 227 |
+
window_segment_groups: list[list[CoreSegment]] = []
|
| 228 |
+
current: list[CoreSegment] = []
|
| 229 |
+
current_size = 0
|
| 230 |
+
for segment in segments:
|
| 231 |
+
segment_size = segment.article_token_end - segment.article_token_start
|
| 232 |
+
is_split_section = segment.fragment_count > 1
|
| 233 |
+
previous_was_split = bool(current) and current[-1].fragment_count > 1
|
| 234 |
+
new_window_required = (
|
| 235 |
+
not current
|
| 236 |
+
or is_split_section
|
| 237 |
+
or previous_was_split
|
| 238 |
+
or current_size + segment_size > max_core_tokens
|
| 239 |
+
)
|
| 240 |
+
if new_window_required and current:
|
| 241 |
+
window_segment_groups.append(current)
|
| 242 |
+
current = []
|
| 243 |
+
current_size = 0
|
| 244 |
+
current.append(segment)
|
| 245 |
+
current_size += segment_size
|
| 246 |
+
if current:
|
| 247 |
+
window_segment_groups.append(current)
|
| 248 |
+
|
| 249 |
+
# Step 3: materialize each window with margins drawn from the surrounding
|
| 250 |
+
# article tokens.
|
| 251 |
+
windows: list[Window] = []
|
| 252 |
+
for group in window_segment_groups:
|
| 253 |
+
core_start_in_article = group[0].article_token_start
|
| 254 |
+
core_end_in_article = group[-1].article_token_end
|
| 255 |
+
left_margin_start = max(0, core_start_in_article - margin)
|
| 256 |
+
right_margin_end = min(n_article_tokens, core_end_in_article + margin)
|
| 257 |
+
token_ids = list(article_token_ids[left_margin_start:right_margin_end])
|
| 258 |
+
core_start_in_window = core_start_in_article - left_margin_start
|
| 259 |
+
core_end_in_window = core_end_in_article - left_margin_start
|
| 260 |
+
windows.append(
|
| 261 |
+
Window(
|
| 262 |
+
token_ids=token_ids,
|
| 263 |
+
core_start=core_start_in_window,
|
| 264 |
+
core_end=core_end_in_window,
|
| 265 |
+
core_segments=list(group),
|
| 266 |
+
article_left_margin_start=left_margin_start,
|
| 267 |
+
article_right_margin_end=right_margin_end,
|
| 268 |
+
)
|
| 269 |
+
)
|
| 270 |
+
return windows
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def pool_section_vectors(
|
| 274 |
+
windows: Sequence[Window],
|
| 275 |
+
window_token_outputs: Sequence[np.ndarray],
|
| 276 |
+
n_sections: int,
|
| 277 |
+
embedding_dim: int,
|
| 278 |
+
) -> np.ndarray:
|
| 279 |
+
"""Reduce per-window per-token output vectors to one vector per section.
|
| 280 |
+
|
| 281 |
+
`window_token_outputs[i]` must have shape `(windows[i].length, embedding_dim)`.
|
| 282 |
+
The pooled outputs are mean-pooled over each section's token range; sections
|
| 283 |
+
that were split into fragments are recombined by token-count-weighted average
|
| 284 |
+
across their fragments.
|
| 285 |
+
"""
|
| 286 |
+
fragment_sums: dict[tuple[int, int], np.ndarray] = {}
|
| 287 |
+
fragment_counts: dict[tuple[int, int], int] = {}
|
| 288 |
+
for window, outputs in zip(windows, window_token_outputs, strict=True):
|
| 289 |
+
if outputs.shape != (window.length, embedding_dim):
|
| 290 |
+
raise ValueError(
|
| 291 |
+
f"window output shape {outputs.shape} != ({window.length}, {embedding_dim})"
|
| 292 |
+
)
|
| 293 |
+
for segment in window.core_segments:
|
| 294 |
+
window_start, window_end = window.core_segment_window_range(segment)
|
| 295 |
+
segment_outputs = outputs[window_start:window_end]
|
| 296 |
+
if segment_outputs.shape[0] == 0:
|
| 297 |
+
continue
|
| 298 |
+
key = (segment.section_index, segment.fragment_index)
|
| 299 |
+
fragment_sums[key] = segment_outputs.sum(axis=0).astype(np.float32)
|
| 300 |
+
fragment_counts[key] = segment_outputs.shape[0]
|
| 301 |
+
|
| 302 |
+
section_vectors = np.zeros((n_sections, embedding_dim), dtype=np.float32)
|
| 303 |
+
section_token_totals = np.zeros(n_sections, dtype=np.int64)
|
| 304 |
+
for (section_index, _fragment_index), summed in fragment_sums.items():
|
| 305 |
+
n_tokens = fragment_counts[(section_index, _fragment_index)]
|
| 306 |
+
section_vectors[section_index] += summed
|
| 307 |
+
section_token_totals[section_index] += n_tokens
|
| 308 |
+
nonzero = section_token_totals > 0
|
| 309 |
+
section_vectors[nonzero] /= section_token_totals[nonzero, None]
|
| 310 |
+
return section_vectors
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def chunk_article(
|
| 314 |
+
text: str,
|
| 315 |
+
tokenizer, # transformers.PreTrainedTokenizer
|
| 316 |
+
context_limit: int = 8192,
|
| 317 |
+
margin: int = 256,
|
| 318 |
+
) -> tuple[list[Window], list[SectionTokenSpan]]:
|
| 319 |
+
"""End-to-end: rendered Markdown -> windows ready for the model.
|
| 320 |
+
|
| 321 |
+
Returns the windows plus the section token spans (so callers can correlate
|
| 322 |
+
section vectors back to heading metadata)."""
|
| 323 |
+
char_spans = find_section_char_spans(text)
|
| 324 |
+
encoding = tokenizer(
|
| 325 |
+
text,
|
| 326 |
+
add_special_tokens=False,
|
| 327 |
+
return_offsets_mapping=True,
|
| 328 |
+
truncation=False,
|
| 329 |
+
)
|
| 330 |
+
token_ids: list[int] = encoding["input_ids"]
|
| 331 |
+
token_offsets: list[tuple[int, int]] = list(encoding["offset_mapping"])
|
| 332 |
+
section_spans = section_token_spans_from_offsets(char_spans, token_offsets)
|
| 333 |
+
windows = plan_windows(token_ids, section_spans, context_limit, margin)
|
| 334 |
+
return windows, section_spans
|
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "usearchwiki"
|
| 3 |
+
version = "0.0.0"
|
| 4 |
+
description = "Multi-model embedding dataset over FineWiki for ANN-search benchmarking"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
license = { text = "Apache-2.0" }
|
| 7 |
+
requires-python = ">=3.12"
|
| 8 |
+
dependencies = [
|
| 9 |
+
"numpy>=1.26",
|
| 10 |
+
"pyarrow>=16",
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
[project.optional-dependencies]
|
| 14 |
+
dense = ["httpx>=0.27"]
|
| 15 |
+
ground = ["cupy-cuda12x>=14", "torch>=2.5"]
|
| 16 |
+
colbert = ["pylate>=1.0"]
|
| 17 |
+
index = ["usearch>=2.25"]
|
| 18 |
+
dev = ["ruff>=0.15", "pytest>=8", "mypy>=1.13"]
|
| 19 |
+
|
| 20 |
+
[tool.ruff]
|
| 21 |
+
line-length = 100
|
| 22 |
+
target-version = "py312"
|
| 23 |
+
|
| 24 |
+
[tool.ruff.lint]
|
| 25 |
+
select = ["E", "F", "I", "B", "UP", "C4"]
|
| 26 |
+
ignore = ["E501"]
|
| 27 |
+
|
| 28 |
+
[tool.ruff.lint.per-file-ignores]
|
| 29 |
+
"tests/*" = ["E402"] # imports after sys.path manipulation
|
| 30 |
+
|
| 31 |
+
[tool.mypy]
|
| 32 |
+
python_version = "3.12"
|
| 33 |
+
strict_optional = true
|
| 34 |
+
warn_unused_ignores = true
|
| 35 |
+
ignore_missing_imports = true
|
| 36 |
+
|
| 37 |
+
[tool.pytest.ini_options]
|
| 38 |
+
testpaths = ["tests"]
|
| 39 |
+
python_files = ["test_*.py"]
|
|
@@ -12,8 +12,6 @@ or directly:
|
|
| 12 |
|
| 13 |
from __future__ import annotations
|
| 14 |
|
| 15 |
-
import json
|
| 16 |
-
import struct
|
| 17 |
import subprocess
|
| 18 |
import sys
|
| 19 |
import tempfile
|
|
@@ -24,7 +22,7 @@ import numpy as np
|
|
| 24 |
REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 25 |
sys.path.insert(0, str(REPO_ROOT))
|
| 26 |
|
| 27 |
-
from wikiverse import
|
| 28 |
|
| 29 |
|
| 30 |
def normalize_rows(matrix: np.ndarray) -> np.ndarray:
|
|
@@ -70,8 +68,8 @@ def assemble_per_shard(
|
|
| 70 |
model_root: Path, suffix: str, extension: str, dtype: str
|
| 71 |
) -> np.ndarray:
|
| 72 |
"""Read every `{wiki}/{stem}.{suffix}.ground_truth.{extension}` and
|
| 73 |
-
concatenate in the same deterministic order
|
| 74 |
-
wikiname, then sorted stem)."""
|
| 75 |
parts: list[np.ndarray] = []
|
| 76 |
for wiki_dir in sorted(model_root.iterdir()):
|
| 77 |
if not wiki_dir.is_dir():
|
|
@@ -87,8 +85,6 @@ def reference_topk(
|
|
| 87 |
"""Brute-force exact top-k via NumPy float32 matmul, with self-match dropped."""
|
| 88 |
f32 = embeddings.astype(np.float32)
|
| 89 |
similarity = f32 @ f32.T
|
| 90 |
-
total = embeddings.shape[0]
|
| 91 |
-
# Drop self-match by setting diagonal to -inf, then take top-k.
|
| 92 |
np.fill_diagonal(similarity, -np.inf)
|
| 93 |
top_indices = np.argsort(-similarity, axis=1)[:, :num_neighbors].astype(np.int32)
|
| 94 |
top_scores = np.take_along_axis(similarity, top_indices, axis=1).astype(np.float32)
|
|
|
|
| 12 |
|
| 13 |
from __future__ import annotations
|
| 14 |
|
|
|
|
|
|
|
| 15 |
import subprocess
|
| 16 |
import sys
|
| 17 |
import tempfile
|
|
|
|
| 22 |
REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 23 |
sys.path.insert(0, str(REPO_ROOT))
|
| 24 |
|
| 25 |
+
from wikiverse import read_bin, write_bin # noqa: E402
|
| 26 |
|
| 27 |
|
| 28 |
def normalize_rows(matrix: np.ndarray) -> np.ndarray:
|
|
|
|
| 68 |
model_root: Path, suffix: str, extension: str, dtype: str
|
| 69 |
) -> np.ndarray:
|
| 70 |
"""Read every `{wiki}/{stem}.{suffix}.ground_truth.{extension}` and
|
| 71 |
+
concatenate in the same deterministic order discover_collection uses
|
| 72 |
+
(sorted wikiname, then sorted stem)."""
|
| 73 |
parts: list[np.ndarray] = []
|
| 74 |
for wiki_dir in sorted(model_root.iterdir()):
|
| 75 |
if not wiki_dir.is_dir():
|
|
|
|
| 85 |
"""Brute-force exact top-k via NumPy float32 matmul, with self-match dropped."""
|
| 86 |
f32 = embeddings.astype(np.float32)
|
| 87 |
similarity = f32 @ f32.T
|
|
|
|
|
|
|
| 88 |
np.fill_diagonal(similarity, -np.inf)
|
| 89 |
top_indices = np.argsort(-similarity, axis=1)[:, :num_neighbors].astype(np.int32)
|
| 90 |
top_scores = np.take_along_axis(similarity, top_indices, axis=1).astype(np.float32)
|
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic tests for late_chunking.py.
|
| 2 |
+
|
| 3 |
+
The chunker is purely arithmetic — given an article's tokens and section
|
| 4 |
+
spans, it produces windows. We can verify all the invariants without a model:
|
| 5 |
+
|
| 6 |
+
- every section's core tokens appear in exactly one window
|
| 7 |
+
(or, when split, every section's core tokens are partitioned across
|
| 8 |
+
fragments without gaps or overlaps)
|
| 9 |
+
- every window's input length is at most context_limit
|
| 10 |
+
- every section's pooled token range falls inside a window's core
|
| 11 |
+
- margins respect article boundaries
|
| 12 |
+
- pool_section_vectors recovers the right per-section means
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 23 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 24 |
+
|
| 25 |
+
from late_chunking import ( # noqa: E402
|
| 26 |
+
CoreSegment,
|
| 27 |
+
SectionCharSpan,
|
| 28 |
+
SectionTokenSpan,
|
| 29 |
+
Window,
|
| 30 |
+
find_section_char_spans,
|
| 31 |
+
plan_windows,
|
| 32 |
+
pool_section_vectors,
|
| 33 |
+
section_token_spans_from_offsets,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def make_synthetic_section_spans(
|
| 38 |
+
section_sizes: list[int],
|
| 39 |
+
) -> tuple[list[int], list[SectionTokenSpan]]:
|
| 40 |
+
"""Build (article_token_ids, section_token_spans) where each token's id
|
| 41 |
+
encodes its (section_index, position_in_section) so we can verify that
|
| 42 |
+
pooling maps the right tokens back to the right section."""
|
| 43 |
+
spans: list[SectionTokenSpan] = []
|
| 44 |
+
token_ids: list[int] = []
|
| 45 |
+
cursor = 0
|
| 46 |
+
for index, size in enumerate(section_sizes):
|
| 47 |
+
spans.append(
|
| 48 |
+
SectionTokenSpan(
|
| 49 |
+
section_index=index,
|
| 50 |
+
token_start=cursor,
|
| 51 |
+
token_end=cursor + size,
|
| 52 |
+
heading_level=2,
|
| 53 |
+
heading_text=f"Section {index}",
|
| 54 |
+
)
|
| 55 |
+
)
|
| 56 |
+
for position in range(size):
|
| 57 |
+
# Encode (section_index, position) so the test can verify pooling.
|
| 58 |
+
token_ids.append(index * 100000 + position)
|
| 59 |
+
cursor += size
|
| 60 |
+
return token_ids, spans
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def assert_windows_cover_all_sections(
|
| 64 |
+
section_sizes: list[int],
|
| 65 |
+
spans: list[SectionTokenSpan],
|
| 66 |
+
windows: list[Window],
|
| 67 |
+
) -> None:
|
| 68 |
+
"""Every section's [token_start, token_end) must be covered by exactly one
|
| 69 |
+
set of CoreSegments whose article ranges concatenate to the original."""
|
| 70 |
+
by_section: dict[int, list[CoreSegment]] = {}
|
| 71 |
+
for window in windows:
|
| 72 |
+
for segment in window.core_segments:
|
| 73 |
+
by_section.setdefault(segment.section_index, []).append(segment)
|
| 74 |
+
for index, span in enumerate(spans):
|
| 75 |
+
section_segments = sorted(
|
| 76 |
+
by_section[index], key=lambda seg: seg.fragment_index
|
| 77 |
+
)
|
| 78 |
+
# Fragments must form a contiguous partition.
|
| 79 |
+
cursor = span.token_start
|
| 80 |
+
for fragment in section_segments:
|
| 81 |
+
assert fragment.article_token_start == cursor, (
|
| 82 |
+
f"section {index} fragment gap at {cursor} vs {fragment.article_token_start}"
|
| 83 |
+
)
|
| 84 |
+
cursor = fragment.article_token_end
|
| 85 |
+
assert fragment.fragment_count == len(section_segments), (
|
| 86 |
+
f"section {index} fragment_count mismatch"
|
| 87 |
+
)
|
| 88 |
+
assert cursor == span.token_end, (
|
| 89 |
+
f"section {index} fragments end at {cursor}, expected {span.token_end}"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def assert_window_lengths_within_limit(
|
| 94 |
+
windows: list[Window], context_limit: int
|
| 95 |
+
) -> None:
|
| 96 |
+
for index, window in enumerate(windows):
|
| 97 |
+
assert window.length <= context_limit, (
|
| 98 |
+
f"window {index} length {window.length} exceeds context_limit {context_limit}"
|
| 99 |
+
)
|
| 100 |
+
# Core boundaries must lie within the window.
|
| 101 |
+
assert 0 <= window.core_start <= window.core_end <= window.length
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def assert_segment_offsets_consistent(windows: list[Window]) -> None:
|
| 105 |
+
for window in windows:
|
| 106 |
+
for segment in window.core_segments:
|
| 107 |
+
window_start, window_end = window.core_segment_window_range(segment)
|
| 108 |
+
assert window.core_start <= window_start < window_end <= window.core_end, (
|
| 109 |
+
f"segment {segment} offsets ({window_start}, {window_end}) "
|
| 110 |
+
f"escape core [{window.core_start}, {window.core_end})"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_single_section_fits_in_one_window() -> None:
|
| 115 |
+
section_sizes = [400]
|
| 116 |
+
article_tokens, spans = make_synthetic_section_spans(section_sizes)
|
| 117 |
+
windows = plan_windows(article_tokens, spans, context_limit=8192, margin=256)
|
| 118 |
+
assert len(windows) == 1
|
| 119 |
+
assert_window_lengths_within_limit(windows, 8192)
|
| 120 |
+
assert_windows_cover_all_sections(section_sizes, spans, windows)
|
| 121 |
+
# No left margin (article starts here) and no right margin (article ends here).
|
| 122 |
+
assert windows[0].core_start == 0
|
| 123 |
+
assert windows[0].core_end == 400
|
| 124 |
+
assert windows[0].length == 400
|
| 125 |
+
print("PASS: single-section fits in one window")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_many_small_sections_pack_into_one_window() -> None:
|
| 129 |
+
section_sizes = [100] * 30 # 3000 total tokens
|
| 130 |
+
article_tokens, spans = make_synthetic_section_spans(section_sizes)
|
| 131 |
+
windows = plan_windows(article_tokens, spans, context_limit=8192, margin=256)
|
| 132 |
+
assert len(windows) == 1, f"expected 1 window, got {len(windows)}"
|
| 133 |
+
assert sum(s.token_end - s.token_start for s in spans) == windows[0].core_end - windows[0].core_start
|
| 134 |
+
print(f"PASS: 30 small sections packed into 1 window ({windows[0].length} tokens)")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_sections_split_across_multiple_windows() -> None:
|
| 138 |
+
# 10 sections of 1000 each = 10K tokens; with core 7680 that's 2 windows.
|
| 139 |
+
section_sizes = [1000] * 10
|
| 140 |
+
article_tokens, spans = make_synthetic_section_spans(section_sizes)
|
| 141 |
+
windows = plan_windows(article_tokens, spans, context_limit=8192, margin=256)
|
| 142 |
+
assert len(windows) == 2, f"expected 2 windows, got {len(windows)}"
|
| 143 |
+
assert_window_lengths_within_limit(windows, 8192)
|
| 144 |
+
assert_windows_cover_all_sections(section_sizes, spans, windows)
|
| 145 |
+
assert_segment_offsets_consistent(windows)
|
| 146 |
+
# Window 0 has no left margin (article start); has a right margin from window 1's first section.
|
| 147 |
+
assert windows[0].article_left_margin_start == 0
|
| 148 |
+
assert windows[0].length > windows[0].core_end - windows[0].core_start # right margin present
|
| 149 |
+
# Window 1 has a left margin from window 0's tail; no right margin (article end).
|
| 150 |
+
assert windows[1].article_right_margin_end == 10000
|
| 151 |
+
assert windows[1].core_start > 0 # left margin present
|
| 152 |
+
print(f"PASS: 10 x 1000-token sections -> {len(windows)} windows with margins")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_oversized_section_split_into_fragments() -> None:
|
| 156 |
+
# One section of 20K tokens, where context=8192, margin=256, core_max=7680.
|
| 157 |
+
# 20000 / 7680 = 3 fragments (sizes 6667, 6667, 6666).
|
| 158 |
+
section_sizes = [20000]
|
| 159 |
+
article_tokens, spans = make_synthetic_section_spans(section_sizes)
|
| 160 |
+
windows = plan_windows(article_tokens, spans, context_limit=8192, margin=256)
|
| 161 |
+
assert len(windows) == 3, f"expected 3 windows, got {len(windows)}"
|
| 162 |
+
fragments = [seg for w in windows for seg in w.core_segments]
|
| 163 |
+
assert len(fragments) == 3
|
| 164 |
+
assert all(f.fragment_count == 3 for f in fragments)
|
| 165 |
+
# Fragments must partition the section's token range.
|
| 166 |
+
starts = [f.article_token_start for f in fragments]
|
| 167 |
+
ends = [f.article_token_end for f in fragments]
|
| 168 |
+
assert starts[0] == 0 and ends[-1] == 20000
|
| 169 |
+
for i in range(len(fragments) - 1):
|
| 170 |
+
assert ends[i] == starts[i + 1]
|
| 171 |
+
assert_window_lengths_within_limit(windows, 8192)
|
| 172 |
+
print("PASS: oversized section split into 3 fragments across 3 windows")
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_mixed_normal_and_oversized_sections() -> None:
|
| 176 |
+
# Lead 100, big middle 10000, tail 200.
|
| 177 |
+
section_sizes = [100, 10000, 200]
|
| 178 |
+
article_tokens, spans = make_synthetic_section_spans(section_sizes)
|
| 179 |
+
windows = plan_windows(article_tokens, spans, context_limit=8192, margin=256)
|
| 180 |
+
assert_windows_cover_all_sections(section_sizes, spans, windows)
|
| 181 |
+
assert_window_lengths_within_limit(windows, 8192)
|
| 182 |
+
assert_segment_offsets_consistent(windows)
|
| 183 |
+
# The middle section needs 2 windows to itself; the lead and tail go in
|
| 184 |
+
# their own windows because we don't share with split sections.
|
| 185 |
+
fragment_counts = {seg.section_index: seg.fragment_count for w in windows for seg in w.core_segments}
|
| 186 |
+
assert fragment_counts == {0: 1, 1: 2, 2: 1}, fragment_counts
|
| 187 |
+
print(f"PASS: mixed normal+oversized -> {len(windows)} windows")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_pool_section_vectors_recovers_means() -> None:
|
| 191 |
+
"""Synthesize per-token outputs whose mean is the section index;
|
| 192 |
+
verify that pooled vectors equal the section index."""
|
| 193 |
+
section_sizes = [50, 30, 20]
|
| 194 |
+
article_tokens, spans = make_synthetic_section_spans(section_sizes)
|
| 195 |
+
windows = plan_windows(article_tokens, spans, context_limit=8192, margin=256)
|
| 196 |
+
embedding_dim = 8
|
| 197 |
+
window_outputs: list[np.ndarray] = []
|
| 198 |
+
for window in windows:
|
| 199 |
+
out = np.zeros((window.length, embedding_dim), dtype=np.float32)
|
| 200 |
+
for segment in window.core_segments:
|
| 201 |
+
wstart, wend = window.core_segment_window_range(segment)
|
| 202 |
+
# Fill core token rows with a vector whose values equal section_index.
|
| 203 |
+
out[wstart:wend] = float(segment.section_index) + 0.0
|
| 204 |
+
window_outputs.append(out)
|
| 205 |
+
pooled = pool_section_vectors(windows, window_outputs, n_sections=3, embedding_dim=embedding_dim)
|
| 206 |
+
expected = np.array(
|
| 207 |
+
[[0.0] * 8, [1.0] * 8, [2.0] * 8],
|
| 208 |
+
dtype=np.float32,
|
| 209 |
+
)
|
| 210 |
+
assert np.allclose(pooled, expected), pooled
|
| 211 |
+
print("PASS: pool_section_vectors recovers per-section means")
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_pool_recovers_split_section_via_weighted_mean() -> None:
|
| 215 |
+
"""Section split into 2 fragments of different sizes; per-fragment mean is
|
| 216 |
+
different; pooled section vector must be the token-weighted average."""
|
| 217 |
+
# Single section, 12K tokens — splits into 2 fragments of 6K each (since
|
| 218 |
+
# core max = 7680 and 12000/7680 rounds to 2).
|
| 219 |
+
section_sizes = [12000]
|
| 220 |
+
article_tokens, spans = make_synthetic_section_spans(section_sizes)
|
| 221 |
+
windows = plan_windows(article_tokens, spans, context_limit=8192, margin=256)
|
| 222 |
+
assert len(windows) == 2
|
| 223 |
+
embedding_dim = 4
|
| 224 |
+
window_outputs: list[np.ndarray] = []
|
| 225 |
+
for window in windows:
|
| 226 |
+
out = np.zeros((window.length, embedding_dim), dtype=np.float32)
|
| 227 |
+
for segment in window.core_segments:
|
| 228 |
+
wstart, wend = window.core_segment_window_range(segment)
|
| 229 |
+
# Fragment 0 -> mean is 1.0; fragment 1 -> mean is 5.0.
|
| 230 |
+
value = 1.0 if segment.fragment_index == 0 else 5.0
|
| 231 |
+
out[wstart:wend] = value
|
| 232 |
+
window_outputs.append(out)
|
| 233 |
+
pooled = pool_section_vectors(windows, window_outputs, n_sections=1, embedding_dim=embedding_dim)
|
| 234 |
+
# Both fragments are 6000 tokens; weighted mean = (1*6000 + 5*6000)/12000 = 3.0.
|
| 235 |
+
assert np.allclose(pooled, np.full((1, 4), 3.0)), pooled
|
| 236 |
+
print("PASS: split section recovered via token-weighted average")
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def test_section_char_spans_lead_only() -> None:
|
| 240 |
+
text = "Just one paragraph of text, no headings."
|
| 241 |
+
spans = find_section_char_spans(text)
|
| 242 |
+
assert len(spans) == 1
|
| 243 |
+
assert spans[0].heading_text is None
|
| 244 |
+
assert spans[0].heading_level == 0
|
| 245 |
+
print("PASS: lead-only article -> 1 section span")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def test_section_char_spans_with_headings() -> None:
|
| 249 |
+
text = "Lead paragraph.\n\n# History\nHistory text.\n\n## Origins\nOrigins text.\n"
|
| 250 |
+
spans = find_section_char_spans(text)
|
| 251 |
+
levels_and_titles = [(s.heading_level, s.heading_text) for s in spans]
|
| 252 |
+
assert levels_and_titles == [(0, None), (1, "History"), (2, "Origins")], levels_and_titles
|
| 253 |
+
# The last section ends at end-of-text.
|
| 254 |
+
assert spans[-1].char_end == len(text)
|
| 255 |
+
print("PASS: lead + 2 headings -> 3 section spans")
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def test_section_token_spans_from_offsets() -> None:
|
| 259 |
+
# Two sections at char [0,100) and [100, 200); offsets every 5 chars.
|
| 260 |
+
char_spans = [
|
| 261 |
+
SectionCharSpan(char_start=0, char_end=100, heading_level=0, heading_text=None),
|
| 262 |
+
SectionCharSpan(char_start=100, char_end=200, heading_level=1, heading_text="X"),
|
| 263 |
+
]
|
| 264 |
+
offsets = [(i * 5, i * 5 + 5) for i in range(40)]
|
| 265 |
+
token_spans = section_token_spans_from_offsets(char_spans, offsets)
|
| 266 |
+
assert len(token_spans) == 2
|
| 267 |
+
assert token_spans[0].token_start == 0 and token_spans[0].token_end == 20
|
| 268 |
+
assert token_spans[1].token_start == 20 and token_spans[1].token_end == 40
|
| 269 |
+
print("PASS: char->token span conversion")
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
if __name__ == "__main__":
|
| 273 |
+
test_section_char_spans_lead_only()
|
| 274 |
+
test_section_char_spans_with_headings()
|
| 275 |
+
test_section_token_spans_from_offsets()
|
| 276 |
+
test_single_section_fits_in_one_window()
|
| 277 |
+
test_many_small_sections_pack_into_one_window()
|
| 278 |
+
test_sections_split_across_multiple_windows()
|
| 279 |
+
test_oversized_section_split_into_fragments()
|
| 280 |
+
test_mixed_normal_and_oversized_sections()
|
| 281 |
+
test_pool_section_vectors_recovers_means()
|
| 282 |
+
test_pool_recovers_split_section_via_weighted_mean()
|
| 283 |
+
print("\nALL TESTS PASSED")
|
|
@@ -4,9 +4,10 @@ from __future__ import annotations
|
|
| 4 |
|
| 5 |
import re
|
| 6 |
import struct
|
|
|
|
| 7 |
from dataclasses import dataclass
|
| 8 |
from pathlib import Path
|
| 9 |
-
from typing import
|
| 10 |
|
| 11 |
import numpy as np
|
| 12 |
import pyarrow.parquet as pq
|
|
@@ -18,6 +19,8 @@ file_extensions = {"f16": "f16bin", "f32": "fbin", "i32": "ibin"}
|
|
| 18 |
|
| 19 |
DType = Literal["f16", "f32", "i32"]
|
| 20 |
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@dataclass(frozen=True, slots=True)
|
| 23 |
class Shard:
|
|
@@ -31,6 +34,96 @@ class Shard:
|
|
| 31 |
return f"{self.group:03d}_{self.index:05d}"
|
| 32 |
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def find_snapshot(cache_dir: str | Path) -> Path:
|
| 35 |
cache_dir = Path(cache_dir)
|
| 36 |
snapshots = cache_dir / "datasets--HuggingFaceFW--finewiki" / "snapshots"
|
|
@@ -72,7 +165,7 @@ def iter_articles(
|
|
| 72 |
table = pq.read_table(shard.path, columns=[id_column, text_column])
|
| 73 |
identifiers = table.column(id_column).to_pylist()
|
| 74 |
texts = table.column(text_column).to_pylist()
|
| 75 |
-
for identifier, text in zip(identifiers, texts):
|
| 76 |
yield str(identifier), text or ""
|
| 77 |
|
| 78 |
|
|
|
|
| 4 |
|
| 5 |
import re
|
| 6 |
import struct
|
| 7 |
+
from collections.abc import Iterator
|
| 8 |
from dataclasses import dataclass
|
| 9 |
from pathlib import Path
|
| 10 |
+
from typing import Literal
|
| 11 |
|
| 12 |
import numpy as np
|
| 13 |
import pyarrow.parquet as pq
|
|
|
|
| 19 |
|
| 20 |
DType = Literal["f16", "f32", "i32"]
|
| 21 |
|
| 22 |
+
LFS_POINTER_PREFIX = b"version https://git-lfs"
|
| 23 |
+
|
| 24 |
|
| 25 |
@dataclass(frozen=True, slots=True)
|
| 26 |
class Shard:
|
|
|
|
| 34 |
return f"{self.group:03d}_{self.index:05d}"
|
| 35 |
|
| 36 |
|
| 37 |
+
@dataclass(frozen=True, slots=True)
|
| 38 |
+
class CollectionShard:
|
| 39 |
+
"""A shard of an embedding collection, populated with its row count and the
|
| 40 |
+
row offset that would assign each of its rows a deterministic global flat ID
|
| 41 |
+
(used as the integer key for ground truth, USearch indexes, and any consumer
|
| 42 |
+
that wants to map vectors back to their source article)."""
|
| 43 |
+
|
| 44 |
+
wikiname: str
|
| 45 |
+
stem: str
|
| 46 |
+
path: Path
|
| 47 |
+
row_offset: int
|
| 48 |
+
row_count: int
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def resolve_lfs_pointer(path: Path) -> Path:
|
| 52 |
+
"""If `path` is a Git-LFS pointer file, return the materialized blob in
|
| 53 |
+
`.git/lfs/objects`; otherwise return the path unchanged.
|
| 54 |
+
|
| 55 |
+
Pointer files are tiny ASCII stubs (~133 bytes) with an `oid sha256:<hex>`
|
| 56 |
+
line. Repositories cloned with `GIT_LFS_SKIP_SMUDGE=1` (or with `git lfs
|
| 57 |
+
fetch` only) keep the actual binaries under `.git/lfs/objects/<aa>/<bb>/<oid>`
|
| 58 |
+
while the working tree holds pointers. Reading those blobs in place avoids
|
| 59 |
+
checking out a duplicate copy of the dataset.
|
| 60 |
+
"""
|
| 61 |
+
try:
|
| 62 |
+
if path.stat().st_size > 1024:
|
| 63 |
+
return path
|
| 64 |
+
except OSError:
|
| 65 |
+
return path
|
| 66 |
+
with open(path, "rb") as file:
|
| 67 |
+
head = file.read(256)
|
| 68 |
+
if not head.startswith(LFS_POINTER_PREFIX):
|
| 69 |
+
return path
|
| 70 |
+
oid: str | None = None
|
| 71 |
+
for line in head.decode("ascii", errors="ignore").splitlines():
|
| 72 |
+
if line.startswith("oid sha256:"):
|
| 73 |
+
oid = line.split(":", 1)[1].strip()
|
| 74 |
+
break
|
| 75 |
+
if not oid:
|
| 76 |
+
raise ValueError(f"{path}: looks like an LFS pointer but no sha256 oid line")
|
| 77 |
+
# Walk parents of the resolved path so symlinked working trees still find
|
| 78 |
+
# the original repo's `.git/lfs/objects`.
|
| 79 |
+
for ancestor in path.resolve().parents:
|
| 80 |
+
candidate = ancestor / ".git" / "lfs" / "objects" / oid[:2] / oid[2:4] / oid
|
| 81 |
+
if candidate.is_file():
|
| 82 |
+
return candidate
|
| 83 |
+
raise FileNotFoundError(
|
| 84 |
+
f"{path}: LFS pointer references oid {oid} but no .git/lfs/objects/ contains it; "
|
| 85 |
+
f"run `git lfs fetch` or pass --output to a tree that has the blobs"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def discover_collection(
|
| 90 |
+
model_root: Path, suffix: str = "body"
|
| 91 |
+
) -> list[CollectionShard]:
|
| 92 |
+
"""Walk an embedding collection's per-shard `.f16bin` files in canonical
|
| 93 |
+
order (sorted wikiname, then sorted shard stem), reading each header to
|
| 94 |
+
capture its row count, and return a list of `CollectionShard`s with
|
| 95 |
+
cumulative `row_offset`s assigned.
|
| 96 |
+
|
| 97 |
+
This is the *contract* for the global flat IDs: the i-th row of the n-th
|
| 98 |
+
shard (after this canonical walk) gets ID `shards[n].row_offset + i`.
|
| 99 |
+
Ground truth files, USearch index keys, and any consumer needing a
|
| 100 |
+
deterministic vector-to-article mapping should reproduce this walk.
|
| 101 |
+
"""
|
| 102 |
+
if not model_root.is_dir():
|
| 103 |
+
raise FileNotFoundError(f"no model directory at {model_root}")
|
| 104 |
+
shards: list[CollectionShard] = []
|
| 105 |
+
cumulative = 0
|
| 106 |
+
for wiki_dir in sorted(model_root.iterdir()):
|
| 107 |
+
if not wiki_dir.is_dir():
|
| 108 |
+
continue
|
| 109 |
+
for path in sorted(wiki_dir.glob(f"*.{suffix}.f16bin")):
|
| 110 |
+
stem = path.name[: -len(f".{suffix}.f16bin")]
|
| 111 |
+
blob = resolve_lfs_pointer(path)
|
| 112 |
+
with open(blob, "rb") as file:
|
| 113 |
+
rows, _columns = struct.unpack("<II", file.read(8))
|
| 114 |
+
shards.append(
|
| 115 |
+
CollectionShard(
|
| 116 |
+
wikiname=wiki_dir.name,
|
| 117 |
+
stem=stem,
|
| 118 |
+
path=path,
|
| 119 |
+
row_offset=cumulative,
|
| 120 |
+
row_count=rows,
|
| 121 |
+
)
|
| 122 |
+
)
|
| 123 |
+
cumulative += rows
|
| 124 |
+
return shards
|
| 125 |
+
|
| 126 |
+
|
| 127 |
def find_snapshot(cache_dir: str | Path) -> Path:
|
| 128 |
cache_dir = Path(cache_dir)
|
| 129 |
snapshots = cache_dir / "datasets--HuggingFaceFW--finewiki" / "snapshots"
|
|
|
|
| 165 |
table = pq.read_table(shard.path, columns=[id_column, text_column])
|
| 166 |
identifiers = table.column(id_column).to_pylist()
|
| 167 |
texts = table.column(text_column).to_pylist()
|
| 168 |
+
for identifier, text in zip(identifiers, texts, strict=True):
|
| 169 |
yield str(identifier), text or ""
|
| 170 |
|
| 171 |
|