nleroy917 commited on
Commit
ac92beb
·
verified ·
1 Parent(s): 2e535e7

upload queries

Browse files
queries/_checksums.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dense": {
3
+ "rows": 100000,
4
+ "query_text_sha256": "3a354db0c5aa2bcf5d4563844c645d8fc23ff1780f83cce28900b7fc917a5756"
5
+ },
6
+ "sparse": {
7
+ "rows": 10000,
8
+ "query_text_sha256": "fd33c5fe47600b11fe12b7438a342cfa866e2ada82f911726e91c04ad079dfc5"
9
+ },
10
+ "text_filters": {
11
+ "rows": 4953,
12
+ "query_text_sha256": "80d4a77cc3cbed241399fe01525e07987aa886178dcccf943a070a4e2e391fed"
13
+ },
14
+ "structured_filters": {
15
+ "rows": 5000,
16
+ "query_text_sha256": "9023ccb0e1afdda88c20a2d83923102d53b33b989b9ce0f2b11a256a16ae9e83"
17
+ }
18
+ }
queries/_sets.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "set": "dense",
4
+ "file": "gt_dense_k1000.parquet",
5
+ "rows": 100000,
6
+ "columns": [
7
+ "msmarco_config",
8
+ "msmarco_split",
9
+ "msmarco_query_id",
10
+ "hit_scores",
11
+ "hit_fineweb_ids"
12
+ ],
13
+ "regenerate_vectors": "dense"
14
+ },
15
+ {
16
+ "set": "sparse",
17
+ "file": "gt_sparse_k1000.parquet",
18
+ "rows": 10000,
19
+ "columns": [
20
+ "msmarco_config",
21
+ "msmarco_split",
22
+ "msmarco_query_id",
23
+ "hit_scores",
24
+ "hit_fineweb_ids"
25
+ ],
26
+ "regenerate_vectors": "sparse"
27
+ },
28
+ {
29
+ "set": "text_filters",
30
+ "file": "gt_text_filters_k1000.parquet",
31
+ "rows": 4953,
32
+ "columns": [
33
+ "msmarco_config",
34
+ "msmarco_split",
35
+ "msmarco_query_id",
36
+ "hit_scores",
37
+ "hit_fineweb_ids",
38
+ "selectivity_tier",
39
+ "keyword_phrase",
40
+ "domains"
41
+ ],
42
+ "regenerate_vectors": "dense"
43
+ },
44
+ {
45
+ "set": "structured_filters",
46
+ "file": "gt_structured_filters_k1000.parquet",
47
+ "rows": 5000,
48
+ "columns": [
49
+ "msmarco_config",
50
+ "msmarco_split",
51
+ "msmarco_query_id",
52
+ "hit_scores",
53
+ "hit_fineweb_ids",
54
+ "selectivity_tier",
55
+ "structured_group",
56
+ "ls_gte",
57
+ "date_gte",
58
+ "date_lt",
59
+ "dump_set"
60
+ ],
61
+ "regenerate_vectors": "dense"
62
+ }
63
+ ]
queries/gt_dense_k1000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f69daadce2c36f76ee5a2bbfc3d94397a34115ad1685869ae32d8b8db7e1269
3
+ size 2129786818
queries/gt_sparse_k1000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48e9bc62a0af8c0e50c5aa560763e5ed4106d8bd315e761fdb39ea07a3f36863
3
+ size 214140613
queries/gt_structured_filters_k1000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f1ac2bfbda019e067b03ff8b1c3e535eaa8717ef92bec6ed6158b62e1afcb70
3
+ size 110162713
queries/gt_text_filters_k1000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56e3939087a7f2c5b7a450c5daf82dfe02fba903ea6671535a2fd974ddcc8a6b
3
+ size 98190990
queries/scripts/regenerate_all.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reconstruct every distributable set, one file at a time.
3
+
4
+ Each ground-truth file names where its queries live in Hugging Face
5
+ `microsoft/ms_marco` but carries no text and no vectors. This walks the four
6
+ sets in turn and, for each, pulls the queries back, re-embeds them, and joins
7
+ the result to that file's ground truth:
8
+
9
+ gt_<set>_k1000.parquet + Hugging Face -> <set>_regenerated.parquet
10
+
11
+ Run it after downloading the release:
12
+
13
+ python scripts/regenerate_all.py --sets release_sets --out-dir regenerated
14
+
15
+ One set at a time, deliberately: the dense set is 100,000 queries and holding
16
+ four regenerated files at once is needless memory. The MS MARCO download is
17
+ cached across sets in `--cache`, so only the first set that needs a given
18
+ config/split pays for it.
19
+
20
+ Which vectors each set needs is read from `_sets.json`, written alongside the
21
+ files by `build_release_sets.py` — `sparse` needs the mGTE sparse scheme,
22
+ everything else needs dense GTE.
23
+
24
+ Reproducibility: the dense embedding is bit-for-bit reproducible when the same
25
+ query set is embedded in one run (verified over 110,000 queries across two
26
+ independent runs). `SentenceTransformer.encode` length-sorts its input
27
+ internally, so embedding a SUBSET produces different batch composition and
28
+ agrees only to ~1e-7 — irrelevant to ranking, but not bitwise. Do not use
29
+ `--limit` to produce vectors you intend to publish.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import subprocess
37
+ import sys
38
+ from pathlib import Path
39
+
40
+ HERE = Path(__file__).resolve().parent
41
+
42
+
43
+ def main() -> None:
44
+ ap = argparse.ArgumentParser(description=__doc__,
45
+ formatter_class=argparse.RawDescriptionHelpFormatter)
46
+ ap.add_argument("--sets", required=True, help="dir written by build_release_sets.py")
47
+ ap.add_argument("--out-dir", required=True)
48
+ ap.add_argument("--cache", default="data/msmarco_cache")
49
+ ap.add_argument("--device", default=None, help="cuda / cpu (default: auto)")
50
+ ap.add_argument("--only", action="append", help="regenerate just this set; repeatable")
51
+ ap.add_argument("--limit", type=int, default=None,
52
+ help="first N rows per set — SMOKE TESTS ONLY, see the note on "
53
+ "reproducibility above")
54
+ args = ap.parse_args()
55
+
56
+ sets_dir = Path(args.sets)
57
+ manifest_path = sets_dir / "_sets.json"
58
+ if not manifest_path.exists():
59
+ raise SystemExit(f"{manifest_path} not found — run build_release_sets.py first")
60
+ manifest = json.loads(manifest_path.read_text())
61
+ if args.only:
62
+ manifest = [m for m in manifest if m["set"] in args.only]
63
+ if not manifest:
64
+ raise SystemExit(f"no set matches {args.only}")
65
+
66
+ out_dir = Path(args.out_dir)
67
+ out_dir.mkdir(parents=True, exist_ok=True)
68
+ if args.limit is not None:
69
+ print(f"!! --limit {args.limit}: smoke test only, vectors will NOT be "
70
+ f"bit-reproducible\n")
71
+
72
+ done = []
73
+ for i, entry in enumerate(manifest, 1):
74
+ src = sets_dir / entry["file"]
75
+ dst = out_dir / f"{entry['set']}_regenerated.parquet"
76
+ print(f"[{i}/{len(manifest)}] {entry['set']} ({entry['rows']:,} queries, "
77
+ f"vectors={entry['regenerate_vectors']})")
78
+ cmd = [
79
+ sys.executable, str(HERE / "regenerate_queries.py"),
80
+ "--in", str(src), "--out", str(dst),
81
+ "--vectors", entry["regenerate_vectors"],
82
+ "--cache", args.cache, "--keep-raw",
83
+ ]
84
+ if args.device:
85
+ cmd += ["--device", args.device]
86
+ if args.limit is not None:
87
+ cmd += ["--limit", str(args.limit)]
88
+ result = subprocess.run(cmd)
89
+ if result.returncode != 0:
90
+ raise SystemExit(f"{entry['set']} failed (exit {result.returncode})")
91
+ done.append(dst)
92
+ print()
93
+
94
+ print("regenerated:")
95
+ for p in done:
96
+ print(f" {p} ({p.stat().st_size / 1e6:.1f} MB)")
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()
queries/scripts/regenerate_queries.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rebuild the MS MARCO queries + their embeddings for a stripped release file.
3
+
4
+ The released files carry results only. Each row names where its query lives in
5
+ Hugging Face `microsoft/ms_marco` (`msmarco_config` / `msmarco_split` /
6
+ `msmarco_query_id`); this script fetches those queries, re-embeds them with the
7
+ models the ground truth was built with, and joins everything back to the hits.
8
+
9
+ python scripts/regenerate_queries.py \
10
+ --in gt_dense_k1000.parquet \
11
+ --out regenerated/dense_regenerated.parquet \
12
+ --vectors dense
13
+
14
+ Vectors are reproduced with the exact conventions of the original run:
15
+
16
+ dense Alibaba-NLP/gte-multilingual-base via sentence-transformers, plain
17
+ encode() (the model's own ST config ends in a Normalize module, so
18
+ output is unit-norm), float32, no query prefix. Verified against the
19
+ released vectors at cosine >= 0.9999999.
20
+
21
+ sparse mGTE's OFFICIAL sparse scheme: relu of the per-token
22
+ AutoModelForTokenClassification logit, token-id keys, special tokens
23
+ dropped, max-dedup, max_length=8192. Verified to reproduce the
24
+ released sparse vectors exactly (identical token sets, cosine
25
+ 1.0000000).
26
+
27
+ NOTE: sentence-transformers' SparseEncoder does NOT produce this
28
+ scheme for gte -- it attaches a randomly-initialized SPLADE head.
29
+ Neither does `nova embed`, whose sparse backend is that SparseEncoder.
30
+ Do not substitute either one.
31
+
32
+ Only `--vectors none` avoids the torch/sentence-transformers dependency.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import sys
39
+ from pathlib import Path
40
+
41
+ import pyarrow as pa
42
+ import pyarrow.parquet as pq
43
+ import requests
44
+
45
+ DATASETS_SERVER = "https://datasets-server.huggingface.co/parquet"
46
+ DENSE_MODEL = "Alibaba-NLP/gte-multilingual-base"
47
+ SPARSE_MODEL = "Alibaba-NLP/gte-multilingual-base"
48
+ MAX_LENGTH = 8192
49
+
50
+
51
+ # --------------------------------------------------------------------------
52
+ # MS MARCO query text
53
+ # --------------------------------------------------------------------------
54
+ def _download(url: str, dst: Path) -> None:
55
+ dst.parent.mkdir(parents=True, exist_ok=True)
56
+ tmp = dst.with_suffix(dst.suffix + ".part")
57
+ with requests.get(url, stream=True, timeout=600) as r:
58
+ r.raise_for_status()
59
+ with open(tmp, "wb") as fh:
60
+ for chunk in r.iter_content(chunk_size=1 << 22):
61
+ fh.write(chunk)
62
+ tmp.rename(dst)
63
+
64
+
65
+ def load_query_text(
66
+ needed: set[tuple[str, str]], cache: Path, keep_raw: bool
67
+ ) -> dict[tuple[str, str, str], str]:
68
+ """(config, split, query_id) -> query, fetching only the SPLITS needed.
69
+
70
+ Keyed on (config, split) throughout, which matters twice:
71
+
72
+ * Download size. the dense set needs only v2.1/test (204 MB); keying on config
73
+ alone would pull all of v2.1 — 7 train shards plus validation, ~2.1 GB —
74
+ to answer a question none of it can answer.
75
+ * Cache correctness. The cache is written one file per split, so "this
76
+ config has a cache file" does not mean "every split I need is cached".
77
+ Interrupting a download once left later runs convinced they were done,
78
+ failing far away with an unresolved-rows error.
79
+ """
80
+ lookup: dict[tuple[str, str, str], str] = {}
81
+ todo = set(needed)
82
+
83
+ for cfg, split in sorted(needed):
84
+ hit = cache / f"qids_{cfg}_{split}.parquet"
85
+ if hit.exists():
86
+ t = pq.read_table(hit).to_pydict()
87
+ lookup.update(
88
+ ((cfg, split, str(i)), q) for i, q in zip(t["query_id"], t["query"])
89
+ )
90
+ todo.discard((cfg, split))
91
+ print(f" {cfg}/{split}: {len(t['query_id']):,} queries from cache")
92
+
93
+ if todo:
94
+ listing = requests.get(DATASETS_SERVER, params={"dataset": "microsoft/ms_marco"}, timeout=120)
95
+ listing.raise_for_status()
96
+ files = [
97
+ f for f in listing.json()["parquet_files"] if (f["config"], f["split"]) in todo
98
+ ]
99
+ per_split: dict[tuple[str, str], dict[str, str]] = {}
100
+ for f in files:
101
+ raw = cache / "raw" / f"{f['config']}_{f['split']}_{f['filename']}"
102
+ if not raw.exists():
103
+ print(f" downloading {f['config']}/{f['split']}/{f['filename']} "
104
+ f"({f['size']/1e6:.0f} MB)", flush=True)
105
+ _download(f["url"], raw)
106
+ t = pq.read_table(raw, columns=["query_id", "query"]).to_pydict()
107
+ per_split.setdefault((f["config"], f["split"]), {}).update(
108
+ (str(i), q) for i, q in zip(t["query_id"], t["query"])
109
+ )
110
+ if not keep_raw:
111
+ raw.unlink()
112
+ for (cfg, split), m in per_split.items():
113
+ pq.write_table(
114
+ pa.table({"query_id": list(m), "query": list(m.values())}),
115
+ cache / f"qids_{cfg}_{split}.parquet",
116
+ compression="zstd",
117
+ )
118
+ lookup.update(((cfg, split, i), q) for i, q in m.items())
119
+ print(f" {cfg}/{split}: {len(m):,} queries cached")
120
+ return lookup
121
+
122
+
123
+ # --------------------------------------------------------------------------
124
+ # embedding
125
+ # --------------------------------------------------------------------------
126
+ def embed_dense(texts: list[str], batch_size: int, device: str | None):
127
+ from sentence_transformers import SentenceTransformer
128
+
129
+ model = SentenceTransformer(DENSE_MODEL, trust_remote_code=True, device=device)
130
+ return model.encode(texts, batch_size=batch_size, convert_to_numpy=True,
131
+ show_progress_bar=True).astype("float32")
132
+
133
+
134
+ def embed_sparse(texts: list[str], batch_size: int, device: str | None):
135
+ """mGTE official sparse -- see module docstring."""
136
+ import torch
137
+ from transformers import AutoModelForTokenClassification, AutoTokenizer
138
+
139
+ tok = AutoTokenizer.from_pretrained(SPARSE_MODEL)
140
+ model = AutoModelForTokenClassification.from_pretrained(SPARSE_MODEL, trust_remote_code=True)
141
+ dev = device or ("cuda" if torch.cuda.is_available() else "cpu")
142
+ model = model.to(dev).eval()
143
+ specials = set(tok.all_special_ids)
144
+
145
+ out = []
146
+ for start in range(0, len(texts), batch_size):
147
+ chunk = texts[start : start + batch_size]
148
+ enc = tok(chunk, padding=True, truncation=True, max_length=MAX_LENGTH,
149
+ return_tensors="pt").to(dev)
150
+ with torch.no_grad():
151
+ weights = torch.relu(model(**enc).logits).squeeze(-1)
152
+ ids_b = enc["input_ids"].tolist()
153
+ mask_b = enc["attention_mask"].tolist()
154
+ for ids, mask, ws in zip(ids_b, mask_b, weights.tolist()):
155
+ acc: dict[int, float] = {}
156
+ for tid, keep, w in zip(ids, mask, ws):
157
+ if not keep or tid in specials or w <= 0:
158
+ continue
159
+ acc[tid] = max(acc.get(tid, 0.0), w) # max-dedup
160
+ items = sorted(acc.items())
161
+ out.append({"indices": [k for k, _ in items], "values": [v for _, v in items]})
162
+ print(f" sparse {min(start+batch_size, len(texts)):,}/{len(texts):,}",
163
+ end="\r", file=sys.stderr, flush=True)
164
+ print(file=sys.stderr)
165
+ return out
166
+
167
+
168
+ # --------------------------------------------------------------------------
169
+ def main() -> None:
170
+ ap = argparse.ArgumentParser(description=__doc__,
171
+ formatter_class=argparse.RawDescriptionHelpFormatter)
172
+ ap.add_argument("--in", dest="inp", required=True, help="stripped release parquet")
173
+ ap.add_argument("--out", required=True)
174
+ ap.add_argument("--vectors", choices=["dense", "sparse", "both", "none"], default="dense")
175
+ ap.add_argument("--cache", default="data/msmarco_cache")
176
+ ap.add_argument("--keep-raw", action="store_true",
177
+ help="keep the downloaded MS MARCO parquets (~2.1 GB) instead of "
178
+ "deleting them once the small id->query cache is built")
179
+ ap.add_argument("--batch-size", type=int, default=128)
180
+ ap.add_argument("--device", default=None, help="cuda / cpu (default: auto)")
181
+ ap.add_argument("--limit", type=int, default=None, help="first N rows only (smoke test)")
182
+ args = ap.parse_args()
183
+
184
+ src = Path(args.inp)
185
+ pf = pq.ParquetFile(src)
186
+ names = pf.schema_arrow.names
187
+ for required in ("msmarco_config", "msmarco_split", "msmarco_query_id"):
188
+ if required not in names:
189
+ raise SystemExit(f"{src.name} has no `{required}` column -- is it a stripped release file?")
190
+
191
+ prov = pq.read_table(src, columns=["msmarco_config", "msmarco_split", "msmarco_query_id"])
192
+ if args.limit is not None:
193
+ prov = prov.slice(0, args.limit)
194
+ keys = list(zip(prov.column(0).to_pylist(), prov.column(1).to_pylist(), prov.column(2).to_pylist()))
195
+ print(f"{src.name}: {len(keys):,} rows, configs={sorted({k[0] for k in keys})}")
196
+
197
+ cache = Path(args.cache)
198
+ cache.mkdir(parents=True, exist_ok=True)
199
+ lookup = load_query_text({(c, s) for c, s, _ in keys}, cache, args.keep_raw)
200
+
201
+ missing = [k for k in keys if k not in lookup]
202
+ if missing:
203
+ raise SystemExit(f"{len(missing)} rows unresolved, e.g. {missing[:3]}")
204
+ queries = [lookup[k] for k in keys]
205
+ print(f"recovered {len(queries):,} query strings")
206
+
207
+ dense = sparse = None
208
+ if args.vectors in ("dense", "both"):
209
+ print(f"embedding dense with {DENSE_MODEL}")
210
+ dense = embed_dense(queries, args.batch_size, args.device)
211
+ if args.vectors in ("sparse", "both"):
212
+ print(f"embedding sparse with {SPARSE_MODEL} (official mGTE scheme)")
213
+ sparse = embed_sparse(queries, args.batch_size, args.device)
214
+
215
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
216
+ writer = None
217
+ pos = 0
218
+ try:
219
+ for batch in pf.iter_batches(batch_size=2048):
220
+ n = batch.num_rows
221
+ if args.limit is not None and pos >= args.limit:
222
+ break
223
+ if args.limit is not None and pos + n > args.limit:
224
+ batch = batch.slice(0, args.limit - pos)
225
+ n = batch.num_rows
226
+ arrays = list(batch.columns) + [pa.array(queries[pos : pos + n], pa.string())]
227
+ out_names = list(batch.schema.names) + ["query"]
228
+ if dense is not None:
229
+ # float64 to match the released files' `list<double>`: an
230
+ # exact upcast from the float32 the model produces, and the
231
+ # only way `pa.concat_tables([original, regenerated])` works.
232
+ arrays.append(pa.array([r.tolist() for r in dense[pos : pos + n]],
233
+ pa.list_(pa.float64())))
234
+ out_names.append("dense_embedding")
235
+ if sparse is not None:
236
+ # Likewise int64/double, matching the released sparse struct.
237
+ arrays.append(pa.array(sparse[pos : pos + n],
238
+ pa.struct([("indices", pa.list_(pa.int64())),
239
+ ("values", pa.list_(pa.float64()))])))
240
+ out_names.append("sparse_embedding")
241
+ rb = pa.RecordBatch.from_arrays(arrays, names=out_names)
242
+ if writer is None:
243
+ writer = pq.ParquetWriter(args.out, rb.schema, compression="zstd")
244
+ writer.write_batch(rb)
245
+ pos += n
246
+ finally:
247
+ if writer is not None:
248
+ writer.close()
249
+ print(f"wrote {pos:,} rows -> {args.out}")
250
+
251
+
252
+ if __name__ == "__main__":
253
+ main()
queries/scripts/verify_regeneration.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Check that a regenerated file recovered the right MS MARCO queries.
3
+
4
+ python scripts/verify_regeneration.py --sets . --regenerated regenerated/
5
+
6
+ Compares the SHA-256 of the recovered `query` column against the fingerprints
7
+ in `_checksums.json`. This is the check worth running: MS MARCO v1.1 and v2.1
8
+ reuse the same numeric query ids for different queries, so a config mix-up
9
+ returns plausible text for the wrong question and silently corrupts every
10
+ recall number computed from it. The hash catches that on the first row.
11
+
12
+ A mismatch means the join is wrong, not that your embeddings are wrong -- this
13
+ does not check vectors. See the README on reproducibility for those.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import hashlib
20
+ import json
21
+ from pathlib import Path
22
+
23
+ import pyarrow.parquet as pq
24
+
25
+
26
+ def main() -> None:
27
+ ap = argparse.ArgumentParser(description=__doc__,
28
+ formatter_class=argparse.RawDescriptionHelpFormatter)
29
+ ap.add_argument("--sets", default=".", help="bundle dir holding _checksums.json")
30
+ ap.add_argument("--regenerated", required=True, help="dir written by regenerate_all.py")
31
+ args = ap.parse_args()
32
+
33
+ expected = json.loads((Path(args.sets) / "_checksums.json").read_text())
34
+ out_dir = Path(args.regenerated)
35
+
36
+ failures, checked = [], 0
37
+ for name, want in expected.items():
38
+ path = out_dir / f"{name}_regenerated.parquet"
39
+ if not path.exists():
40
+ print(f"{name:19} SKIP (not regenerated)")
41
+ continue
42
+
43
+ pf = pq.ParquetFile(path)
44
+ if "query" not in pf.schema_arrow.names:
45
+ failures.append(f"{name}: no `query` column")
46
+ print(f"{name:19} FAIL no `query` column")
47
+ continue
48
+
49
+ h, rows = hashlib.sha256(), 0
50
+ for batch in pf.iter_batches(batch_size=8192, columns=["query"]):
51
+ for q in batch.column(0).to_pylist():
52
+ h.update(q.encode())
53
+ h.update(b"\0")
54
+ rows += 1
55
+
56
+ checked += 1
57
+ if rows != want["rows"]:
58
+ failures.append(f"{name}: {rows:,} rows, expected {want['rows']:,}")
59
+ print(f"{name:19} FAIL {rows:,} rows, expected {want['rows']:,}")
60
+ elif h.hexdigest() != want["query_text_sha256"]:
61
+ failures.append(f"{name}: query text does not match")
62
+ print(f"{name:19} FAIL query text mismatch -- wrong config/split, "
63
+ f"or rows reordered")
64
+ else:
65
+ print(f"{name:19} ok {rows:,} rows")
66
+
67
+ if failures:
68
+ raise SystemExit(f"\n{len(failures)} set(s) failed:\n " + "\n ".join(failures))
69
+ if checked == 0:
70
+ raise SystemExit("\nnothing checked -- is --regenerated pointing at the right dir?")
71
+ print(f"\n{checked} set(s) verified")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()