harpertoken commited on
Commit
321fe9b
·
verified ·
1 Parent(s): 9239869

Upload modeling_move.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_move.py +75 -0
modeling_move.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transformers-compatible wrapper for harpertoken/move.
2
+
3
+ The model classifies KTH actions from 16 frames with max-pooling over time,
4
+ not a transformer. This subclasses PreTrainedModel so the weights serialize
5
+ honestly as config.json plus model.safetensors and load through AutoModel.
6
+ Importing this module registers the architecture.
7
+ """
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers import AutoConfig, AutoModel, PretrainedConfig, PreTrainedModel
12
+
13
+
14
+ class MoveConfig(PretrainedConfig):
15
+ model_type = "move_temporal"
16
+
17
+ def __init__(self, num_labels=6, dropout=0.25, **kwargs):
18
+ super().__init__(**kwargs)
19
+ self.num_labels = num_labels
20
+ self.dropout = dropout
21
+
22
+
23
+ LABELS = ["walking", "jogging", "running", "boxing", "handwaving", "handclapping"]
24
+
25
+
26
+ class MoveTemporal(PreTrainedModel):
27
+ config_class = MoveConfig
28
+ base_model_prefix = "move"
29
+
30
+ # Transformers 5 reads this mapping while finalising a load. Nothing here
31
+ # is tied, but the attribute has to exist or from_pretrained raises
32
+ # AttributeError before the weights are placed.
33
+ all_tied_weights_keys = {}
34
+
35
+ def __init__(self, config):
36
+ super().__init__(config)
37
+ self.cnn = nn.ModuleDict(
38
+ {
39
+ "conv1": nn.Conv2d(1, 32, 3, padding=1),
40
+ "conv2": nn.Conv2d(32, 64, 3, padding=1),
41
+ "fc1": nn.Linear(64 * 8 * 8, 128),
42
+ }
43
+ )
44
+ self.pool = nn.MaxPool2d(2, 2)
45
+ self.adapt = nn.AdaptiveAvgPool2d((8, 8))
46
+ self.head = nn.Linear(128, config.num_labels)
47
+ self.drop = nn.Dropout(config.dropout)
48
+
49
+ def forward(self, clip):
50
+ b, t, _, h, w = clip.shape
51
+ x = clip.view(b * t, 1, h, w)
52
+ x = self.pool(torch.relu(self.cnn["conv1"](x)))
53
+ x = self.pool(torch.relu(self.cnn["conv2"](x)))
54
+ x = self.adapt(x)
55
+ feats = torch.relu(self.cnn["fc1"](x.view(b * t, -1))).view(b, t, -1)
56
+ return self.head(self.drop(feats.amax(1)))
57
+
58
+ def predict_label(self, clip):
59
+ """clip: 16x64x64 float array in [0, 1]. Returns the action."""
60
+ self.eval()
61
+ x = torch.as_tensor(clip, dtype=torch.float32)
62
+ if x.dim() == 3:
63
+ x = x.unsqueeze(0).unsqueeze(0)
64
+ elif x.dim() == 4:
65
+ x = x.unsqueeze(0)
66
+ with torch.no_grad():
67
+ return LABELS[int(self.forward(x).argmax(1)[0])]
68
+
69
+
70
+ def register():
71
+ AutoConfig.register(MoveConfig.model_type, MoveConfig, exist_ok=True)
72
+ AutoModel.register(MoveConfig, MoveTemporal, exist_ok=True)
73
+
74
+
75
+ register()