-
Notifications
You must be signed in to change notification settings - Fork 275
Add PersistencePredictor baseline model #677
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
GiGiKoneti
wants to merge
11
commits into
mllam:main
Choose a base branch
from
GiGiKoneti:feat/persistence-predictor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
0bd45c5
Add PersistencePredictor baseline model
GiGiKoneti e4174ab
Fix imports and pre-commit checks for persistence predictor
GiGiKoneti 5c59987
Address review feedback
GiGiKoneti 9a705b0
Fix test_eval_without_load_warning by patching MODELS
GiGiKoneti 2a5defe
Address review feedback
GiGiKoneti 97d317f
Merge branch 'main' into feat/persistence-predictor
sadamov 2f7e8ac
Address review suggestions
GiGiKoneti 8e3cebe
Merge branch 'main' into feat/persistence-predictor
sadamov b59f173
Merge branch 'upstream/main' into feat/persistence-predictor and reso…
GiGiKoneti 37968b9
Merge branch 'feat/persistence-predictor' of https://github.com/GiGiK…
GiGiKoneti cfcb451
Merge branch 'main' into feat/persistence-predictor
GiGiKoneti File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| """Persistence baseline step predictor.""" | ||
|
|
||
| # Third-party | ||
| import torch | ||
| from loguru import logger | ||
|
|
||
| # Local | ||
| from ...datastore import BaseDatastore | ||
| from .base import StepPredictor | ||
|
|
||
|
|
||
| class PersistencePredictor(StepPredictor): | ||
| """ | ||
| Trivial baseline predictor that returns the previous state unchanged. | ||
|
|
||
| At each AR step the predicted next state is simply the current state, | ||
| i.e. ``X_{t+1} = X_t``. This provides a persistence (climatological | ||
| no-change) baseline that can be evaluated through the standard | ||
| ``ForecasterModule`` / ``ARForecaster`` pipeline. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| datastore: BaseDatastore, | ||
| output_std: bool = False, | ||
| output_clamping_lower: dict[str, float] | None = None, | ||
| output_clamping_upper: dict[str, float] | None = None, | ||
| **kwargs, | ||
| ) -> None: | ||
| """ | ||
| Initialize the PersistencePredictor. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| datastore : BaseDatastore | ||
| The datastore providing grid metadata and data access. | ||
| output_std : bool, default False | ||
| Ignored — persistence never predicts uncertainty. | ||
| output_clamping_lower : dict, optional | ||
| Ignored — persistence returns the raw previous state. | ||
| output_clamping_upper : dict, optional | ||
| Ignored — persistence returns the raw previous state. | ||
| **kwargs | ||
| Absorbed so that the standard CLI kwargs (``graph_name``, | ||
| ``hidden_dim``, etc.) do not cause errors. | ||
| """ | ||
| if output_std: | ||
| logger.warning( | ||
| "Persistence predictor does not support predicting " | ||
| "standard deviation. The output_std parameter will be ignored." | ||
| ) | ||
|
|
||
| super().__init__( | ||
| datastore=datastore, | ||
| output_std=False, | ||
| output_clamping_lower=None, | ||
| output_clamping_upper=None, | ||
| ) | ||
|
|
||
| def forward( | ||
| self, | ||
| prev_state: torch.Tensor, | ||
| prev_prev_state: torch.Tensor, | ||
| forcing: torch.Tensor, | ||
| ) -> tuple[torch.Tensor, None]: | ||
| """ | ||
| Return the previous state as the prediction. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| prev_state : torch.Tensor | ||
| Shape ``(B, num_grid_nodes, num_state_vars)``. | ||
| The current state ``X_t``. | ||
| prev_prev_state : torch.Tensor | ||
| Shape ``(B, num_grid_nodes, num_state_vars)``. | ||
| The previous state ``X_{t-1}`` (unused). | ||
| forcing : torch.Tensor | ||
| Shape ``(B, num_grid_nodes, num_forcing_vars)``. | ||
| External forcings (unused). | ||
|
|
||
| Returns | ||
| ------- | ||
| pred_state : torch.Tensor | ||
| Shape ``(B, num_grid_nodes, num_state_vars)``. | ||
| Equal to ``prev_state``. | ||
| pred_std : None | ||
| Always ``None`` — persistence does not predict uncertainty. | ||
| """ | ||
| return prev_state, None |
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| """Tests for the PersistencePredictor baseline model.""" | ||
|
|
||
| # Third-party | ||
| import pytest | ||
| import torch | ||
|
|
||
| # First-party | ||
| from neural_lam.models import ARForecaster | ||
| from neural_lam.models.step_predictors.persistence import PersistencePredictor | ||
| from tests.conftest import init_datastore_example | ||
|
|
||
|
|
||
| def test_persistence_predictor_returns_prev_state(): | ||
| """PersistencePredictor.forward returns prev_state unchanged.""" | ||
| datastore = init_datastore_example("mdp") | ||
| predictor = PersistencePredictor(datastore=datastore) | ||
| assert predictor.trainable is False | ||
|
|
||
| B = 2 | ||
| num_grid_nodes = predictor.num_grid_nodes | ||
| d_state = datastore.get_num_data_vars(category="state") | ||
| d_forcing = datastore.get_num_data_vars(category="forcing") | ||
|
|
||
| prev_state = torch.randn(B, num_grid_nodes, d_state) | ||
| prev_prev_state = torch.randn(B, num_grid_nodes, d_state) | ||
| forcing = torch.randn(B, num_grid_nodes, d_forcing) | ||
|
|
||
| pred_state, pred_std = predictor(prev_state, prev_prev_state, forcing) | ||
|
|
||
| assert pred_std is None | ||
| assert torch.equal(pred_state, prev_state) | ||
|
|
||
|
|
||
| def test_persistence_predictor_ignores_kwargs(): | ||
| """Extra graph-specific kwargs are silently absorbed.""" | ||
| datastore = init_datastore_example("mdp") | ||
| predictor = PersistencePredictor( | ||
| datastore=datastore, | ||
| graph_name="multiscale", | ||
| hidden_dim=64, | ||
| hidden_layers=1, | ||
| processor_layers=4, | ||
| mesh_aggr="sum", | ||
| ) | ||
| assert isinstance(predictor, PersistencePredictor) | ||
|
|
||
|
|
||
| def test_persistence_forecaster_unroll(): | ||
| """ARForecaster with PersistencePredictor reproduces initial state.""" | ||
| datastore = init_datastore_example("mdp") | ||
| predictor = PersistencePredictor(datastore=datastore) | ||
| forecaster = ARForecaster(predictor, datastore) | ||
|
|
||
| B = 2 | ||
| num_grid_nodes = predictor.num_grid_nodes | ||
| d_state = datastore.get_num_data_vars(category="state") | ||
| d_forcing = datastore.get_num_data_vars(category="forcing") * 3 | ||
| pred_steps = 4 | ||
|
|
||
| init_states = torch.randn(B, 2, num_grid_nodes, d_state) | ||
| forcing = torch.randn(B, pred_steps, num_grid_nodes, d_forcing) | ||
| boundary_states = torch.randn(B, pred_steps, num_grid_nodes, d_state) | ||
|
|
||
| prediction, pred_std = forecaster(init_states, forcing, boundary_states) | ||
|
|
||
| assert prediction.shape == (B, pred_steps, num_grid_nodes, d_state) | ||
| assert pred_std is None | ||
|
|
||
| # Persistence keeps every interior node at init_states[:, 1] for all | ||
| # steps, while boundary nodes are overwritten with boundary_states. | ||
| interior_mask = forecaster.interior_mask.squeeze(0).squeeze(-1).bool() | ||
| boundary_mask = forecaster.boundary_mask.squeeze(0).squeeze(-1).bool() | ||
| for t in range(pred_steps): | ||
| assert torch.equal( | ||
| prediction[:, t, interior_mask, :], | ||
| init_states[:, 1, interior_mask, :], | ||
| ) | ||
| assert torch.equal( | ||
| prediction[:, t, boundary_mask, :], | ||
| boundary_states[:, t, boundary_mask, :], | ||
| ) | ||
|
|
||
|
|
||
| def test_persistence_predicts_std_false(): | ||
| """ | ||
| PersistencePredictor.predicts_std is always False and logs warning | ||
| when output_std is True. | ||
| """ | ||
| # Standard library | ||
| from unittest.mock import patch | ||
|
|
||
| datastore = init_datastore_example("mdp") | ||
| target_patch = ( | ||
| "neural_lam.models.step_predictors.persistence.logger.warning" | ||
| ) | ||
| with patch(target_patch) as mock_warn: | ||
| predictor = PersistencePredictor(datastore=datastore, output_std=True) | ||
| assert not predictor.predicts_std | ||
| mock_warn.assert_called_once_with( | ||
| "Persistence predictor does not support predicting " | ||
| "standard deviation. The output_std parameter will be ignored." | ||
| ) | ||
|
|
||
|
|
||
| def test_persistence_training_error(): | ||
| """ValueError must be raised if trying to train the persistence model.""" | ||
| # Standard library | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| # First-party | ||
| from neural_lam.train_model import main | ||
|
|
||
| mock_args = MagicMock() | ||
| mock_args.eval = None # training mode | ||
| mock_args.load = None | ||
| mock_args.config_path = "dummy.yaml" | ||
| mock_args.val_steps_to_log = [] | ||
| mock_args.var_leads_metrics_watch = "{}" | ||
| mock_args.ar_steps_eval = 10 | ||
| mock_args.model = "persistence" | ||
| mock_args.devices = ["auto"] | ||
|
|
||
| mock_predictor = MagicMock() | ||
| mock_predictor.trainable = False | ||
|
|
||
| with ( | ||
| patch( | ||
| "neural_lam.train_model.ArgumentParser.parse_args", | ||
| return_value=mock_args, | ||
| ), | ||
| patch( | ||
| "neural_lam.train_model.load_config_and_datastore", | ||
| return_value=(MagicMock(), MagicMock()), | ||
| ), | ||
| patch("neural_lam.train_model.WeatherDataModule"), | ||
| patch( | ||
| "neural_lam.train_model.MODELS", | ||
| {"persistence": MagicMock(return_value=mock_predictor)}, | ||
| ), | ||
| pytest.raises( | ||
| ValueError, | ||
| match="The persistence model cannot be trained", | ||
| ), | ||
| ): | ||
| getattr(main, "__wrapped__", main)() | ||
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.