Repository navigation
Fix bugs surfaced by code review - #16
Merged
Merged
Conversation
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>
…unt" This reverts commit af7d7b8.
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>
This reverts commit 3f0bf4f.
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>
This reverts commit ea29ea8.
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 viapytest -m slow).Performance fix (separate commit)
Estimator.trainhard-codednum_workers=3in both the train and validation DataLoader. Lightning's default doesn't enablepersistent_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.num_workers=3)num_workers=0)End-to-end:
chap eval(n-splits=7, max_epochs=30)pytest tests/(integration tests)Made
num_workersaModelConfigurationfield defaulting to0; when set>0,persistent_workers=Trueis also enabled so workers aren't respawned per epoch. Addedscripts/bench_train.py— the diagnostic that surfaced the hotspots.Also pinned
requires-python = ">=3.12,<3.14":chapcreates 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_locationhad an earlyreturn eta, silently turning the scaler into a no-op while still being wired through the lightning module and predictor. Restored the intendedeta * std + muand added unit tests.module.py—RNNWithLocationEmbedding.forwardreferencedself.output_decoder(commented out) andself.ouput_layer(typo). Repaired and switched the dummy decoder zeros tox.new_zerosso GPU/MPS use isn't broken.MultiDataset.__getitem__— droppedpast_yand then crashed inEntry(*output)becauseEntryis a 5-field namedtuple.AuxilliaryEstimator._get_transformed_dataset— three separate bugs: the override didn't acceptvalidation_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_losswas always None;num_rnn_layers/n_layerswere sampled from[4, 8, 16, 32](layer counts, not hidden sizes); replaced deprecatedsuggest_loguniform. Also filter HPO-only fields out before constructing the strictModelConfiguration.Predictor.save/load— didn't persist the target scaler, and the loader always built the module withoutput_dim=2, so anything trained withpredict_nans=Truecouldn't round-trip. Both fixed and exercised by round-trip tests.Estimator.train— fell over whenvalidate=Trueand noadd_validation()was called (HPO's path). Now falls back to internal_split_validation.problem_adaptions.adapt_dataset— thehasattrguard ran after an unguardeddataset.metadata.nameaccess.Cleanup
DataSetshadowing insideEstimator.train.StandardScaler.fit_transform→fit(the transformed result was unused).Log1pTransform/Logp1RateTransformnow dispatch on input type so numpy callers (dataset build) and torch callers (model) both work.torch.load(weights_only=True)in predictor load..dict(),.copy(update=),.json(),parse_file) to v2 equivalents.except Exceptionaroundget_commit_hash.typed_suggestions.suggest_modelnow raisesNotImplementedErrorfor unhandled annotations instead of silently returning an under-specified config.module2.py,estimator2.py,data_set.py).chtorch/study.dbleft behind by optuna.New tests
tests/test_target_scaler.py(was empty) — 6 teststests/test_count_transforms.py— 4 teststests/test_module.py— 3 tests (incl. previously-broken in-file smoke tests)tests/test_auxilliary_estimator.py— 3 plumbing teststest_data_loader.py+2 MultiDataset teststest_estimator.py+2 save/load round-trip teststest_hpo_estimatormarked@pytest.mark.slow;setup.cfgdefaults to-m "not slow".Test plan
pytest(default) → 38 passed, 2 skipped, 1 deselected (HPO); 36 schap evalon Vietnam admin1 monthly (n-splits=7, max_epochs=30) → 2 min 4 s, exit 0pytest -m slow—test_hpo_estimatorruns end-to-end; structurally fixed but opt-in🤖 Generated with Claude Code