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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from models_trans import BasicTransformer, LinearTransformer, SparseTransformer
|
| 4 |
+
from timm.models.layers import trunc_normal_
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def create_block(d_model=192, n_heads=8, d_head=24, dropout=0.1, map_name="elu+1",
|
| 8 |
+
block_name="basic", return_attn=False):
|
| 9 |
+
if block_name == "basic":
|
| 10 |
+
return BasicTransformer(d_model, n_heads, d_head, dropout=dropout,
|
| 11 |
+
return_attn=return_attn)
|
| 12 |
+
elif block_name == "basic-gated":
|
| 13 |
+
return BasicTransformer(d_model, n_heads, d_head, dropout=dropout,
|
| 14 |
+
is_gated=True, return_attn=return_attn)
|
| 15 |
+
elif block_name == "flash":
|
| 16 |
+
return BasicTransformer(d_model, n_heads, d_head, dropout=dropout,
|
| 17 |
+
use_flash_attention=True, return_attn=return_attn)
|
| 18 |
+
elif block_name == "flash-gated":
|
| 19 |
+
return BasicTransformer(d_model, n_heads, d_head, dropout=dropout,
|
| 20 |
+
use_flash_attention=True, is_gated=True, return_attn=return_attn)
|
| 21 |
+
elif block_name == "linear":
|
| 22 |
+
return LinearTransformer(d_model, dropout=dropout, map_name=map_name)
|
| 23 |
+
elif block_name == "sparse":
|
| 24 |
+
return SparseTransformer(d_model, n_heads, dropout=dropout)
|
| 25 |
+
else:
|
| 26 |
+
raise NotImplementedError(f"Block {block_name} not implemented")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
from timm.models.layers import trunc_normal_, lecun_normal_
|
| 30 |
+
import math
|
| 31 |
+
import time
|
| 32 |
+
from functools import partial
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# https://github.com/huggingface/transformers/blob/c28d04e9e252a1a099944e325685f14d242ecdcd/src/transformers/models/gpt2/modeling_gpt2.py#L454
|
| 36 |
+
def _init_weights(
|
| 37 |
+
module,
|
| 38 |
+
n_layer,
|
| 39 |
+
initializer_range=0.02, # Now only used for embedding layer.
|
| 40 |
+
rescale_prenorm_residual=True,
|
| 41 |
+
n_residuals_per_layer=1, # Change to 2 if we have MLP
|
| 42 |
+
):
|
| 43 |
+
if isinstance(module, nn.Linear):
|
| 44 |
+
if module.bias is not None:
|
| 45 |
+
if not getattr(module.bias, "_no_reinit", False):
|
| 46 |
+
nn.init.zeros_(module.bias)
|
| 47 |
+
elif isinstance(module, nn.Embedding):
|
| 48 |
+
nn.init.normal_(module.weight, std=initializer_range)
|
| 49 |
+
|
| 50 |
+
if rescale_prenorm_residual:
|
| 51 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 52 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 53 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 54 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 55 |
+
#
|
| 56 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 57 |
+
for name, p in module.named_parameters():
|
| 58 |
+
if name in ["out_proj.weight", "fc2.weight"]:
|
| 59 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
| 60 |
+
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
|
| 61 |
+
# We need to reinit p since this code could be called multiple times
|
| 62 |
+
# Having just p *= scale would repeatedly scale it down
|
| 63 |
+
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 64 |
+
with torch.no_grad():
|
| 65 |
+
p /= math.sqrt(n_residuals_per_layer * n_layer)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def segm_init_weights(m):
|
| 69 |
+
if isinstance(m, nn.Linear):
|
| 70 |
+
trunc_normal_(m.weight, std=0.02)
|
| 71 |
+
if isinstance(m, nn.Linear) and m.bias is not None:
|
| 72 |
+
nn.init.constant_(m.bias, 0)
|
| 73 |
+
elif isinstance(m, (nn.Conv2d, nn.Conv1d)):
|
| 74 |
+
# NOTE conv was left to pytorch default in my original init
|
| 75 |
+
lecun_normal_(m.weight)
|
| 76 |
+
if m.bias is not None:
|
| 77 |
+
nn.init.zeros_(m.bias)
|
| 78 |
+
elif isinstance(m, (nn.LayerNorm, nn.GroupNorm, nn.BatchNorm2d)):
|
| 79 |
+
nn.init.zeros_(m.bias)
|
| 80 |
+
nn.init.ones_(m.weight)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class StrideEmbed(nn.Module):
|
| 84 |
+
def __init__(self, arr_length=1600, stride_size=4, in_chans=1, embed_dim=192):
|
| 85 |
+
super().__init__()
|
| 86 |
+
assert arr_length % stride_size == 0
|
| 87 |
+
self.num_patches = arr_length // stride_size
|
| 88 |
+
self.proj = nn.Conv1d(in_chans, embed_dim, kernel_size=stride_size, stride=stride_size)
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
"""
|
| 92 |
+
x: [B, N]
|
| 93 |
+
"""
|
| 94 |
+
return self.proj(x).transpose(1, 2) # [B, N, D]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class NetTransformer(nn.Module):
|
| 98 |
+
def __init__(self,
|
| 99 |
+
arr_length=1600,
|
| 100 |
+
stride_size=4,
|
| 101 |
+
in_chans=1,
|
| 102 |
+
embed_dim=192, depth=4,
|
| 103 |
+
decoder_embed_dim=128, decoder_depth=2,
|
| 104 |
+
num_classes=1000,
|
| 105 |
+
n_heads=8, block_name="basic",
|
| 106 |
+
norm_pix_loss=False,
|
| 107 |
+
drop_rate=0.,
|
| 108 |
+
is_pretrain=False,
|
| 109 |
+
if_cls_token=True,
|
| 110 |
+
device=None, dtype=None,
|
| 111 |
+
return_attn=False,
|
| 112 |
+
**kwargs):
|
| 113 |
+
super().__init__()
|
| 114 |
+
|
| 115 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 116 |
+
# add factory_kwargs into kwargs
|
| 117 |
+
kwargs.update(factory_kwargs)
|
| 118 |
+
self.num_classes = num_classes
|
| 119 |
+
self.d_model = self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
| 120 |
+
self.is_pretrain = is_pretrain
|
| 121 |
+
self.return_attn = return_attn
|
| 122 |
+
self.stride_size = stride_size
|
| 123 |
+
|
| 124 |
+
# --------------------------------------------------------------------------
|
| 125 |
+
# NetMamba encoder specifics
|
| 126 |
+
self.patch_embed = StrideEmbed(arr_length=arr_length, stride_size=stride_size, embed_dim=embed_dim)
|
| 127 |
+
self.num_patches = self.patch_embed.num_patches
|
| 128 |
+
self.if_cls_token = if_cls_token
|
| 129 |
+
if if_cls_token:
|
| 130 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 131 |
+
self.num_cls_token = 1
|
| 132 |
+
else:
|
| 133 |
+
self.num_cls_token = 0
|
| 134 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + self.num_cls_token, embed_dim))
|
| 135 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
| 136 |
+
# Mamba blocks
|
| 137 |
+
self.blocks = nn.ModuleList([
|
| 138 |
+
create_block(d_model=embed_dim, n_heads=n_heads, d_head=embed_dim // n_heads, dropout=0.1,
|
| 139 |
+
block_name=block_name, return_attn=return_attn)
|
| 140 |
+
for _ in range(depth)])
|
| 141 |
+
# --------------------------------------------------------------------------
|
| 142 |
+
|
| 143 |
+
if is_pretrain:
|
| 144 |
+
# --------------------------------------------------------------------------
|
| 145 |
+
# NetMamba decoder specifics
|
| 146 |
+
self.decoder_embed = nn.Linear(embed_dim, decoder_embed_dim, bias=True)
|
| 147 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_embed_dim))
|
| 148 |
+
self.decoder_pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + self.num_cls_token, decoder_embed_dim))
|
| 149 |
+
self.decoder_blocks = nn.ModuleList([
|
| 150 |
+
create_block(d_model=decoder_embed_dim, n_heads=n_heads, d_head=decoder_embed_dim // n_heads, dropout=0.1,
|
| 151 |
+
block_name=block_name, return_attn=return_attn)
|
| 152 |
+
for _ in range(decoder_depth)])
|
| 153 |
+
self.decoder_pred = nn.Linear(decoder_embed_dim, stride_size * in_chans, bias=True) # decoder to stride
|
| 154 |
+
# --------------------------------------------------------------------------
|
| 155 |
+
else:
|
| 156 |
+
# --------------------------------------------------------------------------
|
| 157 |
+
# NetMamba classifier specifics
|
| 158 |
+
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
|
| 159 |
+
# --------------------------------------------------------------------------
|
| 160 |
+
|
| 161 |
+
self.norm_pix_loss = norm_pix_loss
|
| 162 |
+
self.initialize_weights(depth)
|
| 163 |
+
|
| 164 |
+
def initialize_weights(self, depth):
|
| 165 |
+
self.patch_embed.apply(segm_init_weights)
|
| 166 |
+
if not self.is_pretrain:
|
| 167 |
+
self.head.apply(segm_init_weights)
|
| 168 |
+
trunc_normal_(self.pos_embed, std=.02)
|
| 169 |
+
trunc_normal_(self.cls_token, std=.02)
|
| 170 |
+
if self.is_pretrain:
|
| 171 |
+
trunc_normal_(self.decoder_pos_embed, std=.02)
|
| 172 |
+
trunc_normal_(self.mask_token, std=.02)
|
| 173 |
+
# initialize nn.Linear and nn.LayerNorm
|
| 174 |
+
self.apply(partial(_init_weights, n_layer=depth,))
|
| 175 |
+
|
| 176 |
+
@torch.jit.ignore
|
| 177 |
+
def no_weight_decay(self):
|
| 178 |
+
return {"pos_embed", "cls_token", "dist_token", "cls_token_head", "cls_token_tail"}
|
| 179 |
+
|
| 180 |
+
def stride_patchify(self, imgs):
|
| 181 |
+
"""
|
| 182 |
+
imgs: (N, 1, H, W)
|
| 183 |
+
x: (N, L, patch_size**2 *1)
|
| 184 |
+
"""
|
| 185 |
+
B, C, H, W = imgs.shape
|
| 186 |
+
assert C == 1, "Input images should be grayscale"
|
| 187 |
+
stride_size = self.stride_size
|
| 188 |
+
x = imgs.reshape(B, H*W // stride_size, stride_size)
|
| 189 |
+
return x
|
| 190 |
+
|
| 191 |
+
def random_masking(self, x, mask_ratio):
|
| 192 |
+
"""
|
| 193 |
+
Perform per-sample random masking by per-sample shuffling.
|
| 194 |
+
Per-sample shuffling is done by argsort random noise.
|
| 195 |
+
x: [B N D], sequence
|
| 196 |
+
"""
|
| 197 |
+
B, N, D = x.shape # batch, length, dim
|
| 198 |
+
len_keep = int(N * (1 - mask_ratio))
|
| 199 |
+
|
| 200 |
+
noise = torch.rand(B, N, device=x.device) # noise in [0, 1]
|
| 201 |
+
|
| 202 |
+
# sort noise for each sample
|
| 203 |
+
ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove
|
| 204 |
+
ids_restore = torch.argsort(ids_shuffle, dim=1) # ids_restore[i] = i-th noise element's rank
|
| 205 |
+
|
| 206 |
+
# keep the first subset
|
| 207 |
+
ids_keep = ids_shuffle[:, :len_keep]
|
| 208 |
+
x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, D)) # x_masked are acctually non-masked elements
|
| 209 |
+
|
| 210 |
+
# generate the binary mask: 0 is keep, 1 is remove
|
| 211 |
+
mask = torch.ones([B, N], device=x.device)
|
| 212 |
+
mask[:, :len_keep] = 0
|
| 213 |
+
# unshuffle to get the binary mask
|
| 214 |
+
mask = torch.gather(mask, dim=1, index=ids_restore)
|
| 215 |
+
|
| 216 |
+
return x_masked, mask, ids_restore
|
| 217 |
+
|
| 218 |
+
def forward_encoder(self, x, mask_ratio, if_mask=True):
|
| 219 |
+
"""
|
| 220 |
+
x: [B, 1, H, W]
|
| 221 |
+
"""
|
| 222 |
+
# embed patches
|
| 223 |
+
B, C, H, W = x.shape
|
| 224 |
+
x = self.patch_embed(x.reshape(B, C, -1))
|
| 225 |
+
|
| 226 |
+
# add pos embed w/o cls token
|
| 227 |
+
if self.if_cls_token:
|
| 228 |
+
x = x + self.pos_embed[:, :-1, :]
|
| 229 |
+
else:
|
| 230 |
+
x = x + self.pos_embed
|
| 231 |
+
|
| 232 |
+
# masking: length -> length * mask_ratio
|
| 233 |
+
if if_mask:
|
| 234 |
+
x, mask, ids_restore = self.random_masking(x, mask_ratio)
|
| 235 |
+
|
| 236 |
+
# append cls token
|
| 237 |
+
if self.if_cls_token:
|
| 238 |
+
cls_token = self.cls_token + self.pos_embed[:, -1, :]
|
| 239 |
+
cls_tokens = cls_token.expand(x.shape[0], -1, -1)
|
| 240 |
+
x = torch.cat((x, cls_tokens), dim=1)
|
| 241 |
+
x = self.pos_drop(x)
|
| 242 |
+
|
| 243 |
+
# apply Mamba blocks
|
| 244 |
+
attn_list = []
|
| 245 |
+
for blk in self.blocks:
|
| 246 |
+
if self.return_attn:
|
| 247 |
+
x, attn = blk(x)
|
| 248 |
+
attn_list.append(attn)
|
| 249 |
+
else:
|
| 250 |
+
x = blk(x)
|
| 251 |
+
if if_mask:
|
| 252 |
+
return x, mask, ids_restore
|
| 253 |
+
else:
|
| 254 |
+
# return x
|
| 255 |
+
if self.return_attn:
|
| 256 |
+
return x, attn_list
|
| 257 |
+
else:
|
| 258 |
+
return x
|
| 259 |
+
|
| 260 |
+
def forward_decoder(self, x, ids_restore):
|
| 261 |
+
# embed tokens
|
| 262 |
+
x = self.decoder_embed(x)
|
| 263 |
+
|
| 264 |
+
# append mask tokens to sequence
|
| 265 |
+
mask_tokens = self.mask_token.repeat(x.shape[0], ids_restore.shape[1] + self.num_cls_token - x.shape[1], 1)
|
| 266 |
+
if self.if_cls_token:
|
| 267 |
+
visible_tokens = x[:, :-1, :]
|
| 268 |
+
else:
|
| 269 |
+
visible_tokens = x
|
| 270 |
+
x_ = torch.cat([visible_tokens, mask_tokens], dim=1) # no cls token
|
| 271 |
+
x_ = torch.gather(x_, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, x.shape[2])) # unshuffle
|
| 272 |
+
if self.if_cls_token:
|
| 273 |
+
x = torch.cat([x_, x[:, -1:, :]], dim=1) # append cls token
|
| 274 |
+
else:
|
| 275 |
+
x = x_
|
| 276 |
+
|
| 277 |
+
# add pos embed
|
| 278 |
+
x = x + self.decoder_pos_embed
|
| 279 |
+
|
| 280 |
+
# apply Mamba blocks
|
| 281 |
+
for blk in self.decoder_blocks:
|
| 282 |
+
x = blk(x)
|
| 283 |
+
|
| 284 |
+
# predictor projection
|
| 285 |
+
x = self.decoder_pred(x)
|
| 286 |
+
|
| 287 |
+
# remove cls token
|
| 288 |
+
if self.if_cls_token:
|
| 289 |
+
x = x[:, :-1, :]
|
| 290 |
+
return x
|
| 291 |
+
|
| 292 |
+
def forward_rec_loss(self, imgs, pred, mask):
|
| 293 |
+
"""
|
| 294 |
+
imgs: [N, 1, H, W]
|
| 295 |
+
pred: [N, L, p*p*1]
|
| 296 |
+
mask: [N, L], 0 is keep, 1 is remove,
|
| 297 |
+
"""
|
| 298 |
+
target = self.stride_patchify(imgs)
|
| 299 |
+
if self.norm_pix_loss:
|
| 300 |
+
mean = target.mean(dim=-1, keepdim=True)
|
| 301 |
+
var = target.var(dim=-1, keepdim=True)
|
| 302 |
+
target = (target - mean) / (var + 1.e-6) ** .5
|
| 303 |
+
|
| 304 |
+
loss = (pred - target) ** 2
|
| 305 |
+
loss = loss.mean(dim=-1) # [N, L], mean loss per patch
|
| 306 |
+
|
| 307 |
+
loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
|
| 308 |
+
return loss
|
| 309 |
+
|
| 310 |
+
def forward(self, imgs, mask_ratio=0.9, **kwargs):
|
| 311 |
+
# imgs: [B, 1, H, W]
|
| 312 |
+
B, C, H, W = imgs.shape
|
| 313 |
+
assert C == 1, "Input images should be grayscale"
|
| 314 |
+
if self.is_pretrain:
|
| 315 |
+
latent, mask, ids_restore = self.forward_encoder(imgs,
|
| 316 |
+
mask_ratio=mask_ratio,)
|
| 317 |
+
pred = self.forward_decoder(latent, ids_restore)
|
| 318 |
+
loss = self.forward_rec_loss(imgs, pred, mask)
|
| 319 |
+
return loss, pred, mask
|
| 320 |
+
else:
|
| 321 |
+
if self.return_attn:
|
| 322 |
+
x, attn_list = self.forward_encoder(imgs, mask_ratio=mask_ratio, if_mask=False)
|
| 323 |
+
if self.if_cls_token:
|
| 324 |
+
return self.head(x[:, -1, :]), attn_list
|
| 325 |
+
else:
|
| 326 |
+
return self.head(torch.mean(x, dim=1)), attn_list
|
| 327 |
+
else:
|
| 328 |
+
x = self.forward_encoder(imgs, mask_ratio=mask_ratio, if_mask=False)
|
| 329 |
+
if self.if_cls_token:
|
| 330 |
+
return self.head(x[:, -1, :])
|
| 331 |
+
else:
|
| 332 |
+
return self.head(torch.mean(x, dim=1))
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def net_bt_base_pretrain(**kwargs):
|
| 336 |
+
model = NetTransformer(
|
| 337 |
+
is_pretrain=True, embed_dim=192, depth=4,
|
| 338 |
+
decoder_embed_dim=128, decoder_depth=2, **kwargs)
|
| 339 |
+
return model
|
| 340 |
+
|
| 341 |
+
def net_bt_base_classifier(**kwargs):
|
| 342 |
+
model = NetTransformer(
|
| 343 |
+
is_pretrain=False, embed_dim=192, depth=4,
|
| 344 |
+
**kwargs)
|
| 345 |
+
return model
|
| 346 |
+
|
| 347 |
+
def net_bt_medium_pretrain(**kwargs):
|
| 348 |
+
model = NetTransformer(
|
| 349 |
+
is_pretrain=True, embed_dim=256, depth=4,
|
| 350 |
+
decoder_embed_dim=128, decoder_depth=2, **kwargs)
|
| 351 |
+
return model
|
| 352 |
+
|
| 353 |
+
def net_bt_meidum_classifier(**kwargs):
|
| 354 |
+
model = NetTransformer(
|
| 355 |
+
is_pretrain=False, embed_dim=256, depth=4,
|
| 356 |
+
**kwargs)
|
| 357 |
+
return model
|
| 358 |
+
|
| 359 |
+
def net_bgt_base_pretrain(**kwargs):
|
| 360 |
+
model = NetTransformer(
|
| 361 |
+
is_pretrain=True, embed_dim=192, depth=4,
|
| 362 |
+
decoder_embed_dim=128, decoder_depth=2, block_name="basic-gated", **kwargs)
|
| 363 |
+
return model
|
| 364 |
+
|
| 365 |
+
def net_bgt_base_classifier(**kwargs):
|
| 366 |
+
model = NetTransformer(
|
| 367 |
+
is_pretrain=False, embed_dim=192, depth=4, block_name="basic-gated",
|
| 368 |
+
**kwargs)
|
| 369 |
+
return model
|
| 370 |
+
|
| 371 |
+
def net_bgt_medium_pretrain(**kwargs):
|
| 372 |
+
model = NetTransformer(
|
| 373 |
+
is_pretrain=True, embed_dim=256, depth=4,
|
| 374 |
+
decoder_embed_dim=128, decoder_depth=2, block_name="basic-gated", **kwargs)
|
| 375 |
+
return model
|
| 376 |
+
|
| 377 |
+
def net_bgt_medium_classifier(**kwargs):
|
| 378 |
+
model = NetTransformer(
|
| 379 |
+
is_pretrain=False, embed_dim=256, depth=4, block_name="basic-gated",
|
| 380 |
+
**kwargs)
|
| 381 |
+
return model
|
| 382 |
+
|
| 383 |
+
def net_ft_base_pretrain(**kwargs):
|
| 384 |
+
model = NetTransformer(
|
| 385 |
+
is_pretrain=True, embed_dim=192, depth=4,
|
| 386 |
+
decoder_embed_dim=128, decoder_depth=2, block_name="flash", **kwargs)
|
| 387 |
+
return model
|
| 388 |
+
|
| 389 |
+
def net_ft_base_classifier(**kwargs):
|
| 390 |
+
model = NetTransformer(
|
| 391 |
+
is_pretrain=False, embed_dim=192, depth=4,
|
| 392 |
+
block_name="flash", **kwargs)
|
| 393 |
+
return model
|
| 394 |
+
|
| 395 |
+
def net_fgt_base_pretrain(**kwargs):
|
| 396 |
+
model = NetTransformer(
|
| 397 |
+
is_pretrain=True, embed_dim=192, depth=4,
|
| 398 |
+
decoder_embed_dim=128, decoder_depth=2, block_name="flash-gated", **kwargs)
|
| 399 |
+
return model
|
| 400 |
+
|
| 401 |
+
def net_fgt_base_classifier(**kwargs):
|
| 402 |
+
model = NetTransformer(
|
| 403 |
+
is_pretrain=False, embed_dim=192, depth=4,
|
| 404 |
+
block_name="flash-gated", **kwargs)
|
| 405 |
+
return model
|
| 406 |
+
|
| 407 |
+
def net_fgt_medium_pretrain(**kwargs):
|
| 408 |
+
model = NetTransformer(
|
| 409 |
+
is_pretrain=True, embed_dim=256, depth=4,
|
| 410 |
+
decoder_embed_dim=128, decoder_depth=2, block_name="flash-gated", **kwargs)
|
| 411 |
+
return model
|
| 412 |
+
|
| 413 |
+
def net_fgt_medium_classifier(**kwargs):
|
| 414 |
+
model = NetTransformer(
|
| 415 |
+
is_pretrain=False, embed_dim=256, depth=4,
|
| 416 |
+
block_name="flash-gated", **kwargs)
|
| 417 |
+
return model
|
| 418 |
+
|
| 419 |
+
def net_lt_base_pretrain(**kwargs):
|
| 420 |
+
model = NetTransformer(
|
| 421 |
+
is_pretrain=True, embed_dim=192, depth=4,
|
| 422 |
+
decoder_embed_dim=128, decoder_depth=2, block_name="linear", **kwargs)
|
| 423 |
+
return model
|
| 424 |
+
|
| 425 |
+
def net_lt_base_classifier(**kwargs):
|
| 426 |
+
model = NetTransformer(
|
| 427 |
+
is_pretrain=False, embed_dim=192, depth=4,
|
| 428 |
+
block_name="linear", **kwargs)
|
| 429 |
+
return model
|
| 430 |
+
|
| 431 |
+
def net_st_base_pretrain(**kwargs):
|
| 432 |
+
model = NetTransformer(
|
| 433 |
+
is_pretrain=True, embed_dim=192, depth=4,
|
| 434 |
+
decoder_embed_dim=128, decoder_depth=2, block_name="sparse",
|
| 435 |
+
if_cls_token=False, **kwargs)
|
| 436 |
+
return model
|
| 437 |
+
|
| 438 |
+
def net_st_base_classifier(**kwargs):
|
| 439 |
+
model = NetTransformer(
|
| 440 |
+
is_pretrain=False, embed_dim=192, depth=4,
|
| 441 |
+
block_name="sparse", if_cls_token=False, **kwargs)
|
| 442 |
+
return model
|