Gabriele Campanella commited on
Commit
fd277fe
1 Parent(s): 7dad98b

first commit

Browse files
Files changed (2) hide show
  1. README.md +55 -0
  2. vision_transformer.py +329 -0
README.md CHANGED
@@ -1,3 +1,58 @@
1
  ---
2
  license: cc-by-nc-sa-4.0
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: cc-by-nc-sa-4.0
3
+ language:
4
+ - en
5
+ pipeline_tag: image-feature-extraction
6
+ tags:
7
+ - pathology
8
+ - foundation_model
9
+ - vit
10
  ---
11
+
12
+ # SP85M
13
+
14
+ ViT-base (85M parameters) trained on 423,000 H&E slides from the Mount Sinai Health System.
15
+
16
+ ## Model Usage
17
+
18
+ To get started, first clone the repository with this command:
19
+ ```bash
20
+ git clone --no-checkout https://huggingface.co/MountSinaiCompPath/SP85M && cd SP85M && git sparse-checkout init --no-cone && git sparse-checkout set '/*' '!*.bin' && git checkout
21
+ ```
22
+
23
+ Now you can use the following code:
24
+ ```python
25
+ from PIL import Image
26
+ import numpy as np
27
+ import vision_transformer
28
+ import torch
29
+ import torch.nn as nn
30
+ import torchvision.transforms as transforms
31
+ from huggingface_hub import PyTorchModelHubMixin
32
+
33
+ class SP85M(nn.Module, PyTorchModelHubMixin):
34
+ def __init__(self):
35
+ super().__init__()
36
+ self.encoder = vision_transformer.vit_small(num_classes=0)
37
+
38
+ def forward(self, x):
39
+ return self.encoder(x)
40
+
41
+ # Download up model
42
+ model = SP85M.from_pretrained("MountSinaiCompPath/SP85M")
43
+
44
+ # Set up transform
45
+ transform = transforms.Compose([
46
+ transforms.ToTensor(),
47
+ transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
48
+ ])
49
+
50
+ # Image
51
+ img = np.random.randint(0, 256, size=224*224*3).reshape(224,224,3).astype(np.uint8)
52
+ img = Image.fromarray(img)
53
+ img = transform(img).unsqueeze(0)
54
+
55
+ # Inference
56
+ with torch.no_grad():
57
+ h = model(img)
58
+ ```
vision_transformer.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Mostly copy-paste from timm library.
16
+ https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
17
+ """
18
+ import math
19
+ from functools import partial
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+
25
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
26
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
27
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
28
+ def norm_cdf(x):
29
+ # Computes standard normal cumulative distribution function
30
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
31
+
32
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
33
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
34
+ "The distribution of values may be incorrect.",
35
+ stacklevel=2)
36
+
37
+ with torch.no_grad():
38
+ # Values are generated by using a truncated uniform distribution and
39
+ # then using the inverse CDF for the normal distribution.
40
+ # Get upper and lower cdf values
41
+ l = norm_cdf((a - mean) / std)
42
+ u = norm_cdf((b - mean) / std)
43
+
44
+ # Uniformly fill tensor with values from [l, u], then translate to
45
+ # [2l-1, 2u-1].
46
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
47
+
48
+ # Use inverse cdf transform for normal distribution to get truncated
49
+ # standard normal
50
+ tensor.erfinv_()
51
+
52
+ # Transform to proper mean, std
53
+ tensor.mul_(std * math.sqrt(2.))
54
+ tensor.add_(mean)
55
+
56
+ # Clamp to ensure it's in the proper range
57
+ tensor.clamp_(min=a, max=b)
58
+ return tensor
59
+
60
+
61
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
62
+ # type: (Tensor, float, float, float, float) -> Tensor
63
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
64
+
65
+ def drop_path(x, drop_prob: float = 0., training: bool = False):
66
+ if drop_prob == 0. or not training:
67
+ return x
68
+ keep_prob = 1 - drop_prob
69
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
70
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
71
+ random_tensor.floor_() # binarize
72
+ output = x.div(keep_prob) * random_tensor
73
+ return output
74
+
75
+
76
+ class DropPath(nn.Module):
77
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
78
+ """
79
+ def __init__(self, drop_prob=None):
80
+ super(DropPath, self).__init__()
81
+ self.drop_prob = drop_prob
82
+
83
+ def forward(self, x):
84
+ return drop_path(x, self.drop_prob, self.training)
85
+
86
+
87
+ class Mlp(nn.Module):
88
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
89
+ super().__init__()
90
+ out_features = out_features or in_features
91
+ hidden_features = hidden_features or in_features
92
+ self.fc1 = nn.Linear(in_features, hidden_features)
93
+ self.act = act_layer()
94
+ self.fc2 = nn.Linear(hidden_features, out_features)
95
+ self.drop = nn.Dropout(drop)
96
+
97
+ def forward(self, x):
98
+ x = self.fc1(x)
99
+ x = self.act(x)
100
+ x = self.drop(x)
101
+ x = self.fc2(x)
102
+ x = self.drop(x)
103
+ return x
104
+
105
+
106
+ class Attention(nn.Module):
107
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
108
+ super().__init__()
109
+ self.num_heads = num_heads
110
+ head_dim = dim // num_heads
111
+ self.scale = qk_scale or head_dim ** -0.5
112
+
113
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
114
+ self.attn_drop = nn.Dropout(attn_drop)
115
+ self.proj = nn.Linear(dim, dim)
116
+ self.proj_drop = nn.Dropout(proj_drop)
117
+
118
+ def forward(self, x):
119
+ B, N, C = x.shape
120
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
121
+ q, k, v = qkv[0], qkv[1], qkv[2]
122
+
123
+ attn = (q @ k.transpose(-2, -1)) * self.scale
124
+ attn = attn.softmax(dim=-1)
125
+ attn = self.attn_drop(attn)
126
+
127
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
128
+ x = self.proj(x)
129
+ x = self.proj_drop(x)
130
+ return x, attn
131
+
132
+
133
+ class Block(nn.Module):
134
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
135
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
136
+ super().__init__()
137
+ self.norm1 = norm_layer(dim)
138
+ self.attn = Attention(
139
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
140
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
141
+ self.norm2 = norm_layer(dim)
142
+ mlp_hidden_dim = int(dim * mlp_ratio)
143
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
144
+
145
+ def forward(self, x, return_attention=False):
146
+ y, attn = self.attn(self.norm1(x))
147
+ if return_attention:
148
+ return attn
149
+ x = x + self.drop_path(y)
150
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
151
+ return x
152
+
153
+
154
+ class PatchEmbed(nn.Module):
155
+ """ Image to Patch Embedding
156
+ """
157
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
158
+ super().__init__()
159
+ num_patches = (img_size // patch_size) * (img_size // patch_size)
160
+ self.img_size = img_size
161
+ self.patch_size = patch_size
162
+ self.num_patches = num_patches
163
+
164
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
165
+
166
+ def forward(self, x):
167
+ B, C, H, W = x.shape
168
+ x = self.proj(x).flatten(2).transpose(1, 2)
169
+ return x
170
+
171
+
172
+ class VisionTransformer(nn.Module):
173
+ """ Vision Transformer """
174
+ def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,
175
+ num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
176
+ drop_path_rate=0., norm_layer=nn.LayerNorm, **kwargs):
177
+ super().__init__()
178
+ self.num_features = self.embed_dim = embed_dim
179
+
180
+ self.patch_embed = PatchEmbed(
181
+ img_size=img_size[0], patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
182
+ num_patches = self.patch_embed.num_patches
183
+
184
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
185
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
186
+ self.pos_drop = nn.Dropout(p=drop_rate)
187
+
188
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
189
+ self.blocks = nn.ModuleList([
190
+ Block(
191
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
192
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
193
+ for i in range(depth)])
194
+ self.norm = norm_layer(embed_dim)
195
+
196
+ # Classifier head
197
+ self.head = nn.Linear(embed_dim, num_classes) if num_classes > 0 else nn.Identity()
198
+
199
+ trunc_normal_(self.pos_embed, std=.02)
200
+ trunc_normal_(self.cls_token, std=.02)
201
+ self.apply(self._init_weights)
202
+
203
+ def _init_weights(self, m):
204
+ if isinstance(m, nn.Linear):
205
+ trunc_normal_(m.weight, std=.02)
206
+ if isinstance(m, nn.Linear) and m.bias is not None:
207
+ nn.init.constant_(m.bias, 0)
208
+ elif isinstance(m, nn.LayerNorm):
209
+ nn.init.constant_(m.bias, 0)
210
+ nn.init.constant_(m.weight, 1.0)
211
+
212
+ def interpolate_pos_encoding(self, x, w, h):
213
+ npatch = x.shape[1] - 1
214
+ N = self.pos_embed.shape[1] - 1
215
+ if npatch == N and w == h:
216
+ return self.pos_embed
217
+ class_pos_embed = self.pos_embed[:, 0]
218
+ patch_pos_embed = self.pos_embed[:, 1:]
219
+ dim = x.shape[-1]
220
+ w0 = w // self.patch_embed.patch_size
221
+ h0 = h // self.patch_embed.patch_size
222
+ # we add a small number to avoid floating point error in the interpolation
223
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
224
+ w0, h0 = w0 + 0.1, h0 + 0.1
225
+ patch_pos_embed = nn.functional.interpolate(
226
+ patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),
227
+ scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),
228
+ mode='bicubic',
229
+ )
230
+ assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]
231
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
232
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
233
+
234
+ def prepare_tokens(self, x):
235
+ B, nc, w, h = x.shape
236
+ x = self.patch_embed(x) # patch linear embedding
237
+
238
+ # add the [CLS] token to the embed patch tokens
239
+ cls_tokens = self.cls_token.expand(B, -1, -1)
240
+ x = torch.cat((cls_tokens, x), dim=1)
241
+
242
+ # add positional encoding to each token
243
+ x = x + self.interpolate_pos_encoding(x, w, h)
244
+
245
+ return self.pos_drop(x)
246
+
247
+ def forward(self, x):
248
+ x = self.prepare_tokens(x)
249
+ for blk in self.blocks:
250
+ x = blk(x)
251
+ x = self.norm(x)
252
+ return x[:, 0]
253
+
254
+ def get_last_selfattention(self, x):
255
+ x = self.prepare_tokens(x)
256
+ for i, blk in enumerate(self.blocks):
257
+ if i < len(self.blocks) - 1:
258
+ x = blk(x)
259
+ else:
260
+ # return attention of the last block
261
+ return blk(x, return_attention=True)
262
+
263
+ def get_intermediate_layers(self, x, n=1):
264
+ x = self.prepare_tokens(x)
265
+ # we return the output tokens from the `n` last blocks
266
+ output = []
267
+ for i, blk in enumerate(self.blocks):
268
+ x = blk(x)
269
+ if len(self.blocks) - i <= n:
270
+ output.append(self.norm(x))
271
+ return output
272
+
273
+
274
+ def vit_tiny(patch_size=16, **kwargs):
275
+ model = VisionTransformer(
276
+ patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, mlp_ratio=4,
277
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
278
+ return model
279
+
280
+
281
+ def vit_small(patch_size=16, **kwargs):
282
+ model = VisionTransformer(
283
+ patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4,
284
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
285
+ return model
286
+
287
+
288
+ def vit_base(patch_size=16, **kwargs):
289
+ model = VisionTransformer(
290
+ patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4,
291
+ qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs)
292
+ return model
293
+
294
+
295
+ class DINOHead(nn.Module):
296
+ def __init__(self, in_dim, out_dim, use_bn=False, norm_last_layer=True, nlayers=3, hidden_dim=2048, bottleneck_dim=256):
297
+ super().__init__()
298
+ nlayers = max(nlayers, 1)
299
+ if nlayers == 1:
300
+ self.mlp = nn.Linear(in_dim, bottleneck_dim)
301
+ else:
302
+ layers = [nn.Linear(in_dim, hidden_dim)]
303
+ if use_bn:
304
+ layers.append(nn.BatchNorm1d(hidden_dim))
305
+ layers.append(nn.GELU())
306
+ for _ in range(nlayers - 2):
307
+ layers.append(nn.Linear(hidden_dim, hidden_dim))
308
+ if use_bn:
309
+ layers.append(nn.BatchNorm1d(hidden_dim))
310
+ layers.append(nn.GELU())
311
+ layers.append(nn.Linear(hidden_dim, bottleneck_dim))
312
+ self.mlp = nn.Sequential(*layers)
313
+ self.apply(self._init_weights)
314
+ self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))
315
+ self.last_layer.weight_g.data.fill_(1)
316
+ if norm_last_layer:
317
+ self.last_layer.weight_g.requires_grad = False
318
+
319
+ def _init_weights(self, m):
320
+ if isinstance(m, nn.Linear):
321
+ trunc_normal_(m.weight, std=.02)
322
+ if isinstance(m, nn.Linear) and m.bias is not None:
323
+ nn.init.constant_(m.bias, 0)
324
+
325
+ def forward(self, x):
326
+ x = self.mlp(x)
327
+ x = nn.functional.normalize(x, dim=-1, p=2)
328
+ x = self.last_layer(x)
329
+ return x