Spaces:
Runtime error
Runtime error
File size: 9,533 Bytes
b73936d |
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
import math
import logging
from itertools import chain
import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from timm.models.layers import DropPath, trunc_normal_
import torch.fft
from .transformer_ls import AttentionLS
_logger = logging.getLogger(__name__)
class Mlp(nn.Module):
def __init__(
self,
in_features,
hidden_features=None,
out_features=None,
act_layer=nn.GELU,
drop=0.0,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class SpectralGatingNetwork(nn.Module):
def __init__(self, dim, h=14, w=8):
super().__init__()
self.complex_weight = nn.Parameter(torch.randn(h, w, dim, 2) * 0.02)
self.w = w
self.h = h
def forward(self, x, spatial_size=None):
B, N, C = x.shape # torch.Size([1, 262144, 1024])
if spatial_size is None:
a = b = int(math.sqrt(N)) # a=b=512
else:
a, b = spatial_size
x = x.view(B, a, b, C) # torch.Size([1, 512, 512, 1024])
# FROM HERE USED TO BE AUTOCAST to float32
dtype = x.dtype
x = x.to(torch.float32)
x = torch.fft.rfft2(
x, dim=(1, 2), norm="ortho"
) # torch.Size([1, 512, 257, 1024])
weight = torch.view_as_complex(
self.complex_weight.to(torch.float32)
) # torch.Size([512, 257, 1024])
x = x * weight
x = torch.fft.irfft2(
x, s=(a, b), dim=(1, 2), norm="ortho"
) # torch.Size([1, 512, 512, 1024])
x = x.to(dtype)
x = x.reshape(B, N, C) # torch.Size([1, 262144, 1024])
# UP TO HERE USED TO BE AUTOCAST to float32
return x
class BlockSpectralGating(nn.Module):
def __init__(
self,
dim,
mlp_ratio=4.0,
drop=0.0,
drop_path=0.0,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
h=14,
w=8,
):
super().__init__()
self.norm1 = norm_layer(dim)
self.filter = SpectralGatingNetwork(dim, h=h, w=w)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(
in_features=dim,
hidden_features=mlp_hidden_dim,
act_layer=act_layer,
drop=drop,
)
def forward(self, x, *args):
x = x + self.drop_path(self.mlp(self.norm2(self.filter(self.norm1(x)))))
return x
class BlockAttention(nn.Module):
def __init__(
self,
dim,
num_heads: int = 8,
mlp_ratio=4.0,
drop=0.0,
drop_path=0.0,
w=2,
dp_rank=2,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
rpe=False,
adaLN=False,
nglo=0,
):
"""
num_heads: Attention heads. 4 for tiny, 8 for small and 12 for base
"""
super().__init__()
self.norm1 = norm_layer(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(
in_features=dim,
hidden_features=mlp_hidden_dim,
act_layer=act_layer,
drop=drop,
)
self.attn = AttentionLS(
dim=dim,
num_heads=num_heads,
w=w,
dp_rank=dp_rank,
nglo=nglo,
rpe=rpe,
)
if adaLN:
self.adaLN_modulation = nn.Sequential(
nn.Linear(dim, dim, bias=True),
act_layer(),
nn.Linear(dim, 6 * dim, bias=True),
)
else:
self.adaLN_modulation = None
def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
if self.adaLN_modulation is not None:
(
shift_mha,
scale_mha,
gate_mha,
shift_mlp,
scale_mlp,
gate_mlp,
) = self.adaLN_modulation(c).chunk(6, dim=2)
else:
shift_mha, scale_mha, gate_mha, shift_mlp, scale_mlp, gate_mlp = 6 * (1.0,)
x = x + gate_mha * self.drop_path(
self.attn(
self.norm1(x) * scale_mha + shift_mha,
)
)
x = x + gate_mlp * self.drop_path(
self.mlp(self.norm2(x) * scale_mlp + shift_mlp)
)
return x
class SpectFormer(nn.Module):
def __init__(
self,
grid_size: int = 224 // 16,
embed_dim=768,
depth=12,
n_spectral_blocks=4,
num_heads: int = 8,
mlp_ratio=4.0,
uniform_drop=False,
drop_rate=0.0,
drop_path_rate=0.0,
window_size=2,
dp_rank=2,
norm_layer=nn.LayerNorm,
checkpoint_layers: list[int] | None = None,
rpe=False,
ensemble: int | None = None,
nglo: int = 0,
):
"""
Args:
img_size (int, tuple): input image size
patch_size (int, tuple): patch size
embed_dim (int): embedding dimension
depth (int): depth of transformer
n_spectral_blocks (int): number of spectral gating blocks
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
uniform_drop (bool): true for uniform, false for linearly increasing drop path probability.
drop_rate (float): dropout rate
drop_path_rate (float): drop path (stochastic depth) rate
window_size: window size for long/short attention
dp_rank: dp rank for long/short attention
norm_layer: (nn.Module): normalization layer for attention blocks
checkpoint_layers: indicate which layers to use for checkpointing
rpe: Use relative position encoding in Long-Short attention blocks.
ensemble: Integer indicating ensemble size or None for deterministic model.
nglo: Number of (additional) global tokens.
"""
super().__init__()
self.embed_dim = embed_dim
self.n_spectral_blocks = n_spectral_blocks
self._checkpoint_layers = checkpoint_layers or []
self.ensemble = ensemble
self.nglo = nglo
h = grid_size
w = h // 2 + 1
if uniform_drop:
_logger.info(f"Using uniform droppath with expect rate {drop_path_rate}.")
dpr = [drop_path_rate for _ in range(depth)]
else:
_logger.info(
f"Using linear droppath with expect rate {drop_path_rate * 0.5}."
)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
self.blocks_spectral_gating = nn.ModuleList()
self.blocks_attention = nn.ModuleList()
for i in range(depth):
if i < n_spectral_blocks:
layer = BlockSpectralGating(
dim=embed_dim,
mlp_ratio=mlp_ratio,
drop=drop_rate,
drop_path=dpr[i],
norm_layer=norm_layer,
h=h,
w=w,
)
self.blocks_spectral_gating.append(layer)
else:
layer = BlockAttention(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
drop=drop_rate,
drop_path=dpr[i],
norm_layer=norm_layer,
w=window_size,
dp_rank=dp_rank,
rpe=rpe,
adaLN=True if ensemble is not None else False,
nglo=nglo,
)
self.blocks_attention.append(layer)
self.apply(self._init_weights)
def forward(self, tokens: torch.Tensor) -> torch.Tensor:
"""
Args:
tokens: Tensor of shape B, N, C for deterministic of BxE, N, C for ensemble forecast.
Returns:
Tensor of same shape as input.
"""
if self.ensemble:
BE, N, C = tokens.shape
noise = torch.randn(
size=(BE, N, C), dtype=tokens.dtype, device=tokens.device
)
else:
noise = None
for i, blk in enumerate(
chain(self.blocks_spectral_gating, self.blocks_attention)
):
if i in self._checkpoint_layers:
tokens = checkpoint(blk, tokens, noise, use_reentrant=False)
else:
tokens = blk(tokens, noise)
return tokens
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
|