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
5 changes: 4 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ uses `elements/` (the spec, `strings`, and the readers and writers that
- `raise _fail(e)` prints an exception as the one `Error:` line on stderr
and exits 1. `main(argv)` runs the arguments it is given and raises
`SystemExit` for its caller; run as the command (`argv` None), a failed
run ends the process at once (`_leave`), past h5py's teardown.
run ends the process at once (`_leave`), past h5py's teardown. For the
run it turns off numpy's requests for huge pages (`_small_pages`), which
stall every page fault on a node with fragmented memory, unless
`NUMPY_MADVISE_HUGEPAGE` is set.
- **`commands/`**: one module per command. Each orchestrates its command:
- planning and refusals;
- progress output;
Expand Down
29 changes: 28 additions & 1 deletion STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,40 @@ The conversion epic's sub-issues (#21–#30) are all done and ticked in #20.

## In progress

Nothing. The fixes from the October 2026 audit (epic #87, 164 findings in 16
Faster on Lustre, from the storage and engine probe (`benchmarks/lustre/`,
branch `perf/lustre-probe`, run on the farm in December 2026). The two
cheapest wins first, on `perf/block-bytes-thp`:

- [x] Sparse blocks read at least 32 MiB (`TARGET_READ_BYTES`) of `data` and
`indices`, whatever `--chunk` says (`sparse_block_entries`). At `--chunk`
1024 a narrow matrix (4.3M × 480) was read 800 KB at a time. On one
node `subset --obs` of half its cells took 6.4 to 6.9 minutes on main and
1.5 to 2.1 with the floor, at the same peak memory (820 MB). Covers
`subset`, `split` and the 10x-style conversions, all through
`fan_out_sparse_matrix`.
- [x] `main` turns off numpy's requests for huge pages for the run, unless
`NUMPY_MADVISE_HUGEPAGE` is set. On a node with fragmented memory each
page fault of an array of 4 MiB or more waited on a failed compaction:
a 2 GB write had written nothing after 55 minutes, and took 11 seconds
with them off.
- [x] Measure `subset` on the probe's spatial store on the farm, at the
default `--chunk` (above; node-13-16, two rounds of each build).

Next from the probe, in order: compress gzip HDF5 outputs on several
threads; threaded gzip for MTX and 10x-mtx; a faster MTX import parser; a
direct-I/O chunk reader. zarrs' direct I/O was measured and dropped: it
wrote uncompressed data more slowly than without it.

The fixes from the October 2026 audit (epic #87, 164 findings in 16
batches) finished with 0.17.6; the sub-issues (#88–#103) are all done and
ticked in #87. The batch names in the follow-ups below (B1 to B10) are
theirs.

## Follow-ups noticed

- From the Lustre probe: concat's sparse blocks (`_entries_per_block`, which
also sizes its CSC buckets) and recast's have no 32 MiB floor yet, so a
narrow matrix is read in small pieces there too.
- From #127: `convert` from h5ad refuses `--feature-type` and
`--split-feature-types`; they could filter on var's `feature_types`
column, so one h5ad converted from a multiome `.h5` splits as the `.h5`
Expand Down
4 changes: 3 additions & 1 deletion docs/developers.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ element faithfully).
stderr stays on one line. `raise _fail(e)` turns an exception into that
line, `Error: ...`, and exit code 1. `main(argv)` runs the arguments it is
given and raises `SystemExit` for the caller; run as the command, a failed
run ends the process at once. `--chunk` and `--no-space-check` are
run ends the process at once. For the run it turns off numpy's requests
for huge pages, which stall on a node with fragmented memory, unless
`NUMPY_MADVISE_HUGEPAGE` is set. `--chunk` and `--no-space-check` are
defined once, as `_chunk_option` and `_space_check_option`; a new command
reuses them.
- **`commands/`** orchestrates one command: what to read, what to refuse, what
Expand Down
12 changes: 11 additions & 1 deletion docs/guides/pipelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ most data:

A dense block holds `--chunk` × n_var values, so lower it for very wide dense
matrices. It must be at least 1; zero or a negative value is a usage error. Sparse matrices stream in blocks too: in `subset` and `split`, about as
many entries a block as `--chunk` rows hold. obs and var columns are read
many entries a block as `--chunk` rows hold, and never less than 32 MiB of
them, since a smaller read spends most of its time waiting on a network
filesystem. obs and var columns are read
whole, which is what grows with the number of cells.

Three things are set by the store's layout rather than by `--chunk`, each
Expand Down Expand Up @@ -159,6 +161,14 @@ What `--chunk` does not bound, held whole by design:
- the whole matrix, when asked for with `--in-memory` (`recast`'s transpose,
`export sparse`).

## Huge pages

numpy asks Linux for huge pages (2 MiB) for every array of 4 MiB or more.
On a node whose memory is fragmented, the kernel's default makes each such
allocation wait while it tries to free a huge page, and a step that takes
seconds can take hours, nearly all of it system time. adata turns the
request off for its run. To keep it, set `NUMPY_MADVISE_HUGEPAGE=1`.

## Exit codes and output streams

| Exit code | Meaning |
Expand Down
37 changes: 37 additions & 0 deletions src/adata/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1828,12 +1828,49 @@ def main(argv: Optional[Sequence[str]] = None) -> None:
(`_leave`). Given `argv`, it raises SystemExit as Click does, for the
caller, a test or a notebook, to catch.
"""
huge_pages = _small_pages()
try:
app(args=list(argv) if argv is not None else None, standalone_mode=True)
except SystemExit as done:
if argv is None and isinstance(done.code, int) and done.code != 0:
_leave(done.code)
raise
finally:
_restore_pages(huge_pages)


def _small_pages() -> Optional[bool]:
"""Stop numpy asking Linux for huge pages for the run; the earlier
setting, for `_restore_pages`, or None when left alone.

numpy asks for transparent huge pages (2 MiB) for every array of 4 MiB
or more, as most blocks a command holds are. Where the kernel compacts
memory to meet that request (`defrag` set to `madvise`, the kernel's
default) and a node's memory is fragmented, every page fault waits on
a compaction that fails. A 2 GB write on such a node had written
nothing after 55 minutes, all of it in the kernel, and took 11 seconds
with the request off. Streaming in blocks gains nothing from huge
pages. A `NUMPY_MADVISE_HUGEPAGE` the user set is kept: numpy read it
when it was imported.
"""
import os

if "NUMPY_MADVISE_HUGEPAGE" in os.environ:
return None
try:
from numpy._core.multiarray import _set_madvise_hugepage
except ImportError: # pragma: no cover - a numpy without the switch
return None
return bool(_set_madvise_hugepage(False))


def _restore_pages(before: Optional[bool]) -> None:
"""Put back what `_small_pages` changed, for a caller that runs on."""
if before is None:
return
from numpy._core.multiarray import _set_madvise_hugepage

_set_madvise_hugepage(before)


def _leave(code: int) -> None:
Expand Down
29 changes: 24 additions & 5 deletions src/adata/core/subset.py
Original file line number Diff line number Diff line change
Expand Up @@ -669,16 +669,31 @@ def subset_sparse_matrix_group(
)


def sparse_block_entries(n_rows: int, nnz: int, chunk_rows: int) -> int:
#: The least a block of a sparse matrix reads, `data` and `indices` together:
#: the read budget (`sparse_block_entries`).
SPARSE_BLOCK_BYTES = TARGET_READ_BYTES


def sparse_block_entries(n_rows: int, nnz: int, chunk_rows: int, *, entry_bytes: int) -> int:
"""Entries a block of a sparse matrix holds: as many as `chunk_rows`
rows hold on average, in either layout.
rows hold on average, in either layout, and never fewer than fill
`SPARSE_BLOCK_BYTES` of `data` and `indices` together, `entry_bytes`
an entry.

Blocks were 4,096 majors, whatever --chunk said. Of a CSC matrix that is
4,096 genes across every cell, a block growing with n_obs: 270M entries,
several GB, at a million cells (F032).

Without the floor, a block of a narrow matrix was a small read: 1,024
rows of 480 genes, about 800 KB of `data` and `indices`. On Lustre each
read waits for the network, so a subset of a 6.7 GB store took 6.4 to
6.9 minutes on one node, most of it waiting; with the floor it took 1.5
to 2.1 minutes on the same node, at the same peak memory. A dense array
is copied in reads of the same size (`_chunk_step`).
"""
per_row = -(-int(nnz) // max(1, int(n_rows))) if nnz else 1
return max(1, int(chunk_rows) * max(1, per_row))
floor = SPARSE_BLOCK_BYTES // max(1, int(entry_bytes))
return max(1, int(chunk_rows) * max(1, per_row), floor)


def _sparse_blocks(
Expand Down Expand Up @@ -745,7 +760,8 @@ def fan_out_sparse_matrix(
"""Write one subset of a CSR/CSC matrix per target, reading it once.

The source is read a block of entries at a time -- about as many as
`chunk_rows` rows hold (`sparse_block_entries`), whole majors where
`chunk_rows` rows hold, and at least `SPARSE_BLOCK_BYTES` of them
(`sparse_block_entries`), whole majors where
they fit and a major too large for one block in parts -- and each block
is read once, only from the first to the last major any target keeps,
then shared out among the targets. Peak memory is set by the block,
Expand Down Expand Up @@ -803,7 +819,10 @@ def fan_out_sparse_matrix(
)

del lengths
budget = sparse_block_entries(n_rows, int(indptr[-1]) if indptr.size else 0, chunk_rows)
budget = sparse_block_entries(
n_rows, int(indptr[-1]) if indptr.size else 0, chunk_rows,
entry_bytes=np.dtype(data_ds.dtype).itemsize + np.dtype(indices_ds.dtype).itemsize,
)
for first, stop, lo, hi in _sparse_blocks(
indptr, budget, [out.selection for out in outputs]
):
Expand Down
34 changes: 34 additions & 0 deletions tests/test_cli_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,40 @@ def test_main_run_from_the_command_line_leaves_with_the_failing_code(monkeypatch
assert codes == [2]


def _huge_pages() -> bool:
"""Whether numpy asks for huge pages now, leaving it as it is."""
from numpy._core.multiarray import _set_madvise_hugepage

now = bool(_set_madvise_hugepage(False))
_set_madvise_hugepage(now)
return now


@pytest.mark.parametrize("chosen,during", [(None, False), ("1", True), ("0", True)])
def test_a_run_asks_numpy_for_no_huge_pages_unless_the_user_chose(monkeypatch, chosen, during):
"""On a node whose memory was fragmented, numpy's request for huge pages
made every page fault wait on a failed compaction: a 2 GB write had
written nothing after 55 minutes, and took 11 seconds without it. A run
turns the request off, keeps a NUMPY_MADVISE_HUGEPAGE the user set (numpy
read it at import), and puts the setting back for a caller that runs on."""
from numpy._core.multiarray import _set_madvise_hugepage

if chosen is None:
monkeypatch.delenv("NUMPY_MADVISE_HUGEPAGE", raising=False)
else:
monkeypatch.setenv("NUMPY_MADVISE_HUGEPAGE", chosen)
seen = []
monkeypatch.setattr(cli, "app", lambda **_: seen.append(_huge_pages()))
before = _set_madvise_hugepage(True)
try:
cli.main(["view", "x.h5ad"])
after = _huge_pages()
finally:
_set_madvise_hugepage(before)
assert seen == [during]
assert after is True


@pytest.mark.parametrize(
"value", ["plain", "pct_counts[mt]", "[red]b", "x[/y]", "x[red", "a]b", "end\\", "two\\\\", "a\\[b]", "[link=x]y"]
)
Expand Down
78 changes: 71 additions & 7 deletions tests/test_performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -2080,15 +2080,21 @@ def measure(n: int) -> int:
)
@pytest.mark.slow
def test_streamed_peak_memory_grows_far_slower_than_the_input(
tmp_path, label, factor, run
tmp_path, monkeypatch, label, factor, run
):
"""Not flat, and the guards should not pretend otherwise.

These paths read an index or an indptr whole, so peak allocation does
track n_obs -- just far below it. `subset` is the weakest of the three
because obs columns are materialised per column; that is a known gap,
reported by `benchmarks/` rather than hidden here.

A sparse subset reads at least 32 MiB a block, more than these
matrices hold, so each would be read whole: the floor is taken out of
the way, as it is a constant (`test_a_sparse_block_reads_the_floor_
whatever_the_input`).
"""
_no_sparse_floor(monkeypatch)

def measure(n: int) -> int:
return _peak_for(tmp_path, f"st{label[-4:]}", n,
Expand Down Expand Up @@ -2423,6 +2429,14 @@ def _grid_store(directory: Path, layout: str, axis: str, n: int) -> tuple:
),
}

def _no_sparse_floor(monkeypatch) -> None:
"""Take away the floor under a sparse block (`SPARSE_BLOCK_BYTES`), for a
guard of what --chunk sets on a matrix smaller than the floor."""
import adata.core.subset as subset

monkeypatch.setattr(subset, "SPARSE_BLOCK_BYTES", 1)


#: Known gaps, each owned by another batch, and whether the fix must flip it.
#: Sparse subset was one (F032): its blocks were 4,096 majors, whatever
#: --chunk said, 3 to 5 times the input added per byte; a block holds about
Expand All @@ -2443,8 +2457,13 @@ def _grid_cases():


@pytest.mark.parametrize("command,layout,axis", list(_grid_cases()))
def test_peak_memory_is_a_small_share_of_the_input(grid_dir, tmp_path, command, layout, axis):
"""F091: every layout, both axes, against what the input itself costs."""
def test_peak_memory_is_a_small_share_of_the_input(
grid_dir, tmp_path, monkeypatch, command, layout, axis
):
"""F091: every layout, both axes, against what the input itself costs.
The grid's matrices hold less than the 32 MiB a sparse block reads at
least, so that floor is taken out of the way."""
_no_sparse_floor(monkeypatch)
run = GRID_COMMANDS[command]
copies = 2 if command == "concat" else 1

Expand Down Expand Up @@ -2855,13 +2874,16 @@ def test_a_sharded_source_is_read_with_its_shard_index_once(sharded_dir, tmp_pat


@pytest.mark.parametrize("layout", ["csr", "csc"])
def test_a_sparse_subset_reads_a_block_set_by_the_chunk(tmp_path, layout):
def test_a_sparse_subset_reads_a_block_set_by_the_chunk(tmp_path, monkeypatch, layout):
"""F032: sparse subset read 4,096 majors a block, whatever --chunk said:
of a CSC matrix, 4,096 genes across every cell, a block growing with
n_obs (26,214 entries at 4,096 cells, 209,715 at 32,768, at --chunk
64). A block holds about --chunk rows' entries now."""
64). A block holds about --chunk rows' entries now. The floor under a
block (`SPARSE_BLOCK_BYTES`) is taken out of the way."""
import adata.core.subset as subset
from tests.perf_fixtures import matrix_store

monkeypatch.setattr(subset, "SPARSE_BLOCK_BYTES", 1)
rows = 64

def measure(n: int) -> int:
Expand All @@ -2881,12 +2903,15 @@ def measure(n: int) -> int:
axis="n_obs", sizes=(4096, 32768))


def test_a_gene_in_every_cell_is_read_in_parts(tmp_path):
def test_a_gene_in_every_cell_is_read_in_parts(tmp_path, monkeypatch):
"""F032, its other half: a major holding more entries than a block --
a gene expressed in every cell, read whole -- grew with n_obs however
small the block. It is read in parts of a block now."""
small the block. It is read in parts of a block now. The floor under a
block (`SPARSE_BLOCK_BYTES`) is taken out of the way."""
import adata.core.subset as subset
from tests.perf_fixtures import matrix_store, skewed_matrix

monkeypatch.setattr(subset, "SPARSE_BLOCK_BYTES", 1)
n = 16384
matrix = skewed_matrix(n, 64, layout="csc")
source = matrix_store(tmp_path, n_obs=n, n_var=64, layout="csc", matrix=matrix, tag="skew")
Expand All @@ -2899,6 +2924,43 @@ def test_a_gene_in_every_cell_is_read_in_parts(tmp_path):
assert 0 < largest <= bound, f"read {largest:,} entries at once against {bound:,}"


@pytest.mark.parametrize("layout", ["csr", "csc"])
def test_a_sparse_block_reads_the_floor_whatever_the_input(tmp_path, monkeypatch, layout):
"""From the Lustre probe: a block of --chunk rows of a narrow matrix was a
small read, 800 KB of `data` and `indices` at --chunk 1024 and 480
genes, and on Lustre each read waits for the network: `subset` of a
6.7 GB store spent four fifths of 5 to 6 minutes waiting. A block reads
at least `SPARSE_BLOCK_BYTES` now, and no more: the floor is a constant,
not the input. It is made small rather than the matrix large."""
import h5py

import adata.core.subset as subset
from tests.perf_fixtures import matrix_store

floor = 64 * 1024
monkeypatch.setattr(subset, "SPARSE_BLOCK_BYTES", floor)

def measure(n: int) -> int:
source = matrix_store(tmp_path / str(n), n_obs=n, n_var=64, layout=layout)
with h5py.File(source, "r") as handle:
entry = handle["X/data"].dtype.itemsize + handle["X/indices"].dtype.itemsize
nnz = handle["X/data"].shape[0]
with count_io() as io:
_subset(source, tmp_path / f"o{n}.h5ad", chunk_rows=16)
largest = _largest_matrix_read(io, elements=True)
# Whole majors up to the floor: a CSC major, a gene, holds a tenth of n.
least = floor // entry - (n // 5 if layout == "csc" else 64)
assert nnz > floor // entry, "the matrix fits one block"
assert least <= largest <= floor // entry, (
f"a {layout} subset of {n:,} cells at --chunk 16 read {largest:,} entries "
f"at once, against a floor of {floor // entry:,}"
)
return largest

assert_independent_of(measure, what=f"the largest read of a {layout} subset",
axis="n_obs", sizes=(16384, 65536))


def test_copying_a_column_chunked_matrix_reads_tiles_not_the_matrix(tmp_path, monkeypatch):
"""F081: `copy_dataset` read whole rows, at least one chunk height, so a
matrix chunked (n_obs, 8) was read in one piece, the whole matrix,
Expand Down Expand Up @@ -2952,6 +3014,8 @@ def test_writing_whole_units_holds_a_few_units_not_the_shard(
unit = 1 << 19
monkeypatch.setattr(storage, "WRITE_UNIT_BYTES", unit, raising=False)
monkeypatch.setattr(subset, "WRITE_UNIT_BYTES", unit, raising=False)
# The block, a --chunk of rows, not the 32 MiB floor: more than the matrix.
_no_sparse_floor(monkeypatch)
source = matrix_store(tmp_path, n_obs=n_obs, n_var=n_var, layout=layout,
fmt="zarr3", density=density)
if layout == "dense":
Expand Down
Loading