Skip to content

[Scripting] Add map-reduce parallel reductions over leaf cells - #287

Open
BenWibking wants to merge 2 commits into
mainfrom
analysis-4-parallel
Open

BenWibking wants to merge 2 commits into
mainfrom
analysis-4-parallel

Conversation

@BenWibking

@BenWibking BenWibking commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Pure-Python layers on the package from the previous PR.

  • amrexplorer.parallel.map_reduce reads and maps leaf-chunk plan items on thread, process or MPI-partitioned workers.
    • Ownership. By default each worker opens its own dataset handle and plans the same request, checking that the plan matches. ownership="shared" keeps one handle for every thread instead.
    • Scheduling. At most max_in_flight items are in progress at once, which bounds memory.
    • Reduction. Partials are combined in plan order by default, so results are bit-identical to a serial run whatever the worker count. ordered=False combines partials as they arrive.
    • Progress callbacks and cancellation work across executors, and worker errors propagate.
  • amrexplorer.sequence finds a run's plotfiles in step order, opens them one at a time, and skips outputs already written.
  • tools/analysis_validation/benchmark_parallel.py times the executors and ownership models on a real plotfile. With worker-local handles, 8 threads ran 2.5x faster than serial on a 92-million-cell plotfile. A shared handle is slower than serial, because PlotfileDataset serializes block reads.

Tests

  • test_parallel.py:
    • serial, thread (both ownership models) and process executors give bit-identical ordered reductions on multilevel data
    • partitioned ranks combine to the whole
    • unordered reduction gives the same total
    • errors propagate
  • test_batch.py: cancellation of reads and iteration, progress callbacks, and sequence discovery.
  • The headless ctest suite passes (65 tests).

Stack

Part of a stack replacing #276. Review and merge in order; each PR shows only its own layer.

  1. [Scripting] Generalize PlotfileDataset and the cache budget for analysis tools #289 Prepare PlotfileDataset and the cache budget for analysis
  2. [Scripting] Add iteration plans for leaf-cell chunks #285 Exact leaf-cell plans and chunks (C++)
  3. [Scripting] Add the amrexplorer Python package for batch analysis #286 The amrexplorer Python package (bindings)
  4. [Scripting] Add map-reduce parallel reductions over leaf cells #287 Parallel reductions and batch helpers ← this PR

🤖 Generated with Claude Code

@BenWibking BenWibking changed the title Add parallel reductions and batch helpers over leaf cells [Scripting] Add parallel reductions and batch helpers over leaf cells Oct 29, 2026
@BenWibking
BenWibking added this pull request to stack #291 October 29, 2026 01:21
@BenWibking
BenWibking removed this pull request from stack #291 October 29, 2026 03:53
@BenWibking
BenWibking added this pull request to stack #292 October 29, 2026 03:53
@BenWibking BenWibking changed the title [Scripting] Add parallel reductions and batch helpers over leaf cells [Scripting] Add map-reduce parallel reductions over leaf cells Nov 2, 2026
@BenWibking
BenWibking removed this pull request from stack #292 November 2, 2026 16:22
@BenWibking
BenWibking added this pull request to stack #294 November 2, 2026 16:22
WeiqunZhang pushed a commit that referenced this pull request Nov 4, 2026
…sis tools (#289)

Small changes to existing code that the analysis library (next PR)
needs. No new feature yet.

- **Cache budget in `core`.** The cache-budget default and
`AMREXPLORER_CACHE_SIZE_MB` parsing move from `src/qt/CacheConfig.hpp`
to `include/amrexplorer/core/CacheConfig.hpp`, so code without Qt can
share them. `src/qt/CacheConfig.hpp` now uses the core version.
- **Derived-field policy.** `PlotfileDataset` takes a
`DerivedFieldPolicy`:
  - The viewer keeps `Skip`.
- An unattended analysis passes `Strict`, so a definition that doesn't
resolve fails at open instead of silently dropping the field.
- **`derivedFieldProgram(field)`.** Exposes a derived field's compiled
program, so a caller can bound in advance which blocks a read will pin.
- **`FabValues` spans.** `FabValues::singleValues()` and
`doubleValues()` expose the payload in its stored precision, for callers
copying many values without dispatching on precision per value.

## Tests

- New `tests/integration/test_derived_field_policy.cpp`:
  - `Skip` installs what resolves and reports the rest.
  - `Strict` fails the open, naming the broken definition.
- `derivedFieldProgram` returns null for a stored field and the right
inputs for a derived one, and a derived block evaluates its program.
- `test_single_precision_plotfile.cpp` checks both span accessors for
float and double FABs.
- The headless ctest suite passes (63 tests).

## Stack

Part of a stack replacing #276. Review and merge in order; each PR shows
only its own layer.
1. #289 Prepare PlotfileDataset and the cache budget for analysis ← this
PR
2. #285 Exact leaf-cell plans and chunks (C++)
3. #286 The amrexplorer Python package (bindings)
4. #287 Parallel reductions and batch helpers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@WeiqunZhang

Copy link
Copy Markdown
Member

PR 287 review draft (head 7fd2d90) — Request changes

Review body

The scheduling and reduction logic looks right. Ordered combining can't
stall, because items are handed out in plan order, so the item at the head of
the order is always in flight. Waiting partials count against
max_in_flight. Errors cancel the queued futures and re-raise the original,
and worker handles are closed in a finally. Two things before this merges:

  1. Memory grows with workers × cache_bytes, not with max_in_flight.
    With ownership="worker", each worker's handle keeps an LRU cache of the
    blocks it has read, up to the full cache_bytes. map_reduce reads each
    block once, so that cache gains nothing and holds memory until the call
    ends. Peak RSS on a 14M-cell, two-level Castro plotfile, reading 4 fields
    with cache_bytes=64 MiB: 128 MiB serial, 356 MiB with 4 threads, 567 MiB
    with 8. With the defaults (os.cpu_count() workers, 1 GiB each), a
    128-core node can keep ~128 GiB of blocks resident. Options: clear each
    worker's unpinned blocks after every item, or give worker handles
    cache_bytes / workers (no less than the largest item's estimate). At the
    least, document the cost and reconsider cpu_count() as the default
    worker count.

  2. The guide's parallel and batch sections need complete examples. See the
    inline comments.

The tests here are pure Python, so they also depend on the CI job requested
in #286.

Inline comments

python/amrexplorer/parallel.py:13

This bound doesn't hold for ownership="worker": each worker handle also
retains up to cache_bytes of unpinned blocks, so resident memory is up to
workers × cache_bytes (see the review body for measurements). Either make
the bound true (clear unpinned blocks after each item, or split the budget),
or state the real one here and in the guide.

python/amrexplorer/parallel.py:190

Combined with a full-size cache per worker handle, os.cpu_count() as the
default makes memory depend on the node: 1 GiB per core by default. A fixed
small default, or a memory-aware one, would be safer on large HPC nodes.

docs/python-analysis.md:90

executor="processes" needs more than a picklable mapper. The mapper must be
defined at module level (the lambda in the example above won't pickle), and
the call must sit under if __name__ == "__main__":. Python 3.14's default
forkserver start method fails without the guard, with an obscure
"bootstrapping phase" error. A complete script example would help.

docs/python-analysis.md:89

Please describe ownership, ordered and max_in_flight, with their
defaults. Users should know that ownership="shared" uses less memory but is
slower (your benchmark shows it slower than serial), and what memory the
default costs.

docs/python-analysis.md:92

The MPI hint leaves out where plan, rank and size come from, that
mpi4py is the user's to install, and how to combine rank results "with the
same ordered rule". A short complete example would make it usable: open,
plan, map_reduce(..., items=plan.partition(rank, size)), gather to rank 0,
reduce in rank order.

docs/python-analysis.md:97

This section needs an example. It names output_path and needs_output
without saying what they're for: writing one output per plotfile, and
skipping plotfiles already done when a job is rerun. A five-line loop over
find_plotfiles → open_each → needs_output would show it.

WeiqunZhang pushed a commit that referenced this pull request Nov 4, 2026
A Qt-free `src/analysis` library with an exact planner and reader for a
plotfile's **leaf cells**, the cells no finer level covers. This is the
core algorithm the Python package builds on.

- **Plans.** `planLeafChunks` partitions the leaf cells of a region into
one item per grid, in a fixed order: levels coarsest first, grids in
native FAB order.
- Covered coarse cells never appear, and every leaf cell appears exactly
once.
- Regions select cells by center, `lower <= center < upper`, so adjacent
regions split the cells between them.
  - Planning reads metadata only.
- **Precision.** Field values keep the widest precision any level stores
unless the plan asks for float32 or float64. Derived fields are
evaluated per block and follow the plan's dtype.
- **Cache budget.** Each item's worst-case cache use is checked against
the budget at planning, and again when reading. The error names the
item.
- **Chunks.** `readLeafChunk` copies an item's values out of the cache:
a chunk holds no cache pins and outlives the dataset. Geometry arrays
(indices, centers, widths, volumes) are computed on first use.
- **Errors.** Unknown fields, unsupported geometry or centering, invalid
regions and items planned on another dataset are `AnalysisError`.

## Review notes

`src/analysis/LeafChunks.cpp` is the file to read closely. The
covered-cell computation, region-to-index-box conversion and the
pinned-bytes estimate are where the guarantees come from.

## Tests

`tests/integration/test_leaf_chunks.cpp` runs on a two-level 2-D fixture
whose fine grid straddles a coarse grid boundary. It checks:
- exact partition, stored values, and the leaf cells tiling the domain
- the half-open region rule, and an empty plan outside the domain
- unknown, duplicate and non-finite requests are refused, as is
non-Cartesian geometry
- float32 narrowing and derived fields
- reading items repeatedly and in any order
- no pins after a read, and chunks outliving the dataset
- the planning-time and read-time budget checks
- cancellation, and items bound to their dataset

The headless ctest suite passes (64 tests).

## Stack

Part of a stack replacing #276. Review and merge in order; each PR shows
only its own layer.
1. #289 Prepare PlotfileDataset and the cache budget for analysis
2. #285 Exact leaf-cell plans and chunks (C++) ← this PR
3. #286 The amrexplorer Python package (bindings)
4. #287 Parallel reductions and batch helpers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Base automatically changed from analysis-3-python to main November 17, 2026 22:24
BenWibking and others added 2 commits November 17, 2026 14:24
amrexplorer.parallel.map_reduce reads and maps leaf-chunk plan items
across thread, process, or MPI-partitioned workers:

- Each worker opens its own dataset handle and plans the same request,
  checking that the plan matches.
- At most max_in_flight items are in progress at once.
- Partials are combined in plan order by default, so results are
  bit-identical to a serial run.

amrexplorer.sequence finds a run's plotfiles in step order, opens them
one at a time, and skips outputs already written.
tools/analysis_validation/benchmark_parallel.py measures the executors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Handles that map_reduce opens itself now drop their unpinned blocks after
every item: worker threads, worker processes, and the handle opened for a
path. Each item is read once, so those caches were never hit and only held
up to cache_bytes per worker until the call ended. A handle the caller
passes in, and the shared handle, keep their caches. Exposes
Dataset.clear_unpinned_cache() for this.

The default worker count is now AMREXPLORER_WORKERS, or else the CPUs the
process may use, at most 8; workers= overrides both.

The guide's parallel section now lists every option with its default and
memory cost, and gives complete processes and MPI scripts. The MPI text no
longer claims rank results combine to the serial result: partition() is
round-robin, so the result is reproducible for a fixed rank count but may
differ from serial in the last bits. The batch section gains a complete
loop. A new test runs each of these examples as a script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WeiqunZhang pushed a commit that referenced this pull request Nov 17, 2026
The `amrexplorer` Python package: nanobind bindings over the leaf-cell
planner and reader from the previous PR, plus a small pure-Python
wrapper and build plumbing. Most of this PR is mechanical glue. The
Python tests are the clearest statement of the API.

- **`open_plotfile(path, derived=..., cache_bytes=...)`** returns a
`Dataset` usable as a context manager. Derived-field definitions use
`Strict`, so a bad one fails at open.
- **Plans and chunks.** `plan_leaf_chunks` returns a sequence of items,
and `read_leaf_chunk` returns a chunk.
- A chunk is a mapping of read-only NumPy arrays that keep their memory
alive, so they outlive the chunk and the dataset.
  - Geometry (`x`, `dx`, `i`, `cell_volume`, ...) is computed lazily.
  - `leaf_cells()` plans and reads in one loop.
- **`CancelToken`** stops a read in progress. Analysis, cache-budget,
read, closed-dataset and cancellation errors map to Python exceptions.
- **Build.**
- `-DAMREXPLORER_ENABLE_PYTHON=ON` builds the module into
`<build>/python`.
- `pip install .` builds the module alone through scikit-build-core
(`pyproject.toml`).
- ctest runs the pytest suite as `python_analysis` when pytest is
installed.
- **Docs.** `docs/python-analysis.md` (installing and leaf cells) and
`docs/building.md`.

## Review notes

- `python/src/module.cpp` (~540 lines) is type conversion: dicts and
boxes, NumPy views kept alive by capsules, GIL release around reads, and
closed-dataset checks.
- `python/amrexplorer/_dataset.py` is property accessors and the
Mapping/Sequence protocols over the native objects.
- Both are worth skimming, not reading line by line.

## Tests

- `tests/python/test_leaf_chunks.py` (25 tests) checks every contract
against an independent NumPy reconstruction of 1-D, 2-D and 3-D fixture
plotfiles. It includes a region over a 2^64-cell domain, a regression
test for an overflow found on real data.
- `tests/python/plotfile_writer.py` writes AMReX-layout plotfiles
(per-level precision, stored ghost cells, version-1 and version-2 FAB
headers) for these and later tests.
- The headless ctest suite passes (65 tests, `python_analysis` among
them).

## Stack

Part of a stack replacing #276. Review and merge in order; each PR shows
only its own layer.
1. #289 Prepare PlotfileDataset and the cache budget for analysis
2. #285 Exact leaf-cell plans and chunks (C++)
3. #286 The amrexplorer Python package (bindings) ← this PR
4. #287 Parallel reductions and batch helpers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@WeiqunZhang

Copy link
Copy Markdown
Member

Blocking:

  1. Windows CI is failing now (tests/python/test_batch.py:67): 1 failed, 59 passed, confirmed in the log. The test splits paths with rsplit("/"), but find_plotfiles returns str(Path), which uses
    backslashes on Windows. Comparing Path(p).name fixes it.
  2. Use-after-free in clear_unpinned_cache (python/src/module.cpp:418): it takes a raw dataset() reference and then releases the GIL. If another thread calls close() meanwhile, the dataset is
    freed while still in use. The class's own comment says to use held() here, as levels() and widestDtype() do.

Non-blocking, worth raising with Ben:
3. Stale and checkpoint directories get picked up (python/amrexplorer/sequence.py:26,32). find_plotfiles keeps renamed stale plotfiles like plt00100.old. and reads the timestamp as
the step number. It also accepts checkpoints, since it treats any directory with a Header file as a plotfile, and the batch then fails when it opens one. Please confirm one assumption: that
AMReX renames an existing plotfile directory to .old.. The review recalled that rather than checking it.
4. Duplicate items lose a result with ordered=True (python/amrexplorer/parallel.py:155): items=[1, 0, 0] silently drops one partial, while ordered=False keeps both.
5. Errors in the process-pool setup are hidden (parallel.py:176): the caller gets BrokenProcessPool instead of the AnalysisError, so except AnalysisError misses it.
6. AMREXPLORER_WORKERS is checked even for executor='serial' (parallel.py:235): a bad value breaks the guide's MPI example, though serial never uses workers.
7. A cancellation test can't fail (test_batch.py:47): assert max(seen) < 9 always passes, because the plan has at most 7 items.
8. A mistyped directory gives an empty sequence (sequence.py:58): find_plotfiles('ouputs/') returns [] with no error, so a job finishes successfully with no output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants