Skip to content

Commit dfc8df6

Browse files
committed
add the u-vit implementation with simple vit + register tokens
1 parent 9992a61 commit dfc8df6

File tree

2 files changed

+187
-0
lines changed

2 files changed

+187
-0
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2081,6 +2081,17 @@ Coming from computer vision and new to transformers? Here are some resources tha
20812081
}
20822082
```
20832083

2084+
```bibtex
2085+
@article{Bao2022AllAW,
2086+
title = {All are Worth Words: A ViT Backbone for Diffusion Models},
2087+
author = {Fan Bao and Shen Nie and Kaiwen Xue and Yue Cao and Chongxuan Li and Hang Su and Jun Zhu},
2088+
journal = {2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
2089+
year = {2022},
2090+
pages = {22669-22679},
2091+
url = {https://api.semanticscholar.org/CorpusID:253581703}
2092+
}
2093+
```
2094+
20842095
```bibtex
20852096
@misc{Rubin2024,
20862097
author = {Ohad Rubin},

vit_pytorch/simple_uvit.py

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
import torch
2+
from torch import nn
3+
from torch.nn import Module, ModuleList
4+
5+
from einops import rearrange, repeat, pack, unpack
6+
from einops.layers.torch import Rearrange
7+
8+
# helpers
9+
10+
def pair(t):
11+
return t if isinstance(t, tuple) else (t, t)
12+
13+
def exists(v):
14+
return v is not None
15+
16+
def divisible_by(num, den):
17+
return (num % den) == 0
18+
19+
def posemb_sincos_2d(h, w, dim, temperature: int = 10000, dtype = torch.float32):
20+
y, x = torch.meshgrid(torch.arange(h), torch.arange(w), indexing="ij")
21+
assert divisible_by(dim, 4), "feature dimension must be multiple of 4 for sincos emb"
22+
omega = torch.arange(dim // 4) / (dim // 4 - 1)
23+
omega = temperature ** -omega
24+
25+
y = y.flatten()[:, None] * omega[None, :]
26+
x = x.flatten()[:, None] * omega[None, :]
27+
pe = torch.cat((x.sin(), x.cos(), y.sin(), y.cos()), dim=1)
28+
return pe.type(dtype)
29+
30+
# classes
31+
32+
def FeedForward(dim, hidden_dim):
33+
return nn.Sequential(
34+
nn.LayerNorm(dim),
35+
nn.Linear(dim, hidden_dim),
36+
nn.GELU(),
37+
nn.Linear(hidden_dim, dim),
38+
)
39+
40+
class Attention(Module):
41+
def __init__(self, dim, heads = 8, dim_head = 64):
42+
super().__init__()
43+
inner_dim = dim_head * heads
44+
self.heads = heads
45+
self.scale = dim_head ** -0.5
46+
self.norm = nn.LayerNorm(dim)
47+
48+
self.attend = nn.Softmax(dim = -1)
49+
50+
self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)
51+
self.to_out = nn.Linear(inner_dim, dim, bias = False)
52+
53+
def forward(self, x):
54+
x = self.norm(x)
55+
56+
qkv = self.to_qkv(x).chunk(3, dim = -1)
57+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
58+
59+
dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
60+
61+
attn = self.attend(dots)
62+
63+
out = torch.matmul(attn, v)
64+
out = rearrange(out, 'b h n d -> b n (h d)')
65+
return self.to_out(out)
66+
67+
class Transformer(Module):
68+
def __init__(self, dim, depth, heads, dim_head, mlp_dim):
69+
super().__init__()
70+
self.depth = depth
71+
self.norm = nn.LayerNorm(dim)
72+
self.layers = ModuleList([])
73+
74+
for layer in range(1, depth + 1):
75+
latter_half = layer >= (depth / 2 + 1)
76+
77+
self.layers.append(nn.ModuleList([
78+
nn.Linear(dim * 2, dim) if latter_half else None,
79+
Attention(dim, heads = heads, dim_head = dim_head),
80+
FeedForward(dim, mlp_dim)
81+
]))
82+
83+
def forward(self, x):
84+
85+
skips = []
86+
87+
for ind, (combine_skip, attn, ff) in enumerate(self.layers):
88+
layer = ind + 1
89+
first_half = layer <= (self.depth / 2)
90+
91+
if first_half:
92+
skips.append(x)
93+
94+
if exists(combine_skip):
95+
skip = skips.pop()
96+
skip_and_x = torch.cat((skip, x), dim = -1)
97+
x = combine_skip(skip_and_x)
98+
99+
x = attn(x) + x
100+
x = ff(x) + x
101+
102+
assert len(skips) == 0
103+
104+
return self.norm(x)
105+
106+
class SimpleUViT(Module):
107+
def __init__(self, *, image_size, patch_size, num_classes, dim, depth, heads, mlp_dim, num_register_tokens = 4, channels = 3, dim_head = 64):
108+
super().__init__()
109+
image_height, image_width = pair(image_size)
110+
patch_height, patch_width = pair(patch_size)
111+
112+
assert divisible_by(image_height, patch_height) and divisible_by(image_width, patch_width), 'Image dimensions must be divisible by the patch size.'
113+
114+
patch_dim = channels * patch_height * patch_width
115+
116+
self.to_patch_embedding = nn.Sequential(
117+
Rearrange("b c (h p1) (w p2) -> b (h w) (p1 p2 c)", p1 = patch_height, p2 = patch_width),
118+
nn.LayerNorm(patch_dim),
119+
nn.Linear(patch_dim, dim),
120+
nn.LayerNorm(dim),
121+
)
122+
123+
pos_embedding = posemb_sincos_2d(
124+
h = image_height // patch_height,
125+
w = image_width // patch_width,
126+
dim = dim
127+
)
128+
129+
self.register_buffer('pos_embedding', pos_embedding, persistent = False)
130+
131+
self.register_tokens = nn.Parameter(torch.randn(num_register_tokens, dim))
132+
133+
self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim)
134+
135+
self.pool = "mean"
136+
self.to_latent = nn.Identity()
137+
138+
self.linear_head = nn.Linear(dim, num_classes)
139+
140+
def forward(self, img):
141+
batch, device = img.shape[0], img.device
142+
143+
x = self.to_patch_embedding(img)
144+
x = x + self.pos_embedding.type(x.dtype)
145+
146+
r = repeat(self.register_tokens, 'n d -> b n d', b = batch)
147+
148+
x, ps = pack([x, r], 'b * d')
149+
150+
x = self.transformer(x)
151+
152+
x, _ = unpack(x, ps, 'b * d')
153+
154+
x = x.mean(dim = 1)
155+
156+
x = self.to_latent(x)
157+
return self.linear_head(x)
158+
159+
# quick test on odd number of layers
160+
161+
if __name__ == '__main__':
162+
163+
v = SimpleUViT(
164+
image_size = 256,
165+
patch_size = 32,
166+
num_classes = 1000,
167+
dim = 1024,
168+
depth = 7,
169+
heads = 16,
170+
mlp_dim = 2048
171+
).cuda()
172+
173+
img = torch.randn(2, 3, 256, 256).cuda()
174+
175+
preds = v(img)
176+
assert preds.shape == (2, 1000)

0 commit comments

Comments
 (0)