NikoKKK commited on
Commit
136ad90
·
verified ·
1 Parent(s): b1a08b7

Upload modeling_imu_encoder.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_imu_encoder.py +317 -0
modeling_imu_encoder.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WISDM IMU Masked Encoder — self-supervised Transformer for activity recognition.
2
+
3
+ A pure-PyTorch model for encoding 10-second IMU sensor windows (6-channel
4
+ accelerometer + gyroscope @ 20 Hz) into 192-dim representations. Pretrained
5
+ with masked prediction, SupCon contrastive learning, and LMM frequency loss
6
+ on the WISDM smartphone+smartwatch dataset (18 activity classes).
7
+
8
+ Usage:
9
+ from modeling_imu_encoder import IMUMaskedEncoder
10
+
11
+ model = IMUMaskedEncoder.from_pretrained("NikoKKK/IMU-SelfSupEncoder-v1")
12
+ model.eval()
13
+
14
+ # Input: (B, 6, 200) tensor — 6 IMU channels, 200 timesteps
15
+ with torch.no_grad():
16
+ patch_out, intermediates, cls_out, global_freq = model(x)
17
+ # cls_out: (B, 192) — global representation for classification
18
+ # patch_out: (B, 20, 192) — per-window-patch embeddings
19
+ # intermediates: {layer_idx: (B, 20, 192)} — intermediate layer outputs
20
+ """
21
+
22
+ import math
23
+ import json
24
+ import os
25
+ from typing import Dict, List, Optional, Tuple
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Configuration
34
+ # ---------------------------------------------------------------------------
35
+
36
+ class IMUEncoderConfig:
37
+ """Configuration for IMUMaskedEncoder.
38
+
39
+ Attributes:
40
+ n_channels (int): Number of IMU sensor channels (default: 6).
41
+ patch_size (int): Conv-stem patch size in timesteps (default: 10).
42
+ n_patches (int): Number of patches per window (default: 20).
43
+ embed_dim (int): Embedding dimension (default: 192).
44
+ n_layers (int): Number of Transformer encoder layers (default: 4).
45
+ n_heads (int): Number of attention heads (default: 6).
46
+ mlp_ratio (float): MLP hidden/embed_dim ratio (default: 3.0).
47
+ dropout (float): Dropout probability (default: 0.1).
48
+ target_layers (List[int]): Layers collected as intermediate outputs.
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ n_channels: int = 6,
54
+ patch_size: int = 10,
55
+ n_patches: int = 20,
56
+ embed_dim: int = 192,
57
+ n_layers: int = 4,
58
+ n_heads: int = 6,
59
+ mlp_ratio: float = 3.0,
60
+ dropout: float = 0.1,
61
+ target_layers: Optional[List[int]] = None,
62
+ **kwargs,
63
+ ):
64
+ self.n_channels = n_channels
65
+ self.patch_size = patch_size
66
+ self.n_patches = n_patches
67
+ self.embed_dim = embed_dim
68
+ self.n_layers = n_layers
69
+ self.n_heads = n_heads
70
+ self.mlp_ratio = mlp_ratio
71
+ self.dropout = dropout
72
+ self.target_layers = target_layers or [2, 4]
73
+
74
+ @classmethod
75
+ def from_dict(cls, d: dict) -> "IMUEncoderConfig":
76
+ return cls(**{k: v for k, v in d.items() if not k.startswith("_")})
77
+
78
+ def to_dict(self) -> dict:
79
+ return {
80
+ "n_channels": self.n_channels,
81
+ "patch_size": self.patch_size,
82
+ "n_patches": self.n_patches,
83
+ "embed_dim": self.embed_dim,
84
+ "n_layers": self.n_layers,
85
+ "n_heads": self.n_heads,
86
+ "mlp_ratio": self.mlp_ratio,
87
+ "dropout": self.dropout,
88
+ "target_layers": self.target_layers,
89
+ }
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # Sub-modules
94
+ # ---------------------------------------------------------------------------
95
+
96
+ class PatchTimeFreqEmbedding(nn.Module):
97
+ """Conv-stem per-patch time + local frequency fusion -> embed_dim tokens."""
98
+
99
+ def __init__(self, config: IMUEncoderConfig):
100
+ super().__init__()
101
+ half_dim = config.embed_dim // 2
102
+ self.conv_stem = nn.Conv1d(
103
+ config.n_channels, half_dim, kernel_size=config.patch_size,
104
+ stride=config.patch_size, bias=False,
105
+ )
106
+ n_freq_bins = config.patch_size // 2 + 1
107
+ self.freq_proj = nn.Linear(config.n_channels * n_freq_bins, half_dim)
108
+ self.pos_embed = nn.Parameter(
109
+ torch.randn(1, config.n_patches + 1, config.embed_dim) * 0.02
110
+ )
111
+ self.fusion = nn.Linear(config.embed_dim, config.embed_dim)
112
+ self.norm = nn.LayerNorm(config.embed_dim)
113
+ self.patch_size = config.patch_size
114
+ self.n_patches = config.n_patches
115
+
116
+ # FFT over full 200-timestep signal: rfft(200) → 101 bins, then .mean(dim=1)
117
+ n_global_freq_bins = config.patch_size * config.n_patches // 2 + 1
118
+ self.global_freq_proj = nn.Linear(n_global_freq_bins, config.embed_dim, bias=False)
119
+
120
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
121
+ B, C, T = x.shape
122
+ time_feat = self.conv_stem(x)
123
+
124
+ x_patch = x.view(B, C, self.n_patches, self.patch_size)
125
+ x_patch_centered = x_patch - x_patch.mean(dim=-1, keepdim=True)
126
+ freq_mag = torch.abs(torch.fft.rfft(x_patch_centered, dim=-1))
127
+ n_freq = freq_mag.size(-1)
128
+ freq_flat = freq_mag.permute(0, 2, 1, 3).reshape(B, self.n_patches, C * n_freq)
129
+ freq_feat = self.freq_proj(freq_flat).transpose(1, 2)
130
+
131
+ combined = torch.cat([time_feat, freq_feat], dim=1)
132
+ tokens = self.fusion(combined.transpose(1, 2))
133
+
134
+ full_freq = torch.abs(torch.fft.rfft(x, dim=-1)).mean(dim=1)
135
+ global_freq = self.global_freq_proj(full_freq).unsqueeze(1)
136
+
137
+ tokens = tokens + self.pos_embed[:, :self.n_patches, :]
138
+ global_freq = global_freq + self.pos_embed[:, self.n_patches:self.n_patches + 1, :]
139
+ tokens = self.norm(tokens)
140
+ global_freq = self.norm(global_freq)
141
+ return tokens, global_freq
142
+
143
+
144
+ class TransformerEncoder(nn.Module):
145
+ """Standard Transformer encoder, collects intermediate layer outputs."""
146
+
147
+ def __init__(self, config: IMUEncoderConfig):
148
+ super().__init__()
149
+ self.n_layers = config.n_layers
150
+ self.collect_layers = config.target_layers
151
+ self.cls_token = nn.Parameter(torch.randn(1, 1, config.embed_dim) * 0.02)
152
+ self.layers = nn.ModuleList([
153
+ nn.TransformerEncoderLayer(
154
+ d_model=config.embed_dim,
155
+ nhead=config.n_heads,
156
+ dim_feedforward=int(config.embed_dim * config.mlp_ratio),
157
+ dropout=config.dropout,
158
+ activation="gelu",
159
+ batch_first=True,
160
+ norm_first=True,
161
+ )
162
+ for _ in range(config.n_layers)
163
+ ])
164
+ self.final_norm = nn.LayerNorm(config.embed_dim)
165
+ self.dropout = nn.Dropout(config.dropout)
166
+
167
+ def forward(self, x: torch.Tensor):
168
+ B = x.shape[0]
169
+ cls_tokens = self.cls_token.expand(B, -1, -1)
170
+ x = torch.cat([cls_tokens, self.dropout(x)], dim=1)
171
+
172
+ intermediates = {}
173
+ for i, layer in enumerate(self.layers):
174
+ x = layer(x)
175
+ layer_idx = i + 1
176
+ if layer_idx in self.collect_layers:
177
+ intermediates[layer_idx] = self.final_norm(x[:, 1:, :])
178
+
179
+ x = self.final_norm(x)
180
+ cls_out = x[:, 0, :]
181
+ patch_out = x[:, 1:, :]
182
+ if self.n_layers in self.collect_layers:
183
+ intermediates[self.n_layers] = patch_out
184
+ return patch_out, intermediates, cls_out
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Main model
189
+ # ---------------------------------------------------------------------------
190
+
191
+ class IMUMaskedEncoder(nn.Module):
192
+ """Self-supervised encoder for IMU-based human activity recognition.
193
+
194
+ Input: (B, 6, 200) — 6-channel IMU window (accel_x/y/z, gyro_x/y/z) @ 20 Hz.
195
+ Output: patch_out (B, 20, 192), intermediates dict, cls_out (B, 192),
196
+ global_freq (B, 1, 192).
197
+
198
+ The CLS token (`cls_out`) is the primary global representation for
199
+ downstream classification. Intermediate layer outputs can be used for
200
+ multi-level feature extraction or distillation.
201
+
202
+ Usage:
203
+ model = IMUMaskedEncoder.from_pretrained("NikoKKK/IMU-SelfSupEncoder-v1")
204
+ model.eval()
205
+
206
+ x = torch.randn(8, 6, 200) # 8 windows of 10 seconds each
207
+ with torch.no_grad():
208
+ patch_out, intermediates, cls_out, global_freq = model(x)
209
+
210
+ print(cls_out.shape) # (8, 192)
211
+ """
212
+
213
+ _HUB_URL = "https://huggingface.co/NikoKKK/IMU-SelfSupEncoder-v1"
214
+
215
+ def __init__(self, config: IMUEncoderConfig):
216
+ super().__init__()
217
+ self.config = config
218
+ self.embed = PatchTimeFreqEmbedding(config)
219
+ self.transformer = TransformerEncoder(config)
220
+ self.mask_token = nn.Parameter(torch.randn(1, 1, config.embed_dim) * 0.02)
221
+
222
+ @classmethod
223
+ def from_pretrained(cls, model_id: str = "NikoKKK/IMU-SelfSupEncoder-v1",
224
+ force_download: bool = False) -> "IMUMaskedEncoder":
225
+ """Load pretrained model from Hugging Face Hub or local path.
226
+
227
+ Args:
228
+ model_id: Hugging Face model ID (e.g. "NikoKKK/IMU-SelfSupEncoder-v1")
229
+ or local directory path.
230
+ force_download: Force re-download from Hub.
231
+
232
+ Returns:
233
+ IMUMaskedEncoder with pretrained weights loaded.
234
+ """
235
+ from huggingface_hub import hf_hub_download
236
+ from safetensors.torch import load_file
237
+
238
+ # Determine if model_id is a local path
239
+ if os.path.isdir(model_id):
240
+ config_path = os.path.join(model_id, "config.json")
241
+ weights_path = os.path.join(model_id, "model.safetensors")
242
+ else:
243
+ config_path = hf_hub_download(
244
+ model_id, "config.json", force_download=force_download,
245
+ )
246
+ weights_path = hf_hub_download(
247
+ model_id, "model.safetensors", force_download=force_download,
248
+ )
249
+
250
+ with open(config_path, "r") as f:
251
+ config_dict = json.load(f)
252
+ config = IMUEncoderConfig.from_dict(config_dict)
253
+
254
+ model = cls(config)
255
+ state_dict = load_file(weights_path)
256
+ model.load_state_dict(state_dict, strict=True)
257
+ return model
258
+
259
+ def forward(self, x: torch.Tensor, mask_matrix=None):
260
+ """Forward pass.
261
+
262
+ Args:
263
+ x: (B, C, T) tensor — IMU sensor window.
264
+ Expected C=6 (accel_x,y,z + gyro_x,y,z), T=200 @ 20 Hz.
265
+ mask_matrix: Optional (B, N_patches) boolean tensor. When given,
266
+ masked positions are replaced with [MASK] tokens.
267
+ Used during pretraining only.
268
+
269
+ Returns:
270
+ patch_out: (B, N_patches, embed_dim)
271
+ intermediates: {layer_idx: (B, N_patches, embed_dim)}
272
+ cls_out: (B, embed_dim) — global representation
273
+ global_freq: (B, 1, embed_dim) — global frequency token
274
+ """
275
+ B, C, T = x.shape
276
+ tokens, global_freq = self.embed(x)
277
+
278
+ if mask_matrix is not None:
279
+ mask_tok = self.mask_token.expand(B, tokens.size(1), -1)
280
+ tokens = torch.where(mask_matrix.unsqueeze(-1), mask_tok, tokens)
281
+
282
+ input_tokens = torch.cat([global_freq, tokens], dim=1)
283
+ full_out, intermediates, cls_out = self.transformer(input_tokens)
284
+
285
+ # Remove global_freq position from patch outputs
286
+ patch_out = full_out[:, 1:, :]
287
+ trimmed_intermediates = {k: v[:, 1:, :] for k, v in intermediates.items()}
288
+
289
+ return patch_out, trimmed_intermediates, cls_out, global_freq
290
+
291
+ def encode(self, x: torch.Tensor) -> torch.Tensor:
292
+ """Extract CLS token embedding for downstream tasks.
293
+
294
+ Args:
295
+ x: (B, 6, 200) IMU sensor window.
296
+
297
+ Returns:
298
+ (B, embed_dim) global representation.
299
+ """
300
+ _, _, cls_out, _ = self.forward(x)
301
+ return cls_out
302
+
303
+ def encode_with_layers(self, x: torch.Tensor) -> Dict[int, torch.Tensor]:
304
+ """Extract multi-level intermediate representations.
305
+
306
+ Args:
307
+ x: (B, 6, 200) IMU sensor window.
308
+
309
+ Returns:
310
+ {layer_idx: (B, N_patches, embed_dim)} for configured target layers.
311
+ """
312
+ _, intermediates, _, _ = self.forward(x)
313
+ return intermediates
314
+
315
+
316
+ # For HF AutoModel compatibility
317
+ IMUMaskedEncoder.config_class = IMUEncoderConfig