TETSU0701 commited on
Commit
6ede834
·
verified ·
1 Parent(s): 5bde5a1

Upload 5 files

Browse files
ctrans_model/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .ctranspath import CTransPath
2
+ from .dsmil import DSMIL
3
+ from .perceiver import Perceiver
4
+
5
+
6
+ __all__ = [
7
+ 'CTransPath',
8
+ 'DSMIL',
9
+ 'Perceiver',
10
+ ]
ctrans_model/ctranspath.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import nn
2
+
3
+ from .swin_transformer import SwinTransformer
4
+
5
+
6
+ def to_2tuple(x):
7
+ from itertools import repeat
8
+ import collections.abc
9
+ if isinstance(x, collections.abc.Iterable):
10
+ return x
11
+ return tuple(repeat(x, 2))
12
+
13
+
14
+ class ConvStem(nn.Module):
15
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
16
+ super().__init__()
17
+
18
+ assert patch_size == 4
19
+ assert embed_dim % 8 == 0
20
+
21
+ img_size = to_2tuple(img_size)
22
+ patch_size = to_2tuple(patch_size)
23
+ self.img_size = img_size
24
+ self.patch_size = patch_size
25
+ self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
26
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
27
+ self.flatten = flatten
28
+
29
+ stem = []
30
+ input_dim, output_dim = 3, embed_dim // 8
31
+ for l in range(2):
32
+ stem.append(nn.Conv2d(input_dim, output_dim, kernel_size=3, stride=2, padding=1, bias=False))
33
+ stem.append(nn.BatchNorm2d(output_dim))
34
+ stem.append(nn.ReLU(inplace=True))
35
+ input_dim = output_dim
36
+ output_dim *= 2
37
+ stem.append(nn.Conv2d(input_dim, embed_dim, kernel_size=1))
38
+ self.proj = nn.Sequential(*stem)
39
+
40
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
41
+
42
+ def forward(self, x):
43
+ B, C, H, W = x.shape
44
+ assert H == self.img_size[0] and W == self.img_size[1], \
45
+ f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
46
+ x = self.proj(x)
47
+ if self.flatten:
48
+ x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
49
+ x = self.norm(x)
50
+ return x
51
+
52
+
53
+ def CTransPath(
54
+ num_classes: int,
55
+ drop_rate: float = 0.,
56
+ drop_path_rate: float = 0.1,
57
+ ) -> nn.Module:
58
+ model = SwinTransformer(patch_size=4, window_size=7, embed_dim=96, depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24), embed_layer=ConvStem, drop_rate=drop_rate, drop_path_rate=drop_path_rate)
59
+ if num_classes == 0:
60
+ model.head = nn.Identity()
61
+ else:
62
+ model.head = nn.Linear(768, num_classes)
63
+
64
+ return model
ctrans_model/dsmil.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from torch.nn import functional as F
4
+
5
+
6
+ class DSMIL_Attention(nn.Module):
7
+ def __init__(self):
8
+ super().__init__()
9
+
10
+ # q(patch_num, size[2]), q_max(num_classes, size[2])
11
+ def forward(self, q, q_max):
12
+ attn = q @ q_max.transpose(1, 0) # (patch_num, num_classes)
13
+
14
+ return F.softmax(attn / torch.sqrt(torch.tensor(q.shape[1], dtype=torch.float32)), dim=0) # (patch_num, num_classes)
15
+
16
+
17
+ class DSMIL_BClassifier(nn.Module):
18
+ def __init__(self,
19
+ num_classes: int,
20
+ size = [768, 128, 128],
21
+ dropout: float = 0.5,
22
+ ):
23
+ super().__init__()
24
+
25
+ self.q = nn.Sequential(
26
+ nn.Linear(size[0], size[1]),
27
+ nn.ReLU(),
28
+ nn.Linear(size[1], size[2]),
29
+ nn.Tanh()
30
+ )
31
+ self.v = nn.Sequential(
32
+ nn.Dropout(dropout),
33
+ nn.Linear(size[0], size[0]),
34
+ nn.ReLU()
35
+ )
36
+ self.attention = DSMIL_Attention()
37
+ self.classifier = nn.Sequential(
38
+ nn.Dropout(dropout),
39
+ nn.Conv1d(num_classes, num_classes, kernel_size=size[0])
40
+ )
41
+
42
+ # x(patch_num, size[0]), inst_logits(patch_num, num_classes)
43
+ def forward(self, x, inst_logits):
44
+ v = self.v(x) # (patch_num, size[0])
45
+ q = self.q(x) # (patch_num, size[2])
46
+
47
+ _, idxs = torch.sort(inst_logits, dim=0, descending=True) # (patch_num, num_classes)
48
+ idxs = idxs[0] # (num_classes,)
49
+ x_sub = x[idxs] # (num_classes, size[0])
50
+ q_max = self.q(x_sub) # (num_classes, size[2])
51
+
52
+ attn = self.attention(q, q_max) # (patch_num, num_classes)
53
+
54
+ bag_feature = attn.transpose(1, 0) @ v # (num_classes, size[0])
55
+ bag_logits = self.classifier(bag_feature)[:, 0] # (num_classes,)
56
+
57
+ return bag_logits, attn, bag_feature
58
+
59
+
60
+ class DSMIL(nn.Module):
61
+ def __init__(self,
62
+ num_classes: int,
63
+ size = [768, 128, 128],
64
+ dropout: float = 0.5,
65
+ ):
66
+ super().__init__()
67
+
68
+ self.i_classifier = nn.Linear(size[0], num_classes)
69
+ self.b_classifier = DSMIL_BClassifier(num_classes, size, dropout)
70
+
71
+ def forward(self, x):
72
+ inst_logits = self.i_classifier(x)
73
+ bag_logits, attn, bag_feature = self.b_classifier(x, inst_logits)
74
+
75
+ # (num_classes,), (N, num_classes),
76
+ return bag_logits, inst_logits, attn, bag_feature
77
+
ctrans_model/perceiver.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import pi
2
+ from functools import wraps
3
+
4
+ from einops import rearrange, repeat
5
+ from einops.layers.torch import Reduce
6
+ import torch
7
+ from torch import nn, einsum
8
+ import torch.nn.functional as F
9
+
10
+
11
+ def print_trainable_parameters(model: torch.nn) -> None:
12
+ """Print number of trainable parameters."""
13
+ trainable_params = 0
14
+ all_param = 0
15
+ for _, param in model.named_parameters():
16
+ all_param += param.numel()
17
+ if param.requires_grad:
18
+ trainable_params += param.numel()
19
+ print(
20
+ f"trainable params: {trainable_params} || all params: {all_param}"
21
+ f" || trainable%: {100 * trainable_params / all_param:.2f}"
22
+ )
23
+
24
+
25
+ def exists(val):
26
+ return val is not None
27
+
28
+ def default(val, d):
29
+ return val if exists(val) else d
30
+
31
+ def cache_fn(f):
32
+ cache = dict()
33
+ @wraps(f)
34
+ def cached_fn(*args, _cache = True, key = None, **kwargs):
35
+ if not _cache:
36
+ return f(*args, **kwargs)
37
+ nonlocal cache
38
+ if key in cache:
39
+ return cache[key]
40
+ result = f(*args, **kwargs)
41
+ cache[key] = result
42
+ return result
43
+ return cached_fn
44
+
45
+ def fourier_encode(x, max_freq, num_bands = 4):
46
+ x = x.unsqueeze(-1)
47
+ device, dtype, orig_x = x.device, x.dtype, x
48
+
49
+ scales = torch.linspace(1., max_freq / 2, num_bands, device = device, dtype = dtype)
50
+ scales = scales[(*((None,) * (len(x.shape) - 1)), Ellipsis)]
51
+
52
+ x = x * scales * pi
53
+ x = torch.cat([x.sin(), x.cos()], dim = -1)
54
+ x = torch.cat((x, orig_x), dim = -1)
55
+ return x
56
+
57
+ # helper classes
58
+
59
+ class PreNorm(nn.Module):
60
+ def __init__(self, dim, fn, context_dim = None):
61
+ super().__init__()
62
+ self.fn = fn
63
+ self.norm = nn.LayerNorm(dim)
64
+ self.norm_context = nn.LayerNorm(context_dim) if exists(context_dim) else None
65
+
66
+ def forward(self, x, **kwargs):
67
+ x = self.norm(x)
68
+
69
+ if exists(self.norm_context):
70
+ context = kwargs['context']
71
+ normed_context = self.norm_context(context)
72
+ kwargs.update(context = normed_context)
73
+
74
+ return self.fn(x, **kwargs)
75
+
76
+ class GEGLU(nn.Module):
77
+ def forward(self, x):
78
+ x, gates = x.chunk(2, dim = -1)
79
+ return x * F.gelu(gates)
80
+
81
+ class FeedForward(nn.Module):
82
+ def __init__(self, dim, mult = 4, dropout = 0.):
83
+ super().__init__()
84
+ self.net = nn.Sequential(
85
+ nn.Linear(dim, dim * mult * 2),
86
+ GEGLU(),
87
+ nn.Linear(dim * mult, dim),
88
+ nn.Dropout(dropout)
89
+ )
90
+
91
+ def forward(self, x):
92
+ return self.net(x)
93
+
94
+ class Attention(nn.Module):
95
+ def __init__(self, query_dim, context_dim = None, heads = 8, dim_head = 64, dropout = 0., scale=None):
96
+ super().__init__()
97
+ inner_dim = dim_head * heads
98
+ context_dim = default(context_dim, query_dim)
99
+ if scale:
100
+ self.scale = scale #**-1
101
+ else:
102
+ self.scale = dim_head ** -0.5
103
+ self.heads = heads
104
+
105
+ self.to_q = nn.Linear(query_dim, inner_dim, bias = False)
106
+ self.to_kv = nn.Linear(context_dim, inner_dim * 2, bias = False)
107
+
108
+ self.dropout = nn.Dropout(dropout)
109
+ self.to_out = nn.Linear(inner_dim, query_dim)
110
+
111
+ def forward(self, x, context=None, mask=None):
112
+ h = self.heads
113
+
114
+ q = self.to_q(x)
115
+ context = default(context, x)
116
+ k, v = self.to_kv(context).chunk(2, dim = -1)
117
+
118
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h = h), (q, k, v))
119
+
120
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
121
+
122
+ if exists(mask):
123
+ mask = rearrange(mask, 'b ... -> b (...)')
124
+ max_neg_value = -torch.finfo(sim.dtype).max
125
+ mask = repeat(mask, 'b j -> (b h) () j', h = h)
126
+ sim.masked_fill_(~mask, max_neg_value)
127
+
128
+ # attention, what we cannot get enough of
129
+ A = sim.softmax(dim = -1)
130
+ attn = self.dropout(A)
131
+
132
+ out = einsum('b i j, b j d -> b i d', attn, v)
133
+ out = rearrange(out, '(b h) n d -> b n (h d)', h = h)
134
+
135
+ if context.shape != x.shape:
136
+ return self.to_out(out), A
137
+ else:
138
+ return self.to_out(out)
139
+
140
+
141
+ class DualQueryCrossAttention(nn.Module):
142
+ def __init__(self, query_dim, context_dim = None, heads = 8, dim_head = 64, dropout = 0., scale=None):
143
+ super().__init__()
144
+ inner_dim = dim_head * heads
145
+ context_dim = default(context_dim, query_dim)
146
+ if scale:
147
+ self.scale = nn.Parameter(torch.tensor([scale])) #**-1
148
+ else:
149
+ self.scale = dim_head ** -0.5
150
+ self.heads = heads
151
+
152
+ self.to_q = nn.Linear(query_dim, inner_dim, bias = False)
153
+ self.to_kv = nn.Linear(context_dim, inner_dim * 2, bias = False)
154
+
155
+ self.dropout = nn.Dropout(dropout)
156
+ self.to_out = nn.Linear(inner_dim, query_dim)
157
+
158
+ # Attention ranking
159
+ self.to_score_q = nn.Linear(query_dim, inner_dim, bias = False)
160
+ self.to_score_out = nn.Linear(inner_dim, query_dim)
161
+
162
+ def forward(self, x, score_x, context=None, mask=None):
163
+ h = self.heads
164
+
165
+ q = self.to_q(x)
166
+ score_q = self.to_score_q(score_x)
167
+ k, v = self.to_kv(context).chunk(2, dim = -1)
168
+
169
+ q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h = h), (q, k, v))
170
+
171
+ sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
172
+
173
+ score_sim = einsum('b i d, b j d -> b i j', score_q, k) * self.scale
174
+
175
+ if exists(mask):
176
+ mask = rearrange(mask, 'b ... -> b (...)')
177
+ max_neg_value = -torch.finfo(sim.dtype).max
178
+ mask = repeat(mask, 'b j -> (b h) () j', h = h)
179
+ sim.masked_fill_(~mask, max_neg_value)
180
+
181
+ # attention, what we cannot get enough of
182
+ A = sim.softmax(dim = -1)
183
+ attn = self.dropout(A)
184
+
185
+ score_attn = score_sim.softmax(dim = -1)
186
+
187
+ out = einsum('b i j, b j d -> b i d', attn, v)
188
+ out = rearrange(out, '(b h) n d -> b n (h d)', h = h)
189
+
190
+ score_out = einsum('b i j, b j d -> b i d', score_attn, v)
191
+ score_out = rearrange(score_out, '(b h) n d -> b n (h d)', h = h)
192
+
193
+ return self.to_out(out), A, self.to_score_out(score_out), score_attn
194
+
195
+
196
+ # Based on the merging approach from Truong et al. "How Transferable are Self-supervised Features in Medical Image Classification Tasks?"
197
+ class Merger(nn.Module):
198
+ def __init__(self, proj_dim):
199
+ super(Merger, self).__init__()
200
+
201
+ self.vit_head = nn.Linear(384, proj_dim)
202
+ self.swin_head = nn.Linear(768, proj_dim)
203
+ self.swav_head = nn.Linear(2048, proj_dim)
204
+
205
+
206
+ def forward(self, data):
207
+ vit_out = self.vit_head(data['vit_feats'])
208
+ swin_out = self.swin_head(data['swin_feats'])
209
+ swav_out = self.swav_head(data['swav_feats'])
210
+
211
+ joint = torch.cat([vit_out, swin_out, swav_out], dim=-1)
212
+ return joint
213
+
214
+
215
+ class Perceiver(nn.Module):
216
+ def __init__(
217
+ self,
218
+ *,
219
+ num_freq_bands,
220
+ depth,
221
+ max_freq,
222
+ input_channels = 3,
223
+ input_axis = 2,
224
+ num_latents = 1024,
225
+ latent_dim = 512,
226
+ cross_heads = 1,
227
+ latent_heads = 8,
228
+ cross_dim_head = 64,
229
+ latent_dim_head = 64,
230
+ n_classes = 1000,
231
+ attn_dropout = 0.,
232
+ ff_dropout = 0.,
233
+ weight_tie_layers = False,
234
+ fourier_encode_data = True,
235
+ self_per_cross_attn = 1,
236
+ latent_bounds = 2,
237
+ scale = None,
238
+ ):
239
+ """The shape of the final attention mechanism will be:
240
+ depth * (cross attention -> self_per_cross_attn * self attention)
241
+
242
+ Args:
243
+ num_freq_bands: Number of freq bands, with original value (2 * K + 1)
244
+ depth: Depth of net.
245
+ max_freq: Maximum frequency, hyperparameter depending on how
246
+ fine the data is.
247
+ freq_base: Base for the frequency
248
+ input_channels: Number of channels for each token of the input.
249
+ input_axis: Number of axes for input data (2 for images, 3 for video)
250
+ num_latents: Number of latents, or induced set points, or centroids.
251
+ Different papers giving it different names.
252
+ latent_dim: Latent dimension.
253
+ cross_heads: Number of heads for cross attention. Paper said 1.
254
+ latent_heads: Number of heads for latent self attention, 8.
255
+ cross_dim_head: Number of dimensions per cross attention head.
256
+ latent_dim_head: Number of dimensions per latent self attention head.
257
+ num_classes: Output number of classes.
258
+ attn_dropout: Attention dropout
259
+ ff_dropout: Feedforward dropout
260
+ weight_tie_layers: Whether to weight tie layers (optional).
261
+ fourier_encode_data: Whether to auto-fourier encode the data, using
262
+ the input_axis given. defaults to True, but can be turned off
263
+ if you are fourier encoding the data yourself.
264
+ self_per_cross_attn: Number of self attention blocks per cross attn.
265
+ final_classifier_head: mean pool and project embeddings to number of classes (num_classes) at the end
266
+ """
267
+ super().__init__()
268
+ self.input_axis = input_axis
269
+ self.max_freq = max_freq
270
+ self.num_freq_bands = num_freq_bands
271
+ self.n_classes = n_classes
272
+
273
+ self.fourier_encode_data = fourier_encode_data
274
+ fourier_channels = (input_axis * ((num_freq_bands * 2) + 1)) if fourier_encode_data else 0
275
+ self.proj_embeddings = nn.Identity()
276
+ input_dim = fourier_channels + input_channels
277
+
278
+ self.latents = nn.Parameter(
279
+ torch.nn.init.trunc_normal_(
280
+ torch.zeros((num_latents, latent_dim)),
281
+ mean=0,
282
+ std=0.02,
283
+ a=-latent_bounds,
284
+ b=latent_bounds))
285
+
286
+
287
+ self.score_latents = nn.Parameter(
288
+ torch.nn.init.trunc_normal_(
289
+ torch.zeros((1, latent_dim)),
290
+ mean=0,
291
+ std=0.02,
292
+ a=-latent_bounds,
293
+ b=latent_bounds))
294
+
295
+ # Cross-Attention Layer
296
+ get_cross_attn = lambda: PreNorm(latent_dim, DualQueryCrossAttention(latent_dim, input_dim, heads = cross_heads, dim_head = cross_dim_head, dropout = attn_dropout, scale=scale), context_dim = input_dim) #new
297
+ get_cross_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout))
298
+ get_mil_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout))
299
+
300
+
301
+ get_latent_attn = lambda: PreNorm(latent_dim, Attention(latent_dim, heads = latent_heads, dim_head = latent_dim_head, dropout = attn_dropout))
302
+ get_latent_ff = lambda: PreNorm(latent_dim, FeedForward(latent_dim, dropout = ff_dropout))
303
+
304
+ get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff, get_mil_ff = map(cache_fn, (get_cross_attn, get_cross_ff, get_latent_attn, get_latent_ff, get_mil_ff))
305
+
306
+ self.layers = nn.ModuleList([])
307
+ for i in range(depth):
308
+ should_cache = i > 0 and weight_tie_layers
309
+ cache_args = {'_cache': should_cache}
310
+
311
+ self_attns = nn.ModuleList([])
312
+
313
+ for block_ind in range(self_per_cross_attn):
314
+ self_attns.append(nn.ModuleList([
315
+ get_latent_attn(**cache_args, key = block_ind),
316
+ get_latent_ff(**cache_args, key = block_ind)
317
+ ]))
318
+ self.layers.append(nn.ModuleList([
319
+ get_cross_attn(**cache_args),
320
+ get_cross_ff(**cache_args),
321
+ get_mil_ff(**cache_args),
322
+ self_attns
323
+ ]))
324
+
325
+ self.to_logits = nn.Sequential(
326
+ Reduce('b n d -> b d', 'mean'),
327
+ nn.LayerNorm(latent_dim),
328
+ nn.Linear(latent_dim, n_classes)
329
+ )
330
+
331
+ self.to_score_logits = nn.Sequential(
332
+ Reduce('b n d -> b d', 'mean'),
333
+ nn.LayerNorm(latent_dim),
334
+ nn.Linear(latent_dim, n_classes)
335
+ )
336
+
337
+ def forward(
338
+ self,
339
+ data,
340
+ mask = None,
341
+ return_embeddings = False,
342
+ ):
343
+ data = self.proj_embeddings(data)
344
+
345
+
346
+ if len(data.shape)==2: # flops
347
+ data= data.unsqueeze(0) # flops
348
+ b, *axis, _, device, dtype = *data.shape, data.device, data.dtype
349
+ assert len(axis) == self.input_axis, 'input data must have the right number of axis'
350
+
351
+ if self.fourier_encode_data:
352
+ # calculate fourier encoded positions in the range of [-1, 1], for all axis
353
+
354
+ axis_pos = list(map(lambda size: torch.linspace(-1., 1., steps=size, device=device, dtype=dtype), axis))
355
+ pos = torch.stack(torch.meshgrid(*axis_pos, indexing = 'ij'), dim = -1)
356
+ enc_pos = fourier_encode(pos, self.max_freq, self.num_freq_bands)
357
+ enc_pos = rearrange(enc_pos, '... n d -> ... (n d)')
358
+ enc_pos = repeat(enc_pos, '... -> b ...', b = b)
359
+
360
+ data = torch.cat((data, enc_pos), dim = -1)
361
+
362
+ # concat to channels of data and flatten axis
363
+ data = rearrange(data, 'b ... d -> b (...) d')
364
+
365
+ x = repeat(self.latents, 'n d -> b n d', b = b)
366
+
367
+
368
+ score_x = repeat(self.score_latents, 'n d -> b n d', b = b)
369
+
370
+ # layers
371
+ for cross_attn, cross_ff, mil_ff, self_attns in self.layers:
372
+ x_attn, A_raw, score_x_attn, score_A = cross_attn(x=x, score_x=score_x, context=data, mask=mask)
373
+ x = x_attn + x
374
+ x = cross_ff(x) + x
375
+ score_x = score_x_attn + score_x
376
+ score_x = mil_ff(score_x) + score_x
377
+
378
+ for self_attn, self_ff in self_attns:
379
+ x = self_attn(x) + x
380
+ x = self_ff(x) + x
381
+
382
+ # to logits
383
+ logits = self.to_logits(x)
384
+ results_dict={'student_logits':self.to_score_logits(score_x), 'features_teacher':x, 'features_student':score_x}
385
+ Y_hat = torch.argmax(logits, dim=1)
386
+ Y_prob = F.softmax(logits, dim = 1)
387
+
388
+ return logits, Y_prob, Y_hat, score_A, results_dict
389
+
ctrans_model/swin_transformer.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import math
4
+ import warnings
5
+
6
+ from typing import Optional
7
+
8
+
9
+ def to_2tuple(x):
10
+ from itertools import repeat
11
+ import collections.abc
12
+ if isinstance(x, collections.abc.Iterable):
13
+ return x
14
+ return tuple(repeat(x, 2))
15
+
16
+ class Mlp(nn.Module):
17
+ """ MLP as used in Vision Transformer, MLP-Mixer and related networks
18
+ """
19
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
20
+ super().__init__()
21
+ out_features = out_features or in_features
22
+ hidden_features = hidden_features or in_features
23
+ drop_probs = to_2tuple(drop)
24
+
25
+ self.fc1 = nn.Linear(in_features, hidden_features)
26
+ self.act = act_layer()
27
+ self.drop1 = nn.Dropout(drop_probs[0])
28
+ self.fc2 = nn.Linear(hidden_features, out_features)
29
+ self.drop2 = nn.Dropout(drop_probs[1])
30
+
31
+ def forward(self, x):
32
+ x = self.fc1(x)
33
+ x = self.act(x)
34
+ x = self.drop1(x)
35
+ x = self.fc2(x)
36
+ x = self.drop2(x)
37
+ return x
38
+
39
+
40
+ def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep: bool = True):
41
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
42
+
43
+ This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
44
+ the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
45
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
46
+ changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
47
+ 'survival rate' as the argument.
48
+
49
+ """
50
+ if drop_prob == 0. or not training:
51
+ return x
52
+ keep_prob = 1 - drop_prob
53
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
54
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
55
+ if keep_prob > 0.0 and scale_by_keep:
56
+ random_tensor.div_(keep_prob)
57
+ return x * random_tensor
58
+
59
+
60
+ class DropPath(nn.Module):
61
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
62
+ """
63
+ def __init__(self, drop_prob=None, scale_by_keep=True):
64
+ super(DropPath, self).__init__()
65
+ self.drop_prob = drop_prob
66
+ self.scale_by_keep = scale_by_keep
67
+
68
+ def forward(self, x):
69
+ return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
70
+
71
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=-2.):
72
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
73
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
74
+ def norm_cdf(x):
75
+ # Computes standard normal cumulative distribution function
76
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
77
+
78
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
79
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
80
+ "The distribution of values may be incorrect.",
81
+ stacklevel=2)
82
+
83
+ with torch.no_grad():
84
+ # Values are generated by using a truncated uniform distribution and
85
+ # then using the inverse CDF for the normal distribution.
86
+ # Get upper and lower cdf values
87
+ l = norm_cdf((a - mean) / std)
88
+ u = norm_cdf((b - mean) / std)
89
+
90
+ # Uniformly fill tensor with values from [l, u], then translate to
91
+ # [2l-1, 2u-1].
92
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
93
+
94
+ # Use inverse cdf transform for normal distribution to get truncated
95
+ # standard normal
96
+ tensor.erfinv_()
97
+
98
+ # Transform to proper mean, std
99
+ tensor.mul_(std * math.sqrt(2.))
100
+ tensor.add_(mean)
101
+
102
+ # Clamp to ensure it's in the proper range
103
+ tensor.clamp_(min=a, max=b)
104
+ return tensor
105
+
106
+
107
+ def window_partition(x, window_size: int):
108
+ """
109
+ Args:
110
+ x: (B, H, W, C)
111
+ window_size (int): window size
112
+
113
+ Returns:
114
+ windows: (num_windows*B, window_size, window_size, C)
115
+ """
116
+ B, H, W, C = x.shape
117
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
118
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
119
+ return windows
120
+
121
+
122
+ def window_reverse(windows, window_size: int, H: int, W: int):
123
+ """
124
+ Args:
125
+ windows: (num_windows*B, window_size, window_size, C)
126
+ window_size (int): Window size
127
+ H (int): Height of image
128
+ W (int): Width of image
129
+
130
+ Returns:
131
+ x: (B, H, W, C)
132
+ """
133
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
134
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
135
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
136
+ return x
137
+
138
+ class WindowAttention(nn.Module):
139
+ r""" Window based multi-head self attention (W-MSA) module with relative position bias.
140
+ It supports both of shifted and non-shifted window.
141
+
142
+ Args:
143
+ dim (int): Number of input channels.
144
+ window_size (tuple[int]): The height and width of the window.
145
+ num_heads (int): Number of attention heads.
146
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
147
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
148
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
149
+ """
150
+
151
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0., proj_drop=0.):
152
+
153
+ super().__init__()
154
+ self.dim = dim
155
+ self.window_size = window_size # Wh, Ww
156
+ self.num_heads = num_heads
157
+ head_dim = dim // num_heads
158
+ self.scale = head_dim ** -0.5
159
+
160
+ # define a parameter table of relative position bias
161
+ self.relative_position_bias_table = nn.Parameter(
162
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
163
+
164
+ # get pair-wise relative position index for each token inside the window
165
+ coords_h = torch.arange(self.window_size[0])
166
+ coords_w = torch.arange(self.window_size[1])
167
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
168
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
169
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
170
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
171
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
172
+ relative_coords[:, :, 1] += self.window_size[1] - 1
173
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
174
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
175
+ self.register_buffer("relative_position_index", relative_position_index)
176
+
177
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
178
+ self.attn_drop = nn.Dropout(attn_drop)
179
+ self.proj = nn.Linear(dim, dim)
180
+ self.proj_drop = nn.Dropout(proj_drop)
181
+
182
+ trunc_normal_(self.relative_position_bias_table, std=.02)
183
+ self.softmax = nn.Softmax(dim=-1)
184
+
185
+ def forward(self, x, mask: Optional[torch.Tensor] = None):
186
+ """
187
+ Args:
188
+ x: input features with shape of (num_windows*B, N, C)
189
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
190
+ """
191
+ B_, N, C = x.shape
192
+ qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
193
+ q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
194
+
195
+ q = q * self.scale
196
+ attn = (q @ k.transpose(-2, -1))
197
+
198
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
199
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
200
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
201
+ attn = attn + relative_position_bias.unsqueeze(0)
202
+
203
+ if mask is not None:
204
+ nW = mask.shape[0]
205
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
206
+ attn = attn.view(-1, self.num_heads, N, N)
207
+ attn = self.softmax(attn)
208
+ else:
209
+ attn = self.softmax(attn)
210
+
211
+ attn = self.attn_drop(attn)
212
+
213
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
214
+ x = self.proj(x)
215
+ x = self.proj_drop(x)
216
+ return x
217
+
218
+
219
+ class SwinTransformerBlock(nn.Module):
220
+ r""" Swin Transformer Block.
221
+
222
+ Args:
223
+ dim (int): Number of input channels.
224
+ input_resolution (tuple[int]): Input resulotion.
225
+ num_heads (int): Number of attention heads.
226
+ window_size (int): Window size.
227
+ shift_size (int): Shift size for SW-MSA.
228
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
229
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
230
+ drop (float, optional): Dropout rate. Default: 0.0
231
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
232
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
233
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
234
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
235
+ """
236
+
237
+ def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
238
+ mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0., drop_path=0.,
239
+ act_layer=nn.GELU, norm_layer=nn.LayerNorm):
240
+ super().__init__()
241
+ self.dim = dim
242
+ self.input_resolution = input_resolution
243
+ self.num_heads = num_heads
244
+ self.window_size = window_size
245
+ self.shift_size = shift_size
246
+ self.mlp_ratio = mlp_ratio
247
+ if min(self.input_resolution) <= self.window_size:
248
+ # if window size is larger than input resolution, we don't partition windows
249
+ self.shift_size = 0
250
+ self.window_size = min(self.input_resolution)
251
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
252
+
253
+ self.norm1 = norm_layer(dim)
254
+ self.attn = WindowAttention(
255
+ dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, qkv_bias=qkv_bias,
256
+ attn_drop=attn_drop, proj_drop=drop)
257
+
258
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
259
+ self.norm2 = norm_layer(dim)
260
+ mlp_hidden_dim = int(dim * mlp_ratio)
261
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
262
+
263
+ if self.shift_size > 0:
264
+ # calculate attention mask for SW-MSA
265
+ H, W = self.input_resolution
266
+ img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
267
+ h_slices = (slice(0, -self.window_size),
268
+ slice(-self.window_size, -self.shift_size),
269
+ slice(-self.shift_size, None))
270
+ w_slices = (slice(0, -self.window_size),
271
+ slice(-self.window_size, -self.shift_size),
272
+ slice(-self.shift_size, None))
273
+ cnt = 0
274
+ for h in h_slices:
275
+ for w in w_slices:
276
+ img_mask[:, h, w, :] = cnt
277
+ cnt += 1
278
+
279
+ mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
280
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
281
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
282
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
283
+ else:
284
+ attn_mask = None
285
+
286
+ self.register_buffer("attn_mask", attn_mask)
287
+
288
+ def forward(self, x):
289
+ H, W = self.input_resolution
290
+ B, L, C = x.shape
291
+
292
+ shortcut = x
293
+ x = self.norm1(x)
294
+ x = x.view(B, H, W, C)
295
+
296
+ # cyclic shift
297
+ if self.shift_size > 0:
298
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
299
+ else:
300
+ shifted_x = x
301
+
302
+ # partition windows
303
+ x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
304
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
305
+
306
+ # W-MSA/SW-MSA
307
+ attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
308
+
309
+ # merge windows
310
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
311
+ shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
312
+
313
+ # reverse cyclic shift
314
+ if self.shift_size > 0:
315
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
316
+ else:
317
+ x = shifted_x
318
+ x = x.view(B, H * W, C)
319
+
320
+ # FFN
321
+ x = shortcut + self.drop_path(x)
322
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
323
+
324
+ return x
325
+
326
+
327
+ class BasicLayer(nn.Module):
328
+ """ A basic Swin Transformer layer for one stage.
329
+
330
+ Args:
331
+ dim (int): Number of input channels.
332
+ input_resolution (tuple[int]): Input resolution.
333
+ depth (int): Number of blocks.
334
+ num_heads (int): Number of attention heads.
335
+ window_size (int): Local window size.
336
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
337
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
338
+ drop (float, optional): Dropout rate. Default: 0.0
339
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
340
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
341
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
342
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
343
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
344
+ """
345
+
346
+ def __init__(self, dim, input_resolution, depth, num_heads, window_size,
347
+ mlp_ratio=4., qkv_bias=True, drop=0., attn_drop=0.,
348
+ drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
349
+
350
+ super().__init__()
351
+ self.dim = dim
352
+ self.input_resolution = input_resolution
353
+ self.depth = depth
354
+ self.use_checkpoint = use_checkpoint
355
+
356
+ # build blocks
357
+ self.blocks = nn.ModuleList([
358
+ SwinTransformerBlock(
359
+ dim=dim, input_resolution=input_resolution, num_heads=num_heads, window_size=window_size,
360
+ shift_size=0 if (i % 2 == 0) else window_size // 2, mlp_ratio=mlp_ratio,
361
+ qkv_bias=qkv_bias, drop=drop, attn_drop=attn_drop,
362
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, norm_layer=norm_layer)
363
+ for i in range(depth)])
364
+
365
+ # patch merging layer
366
+ if downsample is not None:
367
+ self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
368
+ else:
369
+ self.downsample = None
370
+
371
+ def forward(self, x):
372
+ for blk in self.blocks:
373
+ x = blk(x)
374
+ if self.downsample is not None:
375
+ x = self.downsample(x)
376
+ return x
377
+
378
+ def extra_repr(self) -> str:
379
+ return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
380
+
381
+
382
+ class PatchMerging(nn.Module):
383
+ r""" Patch Merging Layer.
384
+
385
+ Args:
386
+ input_resolution (tuple[int]): Resolution of input feature.
387
+ dim (int): Number of input channels.
388
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
389
+ """
390
+
391
+ def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
392
+ super().__init__()
393
+ self.input_resolution = input_resolution
394
+ self.dim = dim
395
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
396
+ self.norm = norm_layer(4 * dim)
397
+
398
+ def forward(self, x):
399
+ """
400
+ x: B, H*W, C
401
+ """
402
+ H, W = self.input_resolution
403
+ B, L, C = x.shape
404
+
405
+ x = x.view(B, H, W, C)
406
+
407
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
408
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
409
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
410
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
411
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
412
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
413
+
414
+ x = self.norm(x)
415
+ x = self.reduction(x)
416
+
417
+ return x
418
+
419
+ def extra_repr(self) -> str:
420
+ return f"input_resolution={self.input_resolution}, dim={self.dim}"
421
+
422
+ def flops(self):
423
+ H, W = self.input_resolution
424
+ flops = H * W * self.dim
425
+ flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
426
+ return flops
427
+
428
+
429
+ class PatchEmbed(nn.Module):
430
+ """ 2D Image to Patch Embedding
431
+ """
432
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, norm_layer=None, flatten=True):
433
+ super().__init__()
434
+ img_size = to_2tuple(img_size)
435
+ patch_size = to_2tuple(patch_size)
436
+ self.img_size = img_size
437
+ self.patch_size = patch_size
438
+ self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
439
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
440
+ self.flatten = flatten
441
+
442
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
443
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
444
+
445
+ def forward(self, x):
446
+ B, C, H, W = x.shape
447
+ x = self.proj(x)
448
+ if self.flatten:
449
+ x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
450
+ x = self.norm(x)
451
+ return x
452
+
453
+
454
+ class SwinTransformer(nn.Module):
455
+ r""" Swin Transformer
456
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
457
+ https://arxiv.org/pdf/2103.14030
458
+
459
+ Args:
460
+ img_size (int | tuple(int)): Input image size. Default 224
461
+ patch_size (int | tuple(int)): Patch size. Default: 4
462
+ in_chans (int): Number of input image channels. Default: 3
463
+ num_classes (int): Number of classes for classification head. Default: 1000
464
+ embed_dim (int): Patch embedding dimension. Default: 96
465
+ depths (tuple(int)): Depth of each Swin Transformer layer.
466
+ num_heads (tuple(int)): Number of attention heads in different layers.
467
+ window_size (int): Window size. Default: 7
468
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
469
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
470
+ drop_rate (float): Dropout rate. Default: 0
471
+ attn_drop_rate (float): Attention dropout rate. Default: 0
472
+ drop_path_rate (float): Stochastic depth rate. Default: 0.1
473
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
474
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
475
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True
476
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
477
+ """
478
+
479
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, num_classes=1000,
480
+ embed_dim=96, depths=(2, 2, 6, 2), num_heads=(3, 6, 12, 24),
481
+ window_size=7, mlp_ratio=4., qkv_bias=True,
482
+ drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
483
+ norm_layer=nn.LayerNorm, ape=False, patch_norm=True,embed_layer=PatchEmbed,
484
+ use_checkpoint=False, weight_init='', **kwargs):
485
+ super().__init__()
486
+
487
+ self.num_classes = num_classes
488
+ self.num_layers = len(depths)
489
+ self.embed_dim = embed_dim
490
+ self.ape = ape
491
+ self.patch_norm = patch_norm
492
+ self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))
493
+ self.mlp_ratio = mlp_ratio
494
+
495
+ # split image into non-overlapping patches
496
+ self.patch_embed = embed_layer(
497
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,
498
+ norm_layer=norm_layer if self.patch_norm else None)
499
+ num_patches = self.patch_embed.num_patches
500
+ self.patch_grid = self.patch_embed.grid_size
501
+
502
+ # absolute position embedding
503
+ if self.ape:
504
+ self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
505
+ trunc_normal_(self.absolute_pos_embed, std=.02)
506
+ else:
507
+ self.absolute_pos_embed = None
508
+
509
+ self.pos_drop = nn.Dropout(p=drop_rate)
510
+
511
+ # stochastic depth
512
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
513
+
514
+ # build layers
515
+ layers = []
516
+ for i_layer in range(self.num_layers):
517
+ layers += [BasicLayer(
518
+ dim=int(embed_dim * 2 ** i_layer),
519
+ input_resolution=(self.patch_grid[0] // (2 ** i_layer), self.patch_grid[1] // (2 ** i_layer)),
520
+ depth=depths[i_layer],
521
+ num_heads=num_heads[i_layer],
522
+ window_size=window_size,
523
+ mlp_ratio=self.mlp_ratio,
524
+ qkv_bias=qkv_bias,
525
+ drop=drop_rate,
526
+ attn_drop=attn_drop_rate,
527
+ drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],
528
+ norm_layer=norm_layer,
529
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
530
+ use_checkpoint=use_checkpoint)
531
+ ]
532
+ self.layers = nn.Sequential(*layers)
533
+
534
+ self.norm = norm_layer(self.num_features)
535
+ self.avgpool = nn.AdaptiveAvgPool1d(1)
536
+ self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
537
+
538
+ def forward_features(self, x):
539
+ x = self.patch_embed(x)
540
+ if self.absolute_pos_embed is not None:
541
+ x = x + self.absolute_pos_embed
542
+ x = self.pos_drop(x)
543
+
544
+ for layer in self.layers:
545
+ x = layer(x)
546
+ x = self.norm(x) # B L C
547
+ x = self.avgpool(x.transpose(1, 2)) # B C 1
548
+ x = torch.flatten(x, 1)
549
+
550
+ return x
551
+
552
+ def forward(self, x):
553
+ x = self.forward_features(x)
554
+ x = self.head(x)
555
+ return x
556
+