diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ec7ba17..fc7e569a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Fix missing forecast differences in MEPS standardization [\#915](https://github.com/mllam/neural-lam/pull/915) @kalashmishra21 + - Fix `InteractionNet` and `PropagationNet` dimension mismatches when `hidden_dim` differs from `input_dim` [\#836](https://github.com/mllam/neural-lam/pull/836) @Karvy-Singh - Raise a `ValueError` for `--val_interval` below 1 in `train_model.fit`; `0` previously crashed with a `ZeroDivisionError` inside Lightning after the model was built, and negative values were silently accepted [\#847](https://github.com/mllam/neural-lam/pull/847) @nikhil3495 diff --git a/neural_lam/datastore/npyfilesmeps/compute_standardization_stats.py b/neural_lam/datastore/npyfilesmeps/compute_standardization_stats.py index 585b7af5..ad0e45e0 100644 --- a/neural_lam/datastore/npyfilesmeps/compute_standardization_stats.py +++ b/neural_lam/datastore/npyfilesmeps/compute_standardization_stats.py @@ -458,7 +458,6 @@ def main( assert time_step_unit == "hours", ( "Only 'hours' time unit is supported by meps datastore." ) - used_subsample_len = (65 // time_step_int) * time_step_int diff_means, diff_squares = [], [] real_masks_standard = None @@ -480,25 +479,14 @@ def main( # (B, num_times', num_grid_nodes, num_state_vars) batch = torch.cat((init_batch, target_batch), dim=1) # Note: batch contains only 1h-steps - stepped_batch = torch.cat( - [ - batch[:, ss_i:used_subsample_len:time_step_int] - for ss_i in range(time_step_int) - ], - dim=0, - ) - # (B', num_times, num_grid_nodes, num_state_vars), - # B' = step_length*B - batch_diffs = stepped_batch[:, 1:] - stepped_batch[:, :-1] - # (B', num_times-1, num_grid_nodes, num_state_vars) + batch_diffs = batch[:, time_step_int:] - batch[:, :-time_step_int] + # (B, num_times' - time_step_int, num_grid_nodes, num_state_vars) batch_diff_means = torch.mean(batch_diffs, dim=(1, 2)).cpu() - # (B', num_state_vars,) + # (B, num_state_vars) batch_diff_squares = torch.mean(batch_diffs**2, dim=(1, 2)).cpu() - # (B', num_state_vars,) + # (B, num_state_vars) if real_masks_standard is not None: - # stepped_batch stacks the time_step_int ss_i blocks along dim 0, - # so tile the mask (repeat, not repeat_interleave) - mask = real_masks_standard[batch_i].repeat(time_step_int) + mask = real_masks_standard[batch_i] batch_diff_means = batch_diff_means[mask] batch_diff_squares = batch_diff_squares[mask] diff_means.append(batch_diff_means) @@ -527,8 +515,8 @@ def main( ) ] - diff_means = [torch.cat(diff_means, dim=0)] # (B', num_state_vars,) - diff_squares = [torch.cat(diff_squares, dim=0)] # (B', num_state_vars,) + diff_means = [torch.cat(diff_means, dim=0)] + diff_squares = [torch.cat(diff_squares, dim=0)] if rank == 0: save_stats(static_dir_path, diff_means, diff_squares, [], [], "diff") diff --git a/tests/test_compute_standardization_stats.py b/tests/test_compute_standardization_stats.py index 34f92126..87d3d13f 100644 --- a/tests/test_compute_standardization_stats.py +++ b/tests/test_compute_standardization_stats.py @@ -177,6 +177,219 @@ def test_main_gathers_short_batches_without_distributed_padding( torch.testing.assert_close(diff_std, torch.zeros(1)) +class _TailChangeDataset: + """One 65-step forecast with changes only in the final two leads.""" + + def __init__(self, **_): + self.state = torch.tensor([0.0] * 63 + [6.0, 12.0]).view(65, 1, 1) + + def __len__(self): + return 1 + + def __getitem__(self, idx): + forcing = torch.zeros(63, 1, 1) + return ( + self.state[:2], + self.state[2:], + forcing, + torch.zeros(0), + torch.zeros(1), + ) + + +def test_three_hour_difference_stats_include_final_valid_pairs( + tmp_path, monkeypatch +): + """Every valid three-hour pair contributes to difference statistics.""" + monkeypatch.setattr( + compute_standardization_stats, "init_datastore", lambda **_: object() + ) + monkeypatch.setattr( + compute_standardization_stats, "WeatherDataset", _TailChangeDataset + ) + + compute_standardization_stats.main( + datastore_config_path=tmp_path / "config.yaml", + batch_size=1, + step_length=timedelta(hours=3), + n_workers=0, + distributed=False, + ) + + raw = torch.tensor([0.0] * 63 + [6.0, 12.0]) + standardized_differences = (raw[3:] - raw[:-3]) / raw.std(unbiased=False) + expected = torch.stack( + ( + standardized_differences.mean(), + standardized_differences.std(unbiased=False), + ) + ) + actual = torch.stack( + tuple( + torch.load( + tmp_path / "static" / f"diff_{name}.pt", weights_only=True + ) + for name in ("mean", "std") + ) + ).flatten() + torch.testing.assert_close( + actual, + expected, + msg=f"actual mean/std {actual.tolist()}, expected {expected.tolist()}", + ) + + +def _difference_series(sample_index): + """Return two distinguishable features with changes at the final leads.""" + lead = torch.arange(65, dtype=torch.float32) + first = (sample_index + 1) * lead + second = (4 - sample_index) * lead + first[63] += 6 * (sample_index + 1) + first[64] += 12 * (sample_index + 1) + second[63] += 2 * (sample_index + 1) + second[64] += 5 * (sample_index + 1) + return torch.stack((first, second), dim=-1).unsqueeze(1) + + +class _DifferenceSeriesDataset: + """Three distinct 65-lead samples with two state features each.""" + + def __init__(self, **_): + pass + + def __len__(self): + return 3 + + def __getitem__(self, idx): + state = _difference_series(idx) + forcing = torch.full((63, 1, 1), float(10 + idx)) + return state[:2], state[2:], forcing, torch.zeros(0), torch.zeros(1) + + +def _expected_difference_stats(stride): + """Calculate population statistics from every valid raw lead pair.""" + raw = torch.stack([_difference_series(i) for i in range(3)]).double() + state_std = raw.std(dim=(0, 1, 2), unbiased=False) + differences = (raw[:, stride:] - raw[:, :-stride]) / state_std + return torch.stack( + ( + differences.mean(dim=(0, 1, 2)), + differences.std(dim=(0, 1, 2), unbiased=False), + ) + ).float() + + +def _saved_difference_stats(static_path): + """Read the mean and standard deviation created by the real job.""" + return torch.stack( + tuple( + torch.load(static_path / f"diff_{name}.pt", weights_only=True) + for name in ("mean", "std") + ) + ) + + +@pytest.mark.parametrize("stride", [1, 2, 3, 5, 8]) +def test_difference_stats_use_every_valid_pair_for_supported_strides( + tmp_path, monkeypatch, stride +): + """Keep one-hour/divisible controls and include remainder tails.""" + monkeypatch.setattr( + compute_standardization_stats, "init_datastore", lambda **_: object() + ) + monkeypatch.setattr( + compute_standardization_stats, + "WeatherDataset", + _DifferenceSeriesDataset, + ) + compute_standardization_stats.main( + datastore_config_path=tmp_path / "config.yaml", + batch_size=2, + step_length=timedelta(hours=stride), + n_workers=0, + distributed=False, + ) + actual = _saved_difference_stats(tmp_path / "static") + expected = _expected_difference_stats(stride) + torch.testing.assert_close( + actual, + expected, + msg=( + f"stride={stride}: actual {actual.tolist()}, " + f"expected {expected.tolist()}" + ), + ) + + +def _run_distributed_difference_stats(rank, world_size, config_path, init_path): + """Run the same three-sample statistics job on two CPU/Gloo ranks.""" + compute_standardization_stats.init_datastore = lambda **_: object() + compute_standardization_stats.WeatherDataset = _DifferenceSeriesDataset + compute_standardization_stats.get_rank = lambda: rank + compute_standardization_stats.get_world_size = lambda: world_size + compute_standardization_stats.torch.cuda.is_available = lambda: False + + def setup(_rank, _world_size): + compute_standardization_stats.dist.init_process_group( + "gloo", + init_method=init_path.as_uri(), + rank=_rank, + world_size=_world_size, + timeout=timedelta(seconds=60), + ) + + compute_standardization_stats.setup = setup + compute_standardization_stats.main( + datastore_config_path=config_path, + batch_size=2, + step_length=timedelta(hours=3), + n_workers=0, + distributed=True, + ) + + +def test_distributed_difference_stats_include_tail_with_padding( + tmp_path, +): + """Two ranks must score all three distinct samples exactly once.""" + world_size = 2 + mp.spawn( + _run_distributed_difference_stats, + args=(world_size, tmp_path / "config.yaml", tmp_path / "dist_init"), + nprocs=world_size, + join=True, + ) + + static_path = tmp_path / "static" + raw = torch.stack([_difference_series(i) for i in range(3)]).double() + for name, expected in ( + ("parameter_mean", raw.mean(dim=(0, 1, 2)).float()), + ("parameter_std", raw.std(dim=(0, 1, 2), unbiased=False).float()), + ( + "flux_stats", + torch.stack( + ( + torch.tensor(11.0), + torch.tensor([10.0, 11.0, 12.0]).std(unbiased=False), + ) + ), + ), + ): + actual = torch.load(static_path / f"{name}.pt", weights_only=True) + torch.testing.assert_close(actual, expected) + + actual = _saved_difference_stats(static_path) + expected = _expected_difference_stats(3) + torch.testing.assert_close( + actual, + expected, + msg=( + f"distributed actual {actual.tolist()}, " + f"expected {expected.tolist()}" + ), + ) + + # -- Bug 2: positional depadding after distributed gather ------------------