Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lucidrains
GitHub Repository: lucidrains/vit-pytorch
Path: blob/main/vit_pytorch/mp3.py
649 views
1
import torch
2
from torch import nn, einsum
3
import torch.nn.functional as F
4
5
from einops import rearrange, repeat
6
from einops.layers.torch import Rearrange
7
8
# helpers
9
10
def exists(val):
11
return val is not None
12
13
def default(val, d):
14
return val if exists(val) else d
15
16
def pair(t):
17
return t if isinstance(t, tuple) else (t, t)
18
19
# positional embedding
20
21
def posemb_sincos_2d(patches, temperature = 10000, dtype = torch.float32):
22
_, h, w, dim, device, dtype = *patches.shape, patches.device, patches.dtype
23
24
y, x = torch.meshgrid(torch.arange(h, device = device), torch.arange(w, device = device), indexing = 'ij')
25
assert (dim % 4) == 0, 'feature dimension must be multiple of 4 for sincos emb'
26
omega = torch.arange(dim // 4, device = device) / (dim // 4 - 1)
27
omega = 1. / (temperature ** omega)
28
29
y = y.flatten()[:, None] * omega[None, :]
30
x = x.flatten()[:, None] * omega[None, :]
31
pe = torch.cat((x.sin(), x.cos(), y.sin(), y.cos()), dim = 1)
32
return pe.type(dtype)
33
34
# feedforward
35
36
class FeedForward(nn.Module):
37
def __init__(self, dim, hidden_dim, dropout = 0.):
38
super().__init__()
39
self.net = nn.Sequential(
40
nn.LayerNorm(dim),
41
nn.Linear(dim, hidden_dim),
42
nn.GELU(),
43
nn.Dropout(dropout),
44
nn.Linear(hidden_dim, dim),
45
nn.Dropout(dropout)
46
)
47
def forward(self, x):
48
return self.net(x)
49
50
# (cross)attention
51
52
class Attention(nn.Module):
53
def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):
54
super().__init__()
55
inner_dim = dim_head * heads
56
self.heads = heads
57
self.scale = dim_head ** -0.5
58
59
self.attend = nn.Softmax(dim = -1)
60
self.dropout = nn.Dropout(dropout)
61
62
self.norm = nn.LayerNorm(dim)
63
64
self.to_q = nn.Linear(dim, inner_dim, bias = False)
65
self.to_kv = nn.Linear(dim, inner_dim * 2, bias = False)
66
67
self.to_out = nn.Sequential(
68
nn.Linear(inner_dim, dim),
69
nn.Dropout(dropout)
70
)
71
72
def forward(self, x, context = None):
73
b, n, _, h = *x.shape, self.heads
74
75
x = self.norm(x)
76
77
context = self.norm(context) if exists(context) else x
78
79
qkv = (self.to_q(x), *self.to_kv(context).chunk(2, dim = -1))
80
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), qkv)
81
82
dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale
83
84
attn = self.attend(dots)
85
attn = self.dropout(attn)
86
87
out = einsum('b h i j, b h j d -> b h i d', attn, v)
88
out = rearrange(out, 'b h n d -> b n (h d)')
89
return self.to_out(out)
90
91
class Transformer(nn.Module):
92
def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):
93
super().__init__()
94
self.layers = nn.ModuleList([])
95
for _ in range(depth):
96
self.layers.append(nn.ModuleList([
97
Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout),
98
FeedForward(dim, mlp_dim, dropout = dropout)
99
]))
100
def forward(self, x, context = None):
101
for attn, ff in self.layers:
102
x = attn(x, context = context) + x
103
x = ff(x) + x
104
return x
105
106
class ViT(nn.Module):
107
def __init__(self, *, num_classes, image_size, patch_size, dim, depth, heads, mlp_dim, channels = 3, dim_head = 64, dropout = 0.):
108
super().__init__()
109
image_height, image_width = pair(image_size)
110
patch_height, patch_width = pair(patch_size)
111
112
assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'
113
114
num_patches = (image_height // patch_height) * (image_width // patch_width)
115
patch_dim = channels * patch_height * patch_width
116
117
self.dim = dim
118
self.num_patches = num_patches
119
120
self.to_patch_embedding = nn.Sequential(
121
Rearrange('b c (h p1) (w p2) -> b h w (p1 p2 c)', p1 = patch_height, p2 = patch_width),
122
nn.LayerNorm(patch_dim),
123
nn.Linear(patch_dim, dim),
124
nn.LayerNorm(dim),
125
)
126
127
self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)
128
129
self.to_latent = nn.Identity()
130
self.linear_head = nn.Sequential(
131
nn.LayerNorm(dim),
132
nn.Linear(dim, num_classes)
133
)
134
135
def forward(self, img):
136
*_, h, w, dtype = *img.shape, img.dtype
137
138
x = self.to_patch_embedding(img)
139
pe = posemb_sincos_2d(x)
140
x = rearrange(x, 'b ... d -> b (...) d') + pe
141
142
x = self.transformer(x)
143
x = x.mean(dim = 1)
144
145
x = self.to_latent(x)
146
return self.linear_head(x)
147
148
# Masked Position Prediction Pre-Training
149
150
class MP3(nn.Module):
151
def __init__(self, vit: ViT, masking_ratio):
152
super().__init__()
153
self.vit = vit
154
155
assert masking_ratio > 0 and masking_ratio < 1, 'masking ratio must be kept between 0 and 1'
156
self.masking_ratio = masking_ratio
157
158
dim = vit.dim
159
self.mlp_head = nn.Sequential(
160
nn.LayerNorm(dim),
161
nn.Linear(dim, vit.num_patches)
162
)
163
164
def forward(self, img):
165
device = img.device
166
tokens = self.vit.to_patch_embedding(img)
167
tokens = rearrange(tokens, 'b ... d -> b (...) d')
168
169
batch, num_patches, *_ = tokens.shape
170
171
# Masking
172
num_masked = int(self.masking_ratio * num_patches)
173
rand_indices = torch.rand(batch, num_patches, device = device).argsort(dim = -1)
174
masked_indices, unmasked_indices = rand_indices[:, :num_masked], rand_indices[:, num_masked:]
175
176
batch_range = torch.arange(batch, device = device)[:, None]
177
tokens_unmasked = tokens[batch_range, unmasked_indices]
178
179
attended_tokens = self.vit.transformer(tokens, tokens_unmasked)
180
logits = rearrange(self.mlp_head(attended_tokens), 'b n d -> (b n) d')
181
182
# Define labels
183
labels = repeat(torch.arange(num_patches, device = device), 'n -> (b n)', b = batch)
184
loss = F.cross_entropy(logits, labels)
185
186
return loss
187
188