Datasets:
Download modis_s2/model.py from riccardode/s2_res: direct link, hf CLI and curl.
- Browser
- Download file 8.73 kB
-
https://huggingface.co/datasets/riccardode/s2_res/resolve/main/modis_s2/model.py
- Command line
-
hf download hf://datasets/riccardode/s2_res/modis_s2/model.py
-
curl -L -o model.py https://huggingface.co/datasets/riccardode/s2_res/resolve/main/modis_s2/model.py
8.73 kB
| """Multimodal temporal transformer with spatial encoding and a target-day query. | |
| Study adaptation of temporal self-attention and attention-weighted U-Net skips. | |
| Inputs are prefiltered to the declared cutoff. The model accepts predictors only. | |
| """ | |
| import math | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from torch.utils.checkpoint import checkpoint | |
| from .layers import _Conv | |
| class FrameEncoder(nn.Module): | |
| def __init__(self, channels): | |
| super().__init__() | |
| self.half_block = _Conv(channels, 64) | |
| self.quarter_block = _Conv(64, 128) | |
| self.eighth_block = _Conv(128, 256) | |
| def forward(self, image): | |
| half = self.half_block(F.avg_pool2d(image, 2)) | |
| quarter = self.quarter_block(F.avg_pool2d(half, 2)) | |
| eighth = self.eighth_block(F.avg_pool2d(quarter, 2)) | |
| return half, quarter, eighth | |
| class TemporalBlock(nn.Module): | |
| def __init__(self, width=256, heads=8, dropout=.1): | |
| super().__init__() | |
| self.norm1 = nn.LayerNorm(width) | |
| self.attention = nn.MultiheadAttention(width, heads, dropout=dropout, batch_first=True) | |
| self.norm2 = nn.LayerNorm(width) | |
| self.mlp = nn.Sequential(nn.Linear(width, 4 * width), nn.GELU(), nn.Dropout(dropout), | |
| nn.Linear(4 * width, width), nn.Dropout(dropout)) | |
| def forward(self, tokens, absent): | |
| normalized = self.norm1(tokens) | |
| update, _ = self.attention(normalized, normalized, normalized, | |
| key_padding_mask=absent, need_weights=False) | |
| tokens = tokens + update | |
| return tokens + self.mlp(self.norm2(tokens)) | |
| class TemporalTransformer(nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.encoders = nn.ModuleList([FrameEncoder(n) for n in (4, 37, 5, 6)]) | |
| self.static = FrameEncoder(23) | |
| self.sensor = nn.Parameter(torch.randn(4, 256) * .02) | |
| self.time = nn.Sequential(nn.Linear(6, 256), nn.GELU(), nn.Linear(256, 256)) | |
| self.query = nn.Parameter(torch.randn(256) * .02) | |
| self.temporal = nn.ModuleList([TemporalBlock() for _ in range(6)]) | |
| self.cross_norm = nn.LayerNorm(256) | |
| self.cross = nn.MultiheadAttention(256, 8, dropout=.1, batch_first=True) | |
| self.spatial = nn.ModuleList([TemporalBlock(dropout=.1) for _ in range(2)]) | |
| self.quarter_decoder = _Conv(256 + 128 + 128, 192) | |
| self.half_decoder = _Conv(192 + 64 + 64, 96) | |
| self.full_decoder = _Conv(96 + 23, 64) | |
| self.head = nn.Conv2d(64, 1, 1) | |
| nn.init.zeros_(self.head.weight) | |
| nn.init.zeros_(self.head.bias) | |
| def time_features(age, precision): | |
| return torch.stack([age / 120, torch.log1p(age.clamp_min(0)) / 5, | |
| torch.sin(age / 30), torch.cos(age / 30), | |
| (age < 1).to(age.dtype), torch.full_like(age, precision)], -1) | |
| def forward(self, inputs): | |
| context = inputs["same_day"] | |
| b, _, height, width = context.shape | |
| mtg = inputs["geo"] | |
| mtg_mask = mtg[:, :, 2:3].bool().expand_as(mtg[:, :, :2]) | |
| sentinel_offset = inputs["cutoff_offset"] | |
| specs = ( | |
| (inputs["s1"], inputs["s1_mask"], inputs["s1_age"] + sentinel_offset, None, 1.), | |
| (inputs["s2"], inputs["s2_mask"], inputs["s2_age"] + sentinel_offset, | |
| torch.cat([inputs["s2_quality"], inputs["s2_quality_valid"]], 2), 1.), | |
| (mtg[:, :, :2], mtg_mask, inputs["geo_age"], mtg[:, :, 2:3], 1.), | |
| (context[:, None, :2], context[:, None, 2:4].bool(), | |
| context.new_full((b, 1), .5), context[:, None, 4:6], 0.), | |
| ) | |
| features = [] | |
| half_skips = [] | |
| quarter_skips = [] | |
| valid_tokens = [] | |
| for sensor, (value, valid, age, quality, precision) in enumerate(specs): | |
| t = value.shape[1] | |
| order = torch.argsort(age, dim=1, descending=True, stable=True) | |
| indices = order[:, :, None, None, None] | |
| value = torch.gather(value, 1, indices.expand_as(value)) | |
| valid = torch.gather(valid, 1, indices.expand_as(valid)) | |
| if quality is not None: | |
| quality = torch.gather(quality, 1, indices.expand_as(quality)) | |
| age = torch.gather(age, 1, order) | |
| valid = valid.bool() & torch.isfinite(value) | |
| pieces = [torch.where(valid, value, 0), valid.to(value.dtype)] | |
| if quality is not None: | |
| pieces.append(quality) | |
| packed = torch.cat(pieces, 2).flatten(0, 1) | |
| if self.training: | |
| half, quarter, eighth = checkpoint(self.encoders[sensor], packed, use_reentrant=False) | |
| else: | |
| half, quarter, eighth = self.encoders[sensor](packed) | |
| hh, ww = eighth.shape[-2:] | |
| valid_map = F.adaptive_avg_pool2d(valid.any(2).float().flatten(0, 1)[:, None], (hh, ww)) | |
| present = valid_map.reshape(b, t, hh, ww) > 0 | |
| encoded = eighth.reshape(b, t, 256, hh, ww) | |
| time = self.time(self.time_features(age, precision))[:, :, :, None, None] | |
| encoded = encoded + self.sensor[sensor][None, None, :, None, None] + time | |
| features.append(encoded) | |
| valid_tokens.append(present) | |
| half_skips.append(half.reshape(b, t, 64, *half.shape[-2:])) | |
| quarter_skips.append(quarter.reshape(b, t, 128, *quarter.shape[-2:])) | |
| # Static land cover, prior S2 anchor and calendar are independent of labels. | |
| static_image = torch.cat([context[:, 21:39], inputs["anchor"], inputs["calendar"][:, :2]], 1) | |
| static_half, static_quarter, static_eighth = self.static(static_image) | |
| query = static_eighth + self.query[None, :, None, None] | |
| memory = torch.cat(features, 1) | |
| present = torch.cat(valid_tokens, 1) | |
| t = memory.shape[1] | |
| tokens = memory.permute(0, 3, 4, 1, 2).reshape(b * hh * ww, t, 256) | |
| valid = present.permute(0, 2, 3, 1).reshape(b * hh * ww, t) | |
| query = query.permute(0, 2, 3, 1).reshape(b * hh * ww, 1, 256) | |
| tokens = torch.cat([tokens, query], 1) | |
| absent = ~torch.cat([valid, torch.ones_like(valid[:, :1])], 1) | |
| for layer in self.temporal: | |
| tokens = checkpoint(layer, tokens, absent, use_reentrant=False) if self.training else layer(tokens, absent) | |
| # The final query is always valid, including completely missing observations. | |
| normalized = self.cross_norm(tokens) | |
| attended, weights = self.cross(normalized[:, -1:], normalized, normalized, | |
| key_padding_mask=absent, need_weights=True) | |
| target = tokens[:, -1:] + attended | |
| target = target.reshape(b, hh * ww, 256) | |
| yy, xx = torch.meshgrid(torch.linspace(-1, 1, hh, device=target.device), | |
| torch.linspace(-1, 1, ww, device=target.device), indexing="ij") | |
| frequencies = torch.arange(1, 65, device=target.device) * math.pi | |
| position = torch.cat([torch.sin(xx[..., None] * frequencies), torch.cos(xx[..., None] * frequencies), | |
| torch.sin(yy[..., None] * frequencies), torch.cos(yy[..., None] * frequencies)], -1) | |
| target = target + position.reshape(1, hh * ww, 256) | |
| for layer in self.spatial: | |
| target = checkpoint(layer, target, None, use_reentrant=False) if self.training else layer(target, None) | |
| target = target.transpose(1, 2).reshape(b, 256, hh, ww) | |
| temporal_weights = weights[:, 0, :t].reshape(b, hh, ww, t).permute(0, 3, 1, 2) | |
| temporal_weights = temporal_weights / temporal_weights.sum(1, keepdim=True).clamp_min(1e-6) | |
| def aggregate(skips): | |
| values = torch.cat(skips, 1) | |
| scale_weights = F.interpolate(temporal_weights, size=values.shape[-2:], mode="bilinear", align_corners=False) | |
| return (values * scale_weights[:, :, None]).sum(1) | |
| quarter = aggregate(quarter_skips) | |
| half = aggregate(half_skips) | |
| target = self.quarter_decoder(torch.cat([F.interpolate(target, size=quarter.shape[-2:], mode="bilinear", align_corners=False), | |
| quarter, static_quarter], 1)) | |
| target = self.half_decoder(torch.cat([F.interpolate(target, size=half.shape[-2:], mode="bilinear", align_corners=False), | |
| half, static_half], 1)) | |
| target = self.full_decoder(torch.cat([F.interpolate(target, size=(height, width), mode="bilinear", align_corners=False), | |
| static_image], 1)) | |
| return (inputs["anchor"][:, :1] + self.head(target)).clamp(-1, 1) | |