Skip to content

Persistence skip head + per-location residual scaling - #17

Open
knutdrand wants to merge 6 commits into
masterfrom
drop-target-scaler
Open

knutdrand wants to merge 6 commits into
masterfrom
drop-target-scaler

Conversation

@knutdrand

Copy link
Copy Markdown
Collaborator

Summary

Two architectural changes on the prediction head, plus the supporting infrastructure:

  1. Drop the per-location TargetScaler. With IncidenceRateTransform the mean head already lives in log1p(rate) space; the per-loc shift+scale on top created a scale asymmetry (global stats on the input, per-loc stats on the output) that empirically dampened the model's response to recent surges.

  2. Persistence skip head + per-location std residual scaling. The mean channel is now

    eta_mean = network_output * per_loc_std + last_log_rate
    

    network_output = 0 ⇒ predict the most recent observation. Non-zero outputs are deviations in per-location-sigma units of log1p(rate). The network only has to learn residuals — per-location baselines come for free regardless of training-set size.

A configurable toggle persistence_skip: bool = True is exposed for ablations.

Results

Run on both the existing VNM monthly dataset and the LAO monthly dataset (smaller — 18 provinces vs 63), measuring sample-CRPS on log1p-transformed counts ("log-CRPS"):

VNM mean LAO mean
pre-PR baseline (incidence-rate + TargetScaler) 0.643 1.549
drop TargetScaler 0.602 1.877
+ persistence skip 0.629 1.119
+ per-location std residual (HEAD) 0.598 1.120

VNM: −7% vs baseline. LAO: −28% vs baseline. The dataset-size sensitivity was the diagnosis we converged on: VNM has enough samples per location for the embedding to encode a per-location baseline; LAO doesn't, and the persistence skip is what makes the network responsive there. The AR-attention probe on LAO confirms it — pre-change the model predicted ~25 with trail=1460 cases; now it tracks recent values almost exactly.

A full ablation (persistence_skip: false):

Dataset skip=True skip=False
VNM mean log-CRPS 0.598 0.668
LAO mean log-CRPS 1.120 3.550

Skip is load-bearing for LAO; we keep it as the default.

Implementation

  • Estimator._get_single_transformed_dataset now computes per-location std of log1p(rate) and returns target_scaler=None.
  • FlatTSDataSet carries both last_log_rate (un-normalised, per-sample) and per_loc_std per location; Entry namedtuple has two new fields with None defaults.
  • FlatRNN.forward accepts both as kwargs and applies the skip+scaling on the mean channel only (dispersion and any extra channels untouched).
  • Predictor saves/loads per_loc_std via joblib next to the model state dict.
  • MultiDataset.__getitem__ rebuilt around Entry._replace so future Entry fields flow through unmodified.
  • distribution_loss._safe_total_count got a nan_to_num + upper-bound clamp — without the persistence skip the network can output arbitrarily large/negative eta at init, producing NaN/inf in the NB total_count.

Diagnostic scripts added under scripts/

  • log_crps.py / log_crps_all.py — sample-CRPS computation (single + cross-run)
  • probe_ar_attention.py — does the model actually use the most-recent observation?
  • inspect_eval.py / analyse_eval.py — per-location prediction inspection
  • inspect_decay.py — which params end up in which weight-decay bucket (turned up the .0. rule bug earlier)
  • bench_train_val.py — per-epoch train + validation loss
  • bench_train.py — single-train wall-clock + cProfile

Test plan

  • pytest tests/ → 41 passed, 2 skipped, 1 deselected (HPO is slow)
  • chap eval on VNM (vnm_monthly_config.yaml, persistence_skip=true) → 4 min, log-CRPS 0.598
  • chap eval on LAO (same config) → 4 min, log-CRPS 1.120
  • chap eval on the malaria/IRS spray dataset (different covariates) — runs end-to-end (~17 min, log-CRPS 0.392 — not directly comparable, different scale and 0% zero-rate)
  • Ablation persistence_skip: false confirms the toggle works and that the default is the right one

🤖 Generated with Claude Code

knutdrand and others added 6 commits May 27, 2026 15:37
The TargetScaler was creating a scale asymmetry:
- AR features (target_column = log1p(rate)) entered the network
  standardised by GLOBAL StandardScaler stats over all locations × times.
- The mean head was unscaled per-LOCATION (eta * per_loc_std + per_loc_mu).

For a low-incidence province with small per_loc_std, predicting an
outbreak required the network to output very large eta — the gradient
signal in training (where surges are rare) doesn't drive the optimiser
to produce those large values, so surge predictions get dampened.

With IncidenceRateTransform the mean head already lives in log1p(rate)
space, the same space as the AR feature, so the per-location rescale
was both load-bearing for the asymmetry and unnecessary.

Two callsites updated: `Estimator._get_single_transformed_dataset`
returns `target_scaler=None`, and `AuxilliaryEstimator` falls back to
`None` instead of trying to wrap None scalers in MultiTargetScaler.

Tests updated to assert the new behaviour (target_scaler is None on
both fresh predictors and load round-trips).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The mean head now adds the un-normalized log1p(rate) at the final
historic step to the network's raw output. With this:

  eta_mean = network_output + last_observed_log1p_rate

So network_output=0 ⇒ prediction = last observation. The network only
has to learn deviations from "stay the same"; per-location baselines
come for free regardless of training-set size, which directly
addresses the LAO regression from dropping TargetScaler (small
dataset, location embedding too thin to recover the baseline).

Wiring:
- Entry namedtuple gets a last_log_rate field (defaults to None).
- FlatTSDataSet.__getitem__ reads it from X[..., -1] BEFORE the
  StandardScaler transform — tensorifier guarantees target_column is
  the last feature column.
- FlatTSDataSet.last_prediction_instance does the same for predict-
  time; ditto MultiDataset via _replace.
- FlatRNN.forward accepts last_log_rate kwarg and adds it to
  channel 0 (the mean parameter) of every output time step.
  Dispersion and any extra channels are untouched.
- Lightning's train/val steps and Predictor.predict pass
  batch.last_log_rate through.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Builds on the persistence skip: the network's mean-channel output is now
multiplied by per_loc_std before being added to last_log_rate. The
prediction is

    eta_mean = network_out * per_loc_std + last_log_rate

So:
- network_out = 0  → predict last observation (persistence)
- network_out = 1  → one per-location-sigma above last value

Why: per the asymmetry diagnosis, residual-from-persistence has very
different absolute scales across locations (HCM month-to-month deltas
≫ Yên Bái month-to-month deltas). With this scaling, the network
sees all locations in comparable units; gradients are homogenised
across the dataset. It's algebraically equivalent to "per-location
StandardScaler on the input + restored TargetScaler" but implemented
on the output side only — no input changes, no TargetScaler.

Wiring:
- Entry namedtuple gets per_loc_std (defaults to None).
- FlatTSDataSet stores the per-location std array; __getitem__ and
  last_prediction_instance expose it per sample / per location.
- Estimator computes per_loc_std from log1p(rate) of training data.
- Predictor persists per_loc_std via joblib for the predict path.
- FlatRNN.forward accepts the per_loc_std kwarg; mean-channel is
  multiplied before the last_log_rate add.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`_safe_total_count` now also handles NaN/inf via `nan_to_num` and an
upper bound. Without the persistence skip the network can output
arbitrarily large/negative eta at init, and `expm1(eta[0]) / exp(eta[1])`
can produce NaN/inf that `clamp_min` silently passed through, blowing
up the NB constraint check.

Add `RNNConfiguration.persistence_skip: bool = True` to toggle the
persistence + per-loc-std-residual head. Default True (matches the
configuration that gave VNM 0.598, LAO 1.120). False=ablation mode:
predict raw eta with no baseline / no residual scaling.

Diagnostic scripts (scripts/):
- log_crps.py / log_crps_all.py — single-eval and cross-eval log-CRPS
- probe_ar_attention.py — does the model actually adapt to recent cases?
- inspect_eval.py / analyse_eval.py — per-location prediction inspection
- inspect_decay.py — which params end up in which weight-decay bucket
- bench_train_val.py — per-epoch train + validation loss trajectory
- bench_train.py — single-train wall-clock + cProfile

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The workflow was pinned to 3.10 but `pyproject.toml` requires
`>=3.12,<3.14` (torch needs cp312+). CI had been failing on master for
months. Bumping to 3.12 to match the install constraint.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
requirements_dev.txt is a pre-uv-migration artefact pinning ancient
package versions (watchdog==0.9.0, etc.) that don't install on Python
3.12 (e.g. watchdog 0.9 imports `imp`, removed in 3.12).

Match the local dev setup instead: install with uv from pyproject.toml,
run tests with `uv run pytest tests/`. Drops `make test-all` since we
don't need the cov+doctest+example.py passes for the green-tick run.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

1 participant