"""Pass A driver: parse a list of OMol25 calculations and write Zarr shards. Usage (one node, all cores): python pass_a.py --list subsets/subset_100k.txt --out store_100k --workers 64 Usage (sbatch array): add --task-id N --n-tasks M to process a contiguous stripe. Each worker buffers records per dataset and flushes a shard once the buffer exceeds --shard-bytes, so shard files stay a manageable size whether the systems are 15 atoms or 250. """ from __future__ import annotations import argparse, os, sys, time, traceback import multiprocessing as mp import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from omol_parse import parse_archive from omol_store import write_shard, shard_bytes, frontier M5250 = "/global/cfs/projectdirs/m5250/OMol_elec" def dataset_of(rel): parts = rel.split("/") if parts[0] == "omol" and len(parts) > 2: return "/".join(parts[:3]) return parts[0] def _prepare(rec, rel): """Attach identity and derived scalars; drop what the store does not keep.""" rec["rel_path"] = rel rec["calc_id"] = rel.replace("/", "__") rec["dataset"] = dataset_of(rel) rec["n_atoms"] = len(rec["elements"]) rec["homo_a"], rec["lumo_a"], rec["gap_a"] = frontier(rec.get("eps_a"), rec.get("occ_a")) rec["homo_b"], rec["lumo_b"], rec["gap_b"] = frontier(rec.get("eps_b"), rec.get("occ_b")) return rec def worker(args): """Process one (dataset, chunk) unit and write exactly one p1 and one p2 shard. Work is grouped by dataset upstream so each shard is large. Writing many small Zarr groups is metadata-bound on CFS (roughly 80 arrays per shard), so few-and-large is far faster. """ (wid, ds, chunk_idx, rels, out_root, shard_budget, task_id) = args p1_root = os.path.join(out_root, "p1") p2_root = os.path.join(out_root, "p2") recs, buffered, n_sub = [], 0, 0 n_ok = n_fail = 0 failures = [] t0 = time.time() def flush(): nonlocal recs, buffered, n_sub if not recs: return name = f"shard_t{task_id:02d}_{chunk_idx:04d}_{n_sub:02d}.zarr" write_shard(recs, os.path.join(p1_root, ds), name, include_matrices=False) write_shard(recs, os.path.join(p2_root, ds), name, include_matrices=True) n_sub += 1 recs, buffered = [], 0 for rel in rels: tar = os.path.join(M5250, rel, "orca.tar.zst") try: rec = _prepare(parse_archive(tar), rel) # A Fock matrix is not universal: some inputs omit Print[P_Fockian] entirely # (about a quarter of omol/redo_orca6). Those rows are still complete for Project 1, # so they are kept and flagged rather than dropped. if rec["nbas"] is None or not rec["elements"]: raise ValueError("incomplete record (nbas or geometry missing)") recs.append(rec) buffered += shard_bytes(rec) n_ok += 1 if buffered > shard_budget: flush() except Exception as e: n_fail += 1 failures.append(f"{rel}\t{type(e).__name__}\t{str(e)[:200]}") flush() dt = time.time() - t0 print(f"[w{wid:03d}] {ds}/{chunk_idx:04d}: ok={n_ok} fail={n_fail} " f"{dt/max(len(rels),1):.2f}s/calc", flush=True) return wid, n_ok, n_fail, failures, dt def main(): ap = argparse.ArgumentParser() ap.add_argument("--list", required=True) ap.add_argument("--out", required=True) ap.add_argument("--workers", type=int, default=32) ap.add_argument("--limit", type=int, default=0) ap.add_argument("--task-id", type=int, default=0) ap.add_argument("--n-tasks", type=int, default=1) ap.add_argument("--shard-bytes", type=float, default=1.5e9) ap.add_argument("--calcs-per-chunk", type=int, default=1500, help="calculations per work unit; one unit writes one shard") args = ap.parse_args() with open(args.list) as fh: rels = [l.strip() for l in fh if l.strip()] if args.limit: rels = rels[:args.limit] if args.n_tasks > 1: rels = rels[args.task_id::args.n_tasks] os.makedirs(args.out, exist_ok=True) print(f"pass A: {len(rels):,} calculations, {args.workers} workers -> {args.out}", flush=True) by_ds = {} for rel in rels: by_ds.setdefault(dataset_of(rel), []).append(rel) units = [] for ds in sorted(by_ds): lst = by_ds[ds] for c, start in enumerate(range(0, len(lst), args.calcs_per_chunk)): units.append((ds, c, lst[start:start + args.calcs_per_chunk])) units.sort(key=lambda u: -len(u[2])) # longest first, so the tail is short jobs = [(i % args.workers, ds, c, lst, args.out, args.shard_bytes, args.task_id) for i, (ds, c, lst) in enumerate(units)] print(f"{len(by_ds)} datasets -> {len(jobs)} work units " f"(<= {args.calcs_per_chunk} calcs each)", flush=True) t0 = time.time() n_ok = n_fail = 0 all_fail = [] with mp.Pool(min(args.workers, len(jobs))) as pool: done = 0 for wid, ok, fail, failures, dt in pool.imap_unordered(worker, jobs): n_ok += ok n_fail += fail all_fail.extend(failures) done += 1 el = time.time() - t0 print(f" units {done}/{len(jobs)} ok={n_ok:,} fail={n_fail:,} " f"elapsed {el/60:.1f} min eta {el/done*(len(jobs)-done)/60:.1f} min", flush=True) dt = time.time() - t0 fail_path = os.path.join(args.out, f"failures_task{args.task_id}.tsv") if all_fail: with open(fail_path, "w") as fh: fh.write("rel_path\terror\tdetail\n" + "\n".join(all_fail) + "\n") print(f"\nok {n_ok:,} failed {n_fail:,} wall {dt/60:.1f} min " f"({dt*args.workers/max(n_ok,1):.2f} core-s per calc)") if all_fail: print(f"failures written to {fail_path}") if __name__ == "__main__": mp.set_start_method("fork", force=True) # forkserver hangs under srun on Perlmutter main()