| from __future__ import annotations |
|
|
| import math |
|
|
| import torch |
| from torch import nn |
| import torch.nn.functional as F |
|
|
| from .features import COCO_BONES, NUM_JOINTS |
|
|
|
|
| def coco_adjacency(device: torch.device | None = None) -> torch.Tensor: |
| a = torch.eye(NUM_JOINTS, dtype=torch.float32, device=device) |
| for i, j in COCO_BONES: |
| a[i, j] = 1 |
| a[j, i] = 1 |
| deg = a.sum(-1, keepdim=True).clamp_min(1) |
| return a / deg |
|
|
|
|
| class GraphTemporalBlock(nn.Module): |
| def __init__(self, in_ch: int, out_ch: int, adaptive: bool = False, channel_refine: bool = False): |
| super().__init__() |
| self.register_buffer("base_adj", coco_adjacency()) |
| self.adaptive = adaptive |
| self.channel_refine = channel_refine |
| if adaptive: |
| self.delta = nn.Parameter(torch.zeros(NUM_JOINTS, NUM_JOINTS)) |
| if channel_refine: |
| self.channel_gate = nn.Parameter(torch.zeros(out_ch, NUM_JOINTS, NUM_JOINTS)) |
| self.spatial = nn.Linear(in_ch, out_ch) |
| self.temporal = nn.Sequential( |
| nn.Conv2d(out_ch, out_ch, kernel_size=(3, 1), padding=(1, 0)), |
| nn.BatchNorm2d(out_ch), |
| nn.ReLU(inplace=True), |
| ) |
| self.res = nn.Linear(in_ch, out_ch) if in_ch != out_ch else nn.Identity() |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor: |
| |
| adj = self.base_adj |
| if self.adaptive: |
| adj = adj + torch.softmax(self.delta, dim=-1) |
| h = torch.einsum("btvc,vw->btwc", x, adj) |
| h = self.spatial(h) |
| if self.channel_refine: |
| ref = torch.softmax(self.channel_gate, dim=-1) |
| h2 = torch.einsum("btvc,cvw->btwc", h, ref) |
| h = h + h2 |
| h = h + self.res(x) |
| h = h.permute(0, 3, 1, 2) |
| h = self.temporal(h) |
| return h.permute(0, 2, 3, 1) |
|
|
|
|
| class GraphEncoder(nn.Module): |
| def __init__(self, in_ch: int, hidden: int, adaptive: bool = False, channel_refine: bool = False): |
| super().__init__() |
| self.net = nn.Sequential( |
| GraphTemporalBlock(in_ch, hidden, adaptive, channel_refine), |
| GraphTemporalBlock(hidden, hidden, adaptive, channel_refine), |
| GraphTemporalBlock(hidden, hidden, adaptive, channel_refine), |
| ) |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor: |
| h = self.net(x) |
| return h.mean(dim=(1, 2)) |
|
|
|
|
| class LSTMClassifier(nn.Module): |
| def __init__(self, hidden: int = 96, num_classes: int = 2, **_: object): |
| super().__init__() |
| self.lstm = nn.LSTM(NUM_JOINTS * 3, hidden, batch_first=True, bidirectional=True) |
| self.head = nn.Sequential(nn.Dropout(0.25), nn.Linear(hidden * 2, num_classes)) |
|
|
| def forward(self, batch: dict[str, torch.Tensor]) -> torch.Tensor: |
| x = batch["joint"].flatten(2) |
| out, _ = self.lstm(x) |
| return self.head(out[:, -1]) |
|
|
|
|
| class STGCNClassifier(nn.Module): |
| def __init__(self, hidden: int = 96, num_classes: int = 2, **_: object): |
| super().__init__() |
| self.enc = GraphEncoder(3, hidden) |
| self.head = nn.Linear(hidden, num_classes) |
|
|
| def forward(self, batch: dict[str, torch.Tensor]) -> torch.Tensor: |
| return self.head(self.enc(batch["joint"])) |
|
|
|
|
| class AGCNClassifier(nn.Module): |
| def __init__(self, hidden: int = 96, num_classes: int = 2, **_: object): |
| super().__init__() |
| self.joint = GraphEncoder(3, hidden, adaptive=True) |
| self.bone = GraphEncoder(3, hidden, adaptive=True) |
| self.head = nn.Linear(hidden * 2, num_classes) |
|
|
| def forward(self, batch: dict[str, torch.Tensor]) -> torch.Tensor: |
| h = torch.cat([self.joint(batch["joint"]), self.bone(batch["bone"])], dim=1) |
| return self.head(h) |
|
|
|
|
| class CTRGCNClassifier(nn.Module): |
| def __init__(self, hidden: int = 96, num_classes: int = 2, **_: object): |
| super().__init__() |
| self.joint = GraphEncoder(3, hidden, adaptive=True, channel_refine=True) |
| self.bone = GraphEncoder(3, hidden, adaptive=True, channel_refine=True) |
| self.head = nn.Linear(hidden * 2, num_classes) |
|
|
| def forward(self, batch: dict[str, torch.Tensor]) -> torch.Tensor: |
| h = torch.cat([self.joint(batch["joint"]), self.bone(batch["bone"])], dim=1) |
| return self.head(h) |
|
|
|
|
| class TCNTEClassifier(nn.Module): |
| def __init__(self, hidden: int = 96, num_classes: int = 2, **_: object): |
| super().__init__() |
| self.proj = nn.Linear(NUM_JOINTS * 3, hidden) |
| self.tcn = nn.Sequential( |
| nn.Conv1d(hidden, hidden, 3, padding=1), |
| nn.ReLU(inplace=True), |
| nn.Conv1d(hidden, hidden, 3, padding=2, dilation=2), |
| nn.ReLU(inplace=True), |
| ) |
| layer = nn.TransformerEncoderLayer(hidden, nhead=4, batch_first=True, dim_feedforward=hidden * 2) |
| self.tx = nn.TransformerEncoder(layer, num_layers=2) |
| self.head = nn.Linear(hidden, num_classes) |
|
|
| def forward(self, batch: dict[str, torch.Tensor]) -> torch.Tensor: |
| x = self.proj(batch["joint"].flatten(2)) |
| x = self.tcn(x.transpose(1, 2)).transpose(1, 2) |
| x = self.tx(x) |
| return self.head(x.mean(1)) |
|
|
|
|
| class PoseC3DClassifier(nn.Module): |
| def __init__(self, hidden: int = 96, num_classes: int = 2, **_: object): |
| super().__init__() |
| self.net = nn.Sequential( |
| nn.Conv3d(1, 16, kernel_size=3, padding=1), |
| nn.BatchNorm3d(16), |
| nn.ReLU(inplace=True), |
| nn.MaxPool3d((1, 2, 2)), |
| nn.Conv3d(16, 32, kernel_size=3, padding=1), |
| nn.BatchNorm3d(32), |
| nn.ReLU(inplace=True), |
| nn.AdaptiveAvgPool3d(1), |
| ) |
| self.head = nn.Linear(32, num_classes) |
|
|
| def forward(self, batch: dict[str, torch.Tensor]) -> torch.Tensor: |
| heat = pose_heatmap(batch["joint"]) |
| h = self.net(heat).flatten(1) |
| return self.head(h) |
|
|
|
|
| def pose_heatmap(joint: torch.Tensor, size: int = 32, sigma: float = 1.5) -> torch.Tensor: |
| b, t, v, _ = joint.shape |
| xy = (joint[..., :2].clamp(-1.5, 1.5) + 1.5) / 3.0 * (size - 1) |
| conf = joint[..., 2].clamp(0, 1) |
| yy, xx = torch.meshgrid( |
| torch.arange(size, device=joint.device), |
| torch.arange(size, device=joint.device), |
| indexing="ij", |
| ) |
| grid = torch.stack([xx, yy], dim=0).float() |
| heat = [] |
| for k in range(v): |
| mu = xy[:, :, k].view(b, t, 2, 1, 1) |
| dist = ((grid.view(1, 1, 2, size, size) - mu) ** 2).sum(2) |
| hm = torch.exp(-dist / (2 * sigma * sigma)) * conf[:, :, k].view(b, t, 1, 1) |
| heat.append(hm) |
| return torch.stack(heat, dim=0).amax(0).unsqueeze(1) |
|
|
|
|
| class DynamicsEncoder(nn.Module): |
| def __init__(self, in_ch: int, hidden: int): |
| super().__init__() |
| self.proj = nn.Linear(NUM_JOINTS * in_ch, hidden) |
| self.tcn = nn.Sequential( |
| nn.Conv1d(hidden, hidden, 3, padding=1), |
| nn.ReLU(inplace=True), |
| nn.Conv1d(hidden, hidden, 3, padding=1), |
| nn.ReLU(inplace=True), |
| ) |
| self.att = nn.Linear(hidden, 1) |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor: |
| h = self.proj(x.flatten(2)) |
| h = self.tcn(h.transpose(1, 2)).transpose(1, 2) |
| w = torch.softmax(self.att(h), dim=1) |
| return (h * w).sum(1) |
|
|
|
|
| class DynaFallGCN(nn.Module): |
| def __init__( |
| self, |
| hidden: int = 96, |
| num_classes: int = 2, |
| use_bone: bool = True, |
| use_dyn: bool = True, |
| **_: object, |
| ): |
| super().__init__() |
| self.use_bone = use_bone |
| self.use_dyn = use_dyn |
| self.joint = GraphEncoder(3, hidden, adaptive=True) |
| if use_bone: |
| self.bone = GraphEncoder(3, hidden, adaptive=True) |
| if use_dyn: |
| self.dyn = DynamicsEncoder(9, hidden) |
| streams = 1 + int(use_bone) + int(use_dyn) |
| self.head = nn.Sequential( |
| nn.LayerNorm(hidden * streams), |
| nn.Dropout(0.25), |
| nn.Linear(hidden * streams, hidden), |
| nn.ReLU(inplace=True), |
| nn.Linear(hidden, num_classes), |
| ) |
|
|
| def forward(self, batch: dict[str, torch.Tensor]) -> torch.Tensor: |
| hs = [self.joint(batch["joint"])] |
| if self.use_bone: |
| hs.append(self.bone(batch["bone"])) |
| if self.use_dyn: |
| hs.append(self.dyn(batch["dyn"])) |
| return self.head(torch.cat(hs, dim=1)) |
|
|
|
|
| MODEL_REGISTRY = { |
| "lstm": LSTMClassifier, |
| "stgcn": STGCNClassifier, |
| "agcn": AGCNClassifier, |
| "ctrgcn": CTRGCNClassifier, |
| "posec3d": PoseC3DClassifier, |
| "tcnte": TCNTEClassifier, |
| "dynafall": DynaFallGCN, |
| "dynafall_joint": lambda **kw: DynaFallGCN(use_bone=False, use_dyn=False, **kw), |
| "dynafall_joint_bone": lambda **kw: DynaFallGCN(use_bone=True, use_dyn=False, **kw), |
| "dynafall_full_no_dropout": lambda **kw: DynaFallGCN(use_bone=True, use_dyn=True, **kw), |
| "dynafall_random_dropout": lambda **kw: DynaFallGCN(use_bone=True, use_dyn=True, **kw), |
| } |
|
|
|
|
| def build_model(name: str, hidden: int = 96, num_classes: int = 2) -> nn.Module: |
| if name not in MODEL_REGISTRY: |
| raise KeyError(f"Unknown method {name}. Available: {sorted(MODEL_REGISTRY)}") |
| return MODEL_REGISTRY[name](hidden=hidden, num_classes=num_classes) |
|
|