Skip to content

Commit 2f87c0c

Browse files
committed
offer 1d versions, in light of https://arxiv.org/abs/2211.14730
1 parent 59c8948 commit 2f87c0c

File tree

3 files changed

+260
-2
lines changed

3 files changed

+260
-2
lines changed

setup.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
setup(
44
name = 'vit-pytorch',
55
packages = find_packages(exclude=['examples']),
6-
version = '0.38.1',
6+
version = '0.39.1',
77
license='MIT',
88
description = 'Vision Transformer (ViT) - Pytorch',
99
long_description_content_type = 'text/markdown',
@@ -16,7 +16,7 @@
1616
'image recognition'
1717
],
1818
install_requires=[
19-
'einops>=0.4.1',
19+
'einops>=0.6.0',
2020
'torch>=1.10',
2121
'torchvision'
2222
],

vit_pytorch/simple_vit_1d.py

+125
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import torch
2+
from torch import nn
3+
4+
from einops import rearrange
5+
from einops.layers.torch import Rearrange
6+
7+
# helpers
8+
9+
def posemb_sincos_1d(patches, temperature = 10000, dtype = torch.float32):
10+
_, n, dim, device, dtype = *patches.shape, patches.device, patches.dtype
11+
12+
n = torch.arange(n, device = device)
13+
assert (dim % 2) == 0, 'feature dimension must be multiple of 2 for sincos emb'
14+
omega = torch.arange(dim // 2, device = device) / (dim // 2 - 1)
15+
omega = 1. / (temperature ** omega)
16+
17+
n = n.flatten()[:, None] * omega[None, :]
18+
pe = torch.cat((n.sin(), n.cos()), dim = 1)
19+
return pe.type(dtype)
20+
21+
# classes
22+
23+
class FeedForward(nn.Module):
24+
def __init__(self, dim, hidden_dim):
25+
super().__init__()
26+
self.net = nn.Sequential(
27+
nn.LayerNorm(dim),
28+
nn.Linear(dim, hidden_dim),
29+
nn.GELU(),
30+
nn.Linear(hidden_dim, dim),
31+
)
32+
def forward(self, x):
33+
return self.net(x)
34+
35+
class Attention(nn.Module):
36+
def __init__(self, dim, heads = 8, dim_head = 64):
37+
super().__init__()
38+
inner_dim = dim_head * heads
39+
self.heads = heads
40+
self.scale = dim_head ** -0.5
41+
self.norm = nn.LayerNorm(dim)
42+
43+
self.attend = nn.Softmax(dim = -1)
44+
45+
self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)
46+
self.to_out = nn.Linear(inner_dim, dim, bias = False)
47+
48+
def forward(self, x):
49+
x = self.norm(x)
50+
51+
qkv = self.to_qkv(x).chunk(3, dim = -1)
52+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
53+
54+
dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
55+
56+
attn = self.attend(dots)
57+
58+
out = torch.matmul(attn, v)
59+
out = rearrange(out, 'b h n d -> b n (h d)')
60+
return self.to_out(out)
61+
62+
class Transformer(nn.Module):
63+
def __init__(self, dim, depth, heads, dim_head, mlp_dim):
64+
super().__init__()
65+
self.layers = nn.ModuleList([])
66+
for _ in range(depth):
67+
self.layers.append(nn.ModuleList([
68+
Attention(dim, heads = heads, dim_head = dim_head),
69+
FeedForward(dim, mlp_dim)
70+
]))
71+
def forward(self, x):
72+
for attn, ff in self.layers:
73+
x = attn(x) + x
74+
x = ff(x) + x
75+
return x
76+
77+
class SimpleViT(nn.Module):
78+
def __init__(self, *, seq_len, patch_size, num_classes, dim, depth, heads, mlp_dim, channels = 3, dim_head = 64):
79+
super().__init__()
80+
81+
assert seq_len % patch_size == 0
82+
83+
num_patches = seq_len // patch_size
84+
patch_dim = channels * patch_size
85+
86+
self.to_patch_embedding = nn.Sequential(
87+
Rearrange('b c (n p) -> b n (p c)', p = patch_size),
88+
nn.Linear(patch_dim, dim),
89+
)
90+
91+
self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim)
92+
93+
self.to_latent = nn.Identity()
94+
self.linear_head = nn.Sequential(
95+
nn.LayerNorm(dim),
96+
nn.Linear(dim, num_classes)
97+
)
98+
99+
def forward(self, series):
100+
*_, n, dtype = *series.shape, series.dtype
101+
102+
x = self.to_patch_embedding(series)
103+
pe = posemb_sincos_1d(x)
104+
x = rearrange(x, 'b ... d -> b (...) d') + pe
105+
106+
x = self.transformer(x)
107+
x = x.mean(dim = 1)
108+
109+
x = self.to_latent(x)
110+
return self.linear_head(x)
111+
112+
if __name__ == '__main__':
113+
114+
v = SimpleViT(
115+
seq_len = 256,
116+
patch_size = 16,
117+
num_classes = 1000,
118+
dim = 1024,
119+
depth = 6,
120+
heads = 8,
121+
mlp_dim = 2048
122+
)
123+
124+
time_series = torch.randn(4, 3, 256)
125+
logits = v(time_series) # (4, 1000)

vit_pytorch/vit_1d.py

+133
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
import torch
2+
from torch import nn
3+
4+
from einops import rearrange, repeat, pack, unpack
5+
from einops.layers.torch import Rearrange
6+
7+
# classes
8+
9+
class PreNorm(nn.Module):
10+
def __init__(self, dim, fn):
11+
super().__init__()
12+
self.norm = nn.LayerNorm(dim)
13+
self.fn = fn
14+
def forward(self, x, **kwargs):
15+
return self.fn(self.norm(x), **kwargs)
16+
17+
class FeedForward(nn.Module):
18+
def __init__(self, dim, hidden_dim, dropout = 0.):
19+
super().__init__()
20+
self.net = nn.Sequential(
21+
nn.Linear(dim, hidden_dim),
22+
nn.GELU(),
23+
nn.Dropout(dropout),
24+
nn.Linear(hidden_dim, dim),
25+
nn.Dropout(dropout)
26+
)
27+
def forward(self, x):
28+
return self.net(x)
29+
30+
class Attention(nn.Module):
31+
def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):
32+
super().__init__()
33+
inner_dim = dim_head * heads
34+
project_out = not (heads == 1 and dim_head == dim)
35+
36+
self.heads = heads
37+
self.scale = dim_head ** -0.5
38+
39+
self.attend = nn.Softmax(dim = -1)
40+
self.dropout = nn.Dropout(dropout)
41+
42+
self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)
43+
44+
self.to_out = nn.Sequential(
45+
nn.Linear(inner_dim, dim),
46+
nn.Dropout(dropout)
47+
) if project_out else nn.Identity()
48+
49+
def forward(self, x):
50+
qkv = self.to_qkv(x).chunk(3, dim = -1)
51+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
52+
53+
dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
54+
55+
attn = self.attend(dots)
56+
attn = self.dropout(attn)
57+
58+
out = torch.matmul(attn, v)
59+
out = rearrange(out, 'b h n d -> b n (h d)')
60+
return self.to_out(out)
61+
62+
class Transformer(nn.Module):
63+
def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):
64+
super().__init__()
65+
self.layers = nn.ModuleList([])
66+
for _ in range(depth):
67+
self.layers.append(nn.ModuleList([
68+
PreNorm(dim, Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout)),
69+
PreNorm(dim, FeedForward(dim, mlp_dim, dropout = dropout))
70+
]))
71+
def forward(self, x):
72+
for attn, ff in self.layers:
73+
x = attn(x) + x
74+
x = ff(x) + x
75+
return x
76+
77+
class ViT(nn.Module):
78+
def __init__(self, *, seq_len, patch_size, num_classes, dim, depth, heads, mlp_dim, channels = 3, dim_head = 64, dropout = 0., emb_dropout = 0.):
79+
super().__init__()
80+
assert (seq_len % patch_size) == 0
81+
82+
num_patches = seq_len // patch_size
83+
patch_dim = channels * patch_size
84+
85+
self.to_patch_embedding = nn.Sequential(
86+
Rearrange('b c (n p) -> b n (p c)', p = patch_size),
87+
nn.Linear(patch_dim, dim),
88+
)
89+
90+
self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))
91+
self.cls_token = nn.Parameter(torch.randn(dim))
92+
self.dropout = nn.Dropout(emb_dropout)
93+
94+
self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)
95+
96+
self.mlp_head = nn.Sequential(
97+
nn.LayerNorm(dim),
98+
nn.Linear(dim, num_classes)
99+
)
100+
101+
def forward(self, series):
102+
x = self.to_patch_embedding(series)
103+
b, n, _ = x.shape
104+
105+
cls_tokens = repeat(self.cls_token, 'd -> b d', b = b)
106+
107+
x, ps = pack([cls_tokens, x], 'b * d')
108+
109+
x += self.pos_embedding[:, :(n + 1)]
110+
x = self.dropout(x)
111+
112+
x = self.transformer(x)
113+
114+
cls_tokens, _ = unpack(x, ps, 'b * d')
115+
116+
return self.mlp_head(cls_tokens)
117+
118+
if __name__ == '__main__':
119+
120+
v = ViT(
121+
seq_len = 256,
122+
patch_size = 16,
123+
num_classes = 1000,
124+
dim = 1024,
125+
depth = 6,
126+
heads = 8,
127+
mlp_dim = 2048,
128+
dropout = 0.1,
129+
emb_dropout = 0.1
130+
)
131+
132+
time_series = torch.randn(4, 3, 256)
133+
logits = v(time_series) # (4, 1000)

0 commit comments

Comments
 (0)