|
| 1 | +"""Module for physical constraint layers used in graph weather models. |
| 2 | +
|
| 3 | +This module implements several constraints on a network’s intermediate outputs, |
| 4 | +ensuring physical consistency with an input at a lower resolution. |
| 5 | +
|
| 6 | +""" |
| 7 | + |
| 8 | +import torch |
| 9 | +import torch.nn as nn |
| 10 | + |
| 11 | + |
| 12 | +class PhysicalConstraintLayer(nn.Module): |
| 13 | + """ |
| 14 | +
|
| 15 | + This module implements several constraint types on the network’s intermediate outputs ỹ, |
| 16 | + given the corresponding low-resolution input x. The following equations are implemented |
| 17 | + (with all operations acting per patch – here, a patch is the full grid of H×W pixels): |
| 18 | +
|
| 19 | + Additive constraint: |
| 20 | + y = ỹ + x - avg(ỹ) |
| 21 | +
|
| 22 | + Multiplicative constraint: |
| 23 | + y = ỹ * ( x / avg(ỹ) ) |
| 24 | +
|
| 25 | + Softmax constraint: |
| 26 | + y = exp(ỹ) * ( x / sum(exp(ỹ)) ) |
| 27 | +
|
| 28 | + We assume that both the intermediate outputs and the low-resolution reference are 4D |
| 29 | + tensors in grid format, with shape [B, C, H, W], where n = H*W is the number of pixels |
| 30 | + (or nodes) in a patch. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, model, grid_shape, upsampling_factor, constraint_type="none", exp_factor=1.0 |
| 35 | + ): |
| 36 | + """Initialize the PhysicalConstraintLayer. |
| 37 | +
|
| 38 | + Args: |
| 39 | + model (nn.Module): The model containing the helper methods |
| 40 | + 'graph_to_grid' and 'grid_to_graph'. |
| 41 | + grid_shape (tuple): Expected spatial dimensions (H, W) of the |
| 42 | + high-resolution grid. |
| 43 | + upsampling_factor (int): Factor by which the low-resolution grid is upsampled. |
| 44 | + constraint_type (str, optional): The constraint to apply. Options are |
| 45 | + 'additive', 'multiplicative', or 'softmax'. Defaults to "none". |
| 46 | + exp_factor (float, optional): Exponent factor for the softmax constraint. |
| 47 | + Defaults to 1.0. |
| 48 | + """ |
| 49 | + super().__init__() |
| 50 | + self.model = model |
| 51 | + self.constraint_type = constraint_type |
| 52 | + self.grid_shape = grid_shape |
| 53 | + self.exp_factor = exp_factor |
| 54 | + self.upsampling_factor = upsampling_factor |
| 55 | + self.pool = nn.AvgPool2d(kernel_size=upsampling_factor) |
| 56 | + |
| 57 | + def forward(self, hr_graph, lr_graph): |
| 58 | + """Apply the selected physical constraint. |
| 59 | +
|
| 60 | + Processes the high-resolution output and low-resolution input by converting |
| 61 | + between graph and grid formats as needed, and then applying the specified constraint. |
| 62 | +
|
| 63 | + Args: |
| 64 | + hr_graph (torch.Tensor): High-resolution model output in either graph (3D) |
| 65 | + or grid (4D) format. |
| 66 | + lr_graph (torch.Tensor): Low-resolution input in the corresponding |
| 67 | + graph or grid format. |
| 68 | +
|
| 69 | + Returns: |
| 70 | + torch.Tensor: The adjusted output in graph format. |
| 71 | + """ |
| 72 | + # Check if inputs are in graph (3D) or grid (4D) formats. |
| 73 | + if hr_graph.dim() == 3: |
| 74 | + # Convert graph format to grid format |
| 75 | + hr_grid = self.model.graph_to_grid(hr_graph) |
| 76 | + lr_grid = self.model.graph_to_grid(lr_graph) |
| 77 | + elif hr_graph.dim() == 4: |
| 78 | + # Already in grid format: [B, C, H, W] |
| 79 | + _, _, H, W = hr_graph.shape |
| 80 | + if (H, W) != self.grid_shape: |
| 81 | + raise ValueError(f"Expected spatial dimensions {self.grid_shape}, got {(H, W)}") |
| 82 | + hr_grid = hr_graph |
| 83 | + lr_grid = lr_graph |
| 84 | + else: |
| 85 | + raise ValueError("Input tensor must be either 3D (graph) or 4D (grid).") |
| 86 | + |
| 87 | + # Apply constraint based on type in grid format |
| 88 | + if self.constraint_type == "additive": |
| 89 | + result = self.additive_constraint(hr_grid, lr_grid) |
| 90 | + elif self.constraint_type == "multiplicative": |
| 91 | + result = self.multiplicative_constraint(hr_grid, lr_grid) |
| 92 | + elif self.constraint_type == "softmax": |
| 93 | + result = self.softmax_constraint(hr_grid, lr_grid) |
| 94 | + else: |
| 95 | + raise ValueError(f"Unknown constraint type: {self.constraint_type}") |
| 96 | + |
| 97 | + # Convert grid back to graph format |
| 98 | + return self.model.grid_to_graph(result) |
| 99 | + |
| 100 | + def additive_constraint(self, hr, lr): |
| 101 | + """Enforces local conservation using an additive correction: |
| 102 | + y = ỹ + ( x - avg(ỹ) ) |
| 103 | + where avg(ỹ) is computed per patch (via an average-pooling layer). |
| 104 | +
|
| 105 | + For the additive constraint we follow the paper’s formulation using a Kronecker |
| 106 | + product to expand the discrepancy between the low-resolution field and the |
| 107 | + average of the high-resolution output. |
| 108 | +
|
| 109 | + hr: high-resolution tensor [B, C, H_hr, W_hr] |
| 110 | + lr: low-resolution tensor [B, C, h_lr, w_lr] |
| 111 | + (with H_hr = upsampling_factor * h_lr & W_hr = upsampling_factor * w_lr) |
| 112 | + """ |
| 113 | + # Convert grids to graph format using model's mapping |
| 114 | + hr_graph = self.model.grid_to_graph(hr) |
| 115 | + lr_graph = self.model.grid_to_graph(lr) |
| 116 | + |
| 117 | + # Apply constraint logic |
| 118 | + # Compute average over NODES |
| 119 | + avg_hr = hr_graph.mean(dim=1, keepdim=True) |
| 120 | + diff = lr_graph - avg_hr |
| 121 | + |
| 122 | + # Expand difference using spatial mapping |
| 123 | + diff_expanded = diff.repeat(1, self.upsampling_factor**2, 1) |
| 124 | + |
| 125 | + # Apply correction and convert back to GRID format |
| 126 | + adjusted_graph = hr_graph + diff_expanded |
| 127 | + return self.model.graph_to_grid(adjusted_graph) |
| 128 | + |
| 129 | + def multiplicative_constraint(self, hr, lr): |
| 130 | + """Enforce conservation using a multiplicative correction in graph space. |
| 131 | +
|
| 132 | + The correction is applied by scaling the high-resolution output by a ratio computed |
| 133 | + from the low-resolution input and the average of the high-resolution output. |
| 134 | +
|
| 135 | + Args: |
| 136 | + hr (torch.Tensor): High-resolution tensor in grid format [B, C, H_hr, W_hr]. |
| 137 | + lr (torch.Tensor): Low-resolution tensor in grid format [B, C, h_lr, w_lr]. |
| 138 | +
|
| 139 | + Returns: |
| 140 | + torch.Tensor: Adjusted high-resolution tensor in grid format. |
| 141 | + """ |
| 142 | + # Convert grids to graph format using model's mapping |
| 143 | + hr_graph = self.model.grid_to_graph(hr) |
| 144 | + lr_graph = self.model.grid_to_graph(lr) |
| 145 | + |
| 146 | + # Apply constraint logic |
| 147 | + # Compute average over NODES |
| 148 | + avg_hr = hr_graph.mean(dim=1, keepdim=True) |
| 149 | + lr_patch_avg = lr_graph.mean(dim=1, keepdim=True) |
| 150 | + |
| 151 | + # Compute ratio and expand to match HR graph structure |
| 152 | + ratio = lr_patch_avg / (avg_hr + 1e-8) |
| 153 | + |
| 154 | + # Apply multiplicative correction and convert back to GRID format |
| 155 | + adjusted_graph = hr_graph * ratio |
| 156 | + return self.model.graph_to_grid(adjusted_graph) |
| 157 | + |
| 158 | + def softmax_constraint(self, y, lr): |
| 159 | + """Apply a softmax-based constraint correction. |
| 160 | +
|
| 161 | + The softmax correction scales the exponentiated high-resolution output so that the |
| 162 | + sum over spatial blocks matches the low-resolution reference. |
| 163 | +
|
| 164 | + Args: |
| 165 | + y (torch.Tensor): High-resolution tensor in grid format [B, C, H, W]. |
| 166 | + lr (torch.Tensor): Low-resolution tensor in grid format [B, C, h, w]. |
| 167 | +
|
| 168 | + Returns: |
| 169 | + torch.Tensor: Adjusted high-resolution tensor in grid format after applying |
| 170 | + the softmax constraint. |
| 171 | + """ |
| 172 | + # Apply the exponential function |
| 173 | + y = torch.exp(self.exp_factor * y) |
| 174 | + |
| 175 | + # Pool over spatial blocks |
| 176 | + kernel_area = self.upsampling_factor**2 |
| 177 | + sum_y = self.pool(y) * kernel_area |
| 178 | + |
| 179 | + # Ensure that lr * (1/sum_y) is contiguous |
| 180 | + ratio = (lr * (1 / sum_y)).contiguous() |
| 181 | + |
| 182 | + # Use device of lr for kron expansion: |
| 183 | + device = lr.device |
| 184 | + expansion = torch.ones((self.upsampling_factor, self.upsampling_factor), device=device) |
| 185 | + |
| 186 | + # Expand the low-resolution ratio and correct the y values so that the block sum matches lr. |
| 187 | + out = y * torch.kron(ratio, expansion) |
| 188 | + return out |
0 commit comments