Skip to content

Fix bugs surfaced by code review - #16

Merged
knutdrand merged 12 commits into
masterfrom
fix-review-bugs
May 27, 2026
Merged

knutdrand merged 12 commits into
masterfrom
fix-review-bugs

Conversation

@knutdrand

@knutdrand knutdrand commented May 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes a batch of bugs found while reviewing the codebase, plus a major performance fix surfaced when running chap eval. All 38 tests pass (with the one slow HPO end-to-end test deselected by default — opt in via pytest -m slow).

Performance fix (separate commit)

Estimator.train hard-coded num_workers=3 in both the train and validation DataLoader. Lightning's default doesn't enable persistent_workers, so three worker processes were spawned and torn down every epoch. cProfile on this model shows ~85% of wall time in _shutdown_workers / process.join / process.start / select.poll.

per epoch (median)
Before (num_workers=3) 25.2 s
After (num_workers=0) 1.83 s

End-to-end:

wall time
chap eval (n-splits=7, max_epochs=30) 10 h 09 m → 2 m 04 s (~290×)
pytest tests/ (integration tests) 6 m 26 s → 36 s

Made num_workers a ModelConfiguration field defaulting to 0; when set >0, persistent_workers=True is also enabled so workers aren't respawned per epoch. Added scripts/bench_train.py — the diagnostic that surfaced the hotspots.

Also pinned requires-python = ">=3.12,<3.14": chap creates a fresh venv per run from this MLproject, and uv was resolving the unbounded upper bound to Python 3.14, which has no torch wheels.

Critical fixes from the review

  • target_scaler — scale_by_location had an early return eta, silently turning the scaler into a no-op while still being wired through the lightning module and predictor. Restored the intended eta * std + mu and added unit tests.
  • module.py — RNNWithLocationEmbedding.forward referenced self.output_decoder (commented out) and self.ouput_layer (typo). Repaired and switched the dummy decoder zeros to x.new_zeros so GPU/MPS use isn't broken.
  • MultiDataset.__getitem__ — dropped past_y and then crashed in Entry(*output) because Entry is a 5-field namedtuple.
  • AuxilliaryEstimator._get_transformed_dataset — three separate bugs: the override didn't accept validation_dataset, it unpacked 3 of a 4-tuple, and it indexed [-1] (val_dataset) when it meant the target scaler at [2].
  • hpo.py — Estimator(..., validate=True) was a non-existent kwarg; last_val_loss was always None; num_rnn_layers/n_layers were sampled from [4, 8, 16, 32] (layer counts, not hidden sizes); replaced deprecated suggest_loguniform. Also filter HPO-only fields out before constructing the strict ModelConfiguration.
  • Predictor.save / load — didn't persist the target scaler, and the loader always built the module with output_dim=2, so anything trained with predict_nans=True couldn't round-trip. Both fixed and exercised by round-trip tests.
  • Estimator.train — fell over when validate=True and no add_validation() was called (HPO's path). Now falls back to internal _split_validation.
  • problem_adaptions.adapt_dataset — the hasattr guard ran after an unguarded dataset.metadata.name access.

Cleanup

  • Removed DataSet shadowing inside Estimator.train.
  • StandardScaler.fit_transform → fit (the transformed result was unused).
  • Log1pTransform / Logp1RateTransform now dispatch on input type so numpy callers (dataset build) and torch callers (model) both work.
  • torch.load(weights_only=True) in predictor load.
  • Migrated remaining Pydantic v1 calls (.dict(), .copy(update=), .json(), parse_file) to v2 equivalents.
  • Narrowed a bare except Exception around get_commit_hash.
  • typed_suggestions.suggest_model now raises NotImplementedError for unhandled annotations instead of silently returning an under-specified config.
  • Deleted three empty stub files (module2.py, estimator2.py, data_set.py).
  • gitignored chtorch/study.db left behind by optuna.

New tests

  • tests/test_target_scaler.py (was empty) — 6 tests
  • tests/test_count_transforms.py — 4 tests
  • tests/test_module.py — 3 tests (incl. previously-broken in-file smoke tests)
  • tests/test_auxilliary_estimator.py — 3 plumbing tests
  • test_data_loader.py +2 MultiDataset tests
  • test_estimator.py +2 save/load round-trip tests
  • test_hpo_estimator marked @pytest.mark.slow; setup.cfg defaults to -m "not slow".

Test plan

  • pytest (default) → 38 passed, 2 skipped, 1 deselected (HPO); 36 s
  • chap eval on Vietnam admin1 monthly (n-splits=7, max_epochs=30) → 2 min 4 s, exit 0
  • pytest -m slow — test_hpo_estimator runs end-to-end; structurally fixed but opt-in
  • Manual smoke of the CLI on a real dataset

🤖 Generated with Claude Code

knutdrand and others added 12 commits January 22, 2026 14:39
Switch MLproject to use uv_env with pyproject.toml instead of python_env with pyenv.yaml.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Critical fixes:
- target_scaler: remove early `return eta` that made scale_by_location a no-op
- module.py: fix RNNWithLocationEmbedding.forward referencing undefined
  self.output_decoder and self.ouput_layer (typo); use input-device zeros
- data_loader: MultiDataset was dropping past_y and crashing on Entry(*output)
- auxilliary_estimator: signature mismatched parent (no validation_dataset
  arg), unpacked 3 values from a 4-tuple, indexed [-1] (val_dataset) when
  it meant [2] (target_scaler)
- hpo: removed bogus validate= kwarg, persist last_val_loss so HPO can read
  it, fix implausible num_rnn_layers/n_layers ∈ [4,8,16,32], use
  suggest_float(log=True) over deprecated suggest_loguniform; filter out
  HPO-only fields when constructing ModelConfiguration (extra='forbid')
- estimator: Predictor.save/load now persist target_scaler and output_dim
  so models trained with predict_nans=True can be round-tripped
- estimator: fall back to _split_validation when validate=True but no
  external validation set was provided (HPO path)
- problem_adaptions: useless hasattr guard came after dereference

Cleanup:
- Remove DataSet shadowing in Estimator.train
- StandardScaler: fit instead of fit_transform (result was unused)
- Log1pTransform / Logp1RateTransform: dispatch backend on input type so
  both numpy (dataset build) and torch (model) callers work
- Predictor.load: torch.load(weights_only=True), Pydantic v2 APIs
- Migrate remaining .dict() / .copy(update=) / .json() / parse_file to
  v2 equivalents (cli, lightning_module, tensorifier, estimator, hpo)
- Narrow bare except in commit-hash fetch
- typed_suggestions: raise NotImplementedError instead of silently
  returning under-specified configs
- Delete three empty stub files (module2.py, estimator2.py, data_set.py)

Testing:
- Add tests/test_target_scaler.py (was empty) — 6 tests
- Add tests/test_count_transforms.py — 4 tests
- Add tests/test_module.py — 3 tests (incl. previously-broken smoke tests)
- Add tests/test_auxilliary_estimator.py — 3 plumbing tests
- Add 2 MultiDataset tests to test_data_loader.py
- Add 2 save/load round-trip tests to test_estimator.py (output_dim + scaler)
- Mark test_hpo_estimator as slow; default pytest run deselects slow
- gitignore chtorch/study.db left behind by optuna

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The hard-coded num_workers=3 in Estimator.train was respawning three
worker processes every epoch (Lightning doesn't enable
persistent_workers by default). cProfile on a 5-epoch run shows ~85%
of wall time in worker spawn/shutdown:

    _shutdown_workers     84.3s
    process.join          75.0s
    select.poll           49.5s
    process._Popen.start  46.5s

For this model and dataset size (~5k params, ~9k samples) the worker
IPC dominates real compute. Switching to num_workers=0 cut a per-epoch
time from 25.2s to 1.83s (14× faster). End-to-end:

    chap eval (n-splits=7, max_epochs=30):  10h 09m → 2m 04s  (≈290×)
    pytest integration tests:                6m 26s → 36s

Also pin requires-python to >=3.12,<3.14: chap creates a fresh venv
per run from this MLproject, and uv was resolving the unbounded upper
to 3.14, which has no torch wheels.

Add scripts/bench_train.py — the diagnostic that surfaced the
multiprocessing hotspots; useful for future profiling.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
_get_decay_dict put any parameter whose name contains '.0.' into a
'level_2' bucket with weight_decay × 100. With chtorch's location
embeddings being created as

    nn.ModuleList([nn.Embedding(n_locations, ...),
                   nn.Embedding(n_parents,   ...)])

the parameter that hit the 100× rule was `location_embeddings.0.weight`
— the *primary* per-location embedding (e.g. 63 provinces for the VNM
dataset). The smaller parent embedding at index .1 got only the 10×
'embed' decay. That's backwards from any reasonable hierarchical-
regularization intent and pulls the very signal the model needs most
strongly toward zero.

Collapse the level_2 bucket: every 'embed' parameter now gets 10× decay
uniformly, and there's nothing magic about index order.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replace the linear year_position feature (day_of_year / 365 — a sawtooth
that jumps at year-end) with (sin, cos) of the annual phase. Smooth
periodic encoding lets the network learn annual seasonality without
having to bridge a discontinuity between Dec 31 and Jan 1.

While reorganising features, also lock the autoregressive columns into
fixed final positions: na_mask and target_column are now always the last
two columns of the tensorifier output, with the optional
population_column moved ahead of them. FlatRNN.direct_ar now slices
`x[..., -2:]` instead of the order-dependent `x[..., -3:-1]`, which
silently picked up the wrong columns whenever `use_population=False`.

Test shape assertion bumps from 7 to 8 features: -1 (year_position) +2
(sin, cos).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Log1pTransform.inverse used `exp(t)`, off by one from the true inverse
of `log1p(x) = log(1+x)` which is `expm1(t)`. Same off-by-one in
Logp1RateTransform.inverse. Effect on the model: with the buggy
inverse, NB.mean = exp(eta[0]), so target=0 forced the network to
output eta[0] → -∞. With the corrected inverse, NB.mean = expm1(eta[0])
≥ 0 is naturally reachable at eta[0] = 0, matching the scale of the
autoregressive target_column feature (log1p(cases)).

torch.distributions.NegativeBinomial requires total_count > 0, which
the old buggy inverse silently guaranteed via exp > 0. Now that mean
can legitimately be 0, clamp total_count at 1e-6 inside get_dist
(NegativeBinomialLoss / NBLossWithNaN / PoissonLoss rate) so the
distribution stays well-defined.

The original tests for these transforms were structural — they only
checked the formula was `exp(t)`. Replace with actual round-trip
assertions (`inverse(forward(x)) == x`) so future regressions surface.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The decoder previously consumed only a zero-vector + encoder state, so
future-horizon predictions had no awareness of which calendar month they
were forecasting. Per-horizon log-CRPS degraded 24% from h=0 to h=2
because of this.

The seasonal sin/cos features are deterministic from the date — we know
them for any future period without forecasting. Wire them through:

- tensorifier.seasonal_array(period_range) computes (T, 2) sin/cos.
- FlatTSDataSet accepts an optional `seasonal` array; __getitem__ slices
  the future window and exposes it as a new Entry.future_seasonal field.
- last_prediction_instance now takes an explicit future_seasonal arg,
  populated by Predictor.predict from future_data.period_range.
- FlatRNN.forward concatenates the per-step seasonal features onto the
  decoder dummy input (input_size grew from 1 → 1 + decoder_seasonal_dim).
- MultiDataset.__getitem__ rebuilt to use Entry._replace so future_seasonal
  flows through unmodified.
- Lightning passes batch.future_seasonal in train and validation steps.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add `climate_lags: list[int]` to TensorifierConfig (default []). When set,
the tensorifier emits one extra column per (additional_covariate, lag)
pair. Lagged values are pad-prefixed with the first observation so the
output array keeps the same length.

Motivated by dengue's known ~1–2 month delayed response to rainfall and
humidity (mosquito breeding cycle). Lets the model see those lags
explicitly instead of having to reconstruct them through the GRU's
hidden-state dynamics.

The autoregressive slice (`x[..., -2:]` for direct_ar) still works
because lagged columns are appended after the existing covariates, not
after na_mask / target_column.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Introduce IncidenceRateTransform: forward = log1p(cases / pop * 1000),
inverse = expm1(t) * pop / 1000. Mathematically a true inverse-pair
(unlike Log1pTransform whose inverse was exp, off by one), and the
target is on a per-1000-people scale that's comparable across provinces
spanning 0.4M → 8M population. eta[0]=0 now naturally produces a
predicted mean of 0 instead of forcing the model toward -∞.

Switch ModelBase / Estimator / Predictor to IncidenceRateTransform.

Loss-side support:
- MaskedNANLoss.forward broadcasts population to y_true's shape before
  masking, so transforms that consume population get an aligned tensor.
  Needed because past_y covers context_length-1 steps but batch.population
  is only the prediction horizon (population is per-location-constant via
  smooth_population, so broadcasting one column is safe).
- NBLossWithNaN.forward applies the same broadcast.
- _safe_total_count clamps NB total_count at 1e-6 so distributions stay
  valid when predicted mean is exactly 0.

Predictor.predict feeds batch.population (n_locs × pred_len) instead of
the historic-shape array — the shapes now match eta and broadcasting
works.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@knutdrand
knutdrand merged commit e31b2ae into master May 27, 2026
1 check failed
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