-
Notifications
You must be signed in to change notification settings - Fork 44
Add with_rolled_lon to downscaling models #1237
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
39d11b0
Add with_rolled_lon to downscaling models
frodre 5e0ca29
Fix utils riname use in models, consolidate coordinate creation
frodre d4028ae
Fix comments
frodre 3ee4ee6
Remove redundant moe test from test_models and use shared coordinate
frodre 4326050
comment clean up
frodre 5d3d75b
Add value check for static input data
frodre d3fc740
More documentation tweaks
frodre 1c5d882
Merge branch 'main' into feature/lon-roll-model
frodre c060398
Comment clenaup
frodre 69f4130
Merge branch 'feature/lon-roll-model' of github.com:ai2cm/ace into wt…
frodre c2b6aaa
Add flag for rolled model, checked at train time to ensure false
frodre 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,5 +22,6 @@ | |
| coords_require_lon_roll, | ||
| expand_and_fold_tensor, | ||
| find_roll_anchor, | ||
| roll_lon_coords, | ||
| scale_tuple, | ||
| ) | ||
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 |
|---|---|---|
|
|
@@ -21,7 +21,10 @@ | |
| PairedBatchData, | ||
| StaticInputs, | ||
| adjust_fine_coord_range, | ||
| coords_require_lon_roll, | ||
| find_roll_anchor, | ||
| load_coords_from_path, | ||
| roll_lon_coords, | ||
| ) | ||
| from fme.downscaling.metrics_and_maths import filter_tensor_mapping, interpolate | ||
| from fme.downscaling.modules.diffusion_registry import DiffusionModuleRegistrySelector | ||
|
|
@@ -399,6 +402,8 @@ def __init__( | |
| self._channel_axis = -3 | ||
| self.full_fine_coords = full_fine_coords.to(get_device()) | ||
| self.static_inputs = static_inputs.to_device() if static_inputs else None | ||
| # Set True only by with_rolled_lon (inference only); guards train_on_batch. | ||
| self._is_longitude_rolled = False | ||
| self._loss_weight_tensor = _build_variable_loss_weight_tensor( | ||
| config.loss_weights.output_channels, self.out_names | ||
| ) | ||
|
|
@@ -492,6 +497,12 @@ def train_on_batch( | |
| optimizer: Optimization | NullOptimization, | ||
| ) -> ModelOutputs: | ||
| """Performs a denoising training step on a batch of data.""" | ||
| if self._is_longitude_rolled: | ||
| raise RuntimeError( | ||
| "Cannot train a longitude-rolled DiffusionModel. with_rolled_lon " | ||
| "is intended for inference only; rolled models share weights and " | ||
| "would corrupt gradient synchronization under distributed training." | ||
| ) | ||
| _static_inputs = self._subset_static_if_available(batch.coarse) | ||
| coarse, fine = batch.coarse.data, batch.fine.data | ||
| inputs_norm = self._get_input_from_coarse(coarse, _static_inputs) | ||
|
|
@@ -747,6 +758,68 @@ def metadata(self): | |
| else 0, | ||
| ) | ||
|
|
||
| def _lon_roll_amount(self, coarse_lon: torch.Tensor) -> tuple[int, float]: | ||
| """ | ||
| Number of positions to roll the fine grid (and the lon_start it aligns to) | ||
| so the fine cells stay aligned to coarse_lon's coarse cells. | ||
|
|
||
| Assumes a uniformly spaced fine grid; validated by roll_lon_coords when | ||
| the roll is applied. | ||
| """ | ||
| lon_start = float(coarse_lon.min()) | ||
| fine_lon = self.full_fine_coords.lon | ||
| fine_spacing = float(fine_lon[1] - fine_lon[0]) | ||
| # Anchor on the western coarse-cell *edge* (not its center, lon_start) so | ||
| # the roll is a whole number of coarse cells; anchoring on the center | ||
| # would split the boundary coarse cell across the seam. | ||
| western_edge = lon_start - self.downscale_factor * fine_spacing / 2.0 | ||
| return find_roll_anchor(fine_lon, western_edge), lon_start | ||
|
|
||
| def with_rolled_lon(self, coarse_lon: torch.Tensor) -> "DiffusionModel": | ||
| """ | ||
| Return a new model with full_fine_coords and static_inputs rolled to match | ||
| coarse_lon's longitude convention, sharing the network weights. | ||
|
|
||
| Models with rolled longitude are useful when inference region crosses | ||
| the prime meridian, where we want to ensure we can grab proper slices | ||
| from the static inputs and provide the right coordinates for the outputs. | ||
|
|
||
| Returns self unchanged when coarse_lon does not cross the prime meridian. | ||
|
|
||
| Intended for inference only: rebuilding wraps the module in a second | ||
| DistributedDataParallel under torch distributed, which is a hazard for | ||
| gradient-synchronized training. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can an attribute |
||
| """ | ||
| if not coords_require_lon_roll(coarse_lon): | ||
| return self | ||
| roll_amount, lon_start = self._lon_roll_amount(coarse_lon) | ||
|
|
||
| # The new model is built through the constructor (rather than a shallow copy) | ||
| # so its coords are re-validated and derived state is rebuilt fresh; the raw | ||
| # module is unwrapped and passed so __init__ re-wraps it exactly once. | ||
| rolled = DiffusionModel( | ||
| config=self.config, | ||
| module=self.module.module, | ||
| normalizer=self.normalizer, | ||
| loss=self.loss, | ||
| coarse_shape=self.coarse_shape, | ||
| downscale_factor=self.downscale_factor, | ||
| sigma_data=self.sigma_data, | ||
| full_fine_coords=LatLonCoordinates( | ||
| lat=self.full_fine_coords.lat, | ||
| lon=roll_lon_coords(self.full_fine_coords.lon, roll_amount, lon_start), | ||
| ), | ||
| in_names=self.in_names, | ||
| out_names=self.out_names, | ||
| static_inputs=( | ||
| self.static_inputs.roll(roll_amount, lon_start) | ||
| if self.static_inputs is not None | ||
| else None | ||
| ), | ||
| ) | ||
| rolled._is_longitude_rolled = True | ||
| return rolled | ||
|
|
||
|
|
||
| @dataclasses.dataclass | ||
| class _CheckpointModelConfigSelector: | ||
|
|
||
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This will have to be tackled if we want to train with patches across the meridian.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe just do evaluations with patches crossing the meridian first to see if this gap in training distribution is an issue or not.