sfno.py 21.9 KB
Newer Older
Boris Bonev's avatar
Boris Bonev committed
1
2
3
4
5
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
32
33
34
35
36
# coding=utf-8

# SPDX-FileCopyrightText: Copyright (c) 2022 The torch-harmonics Authors. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# 
# 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.
#

import torch
import torch.nn as nn

from torch_harmonics import *

37
from .layers import *
Boris Bonev's avatar
Boris Bonev committed
38

Srikumar Sastry's avatar
Srikumar Sastry committed
39
40
from functools import partial

Boris Bonev's avatar
Boris Bonev committed
41
42
43
44
45
46
47
48
49
50
class SpectralFilterLayer(nn.Module):
    """
    Fourier layer. Contains the convolution part of the FNO/SFNO
    """

    def __init__(
        self,
        forward_transform,
        inverse_transform,
        embed_dim,
Boris Bonev's avatar
Boris Bonev committed
51
52
        filter_type = "non-linear",
        operator_type = "diagonal",
Boris Bonev's avatar
Boris Bonev committed
53
54
55
        sparsity_threshold = 0.0,
        use_complex_kernels = True,
        hidden_size_factor = 2,
Boris Bonev's avatar
Boris Bonev committed
56
        lr_scale_exponent = 0,
Boris Bonev's avatar
Boris Bonev committed
57
58
59
        factorization = None,
        separable = False,
        rank = 1e-2,
Boris Bonev's avatar
Boris Bonev committed
60
        complex_activation = "real",
Boris Bonev's avatar
Boris Bonev committed
61
62
63
64
        spectral_layers = 1,
        drop_rate = 0):
        super(SpectralFilterLayer, self).__init__() 

Boris Bonev's avatar
Boris Bonev committed
65
        if filter_type == "non-linear" and isinstance(forward_transform, RealSHT):
Boris Bonev's avatar
Boris Bonev committed
66
67
68
69
70
71
72
73
74
75
76
            self.filter = SpectralAttentionS2(forward_transform,
                                              inverse_transform,
                                              embed_dim,
                                              operator_type = operator_type,
                                              sparsity_threshold = sparsity_threshold,
                                              hidden_size_factor = hidden_size_factor,
                                              complex_activation = complex_activation,
                                              spectral_layers = spectral_layers,
                                              drop_rate = drop_rate,
                                              bias = False)

Boris Bonev's avatar
Boris Bonev committed
77
        elif filter_type == "non-linear" and isinstance(forward_transform, RealFFT2):
Boris Bonev's avatar
Boris Bonev committed
78
79
80
81
82
83
84
85
86
87
88
            self.filter = SpectralAttention2d(forward_transform,
                                              inverse_transform,
                                              embed_dim,
                                              sparsity_threshold = sparsity_threshold,
                                              use_complex_kernels = use_complex_kernels,
                                              hidden_size_factor = hidden_size_factor,
                                              complex_activation = complex_activation,
                                              spectral_layers = spectral_layers,
                                              drop_rate = drop_rate,
                                              bias = False)

Boris Bonev's avatar
Boris Bonev committed
89
        elif filter_type == "linear" and factorization is None:
Boris Bonev's avatar
Boris Bonev committed
90
91
92
93
94
            self.filter = SpectralConvS2(forward_transform,
                                         inverse_transform,
                                         embed_dim,
                                         embed_dim,
                                         operator_type = operator_type,
Boris Bonev's avatar
Boris Bonev committed
95
                                         lr_scale_exponent = lr_scale_exponent,
Boris Bonev's avatar
Boris Bonev committed
96
                                         bias = True)
Boris Bonev's avatar
Boris Bonev committed
97
98
99
100
101
102
103
104
105
106
107
            
        elif filter_type == "linear" and factorization is not None:
            self.filter = FactorizedSpectralConvS2(forward_transform,
                                                   inverse_transform,
                                                   embed_dim,
                                                   embed_dim,
                                                   operator_type = operator_type,
                                                   rank = rank,
                                                   factorization = factorization,
                                                   separable = separable,
                                                   bias = True)
Boris Bonev's avatar
Boris Bonev committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

        else:
            raise(NotImplementedError)

    def forward(self, x):
        return self.filter(x)

class SphericalFourierNeuralOperatorBlock(nn.Module):
    """
    Helper module for a single SFNO/FNO block. Can use both FFTs and SHTs to represent either FNO or SFNO blocks.
    """
    def __init__(
            self,
            forward_transform,
            inverse_transform,
            embed_dim,
Boris Bonev's avatar
Boris Bonev committed
124
125
            filter_type = "non-linear",
            operator_type = "driscoll-healy",
Boris Bonev's avatar
Boris Bonev committed
126
127
128
129
            mlp_ratio = 2.,
            drop_rate = 0.,
            drop_path = 0.,
            act_layer = nn.GELU,
Boris Bonev's avatar
Boris Bonev committed
130
            norm_layer = nn.Identity,
Boris Bonev's avatar
Boris Bonev committed
131
132
            sparsity_threshold = 0.0,
            use_complex_kernels = True,
Boris Bonev's avatar
Boris Bonev committed
133
            lr_scale_exponent = 0,
Boris Bonev's avatar
Boris Bonev committed
134
135
136
            factorization = None,
            separable = False,
            rank = 128,
Boris Bonev's avatar
Boris Bonev committed
137
138
            inner_skip = "linear",
            outer_skip = None,
Boris Bonev's avatar
Boris Bonev committed
139
140
            concat_skip = False,
            use_mlp = True,
Boris Bonev's avatar
Boris Bonev committed
141
            complex_activation = "real",
Boris Bonev's avatar
Boris Bonev committed
142
143
144
145
146
147
148
149
150
151
152
153
            spectral_layers = 3):
        super(SphericalFourierNeuralOperatorBlock, self).__init__()
        
        # convolution layer
        self.filter = SpectralFilterLayer(forward_transform,
                                          inverse_transform,
                                          embed_dim,
                                          filter_type,
                                          operator_type = operator_type,
                                          sparsity_threshold = sparsity_threshold,
                                          use_complex_kernels = use_complex_kernels,
                                          hidden_size_factor = mlp_ratio,
Boris Bonev's avatar
Boris Bonev committed
154
                                          lr_scale_exponent = lr_scale_exponent,
Boris Bonev's avatar
Boris Bonev committed
155
156
157
158
159
160
161
                                          factorization = factorization,
                                          separable = separable,
                                          rank = rank,
                                          complex_activation = complex_activation,
                                          spectral_layers = spectral_layers,
                                          drop_rate = drop_rate)

Boris Bonev's avatar
Boris Bonev committed
162
        if inner_skip == "linear":
Boris Bonev's avatar
Boris Bonev committed
163
            self.inner_skip = nn.Conv2d(embed_dim, embed_dim, 1, 1)
Boris Bonev's avatar
Boris Bonev committed
164
        elif inner_skip == "identity":
Boris Bonev's avatar
Boris Bonev committed
165
            self.inner_skip = nn.Identity()
Boris Bonev's avatar
Boris Bonev committed
166
167
168
169
        elif inner_skip == "none":
            pass
        else:
            raise ValueError(f"Unknown skip connection type {inner_skip}")
Boris Bonev's avatar
Boris Bonev committed
170
171
172
173
174
175

        self.concat_skip = concat_skip

        if concat_skip and inner_skip is not None:
            self.inner_skip_conv = nn.Conv2d(2*embed_dim, embed_dim, 1, bias=False)

Boris Bonev's avatar
Boris Bonev committed
176
        if filter_type == "linear":
Boris Bonev's avatar
Boris Bonev committed
177
            self.act_layer = act_layer()
Boris Bonev's avatar
Boris Bonev committed
178
179
180

        # first normalisation layer
        self.norm0 = norm_layer()
Boris Bonev's avatar
Boris Bonev committed
181
182
183
184
185
186
187
188
189
190
191
192
        
        # dropout
        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        
        if use_mlp == True:
            mlp_hidden_dim = int(embed_dim * mlp_ratio)
            self.mlp = MLP(in_features = embed_dim,
                           hidden_features = mlp_hidden_dim,
                           act_layer = act_layer,
                           drop_rate = drop_rate,
                           checkpointing = False)

Boris Bonev's avatar
Boris Bonev committed
193
        if outer_skip == "linear":
Boris Bonev's avatar
Boris Bonev committed
194
            self.outer_skip = nn.Conv2d(embed_dim, embed_dim, 1, 1)
Boris Bonev's avatar
Boris Bonev committed
195
        elif outer_skip == "identity":
Boris Bonev's avatar
Boris Bonev committed
196
            self.outer_skip = nn.Identity()
Boris Bonev's avatar
Boris Bonev committed
197
198
199
200
        elif outer_skip == "none":
            pass
        else:
            raise ValueError(f"Unknown skip connection type {outer_skip}")
Boris Bonev's avatar
Boris Bonev committed
201
202
203
204

        if concat_skip and outer_skip is not None:
            self.outer_skip_conv = nn.Conv2d(2*embed_dim, embed_dim, 1, bias=False)

Boris Bonev's avatar
Boris Bonev committed
205
206
207
        # second normalisation layer
        self.norm1 = norm_layer()

Boris Bonev's avatar
Boris Bonev committed
208
209
210
211
    def forward(self, x):

        x, residual = self.filter(x)

Boris Bonev's avatar
Boris Bonev committed
212
        if hasattr(self, "inner_skip"):
Boris Bonev's avatar
Boris Bonev committed
213
214
215
216
217
218
            if self.concat_skip:
                x = torch.cat((x, self.inner_skip(residual)), dim=1)
                x = self.inner_skip_conv(x)
            else:
                x = x + self.inner_skip(residual)

Boris Bonev's avatar
Boris Bonev committed
219
        if hasattr(self, "act_layer"):
Boris Bonev's avatar
Boris Bonev committed
220
221
            x = self.act_layer(x)

Boris Bonev's avatar
Boris Bonev committed
222
        x = self.norm0(x)
Boris Bonev's avatar
Boris Bonev committed
223

Boris Bonev's avatar
Boris Bonev committed
224
        if hasattr(self, "mlp"):
Boris Bonev's avatar
Boris Bonev committed
225
226
227
228
            x = self.mlp(x)

        x = self.drop_path(x)

Boris Bonev's avatar
Boris Bonev committed
229
        if hasattr(self, "outer_skip"):
Boris Bonev's avatar
Boris Bonev committed
230
231
232
233
234
235
            if self.concat_skip:
                x = torch.cat((x, self.outer_skip(residual)), dim=1)
                x = self.outer_skip_conv(x)
            else:
                x = x + self.outer_skip(residual)

Boris Bonev's avatar
Boris Bonev committed
236
237
        x = self.norm1(x)

Boris Bonev's avatar
Boris Bonev committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        return x

class SphericalFourierNeuralOperatorNet(nn.Module):
    """
    SphericalFourierNeuralOperator module. Can use both FFTs and SHTs to represent either FNO or SFNO,
    both linear and non-linear variants.

    Parameters
    ----------
    filter_type : str, optional
        Type of filter to use ('linear', 'non-linear'), by default "linear"
    spectral_transform : str, optional
        Type of spectral transformation to use, by default "sht"
    operator_type : str, optional
Boris Bonev's avatar
Boris Bonev committed
252
        Type of operator to use ('driscoll-healy', 'diagonal'), by default "driscoll-healy"
Boris Bonev's avatar
Boris Bonev committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    img_shape : tuple, optional
        Shape of the input channels, by default (128, 256)
    scale_factor : int, optional
        Scale factor to use, by default 3
    in_chans : int, optional
        Number of input channels, by default 3
    out_chans : int, optional
        Number of output channels, by default 3
    embed_dim : int, optional
        Dimension of the embeddings, by default 256
    num_layers : int, optional
        Number of layers in the network, by default 4
    activation_function : str, optional
        Activation function to use, by default "gelu"
    encoder_layers : int, optional
        Number of layers in the encoder, by default 1
    use_mlp : int, optional
Boris Bonev's avatar
Boris Bonev committed
270
        Whether to use MLPs in the SFNO blocks, by default True
Boris Bonev's avatar
Boris Bonev committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
    mlp_ratio : int, optional
        Ratio of MLP to use, by default 2.0
    drop_rate : float, optional
        Dropout rate, by default 0.0
    drop_path_rate : float, optional
        Dropout path rate, by default 0.0
    sparsity_threshold : float, optional
        Threshold for sparsity, by default 0.0
    normalization_layer : str, optional
        Type of normalization layer to use ("layer_norm", "instance_norm", "none"), by default "instance_norm"
    hard_thresholding_fraction : float, optional
        Fraction of hard thresholding (frequency cutoff) to apply, by default 1.0
    use_complex_kernels : bool, optional
        Whether to use complex kernels, by default True
    big_skip : bool, optional
        Whether to add a single large skip connection, by default True
    rank : float, optional
        Rank of the approximation, by default 1.0
Boris Bonev's avatar
Boris Bonev committed
289
290
    lr_scale_exponent : float, optional
        exponential rescaling of spectral coefficients, by default 0.0 (no rescaling)
Boris Bonev's avatar
Boris Bonev committed
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
    factorization : Any, optional
        Type of factorization to use, by default None
    separable : bool, optional
        Whether to use separable convolutions, by default False
    rank : (int, Tuple[int]), optional
        If a factorization is used, which rank to use. Argument is passed to tensorly
    complex_activation : str, optional
        Type of complex activation function to use, by default "real"
    spectral_layers : int, optional
        Number of spectral layers, by default 3
    pos_embed : bool, optional
        Whether to use positional embedding, by default True

    Example:
    --------
    >>> model = SphericalFourierNeuralOperatorNet(
    ...         img_shape=(128, 256),
    ...         scale_factor=4,
    ...         in_chans=2,
    ...         out_chans=2,
    ...         embed_dim=16,
Boris Bonev's avatar
Boris Bonev committed
312
    ...         num_layers=4,
Boris Bonev's avatar
Boris Bonev committed
313
314
315
316
317
318
319
    ...         use_mlp=True,)
    >>> model(torch.randn(1, 2, 128, 256)).shape
    torch.Size([1, 2, 128, 256])
    """

    def __init__(
            self,
Boris Bonev's avatar
Boris Bonev committed
320
321
322
            filter_type = "linear",
            spectral_transform = "sht",
            operator_type = "driscoll-healy",
Boris Bonev's avatar
Boris Bonev committed
323
324
325
326
327
328
            img_size = (128, 256),
            scale_factor = 3,
            in_chans = 3,
            out_chans = 3,
            embed_dim = 256,
            num_layers = 4,
Boris Bonev's avatar
Boris Bonev committed
329
            activation_function = "gelu",
Boris Bonev's avatar
Boris Bonev committed
330
331
332
333
334
335
            encoder_layers = 1,
            use_mlp = True,
            mlp_ratio = 2.,
            drop_rate = 0.,
            drop_path_rate = 0.,
            sparsity_threshold = 0.0,
Boris Bonev's avatar
Boris Bonev committed
336
            normalization_layer = "none",
Boris Bonev's avatar
Boris Bonev committed
337
338
339
            hard_thresholding_fraction = 1.0,
            use_complex_kernels = True,
            big_skip = True,
Boris Bonev's avatar
Boris Bonev committed
340
            lr_scale_exponent = 0,
Boris Bonev's avatar
Boris Bonev committed
341
342
343
            factorization = None,
            separable = False,
            rank = 128,
Boris Bonev's avatar
Boris Bonev committed
344
            complex_activation = "real",
Boris Bonev's avatar
Boris Bonev committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
            spectral_layers = 2,
            pos_embed = True):

        super(SphericalFourierNeuralOperatorNet, self).__init__()

        self.filter_type = filter_type
        self.spectral_transform = spectral_transform
        self.operator_type = operator_type
        self.img_size = img_size
        self.scale_factor = scale_factor
        self.in_chans = in_chans
        self.out_chans = out_chans
        self.embed_dim = self.num_features = embed_dim
        self.pos_embed_dim = self.embed_dim
        self.num_layers = num_layers
        self.hard_thresholding_fraction = hard_thresholding_fraction
        self.normalization_layer = normalization_layer
        self.use_mlp = use_mlp
        self.encoder_layers = encoder_layers
        self.big_skip = big_skip
Boris Bonev's avatar
Boris Bonev committed
365
        self.lr_scale_exponent = lr_scale_exponent
Boris Bonev's avatar
Boris Bonev committed
366
367
368
369
370
371
372
        self.factorization = factorization
        self.separable = separable,
        self.rank = rank
        self.complex_activation = complex_activation
        self.spectral_layers = spectral_layers

        # activation function
Boris Bonev's avatar
Boris Bonev committed
373
        if activation_function == "relu":
Boris Bonev's avatar
Boris Bonev committed
374
            self.activation_function = nn.ReLU
Boris Bonev's avatar
Boris Bonev committed
375
        elif activation_function == "gelu":
Boris Bonev's avatar
Boris Bonev committed
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
            self.activation_function = nn.GELU
        else:
            raise ValueError(f"Unknown activation function {activation_function}")

        # compute downsampled image size
        self.h = self.img_size[0] // scale_factor
        self.w = self.img_size[1] // scale_factor

        # dropout
        self.pos_drop = nn.Dropout(p=drop_rate) if drop_rate > 0. else nn.Identity()
        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, self.num_layers)]

        # pick norm layer
        if self.normalization_layer == "layer_norm":
            norm_layer0 = partial(nn.LayerNorm, normalized_shape=(self.img_size[0], self.img_size[1]), eps=1e-6)
            norm_layer1 = partial(nn.LayerNorm, normalized_shape=(self.h, self.w), eps=1e-6)
        elif self.normalization_layer == "instance_norm":
            norm_layer0 = partial(nn.InstanceNorm2d, num_features=self.embed_dim, eps=1e-6, affine=True, track_running_stats=False)
            norm_layer1 = norm_layer0
        elif self.normalization_layer == "none":
            norm_layer0 = nn.Identity
            norm_layer1 = norm_layer0
        else:
            raise NotImplementedError(f"Error, normalization {self.normalization_layer} not implemented.") 

        if pos_embed:
            self.pos_embed = nn.Parameter(torch.zeros(1, self.embed_dim, self.img_size[0], self.img_size[1]))
        else:
            self.pos_embed = None

        # encoder
Boris Bonev's avatar
Boris Bonev committed
407
408
409
410
411
412
413
414
415
        encoder_hidden_dim = int(self.embed_dim * mlp_ratio)
        encoder = MLP(in_features = self.in_chans,
                      out_features = self.embed_dim,
                      hidden_features = encoder_hidden_dim,
                      act_layer = self.activation_function,
                      drop_rate = drop_rate,
                      checkpointing = False)
        self.encoder = encoder
        # self.encoder = nn.Sequential(encoder, norm_layer0())
Boris Bonev's avatar
Boris Bonev committed
416
417
        
        # prepare the spectral transform
Boris Bonev's avatar
Boris Bonev committed
418
        if self.spectral_transform == "sht":
Boris Bonev's avatar
Boris Bonev committed
419
420
421
422

            modes_lat = int(self.h * self.hard_thresholding_fraction)
            modes_lon = int((self.w // 2 + 1) * self.hard_thresholding_fraction)

Boris Bonev's avatar
Boris Bonev committed
423
424
425
426
            self.trans_down = RealSHT(*self.img_size, lmax=modes_lat, mmax=modes_lon, grid="equiangular").float()
            self.itrans_up  = InverseRealSHT(*self.img_size, lmax=modes_lat, mmax=modes_lon, grid="equiangular").float()
            self.trans      = RealSHT(self.h, self.w, lmax=modes_lat, mmax=modes_lon, grid="legendre-gauss").float()
            self.itrans     = InverseRealSHT(self.h, self.w, lmax=modes_lat, mmax=modes_lon, grid="legendre-gauss").float()
Boris Bonev's avatar
Boris Bonev committed
427

Boris Bonev's avatar
Boris Bonev committed
428
        elif self.spectral_transform == "fft":
Boris Bonev's avatar
Boris Bonev committed
429
430
431
432
433
434
435
436
437
438

            modes_lat = int(self.h * self.hard_thresholding_fraction)
            modes_lon = int((self.w // 2 + 1) * self.hard_thresholding_fraction)

            self.trans_down = RealFFT2(*self.img_size, lmax=modes_lat, mmax=modes_lon).float()
            self.itrans_up  = InverseRealFFT2(*self.img_size, lmax=modes_lat, mmax=modes_lon).float()
            self.trans      = RealFFT2(self.h, self.w, lmax=modes_lat, mmax=modes_lon).float()
            self.itrans     = InverseRealFFT2(self.h, self.w, lmax=modes_lat, mmax=modes_lon).float()
            
        else:
Boris Bonev's avatar
Boris Bonev committed
439
            raise(ValueError("Unknown spectral transform"))
Boris Bonev's avatar
Boris Bonev committed
440
441
442
443
444
445
446
447
448
449
450
451
452
453

        self.blocks = nn.ModuleList([])
        for i in range(self.num_layers):

            first_layer = i == 0
            last_layer = i == self.num_layers-1

            forward_transform = self.trans_down if first_layer else self.trans
            inverse_transform = self.itrans_up if last_layer else self.itrans

            inner_skip = 'linear'
            outer_skip = 'identity'

            if first_layer:
Boris Bonev's avatar
Boris Bonev committed
454
                norm_layer = norm_layer1
Boris Bonev's avatar
Boris Bonev committed
455
            elif last_layer:
Boris Bonev's avatar
Boris Bonev committed
456
                norm_layer = norm_layer0
Boris Bonev's avatar
Boris Bonev committed
457
            else:
Boris Bonev's avatar
Boris Bonev committed
458
                norm_layer = norm_layer1
Boris Bonev's avatar
Boris Bonev committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474

            block = SphericalFourierNeuralOperatorBlock(forward_transform,
                                                        inverse_transform,
                                                        self.embed_dim,
                                                        filter_type = filter_type,
                                                        operator_type = self.operator_type,
                                                        mlp_ratio = mlp_ratio,
                                                        drop_rate = drop_rate,
                                                        drop_path = dpr[i],
                                                        act_layer = self.activation_function,
                                                        norm_layer = norm_layer,
                                                        sparsity_threshold = sparsity_threshold,
                                                        use_complex_kernels = use_complex_kernels,
                                                        inner_skip = inner_skip,
                                                        outer_skip = outer_skip,
                                                        use_mlp = use_mlp,
Boris Bonev's avatar
Boris Bonev committed
475
                                                        lr_scale_exponent = self.lr_scale_exponent,
Boris Bonev's avatar
Boris Bonev committed
476
477
478
479
480
481
482
483
484
                                                        factorization = self.factorization,
                                                        separable = self.separable,
                                                        rank = self.rank,
                                                        complex_activation = self.complex_activation,
                                                        spectral_layers = self.spectral_layers)

            self.blocks.append(block)

        # decoder
Boris Bonev's avatar
Boris Bonev committed
485
486
487
488
489
490
491
        encoder_hidden_dim = int(self.embed_dim * mlp_ratio)
        self.decoder = MLP(in_features = self.embed_dim + self.big_skip*self.in_chans,
                           out_features = self.out_chans,
                           hidden_features = encoder_hidden_dim,
                           act_layer = self.activation_function,
                           drop_rate = drop_rate,
                           checkpointing = False)
Boris Bonev's avatar
Boris Bonev committed
492
493
494
495
496
497
498
499
500
501
502
503
504

        # trunc_normal_(self.pos_embed, std=.02)
        self.apply(self._init_weights)

    def _init_weights(self, m):
        if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
            trunc_normal_(m.weight, std=.02)
            #nn.init.normal_(m.weight, std=0.02)
            if m.bias is not None:
                nn.init.constant_(m.bias, 0)

    @torch.jit.ignore
    def no_weight_decay(self):
Boris Bonev's avatar
Boris Bonev committed
505
        return {"pos_embed", "cls_token"}
Boris Bonev's avatar
Boris Bonev committed
506
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
532
533
534
535

    def forward_features(self, x):

        x = self.pos_drop(x)

        for blk in self.blocks:
            x = blk(x)
            
        return x

    def forward(self, x):

        if self.big_skip:
            residual = x

        x = self.encoder(x)

        if self.pos_embed is not None:
            x = x + self.pos_embed

        x = self.forward_features(x)

        if self.big_skip:
            x = torch.cat((x, residual), dim=1)

        x = self.decoder(x)

        return x