MaterialsSaddles / scripts /dedup /v2_verify.py
sunghjung3's picture
Merge v2-dedup (77d73af) into main, part 12
46709a8 verified
Raw History Blame Contribute Delete
9.37 kB
"""v2 step 4: exhaustive verification of the written release (read-only, independent of v2_write.py's logic).
For EVERY output shard <out>/<subset>/<fold>/*.aselmdb:
* LMDB keys are exactly "1".."N" plus "nextid"; nextid decodes to N+1 and its bytes equal what ase_db_backends writes;
* N is a multiple of 3 and <= 3 * per_shard; rows decode; row i+1 (1-based key) holds, in ascending ms_id order,
complete triplets (ms % 3 = 0, 1, 2 consecutive);
* sha1 of every stored value equals the sha1 of the SciLM row with the same ms_id (byte-identical copy).
Across shards:
* every ms_id appears once; per subset/fold the ms_id set equals <split_dir>/<subset>/<fold>.parquet minus the
BROKEN triplets exactly;
* the union equals the kept triplets of duplicates.parquet (representative == itself) minus BROKEN, no removed or
BROKEN triplet appears.
ASE-level spot check on a random sample: row read with ase.db equals the SciLM row read with ase.db
(numbers, positions, cell, pbc, constraints, energy, forces, key_value_pairs, data), and every shard opens in
fairchem's AseDBDataset.
usage: v2_verify.py <out_root> <scilm_root> <scilm_index_dir> <split_dir> <duplicates.parquet> <meta_dir> [per_shard] [workers] [subsets]
"""
import glob, hashlib, os, sys, zlib
import numpy as np, pyarrow.parquet as pq
from multiprocessing import Pool
from ase.io.jsonio import decode, encode
out, src_root, idx_dir, split_dir, dup_file, meta_dir = sys.argv[1:7]
per = int(sys.argv[7]) if len(sys.argv) > 7 else 50000; nw = int(sys.argv[8]) if len(sys.argv) > 8 else 48
SUBS = sys.argv[9].split(",") if len(sys.argv) > 9 else ["lemat", "mp20bat", "oc20", "oc22"]; FOLDS = ["train", "val", "test"]
# saddle ms_ids of the 2 broken triplets that v2_write.py leaves out, and the files that therefore hold fewer
# triplets (file name -> triplets left out)
BROKEN = [35584423, 79800988]
SHORT = {"lemat_train_0213.aselmdb": 1, "lemat_train_0479.aselmdb": 1}
def check_shard(path):
import lmdb
env = lmdb.open(path, subdir=False, readonly=True, lock=False, readahead=True, meminit=False)
prob = []; ms = []; raw = []
with env.begin() as t:
keys = [k for k, _ in t.cursor()]
nk = [k for k in keys if k != b"nextid"]; N = len(nk)
if sorted(int(k) for k in nk) != list(range(1, N + 1)) or not all(k.isdigit() for k in nk): prob.append("keys not 1..N")
nv = t.get(b"nextid")
if nv is None or decode(zlib.decompress(nv).decode()) != N + 1: prob.append("nextid wrong")
elif nv != zlib.compress(bytes(encode(N + 1), "utf-8")): prob.append("nextid bytes differ from ase_db_backends encoding")
if N % 3 or N > 3 * per or N == 0: prob.append(f"row count {N}")
for i in range(1, N + 1):
v = t.get(str(i).encode()); d = decode(zlib.decompress(v).decode())
ms.append(int(d["key_value_pairs"]["ms_id"])); raw.append(hashlib.sha1(v).digest())
env.close()
ms = np.array(ms, np.int64)
if not (np.diff(ms) > 0).all(): prob.append("ms_id not strictly ascending")
if N % 3 == 0 and N:
t3 = ms.reshape(-1, 3)
if not ((t3[:, 0] % 3 == 0) & (t3[:, 1] == t3[:, 0] + 1) & (t3[:, 2] == t3[:, 0] + 2)).all(): prob.append("rows not complete R,S,P triplets")
return path, ms, np.frombuffer(b"".join(raw), "S20"), prob
def load_index(s):
Z = [np.load(f) for f in sorted(glob.glob(f"{idx_dir}/{s}__*.npz"))]
ms = np.concatenate([z["ms"] for z in Z]); raw = np.concatenate([z["raw"] for z in Z])
key = np.concatenate([z["key"] for z in Z]); sh = np.concatenate([np.full(len(z["ms"]), str(z["shard"]), object) for z in Z])
o = np.argsort(ms); return ms[o], raw[o], key[o], sh[o]
if __name__ == "__main__":
files = sorted(p for s in SUBS for p in glob.glob(f"{out}/{s}/*/*.aselmdb"))
stray = [p for p in glob.glob(f"{out}/**/*", recursive=True) if os.path.isfile(p) and not p.endswith(".aselmdb")]
print(f"{len(files)} shards; non-shard files under the data dirs: {[os.path.relpath(p, out) for p in stray if '/' in os.path.relpath(p, out)]}", flush=True)
res = {}
with Pool(nw) as pool:
for n, (p, ms, raw, prob) in enumerate(pool.imap_unordered(check_shard, files), 1):
res[p] = (ms, raw, prob)
if prob: print(" PROBLEM", p, prob, flush=True)
if n % 50 == 0: print(f" {n}/{len(files)} shards read", flush=True)
bad = sum(bool(r[2]) for r in res.values())
D = pq.read_table(dup_file); dms = np.asarray(D.column(0)); drep = np.asarray(D.column(1))
M = [np.load(f) for f in sorted(glob.glob(f"{meta_dir}/*.npz"))]
mms = np.concatenate([m["ms"] for m in M]); msub = np.concatenate([m["sub"] for m in M]); sub_of = dict(zip(mms.tolist(), msub.tolist()))
ALL = ["lemat", "mp20bat", "oc20", "oc22"]; tot_ok = bad == 0; obs_file, obs_n, obs_ms = [], [], []
for s in SUBS:
ims, iraw, ikey, ish = load_index(s)
seen = []
for f in FOLDS:
fs = [p for p in files if p.startswith(f"{out}/{s}/{f}/")]
ms = np.concatenate([res[p][0] for p in fs]) if fs else np.array([], np.int64)
raw = np.concatenate([res[p][1] for p in fs]) if fs else np.array([], "S20")
want = np.sort(np.asarray(pq.read_table(f"{split_dir}/{s}/{f}.parquet").column("ms_id")))
want = want[~np.isin(want // 3, np.array(BROKEN) // 3)]
same = np.array_equal(np.sort(ms), want)
pos = np.searchsorted(ims, ms); okpos = (pos < len(ims)) & (ims[np.minimum(pos, len(ims) - 1)] == ms)
bytes_ok = okpos.all() and bool((iraw[pos] == raw).all())
# shards of a fold: named _0000.._NNNN, consecutive ms_id ranges in name order, all but the last full
# (a file in SHORT holds per minus its removed triplets)
names_ok = [os.path.basename(p) for p in fs] == [f"{s}_{f}_{k:04d}.aselmdb" for k in range(len(fs))]
order_ok = all(res[fs[k]][0][-1] < res[fs[k + 1]][0][0] for k in range(len(fs) - 1))
full_ok = all(len(res[p][0]) == 3 * (per - SHORT.get(os.path.basename(p), 0)) for p in fs[:-1])
print(f"{s}/{f}: {len(fs)} shards, {len(ms)//3} triplets; equals split file {same}; every row byte-identical to SciLM {bytes_ok}; "
f"names consecutive {names_ok}, shards in ms_id order {order_ok}, all but last full {full_ok}", flush=True)
tot_ok &= same and bytes_ok and names_ok and order_ok and full_ok; seen.append(ms)
for p in fs: obs_file.append(os.path.relpath(p, out)); obs_n.append(len(res[p][0])); obs_ms.append(res[p][0])
seen = np.concatenate(seen); sad = seen[seen % 3 == 1]
kept = np.sort(np.array([m for m, r in zip(dms.tolist(), drep.tolist()) if m == r and m not in BROKEN and ALL[sub_of[m]] == s], np.int64))
rem = set(m for m, r in zip(dms.tolist(), drep.tolist()) if (m != r or m in BROKEN) and ALL[sub_of[m]] == s)
u = len(np.unique(seen)) == len(seen); eqk = np.array_equal(np.sort(sad), kept); nrem = len(rem & set(sad.tolist()))
print(f"{s}: every ms_id once {u}; saddles == kept set of duplicates.parquet {eqk} ({len(kept)}); removed or broken triplets present {nrem}", flush=True)
tot_ok &= u and eqk and nrem == 0
# ASE-level spot check against the SciLM source
from ase.db import connect
rng = np.random.default_rng(0); fs = [p for p in files if p.startswith(f"{out}/{s}/")]
nchk = 0; nbad = 0
for p in rng.choice(fs, size=min(8, len(fs)), replace=False):
db = connect(p, type="aselmdb", readonly=True); n = db.count()
for i in rng.choice(np.arange(1, n + 1), size=min(25, n), replace=False):
a = db.get(id=int(i)); m = int(a.key_value_pairs["ms_id"]); j = np.searchsorted(ims, m)
b = connect(f"{src_root}/{ish[j]}", type="aselmdb", readonly=True).get(id=int(ikey[j]))
same = (np.array_equal(a.numbers, b.numbers) and np.array_equal(a.positions, b.positions) and np.array_equal(a.cell, b.cell)
and np.array_equal(a.pbc, b.pbc) and a.energy == b.energy and np.array_equal(a.forces, b.forces)
and a.key_value_pairs == b.key_value_pairs and encode(a.data) == encode(b.data)
and [c.todict() for c in a.constraints] == [c.todict() for c in b.constraints])
nchk += 1; nbad += not same
print(f"{s}: ASE-level spot check {nchk} rows, mismatching {nbad}", flush=True); tot_ok &= nbad == 0
try:
from fairchem.core.datasets import AseDBDataset
for p in fs[:3] + fs[-2:]:
ds = AseDBDataset({"src": p}); _ = ds.get_atoms(0); _ = ds.get_atoms(len(ds) - 1)
print(f"{s}: fairchem AseDBDataset opens and reads sample shards OK", flush=True)
except Exception as e:
print(f"{s}: fairchem AseDBDataset FAILED: {e!r}", flush=True); tot_ok = False
# what was observed in the files (row k of a shard has LMDB key / ASE id k+1) -> input of the metadata table
np.savez(f"{os.path.dirname(os.path.abspath(out))}/observed_{os.path.basename(os.path.abspath(out))}.npz",
shard=np.array(obs_file), n=np.array(obs_n), ms=np.concatenate(obs_ms), passed=tot_ok)
print("ALL CHECKS PASSED" if tot_ok else "*** VERIFICATION FAILED ***")