File size: 4,085 Bytes
229e371 eb00f6e 229e371 eb00f6e 1265d09 229e371 eb00f6e 229e371 1265d09 eb00f6e 229e371 eb00f6e 1265d09 229e371 eb00f6e 1265d09 229e371 1265d09 eb00f6e 1265d09 229e371 eb00f6e 1265d09 229e371 1265d09 229e371 1265d09 229e371 eb00f6e 1265d09 eb00f6e 1265d09 229e371 eb00f6e 229e371 1265d09 eb00f6e 229e371 1265d09 eb00f6e 229e371 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | """Validate the keyed benchmark files: structure, invariants, negatives and reproducibility.
python benchmark/test_keyed.py --data data_keyed [--counts 1 2 4 ...] [--lengths 8]
"""
import argparse
import sys
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
sys.path.insert(0, str(Path(__file__).parent))
from generate_keyed import (CHUNK, COUNTS, KEY_POOL, LENGTH, N_EDIT, N_FAR, SPLITS, VOCAB, chunk_rng, # noqa: E402
generate_chunk, n_other, subset_name)
def load(d, split, n, length=LENGTH):
files = sorted(d.glob(f"{split}-*.parquet"))
assert files and len(files) == int(files[0].stem.split("-of-")[1]), f"{d.name}/{split}: shards missing"
out = {}
for f in files:
t = pq.read_table(f)
m = t.num_rows
cols = {"keys": t["keys"].combine_chunks().flatten().to_numpy().reshape(m, n),
"sequences": t["sequences"].combine_chunks().flatten().flatten().to_numpy().reshape(m, n, length),
"query": t["query"].to_numpy()}
if "candidates" in t.column_names:
cols["candidates"] = t["candidates"].combine_chunks().flatten().flatten().to_numpy().reshape(m, N_EDIT + N_FAR, length)
cols["num_changed"] = t["num_changed"].combine_chunks().flatten().to_numpy().reshape(m, N_EDIT + N_FAR)
for k, v in cols.items():
out.setdefault(k, []).append(v)
return {k: np.concatenate(v) for k, v in out.items()}
def check(d, n, split, length=LENGTH):
x = load(d, split, n, length)
m = len(x["query"])
assert m == SPLITS[split], (split, m)
keys, seqs, query = x["keys"], x["sequences"], x["query"]
assert keys.max() < KEY_POOL and seqs.max() < VOCAB and query.max() < n
sk = np.sort(keys, 1)
assert (sk[:, 1:] != sk[:, :-1]).all(), "keys repeat within a sample"
flat = np.unique(seqs.reshape(m * n, length), axis=0, return_inverse=True)[1].reshape(m, n) # exact at any length
ss = np.sort(flat, 1)
assert (ss[:, 1:] != ss[:, :-1]).all(), "a sample stores the same sequence twice"
# chunk 0 regenerates bit for bit
k0, s0, q0, c0, n0 = generate_chunk(chunk_rng(n, split, 0, length), min(CHUNK, m), n, length)
c = len(q0)
assert (k0 == keys[:c]).all() and (s0 == seqs[:c]).all() and (q0 == query[:c]).all(), "chunk 0 does not regenerate"
msg = ""
if "candidates" in x:
cand, changed = x["candidates"], x["num_changed"]
assert (c0 == cand[:c]).all() and (n0 == changed[:c]).all()
true = seqs[np.arange(m), query]
assert (changed == (cand != true[:, None]).sum(-1)).all()
edits = changed[:, :N_EDIT]
assert (edits >= 1).all(), "an edit negative equals the true sequence"
mean = edits.mean()
expect = 1.0 if length == 1 else 2.0 # one forced + (L-1) x 1/(L-1)
assert abs(mean - expect) < 0.05, f"mean changes {mean} vs {expect}"
k = n_other(n)
same = (cand[:, N_EDIT:, None, :] == seqs[:, None, :, :]).all(-1) # [m, N_FAR, n]
assert (same[:, :k].sum(-1) == 1).all(), "an other-key negative is not exactly one stored sequence"
assert not same[np.arange(m), :k, query].any(), "an other-key negative is the queried sequence"
assert not same[:, k:].any(), "a fresh negative was stored"
msg = f"mean changes (edits) {mean:.4f}; far negatives: {k} other-key, {N_FAR - k} fresh"
else:
assert split == "train"
print(f"[ok] {d.name:<16} {split:<10} {m:>7} samples {msg}", flush=True)
def main():
p = argparse.ArgumentParser()
p.add_argument("--data", default="data_keyed")
p.add_argument("--counts", type=int, nargs="+", default=COUNTS)
p.add_argument("--lengths", type=int, nargs="+", default=[LENGTH])
a = p.parse_args()
for n in a.counts:
for length in a.lengths:
for split in SPLITS:
check(Path(a.data) / subset_name(n, length), n, split, length)
print("ALL CHECKS PASSED")
if __name__ == "__main__":
main()
|