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

## Unreleased

**A model takes the row of its own name in a model weights table,
letter for letter, or the row declared for it, and a model with
neither is refused.** Before, the library dropped `surrogate_` from the
tree's names and `*` from the table's and lowercased both, a rule
nobody saw that could put a weight on the wrong model. The refusal
names each model as the tree spells it with the row it comes closest
to, and says the two ways out: write the trees' names into the table,
or declare each model's row, model name to table name, under
`[stats.model_weight_names]` of a pipeline config or as `table_names`
of `read_model_weights` and `fetch_model_weights`. The manifest records
the rows declared. **The published SMME tables do not pass as they
stand.** They name the models in lower case, some with a trailing `*`,
and the surrogates without the prefix, so of the 32 models under
rcp45 and the 33 under rcp85 only `bcc-csm1-1` matches. Until the
tables are rewritten, every run that reads them declares the rows.
`examples/model_weights/` holds the pairs for both tables, written out,
and `load_model_weight_names` reads them. Two models declared to one
row, or taking one row between them, are refused. `ModelWeights` loses
`keys` and gains `check`, and `read_model_weights` takes `sep`. The
France, aggregation, energy percentiles and valued mortality examples
declare their rows.

**A model at weight zero is dropped before every quantile, as it was
from the mean.** `"lower_step"` could return the value of such a model,
since its weight did not move the running share. The published SMME
tables have no row at weight zero.

**`UnweightedModelWeightsWarning` is given when `model_dims` names the
climate model and no weights are set, and no longer when a sample
dimension is called `gcm`.** Its message names no lab.
`summarize_samples` and `pooled_statistics` take `model_dims` without
`include_n_members`, for the warning, where it was refused.

**No fact of one cluster or one cloud account is a default.** With
`backend.local.dask = "slurm"` the queue, the cores, memory and
walltime of a job and the number of jobs, `slurm_queue`, the new
`slurm_cores` and `slurm_memory`, `slurm_walltime` and `n_workers`, are
required. They defaulted to one cluster's partition. With
`backend.kind = "bigquery"`, `backend.bigquery.project` and
`temp_dataset` are required, where they defaulted to one cloud
account's. The docstrings that named a cluster's paths no longer do,
and a test reads every module of the package for such facts, where it
read the pipeline alone.

**The BigQuery backend refuses an edge-offset grid.** Its SQL places
the cells for the centre offset, so it returned the weights of an
edge-offset grid half a cell off. The config and the backend both
refuse it.

The documentation of `quantile_method` says which value estimates a
quantile. `"inverted_cdf"` is the estimator and returns a value a
member has. `"linear"` interpolates and can return a number no member
Expand Down Expand Up @@ -214,14 +263,11 @@ its warming level in a calendar period.
carries is of the bytes the rows were parsed from. `attach` returns
the weight of each row's model and raises if a model has no row.
`record` returns the entry a manifest should keep, described below.
Names match as they did before: a `*` is dropped from the table
name, `surrogate_` is dropped from the member, and both are
lowercased.
- Changed: a weights table in which two rows match the same model is
refused, with both rows named. Before, the last of the two rows was
applied and nothing was said. Neither published SMME table has such
rows (32 names in the rcp45 table, 33 in the rcp85 one, all
distinct after matching), so no run that worked is refused.
A model takes the row of its own name or the row declared for it,
as the first entry of this section says.
- Changed: a weights table with a name in it twice is refused, with
the name given. Before, the last of the two rows was applied and
nothing was said.
- Changed: the pipeline reads the model weights file once, in the
parent, and hands those rows to the workers. Before, every worker
read the file again when it started, and workers are replaced every
Expand Down
70 changes: 46 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,10 @@ product reads the same table. `attach` gives every draw the weight of
its model, so the weight repeats across batches:

```python
weights = cilreg.fetch_model_weights("rcp85")
from cil_regionalization.pipelines.montecarlo import load_model_weight_names

names = load_model_weight_names("examples/model_weights/smme_rcp85_names.toml")
weights = cilreg.fetch_model_weights("rcp85", table_names=names)
draws["weight"] = weights.attach(draws["gcm"])
stats = cilreg.summarize_samples(
draws,
Expand All @@ -242,34 +245,51 @@ stats = cilreg.summarize_samples(
)
```

The naming rule: weight file names are lowercase, a trailing `*` is
bookkeeping and drops out, and an underscore suffix (`gfdl-cm3_94`)
marks a surrogate, which the projection trees spell with a prefix
(`surrogate_GFDL-CM3_94`). Strip the prefix and lowercase, and every
model in the trees matches exactly one weight row.

`read_model_weights` applies that rule to a file on disk. It reads the
file once and refuses a table in which two rows match the same model.
A model takes the row of its own name, letter for letter, or the row
declared for it, and a model with neither is refused. Nothing reads a
name to decide what it means, so a weight cannot land on the wrong
model by a rule nobody sees. The published tables do not pass as they
stand. They name the models in lower case, some with a trailing `*`,
and the surrogates without the `surrogate_` prefix of the trees, so
`ACCESS1-0` is the row `access1-0*` and `surrogate_GFDL-CM3_94` the row
`gfdl-cm3_94`. Until the tables are rewritten with the trees' names, a
run declares each model's row, model name to table name, written out.
`examples/model_weights/` holds the pairs for both published tables,
which the code above reads. The refusal names the row a model comes
closest to, and the two ways out, fixing the table or declaring the
row.

`read_model_weights` does the same for a file on disk. It reads the
file once and refuses a table that has a name twice, and two models
declared to one row.

```python
weights = cilreg.read_model_weights("rcp85_SMME_weights.tsv")
weights = cilreg.read_model_weights("rcp85_SMME_weights.tsv", table_names=names)
draws["weight"] = weights.attach(draws["gcm"])
entry = weights.record(leaf_models) # one model name per leaf pooled
```

`attach` raises if a model has no row. `record` returns what a manifest
should keep about the run: the file's path and SHA256, each model that
was given a weight with that weight and its number of leaves, and the
rows no model matched with their weights. The two lists together are
the whole table, so the statistics can be rerun from the manifest if
the file is lost. A pipeline run writes this entry to its manifest as
`model_weights_record`.
`attach` raises if a model has no row, or two models take one row.
`record` returns what a manifest should keep about the run: the file's
path and SHA256, the rows declared, each model that was given a weight
with its row, that weight and its number of leaves, and the rows no
model took with their weights. The two lists together are the whole
table, so the statistics can be rerun from the manifest if the file is
lost. A pipeline run writes this entry to its manifest as
`model_weights_record`, and takes the declared rows as
`[stats.model_weight_names]`:

```toml
[stats.model_weight_names]
"ACCESS1-0" = "access1-0*"
"surrogate_GFDL-CM3_94" = "gfdl-cm3_94"
```

Weighted quantiles follow the historical extraction tool: the left
step inverse of the weighted empirical distribution, not the
interpolated quantiles of the unweighted path. Pooling a sample
dimension named `gcm` without weights warns once; filter
`UnweightedModelWeightsWarning` to silence it. On the Mexico sample
interpolated quantiles of the unweighted path. Pooling without
weights while `model_dims` names the climate model warns once. Filter
`UnweightedModelWeightsWarning` where equal weights are meant. On the Mexico sample
(`examples/rates`) the weights barely move the median and pull the
95th percentile down by about a fifth.

Expand All @@ -279,8 +299,8 @@ the computation:
- `"inverted_cdf"` is the estimator of a quantile, the standard
inverse of the empirical distribution (Hyndman and Fan type 1), the
smallest member value whose cumulative weight share reaches q. It is
the same with or without weights, always returns the value of a
member, and never that of a member whose weight is zero.
the same with or without weights, and always returns the value of a
member.
- `"linear"` interpolates between two members, so it can return a
number no member holds. It is computed by numpy, so it is
`numpy.quantile(method="linear")` and xarray's `.quantile` to the
Expand All @@ -291,10 +311,12 @@ the computation:
except the median of members that count equally. Without weights
every member counts the same, which is what that tool did when it
was told to use no model weights. A quantile at or below the first
member's share is `-inf`, and the value of a member with weight zero
can come back.
member's share is `-inf`.

The names say what each computes, so pick by that, not by the name.
A member with weight zero is dropped before any of them, and before
the mean and the counts, so no quantile returns the value of a member
that weighs nothing.

With four members that count equally the three give three different
95th percentiles. `"inverted_cdf"` gives the fourth member, `"linear"`
Expand Down
4 changes: 3 additions & 1 deletion cil_regionalization/backends/bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@


from cil_regionalization.backends.base import WeightsBackend, WeightsResult
from cil_regionalization.config import Config
from cil_regionalization.config import BIGQUERY_CENTRE_ONLY, Config
from cil_regionalization.fallback import (
apply_fallback,
compute_native_weights,
Expand Down Expand Up @@ -317,6 +317,8 @@ def _validate_inputs(
"BigQueryBackend Stage 3 supports grid.mode='generate' only. "
"Prebuilt grids land later."
)
if grid.offset != "center":
raise ValueError(BIGQUERY_CENTRE_ONLY.format(offset=grid.offset))
for w in weights:
if w.is_area:
continue
Expand Down
5 changes: 5 additions & 0 deletions cil_regionalization/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,11 @@ def _cmd_regions_find(config_path: str, *, pattern: str, limit: int) -> int:
def _regions_find_bq(cfg: Config, primary: str, pattern: str, limit: int) -> int:
from google.cloud import bigquery

if cfg.backend.bigquery.project is None:
raise ValueError(
"regions.table is read through BigQuery, which needs "
"backend.bigquery.project, the billing project. It has no default."
)
client = bigquery.Client(project=cfg.backend.bigquery.project)
table = cfg.regions.table
project, dataset, _ = table.split(".", 2)
Expand Down
41 changes: 18 additions & 23 deletions cil_regionalization/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
with dask_client_for(cfg.backend.local) as client:
... # `client` is None when dask = "off"

The config's `n_workers`, `threads_per_worker`, `slurm_queue` and
`slurm_walltime` override the defaults. The cores and memory of a SLURM
job are fixed to the CIL 'cil' partition.
The config's `n_workers` and `threads_per_worker` override the local
defaults. A SLURM cluster takes its queue, the cores, memory and
walltime of a job and the number of jobs from the config alone, which
has no default for any of them.
"""

from __future__ import annotations
Expand All @@ -22,15 +23,6 @@
logger = logging.getLogger(__name__)


# CIL 'cil' partition reference shape: 64 cores, 251 GB RAM per node,
# typical run uses 2 nodes. One Dask worker per node by default so
# in-process geometry caches are shared across threads.
_SLURM_DEFAULT_QUEUE = "cil"
_SLURM_DEFAULT_CORES = 64
_SLURM_DEFAULT_MEMORY = "251GB"
_SLURM_DEFAULT_WALLTIME = "02:00:00"
_SLURM_DEFAULT_N_WORKERS = 2

# LocalCluster reference shape: one worker per process so each gets
# its own Python interpreter (geometry ops release the GIL only
# partially); single thread per worker keeps the scheduler simple.
Expand All @@ -46,9 +38,10 @@ def dask_client_for(opts: LocalBackendOptions) -> Iterator[Optional[object]]:
Under ``"off"`` the caller runs serially and Dask is not imported, so
this works without the optional dependency. ``"local"`` starts a
``LocalCluster`` on this machine. ``"slurm"`` starts a
``dask_jobqueue.SLURMCluster`` on the CIL 'cil' partition and scales it
to ``opts.n_workers`` jobs. The client and cluster are closed when the
``with`` block exits. Raises if ``opts.dask`` is any other value.
``dask_jobqueue.SLURMCluster`` with the queue, cores, memory and
walltime of ``opts`` and scales it to ``opts.n_workers`` jobs. The
client and cluster are closed when the ``with`` block exits. Raises
if ``opts.dask`` is any other value, or a SLURM setting is missing.
"""
if opts.dask == "off":
yield None
Expand Down Expand Up @@ -79,23 +72,25 @@ def dask_client_for(opts: LocalBackendOptions) -> Iterator[Optional[object]]:
return

if opts.dask == "slurm":
# checked again, before anything is imported, for options built
# without the model's check
type(opts).model_validate(opts.model_dump())
from dask.distributed import Client
from dask_jobqueue import SLURMCluster

n_workers = opts.n_workers or _SLURM_DEFAULT_N_WORKERS
cluster = SLURMCluster(
queue=opts.slurm_queue or _SLURM_DEFAULT_QUEUE,
cores=_SLURM_DEFAULT_CORES,
memory=_SLURM_DEFAULT_MEMORY,
walltime=opts.slurm_walltime or _SLURM_DEFAULT_WALLTIME,
queue=opts.slurm_queue,
cores=opts.slurm_cores,
memory=opts.slurm_memory,
walltime=opts.slurm_walltime,
processes=opts.threads_per_worker or 1,
)
cluster.scale(jobs=n_workers)
cluster.scale(jobs=opts.n_workers)
client = Client(cluster)
logger.info(
"dask SLURMCluster requested: %d jobs on queue %r",
n_workers,
opts.slurm_queue or _SLURM_DEFAULT_QUEUE,
opts.n_workers,
opts.slurm_queue,
)
try:
yield client
Expand Down
Loading