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
910 changes: 72 additions & 838 deletions CHANGELOG.md

Large diffs are not rendered by default.

82 changes: 53 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -351,12 +351,37 @@ written, and the member count beside it says why. Any other infinite
statistic is the arithmetic passing the largest float, and is refused.
A NaN is a group with no value, and is written.

A group whose quantile is below one at a lower level is refused under
every method and sum, before anything is written, and the refusal names
the group and the pair with their values. It has no setting and no
tolerance. Equal quantiles are in order, the NaN quantiles of a group
with no value pass, the levels go in their own order and not in the
order asked for, and the mean is not one of them. The one level left out
is the 0.5 quantile of `"lower_step"`, which for members that count
equally is their plain median, as the historical tool defined it, and
not a point of the step. It can sit above the step quantile just over
0.5, and above the `-inf` that every step quantile of a single member
is. Its row says so. Every statistics file has a `plain_median` column,
true on such a q50 and false on every other row and under every other
method, so the schema does not change with the settings, and the
manifest records what the column means.

Files made before v0.6.0 had no such options. They are reproduced by
`"lower_step"` if the run had weights and `"linear"` if it had none,
with `"fast"`. Those without weights took their quantiles from pandas,
whose arithmetic for the same interpolation differs from numpy's in
the last bit of about one quantile in a hundred.

`"lower_step"` reproduces the historical extraction tool except where a
member is left out for a weight of zero, a missing weight or a missing
value. The tool asks whether a group's weights are equal with such a
member among them at weight zero, and the library asks it of the members
kept. So there, and only at q50, the library can give the plain median
where the tool gives the step value, never the other way. Anyone
comparing a q50 with a number the tool published meets it there. The
library drops such a member on purpose, since a member that does not
count must not decide anything else either.

## Country values from state values

A country value is not a statistic of its states' statistics, since a
Expand Down Expand Up @@ -631,35 +656,34 @@ n_workers = 16 # run.n_workers unless set
`--dry-run` prints the blocks and the number of file opens that budget
gives. The blocks are sized from an estimate of the bytes a kept row
takes, 240 for a leaf with no dimension and 40 more for each dimension,
set from resident memory on macOS. On real data on Linux, in the one run
measured there, a kept row of a leaf with no dimension took up to 223.05
bytes, so the estimate covers it by 1.076. 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. On Linux a first block
that keeps 100,000 rows or more and takes more than 1.25 times the
estimate stops the run, with nothing written, since its blocks could
take more than the budget. The first block stands for the others because
every block is of one size and does the same work, and on real data, on
Linux, the first blocks of sixteen workers agreed within 2%. On macOS
the first block is measured and recorded and not judged, and
`reduce.block_size.not_judged_here` says why. The same synthetic block
read there from 50 to 212 bytes a kept row from one fresh worker to the
next, for a cause not found, and a refusal against that would be one
against noise. On one worker the blocks run in the process that planned
the run, whose peak includes what it did before. A block that fits in
memory the worker already held leaves its peak where it was. In both
cases the manifest says there is no measurement and why, and the run is
not judged. The peak is read as each platform keeps it, as VmHWM of
`/proc/self/status` on Linux and as `ru_maxrss` on macOS. On Linux
`ru_maxrss` survives an exec, so a spawned worker's would start from the
peak of the process that started it. Under fork a worker counts the
pages it shares with that process as its own, so the peaks under
`reduce.block_size` and `max_worker_peak_gb` overstate what a worker
alone holds, which errs on the side of the budget. The growth, the
difference of two peaks that both count those pages, is exact.
set from resident memory on macOS. 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. On Linux a first block that keeps 100,000
rows or more and takes more than 1.25 times the estimate stops the run,
with nothing written, since its blocks could take more than the budget.
The first block stands for the others because every block of a run is
sized to the same budget and does the same work, so a first block well
above the estimate says the estimate is wrong for that data, and the
tolerance can be tight. Each run's manifest has what its blocks took. On
macOS the first block is measured and recorded and not judged, and
`reduce.block_size.not_judged_here` says why. The same block has read
there several times more from one fresh worker to the next, for a cause
not found, and a refusal against that would be one against noise. On one
worker the blocks run in the process that planned the run, whose peak
includes what it did before. A block that fits in memory the worker
already held leaves its peak where it was. In both cases the manifest
says there is no measurement and why, and the run is not judged. The
peak is read as each platform keeps it, as VmHWM of `/proc/self/status`
on Linux and as `ru_maxrss` on macOS. On Linux `ru_maxrss` survives an
exec, so a spawned worker's would start from the peak of the process
that started it. Under fork a worker counts the pages it shares with
that process as its own, so the peaks under `reduce.block_size` and
`max_worker_peak_gb` overstate what a worker alone holds, which errs on
the side of the budget. The growth, the difference of two peaks that
both count those pages, is exact.

Every block is recorded under `reduce.block_size.every_block`, each
worker's first block is measured, and only the run's first block is
Expand Down
6 changes: 3 additions & 3 deletions benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,6 @@ workers mute the warning the library logs for every leaf.
| `BENCH_WORKERS` | cores, at most 8 | pool size |
| `BENCH_LEAVES` | 48 | leaves in one coarse pool task |

A full-size leaf peaks at about 2 GiB in one process. The pool test
uses smaller leaves by default because eight full-size workers swap on
a 16 GB machine, and then the run measures swapping.
The pool test uses smaller leaves by default because eight full-size
workers swap on a laptop, and then the run measures swapping. The
benchmark prints its times and not its memory.
2 changes: 1 addition & 1 deletion benchmarks/test_bench_leaf.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
_KW = dict(time_col="year", windows=WINDOWS, value_col="pct", summation="fast")
_COLUMNS = ID_FIELDS + list(LABELS) + ["window", "pct"]

# Eight full-size workers need about 16 GiB, so the pool runs on leaves
# Eight full-size workers swap on a laptop, so the pool runs on leaves
# an eighth of the size unless told otherwise.
POOL_SCALE = int(os.environ.get("BENCH_POOL_SCALE", "8"))
POOL_WORKERS = int(os.environ.get("BENCH_WORKERS", min(8, os.cpu_count() or 1)))
Expand Down
4 changes: 2 additions & 2 deletions cil_regionalization/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -903,8 +903,8 @@ def _first_rows(codes: np.ndarray, card: int) -> np.ndarray:
def _rows_in(frame: pd.DataFrame, keys: list[str], ids: set[tuple]) -> np.ndarray:
"""Boolean mask of the rows whose ``keys`` tuple is in ``ids``, the
same as ``frame[keys].apply(tuple, axis=1).isin(ids)``."""
# This builds no Python tuple per row. Building one per row cost
# minutes and about 16 GiB at 100M rows.
# This builds no Python tuple per row. One per row is far slower and
# far larger at a hundred million rows.
return pd.MultiIndex.from_frame(frame[keys]).isin(ids)


Expand Down
4 changes: 2 additions & 2 deletions cil_regionalization/backends/bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -682,8 +682,8 @@ def _upload_temp_table(
# NEVER fail on geometry content; parsing is deferred to SQL
# where we run ``ST_GEOGFROMTEXT(geometry, make_valid => TRUE)``
# so spherical-invalid polygons (planar-valid but with edges
# that cross as geodesics, the exact failure mode of the 17
# 2022 NULLs) get repaired in the spherical domain at parse time.
# that cross as geodesics, the exact failure mode of the NULLs of
# 2022) get repaired in the spherical domain at parse time.
# No SAFE. wrapper: if make_valid cannot repair we want the loud
# named error, not a silent NULL.
job_config = self._bq.LoadJobConfig(
Expand Down
48 changes: 23 additions & 25 deletions cil_regionalization/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ class RegionsConfig(_Strict):
on_invalid_geometry: InvalidGeomPolicy
# NULL geometries in BQ regions tables: error (default, abort and list
# the offending hierids) or skip (exclude them, record in the manifest
# under null_geometry_regions). Measured 17 NULL hierids in the s51 IR
# table inherited from the legacy pipeline's SAFE.ST_GEOGFROMTEXT.
# under null_geometry_regions). The s51 IR table has such NULLs,
# inherited from the legacy pipeline's SAFE.ST_GEOGFROMTEXT.
on_null_geometry: Literal["error", "skip"] = "error"
# Requested ids in `regions.keep` that do not exist in the regions
# table: error (default, abort and list them) or skip (exclude,
Expand Down Expand Up @@ -193,10 +193,10 @@ class SourceConfig(_Strict):
# manifest under partial_coverage and the application layer refuses
# the artifact unless the caller explicitly allows it. The default
# tolerates boundary digitization noise between geometry products
# (well under 0.1 percent for interior units) while catching subset
# border slivers, which sit near zero coverage. Coastline mismatch
# between products may legitimately exceed the default for coastal
# units; the recording exists to measure that, not hide it.
# while catching subset border slivers, which sit near zero coverage.
# Coastline mismatch between products may legitimately exceed the
# default for coastal units; the recording exists to measure that,
# not hide it.
coverage_threshold: float = Field(default=0.999, gt=0, le=1)


Expand Down Expand Up @@ -229,19 +229,16 @@ class LocalBackendOptions(_Strict):
slurm_memory: Optional[str] = Field(default=None, min_length=1)
slurm_walltime: Optional[str] = Field(default=None, min_length=1)
# Segments below this geodesic area are dropped as boundary residue.
# The default is justified by the measured global IR-to-ADM1
# distribution: 3,410 of 28,646 segments fall below 1 m2 (floating
# point slivers where source boundaries run along target boundaries),
# then a natural gap with almost nothing between 1 m2 and a hectare,
# with real segments starting around the hectare scale. The largest
# share of any source unit's area carried by a sub-1 m2 segment is
# 8e-9, nine orders of magnitude below the sum tolerance, so the
# exact number is not delicate. Degenerate slivers are also what
# crashes exactextract's traversal. Set 0 to restore the exact
# positive-area filter. Every run records what the threshold dropped
# in the manifest under min_segment_area, so the "nothing real is
# being eaten" claim stays inspectable per run rather than trusted
# from the one measurement above.
# On the global IR-to-ADM1 intersection the segments below 1 m2 are
# floating point slivers where source boundaries run along target
# boundaries, with a gap above them before real segments start around
# the hectare scale, and none carries a share of its source unit's
# area anywhere near the sum tolerance, so the exact number is not
# delicate. Degenerate slivers are also what crashes exactextract's
# traversal. Set 0 to restore the exact positive-area filter. Every
# run records what the threshold dropped in the manifest under
# min_segment_area, so the "nothing real is being eaten" claim stays
# inspectable per run rather than trusted.
min_segment_area_m2: float = Field(default=1.0, ge=0)

@model_validator(mode="after")
Expand Down Expand Up @@ -281,12 +278,13 @@ class BigQueryBackendOptions(_Strict):
# needs both. No dataset is ever created.
project: Optional[str] = Field(default=None, min_length=1)
temp_dataset: Optional[str] = Field(default=None, min_length=1)
# 10 GB matches the confirmed worst-case s51 full-table scan of the GPW
# population table (~6 GB) with headroom. The ST_CONTAINS join scans
# the full GPW table regardless of how few regions are requested, so
# ~6 GB is the real cost of any run, not an estimate artifact of big
# ones. Larger runs must override explicitly in config; a
# defense-in-depth default ships before the code that needs it.
# The default sits above the worst full-table scan of the GPW
# population table measured for s51, with headroom. The ST_CONTAINS
# join scans the full GPW table regardless of how few regions are
# requested, so that scan is the real cost of any run, not an
# estimate artifact of big ones. Larger runs must override explicitly
# in config; a defense-in-depth default ships before the code that
# needs it.
dry_run_byte_ceiling: int = Field(default=10_000_000_000, ge=0)
# GCS staging URI for the geometry load job. The IR geometries table is
# in us-west1 and GPW is in US; we fetch geometries client-side and
Expand Down
26 changes: 20 additions & 6 deletions cil_regionalization/pipelines/montecarlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,11 @@
# same, which a test pins, and the pooled frame shrinks by the ratio of
# years to windows.
#
# Memory at scale, measured: a full mortality ADM2 run (about 4,000
# leaves by 42,726 targets, roughly 500 million member rows) peaked at
# 188.3 GB resident in the parent process at the pooled-statistics
# stage, and requests of 128 GB died three times at that scale. Size
# ADM2-scale requests at 224 GB or more, and read the memory[...] lines
# the run prints before trusting any smaller figure.
# Memory at scale is far above what a small run suggests. The pooled
# statistics stage holds the most, in the parent process, and a full
# ADM2 run needs a much larger request than an ADM1 one. Read the
# memory[...] lines the run prints, its own measure, before trusting
# any figure.

from __future__ import annotations

Expand Down Expand Up @@ -890,6 +889,17 @@ def _leaves_stem(cfg: MonteCarloPipelineConfig) -> str:
return cfg.output.leaves_stem or cfg.output.stem


# What the plain_median column of the statistics says, recorded in every
# manifest beside the method.
_PLAIN_MEDIAN_MEANING = (
'true on a q50 row that "lower_step" gives as the plain median of '
"members that count equally, as WeightedECDF.inverse of the historical "
"extraction tool gives it, and not a point of the step, so it can sit "
"above the quantile at the next level and is left out of the check of "
"the quantiles' order. False on every other row."
)


def run_pipeline(
cfg: MonteCarloPipelineConfig,
*,
Expand Down Expand Up @@ -1194,6 +1204,7 @@ def take(outcome: dict) -> None:
"windows": [_window_label(lo, hi) for lo, hi in cfg.stats.windows],
"quantiles": cfg.stats.quantiles,
"quantile_method": cfg.stats.quantile_method,
"plain_median": _PLAIN_MEDIAN_MEANING,
"summation": cfg.stats.summation,
"time_reduction": cfg.stats.time_reduction,
"years": None,
Expand Down Expand Up @@ -2168,6 +2179,7 @@ def _run_reduce(
),
"quantiles": cfg.stats.quantiles,
"quantile_method": cfg.stats.quantile_method,
"plain_median": _PLAIN_MEDIAN_MEANING,
"summation": cfg.stats.summation,
"time_reduction": cfg.stats.time_reduction,
"years": list(cfg.stats.years) if cfg.stats.years else None,
Expand Down Expand Up @@ -2240,6 +2252,7 @@ def _check_level_names(levels: list[str], id_fields: list[str]) -> None:
**{name: "an id field of the weights artifact" for name in id_fields},
"window": "the column of window labels",
"statistic": "the column of statistic labels",
"plain_median": "the column that marks a plain median",
"n_members": "the column stats.include_n_members writes",
"n_models": "the column of the climate models behind a statistic",
"n_sample": "the column of pooled rows stats.time_reduction writes",
Expand Down Expand Up @@ -2316,6 +2329,7 @@ def _ordered(frame: pd.DataFrame, cfg: MonteCarloPipelineConfig) -> pd.DataFrame
for column in frame.columns:
if column in declared or column in (
cfg.data.value_col,
"plain_median",
"n_members",
"n_sample",
"n_models",
Expand Down
2 changes: 1 addition & 1 deletion cil_regionalization/reduce/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def columns(self) -> list[str]:
+ kept_dims
+ kept_levels
+ ([self.time_col] if self.time_reduction == "per_year" else ["window"])
+ ["statistic", self.value_col]
+ ["statistic", self.value_col, "plain_median"]
+ (["n_members"] if self.include_n_members else [])
+ (
["n_sample"]
Expand Down
Loading