-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmamba2.py
More file actions
97 lines (80 loc) · 2.95 KB
/
mamba2.py
File metadata and controls
97 lines (80 loc) · 2.95 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import torch
from torch import nn
from einops import rearrange, repeat
from mamba_ssm import Mamba2
class MLPProjector(nn.Module):
def __init__(self, input_dim=90, hidden_dim=128, output_dim=128):
super().__init__()
self.net = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.GELU(),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, x):
return self.net(x)
class MambaStack(nn.Module):
def __init__(self, dim, depth, d_state=64, d_conv=4, expand=2, dropout=0.2):
super().__init__()
self.drop = nn.Dropout(dropout)
self.layers = nn.ModuleList([
Mamba2(
d_model=dim,
d_state=d_state,
d_conv=d_conv,
expand=expand,
) for _ in range(depth)
])
self.norms = nn.ModuleList([
nn.LayerNorm(dim) for _ in range(depth)
])
def forward(self, x):
for layer, norm in zip(self.layers, self.norms):
y = layer(x)
y = norm(y)
x = x + y
return self.drop(x)
class RingToolMamba(nn.Module):
def __init__(self,
in_channels=3,
window_size=5,
dim=128,
depth=4,
d_state=64,
d_conv=4,
expand=2,
num_classes=1,
**kw):
super().__init__()
self.projection = nn.Sequential(
nn.Unfold(kernel_size=(window_size, 1), stride=window_size),
Rearrange('b (c w) l -> b l (w c)', w=window_size, c=in_channels),
MLPProjector(input_dim=in_channels*window_size, output_dim=dim)
)
self.mamba = MambaStack(dim, depth, d_state, d_conv, expand)
self.cls_head = nn.Sequential(
nn.LayerNorm(dim),
nn.Linear(dim, num_classes)
)
self.cls_token = nn.Parameter(torch.randn(1, 1, dim))
self._init_weights()
def _init_weights(self):
for module in self.modules():
if isinstance(module, nn.Linear):
nn.init.xavier_normal_(module.weight)
if module.bias is not None:
module.bias.data.zero_()
def forward(self, x):
x = x.permute(0, 2, 1).unsqueeze(-1)
x = self.projection(x) # [batch, seq_len, dim]
cls_tokens = repeat(self.cls_token, '1 1 d -> b 1 d', b=x.shape[0])
x = torch.cat((x, cls_tokens), dim=1) # [batch, seq_len+1, dim]
x = self.mamba(x) # [batch, seq_len+1, dim]
cls_output = x[:, -1] # [batch, dim]
return self.cls_head(cls_output)[:, 0], x
class Rearrange(nn.Module):
def __init__(self, pattern, **kw):
super().__init__()
self.pattern = pattern
self.kw = kw
def forward(self, x):
return rearrange(x, self.pattern, **self.kw)