_layers.py 23.7 KB
Newer Older
Boris Bonev's avatar
Boris Bonev committed
1
2
3
4
# coding=utf-8

# SPDX-FileCopyrightText: Copyright (c) 2022 The torch-harmonics Authors. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
Boris Bonev's avatar
Boris Bonev committed
5
#
Boris Bonev's avatar
Boris Bonev committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

Boris Bonev's avatar
Boris Bonev committed
32
33
34
import abc
import math

Boris Bonev's avatar
Boris Bonev committed
35
36
37
import torch
import torch.nn as nn
import torch.fft
38
from torch.utils.checkpoint import checkpoint
Boris Bonev's avatar
Boris Bonev committed
39

Boris Bonev's avatar
Boris Bonev committed
40
41
from torch_harmonics import InverseRealSHT

Boris Bonev's avatar
Boris Bonev committed
42
43

def _no_grad_trunc_normal_(tensor, mean, std, a, b):
apaaris's avatar
apaaris committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    """
    Internal function to fill tensor with truncated normal distribution values.
    
    Parameters
    -----------
    tensor : torch.Tensor
        Tensor to fill with values
    mean : float
        Mean of the normal distribution
    std : float
        Standard deviation of the normal distribution
    a : float
        Lower bound for truncation
    b : float
        Upper bound for truncation
        
    Returns
    -------
    torch.Tensor
        The filled tensor
    """
Boris Bonev's avatar
Boris Bonev committed
65
66
67
68
    # Cut & paste from PyTorch official master until it's in a few official releases - RW
    # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
    def norm_cdf(x):
        # Computes standard normal cumulative distribution function
Boris Bonev's avatar
Boris Bonev committed
69
        return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
Boris Bonev's avatar
Boris Bonev committed
70

Boris Bonev's avatar
Boris Bonev committed
71
    if (mean < a - 2 * std) or (mean > b + 2 * std):
Boris Bonev's avatar
Boris Bonev committed
72
        warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " "The distribution of values may be incorrect.", stacklevel=2)
Boris Bonev's avatar
Boris Bonev committed
73

Boris Bonev's avatar
Boris Bonev committed
74
75
76
77
78
79
    with torch.no_grad():
        # Values are generated by using a truncated uniform distribution and
        # then using the inverse CDF for the normal distribution.
        # Get upper and lower cdf values
        l = norm_cdf((a - mean) / std)
        u = norm_cdf((b - mean) / std)
Boris Bonev's avatar
Boris Bonev committed
80

Boris Bonev's avatar
Boris Bonev committed
81
82
83
        # Uniformly fill tensor with values from [l, u], then translate to
        # [2l-1, 2u-1].
        tensor.uniform_(2 * l - 1, 2 * u - 1)
Boris Bonev's avatar
Boris Bonev committed
84

Boris Bonev's avatar
Boris Bonev committed
85
86
87
        # Use inverse cdf transform for normal distribution to get truncated
        # standard normal
        tensor.erfinv_()
Boris Bonev's avatar
Boris Bonev committed
88

Boris Bonev's avatar
Boris Bonev committed
89
        # Transform to proper mean, std
Boris Bonev's avatar
Boris Bonev committed
90
        tensor.mul_(std * math.sqrt(2.0))
Boris Bonev's avatar
Boris Bonev committed
91
        tensor.add_(mean)
Boris Bonev's avatar
Boris Bonev committed
92

Boris Bonev's avatar
Boris Bonev committed
93
94
95
        # Clamp to ensure it's in the proper range
        tensor.clamp_(min=a, max=b)
        return tensor
Boris Bonev's avatar
Boris Bonev committed
96
97


Boris Bonev's avatar
Boris Bonev committed
98
def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0):
Boris Bonev's avatar
Boris Bonev committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    r"""Fills the input Tensor with values drawn from a truncated
    normal distribution. The values are effectively drawn from the
    normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
    with values outside :math:`[a, b]` redrawn until they are within
    the bounds. The method used for generating the random values works
    best when :math:`a \leq \text{mean} \leq b`.
    Args:
    tensor: an n-dimensional `torch.Tensor`
    mean: the mean of the normal distribution
    std: the standard deviation of the normal distribution
    a: the minimum cutoff value
    b: the maximum cutoff value
    Examples:
    >>> w = torch.empty(3, 5)
    >>> nn.init.trunc_normal_(w)
    """
    return _no_grad_trunc_normal_(tensor, mean, std, a, b)


@torch.jit.script
Boris Bonev's avatar
Boris Bonev committed
119
def drop_path(x: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
apaaris's avatar
apaaris committed
120
121
122
    """
    Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
    
Boris Bonev's avatar
Boris Bonev committed
123
124
125
126
127
    This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
    the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
    See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
    changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
    'survival rate' as the argument.
apaaris's avatar
apaaris committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    
    Parameters
    -----------
    x : torch.Tensor
        Input tensor
    drop_prob : float, optional
        Dropout probability, by default 0.0
    training : bool, optional
        Whether in training mode, by default False
        
    Returns
    -------
    torch.Tensor
        Output tensor with potential drop path applied
Boris Bonev's avatar
Boris Bonev committed
142
    """
Boris Bonev's avatar
Boris Bonev committed
143
    if drop_prob == 0.0 or not training:
Boris Bonev's avatar
Boris Bonev committed
144
        return x
Boris Bonev's avatar
Boris Bonev committed
145
    keep_prob = 1.0 - drop_prob
Boris Bonev's avatar
Boris Bonev committed
146
147
148
149
150
151
152
153
    shape = (x.shape[0],) + (1,) * (x.ndim - 1)  # work with diff dim tensors, not just 2d ConvNets
    random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
    random_tensor.floor_()  # binarize
    output = x.div(keep_prob) * random_tensor
    return output


class DropPath(nn.Module):
Boris Bonev's avatar
Boris Bonev committed
154
155
    """Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks)."""

Boris Bonev's avatar
Boris Bonev committed
156
    def __init__(self, drop_prob=None):
apaaris's avatar
apaaris committed
157
158
159
160
161
162
163
164
        """
        Initialize DropPath module.
        
        Parameters
        -----------
        drop_prob : float, optional
            Dropout probability, by default None
        """
Boris Bonev's avatar
Boris Bonev committed
165
166
        super(DropPath, self).__init__()
        self.drop_prob = drop_prob
Boris Bonev's avatar
Boris Bonev committed
167

Boris Bonev's avatar
Boris Bonev committed
168
    def forward(self, x):
apaaris's avatar
apaaris committed
169
170
171
172
173
174
175
176
177
178
179
180
181
        """
        Forward pass with drop path.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
            
        Returns
        -------
        torch.Tensor
            Output tensor with potential drop path applied
        """
Boris Bonev's avatar
Boris Bonev committed
182
        return drop_path(x, self.drop_prob, self.training)
Boris Bonev's avatar
Boris Bonev committed
183

Boris Bonev's avatar
Boris Bonev committed
184
185

class PatchEmbed(nn.Module):
apaaris's avatar
apaaris committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    """
    Patch embedding layer for vision transformers.
    
    Parameters
    -----------
    img_size : tuple, optional
        Input image size (height, width), by default (224, 224)
    patch_size : tuple, optional
        Patch size (height, width), by default (16, 16)
    in_chans : int, optional
        Number of input channels, by default 3
    embed_dim : int, optional
        Embedding dimension, by default 768
    """
    
Boris Bonev's avatar
Boris Bonev committed
201
202
203
204
205
206
207
208
209
210
211
212
    def __init__(self, img_size=(224, 224), patch_size=(16, 16), in_chans=3, embed_dim=768):
        super(PatchEmbed, self).__init__()
        self.red_img_size = ((img_size[0] // patch_size[0]), (img_size[1] // patch_size[1]))
        num_patches = self.red_img_size[0] * self.red_img_size[1]
        self.img_size = img_size
        self.patch_size = patch_size
        self.num_patches = num_patches
        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=True)
        self.proj.weight.is_shared_mp = ["spatial"]
        self.proj.bias.is_shared_mp = ["spatial"]

    def forward(self, x):
apaaris's avatar
apaaris committed
213
214
215
216
217
218
219
220
221
222
223
224
225
        """
        Forward pass of patch embedding.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor with shape (batch, channels, height, width)
            
        Returns
        -------
        torch.Tensor
            Embedded patches with shape (batch, embed_dim, num_patches)
        """
Boris Bonev's avatar
Boris Bonev committed
226
227
228
229
230
231
232
233
        # gather input
        B, C, H, W = x.shape
        assert H == self.img_size[0] and W == self.img_size[1], f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
        # new: B, C, H*W
        x = self.proj(x).flatten(2)
        return x


Boris Bonev's avatar
Boris Bonev committed
234
class MLP(nn.Module):
apaaris's avatar
apaaris committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    """
    Multi-layer perceptron with optional checkpointing.
    
    Parameters
    -----------
    in_features : int
        Number of input features
    hidden_features : int, optional
        Number of hidden features, by default None (same as in_features)
    out_features : int, optional
        Number of output features, by default None (same as in_features)
    act_layer : nn.Module, optional
        Activation layer, by default nn.ReLU
    output_bias : bool, optional
        Whether to use bias in output layer, by default False
    drop_rate : float, optional
        Dropout rate, by default 0.0
    checkpointing : bool, optional
        Whether to use gradient checkpointing, by default False
    gain : float, optional
        Gain factor for output initialization, by default 1.0
    """
    
Boris Bonev's avatar
Boris Bonev committed
258
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.ReLU, output_bias=False, drop_rate=0.0, checkpointing=False, gain=1.0):
Boris Bonev's avatar
Boris Bonev committed
259
260
261
262
263
        super(MLP, self).__init__()
        self.checkpointing = checkpointing
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features

264
        # Fist dense layer
Boris Bonev's avatar
Boris Bonev committed
265
        fc1 = nn.Conv2d(in_features, hidden_features, 1, bias=True)
266
267
        # initialize the weights correctly
        scale = math.sqrt(2.0 / in_features)
Boris Bonev's avatar
Boris Bonev committed
268
        nn.init.normal_(fc1.weight, mean=0.0, std=scale)
269
270
271
272
        if fc1.bias is not None:
            nn.init.constant_(fc1.bias, 0.0)

        # activation
Boris Bonev's avatar
Boris Bonev committed
273
        act = act_layer()
274
275
276
277
278

        # output layer
        fc2 = nn.Conv2d(hidden_features, out_features, 1, bias=output_bias)
        # gain factor for the output determines the scaling of the output init
        scale = math.sqrt(gain / hidden_features)
Boris Bonev's avatar
Boris Bonev committed
279
        nn.init.normal_(fc2.weight, mean=0.0, std=scale)
280
281
282
        if fc2.bias is not None:
            nn.init.constant_(fc2.bias, 0.0)

Boris Bonev's avatar
Boris Bonev committed
283
        if drop_rate > 0.0:
284
            drop = nn.Dropout2d(drop_rate)
Boris Bonev's avatar
Boris Bonev committed
285
286
287
            self.fwd = nn.Sequential(fc1, act, drop, fc2, drop)
        else:
            self.fwd = nn.Sequential(fc1, act, fc2)
Boris Bonev's avatar
Boris Bonev committed
288

Boris Bonev's avatar
Boris Bonev committed
289
290
    @torch.jit.ignore
    def checkpoint_forward(self, x):
apaaris's avatar
apaaris committed
291
292
293
294
295
296
297
298
299
300
301
302
303
        """
        Forward pass with gradient checkpointing.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
            
        Returns
        -------
        torch.Tensor
            Output tensor
        """
Boris Bonev's avatar
Boris Bonev committed
304
        return checkpoint(self.fwd, x)
Boris Bonev's avatar
Boris Bonev committed
305

Boris Bonev's avatar
Boris Bonev committed
306
    def forward(self, x):
apaaris's avatar
apaaris committed
307
308
309
310
311
312
313
314
315
316
317
318
319
        """
        Forward pass of the MLP.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
            
        Returns
        -------
        torch.Tensor
            Output tensor
        """
Boris Bonev's avatar
Boris Bonev committed
320
321
322
323
324
        if self.checkpointing:
            return self.checkpoint_forward(x)
        else:
            return self.fwd(x)

Boris Bonev's avatar
Boris Bonev committed
325

Boris Bonev's avatar
Boris Bonev committed
326
327
328
329
class RealFFT2(nn.Module):
    """
    Helper routine to wrap FFT similarly to the SHT
    """
Boris Bonev's avatar
Boris Bonev committed
330
331

    def __init__(self, nlat, nlon, lmax=None, mmax=None):
apaaris's avatar
apaaris committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
        """
        Initialize RealFFT2 module.
        
        Parameters
        -----------
        nlat : int
            Number of latitude points
        nlon : int
            Number of longitude points
        lmax : int, optional
            Maximum l mode, by default None (same as nlat)
        mmax : int, optional
            Maximum m mode, by default None (nlon // 2 + 1)
        """
Boris Bonev's avatar
Boris Bonev committed
346
347
348
349
350
351
352
353
        super(RealFFT2, self).__init__()

        self.nlat = nlat
        self.nlon = nlon
        self.lmax = lmax or self.nlat
        self.mmax = mmax or self.nlon // 2 + 1

    def forward(self, x):
apaaris's avatar
apaaris committed
354
355
356
357
358
359
360
361
362
363
364
365
366
        """
        Forward pass of RealFFT2.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor with shape (batch, channels, nlat, nlon)
            
        Returns
        -------
        torch.Tensor
            Output tensor with shape (batch, channels, nlat, mmax)
        """
Boris Bonev's avatar
Boris Bonev committed
367
        y = torch.fft.rfft2(x, dim=(-2, -1), norm="ortho")
Boris Bonev's avatar
Boris Bonev committed
368
        y = torch.cat((y[..., : math.ceil(self.lmax / 2), : self.mmax], y[..., -math.floor(self.lmax / 2) :, : self.mmax]), dim=-2)
Boris Bonev's avatar
Boris Bonev committed
369
370
        return y

Boris Bonev's avatar
Boris Bonev committed
371

Boris Bonev's avatar
Boris Bonev committed
372
373
class InverseRealFFT2(nn.Module):
    """
apaaris's avatar
apaaris committed
374
    Helper routine to wrap inverse FFT similarly to the SHT
Boris Bonev's avatar
Boris Bonev committed
375
    """
Boris Bonev's avatar
Boris Bonev committed
376
377

    def __init__(self, nlat, nlon, lmax=None, mmax=None):
apaaris's avatar
apaaris committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
        """
        Initialize InverseRealFFT2 module.
        
        Parameters
        -----------
        nlat : int
            Number of latitude points
        nlon : int
            Number of longitude points
        lmax : int, optional
            Maximum l mode, by default None (same as nlat)
        mmax : int, optional
            Maximum m mode, by default None (nlon // 2 + 1)
        """
Boris Bonev's avatar
Boris Bonev committed
392
393
394
395
396
397
398
399
        super(InverseRealFFT2, self).__init__()

        self.nlat = nlat
        self.nlon = nlon
        self.lmax = lmax or self.nlat
        self.mmax = mmax or self.nlon // 2 + 1

    def forward(self, x):
apaaris's avatar
apaaris committed
400
401
402
403
404
405
406
407
408
409
410
411
412
        """
        Forward pass of InverseRealFFT2.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor with shape (batch, channels, nlat, mmax)
            
        Returns
        -------
        torch.Tensor
            Output tensor with shape (batch, channels, nlat, nlon)
        """
Boris Bonev's avatar
Boris Bonev committed
413
        return torch.fft.irfft2(x, dim=(-2, -1), s=(self.nlat, self.nlon), norm="ortho")
Boris Bonev's avatar
Boris Bonev committed
414

Boris Bonev's avatar
Boris Bonev committed
415
416
417
418
419
420
421

class LayerNorm(nn.Module):
    """
    Wrapper class that moves the channel dimension to the end
    """

    def __init__(self, in_channels, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None):
apaaris's avatar
apaaris committed
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
        """
        Initialize LayerNorm module.
        
        Parameters
        -----------
        in_channels : int
            Number of input channels
        eps : float, optional
            Epsilon for numerical stability, by default 1e-05
        elementwise_affine : bool, optional
            Whether to use learnable affine parameters, by default True
        bias : bool, optional
            Whether to use bias, by default True
        device : torch.device, optional
            Device to place the module on, by default None
        dtype : torch.dtype, optional
            Data type, by default None
        """
Boris Bonev's avatar
Boris Bonev committed
440
441
442
443
444
445
446
        super().__init__()

        self.channel_dim = -3

        self.norm = nn.LayerNorm(normalized_shape=in_channels, eps=1e-6, elementwise_affine=elementwise_affine, bias=bias, device=device, dtype=dtype)

    def forward(self, x):
apaaris's avatar
apaaris committed
447
448
449
450
451
452
453
454
455
456
457
458
459
        """
        Forward pass of LayerNorm.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
            
        Returns
        -------
        torch.Tensor
            Normalized tensor
        """
Boris Bonev's avatar
Boris Bonev committed
460
461
462
        return self.norm(x.transpose(self.channel_dim, -1)).transpose(-1, self.channel_dim)


Boris Bonev's avatar
Boris Bonev committed
463
464
class SpectralConvS2(nn.Module):
    """
apaaris's avatar
apaaris committed
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
    Spectral convolution layer for spherical data.
    
    Parameters
    -----------
    forward_transform : nn.Module
        Forward transform (e.g., RealSHT)
    inverse_transform : nn.Module
        Inverse transform (e.g., InverseRealSHT)
    in_channels : int
        Number of input channels
    out_channels : int
        Number of output channels
    gain : float, optional
        Gain factor for weight initialization, by default 2.0
    operator_type : str, optional
        Type of spectral operator, by default "driscoll-healy"
    lr_scale_exponent : int, optional
        Learning rate scale exponent, by default 0
    bias : bool, optional
        Whether to use bias, by default False
Boris Bonev's avatar
Boris Bonev committed
485
    """
apaaris's avatar
apaaris committed
486
    
Boris Bonev's avatar
Boris Bonev committed
487
    def __init__(self, forward_transform, inverse_transform, in_channels, out_channels, gain=2.0, operator_type="driscoll-healy", lr_scale_exponent=0, bias=False):
apaaris's avatar
apaaris committed
488
        super(SpectralConvS2, self).__init__()
Boris Bonev's avatar
Boris Bonev committed
489
490
491

        self.forward_transform = forward_transform
        self.inverse_transform = inverse_transform
apaaris's avatar
apaaris committed
492
493
        self.in_channels = in_channels
        self.out_channels = out_channels
Boris Bonev's avatar
Boris Bonev committed
494
        self.operator_type = operator_type
apaaris's avatar
apaaris committed
495
        self.lr_scale_exponent = lr_scale_exponent
Boris Bonev's avatar
Boris Bonev committed
496

apaaris's avatar
apaaris committed
497
        # initialize the weights
498
        scale = math.sqrt(gain / in_channels)
apaaris's avatar
apaaris committed
499
500
        self.weight = nn.Parameter(scale * torch.randn(out_channels, in_channels, dtype=torch.cfloat))

Boris Bonev's avatar
Boris Bonev committed
501
        if bias:
apaaris's avatar
apaaris committed
502
503
504
            self.bias = nn.Parameter(torch.zeros(out_channels, dtype=torch.cfloat))
        else:
            self.bias = None
Boris Bonev's avatar
Boris Bonev committed
505
506

    def forward(self, x):
apaaris's avatar
apaaris committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
        """
        Forward pass of spectral convolution.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
            
        Returns
        -------
        torch.Tensor
            Output tensor after spectral convolution
        """
        # apply forward transform
        x = self.forward_transform(x)

        # apply spectral convolution
        x = torch.einsum("bilm,oim->bolm", x, self.weight)

        # apply inverse transform
        x = self.inverse_transform(x)

        # add bias if present
        if self.bias is not None:
            x = x + self.bias.view(1, -1, 1, 1)
Boris Bonev's avatar
Boris Bonev committed
532

apaaris's avatar
apaaris committed
533
        return x
Boris Bonev's avatar
Boris Bonev committed
534

Boris Bonev's avatar
Boris Bonev committed
535
536
537

class PositionEmbedding(nn.Module, metaclass=abc.ABCMeta):
    """
apaaris's avatar
apaaris committed
538
539
540
541
542
543
544
545
546
547
    Abstract base class for position embeddings on spherical data.
    
    Parameters
    -----------
    img_shape : tuple, optional
        Image shape (height, width), by default (480, 960)
    grid : str, optional
        Grid type, by default "equiangular"
    num_chans : int, optional
        Number of channels, by default 1
Boris Bonev's avatar
Boris Bonev committed
548
    """
apaaris's avatar
apaaris committed
549
    
Boris Bonev's avatar
Boris Bonev committed
550
    def __init__(self, img_shape=(480, 960), grid="equiangular", num_chans=1):
apaaris's avatar
apaaris committed
551
        super(PositionEmbedding, self).__init__()
Boris Bonev's avatar
Boris Bonev committed
552
        self.img_shape = img_shape
apaaris's avatar
apaaris committed
553
        self.grid = grid
Boris Bonev's avatar
Boris Bonev committed
554
555
        self.num_chans = num_chans

apaaris's avatar
apaaris committed
556
    @abc.abstractmethod
Boris Bonev's avatar
Boris Bonev committed
557
    def forward(self, x: torch.Tensor):
apaaris's avatar
apaaris committed
558
559
560
561
562
563
564
565
566
        """
        Abstract forward method for position embedding.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
        """
        pass
Boris Bonev's avatar
Boris Bonev committed
567
568
569
570


class SequencePositionEmbedding(PositionEmbedding):
    """
apaaris's avatar
apaaris committed
571
572
573
574
575
576
577
578
579
580
581
582
583
    Sequence-based position embedding for spherical data.
    
    This module adds position embeddings based on the sequence of latitude and longitude
    coordinates, providing spatial context to the model.
    
    Parameters
    -----------
    img_shape : tuple, optional
        Image shape (height, width), by default (480, 960)
    grid : str, optional
        Grid type, by default "equiangular"
    num_chans : int, optional
        Number of channels, by default 1
Boris Bonev's avatar
Boris Bonev committed
584
585
586
    """

    def __init__(self, img_shape=(480, 960), grid="equiangular", num_chans=1):
apaaris's avatar
apaaris committed
587
        super(SequencePositionEmbedding, self).__init__(img_shape=img_shape, grid=grid, num_chans=num_chans)
Boris Bonev's avatar
Boris Bonev committed
588

apaaris's avatar
apaaris committed
589
590
591
592
        # create position embeddings
        pos_embed = torch.zeros(1, num_chans, img_shape[0], img_shape[1])
        nn.init.trunc_normal_(pos_embed, std=0.02)
        self.register_buffer("pos_embed", pos_embed)
Boris Bonev's avatar
Boris Bonev committed
593

apaaris's avatar
apaaris committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
    def forward(self, x: torch.Tensor):
        """
        Forward pass of sequence position embedding.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
            
        Returns
        -------
        torch.Tensor
            Tensor with position embeddings added
        """
        return x + self.pos_embed
Boris Bonev's avatar
Boris Bonev committed
609
610
611


class SpectralPositionEmbedding(PositionEmbedding):
apaaris's avatar
apaaris committed
612
613
614
615
616
617
618
619
620
621
622
623
624
625
    r"""
    Spectral position embedding for spherical data.
    
    This module adds position embeddings in the spectral domain using spherical harmonics,
    providing spectral context to the model.
    
    Parameters
    -----------
    img_shape : tuple, optional
        Image shape (height, width), by default (480, 960)
    grid : str, optional
        Grid type, by default "equiangular"
    num_chans : int, optional
        Number of channels, by default 1
Boris Bonev's avatar
Boris Bonev committed
626
627
628
    """

    def __init__(self, img_shape=(480, 960), grid="equiangular", num_chans=1):
apaaris's avatar
apaaris committed
629
        super(SpectralPositionEmbedding, self).__init__(img_shape=img_shape, grid=grid, num_chans=num_chans)
Boris Bonev's avatar
Boris Bonev committed
630

apaaris's avatar
apaaris committed
631
632
633
634
635
        # create spectral position embeddings
        pos_embed = torch.zeros(1, num_chans, img_shape[0], img_shape[1] // 2 + 1, dtype=torch.cfloat)
        nn.init.trunc_normal_(pos_embed.real, std=0.02)
        nn.init.trunc_normal_(pos_embed.imag, std=0.02)
        self.register_buffer("pos_embed", pos_embed)
Boris Bonev's avatar
Boris Bonev committed
636

apaaris's avatar
apaaris committed
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
    def forward(self, x: torch.Tensor):
        """
        Forward pass of spectral position embedding.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
            
        Returns
        -------
        torch.Tensor
            Tensor with spectral position embeddings added
        """
        return x + self.pos_embed
Boris Bonev's avatar
Boris Bonev committed
652
653
654


class LearnablePositionEmbedding(PositionEmbedding):
apaaris's avatar
apaaris committed
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
    r"""
    Learnable position embedding for spherical data.
    
    This module adds learnable position embeddings that are optimized during training,
    allowing the model to learn optimal spatial representations.
    
    Parameters
    -----------
    img_shape : tuple, optional
        Image shape (height, width), by default (480, 960)
    grid : str, optional
        Grid type, by default "equiangular"
    num_chans : int, optional
        Number of channels, by default 1
    embed_type : str, optional
        Embedding type ("lat", "lon", or "both"), by default "lat"
Boris Bonev's avatar
Boris Bonev committed
671
672
673
    """

    def __init__(self, img_shape=(480, 960), grid="equiangular", num_chans=1, embed_type="lat"):
apaaris's avatar
apaaris committed
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        super(LearnablePositionEmbedding, self).__init__(img_shape=img_shape, grid=grid, num_chans=num_chans)

        self.embed_type = embed_type

        if embed_type == "lat":
            # latitude embedding
            pos_embed = nn.Parameter(torch.zeros(1, num_chans, img_shape[0], 1))
            nn.init.trunc_normal_(pos_embed, std=0.02)
            self.register_parameter("pos_embed", pos_embed)
        elif embed_type == "lon":
            # longitude embedding
            pos_embed = nn.Parameter(torch.zeros(1, num_chans, 1, img_shape[1]))
            nn.init.trunc_normal_(pos_embed, std=0.02)
            self.register_parameter("pos_embed", pos_embed)
        elif embed_type == "latlon":
            # full lat-lon embedding
            pos_embed = nn.Parameter(torch.zeros(1, num_chans, img_shape[0], img_shape[1]))
            nn.init.trunc_normal_(pos_embed, std=0.02)
            self.register_parameter("pos_embed", pos_embed)
Boris Bonev's avatar
Boris Bonev committed
693
        else:
apaaris's avatar
apaaris committed
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
            raise ValueError(f"Unknown embedding type {embed_type}")

    def forward(self, x: torch.Tensor):
        """
        Forward pass of learnable position embedding.
        
        Parameters
        -----------
        x : torch.Tensor
            Input tensor
            
        Returns
        -------
        torch.Tensor
            Tensor with learnable position embeddings added
        """
        return x + self.pos_embed
Boris Bonev's avatar
Boris Bonev committed
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734

# class SpiralPositionEmbedding(PositionEmbedding):
#     """
#     Returns position embeddings on the torus
#     """

#     def __init__(self, img_shape=(480, 960), grid="equiangular", num_chans=1):

#         super().__init__(img_shape=img_shape, grid=grid, num_chans=num_chans)

#         with torch.no_grad():

#             # alternating custom position embeddings
#             lats, _ = _precompute_latitudes(img_shape[0], grid=grid)
#             lats = lats.reshape(-1, 1)
#             lons = torch.linspace(0, 2 * math.pi, img_shape[1] + 1)[:-1]
#             lons = lons.reshape(1, -1)

#             # channel index
#             k = torch.arange(self.num_chans).reshape(1, -1, 1, 1)
#             pos_embed = torch.where(k % 2 == 0, torch.sin(k * (lons + lats)), torch.cos(k * (lons - lats)))

#         # register tensor
#         self.register_buffer("position_embeddings", pos_embed.float())