File size: 16,399 Bytes
0107764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""SetCon: setup-conditioned IMU encoder with its calibrator (Hugging Face remote code).

    model = AutoModel.from_pretrained("<repo>", trust_remote_code=True)              # seed 1
    model = AutoModel.from_pretrained("<repo>", subfolder="seed2", trust_remote_code=True)

Two networks share one checkpoint:
  encoder     spatio-temporal graph network over 22 body sites and 0.2-s patches -> 512-d window embedding in the
              space of the frozen CLIP ViT-B/32 text encoder (paper Sec. 3.3)
  calibrator  estimates the setup reference of one device, the rotation from device axes into the segment frame,
              from a few unlabeled windows, as a mixture of two Matrix-Fisher densities on SO(3) (paper Sec. 3.2)

Input preparation (gravity canonicalization, site names) lives in processing_setcon.py.
"""
from __future__ import annotations

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel

from .configuration_setcon import SetConConfig
from .processing_setcon import (BODY_PART_OF_SITE, SIDE_OF_SITE, SITE_INDEX, SITE_PARENTS, calibrator_input,
                                select_by_elimination, tilt_score, tilt_sigma)


# ---------------------------------------------------------------------------------------------- encoder
def body_adjacency(parents=SITE_PARENTS):
    """A[partition, receiver, sender] for the partitions self, parent -> child, child -> parent (row-normalized)."""
    n = len(parents)
    a = torch.zeros(3, n, n)
    a[0] = torch.eye(n)
    for child, parent in enumerate(parents):
        if parent >= 0:
            a[1, child, parent] = 1
            a[2, parent, child] = 1
    return a / a.sum(-1, keepdim=True).clamp_min(1)


class GraphBlock(nn.Module):
    """One residual block: graph convolution over the sites (learned edge weights), then a convolution along time
    over `temporal_kernel` patches. Tensors are (batch, sites, patches, width); padded patches stay zero."""

    def __init__(self, width, temporal_kernel=9):
        super().__init__()
        self.norm_spatial = nn.LayerNorm(width)
        self.spatial = nn.Linear(width, 3 * width)
        self.norm_temporal = nn.LayerNorm(width)
        self.temporal = nn.Conv2d(width, width, (temporal_kernel, 1), padding=(temporal_kernel // 2, 0))
        self.register_buffer("adjacency", body_adjacency())
        self.edge_importance = nn.Parameter(torch.ones(3, len(SITE_PARENTS), len(SITE_PARENTS)))

    def forward(self, x, patch_valid):
        b, v, p, d = x.shape
        valid = patch_valid[:, None, :, None]
        h = self.spatial(self.norm_spatial(x)).reshape(b, v, p, 3, d)
        a = self.adjacency * self.edge_importance
        h = torch.einsum("bspkd,kvs->bvpd", h, a)
        h = self.norm_temporal(F.gelu(h))
        h = h.masked_fill(~valid, 0)                    # biases must not turn padded time into evidence
        h = self.temporal(h.permute(0, 3, 2, 1)).permute(0, 3, 2, 1)
        return (x + h).masked_fill(~valid, 0)


class SetConEncoder(nn.Module):
    """Patch tokens of every site -> graph blocks -> mean over worn sites and valid patches -> text space.

    A worn site holds one token per patch (a linear map of its 4 frames x 9 channels). A site without a device holds
    a learned mask token that relays information between worn sites; its output is never pooled. Every token also
    gets learned embeddings of its site, its patch and its gyroscope flag, plus a linear map of the 44 worn-site and
    gyroscope flags (the setup token)."""

    def __init__(self, config):
        super().__init__()
        d, S, P = config.hidden_size, config.num_sites, config.num_patches
        patch_values = config.frames_per_patch * config.input_channels
        self.patch_embed = nn.Linear(patch_values, d)
        self.site_embedding = nn.Parameter(torch.zeros(S, d))
        self.time_embedding = nn.Parameter(torch.zeros(P, d))
        self.gyro_flag_embedding = nn.Parameter(torch.zeros(2, d))
        self.mask_token = nn.Parameter(torch.zeros(d))
        self.setup_embed = nn.Linear(2 * S, d)
        self.blocks = nn.ModuleList([GraphBlock(d, config.temporal_kernel) for _ in range(config.num_graph_blocks)])
        self.final_norm = nn.LayerNorm(d)
        self.text_projection = nn.Linear(d, config.embedding_dim)
        self.logit_scale = nn.Parameter(torch.zeros(()))          # learned CLIP temperature (log); not needed to embed

    def forward(self, x, worn, gyro, patch_valid):
        """x (B, sites, patches, 36) scaled patch values, worn / gyro (B, sites) bool, patch_valid (B, patches) bool
        -> unit embeddings (B, embedding_dim)."""
        observed = worn[:, :, None] & patch_valid[:, None, :]
        tok = self.patch_embed(x.masked_fill(~observed[..., None], 0))
        tok = torch.where(observed[..., None], tok, self.mask_token)
        gyro = gyro & worn
        setup = self.setup_embed(torch.cat([worn.float(), gyro.float()], dim=1))
        tok = tok + self.site_embedding[None, :, None, :] + self.time_embedding[None, None, :, :] \
            + self.gyro_flag_embedding[gyro.long()][:, :, None, :] + setup[:, None, None, :]
        tok = tok.masked_fill(~patch_valid[:, None, :, None], 0)
        for block in self.blocks:
            tok = block(tok, patch_valid)
        e = self.final_norm(tok).masked_fill(~observed[..., None], 0)
        w = observed.float()[..., None]
        pooled = (e * w).sum(dim=(1, 2)) / w.sum(dim=(1, 2)).clamp(min=1.0)
        return F.normalize(self.text_projection(pooled), dim=-1)


# ---------------------------------------------------------------------------------------------- calibrator
def gram_schmidt(v):
    """(..., 6) -> rotation matrices (..., 3, 3) whose first two columns follow the two 3-vectors."""
    a1, a2 = v[..., 0:3], v[..., 3:6]
    b1 = F.normalize(a1, dim=-1, eps=1e-6)
    b2 = F.normalize(a2 - (b1 * a2).sum(-1, keepdim=True) * b1, dim=-1, eps=1e-6)
    b3 = torch.cross(b1, b2, dim=-1)
    return torch.stack([b1, b2, b3], dim=-1)


CONCENTRATION_MAX = 3000.0


class SetConCalibrator(nn.Module):
    """Set network over the unlabeled windows of one device.

    Each window (T frames x 7 channels: acceleration and angular velocity in device axes, each divided by one scalar,
    plus a missing-gyroscope flag) passes a small 1-D CNN; embeddings of body part, side and gyroscope flag are added;
    two per-window residual MLP blocks follow; the set is pooled order-invariantly as [mean; max]; an MLP head outputs
    a mixture of two Matrix-Fisher densities F_c = M_c V_c diag(s_c) V_c^T over the setup reference."""

    def __init__(self, config):
        super().__init__()
        d = config.calibrator_hidden_size
        self.conv_layers = nn.ModuleList()
        c_in = 7
        for c_out, stride in zip(config.calibrator_conv_channels, config.calibrator_conv_strides):
            self.conv_layers.append(nn.ModuleDict(dict(
                conv=nn.Conv1d(c_in, c_out, 5, stride=stride, padding=2), norm=nn.GroupNorm(8, c_out))))
            c_in = c_out
        self.strides = tuple(config.calibrator_conv_strides)
        self.window_mlp = nn.Sequential(nn.Linear(2 * c_in, d), nn.GELU(), nn.Linear(d, d))
        self.body_part_embedding = nn.Embedding(config.calibrator_body_parts, d)
        self.side_embedding = nn.Embedding(config.calibrator_sides, d)
        self.missing_gyro_embedding = nn.Embedding(2, d)
        self.set_blocks = nn.ModuleList([nn.ModuleDict(dict(
            norm=nn.LayerNorm(d), mlp=nn.Sequential(nn.Linear(d, 2 * d), nn.GELU(), nn.Linear(2 * d, d))))
            for _ in range(config.calibrator_set_blocks)])
        self.pool_norm = nn.LayerNorm(d)
        self.pool_mlp = nn.Sequential(nn.Linear(2 * d, d), nn.GELU(), nn.Linear(d, d))
        self.n_components = config.calibrator_components
        self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, 2 * d), nn.GELU(), nn.Linear(2 * d, self.n_components * 16))

    def window_features(self, w, valid):
        """w (B*, T, 7), valid (B*, T) -> (B*, d): CNN, then masked mean and max over time."""
        dtype = self.window_mlp[0].weight.dtype
        h = w.to(dtype).transpose(1, 2)
        m = valid.to(dtype)[:, None, :]
        for layer, stride in zip(self.conv_layers, self.strides):
            h = F.gelu(layer["norm"](layer["conv"](h * m)))
            if stride > 1:
                m = F.max_pool1d(m, kernel_size=stride, stride=stride, ceil_mode=True)[..., :h.shape[-1]]
        count = m.sum(-1).clamp(min=1.0)
        mean = (h * m).sum(-1) / count
        mx = h.masked_fill(m < 0.5, -1e4).amax(-1)
        mx = torch.where(m.sum(-1) > 0, mx, torch.zeros_like(mx))
        return self.window_mlp(torch.cat([mean, mx], -1))

    def forward(self, windows, valid, set_mask, body_part, side, gyro_missing):
        """windows (B, N, T, 7), valid (B, N, T), set_mask (B, N) True = window present, body_part / side /
        gyro_missing (B,). Returns dict(M, V (B, C, 3, 3), s (B, C, 3), logit (B, C))."""
        B, N, T, _ = windows.shape
        f = self.window_features(windows.reshape(B * N, T, -1), valid.reshape(B * N, T)).reshape(B, N, -1)
        meta = self.body_part_embedding(body_part) + self.side_embedding(side) \
            + self.missing_gyro_embedding(gyro_missing.long())
        h = f + meta[:, None]
        for block in self.set_blocks:
            h = h + block["mlp"](block["norm"](h))
        x = self.pool_norm(h)
        m = set_mask.to(x.dtype)[..., None]
        count = m.sum(1).clamp(min=1.0)
        mean = (x * m).sum(1) / count
        mx = x.masked_fill(m < 0.5, -1e4).amax(1)
        mx = torch.where(count > 0.5, mx, torch.zeros_like(mx))
        o = self.head(self.pool_mlp(torch.cat([mean, mx], -1)) + meta)
        o = (o.float() if o.dtype in (torch.float16, torch.bfloat16) else o).reshape(B, self.n_components, 16)
        M = gram_schmidt(o[..., 0:6])
        V = gram_schmidt(o[..., 6:12])
        s = CONCENTRATION_MAX * torch.sigmoid(o[..., 12:15] - 8.0)
        return dict(M=M, V=V, s=s, logit=o[..., 15])


# ---------------------------------------------------------------------------------------------- model
class SetConModel(PreTrainedModel):
    """Encoder + calibrator of one SetCon checkpoint, with NumPy helpers for inference.

    Reference settings of the paper: encoder on CUDA under bfloat16 autocast with batches of 64 windows; calibrator
    on CPU in float32. Other devices, precisions or batch sizes give embeddings that differ in the last bits."""

    config_class = SetConConfig
    base_model_prefix = "setcon"
    main_input_name = "windows"

    def __init__(self, config: SetConConfig):
        super().__init__(config)
        self.encoder = SetConEncoder(config)
        self.calibrator = SetConCalibrator(config)
        self.post_init()

    def _init_weights(self, module):
        """Weights always come from a checkpoint; nothing to initialize."""

    # ---------------------------------------------------------------- encoder
    def encoder_inputs(self, windows):
        """(B, 200, 22, 9) float tensor -> encoder arguments (patch values, worn, gyro, patch_valid)."""
        cfg = self.config
        xb = windows.float().clone()
        worn = xb.abs().sum(dim=(1, 3)) > 0
        gyro = xb[..., 3:6].abs().sum(dim=(1, 3)) > 0
        frame_valid = xb.abs().sum(dim=(2, 3)) > 0
        patch_valid = frame_valid.reshape(-1, cfg.num_patches, cfg.frames_per_patch).all(dim=2)
        xb[..., 0:3] /= cfg.force_scale
        xb[..., 3:6] /= cfg.rate_scale
        x = xb.permute(0, 2, 1, 3).reshape(-1, cfg.num_sites, cfg.num_patches,
                                           cfg.frames_per_patch * cfg.input_channels)
        return x, worn, gyro, patch_valid

    def forward(self, windows):
        """windows (B, 200, 22, 9) -> unit embeddings (B, 512) in the CLIP ViT-B/32 text space."""
        x, worn, gyro, patch_valid = self.encoder_inputs(windows)
        return self.encoder(x, worn, gyro, patch_valid)

    @torch.no_grad()
    def embed(self, windows, batch_size=64):
        """NumPy windows (N, 200, 22, 9) -> NumPy unit embeddings (N, 512) float32, computed on the encoder's device
        (bfloat16 autocast on CUDA)."""
        device = next(self.encoder.parameters()).device
        out = []
        for i in range(0, len(windows), batch_size):
            x, worn, gyro, patch_valid = self.encoder_inputs(torch.from_numpy(np.asarray(windows[i:i + batch_size])))
            with torch.autocast("cuda", dtype=torch.bfloat16, enabled=device.type == "cuda"):
                z = self.encoder(x.to(device), worn.to(device), gyro.to(device), patch_valid.to(device))
            out.append(z.float().cpu())
        return torch.cat(out).numpy() if out else np.zeros((0, self.config.embedding_dim), np.float32)

    # ---------------------------------------------------------------- calibrator
    @torch.no_grad()
    def calibrate_batch(self, inputs, valid, sites, gyro_missing):
        """One calibrator pass over many devices with the same number of context windows.

        inputs (B, n, T, 7) float32 and valid (B, n, T) from processing_setcon.calibrator_input, sites (B,) site
        indices, gyro_missing (B,) bool. Returns NumPy float64 arrays: reference (B, 3, 3) = mode of the heaviest
        component, and the mixture parameters M, V, s, logit."""
        device = next(self.calibrator.parameters()).device
        w = torch.from_numpy(np.stack(inputs) if isinstance(inputs, (list, tuple)) else inputs).float()
        v = torch.from_numpy(np.stack(valid) if isinstance(valid, (list, tuple)) else valid)
        site = torch.as_tensor(np.asarray(sites)).long()
        part = torch.as_tensor(np.asarray(BODY_PART_OF_SITE))[site]
        side = torch.as_tensor(np.asarray(SIDE_OF_SITE))[site]
        set_mask = torch.ones(w.shape[:2], dtype=torch.bool)
        out = self.calibrator(w.to(device), v.to(device), set_mask.to(device), part.to(device), side.to(device),
                              torch.tensor(list(gyro_missing)).to(device))
        heaviest = out["logit"].argmax(-1)
        reference = out["M"][torch.arange(len(heaviest), device=heaviest.device), heaviest]
        res = {k: out[k].double().cpu().numpy() for k in ("M", "V", "s", "logit")}
        res["reference"] = reference.double().cpu().numpy()
        return res

    def estimate_reference(self, context, site, has_gyro=None):
        """Setup reference of one device from its unlabeled context windows.

        context (n, 200, 9) windows of the device as prepared by processing_setcon.prepare_device, site a name from
        processing_setcon.SITE_NAMES. Returns dict(reference (3, 3), tilt_sigma_deg)."""
        context = np.asarray(context, np.float32)
        if has_gyro is None:
            has_gyro = bool(np.abs(context[..., 3:6]).sum() > 0)
        w, v = calibrator_input(context, has_gyro, self.config.force_scale, self.config.rate_scale)
        res = self.calibrate_batch(w[None], v[None], [SITE_INDEX[site]], [not has_gyro])
        c = int(res["logit"][0].argmax())
        sigma = float(tilt_sigma(res["M"][0, c], res["V"][0, c], res["s"][0, c]))
        return dict(reference=res["reference"][0], tilt_sigma_deg=float(np.degrees(sigma)))

    def select_context(self, windows, site, keep=6, has_gyro=None):
        """Paper Sec. 3.5: from a pool of unlabeled windows of one device (n, 200, 9), repeatedly drop the window
        whose removal leaves the smallest tilt uncertainty until `keep` remain. Returns their positions."""
        windows = np.asarray(windows, np.float32)
        if has_gyro is None:
            has_gyro = bool(np.abs(windows[..., 3:6]).sum() > 0)
        w, v = calibrator_input(windows, has_gyro, self.config.force_scale, self.config.rate_scale)
        site_idx = SITE_INDEX[site]

        def score(requests):
            res = self.calibrate_batch(np.stack([w[list(p)] for _, p in requests]),
                                       np.stack([v[list(p)] for _, p in requests]),
                                       [site_idx] * len(requests), [not has_gyro] * len(requests))
            sc = tilt_score(res["M"], res["V"], res["s"], res["logit"])
            return {(key, p): float(sc[i]) for i, (key, p) in enumerate(requests)}

        return select_by_elimination({0: len(windows)}, score, keep)[0]