Download ai4sde_data.py from AI4SDE/DATASET: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/AI4SDE/DATASET/resolve/main/ai4sde_data.py
- Command line
-
hf download hf://datasets/AI4SDE/DATASET/ai4sde_data.py
-
curl -L -o ai4sde_data.py https://huggingface.co/datasets/AI4SDE/DATASET/resolve/main/ai4sde_data.py
10.6 kB
| """AI4SDE dataset: download by category from the Hugging Face Hub, verify, and load with numpy. | |
| Categories (every filter takes a name, a glob pattern or a list of them; None means all): | |
| collection core, extension, training_extension, ood_ladders, tail_events, long_horizon, numerical_baselines, | |
| metric_controls, kuramoto_coupled_bank, rare_events, paired_noise_panels, stats | |
| problem e.g. scalar_ornstein_uhlenbeck, double_well, heston, noisy_kuramoto_d128, stochastic_lorenz96 | |
| split train, validation, test_in_distribution, test_parameter_shift, test_noise_shift, | |
| test_initial_state_shift, test_targeted, test_control, coupled_bank | |
| (files without a split, such as problem.json, conditions.npz and the supplementary collections, | |
| always pass this filter) | |
| kind states, valid, features, conditions, problem, event, panel, index, records, bank, law, checksums, stats | |
| level, ensemble rare-event ladders only (level 0-4, ensemble A or B) | |
| Command line: | |
| python ai4sde_data.py list [--collection core] | |
| python ai4sde_data.py download --collection core --problem double_well --split train validation \ | |
| --kind states valid conditions problem --dir ai4sde | |
| python ai4sde_data.py download --collection ood_ladders --dry-run | |
| python ai4sde_data.py verify --dir ai4sde | |
| Python: | |
| import ai4sde_data as A | |
| A.download(collection="core", problem="double_well", split="test_in_distribution", | |
| kind=["states", "valid", "conditions", "problem"], local_dir="ai4sde") | |
| x = A.load("core", "double_well", "test_in_distribution", local_dir="ai4sde") # (128, 2, 1024, 257, 1) | |
| spec, conds = A.load_problem("core", "double_well", local_dir="ai4sde") # conds["train/params/alpha"], ... | |
| Every downloaded file is checked against the SHA-256 in catalog.json. Requires huggingface_hub; loading needs numpy. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import fnmatch | |
| import hashlib | |
| import json | |
| import os | |
| import sys | |
| REPO_ID = "AI4SDE/DATASET" | |
| REPO_TYPE = "dataset" | |
| DEFAULT_DIR = "ai4sde_data" | |
| FIELDS = ("collection", "problem", "split", "kind", "level", "ensemble") | |
| def _hub(): | |
| from huggingface_hub import hf_hub_download, snapshot_download | |
| return hf_hub_download, snapshot_download | |
| def catalog(revision=None) -> list: | |
| """All file records: path, collection, problem, split, kind, level, ensemble, bytes, sha256.""" | |
| hf_hub_download, _ = _hub() | |
| p = hf_hub_download(REPO_ID, "catalog.json", repo_type=REPO_TYPE, revision=revision) | |
| with open(p, encoding="utf-8") as f: | |
| return json.load(f)["files"] | |
| def _patterns(v): | |
| if v is None: | |
| return None | |
| return [str(x) for x in ([v] if isinstance(v, (str, int)) else v)] | |
| def _match(value, pats) -> bool: | |
| return any(fnmatch.fnmatchcase("" if value is None else str(value), p) for p in pats) | |
| def select(files: list, collection=None, problem=None, split=None, kind=None, level=None, ensemble=None) -> list: | |
| """Filter catalog records by category (see the module docstring).""" | |
| want = dict(zip(FIELDS, map(_patterns, (collection, problem, split, kind, level, ensemble)))) | |
| out = [] | |
| for f in files: | |
| ok = True | |
| for k, pats in want.items(): | |
| if pats is None: | |
| continue | |
| if k in ("split", "level", "ensemble") and f.get(k) is None: | |
| continue | |
| if not _match(f.get(k), pats): | |
| ok = False | |
| break | |
| if ok: | |
| out.append(f) | |
| return out | |
| def sha256_file(path: str, chunk: int = 1 << 24) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for b in iter(lambda: f.read(chunk), b""): | |
| h.update(b) | |
| return h.hexdigest() | |
| def check(files: list, local_dir: str = DEFAULT_DIR, quiet: bool = False) -> list: | |
| """Paths of the records that are missing, have the wrong size or the wrong SHA-256 under local_dir.""" | |
| bad = [] | |
| for f in files: | |
| p = os.path.join(local_dir, f["path"]) | |
| if not os.path.isfile(p) or os.path.getsize(p) != f["bytes"] or sha256_file(p) != f["sha256"]: | |
| bad.append(f["path"]) | |
| if not quiet: | |
| print(f"checked {len(files)} files: {len(files) - len(bad)} ok, {len(bad)} bad", file=sys.stderr) | |
| return bad | |
| def download(collection=None, problem=None, split=None, kind=None, level=None, ensemble=None, | |
| local_dir: str = DEFAULT_DIR, verify: bool = True, dry_run: bool = False, max_workers: int = 8, | |
| revision=None) -> list: | |
| """Download the selected files into local_dir (the repository layout is kept) and verify them. | |
| Returns the selected catalog records (also for dry_run, which downloads nothing).""" | |
| files = select(catalog(revision), collection, problem, split, kind, level, ensemble) | |
| if not files: | |
| raise ValueError("no file matches this selection; run `python ai4sde_data.py list`") | |
| total = sum(f["bytes"] for f in files) | |
| print(f"{len(files)} files, {total / 1e9:.3f} GB -> {local_dir}", file=sys.stderr) | |
| if dry_run: | |
| return files | |
| _, snapshot_download = _hub() | |
| snapshot_download(REPO_ID, repo_type=REPO_TYPE, revision=revision, local_dir=local_dir, | |
| allow_patterns=[f["path"] for f in files], max_workers=max_workers) | |
| if verify: | |
| bad = check(files, local_dir) | |
| if bad: | |
| raise RuntimeError(f"{len(bad)} files failed the SHA-256 check, e.g. {bad[:3]}; download them again") | |
| return files | |
| def load(collection: str, problem: str, split: str = None, kind: str = "states", level: int = None, | |
| ensemble: str = None, local_dir: str = DEFAULT_DIR, mmap: bool = True): | |
| """One array as numpy (memory-mapped by default), downloaded first if needed. | |
| Rare-event ladders: pass level (0-4) and ensemble ('A' or 'B').""" | |
| import numpy as np | |
| name = kind + (f"_level{level}_{ensemble}" if level is not None else "") + ".npy" | |
| p = os.path.join(local_dir, collection, problem, *([split] if split else []), name) | |
| if not os.path.isfile(p): | |
| download(collection=collection, problem=problem, split=split, kind=kind, level=level, ensemble=ensemble, | |
| local_dir=local_dir) | |
| return np.load(p, mmap_mode="r" if mmap else None) | |
| _SPLIT_NAMES = {"val": "validation", "test_id": "test_in_distribution", "test_param": "test_parameter_shift", | |
| "test_noise": "test_noise_shift", "test_init": "test_initial_state_shift", "test_ctrl": "test_control", | |
| "bank": "coupled_bank"} | |
| def _public_key(key: str) -> str: | |
| head, sep, rest = key.partition("/") | |
| return _SPLIT_NAMES.get(head, head) + sep + rest | |
| def load_problem(collection: str, problem: str, local_dir: str = DEFAULT_DIR): | |
| """(specification dict from problem.json / event.json / panel.json, dict of per-condition arrays from | |
| conditions.npz keyed '<split>/<field>'); split names are given as in the folder layout. Either part is None | |
| when the collection has no such file.""" | |
| import numpy as np | |
| recs = select(catalog(), collection=collection, problem=problem, kind=["problem", "event", "panel", "conditions"]) | |
| if any(not os.path.isfile(os.path.join(local_dir, f["path"])) for f in recs): | |
| download(collection=collection, problem=problem, kind=["problem", "event", "panel", "conditions"], | |
| local_dir=local_dir) | |
| spec = conds = None | |
| for f in recs: | |
| p = os.path.join(local_dir, f["path"]) | |
| if p.endswith(".json"): | |
| with open(p, encoding="utf-8") as fh: | |
| spec = json.load(fh) | |
| for k in ("splits", "split_spec"): | |
| if isinstance(spec.get(k), dict): | |
| spec[k] = {_SPLIT_NAMES.get(s, s): v for s, v in spec[k].items()} | |
| elif p.endswith(".npz"): | |
| with np.load(p, allow_pickle=False) as z: | |
| conds = {_public_key(k): z[k] for k in z.files} | |
| return spec, conds | |
| def summary(files: list) -> dict: | |
| """{collection: {problem: {"bytes": .., "files": .., "splits": {..}, "kinds": {..}}}}""" | |
| out = {} | |
| for f in files: | |
| b = out.setdefault(f["collection"], {}).setdefault(f["problem"] or "-", | |
| dict(bytes=0, files=0, splits=set(), kinds=set())) | |
| b["bytes"] += f["bytes"] | |
| b["files"] += 1 | |
| if f.get("split"): | |
| b["splits"].add(f["split"]) | |
| b["kinds"].add(f["kind"]) | |
| return out | |
| def _main(argv=None): | |
| ap = argparse.ArgumentParser(description="AI4SDE dataset: list, download by category, verify") | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| for name in ("list", "download", "verify"): | |
| p = sub.add_parser(name) | |
| for k in FIELDS: | |
| p.add_argument("--" + k, nargs="*") | |
| p.add_argument("--dir", default=DEFAULT_DIR) | |
| p.add_argument("--revision") | |
| if name == "download": | |
| p.add_argument("--dry-run", action="store_true") | |
| p.add_argument("--no-verify", action="store_true") | |
| p.add_argument("--workers", type=int, default=8) | |
| p.add_argument("--yes", action="store_true", help="needed for selections above 100 GB") | |
| a = ap.parse_args(argv) | |
| sel = {k: getattr(a, k) for k in FIELDS} | |
| if a.cmd == "list": | |
| files = select(catalog(a.revision), **sel) | |
| for c, probs in summary(files).items(): | |
| tot = sum(b["bytes"] for b in probs.values()) | |
| print(f"{c} ({tot / 1e9:.1f} GB, {sum(b['files'] for b in probs.values())} files)") | |
| for name, b in sorted(probs.items()): | |
| sp = ", ".join(sorted(b["splits"])) or "-" | |
| print(f" {name:<30} {b['bytes'] / 1e9:9.3f} GB {b['files']:4d} files splits: {sp}" | |
| f" kinds: {', '.join(sorted(b['kinds']))}") | |
| elif a.cmd == "download": | |
| files = select(catalog(a.revision), **sel) | |
| total = sum(f["bytes"] for f in files) | |
| if total > 100e9 and not (a.yes or a.dry_run): | |
| sys.exit(f"selection is {total / 1e9:.1f} GB; add --yes to download it, or narrow it (see --dry-run)") | |
| download(local_dir=a.dir, verify=not a.no_verify, dry_run=a.dry_run, max_workers=a.workers, | |
| revision=a.revision, **sel) | |
| else: | |
| files = [f for f in select(catalog(a.revision), **sel) if os.path.exists(os.path.join(a.dir, f["path"]))] | |
| bad = check(files, a.dir) | |
| sys.exit(1 if bad else 0) | |
| if __name__ == "__main__": | |
| _main() | |