Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions benchmarks/lustre/README.md
Original file line number Diff line number Diff line change
@@ -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.
281 changes: 281 additions & 0 deletions benchmarks/lustre/ceiling.py
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading