diff --git a/benchmarks/lustre/README.md b/benchmarks/lustre/README.md new file mode 100644 index 0000000..7bc2c93 --- /dev/null +++ b/benchmarks/lustre/README.md @@ -0,0 +1,89 @@ +# Storage and engine probe + +Measures, on an LSF cluster, where adata's time goes on big h5ad files and +which I/O engine would make it scale. Three storage tiers are compared: +Lustre, a compute node's local `/tmp`, and NFS. + +- **Job A**: today's `adata`, one step per job, on each input and its 1/4 + and 1/16 slices. The steps are subset (obs to h5ad and to Zarr, var), + split, convert (Zarr, gzip h5ad, 10x-h5 and back, 10x-mtx, loom), export + and import MTX, and export obs, var and obsm. For each it records wall, + CPU, peak RSS and bytes. The inputs in `PROFILE_LABELS` run every step + again under pyinstrument, which samples from inside the process (py-spy + needs ptrace, which LSF nodes refuse); `PARTS=profile` submits only + those reruns. +- **Job B**: read engines on one input's X: + - h5py; + - `h5chunks.py`, a read-only zarr store that maps an HDF5 dataset's + chunks to byte ranges, so zarr-python's concurrent engine reads them + without libhdf5; + - the same store fetching through obstore; + - DuckDB's `h5db` extension; + - DuckDB's `anndata` extension. +- **Job C**: write engines: h5py (uncompressed and gzip) against Zarr v2 + and v3 under zarr-python's pipeline and under zarrs. +- **Job D**: the text formats: adata against DuckDB for MTX export and + import and obs to CSV. +- **Job E**: one command on Lustre at several `--chunk` sizes (rows a + block), twice each, to see what many small reads cost: `export + dataframe obs`, or `subset --obs` (`WHAT=subset_obs`), whose sparse + blocks are `--chunk` rows' worth of entries (`PARTS=chunks`, inputs in + `CHUNK_LABELS`). +- **Job F**: one node's ceiling, with plain byte ranges: buffered reads + against O_DIRECT at several depths, `lfs ladvise willneed`, several + processes, two files at once, and buffered against O_DIRECT writes + (`ceiling.py`, `PARTS=ceiling`). + +None of the engines under test is a dependency of adata. They live only in +the probe's own venv. + +## Run + +1. **Copy the repository and this folder to the probe directory on Lustre:** + ``` + rsync -a --exclude .venv --exclude .git ./ HOST:$PROBE/repo/ + rsync -a benchmarks/lustre/ HOST:$PROBE/scripts/ + ``` +2. **Configure the probe:** copy `probe.conf.example` to + `$PROBE/probe.conf` and fill it in (paths, LSF group, inputs, slices). +3. **Build the venvs and fetch the DuckDB extensions,** on a host with + internet access: + ``` + PROBE=... bash $PROBE/scripts/setup.sh + ``` +4. **Submit everything,** from a submit host: + ``` + PROBE=... bash $PROBE/scripts/submit.sh + ``` + The jobs are chained so that the engine measurements don't run against + each other (see the header of `submit.sh`). +5. **When the jobs are done, write the report:** + ``` + $PROBE/venv/bin/python $PROBE/scripts/report.py $PROBE/results > report.md + ``` +6. **For the docs,** copy `$PROBE/results` and `$PROBE/profiles` off the + cluster and make the cleaned summary and the charts of + `docs/reference/cluster-storage.md` from them: + ``` + uv run python benchmarks/lustre/evidence.py summarise RESULTS PROFILES -o benchmarks/lustre/results/2026-12.json + uv run python benchmarks/lustre/evidence.py charts benchmarks/lustre/results/2026-12.json -o docs/_includes/charts + ``` + The raw results name the inputs' paths and the probe's folders; the + summary keeps neither, only the numbers the page uses. + +To run Job E with another build of adata, say a branch's, install it into a +venv of its own and pass `ADATA` (that venv's `adata`) and `TAG` (a name for +the build, added to the step names) to `PARTS=chunks`. + +## Reading the results + +- **CPU share** is (user + system time) / wall: + - near 1, the step is computing; + - well under 1, it is waiting on storage; + - above 1, threads are working in parallel. +- **The slopes** are log(wall time) against log(input size), across an + input and its slices. 1 means linear. +- **Caching:** before each run the input is dropped from the page cache + (`posix_fadvise`, and `lfs ladvise` on Lustre), so a rerun on the same + node isn't flattered. The `cache_drop` column says whether that worked. +- **Disk space:** each output is deleted after it is measured. diff --git a/benchmarks/lustre/ceiling.py b/benchmarks/lustre/ceiling.py new file mode 100644 index 0000000..8d105f8 --- /dev/null +++ b/benchmarks/lustre/ceiling.py @@ -0,0 +1,281 @@ +"""Job F: what one node can read from and write to Lustre, by I/O style. + + python ceiling.py --file F --other G --dir D --tier T --out R.jsonl + +Every engine in Job B read X at about the same rate from one node. This +asks whether that is a ceiling of buffered reads, of one process, of one +file, or of the node, with plain byte ranges, so no format library is in +the way. F and G are inputs; what they hold does not matter. + +Reads, each trial on a region of F, G or a --pool file, after dropping +that region from the client's page cache and the servers' (`lfs ladvise +-a dontneed`): + +- buffered 16 MiB preads, one thread, then four; +- O_DIRECT, which skips the client's page cache, at 1, 4, 16, 32 and 64 + reads in flight of 16 MiB, and 4 of 64 MiB; +- buffered, one thread, with `lfs ladvise -a willneed` sent ahead, which + asks the servers to start reading early; +- 4 processes on parts of one region, buffered, then direct; +- 2 processes on two files, buffered, then direct. + +Writes, into D, a new file a trial, fsync included, deleted after: +buffered at 1 and 8 in flight, O_DIRECT at 1, 8 and 16. + +`--rounds N` runs all of it N times, each round in its own shuffled order. +""" + +from __future__ import annotations + +import argparse +import itertools +import json +import mmap +import os +import random +import resource +import shutil +import socket +import subprocess +import sys +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +MiB = 1 << 20 + + +def cpu_now() -> float: + """This process's CPU and its waited-for children's, threads included.""" + own = resource.getrusage(resource.RUSAGE_SELF) + kids = resource.getrusage(resource.RUSAGE_CHILDREN) + return own.ru_utime + own.ru_stime + kids.ru_utime + kids.ru_stime + + +def drop(path: str, lo: int, hi: int) -> None: + if hasattr(os, "posix_fadvise"): # not on macOS, where it is tried out + fd = os.open(path, os.O_RDONLY) + try: + os.posix_fadvise(fd, lo, hi - lo, os.POSIX_FADV_DONTNEED) + finally: + os.close(fd) + if shutil.which("lfs"): + subprocess.run(["lfs", "ladvise", "-a", "dontneed", "-s", str(lo), "-e", str(hi), path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def run_blocks(fd: int, lo: int, n: int, block: int, threads: int, op, before=None) -> int: + """Run `op(fd, buffer, offset)` on blocks lo + i * block, i < n, with + `threads` in flight, each thread on its own page-aligned buffer (an + anonymous mmap), as O_DIRECT needs. Returns the bytes moved.""" + blocks = iter(range(n)) + lock = threading.Lock() + moved = [0] * threads + + def worker(t: int) -> None: + buf = mmap.mmap(-1, block) + try: + while True: + with lock: + i = next(blocks, None) + if i is None: + return + if before: + before(lo + i * block) + moved[t] += op(fd, buf, lo + i * block) + finally: + buf.close() + + with ThreadPoolExecutor(threads) as pool: + list(pool.map(worker, range(threads))) + return sum(moved) + + +def read_range(path: str, lo: int, hi: int, block: int, threads: int, direct: bool, + willneed_ahead: int = 0) -> int: + fd = os.open(path, os.O_RDONLY | (os.O_DIRECT if direct else 0)) + advised = [lo] + pending = [] + + def before(offset: int) -> None: + # Keep `willneed_ahead` bytes past this block asked for, in steps. + step = 256 * MiB + while advised[0] < min(hi, offset + willneed_ahead): + start, end = advised[0], min(hi, advised[0] + step) + pending.append(subprocess.Popen( + ["lfs", "ladvise", "-a", "willneed", "-b", "-s", str(start), "-e", str(end), path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) + advised[0] = end + + try: + return run_blocks(fd, lo, (hi - lo) // block, block, threads, + lambda f, buf, off: os.preadv(f, [buf], off), + before if willneed_ahead else None) + finally: + os.close(fd) + for p in pending: + p.wait() + + +def write_file(path: Path, total: int, block: int, threads: int, direct: bool) -> int: + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | (os.O_DIRECT if direct else 0) + fd = os.open(path, flags, 0o644) + payload = os.urandom(block) + + def op(f, buf, off): + buf[:] = payload # a copy a block, as a writer filling its buffer would + return os.pwritev(f, [buf], off) + + try: + moved = run_blocks(fd, 0, total // block, block, threads, op) + os.fsync(fd) + return moved + finally: + os.close(fd) + + +def spawn_readers(parts: list) -> int: + """One child a (path, lo, hi, block, threads, direct); returns the bytes they read.""" + children = [subprocess.Popen( + [sys.executable, __file__, "--worker", path, str(lo), str(hi), str(block), + str(threads), str(int(direct))], stdout=subprocess.PIPE) + for path, lo, hi, block, threads, direct in parts] + total = 0 + for child in children: + out, _ = child.communicate() + if child.returncode: + raise RuntimeError(f"a reader exited {child.returncode}") + total += int(out) + return total + + +def main() -> None: + if len(sys.argv) > 1 and sys.argv[1] == "--worker": + path, lo, hi, block, threads, direct = sys.argv[2:8] + print(read_range(path, int(lo), int(hi), int(block), int(threads), direct == "1")) + return + + p = argparse.ArgumentParser() + p.add_argument("--file", required=True) + p.add_argument("--other", required=True) + p.add_argument("--pool", nargs="*", default=[], help="more files to take read regions from") + p.add_argument("--dir", required=True) + p.add_argument("--tier", required=True) + p.add_argument("--out", required=True) + p.add_argument("--rounds", type=int, default=1) + p.add_argument("--region-mib", type=int, default=4096) + p.add_argument("--write-mib", type=int, default=8192) + p.add_argument("--block-mib", type=int, default=16) + p.add_argument("--start-mib", type=int, default=1024, + help="where the first region starts: past the header and obs") + args = p.parse_args() + region, block = args.region_mib * MiB, args.block_mib * MiB + work = Path(args.dir) + work.mkdir(parents=True, exist_ok=True) + base = {"host": socket.gethostname(), "tier": args.tier, + "nproc": os.environ.get("LSB_DJOB_NUMPROC", str(os.cpu_count()))} + + def regions(path: str) -> list: + # Each starts block-aligned, so O_DIRECT can read it. + start, size, out = args.start_mib * MiB, os.path.getsize(path), [] + while start + region <= size: + out.append((path, start, start + region)) + start += region + return out + + # Every region of every file, the files interleaved. A long run reads + # more regions than the files hold, so regions come round again; each + # is dropped from the client's and the servers' caches before a read. + files = [args.file, args.other, *args.pool] + order = [r for group in itertools.zip_longest(*map(regions, files)) for r in group if r] + if not order: + raise SystemExit(f"no file is larger than {args.start_mib + args.region_mib} MiB") + cursor = [0] + + def take(avoid: str = "") -> tuple: + for _ in range(len(order)): + path, lo, hi = order[cursor[0] % len(order)] + cursor[0] += 1 + if path != avoid: + drop(path, lo, hi) + return path, lo, hi + raise RuntimeError(f"no region outside {avoid}") + + def emit(row: dict) -> None: + with open(args.out, "a") as fh: + fh.write(json.dumps({**base, **row}) + "\n") + print(json.dumps(row), flush=True) + + def trial(name: str, fn, **meta) -> None: + try: + started, cpu = time.perf_counter(), cpu_now() + moved = fn() + wall = time.perf_counter() - started + emit({"trial": name, "mb_s": round(moved / wall / 1e6, 1), "wall_s": round(wall, 2), + "cpu_s": round(cpu_now() - cpu, 2), "bytes": moved, **meta}) + except Exception as error: + emit({"trial": name, "error": f"{type(error).__name__}: {error}"[:300], **meta}) + + def reads(threads: int, direct: bool, size: int = block, ahead: int = 0): + def fn(): + path, lo, hi = take() + return read_range(path, lo, hi, size, threads, direct, ahead) + return fn + + def processes(n: int, threads: int, direct: bool): + def fn(): + path, lo, hi = take() + part = (hi - lo) // n // block * block + return spawn_readers([(path, lo + i * part, lo + (i + 1) * part, block, threads, direct) + for i in range(n)]) + return fn + + def two_files(threads: int, direct: bool): + def fn(): + first = take() + second = take(avoid=first[0]) + return spawn_readers([(*first, block, threads, direct), (*second, block, threads, direct)]) + return fn + + mib = args.block_mib + read_trials = [ + ("read-buffered-t1", reads(1, False), {"threads": 1, "block_mib": mib}), + ("read-buffered-t4", reads(4, False), {"threads": 4, "block_mib": mib}), + *[(f"read-direct-t{t}", reads(t, True), {"threads": t, "block_mib": mib}) + for t in (1, 4, 16, 32, 64)], + ("read-direct-t4-64M", reads(4, True, 64 * MiB), {"threads": 4, "block_mib": 64}), + ("read-buffered-t1-willneed", reads(1, False, ahead=1 << 30), + {"threads": 1, "block_mib": mib, "willneed_ahead_mib": 1024}), + ("read-buffered-4proc", processes(4, 1, False), {"processes": 4, "threads": 1}), + ("read-direct-4proc-t4", processes(4, 4, True), {"processes": 4, "threads": 4}), + ("read-buffered-2files", two_files(1, False), {"processes": 2, "threads": 1}), + ("read-direct-2files-t8", two_files(8, True), {"processes": 2, "threads": 8}), + ] + target = work / "ceiling.bin" + + def writes(threads: int, direct: bool): + def fn(): + try: + return write_file(target, args.write_mib * MiB, block, threads, direct) + finally: + target.unlink(missing_ok=True) + return fn + + write_trials = [ + (f"write-{'direct' if direct else 'buffered'}-t{t}", writes(t, direct), + {"threads": t, "block_mib": mib}) + for direct, threads in ((False, (1, 8)), (True, (1, 8, 16))) for t in threads + ] + # Each round in its own order, so a change in the filesystem's load + # over the run does not always fall on the same trial. + for number in range(1, args.rounds + 1): + shuffle = random.Random(number).shuffle + for kind, trials in (("read", list(read_trials)), ("write", list(write_trials))): + shuffle(trials) + for name, fn, meta in trials: + trial(name, fn, kind=kind, round=number, **meta) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/lustre/env.sh b/benchmarks/lustre/env.sh new file mode 100755 index 0000000..de746ce --- /dev/null +++ b/benchmarks/lustre/env.sh @@ -0,0 +1,36 @@ +# Sourced by every job (as $PROBE/scripts/env.sh): configuration and environment. +# shellcheck shell=bash +: "${PROBE:?PROBE must point at the probe directory}" +source "$PROBE/probe.conf" +export PROBE NFS_ROOT +export UV_CACHE_DIR=$PROBE/uv-cache +export PY=$PROBE/venv/bin/python +# ADATA, when set, is another build's command (a branch's venv) for Job E. +export ADATA=${ADATA:-$PROBE/venv/bin/adata} +export PATH=$PROBE/venv/bin:$PATH +export DUCKDB_EXT=$PROBE/duckdb-ext +# DuckDB's anndata extension is published for DuckDB 1.5.x only; its runs +# use this interpreter, which has DuckDB 1.5.3 and nothing else. +export DUCK15=$PROBE/venv-duckdb15/bin/python + +# input_path LABEL: a configured input, or a slice made by prep.sh. +input_path() { + local var="INPUT_$1" + if [[ -n "${!var:-}" ]]; then echo "${!var}"; else echo "$PROBE/inputs/$1.h5ad"; fi +} + +# all_labels: inputs, then their slices. +all_labels() { + local l + for l in $INPUTS; do echo "$l"; done + for l in $OBS_SLICES; do echo "${l}_obs4"; echo "${l}_obs16"; done + for l in $VAR_SLICES; do echo "${l}_var4"; echo "${l}_var16"; done +} + +# nfs_labels: what the NFS tier runs on. +nfs_labels() { + local l + for l in $NFS_FULL; do echo "$l"; done + for l in $OBS_SLICES; do echo "${l}_obs4"; echo "${l}_obs16"; done + for l in $VAR_SLICES; do echo "${l}_var4"; echo "${l}_var16"; done +} diff --git a/benchmarks/lustre/evidence.py b/benchmarks/lustre/evidence.py new file mode 100644 index 0000000..83bd93e --- /dev/null +++ b/benchmarks/lustre/evidence.py @@ -0,0 +1,627 @@ +"""The evidence behind docs/reference/cluster-storage.md: a cleaned summary of +a probe run, and the page's charts drawn from it. + + python evidence.py summarise RESULTS_DIR PROFILES_DIR -o SUMMARY.json + python evidence.py charts SUMMARY.json -o docs/_includes/charts + +`summarise` keeps the numbers the page uses and nothing that names a path: +the raw results carry the inputs' locations and the probe's folders, which +stay on the cluster. Inputs are named by their label in `INPUTS`. Each +pyinstrument profile is reduced to the share of its samples spent reading, +writing, compressing, parsing or formatting text, and computing. + +`charts` writes one SVG per chart, sized by its viewBox, with a tooltip on +every mark. The page includes them inline, so the tooltips work; the page's +tables carry the same numbers. +""" + +from __future__ import annotations + +import argparse +import csv +import json +import statistics +from collections import defaultdict +from html import escape +from pathlib import Path + +#: The probe's inputs, by label, as the page describes them. +INPUTS = { + "cells": "55 GB, 4.68M cells × 12,288 genes, CSR, float64 values, int64 indices", + "spatial": "6.7 GB, 4.27M bins × 480 genes, CSR X and a counts layer, float32/int32", + "peaks": "21.7 GB ATAC, 115,503 cells × 2,337,084 peaks, CSR, int32/int32", +} + +#: The job that measured numpy's huge pages on node-13-21 with them on was +#: killed after 55 minutes, so it wrote no row. What it had done was read +#: from /proc and the job's work folder at that point. +HUGE_PAGES_ON = { + "host": "node-13-21", "trial": "zarr3-shard-none-default", "gb": 2, + "after_s": 3300, "written_bytes": 0, "user_s": 5.1, "sys_s": 3327.3, +} + + +def _jsonl(path: Path) -> list: + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text().splitlines() if line.strip()] + + +def _tsv(path: Path) -> list: + with open(path) as fh: + return list(csv.DictReader(fh, delimiter="\t")) + + +def _median(values): + return statistics.median(values) if values else None + + +# --------------------------------------------------------------------------- +# profiles + +def _frame(ident: str) -> tuple: + func, _, rest = ident.partition("\x00") + path, _, _ = rest.partition("\x00") + return func, path + + +TEXT_MODULES = ("adata/formats/mtx.py", "adata/formats/textio.py", "adata/formats/table.py", + "adata/formats/csv", "/csv.py") +ZLIB = ("compress", "decompress", "crc32", "flush", "_ZlibDecompressor.decompress", + "Compress.compress", "Compress.flush") + + +def category(stack: list) -> str: + """What a sample was doing: read, write, compress, text or compute. + + By the leaf first (zlib's calls; a file's own reads and writes), then by + the store call on the stack (an h5py or zarr read or write: HDF5's own + filters run inside it, so a gzip output's compression counts as its + write), then by the adata module (Matrix Market and CSV text). + """ + frames = [_frame(s) for s in stack] + leaf, leaf_path = frames[-1] + if leaf in ZLIB and "" in leaf_path or leaf_path.endswith(("gzip.py", "zlib")): + return "compress" + if leaf in ("BufferedReader.read", "readinto", "FileIO.readinto", "BufferedReader.readinto"): + return "read" + if leaf in ("sendfile", "BufferedWriter.write", "FileIO.write", "copyfileobj"): + return "write" + for func, path in reversed(frames): + store = "/h5py/" in path or "/zarr/" in path + if store and func in ("__getitem__", "read_direct", "get_basic_selection", + "get_orthogonal_selection", "_get_selection", "getitem"): + return "read" + if store and func in ("__setitem__", "write_direct", "set_basic_selection", + "set_orthogonal_selection", "_set_selection", "setitem"): + return "write" + if leaf in ("fromstring", "writerows", "writer.writerows") or leaf.startswith("bytes."): + return "text" + for func, path in reversed(frames): + if "/adata/" in path: + return "text" if path.endswith(TEXT_MODULES) else "compute" + return "compute" + + +def profile_shares(path: Path) -> dict: + data = json.loads(path.read_text()) + shares, total = defaultdict(float), 0.0 + for stack, seconds in data["frame_records"]: + shares[category(stack)] += seconds + total += seconds + return { + "wall_s": round(data["duration"], 1), "cpu_s": round(data["cpu_time"], 1), + "shares": {k: round(shares[k] / total, 3) for k in CATEGORIES}, + } + + +CATEGORIES = ("read", "write", "compress", "text", "compute") + + +# --------------------------------------------------------------------------- +# summarise + +def summarise(results: Path, profiles: Path) -> dict: + out: dict = {"inputs": INPUTS} + + latest = {} + for path in sorted(results.glob("a_*.tsv")): + for r in _tsv(path): + if r["step"].endswith(("+profile", "+pyspy")): + continue + latest[(r["label"], r["step"], r["tier"])] = r + out["commands"] = [ + {"label": label, "step": step, "tier": tier, "host": r["host"], "exit": int(r["exit"]), + "wall_s": round(float(r["wall_s"]), 1), + "cpu_share": round((float(r["user_s"]) + float(r["sys_s"])) / max(float(r["wall_s"]), 1e-9), 2), + "user_s": round(float(r["user_s"]), 1), "sys_s": round(float(r["sys_s"]), 1), + "rss_mb": int(float(r["max_rss_mb"])), "input_bytes": int(r["input_bytes"])} + for (label, step, tier), r in sorted(latest.items()) + ] + + out["reads"] = [ + {k: r.get(k) for k in ("tier", "host", "trial", "engine", "concurrency", "threads", + "block", "mb_s", "wall_s", "cpu_s")} + for r in (_jsonl(results / "read_lustre.jsonl") + _jsonl(results / "read_tmp.jsonl") + + _jsonl(results / "read_nfs.jsonl")) + if r.get("trial") != "check" and "mb_s" in r + ] + + groups = defaultdict(list) + for name in ("write_lustre.jsonl", "write_lustre_thp_off.jsonl", "write_tmp.jsonl", + "write_nfs.jsonl"): + for r in _jsonl(results / name): + if "error" not in r: + groups[(r["tier"], r["host"], r["trial"], r.get("numpy_hugepage", "default"))].append(r) + out["writes"] = [ + {"tier": tier, "host": host, "trial": trial, "numpy_hugepage": thp, "runs": len(rs), + "mb_s": [r["mb_s"] for r in rs], "median_mb_s": _median([r["mb_s"] for r in rs]), + "median_cpu_s": _median([r["cpu_s"] for r in rs]), + "gb": round(rs[0]["bytes"] / 2**30, 1), "disk_gb": round(rs[0]["disk_bytes"] / 2**30, 2)} + for (tier, host, trial, thp), rs in sorted(groups.items()) + ] + out["huge_pages_on"] = HUGE_PAGES_ON + + groups = defaultdict(list) + for r in _jsonl(results / "ceiling_lustre.jsonl"): + if "error" not in r: + groups[(r["host"], r["trial"])].append(r) + out["ceiling"] = [ + {"host": host, "trial": trial, "runs": len(rs), + "median_mb_s": round(_median([r["mb_s"] for r in rs])), + "min_mb_s": round(min(r["mb_s"] for r in rs)), "max_mb_s": round(max(r["mb_s"] for r in rs)), + "median_cpu_s": _median([r["cpu_s"] for r in rs])} + for (host, trial), rs in sorted(groups.items()) + ] + + out["text"] = [ + {k: r.get(k) for k in ("tier", "host", "trial", "threads", "wall_s", "cpu_s", "max_rss_mb")} + for r in _jsonl(results / "text_lustre.jsonl") + _jsonl(results / "text_tmp.jsonl") + ] + + # A run that failed is counted, never timed: a refusal or a failed write + # ends early, and averaged in it would read as a faster block size. + sweep, failed = defaultdict(list), defaultdict(int) + for path in sorted(results.glob("chunks_*.tsv")): + for r in _tsv(path): + what, chunk = r["step"].rsplit("_chunk", 1) + build = "main" + for tag in ("blocks", "main"): + if what.endswith("_" + tag): + what, build = what[: -len(tag) - 1], ("floor" if tag == "blocks" else "main") + key = (r["label"], what, build, int(chunk), r["host"]) + if r["exit"] != "0": + failed[key] += 1 + continue + sweep[key].append(r) + out["chunks"] = [ + {"label": label, "what": what, "build": build, "chunk": chunk, "host": host, + "wall_s": [round(float(r["wall_s"]), 1) for r in rs], + "cpu_share": [round((float(r["user_s"]) + float(r["sys_s"])) / float(r["wall_s"]), 2) for r in rs], + "rss_mb": max(int(float(r["max_rss_mb"])) for r in rs), + "failed": failed[(label, what, build, chunk, host)]} + for (label, what, build, chunk, host), rs in sorted(sweep.items()) + ] + out["chunks_failed"] = [ + {"label": label, "what": what, "build": build, "chunk": chunk, "host": host, "runs": n} + for (label, what, build, chunk, host), n in sorted(failed.items()) if (label, what, build, chunk, host) not in sweep + ] + + out["profiles"] = [] + for path in sorted(profiles.glob("*.pyisession")): + _, label, step = path.stem.split("_", 2) + if step.startswith(("obs4_", "var4_", "obs16_", "var16_")): + part, step = step.split("_", 1) + label = f"{label}_{part}" + out["profiles"].append({"label": label, "step": step, **profile_shares(path)}) + return out + + +# --------------------------------------------------------------------------- +# charts + +INK = {"primary": "#0b0b0b", "secondary": "#52514e", "muted": "#898781", + "grid": "#e1e0d9", "axis": "#c3c2b7", "surface": "#ffffff"} +#: The reference palette's first five categorical slots, in its fixed order. +SERIES = ("#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4") +FONT = 'font-family="system-ui, -apple-system, Segoe UI, sans-serif"' + + +def _svg(width: int, height: int, title: str, body: list) -> str: + """One chart: no blank line and no indented line, so kramdown passes it + through whole when the page includes it.""" + head = (f'') + return "\n".join([head, f"{escape(title)}", *body, ""]) + "\n" + + +def _text(x, y, s, *, size=12, ink="secondary", anchor="start", weight=None, halo=False) -> str: + w = f' font-weight="{weight}"' if weight else "" + h = (f' stroke="{INK["surface"]}" stroke-width="4" stroke-linejoin="round" paint-order="stroke"' + if halo else "") + return (f'{escape(s)}') + + +def _bar(x, y, w, h, color, tip) -> str: + """A horizontal bar from the baseline at x: square there, 4px round at its end.""" + w = max(w, 1.0) + r = min(4.0, w / 2, h / 2) + d = (f"M{x:.1f},{y:.1f} h{w - r:.1f} a{r},{r} 0 0 1 {r},{r} v{h - 2 * r:.1f} " + f"a{r},{r} 0 0 1 {-r},{r} h{-(w - r):.1f} z") + return f'{escape(tip)}' + + +def _legend(x, y, items) -> list: + out, at = [], x + for color, label in items: + out.append(f'') + out.append(_text(at + 15, y, label, size=12, ink="secondary")) + at += 15 + 6.6 * len(label) + 18 + return out + + +def _ticks(top: float) -> list: + """About five clean ticks from 0 to `top`: 1, 2, 2.5 or 5 times a power of ten.""" + import math + + raw = top / 5 + power = 10 ** math.floor(math.log10(raw)) + step = next(n * power for n in (1, 2, 2.5, 5, 10) if n * power >= raw) + return [i * step for i in range(int(top // step) + 1)] + + +def hbar_chart(rows, *, title, unit, legend, label_w=250, width=760, fmt=None) -> str: + """Horizontal bars, one row each: (group or None, label, value, color, tip). + A row whose label is None is a group heading.""" + fmt = fmt or (lambda v: f"{v:,.0f}") + top = max(v for g, lab, v, c, t in rows if lab is not None) * 1.12 + plot_x, plot_w = label_w, width - label_w - 70 + row_h, bar_h, y0 = 26, 16, 52 + body = _legend(0, 18, legend) + y = y0 + heights = [] + for group, label, value, color, tip in rows: + if label is None: + body.append(_text(0, y + 16, group, size=12, ink="primary", weight="600", halo=True)) + y += row_h + continue + body.append(_text(label_w - 10, y + bar_h - 3, label, anchor="end")) + w = value / top * plot_w + body.append(_bar(plot_x, y, w, bar_h, color, tip)) + body.append(_text(plot_x + w + 6, y + bar_h - 3, fmt(value), ink="primary")) + heights.append(y) + y += row_h + axis_y = y + 4 + grid = [] + for t in _ticks(top): + gx = plot_x + t / top * plot_w + grid.append(f'') + grid.append(_text(gx, axis_y + 16, f"{t:,.0f}", size=11, ink="muted", anchor="middle")) + grid.append(_text(plot_x + plot_w / 2, axis_y + 34, unit, size=12, ink="muted", anchor="middle")) + return _svg(width, int(axis_y + 44), title, grid + body) + + +def stacked_chart(rows, *, title, width=760, label_w=230) -> str: + """100% stacked bars: (label, wall label, shares by category, tip prefix).""" + names = {"read": "reading the store", "write": "writing (HDF5's gzip included)", + "compress": "gzip in Python", "text": "parsing or formatting text", + "compute": "other computing"} + plot_x, plot_w = label_w, width - label_w - 62 + row_h, bar_h, y0 = 28, 18, 64 + body = _legend(0, 18, [(SERIES[i], names[c]) for i, c in enumerate(CATEGORIES[:3])]) + body += _legend(0, 38, [(SERIES[i + 3], names[c]) for i, c in enumerate(CATEGORIES[3:])]) + y = y0 + for label, wall, shares, tip in rows: + if shares is None: + body.append(_text(0, y + 16, label, size=12, ink="primary", weight="600")) + y += row_h - 4 + continue + body.append(_text(label_w - 10, y + bar_h - 4, label, anchor="end")) + x = plot_x + parts = [(c, shares[c]) for c in CATEGORIES if shares[c] > 0.004] + for i, (c, share) in enumerate(parts): + w = share * plot_w + gap = 2 if i < len(parts) - 1 else 0 + body.append(f'{escape(tip)}: ' + f'{escape(names[c])}, {share:.0%}') + x += w + body.append(_text(plot_x + plot_w + 8, y + bar_h - 4, wall, ink="primary")) + y += row_h + for t in (0, 0.25, 0.5, 0.75, 1.0): + gx = plot_x + t * plot_w + body.append(_text(gx, y + 14, f"{t:.0%}", size=11, ink="muted", anchor="middle")) + body.append(_text(plot_x + plot_w / 2, y + 32, "share of wall time (pyinstrument samples)", + size=12, ink="muted", anchor="middle")) + body.append(_text(plot_x + plot_w + 8, y0 + 12, "wall", size=11, ink="muted")) + return _svg(width, y + 42, title, body) + + +def line_chart(series, *, title, width=760, height=330) -> str: + """Lines on a log x axis: (name, color, [(x, y, tip)]).""" + import math + + left, right, top, bottom = 56, 150, 44, 50 + xs = [p[0] for _, _, pts in series for p in pts] + ys = [p[1] for _, _, pts in series for p in pts] + lo, hi = math.log10(min(xs)) - 0.05, math.log10(max(xs)) + 0.05 + ytop = max(ys) * 1.1 + pw, ph = width - left - right, height - top - bottom + + def px(x): + return left + (math.log10(x) - lo) / (hi - lo) * pw + + def py(v): + return top + ph - v / ytop * ph + + body = _legend(0, 18, [(c, n) for n, c, _ in series]) + for t in _ticks(ytop): + body.append(f'') + body.append(_text(left - 8, py(t) + 4, f"{t:g}", size=11, ink="muted", anchor="end")) + for e in range(math.ceil(lo), math.floor(hi) + 1): + x = 10 ** e + body.append(f'') + body.append(_text(px(x), top + ph + 16, f"{x:,}", size=11, ink="muted", anchor="middle")) + body.append(_text(left + pw / 2, height - 8, "--chunk (rows, log scale)", size=12, ink="muted", + anchor="middle")) + body.append(_text(left - 8, top - 10, "minutes", size=11, ink="muted", anchor="end")) + for name, color, pts in series: + pts = sorted(pts) + d = " ".join(f"{'M' if i == 0 else 'L'}{px(x):.1f},{py(v):.1f}" for i, (x, v, _) in enumerate(pts)) + body.append(f'') + for x, v, tip in pts: + body.append(f'{escape(tip)}') + x, v, _ = pts[-1] + body.append(_text(px(x) + 10, py(v) + 4, name, size=12, ink="secondary")) + return _svg(width, height, title, body) + + +def dot_chart(rows, *, title, legend, ticks, unit, width=760, label_w=230) -> str: + """One row per item, a dot per series on a log x axis: (label, [(value, color, + hollow, tip)]). A hollow dot is a run the page sets apart.""" + import math + + values = [v for _, pts in rows for v, *_ in pts] + lo, hi = math.log10(min(min(values), ticks[0])), math.log10(max(max(values), ticks[-1])) + plot_x, plot_w = label_w, width - label_w - 24 + row_h, y0 = 26, 44 + + def px(v): + return plot_x + (math.log10(v) - lo) / (hi - lo) * plot_w + + body = _legend(0, 18, legend) + y_end = y0 + row_h * len(rows) + for t in ticks: + body.append(f'') + body.append(_text(px(t), y_end + 16, f"{t:g}", size=11, ink="muted", anchor="middle")) + body.append(_text(plot_x + plot_w / 2, y_end + 34, unit, size=12, ink="muted", anchor="middle")) + y = y0 + for label, pts in rows: + cy = y + row_h / 2 + body.append(_text(label_w - 10, cy + 4, label, anchor="end")) + body.append(f'') + for v, color, hollow, tip in pts: + fill, stroke = (INK["surface"], color) if hollow else (color, INK["surface"]) + body.append(f'{escape(tip)}') + y += row_h + return _svg(width, int(y_end + 44), title, body) + + +TIERS = (("lustre", "Lustre"), ("tmp", "node-local /tmp"), ("nfs", "NFS")) + + +def stalled(run: dict, others: list) -> bool: + """A run its node held up rather than its filesystem: most of its time + in the kernel, and five times the system time of the same work elsewhere.""" + least = min((o["sys_s"] for o in others), default=None) + return (run["sys_s"] > 0.5 * run["wall_s"] and least is not None + and run["sys_s"] > 5 * max(least, 1.0)) + + +STEP_NAMES = { + "subset_obs_h5ad": "subset --obs to h5ad", "subset_obs_zarr": "subset --obs to Zarr", + "subset_var": "subset --var", "split": "split --by", + "convert_zarr": "convert to Zarr", "convert_gzip": "convert to gzip h5ad", + "tenx_h5": "convert to 10x .h5", "tenx_h5_back": "convert 10x .h5 to h5ad", + "tenx_mtx": "convert to 10x MTX folder", "export_mtx": "export sparse to .mtx.gz", + "import_mtx": "import sparse from .mtx.gz", "export_obs": "export dataframe obs", + "loom": "convert to loom", +} + + +def _minutes(s: float) -> str: + return f"{s / 60:.1f} min" if s >= 60 else f"{s:.0f} s" + + +def charts(summary: dict, out: Path) -> None: + out.mkdir(parents=True, exist_ok=True) + ceiling = {(c["host"], c["trial"]): c for c in summary["ceiling"]} + + # Reads: the h5ad engines on Lustre, then the raw filesystem. + reads = {r["trial"]: r for r in summary["reads"] if r["tier"] == "lustre"} + picks = [("h5py-32M", "h5py, 32 MiB reads (adata today)", 0), + ("h5py-256M", "h5py, 256 MiB reads", 0), + ("zarr-pread-c64-256M", "zarr over HDF5 chunks, 64 in flight", 1), + ("zarr-pread-c32-32M", "zarr over HDF5 chunks, 32 in flight", 1), + ("duckdb-h5db-t8", "DuckDB h5db, 8 threads", 1), + ("duckdb-h5db-t32", "DuckDB h5db, 32 threads", 1), + ("zarr-obstore-c64-1G", "obstore ranged reads, 64 in flight", 1)] + rows = [("Reading X of the 55 GB store (4 GB regions)", None, 0, None, None)] + for trial, label, slot in picks: + r = reads[trial] + rows.append((None, label, r["mb_s"], SERIES[slot], + f"{label}: {r['mb_s']:.0f} MB/s, {r['cpu_s']:.0f} CPU s, on {r['host']}")) + rows.append(("Raw bytes, no format (median of 3 rounds)", None, 0, None, None)) + for trial, label in [("read-buffered-t1", "one stream"), + ("read-buffered-t4", "4 threads"), + ("read-direct-t16", "direct I/O, 16 in flight"), + ("read-direct-t32", "direct I/O, 32 in flight")]: + c = ceiling[("node-13-16", trial)] + rows.append((None, label, c["median_mb_s"], SERIES[2], + f"{label}: {c['median_mb_s']:,} MB/s ({c['min_mb_s']:,}–{c['max_mb_s']:,}), " + f"on {c['host']}")) + (out / "lustre-reads.svg").write_text(hbar_chart( + rows, title="Reading on Lustre: h5ad engines against the raw filesystem", + unit="MB/s", legend=[(SERIES[0], "adata's reader (h5py)"), (SERIES[1], "other engines"), + (SERIES[2], "raw filesystem")])) + + # Writes: 8 GB of X-like arrays on Lustre, then the raw filesystem. + writes = {(w["trial"]): w for w in summary["writes"] + if w["host"] == "node-13-07" and w["numpy_hugepage"] == "0"} + gzip = next(w for w in summary["writes"] if w["trial"] == "h5py-gzip" and w["tier"] == "lustre") + picks = [("h5py-anndata-chunks", "h5py, uncompressed (adata today)", 0), + ("zarr3-shard-none-default", "Zarr v3, uncompressed", 1), + ("zarr3-shard-none-zarrs-t32", "Zarr v3 + zarrs, uncompressed", 1), + ("zarr3-shard-none-zarrs-t32-direct", "… with direct I/O", 1), + ("zarr3-shard-zstd-default", "Zarr v3, zstd", 1), + ("zarr3-shard-zstd-zarrs-t32", "Zarr v3 + zarrs, zstd", 1), + ("zarr3-shard-zstd-zarrs-t32-direct", "… with direct I/O", 1)] + rows = [("Writing 8 GiB of values and indices (median of 3 rounds)", None, 0, None, None)] + rows.append((None, "h5py, gzip (one run)", gzip["median_mb_s"], SERIES[0], + f"h5py with gzip: {gzip['median_mb_s']:.0f} MB/s, one run on {gzip['host']}")) + for trial, label, slot in picks: + w = writes[trial] + rows.append((None, label, w["median_mb_s"], SERIES[slot], + f"{trial}: {w['median_mb_s']:.0f} MB/s (runs {', '.join(f'{v:.0f}' for v in w['mb_s'])}), " + f"{w['disk_gb']} GiB on disk")) + rows.append(("Raw bytes, no format (median of 3 rounds)", None, 0, None, None)) + for trial, label in [("write-buffered-t1", "one stream"), ("write-buffered-t8", "8 threads"), + ("write-direct-t8", "direct I/O, 8 in flight"), + ("write-direct-t16", "direct I/O, 16 in flight")]: + c = ceiling[("node-13-16", trial)] + rows.append((None, label, c["median_mb_s"], SERIES[2], + f"{label}: {c['median_mb_s']:,} MB/s ({c['min_mb_s']:,}–{c['max_mb_s']:,})")) + (out / "lustre-writes.svg").write_text(hbar_chart( + rows, title="Writing on Lustre: engines against the raw filesystem", + unit="MB/s of uncompressed data, fsync included", + legend=[(SERIES[0], "adata's writer (h5py)"), (SERIES[1], "other engines"), + (SERIES[2], "raw filesystem")])) + + # Where the time goes: the 1/4 slice of the 55 GB store, and the spatial store's loom. + profiles = {(p["label"], p["step"]): p for p in summary["profiles"]} + order = ["subset_obs_h5ad", "split", "subset_obs_zarr", "convert_zarr", "convert_gzip", + "tenx_h5", "tenx_h5_back", "tenx_mtx", "export_mtx", "import_mtx", "export_obs"] + rows = [("A quarter of the 55 GB store's cells (15.7 GB)", "", None, "")] + for step in order: + p = profiles[("cells_obs4", step)] + rows.append((STEP_NAMES[step], _minutes(p["wall_s"]), p["shares"], STEP_NAMES[step])) + rows.append(("The 6.7 GB store (4.27M × 480)", "", None, "")) + p = profiles[("spatial", "subset_obs_h5ad")] + rows.append(("subset --obs, before the floor", _minutes(p["wall_s"]), p["shares"], + "subset --obs of the 6.7 GB store, before the floor")) + p = profiles[("spatial", "loom")] + rows.append(("convert to loom", _minutes(p["wall_s"]), p["shares"], + "convert to loom, 6.7 GB store")) + (out / "lustre-time-split.svg").write_text(stacked_chart( + rows, title="Where each command's time goes, on Lustre")) + + # The filesystems: reads and writes by tier, then each command on the 6.7 GB store. + reads_by = {(r["tier"], r["trial"]): r for r in summary["reads"]} + writes_by = {(w["tier"], w["trial"]): w for w in summary["writes"] + if w["host"] in ("node-14-17", "node-14-15") and w["numpy_hugepage"] == "default"} + measures = [ + ("Reading with h5py, 32 MiB a read (adata)", lambda t: reads_by[(t, "h5py-32M")]["mb_s"]), + ("Reading with zarr over HDF5 chunks, 32 in flight", lambda t: reads_by[(t, "zarr-pread-c32-32M")]["mb_s"]), + ("Reading with DuckDB h5db, 8 threads", lambda t: reads_by[(t, "duckdb-h5db-t8")]["mb_s"]), + ("Writing with h5py, uncompressed (adata)", lambda t: writes_by[(t, "h5py-anndata-chunks")]["median_mb_s"]), + ("Writing with h5py, gzip (adata)", lambda t: writes_by[(t, "h5py-gzip")]["median_mb_s"]), + ("Writing Zarr v3 with zarrs, zstd, 32 threads", + lambda t: writes_by[(t, "zarr3-shard-zstd-zarrs-t32")]["median_mb_s"]), + ] + rows = [] + for heading, value in measures: + rows.append((heading, None, 0, None, None)) + for i, (tier, name) in enumerate(TIERS): + v = value(tier) + rows.append((None, name, v, SERIES[i], f"{heading}, {name}: {v:,.0f} MB/s")) + (out / "tiers-io.svg").write_text(hbar_chart( + rows, title="Reading and writing on Lustre, node-local /tmp and NFS", + unit="MB/s", label_w=150, legend=[(SERIES[i], name) for i, (_, name) in enumerate(TIERS)])) + + runs = {(c["step"], c["tier"]): c for c in summary["commands"] + if c["label"] == "spatial" and c["exit"] == 0} + order = ["subset_obs_h5ad", "subset_obs_zarr", "export_obs", "subset_var", "split", + "convert_zarr", "convert_gzip", "tenx_h5", "tenx_h5_back", "tenx_mtx", + "export_mtx", "import_mtx", "loom"] + rows = [] + for step in order: + pts = [] + for i, (tier, name) in enumerate(TIERS): + run = runs[(step, tier)] + others = [runs[(step, t)] for t, _ in TIERS if t != tier] + held = stalled(run, others) + tip = (f"{STEP_NAMES[step]} on {name}: {_minutes(run['wall_s'])}, " + f"{run['user_s']:.0f} s user and {run['sys_s']:.0f} s system time, on {run['host']}" + + (" (the node, not the filesystem: most of it in the kernel)" if held else "")) + pts.append((run["wall_s"] / 60, SERIES[i], held, tip)) + rows.append((STEP_NAMES[step], pts)) + (out / "tiers-commands.svg").write_text(dot_chart( + rows, title="The 6.7 GB store's commands on three filesystems", + legend=[(SERIES[i], name) for i, (_, name) in enumerate(TIERS)], + ticks=[0.5, 1, 2, 5, 10], unit="minutes (log scale); a hollow dot is a run its node held up")) + + # --chunk: wall time against the block size, on the main build. + series = [] + for label, what, name, slot in [("spatial", "subset_obs", "subset, 6.7 GB", 0), + ("spatial", "export_obs", "export obs, 6.7 GB", 1), + ("cells", "export_obs", "export obs, 55 GB", 2)]: + pts = [] + for c in summary["chunks"]: + if c["label"] == label and c["what"] == what and c["build"] == "main" \ + and c["host"] != "node-13-16": + m = statistics.mean(c["wall_s"]) / 60 + pts.append((c["chunk"], m, f"{name} at --chunk {c['chunk']:,}: " + + ", ".join(_minutes(s) for s in c["wall_s"]) + + f" (peak {c['rss_mb']:,} MB)")) + series.append((name, SERIES[slot], pts)) + (out / "lustre-chunk.svg").write_text(line_chart( + series, title="Wall time against --chunk on Lustre, before the floor")) + + # Before and after the 32 MiB floor, on one node. + rows = [("subset --obs of half the 6.7 GB store's cells, node-13-16", None, 0, None, None)] + for build, chunk, label, slot in [("main", 1024, "main, --chunk 1,024", 1), + ("floor", 1024, "32 MiB floor, --chunk 1,024", 0), + ("floor", 65536, "32 MiB floor, --chunk 65,536", 0)]: + c = next(c for c in summary["chunks"] if c["build"] == build and c["chunk"] == chunk + and c["host"] == "node-13-16") + m = statistics.mean(c["wall_s"]) / 60 + rows.append((None, label, m, SERIES[slot], + f"{label}: " + ", ".join(_minutes(s) for s in c["wall_s"]) + + f", peak {c['rss_mb']:,} MB")) + (out / "lustre-floor.svg").write_text(hbar_chart( + rows, title="Sparse subset before and after the 32 MiB floor", + unit="minutes, mean of 2 runs", label_w=220, + legend=[(SERIES[1], "main"), (SERIES[0], "with the floor (#129)")], + fmt=lambda v: f"{v:.1f} min")) + + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = p.add_subparsers(dest="cmd", required=True) + s = sub.add_parser("summarise") + s.add_argument("results", type=Path) + s.add_argument("profiles", type=Path) + s.add_argument("-o", "--out", type=Path, required=True) + c = sub.add_parser("charts") + c.add_argument("summary", type=Path) + c.add_argument("-o", "--out", type=Path, required=True) + args = p.parse_args() + if args.cmd == "summarise": + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(summarise(args.results, args.profiles), indent=1) + "\n") + else: + charts(json.loads(args.summary.read_text()), args.out) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/lustre/h5chunks.py b/benchmarks/lustre/h5chunks.py new file mode 100644 index 0000000..8dee3b8 --- /dev/null +++ b/benchmarks/lustre/h5chunks.py @@ -0,0 +1,206 @@ +"""A read-only zarr store over one HDF5 dataset's chunks. + +The probe's version of the Phase 2 design. libhdf5 is used once, to find +where each chunk lives (`chunk_iter`); after that zarr-python's own engine +fetches the chunks of a read concurrently (`async.concurrency`) and decodes +them on its threads. An HDF5 chunk that is uncompressed, or deflated with or +without shuffle, is a byte range zarr can decode with numcodecs Zlib and +Shuffle, so libhdf5 -- one call at a time, behind h5py's lock -- is off the +data path. A contiguous dataset is cut into virtual chunks, which is +possible because it is uncompressed. + +Two ways to fetch a byte range are compared: `os.pread` on a shared file +descriptor, run in zarr's thread pool, and obstore's Rust `get_range_async`. +""" + +from __future__ import annotations + +import asyncio +import json +import os +from typing import Any, AsyncIterator, Iterable, Optional + +import h5py +import numpy as np +from zarr.abc.store import ByteRequest, Store +from zarr.core.buffer import Buffer, BufferPrototype, default_buffer_prototype + +#: Bytes per virtual chunk of a contiguous dataset. +VIRTUAL_CHUNK_BYTES = 8 << 20 + + +class Unsupported(ValueError): + """A dataset this store cannot map (the caller falls back to h5py).""" + + +def _codecs(ds: h5py.Dataset) -> tuple: + """zarr v2 `(compressor, filters)` equal to the dataset's HDF5 filters.""" + plist = ds.id.get_create_plist() + pipeline = [plist.get_filter(i)[0] for i in range(plist.get_nfilters())] + compressor = None + filters = [] + for code in pipeline: + if code == h5py.h5z.FILTER_SHUFFLE and compressor is None: + filters.append({"id": "shuffle", "elementsize": ds.dtype.itemsize}) + elif code == h5py.h5z.FILTER_DEFLATE and compressor is None: + # Decoding ignores the level; it only has to name zlib. + compressor = {"id": "zlib", "level": 1} + else: + raise Unsupported(f"{ds.name}: HDF5 filter {code} in pipeline {pipeline}") + return compressor, filters or None + + +def describe(ds: h5py.Dataset) -> tuple: + """`(zarray, ranges, pad)`: zarr v2 metadata, chunk key -> `(offset, + size)`, and the full size a short last chunk is padded to (contiguous + datasets only).""" + dtype = ds.dtype + if dtype.kind not in "biuf" or dtype.fields is not None or not ds.shape: + raise Unsupported(f"{ds.name}: dtype {dtype} shape {ds.shape}") + compressor, filters = _codecs(ds) + meta = { + "zarr_format": 2, + "shape": list(ds.shape), + "dtype": dtype.str, + "compressor": compressor, + "filters": filters, + "fill_value": ds.fillvalue.item() if hasattr(ds.fillvalue, "item") else ds.fillvalue, + "order": "C", + "dimension_separator": ".", + } + ranges: dict = {} + pad = 0 + if ds.chunks: + chunks = tuple(int(c) for c in ds.chunks) + meta["chunks"] = list(chunks) + + def keep(info: Any) -> None: + if info.byte_offset is None: + return # unallocated: zarr fills it + key = ".".join(str(o // c) for o, c in zip(info.chunk_offset, chunks)) + ranges[key] = (int(info.byte_offset), int(info.size)) + + ds.id.chunk_iter(keep) + else: + row = dtype.itemsize * int(np.prod(ds.shape[1:], dtype=np.int64)) + rows = max(1, VIRTUAL_CHUNK_BYTES // max(1, row)) + meta["chunks"] = [rows] + list(ds.shape[1:]) + base = ds.id.get_offset() + total = row * int(ds.shape[0]) + pad = rows * row + if base is not None: + tail = (0,) * (len(ds.shape) - 1) + for i in range(-(-int(ds.shape[0]) // rows)): + key = ".".join(str(k) for k in (i,) + tail) + start = i * pad + ranges[key] = (int(base) + start, min(pad, total - start)) + return meta, ranges, pad + + +class H5ChunkStore(Store): + """Read-only: `.zarray` is made up, chunk keys are byte ranges of the file.""" + + supports_writes = False + supports_deletes = False + supports_partial_writes = False + supports_listing = False + + def __init__(self, path: str, dataset: str, *, fetch: str = "pread") -> None: + super().__init__(read_only=True) + self.path = os.path.abspath(path) + self.dataset = dataset + with h5py.File(self.path, "r") as f: + self.meta, self.ranges, self.pad = describe(f[dataset]) + self.fetch = fetch + self.fd = os.open(self.path, os.O_RDONLY) + self._obstore = None + if fetch == "obstore": + from obstore.store import LocalStore + + self._obstore = LocalStore(prefix=os.path.dirname(self.path)) + self._name = os.path.basename(self.path) + + def close(self) -> None: + if self.fd is not None: + os.close(self.fd) + self.fd = None + super().close() + + def __eq__(self, other: object) -> bool: + return other is self + + def _pread(self, offset: int, size: int) -> bytes: + parts = [] + while size: + got = os.pread(self.fd, size, offset) + if not got: + raise OSError(f"short read at {offset} of {self.path}") + parts.append(got) + offset += len(got) + size -= len(got) + return parts[0] if len(parts) == 1 else b"".join(parts) + + async def _fetch(self, offset: int, size: int) -> bytes: + if self._obstore is not None: + import obstore + + got = await obstore.get_range_async( + self._obstore, self._name, start=offset, length=size + ) + return bytes(got) + return await asyncio.to_thread(self._pread, offset, size) + + async def get( + self, key: str, prototype: Optional[BufferPrototype] = None, + byte_range: Optional[ByteRequest] = None, + ) -> Optional[Buffer]: + prototype = prototype or default_buffer_prototype() + if key == ".zarray": + return prototype.buffer.from_bytes(json.dumps(self.meta).encode()) + where = self.ranges.get(key) + if where is None: + return None + data = await self._fetch(*where) + if self.pad and len(data) < self.pad: + data = data + bytes(self.pad - len(data)) + return prototype.buffer.from_bytes(data) + + async def get_partial_values( + self, prototype: BufferPrototype, key_ranges: Iterable[tuple] + ) -> list: + return [await self.get(k, prototype, r) for k, r in key_ranges] + + async def exists(self, key: str) -> bool: + return key == ".zarray" or key in self.ranges + + async def set(self, key: str, value: Buffer) -> None: + raise NotImplementedError + + async def delete(self, key: str) -> None: + raise NotImplementedError + + async def clear(self) -> None: + raise NotImplementedError + + async def is_empty(self, prefix: str) -> bool: + return False + + async def list(self) -> AsyncIterator[str]: + for key in (".zarray", *self.ranges): + yield key + + async def list_prefix(self, prefix: str) -> AsyncIterator[str]: + async for key in self.list(): + if key.startswith(prefix): + yield key + + async def list_dir(self, prefix: str) -> AsyncIterator[str]: + if False: # pragma: no cover - flat store + yield "" + + +def open_array(path: str, dataset: str, *, fetch: str = "pread") -> Any: + """A read-only zarr array over `dataset` of the HDF5 file at `path`.""" + import zarr + + return zarr.open_array(H5ChunkStore(path, dataset, fetch=fetch), mode="r", zarr_format=2) diff --git a/benchmarks/lustre/io_read.py b/benchmarks/lustre/io_read.py new file mode 100644 index 0000000..1ed13cf --- /dev/null +++ b/benchmarks/lustre/io_read.py @@ -0,0 +1,230 @@ +"""Job B: read engines on one h5ad's X/data and X/indices. + + python io_read.py --file F --tier T --out R.jsonl [--anndata-slice S] + [--duckdb-ext DIR] [--trials NAME,NAME,...] + +Each trial reads its own region of the two arrays, so no trial reads bytes +an earlier one brought into the page or Lustre client cache; the whole file +is dropped from the cache before each trial as well. One JSON line per +trial: engine, settings, bytes, wall, CPU (all threads), MB/s. + +Engines: +- `h5py`: today's path, `ds[lo:hi]` blocks. +- `zarr-pread`, `zarr-obstore`: the HDF5-chunk zarr view (`h5chunks.py`) + at a given `async.concurrency` and block size. +- `duckdb-h5db`: DuckDB's h5db extension, `sum()` over an index range, at a + given DuckDB thread count. +- `duckdb-anndata`: DuckDB's anndata extension scanning X of a small slice + (it exposes X one column per gene, so only a slice is practical). +""" + +from __future__ import annotations + +import argparse +import json +import os +import resource +import socket +import subprocess +import sys +import time +from pathlib import Path + +import h5py +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import h5chunks # noqa: E402 + +MiB = 1 << 20 +GiB = 1 << 30 + +#: name -> (engine, settings). Order is the order they run. +TRIALS = { + "h5py-32M": ("h5py", {"block": 32 * MiB}), + "h5py-256M": ("h5py", {"block": 256 * MiB}), + "zarr-pread-c1-32M": ("zarr-pread", {"concurrency": 1, "block": 32 * MiB}), + "zarr-pread-c8-32M": ("zarr-pread", {"concurrency": 8, "block": 32 * MiB}), + "zarr-pread-c32-32M": ("zarr-pread", {"concurrency": 32, "block": 32 * MiB}), + "zarr-pread-c8-256M": ("zarr-pread", {"concurrency": 8, "block": 256 * MiB}), + "zarr-pread-c32-256M": ("zarr-pread", {"concurrency": 32, "block": 256 * MiB}), + "zarr-pread-c64-256M": ("zarr-pread", {"concurrency": 64, "block": 256 * MiB}), + "zarr-pread-c64-1G": ("zarr-pread", {"concurrency": 64, "block": 1024 * MiB}), + "zarr-obstore-c32-256M": ("zarr-obstore", {"concurrency": 32, "block": 256 * MiB}), + "zarr-obstore-c64-1G": ("zarr-obstore", {"concurrency": 64, "block": 1024 * MiB}), + "duckdb-h5db-t1": ("duckdb-h5db", {"threads": 1}), + "duckdb-h5db-t8": ("duckdb-h5db", {"threads": 8}), + "duckdb-h5db-t32": ("duckdb-h5db", {"threads": 32}), +} + + +def drop_cache(path: str) -> None: + try: + fd = os.open(path, os.O_RDONLY) + os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED) + os.close(fd) + except (OSError, AttributeError): + pass + if path.startswith("/lustre"): + subprocess.run(["lfs", "ladvise", "-a", "dontneed", path], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def regions(path: str, n: int, cap: int) -> list: + """`n` disjoint `(dataset, lo, hi)` element ranges across X/data and + X/indices, each at most `cap` bytes.""" + with h5py.File(path, "r") as f: + arrays = [(name, f[name].shape[0], f[name].dtype.itemsize) + for name in ("X/data", "X/indices")] + per = -(-n // len(arrays)) + out = [] + for name, length, itemsize in arrays: + step = min(cap // itemsize, length // per) + for i in range(per): + out.append((name, i * step, (i + 1) * step)) + return out[:n] + + +def read_h5py(path, name, lo, hi, block) -> int: + with h5py.File(path, "r", rdcc_nbytes=1 << 20) as f: + ds = f[name] + step = max(1, block // ds.dtype.itemsize) + total = 0 + for a in range(lo, hi, step): + total += ds[a:min(hi, a + step)].nbytes + return total + + +def read_zarr(path, name, lo, hi, block, concurrency, fetch) -> int: + import zarr + + with zarr.config.set({"async.concurrency": concurrency}): + z = h5chunks.open_array(path, name, fetch=fetch) + step = max(1, block // z.dtype.itemsize) + total = 0 + for a in range(lo, hi, step): + total += z[a:min(hi, a + step)].nbytes + z.store.close() + return total + + +def _duckdb(ext_dir, threads): + import duckdb + + con = duckdb.connect(config={"threads": threads, "extension_directory": ext_dir, + "autoinstall_known_extensions": False}) + return con + + +def read_h5db(path, name, lo, hi, threads, ext_dir) -> int: + con = _duckdb(ext_dir, threads) + con.execute("LOAD h5db") + col = name.rsplit("/", 1)[1] + con.execute( + f"SELECT sum({col}::DOUBLE) FROM h5_read(?, h5_index(), ?) " + f"WHERE index >= {int(lo)} AND index < {int(hi)}", + [path, "/" + name], + ).fetchall() + with h5py.File(path, "r") as f: + return (hi - lo) * f[name].dtype.itemsize + + +def check(path) -> dict: + """The zarr view reads what h5py reads, at the edges that matter.""" + out = {} + with h5py.File(path, "r") as f: + for name in ("X/data", "X/indices"): + ds = f[name] + z = h5chunks.open_array(path, name) + n = ds.shape[0] + c = ds.chunks[0] if ds.chunks else 1000 + spans = [(0, 10), (c - 5, c + 5), (n // 2, n // 2 + 3 * c + 7), (max(0, n - 10), n)] + out[name] = all(np.array_equal(z[a:b], ds[a:b]) for a, b in spans) + z.store.close() + return out + + +def run_trial(path, engine, settings, region, ext_dir) -> dict: + name, lo, hi = region + drop_cache(path) + before = resource.getrusage(resource.RUSAGE_SELF) + started = time.perf_counter() + if engine == "h5py": + nbytes = read_h5py(path, name, lo, hi, settings["block"]) + elif engine in ("zarr-pread", "zarr-obstore"): + nbytes = read_zarr(path, name, lo, hi, settings["block"], settings["concurrency"], + engine.split("-")[1]) + elif engine == "duckdb-h5db": + nbytes = read_h5db(path, name, lo, hi, settings["threads"], ext_dir) + else: + raise ValueError(engine) + wall = time.perf_counter() - started + after = resource.getrusage(resource.RUSAGE_SELF) + cpu = (after.ru_utime - before.ru_utime) + (after.ru_stime - before.ru_stime) + return {"dataset": name, "lo": lo, "hi": hi, "bytes": nbytes, "wall_s": round(wall, 3), + "cpu_s": round(cpu, 3), "mb_s": round(nbytes / wall / 1e6, 1)} + + +def anndata_scan(path, ext_dir, threads, timeout, python) -> dict: + """DuckDB's anndata extension over X of `path`, in a child process so a + scan that runs away can be cut off. The extension is published for + DuckDB 1.5.x only, so `python` is an interpreter with that DuckDB.""" + code = ( + "import duckdb,sys,time;" + f"c=duckdb.connect(config={{'threads':{threads},'extension_directory':{ext_dir!r}," + "'autoinstall_known_extensions':False});c.execute('LOAD anndata');" + "t=time.perf_counter();" + f"n=c.execute('SELECT count(*) FROM anndata_scan_x(?)',[{path!r}]).fetchone()[0];" + "print(n, time.perf_counter()-t)" + ) + started = time.perf_counter() + try: + done = subprocess.run([python, "-c", code], capture_output=True, text=True, + timeout=timeout) + return {"exit": done.returncode, "wall_s": round(time.perf_counter() - started, 2), + "stdout": done.stdout.strip()[-500:], "stderr": done.stderr.strip()[-500:]} + except subprocess.TimeoutExpired: + return {"exit": "timeout", "wall_s": timeout} + + +def main() -> None: + p = argparse.ArgumentParser() + p.add_argument("--file", required=True) + p.add_argument("--tier", required=True) + p.add_argument("--out", required=True) + p.add_argument("--trials", default=",".join(TRIALS)) + p.add_argument("--region-cap", type=int, default=3 * GiB) + p.add_argument("--duckdb-ext", default=os.environ.get("DUCKDB_EXT", "")) + p.add_argument("--anndata-slice") + p.add_argument("--anndata-timeout", type=int, default=3600) + p.add_argument("--anndata-python", default=os.environ.get("DUCK15", sys.executable)) + args = p.parse_args() + + names = [t for t in args.trials.split(",") if t] + base = {"host": socket.gethostname(), "tier": args.tier, "file": args.file, + "nproc": os.environ.get("LSB_DJOB_NUMPROC", str(os.cpu_count()))} + + def emit(row): + with open(args.out, "a") as fh: + fh.write(json.dumps({**base, **row}) + "\n") + print(json.dumps(row), flush=True) + + emit({"trial": "check", "matches_h5py": check(args.file)}) + spans = regions(args.file, len(names), args.region_cap) + for name, region in zip(names, spans): + engine, settings = TRIALS[name] + try: + row = run_trial(args.file, engine, settings, region, args.duckdb_ext) + except Exception as error: # keep going: one engine failing is a result too + row = {"error": f"{type(error).__name__}: {error}"[:500]} + emit({"trial": name, "engine": engine, **settings, **row}) + if args.anndata_slice: + for threads in (1, 32): + emit({"trial": f"duckdb-anndata-t{threads}", "engine": "duckdb-anndata", + "threads": threads, "file_bytes": os.path.getsize(args.anndata_slice), + **anndata_scan(args.anndata_slice, args.duckdb_ext, threads, + args.anndata_timeout, args.anndata_python)}) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/lustre/io_write.py b/benchmarks/lustre/io_write.py new file mode 100644 index 0000000..5de97ff --- /dev/null +++ b/benchmarks/lustre/io_write.py @@ -0,0 +1,197 @@ +"""Job C: write engines into one directory of a storage tier. + + python io_write.py --dir D --tier T --out R.jsonl [--gb 8] [--trials ...] [--rounds N] + +Each trial writes the same synthetic CSR-like pair -- float64 counts and +sorted int64 column indices, as the 55 GB store holds -- in blocks of 256 +MiB, the way a streaming command fills an output. Two times are kept: +`write_s` to the end of the write and close, and `sync_s` for an fsync of +everything written after it, since a write that only reached the page +cache is not finished. The output is deleted after each trial. + +The `-direct` trials set zarrs' `codec_pipeline.direct_io`, which writes +with O_DIRECT, past the page cache: on Lustre one node writes about four +times as fast that way, with a fraction of the CPU (Job F). `--rounds N` +runs the trials N times, each round in its own shuffled order. +""" + +from __future__ import annotations + +import argparse +import json +import os +import random +import resource +import shutil +import socket +import time +from pathlib import Path + +import h5py +import numpy as np + +MiB = 1 << 20 +BLOCK = 256 * MiB +#: anndata's h5py-guessed chunk for the 55 GB store's data and indices. +ANNDATA_CHUNK = 51915 + +TRIALS = { + "h5py-anndata-chunks": ("h5py", {"chunks": ANNDATA_CHUNK, "compression": None}), + "h5py-16M-chunks": ("h5py", {"chunks": 2 * MiB, "compression": None}), + "h5py-gzip": ("h5py", {"chunks": ANNDATA_CHUNK, "compression": "gzip"}), + "zarr2-512K-none": ("zarr", {"format": 2, "codec": "none", "pipeline": "default", "threads": 32}), + "zarr3-shard-none-default": ("zarr", {"format": 3, "codec": "none", "pipeline": "default", "threads": 32}), + "zarr3-shard-zstd-default": ("zarr", {"format": 3, "codec": "zstd", "pipeline": "default", "threads": 32}), + "zarr3-shard-none-zarrs-t32": ("zarr", {"format": 3, "codec": "none", "pipeline": "zarrs", "threads": 32}), + "zarr3-shard-zstd-zarrs-t1": ("zarr", {"format": 3, "codec": "zstd", "pipeline": "zarrs", "threads": 1}), + "zarr3-shard-zstd-zarrs-t8": ("zarr", {"format": 3, "codec": "zstd", "pipeline": "zarrs", "threads": 8}), + "zarr3-shard-zstd-zarrs-t32": ("zarr", {"format": 3, "codec": "zstd", "pipeline": "zarrs", "threads": 32}), + "zarr3-shard-none-zarrs-t32-direct": ("zarr", {"format": 3, "codec": "none", "pipeline": "zarrs", "threads": 32, "direct": True}), + "zarr3-shard-zstd-zarrs-t8-direct": ("zarr", {"format": 3, "codec": "zstd", "pipeline": "zarrs", "threads": 8, "direct": True}), + "zarr3-shard-zstd-zarrs-t32-direct": ("zarr", {"format": 3, "codec": "zstd", "pipeline": "zarrs", "threads": 32, "direct": True}), +} + + +def blocks(total_bytes: int): + """(data, indices) blocks of BLOCK bytes each, generated once and reused: + what the engines see per block is realistic, and generating 8 GB of + random numbers would cost more than writing it.""" + n = BLOCK // 8 + rng = np.random.default_rng(0) + data = rng.geometric(0.4, n).astype(np.float64) + indices = np.sort(rng.integers(0, 12288, (n // 2048, 2048)), axis=1).astype(np.int64).ravel() + for _ in range(max(1, total_bytes // 2 // BLOCK)): + yield data, indices + + +def fsync_tree(path: Path) -> None: + files = [path] if path.is_file() else [Path(r) / f for r, _, fs in os.walk(path) for f in fs] + for f in files: + fd = os.open(f, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def write_h5py(target: Path, total: int, chunks: int, compression) -> int: + kw = {"chunks": (chunks,), "maxshape": (None,)} + if compression: + kw.update(compression=compression, compression_opts=4) + written = 0 + with h5py.File(target, "w", rdcc_nbytes=1 << 20) as f: + d = f.create_dataset("data", shape=(0,), dtype="f8", **kw) + i = f.create_dataset("indices", shape=(0,), dtype="i8", **kw) + at = 0 + for data, indices in blocks(total): + end = at + data.shape[0] + d.resize((end,)) + i.resize((end,)) + d[at:end] = data + i[at:end] = indices + at = end + written += data.nbytes + indices.nbytes + return written + + +def write_zarr(target: Path, total: int, fmt: int, codec: str, pipeline: str, threads: int, + direct: bool = False) -> int: + import zarr + + n_total = (max(1, total // 2 // BLOCK) * BLOCK) // 8 + config = {"threading.max_workers": threads} + if pipeline == "zarrs": + config["codec_pipeline.path"] = "zarrs.ZarrsCodecPipeline" + config["codec_pipeline.direct_io"] = direct + written = 0 + with zarr.config.set(config): + root = zarr.open_group(str(target), mode="w", zarr_format=fmt) + kw: dict = {"shape": (n_total,), "chunks": (65536,)} + if fmt == 3: + kw["shards"] = (BLOCK // 8 // 8,) # 32 MiB shards of 512 KiB chunks + kw["compressors"] = None if codec == "none" else zarr.codecs.ZstdCodec(level=3) + else: + import numcodecs + + kw["compressors"] = None if codec == "none" else numcodecs.Zstd(level=3) + d = root.create_array("data", dtype="f8", **kw) + i = root.create_array("indices", dtype="i8", **kw) + at = 0 + for data, indices in blocks(total): + end = at + data.shape[0] + d[at:end] = data + i[at:end] = indices + at = end + written += data.nbytes + indices.nbytes + return written + + +def main() -> None: + p = argparse.ArgumentParser() + p.add_argument("--dir", required=True) + p.add_argument("--tier", required=True) + p.add_argument("--out", required=True) + p.add_argument("--gb", type=float, default=8) + p.add_argument("--trials", default=",".join(TRIALS)) + p.add_argument("--rounds", type=int, default=1) + args = p.parse_args() + root = Path(args.dir) + root.mkdir(parents=True, exist_ok=True) + total = int(args.gb * (1 << 30)) + # numpy asks for transparent huge pages on arrays of 4 MiB and more; on + # a node whose memory is fragmented, each page fault then stalls in + # compaction, and a write runs a hundred times slower, all of it in the + # kernel. NUMPY_MADVISE_HUGEPAGE=0 turns that off; the row says which. + base = {"host": socket.gethostname(), "tier": args.tier, "dir": str(root), + "nproc": os.environ.get("LSB_DJOB_NUMPROC", str(os.cpu_count())), + "numpy_hugepage": os.environ.get("NUMPY_MADVISE_HUGEPAGE", "default")} + names = [t for t in args.trials.split(",") if t] + runs = [] + for number in range(1, args.rounds + 1): + order = list(names) + if args.rounds > 1: + random.Random(number).shuffle(order) + runs += [(number, name) for name in order] + for number, name in runs: + engine, settings = TRIALS[name] + target = root / (name + (".h5" if engine == "h5py" else ".zarr")) + shutil.rmtree(target, ignore_errors=True) if target.is_dir() else target.unlink(missing_ok=True) + row = {"trial": name, "engine": engine, **settings} + if args.rounds > 1: + row["round"] = number + try: + before = resource.getrusage(resource.RUSAGE_SELF) + started = time.perf_counter() + if engine == "h5py": + nbytes = write_h5py(target, total, settings["chunks"], settings["compression"]) + else: + nbytes = write_zarr(target, total, settings["format"], settings["codec"], + settings["pipeline"], settings["threads"], + settings.get("direct", False)) + wrote = time.perf_counter() + fsync_tree(target) + synced = time.perf_counter() + after = resource.getrusage(resource.RUSAGE_SELF) + files = 1 if target.is_file() else sum(len(fs) for _, _, fs in os.walk(target)) + disk = target.stat().st_size if target.is_file() else sum( + (Path(r) / f).stat().st_size for r, _, fs in os.walk(target) for f in fs) + row.update({ + "bytes": nbytes, "disk_bytes": disk, "files": files, + "write_s": round(wrote - started, 2), "sync_s": round(synced - wrote, 2), + "cpu_s": round((after.ru_utime - before.ru_utime) + (after.ru_stime - before.ru_stime), 2), + "mb_s": round(nbytes / (synced - started) / 1e6, 1), + }) + except Exception as error: + row["error"] = f"{type(error).__name__}: {error}"[:500] + finally: + if target.is_dir(): + shutil.rmtree(target, ignore_errors=True) + else: + target.unlink(missing_ok=True) + with open(args.out, "a") as fh: + fh.write(json.dumps({**base, **row}) + "\n") + print(json.dumps(row), flush=True) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/lustre/job_a.sh b/benchmarks/lustre/job_a.sh new file mode 100755 index 0000000..c80491c --- /dev/null +++ b/benchmarks/lustre/job_a.sh @@ -0,0 +1,116 @@ +#!/bin/bash +# Job A: today's adata on one input, one step per array element. +# +# Environment (set by submit.sh): +# PROBE probe root on Lustre (env.sh, meta/, results/, logs/) +# TIER lustre | tmp | nfs +# LABEL input label (its name lists and layout are in meta/$LABEL) +# SRC the input h5ad (on Lustre for lustre and tmp, on NFS for nfs) +# STEPS space-separated steps; element $LSB_JOBINDEX picks one. +# An element may also be "label:step" when one array covers +# several inputs (the NFS array); then LABEL and SRC come from +# meta/inputs.tsv. +# PROFILE 1 to run the step under pyinstrument (profiles in profiles/) +set -uo pipefail +source "$PROBE/scripts/env.sh" + +read -r -a ALL <<< "$STEPS" +ITEM=${ALL[$(( ${LSB_JOBINDEX:-1} - 1 ))]} +if [[ "$ITEM" == *:* ]]; then + LABEL=${ITEM%%:*} + STEP=${ITEM#*:} + SRC=$(awk -v l="$LABEL" -v t="$TIER" '$1==l && $2==t {print $3}' "$PROBE/meta/inputs.tsv") +else + STEP=$ITEM +fi +META=$PROBE/meta/$LABEL +SUFFIX="" +[[ "${PROFILE:-0}" == 1 ]] && SUFFIX=_profile +RESULTS=$PROBE/results/a_${TIER}_${LABEL}${SUFFIX}.tsv +LOG=$PROBE/logs/a_${TIER}_${LABEL}_${STEP}${SUFFIX}.log +layout() { "$PY" -c "import json,sys; v=json.load(open('$META/layout.json'))['$1']; print('' if v is None else v)"; } + +case "$TIER" in + lustre) WORK=$PROBE/work/lustre/$LABEL/$STEP ;; + nfs) WORK=$NFS_ROOT/work/$LABEL/$STEP ;; + tmp) WORK=/tmp/adata-probe-${LSB_JOBID:-$$}-${LSB_JOBINDEX:-0} ;; +esac +rm -rf "$WORK" +mkdir -p "$WORK" +trap 'rm -rf "$WORK"' EXIT + +m() { # m STEP [measure.py options] -- command + local step=$1; shift + local prof=() + [[ "${PROFILE:-}" == 1 ]] && prof=(--profile "$PROBE/profiles/${TIER}_${LABEL}_${step}.pyisession") + "$PY" "$PROBE/scripts/measure.py" --results "$RESULTS" --tier "$TIER" --label "$LABEL" \ + --step "$step" --log "$LOG" ${prof[@]+"${prof[@]}"} "$@" +} + +IN=$SRC +if [[ "$TIER" == tmp ]]; then + IN=$WORK/in.h5ad + m stage_in --input "$SRC" --output "$IN" --keep -- cp "$SRC" "$IN" +fi + +echo "$(date) host=$(hostname) tier=$TIER label=$LABEL step=$STEP in=$IN work=$WORK" >> "$LOG" +case "$STEP" in + subset_obs_h5ad) + m "$STEP" --input "$IN" --output "$WORK/out.h5ad" -- \ + "$ADATA" subset "$IN" -o "$WORK/out.h5ad" --obs "$META/obs_half.txt" --no-space-check ;; + subset_obs_zarr) + m "$STEP" --input "$IN" --output "$WORK/out.zarr" -- \ + "$ADATA" subset "$IN" -o "$WORK/out.zarr" --obs "$META/obs_half.txt" --no-space-check ;; + subset_var) + m "$STEP" --input "$IN" --output "$WORK/out.h5ad" -- \ + "$ADATA" subset "$IN" -o "$WORK/out.h5ad" --var "$META/var_half.txt" --no-space-check ;; + split) + BY=$(layout split_by) + if [[ -n "$BY" ]]; then + m "$STEP" --input "$IN" --output "$WORK/split" -- \ + "$ADATA" split "$IN" --by "$BY" -o "$WORK/split" --no-manifest --no-space-check + fi ;; + convert_zarr) + m "$STEP" --input "$IN" --output "$WORK/out.zarr" -- \ + "$ADATA" convert "$IN" -o "$WORK/out.zarr" --no-space-check ;; + convert_gzip) + m "$STEP" --input "$IN" --output "$WORK/out.h5ad" -- \ + "$ADATA" convert "$IN" -o "$WORK/out.h5ad" --compression gzip --no-space-check ;; + tenx_h5) + m tenx_h5 --input "$IN" --output "$WORK/out.h5" --keep -- \ + "$ADATA" convert "$IN" -o "$WORK/out.h5" --to 10x-h5 --force --no-space-check + if [[ -f "$WORK/out.h5" ]]; then + m tenx_h5_back --input "$WORK/out.h5" --output "$WORK/back.h5ad" -- \ + "$ADATA" convert "$WORK/out.h5" -o "$WORK/back.h5ad" --no-space-check + fi ;; + tenx_mtx) + m "$STEP" --input "$IN" --output "$WORK/mtx" -- \ + "$ADATA" convert "$IN" -o "$WORK/mtx" --to 10x-mtx --force --no-space-check ;; + loom) + # loom stores X dense: only where that stays under 20 GB. + if (( $(layout dense_bytes) <= 20000000000 )); then + m "$STEP" --input "$IN" --output "$WORK/out.loom" -- \ + "$ADATA" convert "$IN" -o "$WORK/out.loom" --no-space-check + fi ;; + mtx) + m export_mtx --input "$IN" --output "$WORK/X.mtx.gz" --keep -- \ + "$ADATA" export sparse "$IN" X -o "$WORK/X.mtx.gz" + if [[ -f "$WORK/X.mtx.gz" ]]; then + m import_mtx --input "$WORK/X.mtx.gz" --output "$WORK/imp.h5ad" -- \ + "$ADATA" import sparse "$IN" X "$WORK/X.mtx.gz" -o "$WORK/imp.h5ad" --no-space-check + fi ;; + export_obs) + m "$STEP" --input "$IN" --output "$WORK/obs.csv" -- \ + "$ADATA" export dataframe "$IN" obs -o "$WORK/obs.csv" ;; + export_var) + m "$STEP" --input "$IN" --output "$WORK/var.csv" -- \ + "$ADATA" export dataframe "$IN" var -o "$WORK/var.csv" ;; + export_obsm) + KEY=$(layout obsm_first) + if [[ -n "$KEY" ]]; then + m "$STEP" --input "$IN" --output "$WORK/obsm.npy" -- \ + "$ADATA" export array "$IN" "obsm/$KEY" -o "$WORK/obsm.npy" + fi ;; + *) + echo "unknown step $STEP" >&2; exit 2 ;; +esac diff --git a/benchmarks/lustre/job_ceiling.sh b/benchmarks/lustre/job_ceiling.sh new file mode 100755 index 0000000..7dfc6d3 --- /dev/null +++ b/benchmarks/lustre/job_ceiling.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# Job F: what one node can read from and write to Lustre (ceiling.py). +# +# Environment (set by submit.sh): +# PROBE probe root on Lustre +# CEILING_OTHER the second input, for two files at once (default peaks) +# CEILING_POOL more inputs to read regions from (labels; default none) +# ROUNDS, REGION_MIB, WRITE_MIB as ceiling.py's options (1, 4096, 8192) +set -euo pipefail +source "$PROBE/scripts/env.sh" +WORK=$PROBE/work/ceiling +rm -rf "$WORK" +mkdir -p "$WORK" +trap 'rm -rf "$WORK"' EXIT +echo "$(date) host=$(hostname)" +pool=() +for label in ${CEILING_POOL:-}; do pool+=("$(input_path "$label")"); done +"$PY" "$PROBE/scripts/ceiling.py" --file "$(input_path "$READ_INPUT")" \ + --other "$(input_path "${CEILING_OTHER:-peaks}")" ${pool[@]+--pool "${pool[@]}"} \ + --rounds "${ROUNDS:-1}" --region-mib "${REGION_MIB:-4096}" --write-mib "${WRITE_MIB:-8192}" \ + --dir "$WORK" --tier lustre --out "$PROBE/results/ceiling_lustre.jsonl" diff --git a/benchmarks/lustre/job_chunks.sh b/benchmarks/lustre/job_chunks.sh new file mode 100755 index 0000000..151e8ef --- /dev/null +++ b/benchmarks/lustre/job_chunks.sh @@ -0,0 +1,50 @@ +#!/bin/bash +# Job E: one command at several --chunk sizes, on Lustre, to see what the +# block size costs when a store is read in many small pieces. +# +# Environment (set by submit.sh): +# PROBE, LABEL, SRC as for job_a.sh +# WHAT export_obs (default): `export dataframe obs` to CSV; or +# subset_obs: `subset --obs` of every second cell to h5ad, whose +# sparse matrices are read --chunk rows' worth of entries a block +# CHUNKS block sizes in rows (default "1000 10000 100000 1000000") +# REPEATS rounds (default 2); each runs every size once, odd rounds in +# the order given and even rounds reversed, so a drift in the +# filesystem's load over the job does not favour one size +# TAG names the build when ADATA is another one: the steps are +# WHAT_TAG_chunkN, and the work folder is its own +set -uo pipefail +source "$PROBE/scripts/env.sh" +WHAT=${WHAT:-export_obs} +CHUNKS=${CHUNKS:-1000 10000 100000 1000000} +REPEATS=${REPEATS:-2} +read -r -a SIZES <<< "$CHUNKS" +STEP=$WHAT${TAG:+_$TAG} +WORK=$PROBE/work/lustre/$LABEL/chunks_$STEP +case "$WHAT" in + export_obs) OUT=$WORK/obs.csv + CMD=("$ADATA" export dataframe "$SRC" obs -o "$OUT") ;; + subset_obs) OUT=$WORK/out.h5ad + CMD=("$ADATA" subset "$SRC" -o "$OUT" --obs "$PROBE/meta/$LABEL/obs_half.txt" + --no-space-check) ;; + *) echo "unknown WHAT $WHAT" >&2; exit 2 ;; +esac +rm -rf "$WORK" +mkdir -p "$WORK" +trap 'rm -rf "$WORK"' EXIT +RESULTS=$PROBE/results/chunks_lustre_${LABEL}.tsv +LOG=$PROBE/logs/chunks_lustre_${LABEL}.log +echo "$(date) host=$(hostname) label=$LABEL what=$STEP adata=$ADATA in=$SRC chunks=$CHUNKS repeats=$REPEATS" >> "$LOG" + +for (( round = 1; round <= REPEATS; round++ )); do + order=("${SIZES[@]}") + if (( round % 2 == 0 )); then + order=() + for (( i = ${#SIZES[@]} - 1; i >= 0; i-- )); do order+=("${SIZES[$i]}"); done + fi + for chunk in "${order[@]}"; do + "$PY" "$PROBE/scripts/measure.py" --results "$RESULTS" --tier lustre --label "$LABEL" \ + --step "${STEP}_chunk$chunk" --log "$LOG" --input "$SRC" --output "$OUT" -- \ + "${CMD[@]}" --chunk "$chunk" + done +done diff --git a/benchmarks/lustre/job_engines.sh b/benchmarks/lustre/job_engines.sh new file mode 100755 index 0000000..630efbd --- /dev/null +++ b/benchmarks/lustre/job_engines.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# Jobs B, C and D on one tier: read engines, write engines, text engines. +# +# Environment: PROBE, TIER (lustre | tmp | nfs), KIND (read | write | text); +# for write, optionally WRITE_TRIALS (io_write.py's --trials), ROUNDS and +# WRITE_GB (default 8, 2 on NFS) and WRITE_TAG (a suffix for the results file). +set -uo pipefail +source "$PROBE/scripts/env.sh" +SCRIPTS=$PROBE/scripts +LOG=$PROBE/logs/${KIND}_${TIER}.log +STAGE=$PROBE/results/stage_${KIND}_${TIER}.tsv + +case "$TIER" in + lustre) WORK=$PROBE/work/lustre/$KIND${LSB_JOBID:+-$LSB_JOBID} ;; + nfs) WORK=$NFS_ROOT/work/$KIND ;; + tmp) WORK=/tmp/adata-probe-${LSB_JOBID:-$$}-$KIND ;; +esac +rm -rf "$WORK" +mkdir -p "$WORK" +trap 'rm -rf "$WORK"' EXIT +echo "$(date) host=$(hostname) tier=$TIER kind=$KIND work=$WORK" >> "$LOG" + +# on_tier LABEL: the input's path on this tier, copied there (timed) when +# the tier is /tmp. +on_tier() { + local src + if [[ "$TIER" == nfs ]]; then echo "$NFS_ROOT/inputs/$1.h5ad"; return; fi + src=$(input_path "$1") + if [[ "$TIER" == tmp ]]; then + "$PY" "$SCRIPTS/measure.py" --results "$STAGE" --tier tmp --label "$1" --step stage_in \ + --input "$src" --output "$WORK/$1.h5ad" --keep --log "$LOG" -- cp "$src" "$WORK/$1.h5ad" >&2 + echo "$WORK/$1.h5ad" + else + echo "$src" + fi +} + +case "$KIND" in + read) + label=$READ_INPUT + [[ "$TIER" == nfs ]] && label=${READ_INPUT}_obs4 + file=$(on_tier "$label") + extra=() + [[ "$TIER" == lustre ]] && extra=(--anndata-slice "$(input_path "${READ_INPUT}_obs16")") + "$PY" "$SCRIPTS/io_read.py" --file "$file" --tier "$TIER" \ + --out "$PROBE/results/read_${TIER}.jsonl" ${extra[@]+"${extra[@]}"} >> "$LOG" 2>&1 ;; + write) + gb=8 + [[ "$TIER" == nfs ]] && gb=2 + gb=${WRITE_GB:-$gb} + extra=() + [[ -n "${WRITE_TRIALS:-}" ]] && extra+=(--trials "$WRITE_TRIALS") + [[ -n "${ROUNDS:-}" ]] && extra+=(--rounds "$ROUNDS") + "$PY" "$SCRIPTS/io_write.py" --dir "$WORK/out" --tier "$TIER" --gb "$gb" \ + --out "$PROBE/results/write_${TIER}${WRITE_TAG:+_$WRITE_TAG}.jsonl" ${extra[@]+"${extra[@]}"} >> "$LOG" 2>&1 ;; + text) + file=$(on_tier "$TEXT_INPUT") + "$PY" "$SCRIPTS/text_engines.py" --file "$file" --matrix "$TEXT_MATRIX" --dir "$WORK/out" \ + --tier "$TIER" --adata "$ADATA" --out "$PROBE/results/text_${TIER}.jsonl" >> "$LOG" 2>&1 ;; +esac +echo "$(date) done" >> "$LOG" diff --git a/benchmarks/lustre/layout.py b/benchmarks/lustre/layout.py new file mode 100644 index 0000000..1634cdd --- /dev/null +++ b/benchmarks/lustre/layout.py @@ -0,0 +1,136 @@ +"""Describe an h5ad for the probe and write the name lists its runs use. + + python layout.py INPUT OUTDIR + +Writes into OUTDIR: +- `layout.json`: every dataset's shape, dtype, layout, chunks, filters and + bytes, plus the matrix encoding, the split column chosen and the first + obsm key; +- `obs_half.txt`, `var_half.txt`: every second name, for `subset`; +- `obs_first_4.txt`, `obs_first_16.txt`, `var_first_4.txt`, + `var_first_16.txt`: the first quarter and sixteenth, for the size ladder. + +Reads only metadata, the obs and var indexes, and the categories of +categorical obs columns. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import h5py +import numpy as np + +#: Names that make a column the preferred `split --by`. +PREFERRED = ("sample", "donor", "batch", "dataset", "library", "lane") + + +def _attr(obj, name, default=None): + value = obj.attrs.get(name, default) + return value.decode() if isinstance(value, bytes) else value + + +def _strings(ds) -> np.ndarray: + return ds.asstr()[...] if h5py.check_string_dtype(ds.dtype) else ds[...].astype(str) + + +def _index(group) -> np.ndarray: + """The obs or var names, in row order. + + A categorical index is its categories taken by its codes: the categories + alone are in another order, can include unused ones, and gave the wrong + rows to the half and first-quarter selections and the wrong n_obs.""" + key = _attr(group, "_index", "_index") + item = group[key] + if isinstance(item, h5py.Group): + if "codes" in item: # categorical + codes = item["codes"][...] + if codes.size and int(codes.min()) < 0: + raise ValueError(f"{group.name}/{key} has missing names") + return _strings(item["categories"])[codes] + item = item["values"] # nullable string + return _strings(item) + + +def _datasets(f) -> list: + rows = [] + + def visit(name, obj): + if isinstance(obj, h5py.Dataset): + plist = obj.id.get_create_plist() + filters = [plist.get_filter(i)[0] for i in range(plist.get_nfilters())] + rows.append({ + "path": name, + "shape": list(obj.shape), + "dtype": str(obj.dtype), + "layout": {0: "compact", 1: "contiguous", 2: "chunked", 3: "virtual"}.get( + plist.get_layout(), "other"), + "chunks": list(obj.chunks) if obj.chunks else None, + "filters": filters, + "storage_bytes": int(obj.id.get_storage_size()), + }) + + f.visititems(visit) + return rows + + +def _split_column(obs) -> tuple: + """A categorical obs column for `split --by`: a preferred name with 2-128 + categories, else the one with the most categories up to 128.""" + choices = [] + for key in obs: + item = obs[key] + if isinstance(item, h5py.Group) and _attr(item, "encoding-type") == "categorical": + n = int(item["categories"].shape[0]) + if 2 <= n <= 128: + preferred = any(p in key.lower() for p in PREFERRED) + choices.append((not preferred, -n, key, n)) + if not choices: + return None, 0 + choices.sort() + return choices[0][2], choices[0][3] + + +def _write(path: Path, names) -> None: + path.write_text("".join(f"{n}\n" for n in names)) + + +def main(argv: list) -> None: + source, out = Path(argv[0]), Path(argv[1]) + out.mkdir(parents=True, exist_ok=True) + with h5py.File(source, "r") as f: + obs_names, var_names = _index(f["obs"]), _index(f["var"]) + x = f["X"] + encoding = _attr(x, "encoding-type", "array") if isinstance(x, h5py.Group) else "array" + by, n_groups = _split_column(f["obs"]) + obsm = sorted(f["obsm"]) if "obsm" in f else [] + obsm_dense = [k for k in obsm if isinstance(f["obsm"][k], h5py.Dataset) + and f["obsm"][k].dtype.kind in "biuf"] + x_data = x["data"] if isinstance(x, h5py.Group) else x + layout = { + "file": str(source), + "file_bytes": source.stat().st_size, + "n_obs": int(len(obs_names)), + "n_var": int(len(var_names)), + "x_encoding": encoding, + "x_itemsize": int(x_data.dtype.itemsize), + "dense_bytes": int(len(obs_names)) * int(len(var_names)) * int(x_data.dtype.itemsize), + "split_by": by, + "split_groups": n_groups, + "obsm_first": obsm_dense[0] if obsm_dense else None, + "layers": sorted(f["layers"]) if "layers" in f else [], + "datasets": _datasets(f), + } + (out / "layout.json").write_text(json.dumps(layout, indent=1)) + _write(out / "obs_half.txt", obs_names[::2]) + _write(out / "var_half.txt", var_names[::2]) + for k in (4, 16): + _write(out / f"obs_first_{k}.txt", obs_names[: max(1, len(obs_names) // k)]) + _write(out / f"var_first_{k}.txt", var_names[: max(1, len(var_names) // k)]) + print(json.dumps({k: v for k, v in layout.items() if k != "datasets"})) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/benchmarks/lustre/measure.py b/benchmarks/lustre/measure.py new file mode 100644 index 0000000..4aeb062 --- /dev/null +++ b/benchmarks/lustre/measure.py @@ -0,0 +1,179 @@ +"""Run one command and append its costs to a TSV. + + python measure.py --results R.tsv --tier T --label L --step S \ + --input IN [--output OUT ...] [--keep] [--profile FILE] -- command ... + +Before the run the input is dropped from the page cache: `posix_fadvise` +DONTNEED on every file under it, and on Lustre `lfs ladvise -a dontneed` +too, so a rerun on the same node is not flattered by the client cache. +The row records whether either call worked. + +Costs come from `os.wait4` on the child: wall time, user and system CPU, +and peak RSS. Outputs are measured, then deleted unless `--keep`, so a +long series of runs never accumulates outputs. + +`--profile FILE` runs the command, which must be a Python script (adata's +console script is), under pyinstrument, and saves the session to FILE with +a text rendering beside it. pyinstrument samples from inside the process. +py-spy, which reads it from outside, needs ptrace, and LSF nodes refuse it. +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import socket +import subprocess +import sys +import time +from pathlib import Path + +COLUMNS = ( + "time", "host", "tier", "label", "step", "exit", "wall_s", "user_s", "sys_s", + "max_rss_mb", "input_bytes", "output_bytes", "output_files", "cache_drop", + "nproc", "command", +) + + +def files_under(path: Path) -> list: + if path.is_file(): + return [path] + if path.is_dir(): + return [Path(root) / name for root, _, names in os.walk(path) for name in names] + return [] + + +def size_of(paths: list) -> tuple: + total = count = 0 + for path in paths: + for f in files_under(Path(path)): + try: + total += f.stat().st_size + count += 1 + except OSError: + pass + return total, count + + +def drop_cache(path: Path) -> str: + """'fadvise', 'fadvise+ladvise', or 'none' for what worked.""" + worked = [] + ok = bool(files_under(path)) + for f in files_under(path): + try: + fd = os.open(f, os.O_RDONLY) + try: + os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED) + finally: + os.close(fd) + except (OSError, AttributeError): + ok = False + if ok: + worked.append("fadvise") + if str(path.resolve()).startswith("/lustre") and shutil.which("lfs"): + targets = [str(f) for f in files_under(path)][:4096] + if targets: + done = subprocess.run( + ["lfs", "ladvise", "-a", "dontneed", *targets], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + if done.returncode == 0: + worked.append("ladvise") + return "+".join(worked) or "none" + + +def remove(path: Path) -> None: + if path.is_dir() and not path.is_symlink(): + shutil.rmtree(path, ignore_errors=True) + elif path.exists() or path.is_symlink(): + path.unlink() + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--results", required=True) + parser.add_argument("--tier", required=True) + parser.add_argument("--label", required=True) + parser.add_argument("--step", required=True) + parser.add_argument("--input", required=True) + parser.add_argument("--output", action="append", default=[]) + parser.add_argument("--keep", action="store_true") + parser.add_argument("--no-drop", action="store_true") + parser.add_argument("--profile") + parser.add_argument("--log") + parser.add_argument("command", nargs=argparse.REMAINDER) + args = parser.parse_args() + command = args.command[1:] if args.command[:1] == ["--"] else args.command + if not command: + parser.error("no command given after --") + + source = Path(args.input) + outputs = [Path(p) for p in args.output] + for out in outputs: + remove(out) + dropped = "skipped" if args.no_drop else drop_cache(source) + in_bytes, _ = size_of([source]) + + step = args.step + run = list(command) + if args.profile: + # A sample every 10 ms keeps an hour's run to a few hundred + # thousand samples. Wall time, so waiting on storage shows up in + # the frame that waits. + run = [sys.executable, "-m", "pyinstrument", "--renderer", "pyisession", + "--outfile", args.profile, "--interval", "0.01"] + run + step += "+profile" + + log = open(args.log, "ab") if args.log else subprocess.DEVNULL + started = time.perf_counter() + child = subprocess.Popen(run, stdout=log, stderr=log) + _, status, usage = os.wait4(child.pid, 0) + wall = time.perf_counter() - started + child.returncode = os.waitstatus_to_exitcode(status) + if args.log: + log.close() + if args.profile and Path(args.profile).exists(): + # --show-all: adata is installed in site-packages, which + # pyinstrument hides by default. + subprocess.run([sys.executable, "-m", "pyinstrument", "--load", args.profile, + "--renderer", "text", "--show-all", "--no-color", "--no-unicode", + "--outfile", str(Path(args.profile).with_suffix(".txt"))], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + out_bytes, out_files = size_of(outputs) + if not args.keep: + for out in outputs: + remove(out) + + rss_mb = usage.ru_maxrss / (1024 * 1024 if sys.platform == "darwin" else 1024) + row = { + "time": time.strftime("%Y-%m-%dT%H:%M:%S"), + "host": socket.gethostname(), + "tier": args.tier, + "label": args.label, + "step": step, + "exit": child.returncode, + "wall_s": f"{wall:.2f}", + "user_s": f"{usage.ru_utime:.2f}", + "sys_s": f"{usage.ru_stime:.2f}", + "max_rss_mb": f"{rss_mb:.0f}", + "input_bytes": in_bytes, + "output_bytes": out_bytes, + "output_files": out_files, + "cache_drop": dropped, + "nproc": os.environ.get("LSB_DJOB_NUMPROC", str(os.cpu_count())), + "command": " ".join(command), + } + results = Path(args.results) + new = not results.exists() + with open(results, "a") as fh: + if new: + fh.write("\t".join(COLUMNS) + "\n") + fh.write("\t".join(str(row[c]) for c in COLUMNS) + "\n") + print("\t".join(f"{c}={row[c]}" for c in ("label", "step", "exit", "wall_s", "max_rss_mb"))) + return child.returncode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/benchmarks/lustre/prep.sh b/benchmarks/lustre/prep.sh new file mode 100755 index 0000000..c684708 --- /dev/null +++ b/benchmarks/lustre/prep.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Prep job: describe each input, cut the slices (timed: they are subsets +# too), describe the slices, and stage the NFS tier's inputs (timed: plain +# Lustre-to-NFS copy speed). +set -uo pipefail +source "$PROBE/scripts/env.sh" +R=$PROBE/results/prep.tsv +LOG=$PROBE/logs/prep.log +mkdir -p "$PROBE/inputs" "$PROBE/meta" + +m() { # m LABEL STEP measure-options -- command + "$PY" "$PROBE/scripts/measure.py" --results "$R" --tier lustre --label "$1" --step "$2" \ + --log "$LOG" "${@:3}" +} + +for l in $INPUTS; do + "$PY" "$PROBE/scripts/layout.py" "$(input_path "$l")" "$PROBE/meta/$l" >> "$LOG" 2>&1 +done + +make_slice() { # make_slice LABEL AXIS K + local src out + src=$(input_path "$1") + out=$PROBE/inputs/${1}_${2}${3}.h5ad + if [[ ! -f "$out" ]]; then + m "$1" "slice_${2}${3}" --input "$src" --output "$out" --keep -- \ + "$ADATA" subset "$src" -o "$out" "--$2" "$PROBE/meta/$1/${2}_first_${3}.txt" --no-space-check + fi + "$PY" "$PROBE/scripts/layout.py" "$out" "$PROBE/meta/${1}_${2}${3}" >> "$LOG" 2>&1 +} +for l in $OBS_SLICES; do make_slice "$l" obs 4; make_slice "$l" obs 16; done +for l in $VAR_SLICES; do make_slice "$l" var 4; make_slice "$l" var 16; done + +: > "$PROBE/meta/inputs.tsv" +for l in $(all_labels); do + printf '%s\tlustre\t%s\n%s\ttmp\t%s\n' "$l" "$(input_path "$l")" "$l" "$(input_path "$l")" \ + >> "$PROBE/meta/inputs.tsv" +done +mkdir -p "$NFS_ROOT/inputs" +for l in $(nfs_labels); do + dst=$NFS_ROOT/inputs/$l.h5ad + [[ -f "$dst" ]] || m "$l" stage_nfs --input "$(input_path "$l")" --output "$dst" --keep -- \ + cp "$(input_path "$l")" "$dst" + printf '%s\tnfs\t%s\n' "$l" "$dst" >> "$PROBE/meta/inputs.tsv" +done +echo "prep done $(date)" >> "$LOG" diff --git a/benchmarks/lustre/probe.conf.example b/benchmarks/lustre/probe.conf.example new file mode 100644 index 0000000..598c136 --- /dev/null +++ b/benchmarks/lustre/probe.conf.example @@ -0,0 +1,36 @@ +# Copy to $PROBE/probe.conf and fill in. Sourced by every job. +# +# Where the probe lives (scripts, venv, results, logs) and runs its Lustre +# tier. It must be on Lustre. +PROBE=/lustre/scratch/you/engine-probe +# The NFS tier's directory. +NFS_ROOT=/nfs/your/project/engine-probe +# LSF group to charge (bsub -G). +GROUP=yourgroup + +# Inputs, by label. Each is read in place for the Lustre tier and copied +# for the others. +INPUTS="cells spatial peaks" +INPUT_cells=/lustre/.../cells.h5ad +INPUT_spatial=/lustre/.../spatial.h5ad +INPUT_peaks=/lustre/.../peaks.h5ad + +# Inputs cut to 1/4 and 1/16 of their cells (obs) or features (var), for +# the slopes. Slices are labelled