-
Notifications
You must be signed in to change notification settings - Fork 0
/
convmixer修改版.py
57 lines (48 loc) · 1.67 KB
/
convmixer修改版.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import torch
import torch.nn as nn
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x):
return self.fn(x) + x
class SelfAttention(nn.Module):
def __init__(self, dim):
super().__init__()
self.attention = nn.MultiheadAttention(dim, num_heads=4, batch_first=True)
def forward(self, x):
b, c, h, w = x.shape
x = x.view(b, c, h*w).transpose(1, 2)
out, _ = self.attention(x, x, x)
out = out.transpose(1, 2).view(b, c, h, w)
return out
def ConvMixer(dim, depth, kernel_size=9, patch_size=7, n_classes=1000):
return nn.Sequential(
nn.Conv2d(3, dim, kernel_size=patch_size, stride=patch_size),
nn.GELU(),
nn.BatchNorm2d(dim),
*[nn.Sequential(
Residual(nn.Sequential(
nn.Conv2d(dim, dim, kernel_size, groups=dim, padding="same"),
nn.GELU(),
nn.BatchNorm2d(dim)
)),
nn.Conv2d(dim, dim, kernel_size=1),
nn.GELU(),
nn.BatchNorm2d(dim),
Residual(SelfAttention(dim))
) for i in range(depth)],
nn.AdaptiveAvgPool2d((1,1)),
nn.Flatten(),
nn.Linear(dim, n_classes)
)
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def main():
# Create a ConvMixer model
model = ConvMixer(dim=256, depth=8)
# Count and print the number of parameters
num_params = count_parameters(model)
print(f"Number of parameters: {num_params:,}")
if __name__ == "__main__":
main()