Datasets:
Download scripts/dedup/v2_write.py from SciLM/MaterialsSaddles: direct link, hf CLI and curl.
- Browser
- Download file 5.05 kB
-
https://huggingface.co/datasets/SciLM/MaterialsSaddles/resolve/main/scripts/dedup/v2_write.py
- Command line
-
hf download hf://datasets/SciLM/MaterialsSaddles/scripts/dedup/v2_write.py
-
curl -L -o v2_write.py https://huggingface.co/datasets/SciLM/MaterialsSaddles/resolve/main/scripts/dedup/v2_write.py
5.05 kB
| """v2 step 3: write the deduplicated, split release by copying stored rows byte for byte. | |
| Every kept triplet (fold from <split_dir>/<subset>/{train,val,test}.parquet) is written to | |
| <out>/<subset>/<fold>/<subset>_<fold>_<NNNN>.aselmdb | |
| in ascending ms_id order (R, S, P rows of a triplet adjacent), at most <per_shard> triplets per file. The files are | |
| cut on the full split list, and then the BROKEN triplets are left out, so lemat_train_0213 and lemat_train_0479 | |
| hold per_shard - 1 triplets and the other files do not change. Rows are NOT | |
| re-serialised: the zlib-compressed JSON value stored in the SciLM shard is copied unchanged under a new LMDB key | |
| ("1".."3n"; the id is not part of the stored value), then "nextid" = 3n+1 is written exactly as ase_db_backends does. | |
| Each file is written as <name>.tmp and renamed only after its transaction committed. | |
| usage: v2_write.py <scilm_root> <scilm_index_dir> <split_dir> <out_root> [per_shard=50000] [workers=48] [subsets] | |
| """ | |
| import glob, os, sys, zlib, json | |
| import numpy as np, pyarrow.parquet as pq | |
| from ase.io.jsonio import encode | |
| from multiprocessing import Pool | |
| FOLDS = ["train", "val", "test"] | |
| src_root, idx_dir, split_dir, out = sys.argv[1:5] | |
| per = int(sys.argv[5]) if len(sys.argv) > 5 else 50000; nw = int(sys.argv[6]) if len(sys.argv) > 6 else 48 | |
| SUBS = sys.argv[7].split(",") if len(sys.argv) > 7 else ["lemat", "mp20bat", "oc20", "oc22"] | |
| # saddle ms_ids of the 2 lemat triplets with broken forces (max |F| at the saddle 4.78e11 and 1.02e8 eV/A), found | |
| # after the split was drawn. They stay in the split lists, so that the file cuts do not move, and are not written. | |
| BROKEN = [35584423, 79800988] | |
| def load_index(s): | |
| Z = [np.load(f) for f in sorted(glob.glob(f"{idx_dir}/{s}__*.npz"))] | |
| shards = [str(z["shard"]) for z in Z] | |
| ms = np.concatenate([z["ms"] for z in Z]); key = np.concatenate([z["key"] for z in Z]) | |
| fi = np.concatenate([np.full(len(z["ms"]), i, np.int32) for i, z in enumerate(Z)]) | |
| o = np.argsort(ms); ms, key, fi = ms[o], key[o], fi[o] | |
| assert (np.diff(ms) > 0).all(), f"{s}: repeated ms_id in the source" | |
| return ms, key, fi, shards | |
| def plan(): | |
| jobs = [] | |
| for s in SUBS: | |
| ms, key, fi, shards = load_index(s) | |
| for f in FOLDS: | |
| fr = np.sort(np.asarray(pq.read_table(f"{split_dir}/{s}/{f}.parquet").column("ms_id"))) | |
| sad = fr[fr % 3 == 1] | |
| assert np.array_equal(fr, np.sort(np.concatenate([sad - 1, sad, sad + 1]))), f"{s}/{f}: incomplete triplets" | |
| pos = np.searchsorted(ms, fr); assert (pos < len(ms)).all() and np.array_equal(ms[pos], fr), f"{s}/{f}: ms_id missing in source" | |
| n = (len(sad) + per - 1) // per | |
| for k in range(n): | |
| rows = pos[3 * k * per: 3 * (k + 1) * per] | |
| rows = rows[~np.isin(ms[rows] // 3, np.array(BROKEN) // 3)] # leave out the 3 rows of a BROKEN triplet | |
| name = f"{s}/{f}/{s}_{f}_{k:04d}.aselmdb" | |
| jobs.append((name, [shards[i] for i in range(len(shards))], fi[rows], key[rows], ms[rows])) | |
| return jobs | |
| def work(job): | |
| import lmdb | |
| name, shards, fi, key, ms = job | |
| dst = f"{out}/{name}" | |
| if os.path.exists(dst): return name, len(ms), "exists" | |
| os.makedirs(os.path.dirname(dst), exist_ok=True) | |
| vals = [None] * len(ms) | |
| for f in np.unique(fi): # read grouped by source file, in key order | |
| env = lmdb.open(f"{src_root}/{shards[f]}", subdir=False, readonly=True, lock=False, readahead=False, meminit=False) | |
| sel = np.where(fi == f)[0]; sel = sel[np.argsort(key[sel])] | |
| with env.begin(buffers=False) as t: | |
| for i in sel: | |
| v = t.get(str(int(key[i])).encode("ascii")); assert v is not None, (name, shards[f], key[i]); vals[i] = v | |
| env.close() | |
| tmp = dst + ".tmp" | |
| for p in (tmp, tmp + "-lock"): | |
| if os.path.exists(p): os.remove(p) | |
| env = lmdb.open(tmp, subdir=False, map_size=2 ** 41, meminit=False, lock=False, sync=True) | |
| with env.begin(write=True) as t: | |
| for i, v in enumerate(vals): | |
| assert t.put(str(i + 1).encode("ascii"), v, overwrite=False) | |
| t.put(b"nextid", zlib.compress(bytes(encode(len(vals) + 1), "utf-8")), overwrite=False) | |
| env.sync(True); env.close() | |
| os.rename(tmp, dst) | |
| return name, len(ms), "written" | |
| if __name__ == "__main__": | |
| jobs = plan(); jobs.sort(key=lambda j: -len(j[4])) | |
| print(f"{len(jobs)} output shards, {sum(len(j[4]) for j in jobs)} rows", flush=True) | |
| man = [(j[0], len(j[4]) // 3, int(j[4][0]), int(j[4][-1])) for j in sorted(jobs)] | |
| os.makedirs(out, exist_ok=True) | |
| if len(SUBS) == 4: | |
| with open(f"{out}/.manifest.tsv", "w") as fh: | |
| fh.write("file\ttriplets\tfirst_ms_id\tlast_ms_id\n") | |
| for m in man: fh.write("\t".join(map(str, m)) + "\n") | |
| with Pool(nw) as pool: | |
| for n, (name, r, st) in enumerate(pool.imap_unordered(work, jobs), 1): | |
| print(f" {n}/{len(jobs)} {name}: {r} rows {st}", flush=True) | |