devicoal commited on
Commit
62854c4
·
verified ·
1 Parent(s): 93e340b

Add LS-ViT architecture (modeling.py)

Browse files
Files changed (1) hide show
  1. modeling.py +337 -0
modeling.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LS-ViT model architecture for HMDB51 action recognition.
2
+
3
+ This module defines the LS-ViT (Long-Short ViT) architecture used to train the
4
+ weights stored in `lsvit_hmdb51_best.pt`. The model wraps a ViT-Base backbone
5
+ with two motion-aware modules:
6
+
7
+ - SMIFModule: Short-term Motion Injection & Fusion, applied to raw RGB frames.
8
+ - LMIModule: Long-term Motion Interaction, applied to patch tokens inside
9
+ every transformer block.
10
+
11
+ Usage:
12
+ import torch
13
+ from modeling import ViTConfig, LSViTForAction
14
+
15
+ config = ViTConfig(image_size=224)
16
+ model = LSViTForAction(config, num_classes=51)
17
+ ckpt = torch.load("lsvit_hmdb51_best.pt", map_location="cpu", weights_only=False)
18
+ model.load_state_dict(ckpt["model"])
19
+ model.eval()
20
+
21
+ # video: (Batch, Time, Channels, Height, Width) in [0, 1] after standard ViT
22
+ # normalization. Trained with T=12, image_size=224.
23
+ logits = model(video)
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import math
29
+ from dataclasses import dataclass
30
+
31
+ import torch
32
+ import torch.nn as nn
33
+ import torch.nn.functional as F
34
+
35
+
36
+ @dataclass
37
+ class ViTConfig:
38
+ image_size: int = 224
39
+ patch_size: int = 16
40
+ in_chans: int = 3
41
+ embed_dim: int = 768
42
+ depth: int = 12
43
+ num_heads: int = 12
44
+ mlp_ratio: float = 4.0
45
+ drop_rate: float = 0.1
46
+ attn_drop_rate: float = 0.1
47
+ drop_path_rate: float = 0.1
48
+ qkv_bias: bool = True
49
+
50
+
51
+ class PatchEmbed(nn.Module):
52
+ def __init__(self, config: ViTConfig):
53
+ super().__init__()
54
+ self.image_size = config.image_size
55
+ self.patch_size = config.patch_size
56
+ self.num_patches = (config.image_size // config.patch_size) ** 2
57
+
58
+ self.proj = nn.Conv2d(
59
+ config.in_chans,
60
+ config.embed_dim,
61
+ kernel_size=config.patch_size,
62
+ stride=config.patch_size,
63
+ )
64
+
65
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
66
+ x = self.proj(x)
67
+ x = x.flatten(2).transpose(1, 2)
68
+ return x
69
+
70
+
71
+ class DropPath(nn.Module):
72
+ """Drop paths per sample when applied in the main path of residual blocks."""
73
+
74
+ def __init__(self, drop_prob: float = 0.0):
75
+ super().__init__()
76
+ self.drop_prob = drop_prob
77
+
78
+ def forward(self, x):
79
+ if self.drop_prob == 0.0 or not self.training:
80
+ return x
81
+ keep_prob = 1 - self.drop_prob
82
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1)
83
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
84
+ random_tensor.floor_()
85
+ return x.div(keep_prob) * random_tensor
86
+
87
+
88
+ class Attention(nn.Module):
89
+ def __init__(self, dim: int, num_heads: int, qkv_bias: bool, attn_drop: float, proj_drop: float):
90
+ super().__init__()
91
+ self.num_heads = num_heads
92
+ head_dim = dim // num_heads
93
+ self.scale = head_dim ** -0.5
94
+
95
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
96
+ self.k = nn.Linear(dim, dim, bias=qkv_bias)
97
+ self.v = nn.Linear(dim, dim, bias=qkv_bias)
98
+
99
+ self.attn_drop = nn.Dropout(attn_drop)
100
+ self.proj = nn.Linear(dim, dim)
101
+ self.proj_drop = nn.Dropout(proj_drop)
102
+
103
+ def forward(self, x):
104
+ B, N, C = x.shape
105
+
106
+ q = self.q(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
107
+ k = self.k(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
108
+ v = self.v(x).reshape(B, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
109
+
110
+ attn = (q @ k.transpose(-2, -1)) * self.scale
111
+ attn = attn.softmax(dim=-1)
112
+ attn = self.attn_drop(attn)
113
+
114
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
115
+ x = self.proj(x)
116
+ x = self.proj_drop(x)
117
+ return x
118
+
119
+
120
+ class SMIFModule(nn.Module):
121
+ """Short-term Motion Injection & Fusion over raw RGB frames."""
122
+
123
+ def __init__(self, channels: int, window_size: int = 5, alpha: float = 0.5, threshold: float = 0.05):
124
+ super().__init__()
125
+ assert window_size % 2 == 1, "window_size must be odd"
126
+ self.channels = channels
127
+ self.window_size = window_size
128
+ self.half = window_size // 2
129
+ self.threshold = threshold
130
+
131
+ self.alpha = nn.Parameter(torch.tensor(alpha))
132
+ self.conv_fuse = nn.Conv2d(channels * 2, channels, kernel_size=1)
133
+
134
+ def forward(self, video: torch.Tensor, return_motion_map: bool = False):
135
+ B, T, C, H, W = video.shape
136
+
137
+ motion_accum = torch.zeros_like(video)
138
+ for offset in range(1, self.half + 1):
139
+ prev_frames = torch.roll(video, shifts=offset, dims=1)
140
+ next_frames = torch.roll(video, shifts=-offset, dims=1)
141
+ prev_frames[:, :offset] = video[:, :offset]
142
+ next_frames[:, -offset:] = video[:, -offset:]
143
+
144
+ diff_future = next_frames - video
145
+ diff_past = video - prev_frames
146
+ motion_accum = motion_accum + diff_future.abs() + diff_past.abs()
147
+
148
+ motion_map = motion_accum / max(self.half, 1)
149
+ mask = (motion_map > self.threshold).float()
150
+ motion_map = motion_map * mask
151
+
152
+ base_2d = video.reshape(B * T, C, H, W)
153
+ motion_2d = motion_map.reshape(B * T, C, H, W)
154
+
155
+ fused = torch.cat([base_2d, motion_2d], dim=1)
156
+ fused = self.conv_fuse(fused)
157
+
158
+ out = base_2d + self.alpha.tanh() * fused
159
+ out = out.clamp(min=-1.0, max=1.0)
160
+ out = out.view(B, T, C, H, W)
161
+
162
+ if return_motion_map:
163
+ return out, motion_map
164
+ return out
165
+
166
+
167
+ class LMIModule(nn.Module):
168
+ """Long-term Motion Interaction operating on token differences across time."""
169
+
170
+ def __init__(self, dim: int, reduction: int = 4, delta: float = 0.1):
171
+ super().__init__()
172
+ reduced_dim = max(1, dim // reduction)
173
+ self.reduce = nn.Linear(dim, reduced_dim)
174
+ self.expand = nn.Linear(reduced_dim, dim)
175
+ self.temporal_mlp = nn.Sequential(
176
+ nn.LayerNorm(reduced_dim),
177
+ nn.Linear(reduced_dim, reduced_dim),
178
+ nn.GELU(),
179
+ nn.Linear(reduced_dim, reduced_dim),
180
+ )
181
+ self.delta = nn.Parameter(torch.tensor(delta))
182
+
183
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
184
+ B, T, N, C = x.shape
185
+ reduced = self.reduce(x)
186
+
187
+ if T > 1:
188
+ diff_f = reduced[:, 1:] - reduced[:, :-1]
189
+ diff_f = torch.cat([diff_f, diff_f[:, -1:]], dim=1)
190
+ diff_b = reduced[:, :-1] - reduced[:, 1:]
191
+ diff_b = torch.cat([diff_b[:, :1], diff_b], dim=1)
192
+ else:
193
+ diff_f = torch.zeros_like(reduced)
194
+ diff_b = torch.zeros_like(reduced)
195
+
196
+ motion = (diff_f.abs() + diff_b.abs()).mean(dim=2)
197
+ motion = self.temporal_mlp(motion)
198
+
199
+ attn = torch.sigmoid(motion).unsqueeze(2)
200
+ attn = self.expand(attn)
201
+ attn = attn.expand(-1, -1, N, -1)
202
+ enhanced = x * attn
203
+ return x + self.delta.tanh() * enhanced
204
+
205
+
206
+ class Mlp(nn.Module):
207
+ def __init__(self, dim: int, mlp_ratio: float, drop: float):
208
+ super().__init__()
209
+ hidden_dim = int(dim * mlp_ratio)
210
+ self.fc1 = nn.Linear(dim, hidden_dim)
211
+ self.act = nn.GELU()
212
+ self.fc2 = nn.Linear(hidden_dim, dim)
213
+ self.drop = nn.Dropout(drop)
214
+
215
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
216
+ x = self.fc1(x)
217
+ x = self.act(x)
218
+ x = self.drop(x)
219
+ x = self.fc2(x)
220
+ x = self.drop(x)
221
+ return x
222
+
223
+
224
+ class LSViTBlock(nn.Module):
225
+ def __init__(self, dim, num_heads, mlp_ratio, drop_rate, attn_drop, drop_path):
226
+ super().__init__()
227
+ self.norm1 = nn.LayerNorm(dim)
228
+ self.attn = Attention(dim, num_heads, True, attn_drop, drop_rate)
229
+ self.drop_path1 = DropPath(drop_path)
230
+ self.norm2 = nn.LayerNorm(dim)
231
+ self.mlp = Mlp(dim, mlp_ratio, drop_rate)
232
+ self.drop_path2 = DropPath(drop_path)
233
+ self.lmim = LMIModule(dim)
234
+
235
+ def forward(self, x, B, T):
236
+ x = x + self.drop_path1(self.attn(self.norm1(x)))
237
+ x = x + self.drop_path2(self.mlp(self.norm2(x)))
238
+ BT, Np1, C = x.shape
239
+ assert BT == B * T
240
+ x = x.view(B, T, Np1, C)
241
+ x = self.lmim(x)
242
+ x = x.view(B * T, Np1, C)
243
+ return x
244
+
245
+
246
+ class LSViTBackbone(nn.Module):
247
+ def __init__(self, config: ViTConfig):
248
+ super().__init__()
249
+ self.config = config
250
+ self.patch_embed = PatchEmbed(config)
251
+ num_patches = self.patch_embed.num_patches
252
+
253
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim))
254
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, config.embed_dim))
255
+ self.pos_drop = nn.Dropout(config.drop_rate)
256
+
257
+ dpr = torch.linspace(0, config.drop_path_rate, steps=config.depth).tolist()
258
+ self.blocks = nn.ModuleList(
259
+ [
260
+ LSViTBlock(
261
+ dim=config.embed_dim,
262
+ num_heads=config.num_heads,
263
+ mlp_ratio=config.mlp_ratio,
264
+ drop_rate=config.drop_rate,
265
+ attn_drop=config.attn_drop_rate,
266
+ drop_path=dpr[i],
267
+ )
268
+ for i in range(config.depth)
269
+ ]
270
+ )
271
+
272
+ self.norm = nn.LayerNorm(config.embed_dim)
273
+
274
+ nn.init.trunc_normal_(self.cls_token, std=0.02)
275
+ nn.init.trunc_normal_(self.pos_embed, std=0.02)
276
+
277
+ def _interpolate_pos_encoding(self, x: torch.Tensor) -> torch.Tensor:
278
+ B, N, C = x.shape
279
+ num_patches = N - 1
280
+ if num_patches == self.patch_embed.num_patches:
281
+ return self.pos_embed
282
+ cls_pos = self.pos_embed[:, :1]
283
+ patch_pos = self.pos_embed[:, 1:]
284
+ dim = patch_pos.shape[-1]
285
+ gs_old = int(math.sqrt(patch_pos.shape[1]))
286
+ gs_new = int(math.sqrt(num_patches))
287
+ patch_pos = patch_pos.reshape(1, gs_old, gs_old, dim).permute(0, 3, 1, 2)
288
+ patch_pos = F.interpolate(patch_pos, size=(gs_new, gs_new), mode="bicubic", align_corners=False)
289
+ patch_pos = patch_pos.permute(0, 2, 3, 1).reshape(1, gs_new * gs_new, dim)
290
+ return torch.cat([cls_pos, patch_pos], dim=1)
291
+
292
+ def forward(self, video: torch.Tensor) -> torch.Tensor:
293
+ B, T, C, H, W = video.shape
294
+ x = video.reshape(B * T, C, H, W)
295
+ x = self.patch_embed(x)
296
+
297
+ cls_tokens = self.cls_token.expand(x.shape[0], -1, -1)
298
+ x = torch.cat((cls_tokens, x), dim=1)
299
+
300
+ pos_embed = self._interpolate_pos_encoding(x)
301
+ x = x + pos_embed
302
+ x = self.pos_drop(x)
303
+
304
+ for block in self.blocks:
305
+ x = block(x, B, T)
306
+
307
+ x = self.norm(x)
308
+ x = x.view(B, T, x.shape[1], x.shape[2])
309
+ return x
310
+
311
+
312
+ class LSViTForAction(nn.Module):
313
+ def __init__(self, config: ViTConfig, num_classes: int = 51, smif_window: int = 5):
314
+ super().__init__()
315
+ self.smif = SMIFModule(config.in_chans, window_size=smif_window)
316
+ self.backbone = LSViTBackbone(config)
317
+ self.head = nn.Linear(config.embed_dim, num_classes)
318
+
319
+ def forward(self, video: torch.Tensor) -> torch.Tensor:
320
+ x = self.smif(video)
321
+ feats = self.backbone(x)
322
+ cls_tokens = feats[:, :, 0]
323
+ pooled = cls_tokens.mean(dim=1)
324
+ logits = self.head(pooled)
325
+ return logits
326
+
327
+
328
+ HMDB51_CLASSES = [
329
+ "brush_hair", "cartwheel", "catch", "chew", "clap", "climb", "climb_stairs",
330
+ "dive", "draw_sword", "dribble", "drink", "eat", "fall_floor", "fencing",
331
+ "flic_flac", "golf", "handstand", "hit", "hug", "jump", "kick", "kick_ball",
332
+ "kiss", "laugh", "pick", "pour", "pullup", "punch", "push", "pushup",
333
+ "ride_bike", "ride_horse", "run", "shake_hands", "shoot_ball", "shoot_bow",
334
+ "shoot_gun", "sit", "situp", "smile", "smoke", "somersault", "stand",
335
+ "swing_baseball", "sword", "sword_exercise", "talk", "throw", "turn",
336
+ "walk", "wave",
337
+ ]