Ash Vardanian commited on
Commit
a66ce43
·
1 Parent(s): cd0fc73

Improve: Consolidate scripts and package into single-file modules

Browse files
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. .gitignore +6 -0
  3. README.md +43 -40
  4. embed.py +196 -0
  5. wikiverse.py +114 -0
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.f16bin filter=lfs diff=lfs merge=lfs -text
.gitignore CHANGED
@@ -205,3 +205,9 @@ cython_debug/
205
  marimo/_static/
206
  marimo/_lsp/
207
  __marimo__/
 
 
 
 
 
 
 
205
  marimo/_static/
206
  marimo/_lsp/
207
  __marimo__/
208
+
209
+ # WikiVerse-specific: deprecated (binary files now tracked via Git LFS)
210
+ data/
211
+ state/
212
+ benchmarks/results/
213
+ logs/
README.md CHANGED
@@ -92,64 +92,67 @@ Average article length across all languages is ~400 tokens, but this is dragged
92
 
93
  ## Dataset Layout
94
 
95
- Data is published on HuggingFace with one __config per model__, so users download only what they need.
96
- Embedding vectors are stored as `.fbin` (row-major binary: `uint32 rows, uint32 cols, float16/float32 data`) for direct compatibility with [USearch bench_cpp](https://github.com/unum-cloud/usearch/blob/main/BENCHMARKS.md) and the Big-ANN benchmark ecosystem.
 
 
 
 
 
97
 
98
  ```
99
  unum-cloud/WikiVerse/
100
  ├── README.md
 
 
 
 
101
 
102
- ├── corpus/
103
- │ ├── passages-en-00000-of-00050.parquet # doc_id, title, text, section
104
- │ ├── passages-en-00001-of-00050.parquet
105
- ── ...
106
-
107
- ├── graph/
108
- ── pagelinks-en.parquet # source_id, target_id
109
- │ ├── categories-en.parquet # page_id, category
110
- ── wikidata-en.parquet # page_id, qid, entity_type
111
- │ └── ...
112
-
113
- ├── qwen3-embedding-0.6b/
114
- │ ├── base.6.6M.f16bin # 6.6M × 1024, float16
115
- │ ├── query.10K.f16bin # 10K × 1024, float16
116
- │ └── groundtruth.10K.ibin # 10K × 100 neighbors
117
 
118
- ├── e5-mistral-7b-instruct/
119
- ── base.6.6M.f16bin # 6.6M × 4096, float16
120
- │ ├── query.10K.f16bin
121
- │ └── groundtruth.10K.ibin
122
 
123
- ├── arctic-embed-l-v2.0/
124
- ── base.6.6M.f16bin # 6.6M × 1024, float16
125
- │ ├── query.10K.f16bin
126
- │ └── groundtruth.10K.ibin
127
 
128
- ├── nomic-embed-text-v1.5/
129
- ── base.6.6M.f16bin # 6.6M × 768, float16
130
- │ ├── query.10K.f16bin
131
- │ └── groundtruth.10K.ibin
132
 
133
- └── gte-moderncolbert-v1/
134
- ── base.6.6M.f16bin # ~13.2B × 128, float16
135
- ├── query.10K.f16bin
136
- └── groundtruth.10K.ibin
 
 
 
 
 
137
  ```
138
 
139
- Load a specific model's embeddings:
140
 
141
  ```python
142
- from datasets import load_dataset
143
- corpus = load_dataset("unum-cloud/WikiVerse", "corpus")
 
144
  ```
145
 
146
- Or download binary vectors directly for C++/Rust benchmarking:
147
 
148
  ```sh
149
  huggingface-cli download unum-cloud/WikiVerse \
150
- qwen3-embedding-0.6b/base.6.6M.f16bin \
151
- qwen3-embedding-0.6b/query.10K.f16bin \
152
- qwen3-embedding-0.6b/groundtruth.10K.ibin
153
  ```
154
 
155
  ### Workflow
 
92
 
93
  ## Dataset Layout
94
 
95
+ Layout mirrors [FineWiki's](https://huggingface.co/datasets/HuggingFaceFW/finewiki) `data/<wiki>/<group>_<shard>.parquet` structure: one directory per Wikipedia language, with shard filenames preserved 1:1.
96
+ Each `.f16bin` is row-aligned with its source parquet `.f16bin` row N is the embedding of parquet row N, in native order.
97
+ If the source text was empty or null the row is a zero vector (`norm == 0`); the parquet's `id` column provides the doc identifier, so no separate ids file is needed.
98
+
99
+ Binary format: `u32` rows count, `u32` columns count, then `rows × cols` little-endian `f16` values — directly compatible with [USearch](https://github.com/unum-cloud/USearch)'s and the Big-ANN benchmark ecosystem.
100
+
101
+ `.body.f16bin` is the article-body embedding; `.title.f16bin` is the title-only embedding (short-context, useful for title-vs-body retrieval studies).
102
 
103
  ```
104
  unum-cloud/WikiVerse/
105
  ├── README.md
106
+ ├── LICENSE
107
+ ├── .gitattributes
108
+ ├── wikiverse.py # consumer module: load_lang, read_bin, ...
109
+ ├── embed.py # reference embedding pipeline (TEI-based)
110
 
111
+ ├── qwen3-embedding-0.6b/ # 1024-dim, decoder, float16
112
+ │ ├── enwiki/
113
+ ├── 000_00000.body.f16bin # mirrors enwiki/000_00000.parquet
114
+ │ ├── 000_00000.title.f16bin
115
+ │ ├── 000_00001.body.f16bin
116
+ │ │ ├── 000_00001.title.f16bin
117
+ │ └── ...
118
+ │ ├── dewiki/
119
+ │ └── ...
120
+ │ └── ... # one dir per Wikipedia language
 
 
 
 
 
121
 
122
+ ├── snowflake-arctic-embed-l-v2.0/ # 1024-dim, encoder, float16
123
+ ── <wiki>/<group>_<shard>.{body,title}.f16bin
 
 
124
 
125
+ ├── nomic-embed-text-v1.5/ # 768-dim, encoder, float16
126
+ ── <wiki>/<group>_<shard>.{body,title}.f16bin
 
 
127
 
128
+ ├── e5-mistral-7b-instruct/ # 4096-dim, decoder, float16 (planned)
129
+ ── <wiki>/<group>_<shard>.{body,title}.f16bin
 
 
130
 
131
+ └── gte-moderncolbert-v1/ # 128-dim per token, ColBERT (planned)
132
+ ── <wiki>/<group>_<shard>.{body,title}.f16bin
133
+ ```
134
+
135
+ Binary embedding files are tracked via [Git LFS](https://git-lfs.com).
136
+ To clone the repo without downloading the binaries (~600 GB):
137
+
138
+ ```sh
139
+ GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/unum-cloud/WikiVerse
140
  ```
141
 
142
+ Load embeddings for a single language (Python):
143
 
144
  ```python
145
+ from wikiverse import read_bin
146
+ mat = read_bin("qwen3-embedding-0.6b/enwiki/000_00000.body.f16bin", dtype="f16")
147
+ # mat.shape == (n_articles_in_shard, 1024)
148
  ```
149
 
150
+ Or pull just one model's embeddings for a single language:
151
 
152
  ```sh
153
  huggingface-cli download unum-cloud/WikiVerse \
154
+ --repo-type dataset \
155
+ --include "qwen3-embedding-0.6b/enwiki/*"
 
156
  ```
157
 
158
  ### Workflow
embed.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Embed FineWiki shards via a running TEI server.
2
+
3
+ Usage:
4
+ python embed.py --cache-dir /path/to/hf-cache --output /path/to/embeddings \\
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
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import asyncio
14
+ import time
15
+ from pathlib import Path
16
+
17
+ import httpx
18
+ import numpy as np
19
+
20
+ from wikiverse import Shard, load_lang, load_shard_texts, write_bin
21
+
22
+
23
+ def select_shards(all_shards: list[Shard], gpu_id: int, world_size: int) -> list[Shard]:
24
+ return [
25
+ shard for index, shard in enumerate(all_shards) if index % world_size == gpu_id
26
+ ]
27
+
28
+
29
+ async def embed_texts(
30
+ client: httpx.AsyncClient,
31
+ url: str,
32
+ texts: list[str],
33
+ batch_size: int,
34
+ concurrency: int,
35
+ character_cap: int,
36
+ dimensions: int,
37
+ ) -> tuple[np.ndarray, dict[str, float]]:
38
+ """Embed `texts` via TEI in input order; empty inputs map to zero rows."""
39
+ semaphore = asyncio.Semaphore(concurrency)
40
+ output = np.zeros((len(texts), dimensions), dtype=np.float16)
41
+
42
+ nonempty_indices = [index for index, text in enumerate(texts) if text]
43
+ truncated = [texts[index][:character_cap] for index in nonempty_indices]
44
+ received: list[list[float] | None] = [None] * len(truncated)
45
+
46
+ async def submit(start: int) -> None:
47
+ end = min(start + batch_size, len(truncated))
48
+ chunk = truncated[start:end]
49
+ async with semaphore:
50
+ response = await client.post(
51
+ url, json={"inputs": chunk, "truncate": True}, timeout=600.0
52
+ )
53
+ response.raise_for_status()
54
+ vectors = response.json()
55
+ for offset, vector in enumerate(vectors):
56
+ received[start + offset] = vector
57
+
58
+ started = time.monotonic()
59
+ if truncated:
60
+ await asyncio.gather(
61
+ *(submit(index) for index in range(0, len(truncated), batch_size))
62
+ )
63
+ elapsed = time.monotonic() - started
64
+
65
+ for received_index, vector in enumerate(received):
66
+ output[nonempty_indices[received_index]] = np.asarray(vector, dtype=np.float16)
67
+
68
+ return output, {
69
+ "embed_seconds": elapsed,
70
+ "n_docs": len(texts),
71
+ "n_nonempty": len(truncated),
72
+ }
73
+
74
+
75
+ async def run(args: argparse.Namespace) -> None:
76
+ output_root = Path(args.output) / args.model_subdir
77
+ output_root.mkdir(parents=True, exist_ok=True)
78
+
79
+ suffix = f".{args.output_suffix}" if args.output_suffix else ""
80
+
81
+ shards = load_lang(args.cache_dir, args.wiki)
82
+ owned = select_shards(shards, args.gpu_id, args.world_size)
83
+ pending = [
84
+ shard
85
+ for shard in owned
86
+ if not (output_root / shard.wikiname / f"{shard.stem}{suffix}.f16bin").exists()
87
+ ]
88
+ print(
89
+ f"[gpu{args.gpu_id} TEI col={args.text_column} suffix='{args.output_suffix}'] "
90
+ f"{len(owned)} owned, {len(pending)} pending @ {args.url}",
91
+ flush=True,
92
+ )
93
+ if not pending:
94
+ return
95
+
96
+ started = time.monotonic()
97
+ total_docs = 0
98
+
99
+ async with httpx.AsyncClient() as probe:
100
+ try:
101
+ response = await probe.get(
102
+ args.url.rsplit("/", 1)[0] + "/health", timeout=10.0
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:
110
+ wiki_dir = output_root / shard.wikiname
111
+ wiki_dir.mkdir(parents=True, exist_ok=True)
112
+ vector_path = wiki_dir / f"{shard.stem}{suffix}.f16bin"
113
+
114
+ _identifiers, texts = load_shard_texts(shard, text_column=args.text_column)
115
+ if not texts:
116
+ np.zeros((0, args.dimensions), dtype=np.float16).tofile(vector_path)
117
+ continue
118
+
119
+ embeddings, stats = await embed_texts(
120
+ client,
121
+ args.url,
122
+ texts,
123
+ batch_size=args.batch_size,
124
+ concurrency=args.concurrency,
125
+ character_cap=args.character_cap,
126
+ dimensions=args.dimensions,
127
+ )
128
+ if embeddings.shape != (len(texts), args.dimensions):
129
+ raise RuntimeError(
130
+ f"shape {embeddings.shape} != ({len(texts)}, {args.dimensions})"
131
+ )
132
+
133
+ temp_path = vector_path.with_suffix(vector_path.suffix + ".tmp")
134
+ write_bin(temp_path, embeddings, dtype="f16")
135
+ temp_path.rename(vector_path)
136
+
137
+ total_docs += stats["n_docs"]
138
+ docs_per_second = stats["n_docs"] / max(stats["embed_seconds"], 1e-3)
139
+ print(
140
+ f"[gpu{args.gpu_id} TEI] {shard.wikiname}/{shard.stem}{suffix}: "
141
+ f"{stats['n_docs']} docs ({stats['n_nonempty']} non-empty) "
142
+ f"in {stats['embed_seconds']:.1f}s -> {docs_per_second:.0f} doc/s",
143
+ flush=True,
144
+ )
145
+
146
+ wall_seconds = time.monotonic() - started
147
+ print(
148
+ f"[gpu{args.gpu_id} TEI] DONE: {total_docs} docs in {wall_seconds:.0f}s "
149
+ f"-> {total_docs/max(wall_seconds,1):.0f} doc/s",
150
+ flush=True,
151
+ )
152
+
153
+
154
+ def main() -> None:
155
+ parser = argparse.ArgumentParser()
156
+ parser.add_argument("--cache-dir", default="/home/ubuntu/wikiverse-data/hf-cache")
157
+ parser.add_argument("--output", default="/home/ubuntu/wikiverse-data/embeddings")
158
+ parser.add_argument("--gpu-id", type=int, default=0)
159
+ parser.add_argument("--world-size", type=int, default=8)
160
+ parser.add_argument(
161
+ "--wiki", required=True, help="single language code (enwiki, dewiki, etc)"
162
+ )
163
+ parser.add_argument("--url", default="http://localhost:8080/embed")
164
+ parser.add_argument(
165
+ "--batch-size", type=int, default=32, help="docs per HTTP request"
166
+ )
167
+ parser.add_argument("--concurrency", type=int, default=8)
168
+ parser.add_argument("--text-column", default="text", choices=["text", "title"])
169
+ parser.add_argument(
170
+ "--character-cap",
171
+ type=int,
172
+ default=16384,
173
+ help="truncate each input at this many characters (~max_length × 4 for English)",
174
+ )
175
+ parser.add_argument(
176
+ "--output-suffix",
177
+ default="body",
178
+ help="filename suffix, e.g. 'body' or 'title'",
179
+ )
180
+ parser.add_argument(
181
+ "--model-subdir",
182
+ default="qwen3-embedding-0.6b",
183
+ help="output goes to {output}/{model-subdir}/, e.g. snowflake-arctic-embed-l-v2.0",
184
+ )
185
+ parser.add_argument(
186
+ "--dimensions",
187
+ type=int,
188
+ default=1024,
189
+ help="embedding dimensionality (1024 Qwen3/arctic, 768 nomic, 4096 e5-mistral)",
190
+ )
191
+ args = parser.parse_args()
192
+ asyncio.run(run(args))
193
+
194
+
195
+ if __name__ == "__main__":
196
+ main()
wikiverse.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WikiVerse: embeddings for FineWiki articles and titles."""
2
+
3
+ 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 Iterator, Literal
10
+
11
+ import numpy as np
12
+ import pyarrow.parquet as pq
13
+
14
+ shard_pattern = re.compile(r"(\d{3})_(\d{5})\.parquet$")
15
+
16
+ numpy_dtypes = {"f16": np.float16, "f32": np.float32, "i32": np.int32}
17
+ 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:
24
+ wikiname: str
25
+ group: int
26
+ index: int
27
+ path: Path
28
+
29
+ @property
30
+ def stem(self) -> str:
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"
37
+ if not snapshots.is_dir():
38
+ raise FileNotFoundError(f"no FineWiki snapshot under {snapshots}")
39
+ return max(snapshots.iterdir(), key=lambda path: path.stat().st_mtime)
40
+
41
+
42
+ def load_lang(cache_dir: str | Path, wikiname: str) -> list[Shard]:
43
+ """Discover all FineWiki shards for a single language."""
44
+ data_root = find_snapshot(cache_dir) / "data"
45
+ wiki_dir = data_root / wikiname
46
+ if not wiki_dir.is_dir():
47
+ raise FileNotFoundError(f"no shard directory for {wikiname}")
48
+ shards: list[Shard] = []
49
+ for parquet_path in sorted(wiki_dir.glob("*.parquet")):
50
+ match = shard_pattern.search(parquet_path.name)
51
+ if not match:
52
+ continue
53
+ shards.append(
54
+ Shard(
55
+ wikiname=wikiname,
56
+ group=int(match.group(1)),
57
+ index=int(match.group(2)),
58
+ path=parquet_path,
59
+ )
60
+ )
61
+ return shards
62
+
63
+
64
+ def iter_articles(
65
+ shard: Shard, text_column: str = "text", id_column: str = "id"
66
+ ) -> Iterator[tuple[str, str]]:
67
+ """Yield (id, text) tuples from a parquet shard, in parquet row order.
68
+
69
+ Empty/null texts pass through as empty string — embedders should write
70
+ zero vectors so row N in .f16bin aligns with parquet row N.
71
+ """
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
+
79
+ def load_shard_texts(
80
+ shard: Shard, text_column: str = "text", id_column: str = "id"
81
+ ) -> tuple[list[str], list[str]]:
82
+ """Load a whole shard into parallel lists (ids, texts), parquet row order preserved."""
83
+ identifiers: list[str] = []
84
+ texts: list[str] = []
85
+ for identifier, text in iter_articles(
86
+ shard, text_column=text_column, id_column=id_column
87
+ ):
88
+ identifiers.append(identifier)
89
+ texts.append(text)
90
+ return identifiers, texts
91
+
92
+
93
+ def write_bin(path: str | Path, matrix: np.ndarray, dtype: DType) -> None:
94
+ """Write a 2-D matrix to a binary file with a `uint32 rows, uint32 cols` header."""
95
+ if matrix.ndim != 2:
96
+ raise ValueError(f"expected 2-D matrix, got shape {matrix.shape}")
97
+ matrix = np.ascontiguousarray(matrix.astype(numpy_dtypes[dtype], copy=False))
98
+ rows, columns = matrix.shape
99
+ with open(path, "wb") as file:
100
+ file.write(struct.pack("<II", rows, columns))
101
+ file.write(matrix.tobytes(order="C"))
102
+
103
+
104
+ def read_bin(path: str | Path, dtype: DType) -> np.ndarray:
105
+ """Read a 2-D matrix from a binary file with a `uint32 rows, uint32 cols` header."""
106
+ with open(path, "rb") as file:
107
+ rows, columns = struct.unpack("<II", file.read(8))
108
+ return np.frombuffer(file.read(), dtype=numpy_dtypes[dtype]).reshape(
109
+ rows, columns
110
+ )
111
+
112
+
113
+ def shard_filename(stem: str, dtype: DType) -> str:
114
+ return f"{stem}.{file_extensions[dtype]}"