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
62 changes: 62 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,68 @@

## Unreleased

**A worker that dies stops the aggregate stage at once, naming the
leaves in flight and how the workers ended.** The leaves ran on a
`multiprocessing.Pool` that renewed each worker after 16 leaves, and a
worker that died outright, killed by a signal such as the kernel's for
memory or ending as its setup raised, left the pool waiting for ever for
the leaf it held. The leaves now run on a `ProcessPoolExecutor` under
the platform's own start method, fork on Linux, in waves of 16 leaves a
worker with new workers for each wave, and no more leaves are handed out
than there are workers. A death raises with the leaves in flight and the
workers' exit codes, and no statistics are written. Leaf files already
written are kept, and the leaves manifest is left incomplete. Any other
error that stops the run, such as a leaf written with other columns, now
waits for the leaves in flight to finish, where the pool killed them.
The reduce stage said a dead worker was most likely killed for memory,
whatever ended it. It now gives the exit codes, and speaks of the memory
budget only when a worker was killed by SIGKILL. A worker whose setup
raised exits with code 0 and logs the traceback, and is said to. The
waves cost half a second to a second on the leaf benchmark, 384 leaves
at an eighth of the size on 8 workers under spawn on macOS. Over two
runs of it, the wall time not spent on leaves, the wall less the leaves'
own seconds over the workers, was 3.5 to 5.1 s with the pool and 4.4 to
6.2 s in waves, on walls of 23 to 69 s that moved more than that from
run to run. Fork on Linux was not measured.

`window_means` takes the rows of each window once, looks for an
infinite value without copying the rows of the windows, and builds the
frame of the group keys once, where it did all three for every window.
On the benchmark leaf of 4.26 million rows it takes 11% less as the
pipeline calls it, and up to 29% less with the level labels on the
frame. No number moves. Every call the test suite and the benchmarks
make gives what the former code gave, to the bit, with the same row
order and dtypes, and every refusal the same text.

**The first block of a reduce is measured, and a run sized by the
estimate is refused when the measurement is more than twice it.** The
blocks are sized from an estimate of the bytes a kept row takes, 240 and
40 for each dimension of a leaf, calibrated once on the resident memory
of a worker on one machine. The first block is now built alone in a
worker of its own and measured as the growth of the worker's peak
resident memory over the block, from the peak once the worker has set
itself up, so that what a worker holds for every block is left out. The
manifest records the estimate, the measurement and the setup peak side
by side under `reduce.block_size`. A first block that keeps 100,000 rows
or more and takes more than twice the estimate stops the run before any
other block, with nothing written, and one that keeps fewer is recorded
and not judged. Twice is a tolerance on a measure with known noise, not
a correction of the estimate. One synthetic first block, measured in one
fresh worker after another, read from a fifth of the estimate to nine
tenths of it, and memory sampled through the block peaked where the
measure did, so the spread is in what the block holds resident and not
in the reading. The manifest records the factor beside the measure. On
one worker the block runs in the process that planned the run, whose
peak cannot be put down to it, and a worker whose peak did not rise, as
a forked one can when the block weighs less than what it inherited, says
nothing of the block either. Neither has a measurement or a judgement,
and the manifest says why, and which start method the workers had. The
peak a worker logs is read in bytes on macOS and kibibytes on Linux,
where Linux's was taken as thousands of bytes. New:
`[reduce.pandas] targets_per_block` declares the size of a block in
place of `memory_gb`. It warns, and the manifest records the size as
declared.

**A histclim file with rows its leaf does not have is refused, naming
the first row and the regions or years the file alone has.** The two
are one projection under two climates, so a row in one alone means the
Expand Down
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,37 @@ n_workers = 16 # run.n_workers unless set
```

`--dry-run` prints the blocks and the number of file opens that
budget gives. Before any work the leaves are checked against their
budget gives. The blocks are sized from an estimate of the bytes a
kept row takes, calibrated on resident memory. The first block is built
alone in a worker of its own, and measured as the growth of that
worker's peak resident memory over the block, from the peak once the
worker has set itself up. The manifest records the estimate and the
measurement side by side under `reduce.block_size`, and the setup peak,
which every worker holds before its first block. A first block that
keeps 100,000 rows or more and takes more than twice the estimate stops
the run, with nothing written, since its blocks could take more than
the budget. Twice, and not once, because the measure is noisy. The same
block, measured in one fresh worker after another, can read from a
fifth of the estimate to nearly all of it. On one worker the blocks
run in the process that planned the run, whose peak includes what it
did before. A forked worker starts from what it inherited, and a block
lighter than that leaves its peak where it was. In both cases the
manifest says there is no measurement and why, and the run is not
judged.

Someone who has measured their own runs can declare the size of a
block instead, in targets, a whole number of the leaves' row groups:

```toml
[reduce.pandas]
targets_per_block = 4096 # in place of memory_gb
```

A declared size warns, since it overrides the estimate, and the
manifest records it as declared, with the first block's measurement
beside it and not judged.

Before any work the leaves are checked against their
manifest: what aggregated them has to be what the config says, field
by field, and every file has to be there with its size. A path is not
part of that. If the weights or the tree have moved, the run says so
Expand Down
7 changes: 6 additions & 1 deletion benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@ time the parts, so a rename there has to be followed here.
`test_bench_leaf.py` takes one leaf through `apply_weights` and
`window_means` with the labels attached at three different points, and
runs a process pool twice over the same leaves: once with 1.4 tasks a
worker and once with every task halved.
worker and once with every task halved. It also runs three waves of
leaves, one a task, through the pool the aggregate stage used, which
renewed each worker after 16 leaves, and through the waves of new
workers that replaced it. The time a leaf takes moves from run to run by
more than the two differ, so it prints the wall time not spent on
leaves beside the wall.
It prints the skipped regions and the missing targets once; the pool
workers mute the warning the library logs for every leaf.

Expand Down
87 changes: 85 additions & 2 deletions benchmarks/test_bench_leaf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""One leaf through `apply_weights` and `window_means`, and a process
pool run with a coarse and a fine task split.
"""One leaf through `apply_weights` and `window_means`, a process pool
run with a coarse and a fine task split, and the aggregate stage's pool
against the waves that replaced it.

The pool runs the same leaves twice, once with about 1.4 tasks a worker
and once with every task halved, at whatever worker count the machine
Expand Down Expand Up @@ -29,7 +30,9 @@
report,
source_leaf,
)
from cil_regionalization.pipelines.montecarlo import LEAVES_PER_WORKER
from cil_regionalization.stats import window_means
from cil_regionalization.workers import run_in_waves

pytestmark = pytest.mark.benchmark

Expand Down Expand Up @@ -122,3 +125,83 @@ def test_finer_tasks_give_the_same_leaves():
f" {2 * n_coarse} tasks of {half} leaves: {fine_s:.1f} s "
f"({fine_s / coarse_s:.0%} of the coarse run)"
)


_WORKER: dict = {}


def _load_weights() -> None:
"""The initializer of both pools. The weights load once a worker, as
the pipeline's do."""
logging.getLogger("cil_regionalization.validate").setLevel(logging.ERROR)
_WORKER["art"] = artifact(POOL_SCALE)


def _one_leaf(seed: int) -> tuple[int, int, float, float]:
"""The leaf's row count and sum, and the seconds it took in the
worker."""
start = time.perf_counter()
reduced = window_means(apply(_WORKER["art"], source_leaf(POOL_SCALE, seed)), **_KW)
return seed, len(reduced), float(reduced["pct"].sum()), time.perf_counter() - start


def _recycled_pool(seeds: list[int]) -> list:
"""What the aggregate stage ran before the waves."""
with mp.Pool(
processes=POOL_WORKERS,
initializer=_load_weights,
maxtasksperchild=LEAVES_PER_WORKER,
) as pool:
return sorted(pool.imap_unordered(_one_leaf, seeds, chunksize=1))


def _waves(seeds: list[int]) -> list:
got: list = []
run_in_waves(
_one_leaf,
seeds,
n_workers=POOL_WORKERS,
per_worker=LEAVES_PER_WORKER,
initializer=_load_weights,
initargs=(),
on_result=got.append,
name=str,
what="benchmark",
)
return sorted(got)


def test_waves_give_what_the_recycled_pool_gave():
"""Three waves of leaves, one a task, under the platform's start
method, each run twice and alternating. The time a leaf takes moves
from one run to the next on a laptop by more than the pools differ,
so what is compared is the wall time not spent on leaves, the wall
less the leaves' own seconds over the workers."""
seeds = list(range(3 * POOL_WORKERS * LEAVES_PER_WORKER))
runs: dict[str, list[tuple[float, float]]] = {"pool": [], "waves": []}
results = {}
for _ in range(2):
for key, run in (("pool", _recycled_pool), ("waves", _waves)):
start = time.perf_counter()
got = run(seeds)
wall = time.perf_counter() - start
runs[key].append((wall, wall - sum(r[3] for r in got) / POOL_WORKERS))
results[key] = [r[:3] for r in got]
assert results["waves"] == results["pool"]

report(
f"{len(seeds)} leaves at 1/{POOL_SCALE} size on {POOL_WORKERS} "
f"workers, {LEAVES_PER_WORKER} a worker, "
f"{mp.get_start_method()} start"
)
for key, label in (
("pool", "pool renewing each worker after its leaves"),
("waves", "waves of new workers"),
):
report(
f" {label + ':':<44} wall "
+ ", ".join(f"{wall:.1f}" for wall, _ in runs[key])
+ " s, not on leaves "
+ ", ".join(f"{other:.1f}" for _, other in runs[key])
+ " s"
)
64 changes: 45 additions & 19 deletions cil_regionalization/pipelines/montecarlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@
import hashlib
import itertools
import json
import multiprocessing as mp
import os
import sys
import warnings
Expand Down Expand Up @@ -141,11 +140,16 @@
members_that_join,
read_gmst,
)
from cil_regionalization.workers import WorkerDied, run_in_waves


VariableKind = Literal["extensive", "intensive", "ratio"]
# in a cell of tree.exclude, every value of the level
EVERY_VALUE = "*"
# The leaves a worker takes on average before new workers start, in
# waves of n_workers times this many. A worker's resident memory grows
# with the leaves it has processed, so the workers are renewed.
LEAVES_PER_WORKER = 16
Stage = Literal["all", "aggregate", "reduce"]


Expand Down Expand Up @@ -585,6 +589,11 @@ class PipelineOutputConfig(_Strict):


class RunConfig(_Strict):
"""``n_workers`` processes aggregate the leaves in waves, each wave on
new workers, since a worker's resident memory grows with the leaves
it has taken. A worker that dies stops the run, naming the leaves in
flight and saying how the workers ended."""

n_workers: int = Field(default=1, ge=1)


Expand Down Expand Up @@ -1016,25 +1025,42 @@ def collect(outcome: dict) -> None:
# The artifact loads once per worker (initializer), not once per
# task: shipping it in every task pickle made long-lived workers
# churn through thousands of unpickled copies, and their resident
# memory grew with leaves processed. maxtasksperchild recycles
# workers to bound what churn remains; chunksize=1 so recycling
# counts actual leaves. imap_unordered streams results so memory
# can be logged as the run accumulates.
# memory grew with leaves processed. New workers for every wave of
# LEAVES_PER_WORKER leaves a worker bound what churn remains. A
# worker that dies stops the run, where a multiprocessing.Pool
# waited for ever for the leaf it held.
worker_peak = 0.0
with mp.Pool(
processes=cfg.run.n_workers,
initializer=_init_worker,
initargs=initargs,
maxtasksperchild=16,
) as pool:
for outcome in pool.imap_unordered(_process_leaf, tasks, chunksize=1):
collect(outcome)
worker_peak = max(worker_peak, outcome.get("worker_peak_gb") or 0.0)
if len(outcomes) % 250 == 0 or len(outcomes) == len(tasks):
_log_memory(
f"leaves {len(outcomes)}/{len(tasks)}, "
f"max worker peak {worker_peak:.1f}G"
)

def take(outcome: dict) -> None:
nonlocal worker_peak
collect(outcome)
worker_peak = max(worker_peak, outcome.get("worker_peak_gb") or 0.0)
if len(outcomes) % 250 == 0 or len(outcomes) == len(tasks):
_log_memory(
f"leaves {len(outcomes)}/{len(tasks)}, "
f"max worker peak {worker_peak:.1f}G"
)

try:
run_in_waves(
_process_leaf,
tasks,
n_workers=cfg.run.n_workers,
per_worker=LEAVES_PER_WORKER,
initializer=_init_worker,
initargs=initargs,
on_result=take,
name=lambda task: "/".join(task[0].values),
what="pipeline",
)
except WorkerDied as error:
kept = (
" The leaf files written so far are kept, and the leaves "
"manifest is left incomplete."
if leaves_document is not None
else ""
)
raise WorkerDied(f"{error} No statistics were written.{kept}") from None
_log_memory("all leaves collected")

failures = [o for o in outcomes if o["error"] is not None]
Expand Down
21 changes: 18 additions & 3 deletions cil_regionalization/reduce/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from typing import Literal, Optional

import pandas as pd
from pydantic import Field
from pydantic import Field, model_validator

from cil_regionalization.config import _Strict

Expand All @@ -27,12 +27,27 @@

class PandasReduceOptions(_Strict):
"""Options of the pandas backend. ``memory_gb`` is the memory all
its workers may hold together and has no default. ``n_workers``
defaults to ``run.n_workers``."""
its workers may hold together, which the blocks are sized from, and
``targets_per_block`` declares their size instead. One of the two is
needed and neither has a default. ``n_workers`` defaults to
``run.n_workers``."""

memory_gb: Optional[float] = Field(default=None, gt=0)
# A whole number of the leaves' row groups. For an expert who has
# measured a run, and the manifest records it as declared.
targets_per_block: Optional[int] = Field(default=None, ge=1)
n_workers: Optional[int] = Field(default=None, ge=1)

@model_validator(mode="after")
def _one_way_to_size_the_blocks(self) -> "PandasReduceOptions":
if self.memory_gb is not None and self.targets_per_block is not None:
raise ValueError(
"[reduce.pandas] takes memory_gb, which the blocks are sized "
"from, or targets_per_block, which declares their size, not "
"both"
)
return self


class ReduceConfig(_Strict):
kind: Literal["pandas"] = "pandas"
Expand Down
Loading