From 6dcd3f645534c19851d4365ef3553a695c0dca28 Mon Sep 17 00:00:00 2001 From: Aljes Date: Wed, 2 Dec 2026 21:16:15 +0000 Subject: [PATCH 1/7] Add a storage and engine probe for LSF clusters Times today's adata on big h5ad files across Lustre, node-local /tmp and NFS, with 1/4 and 1/16 slices for the slopes, and compares read, write and text engines: h5py, a zarr view of HDF5 chunks (zarr-python and obstore), zarrs, and DuckDB's h5db and anndata extensions. Co-Authored-By: Claude Opus 5.5 --- benchmarks/lustre/README.md | 64 +++++++ benchmarks/lustre/env.sh | 35 ++++ benchmarks/lustre/h5chunks.py | 206 ++++++++++++++++++++++ benchmarks/lustre/io_read.py | 230 +++++++++++++++++++++++++ benchmarks/lustre/io_write.py | 170 ++++++++++++++++++ benchmarks/lustre/job_a.sh | 113 ++++++++++++ benchmarks/lustre/job_engines.sh | 55 ++++++ benchmarks/lustre/layout.py | 122 +++++++++++++ benchmarks/lustre/measure.py | 164 ++++++++++++++++++ benchmarks/lustre/prep.sh | 45 +++++ benchmarks/lustre/probe.conf.example | 33 ++++ benchmarks/lustre/report.py | 161 +++++++++++++++++ benchmarks/lustre/setup.sh | 31 ++++ benchmarks/lustre/submit.sh | 79 +++++++++ benchmarks/lustre/text_engines.py | 248 +++++++++++++++++++++++++++ 15 files changed, 1756 insertions(+) create mode 100644 benchmarks/lustre/README.md create mode 100755 benchmarks/lustre/env.sh create mode 100644 benchmarks/lustre/h5chunks.py create mode 100644 benchmarks/lustre/io_read.py create mode 100644 benchmarks/lustre/io_write.py create mode 100755 benchmarks/lustre/job_a.sh create mode 100755 benchmarks/lustre/job_engines.sh create mode 100644 benchmarks/lustre/layout.py create mode 100644 benchmarks/lustre/measure.py create mode 100755 benchmarks/lustre/prep.sh create mode 100644 benchmarks/lustre/probe.conf.example create mode 100644 benchmarks/lustre/report.py create mode 100755 benchmarks/lustre/setup.sh create mode 100755 benchmarks/lustre/submit.sh create mode 100644 benchmarks/lustre/text_engines.py diff --git a/benchmarks/lustre/README.md b/benchmarks/lustre/README.md new file mode 100644 index 0000000..d101828 --- /dev/null +++ b/benchmarks/lustre/README.md @@ -0,0 +1,64 @@ +# 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, export obs and export obsm. For each it records wall, + CPU, peak RSS and bytes. +- **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. + +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 + ``` + +## 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/env.sh b/benchmarks/lustre/env.sh new file mode 100755 index 0000000..e71a398 --- /dev/null +++ b/benchmarks/lustre/env.sh @@ -0,0 +1,35 @@ +# 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 +export 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/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..c1a473e --- /dev/null +++ b/benchmarks/lustre/io_write.py @@ -0,0 +1,170 @@ +"""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 ...] + +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. +""" + +from __future__ import annotations + +import argparse +import json +import os +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}), +} + + +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) -> 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" + 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)) + args = p.parse_args() + root = Path(args.dir) + root.mkdir(parents=True, exist_ok=True) + total = int(args.gb * (1 << 30)) + base = {"host": socket.gethostname(), "tier": args.tier, "dir": str(root), + "nproc": os.environ.get("LSB_DJOB_NUMPROC", str(os.cpu_count()))} + for name in [t for t in args.trials.split(",") if t]: + 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} + 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"]) + 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..dbb9e84 --- /dev/null +++ b/benchmarks/lustre/job_a.sh @@ -0,0 +1,113 @@ +#!/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. +# PYSPY 1 to run the step under py-spy (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="" +[[ "${PYSPY:-0}" == 1 ]] && SUFFIX=_pyspy +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 spy=() + [[ "${PYSPY:-}" == 1 ]] && spy=(--pyspy "$PROBE/profiles/${TIER}_${LABEL}_${step}.json") + "$PY" "$PROBE/scripts/measure.py" --results "$RESULTS" --tier "$TIER" --label "$LABEL" \ + --step "$step" --log "$LOG" ${spy[@]+"${spy[@]}"} "$@" +} + +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_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_engines.sh b/benchmarks/lustre/job_engines.sh new file mode 100755 index 0000000..e00bda7 --- /dev/null +++ b/benchmarks/lustre/job_engines.sh @@ -0,0 +1,55 @@ +#!/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). +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 ;; + 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 + "$PY" "$SCRIPTS/io_write.py" --dir "$WORK/out" --tier "$TIER" --gb "$gb" \ + --out "$PROBE/results/write_${TIER}.jsonl" >> "$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..871cd06 --- /dev/null +++ b/benchmarks/lustre/layout.py @@ -0,0 +1,122 @@ +"""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 _index(group) -> np.ndarray: + key = _attr(group, "_index", "_index") + ds = group[key] + if isinstance(ds, h5py.Group): # a categorical or nullable index + ds = ds["values"] if "values" in ds else ds["categories"] + return ds.asstr()[...] if h5py.check_string_dtype(ds.dtype) else ds[...].astype(str) + + +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..b0e6422 --- /dev/null +++ b/benchmarks/lustre/measure.py @@ -0,0 +1,164 @@ +"""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] [--pyspy 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. +""" + +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("--pyspy") + 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.pyspy: + run = ["py-spy", "record", "--native", "--rate", "20", "--format", "speedscope", + "--output", args.pyspy, "--"] + run + step += "+pyspy" + + 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() + + 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..ca5051a --- /dev/null +++ b/benchmarks/lustre/probe.conf.example @@ -0,0 +1,33 @@ +# 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