st_encoder_decoder.py
Spatio-Temporal encoder-decoder for Monthly Prediction. The main model class is SpatioTemporalModel.
CyclicMonthEmbedding(embed_dim=128, n_harmonics=6)
Bases: Module
Cyclical encoding of month using month-of-year as phse.
This module uses a Fourier base corresponding to the C12 cyclical symmetry group (month based phase representaton.)
Initialize monthly encoding
Args: embed_dim: Dimension of the embedding.The default is 128. Many vision transformers use embedding dimensions that are multiples of 64 (e.g., 64, 128, 256). This can be tuned. n_harmonics: number of harmonics to consider for the fourier basis. Can be modified, but the deafult value of 6 (sin/cos pairs, so 12 functions) represents a complete basis set for the C12 group which the months form.
Source code in climanet/st_encoder_decoder.py
forward(time_features)
Create month embedding for tokens
Source code in climanet/st_encoder_decoder.py
CyclicTimeEmbedding(embed_dim=128, include_cross=True)
Bases: Module
Cyclical Temporal encoding using day-of-year and hour-of-day values in combination sine and cosine functions
This module generates fixed (non-learnable) trigonometric temporal encodings for the temporal dimension using the cyclcial phase encoded day-of-year and hour-of-day values extracted from the datetime associated with the input. This represents a natural positional encoding on the temporal cycle related to the solar (tropical) year and the diurnal cycle.
The module uses fixed Fourier frequencies and mixed doy-hod terms to expand the cyclic encoding to the embedding dimension and capture time of day and day of year interactions. The returned encodings are intended to be added to embeddings of the input data by the caller. The module does not perform the additon.
Initialize temporal encodings
Args: embed_dim: Dimension of the embedding.The default is 128. Many vision transformers use embedding dimensions that are multiples of 64 (e.g., 64, 128, 256). This can be tuned. include_cross: bool, default True. Also Create phase_doy +/- phase_hod cross term emeddings
Source code in climanet/st_encoder_decoder.py
forward(time_features)
create encodings in of size embedding dimension
Args: time_features: (B, M, T, D) ; D is base_dim
Returns: emb_encode : (B,M,T, embed_dim)
Source code in climanet/st_encoder_decoder.py
GeoPositionScaleEmbedding(sh_dim=96, scale_dim=10, embed_dim=128)
Bases: Module
Sphere aware encoding of geographical position and patch (resolution) scales.
This module uses static precomputed spherical-harmonic-based geoposition encodings and scale encodings at the patch level to generate learned positonal embedding for patches. The static, precomputed geo position and scale features are created at the dataset level and passed to the model, together with patch data.
Geo position uses a sphere-aware patch area average of the PCA projection of real-valued spherical harmonics functions up to and including order L ( with dim PCA < (L+1)**2 ) at the resolution of the input data.
Patch scale embedding encodes, patch, scale, anisotropy, linear resolution, and effective harmonic cut-off.
These embeddings are concatenated with learnable vector valued gains and then projected to the required embedding dimension using a simple dense NN.
initialize geo-position and scale embeddings and projection
Args: sh_dim: int, Dimension of pca of spherical harmonics for embedding. defaults to 96 scale_dim: int, Dimension of patch scale feature embedding. default 10 embed_dim: int, Dimension of embeddings to be created. default 128
Source code in climanet/st_encoder_decoder.py
forward(sh_geo_pos, geo_scale_feat)
Create learned geo-position-and-scale embedding of desired dimension from pre-calculated patch level geo-position and patch scale embeddings
Args: sh_geo_pos: Tensor of dimension sh_dim. Patch level geo-position embedding using pca of spherical harmonics geo_scale_feat: Tensor of dimension scale_dim. Patch level patch-scale features Returns: geo_emb: Tensor of dimesnion embed_dim. Learned geo-position-and-scale embedding
Source code in climanet/st_encoder_decoder.py
MonthlyConvDecoder(embed_dim=128, patch_h=4, patch_w=4, hidden=128, overlap=1, dropout=0.0)
Bases: Module
Decoder to reconstruct 2D maps from patch tokens.
The MonthlyConvDecoder converts latent patch tokens back to pixel space: - Applies a 1*1 convolution to mix features on the patch grid. - Uses a transposed convolution (deconvolution) to upsample tokens to the original spatial resolution. - Applies a convolutional refinement block to smooth patch boundaries. - Applies a small convolutional head to produce the final single-channel output. - Optionally masks out land regions using a boolean mask.
Args: embed_dim: Dimension of the patch embedding.The default is 128. Many vision transformers use embedding dimensions that are multiples of 64 (e.g., 64, 128, 256). This can be tuned. patch_h: Patch height patch_w: Patch width hidden: Hidden dimension in the decoder for mixing channel features. The default is 128, which can be tuned. overlap: Overlap size for deconvolution. It creates smooth blending between adjacent upsampled patches. Default is 1, no overlap at edges. dropout: Dropout rate for regularization in the refinement block. Default is 0.0.
Source code in climanet/st_encoder_decoder.py
forward(latent, M, out_H, out_W, land_mask=None)
Reconstruct 2D maps from latent patch tokens. Args: latent: Tensor of shape (B, MHpWp, C) where C is the embedding dimension. M: Number of months (temporal patches) out_H: Target output height (must be divisible by patch_h) out_W: Target output width (must be divisible by patch_w) land_mask: Optional boolean tensor of shape (B, out_H, out_W). Values set to True will be masked out (set to 0) in the output (only ocean pixels exist). Returns: Tensor of shape (B, M, out_H, out_W) representing the monthly variable e.g. SST.
Source code in climanet/st_encoder_decoder.py
SpatialTransformer(embed_dim=128, depth=2, num_heads=4, mlp_ratio=4.0, dropout=0.0)
Bases: Module
Spatial Transformer for spatial feature mixing.
This module applies a standard Transformer encoder to a sequence of spatial tokens (patch embeddings), allowing information to be mixed across all spatial locations.
Key points: - Uses multi-head self-attention and feedforward layers. - Designed to operate on flattened spatial tokens.
Initialize the spatial transformer. Args: embed_dim: Dimension of the embedding. Default is 128. The embedding dimensions are multiples of 64 (e.g., 64, 128, 256). This can be tuned. depth: Number of transformer encoder layers. Default is 2. This can be increased for more complex spatial mixing. num_heads: Number of attention heads in each layer. Default is 4. When embed_dim is 128, 4 heads is a common choice. mlp_ratio: Ratio of feedforward hidden dimension to embed_dim. Default is 4.0. dropout: Dropout rate applied to attention and feedforward layers. Default is 0.0.
Source code in climanet/st_encoder_decoder.py
forward(x)
Forward pass of the spatial transformer. Args: x: Input tensor of shape (B, N, C), where N = number of spatial tokens (H'*W') and C = embedding dimension Returns: Tensor of shape (B, N, C) with spatially mixed features across patches
Source code in climanet/st_encoder_decoder.py
SpatioTemporalModel(in_chans=1, embed_dim=128, patch_size=(1, 4, 4), hidden=256, overlap=1, spatial_depth=2, spatial_heads=4, dropout=0.0, sh_dim=96, scale_dim=10, use_checkpoint=True)
Bases: Module
Spatio-Temporal Model for Monthly Prediction.
Processes daily data in a video-style format with shape (B, C, T, H, W): B: batch size C: number of channels (e.g., 1 for SST, can include additional channels like masks) T: temporal dimension (number of days, e.g., 31 for a month) H: spatial height W: spatial width
The model pipeline: 1. Encode spatio-temporal patches using VideoEncoder. 2. Aggregate temporal information for each spatial patch via TemporalAttentionAggregator. 3. Add 2D spatial positional encodings and mix spatial features with SpatialTransformer. 4. Decode aggregated tokens into a full-resolution 2D map using MonthlyConvDecoder.
Output: - Reconstructed monthly (SST) map of shape (B, M, H, W)
Initialize the Spatio-Temporal Model.
Args: in_chans: Number of input channels (e.g., 1 for SST, additional channels possible) embed_dim: Dimension of the patch embedding patch_size: Tuple of (T, H, W) patch sizes for temporal and spatial patching hidden: Hidden dimension used in the decoder overlap: Overlap for deconvolution in the decoder max_H: Maximum spatial height for 2D positional encoding max_W: Maximum spatial width for 2D positional encoding spatial_depth: Number of layers in the spatial Transformer spatial_heads: Number of attention heads in the spatial Transformer dropout: Dropout rate for regularization in various components. Increase it if there is overfitting. sh_dim: Dimension of spherical harmonics based pca of geo-position scale_dim: Dimension of patch-level patch-scale features
Source code in climanet/st_encoder_decoder.py
forward(input_data, daily_mask, daily_timef, land_mask_patch, geo_pos_embedding_patch, scale_feature_patch, padded_days_mask=None)
Forward pass of the Spatio-Temporal model.
Args: input_data: Tensor of shape (B, C, M, T, H, W) containing daily data, where C is the number of channels (e.g., 1 for SST) daily_mask: Boolean tensor of same shape as input_data indicating missing values daily_timef: Tensor of shape (B, M, T, 2) containing the cyclically phase encoded day-of-year and hour-of-day information for the daily data land_mask_patch: Boolean tensor of shape (B, H, W) to mask land areas in the output padded_days_mask: Optional boolean tensor of shape (B, M, T) indicating which day tokens are padded (True for padded tokens). Used to mask out padded tokens in temporal attention. Returns: monthly_pred: Tensor of shape (B, M, H, W) representing the reconstructed monthly map
Source code in climanet/st_encoder_decoder.py
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 | |
TemporalAttentionAggregator(embed_dim=128, dropout=0.0, chunk_size=1024)
Bases: Module
Temporal attention-based aggregator.
This module aggregates temporal information for each spatial patch by applying attention across the temporal dimension. It consists of two main steps: 1. Day attention: For each month, it computes attention weights across the temporal tokens (days) and performs a weighted sum to get one token per spatial location for each month. 2. Cross-month mixing: After temporal aggregation, it applies a Transformer encoder layer to mix information across months at each spatial location.
For each spatial location, the day attention allows the model to learn which days are most important for predicting the monthly average, while the cross-month mixing allows the model to learn interactions between different months.
Initialize the temporal attention aggregator.
Args: embed_dim: Dimension of the embedding. The default is 128. Many vision transformers use embedding dimensions that are multiples of 64 (e.g., 64, 128, 256). This can be tuned. dropout: Dropout rate for regularization in the day scorer and cross-month mixing. Default is 0.0. Increase it if there is overfitting. chunk_size: Number of chunks to process for memory efficiency. This is related to PyTorch limitation in PyTorch's efficient attention kernels. Default is 1024.
Source code in climanet/st_encoder_decoder.py
forward(x, M, time_features, padded_days_mask=None)
Args: x: (B, M, T, H, W, C) containing spatio-temporal tokens, where C is the embedding dimension. M: number of months T: number of temporal tokens per month after temporal patching (Tp) H: spatial height after spatial patching W: spatial width after spatial patching time_features: (B,M,T,3) containing cyclically phase encoded MOY, DOY and HOD padded_days_mask: Optional boolean tensor of shape (B, M, T), bool, True indicating which day tokens are padded (because some months have fewer days). This is used to mask out padded tokens in attention computation. Returns: Tensor of shape (B, M, H*W, C) with one temporally aggregated, where C is the embedding dimension.
Source code in climanet/st_encoder_decoder.py
VideoEncoder(in_chans=1, embed_dim=128, patch_size=(1, 4, 4))
Bases: Module
Video Encoder with spatio-temporal patch embedding.
This module converts an input video into a sequence of non-overlapping spatio-temporal patch embeddings using a 3D convolution.
Masking is handled by: - zeroing out masked (missing) pixels - concatenating a validity mask as an additional input channel
The convolution uses kernel size and stride equal to the patch size. The output is a sequence of patch embeddings, as used in VideoMAE: https://arxiv.org/abs/2203.12602
Args: in_chans: Number of input channels (1 for SST) embed_dim: Dimension of the patch embedding. The default is 128. Many vision transformers use embedding dimensions that are multiples of 64 (e.g., 64, 128, 256). This can be tuned. patch_size: Tuple of (T, H, W) patch size. Default is (1, 4, 4).
Source code in climanet/st_encoder_decoder.py
forward(x, mask)
Forward pass with masking support via an additional validity channel. Args: x: Input video tensor of shape (B, C, T, H, W) mask: Boolean mask tensor of shape (B, C, T, H, W), where True indicates masked pixels
Returns: Embedded patches of shape (B, N_patches, embed_dim) Notes: - Masked pixels are zeroed out before patch embedding - A validity mask (1 = observed, 0 = missing) is concatenated as an additional input channel