Download pulse/models/t1/backbones.py from velvet-pine-22/PULSE-code: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/velvet-pine-22/PULSE-code/resolve/main/pulse/models/t1/backbones.py
- Command line
-
hf download hf://velvet-pine-22/PULSE-code/pulse/models/t1/backbones.py
-
curl -L -o backbones.py https://huggingface.co/velvet-pine-22/PULSE-code/resolve/main/pulse/models/t1/backbones.py
18.6 kB
| """Sequence backbones and fusion strategies (appendix Tables 16/17, T4). | |
| Ported from the submission's ``models.py`` / ``published_models.py``: | |
| backbones ``cnn`` (CNN1D), ``lstm`` (BiLSTM + attention pooling), | |
| ``transformer`` (sinusoidal positions, now up to 8192 steps; was | |
| 5000), ``tinyhar`` (Zhou et al., ISWC 2022), ``inceptiontime`` | |
| (Fawaz et al., DMKD 2020) | |
| fusion ``early`` (one backbone on the concatenated input), ``late`` (one | |
| backbone + classifier per modality, logits averaged), ``attention``, | |
| ``weighted_late``, ``gated_late``, ``stacking``, ``product`` | |
| (product of experts), ``moe`` (top-2 mixture of experts), | |
| ``feat_concat`` (per-modality backbones, concatenated features) | |
| Every backbone maps ``(x (B,T,C), mask (B,T))`` to ``(B, output_dim)``. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from typing import Mapping | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from .common import MAX_LEN, check_length, offsets | |
| def _pool(x_bct: torch.Tensor, mask) -> torch.Tensor: | |
| """Masked mean over time of ``(B, C, T)``.""" | |
| if mask is None: | |
| return x_bct.mean(2) | |
| m = mask.unsqueeze(1).to(x_bct.dtype) | |
| return (x_bct * m).sum(2) / mask.sum(1, keepdim=True).to(x_bct.dtype).clamp(min=1) | |
| class CNN1DBackbone(nn.Module): | |
| def __init__(self, input_dim, hidden_dim=128): | |
| super().__init__() | |
| self.conv1 = nn.Sequential(nn.Conv1d(input_dim, 64, 7, padding=3), nn.BatchNorm1d(64), | |
| nn.ReLU(), nn.Dropout(0.1)) | |
| self.conv2 = nn.Sequential(nn.Conv1d(64, 128, 5, padding=2), nn.BatchNorm1d(128), | |
| nn.ReLU(), nn.Dropout(0.1)) | |
| self.conv3 = nn.Sequential(nn.Conv1d(128, hidden_dim, 3, padding=1), | |
| nn.BatchNorm1d(hidden_dim), nn.ReLU()) | |
| self.output_dim = hidden_dim | |
| def forward(self, x, mask=None): | |
| return _pool(self.conv3(self.conv2(self.conv1(x.permute(0, 2, 1)))), mask) | |
| class LSTMBackbone(nn.Module): | |
| def __init__(self, input_dim, hidden_dim=128, num_layers=2, dropout=0.2): | |
| super().__init__() | |
| self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers=num_layers, batch_first=True, | |
| bidirectional=True, dropout=dropout if num_layers > 1 else 0) | |
| self.attn = nn.Linear(hidden_dim * 2, 1) | |
| self.output_dim = hidden_dim * 2 | |
| def forward(self, x, mask=None): | |
| out, _ = self.lstm(x) | |
| scores = self.attn(out).squeeze(-1) | |
| if mask is not None: | |
| scores = scores.masked_fill(~mask, float("-inf")) | |
| return (out * torch.softmax(scores, dim=1).unsqueeze(-1)).sum(dim=1) | |
| class TinyHARBackbone(nn.Module): | |
| """TinyHAR (Zhou et al., ISWC 2022): multi-scale temporal convolutions, | |
| cross-channel self-attention, temporal attention pooling.""" | |
| def __init__(self, input_dim, hidden_dim=128, num_scales=4): | |
| super().__init__() | |
| scale_dim = max(4, hidden_dim // num_scales) | |
| actual = scale_dim * num_scales | |
| self.convs = nn.ModuleList([ | |
| nn.Sequential(nn.Conv1d(input_dim, scale_dim, 2 * (i + 1) + 1, padding=i + 1), | |
| nn.BatchNorm1d(scale_dim), nn.ReLU()) | |
| for i in range(num_scales)]) | |
| nhead = max(1, min(4, actual // 8)) | |
| while actual % nhead != 0 and nhead > 1: | |
| nhead -= 1 | |
| self.channel_attn = nn.MultiheadAttention(actual, num_heads=nhead, batch_first=True, | |
| dropout=0.1) | |
| self.channel_norm = nn.LayerNorm(actual) | |
| self.channel_ff = nn.Sequential(nn.Linear(actual, actual), nn.ReLU(), nn.Dropout(0.1), | |
| nn.Linear(actual, actual)) | |
| self.ff_norm = nn.LayerNorm(actual) | |
| self.temporal_query = nn.Parameter(torch.randn(1, 1, actual) * 0.02) | |
| self.temporal_attn = nn.MultiheadAttention(actual, num_heads=1, batch_first=True, | |
| dropout=0.1) | |
| self.output_dim = actual | |
| def forward(self, x, mask=None): | |
| B = x.shape[0] | |
| xt = x.permute(0, 2, 1) | |
| h = torch.cat([conv(xt) for conv in self.convs], dim=1).permute(0, 2, 1) | |
| kpm = ~mask if mask is not None else None | |
| a, _ = self.channel_attn(h, h, h, key_padding_mask=kpm) | |
| h = self.channel_norm(h + a) | |
| h = self.ff_norm(h + self.channel_ff(h)) | |
| pooled, _ = self.temporal_attn(self.temporal_query.expand(B, -1, -1), h, h, | |
| key_padding_mask=kpm) | |
| return pooled.squeeze(1) | |
| class PositionalEncoding(nn.Module): | |
| def __init__(self, d_model, dropout=0.1, max_len=MAX_LEN): | |
| super().__init__() | |
| self.dropout = nn.Dropout(p=dropout) | |
| self.max_len = max_len | |
| pe = torch.zeros(max_len, d_model) | |
| pos = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) | |
| div = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) | |
| pe[:, 0::2] = torch.sin(pos * div) | |
| pe[:, 1::2] = torch.cos(pos * div)[:, : pe[:, 1::2].shape[1]] | |
| self.register_buffer("pe", pe.unsqueeze(0)) | |
| def forward(self, x): | |
| check_length(x.size(1), self.max_len, "PositionalEncoding") | |
| return self.dropout(x + self.pe[:, : x.size(1)]) | |
| class TransformerBackbone(nn.Module): | |
| def __init__(self, input_dim, d_model=128, nhead=4, num_layers=2, dropout=0.1): | |
| super().__init__() | |
| self.input_proj = nn.Linear(input_dim, d_model) | |
| self.pos_enc = PositionalEncoding(d_model, dropout=dropout) | |
| layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, | |
| dim_feedforward=d_model * 4, dropout=dropout, | |
| batch_first=True) | |
| self.encoder = nn.TransformerEncoder(layer, num_layers=num_layers) | |
| self.output_dim = d_model | |
| def forward(self, x, mask=None): | |
| h = self.encoder(self.pos_enc(self.input_proj(x)), | |
| src_key_padding_mask=~mask if mask is not None else None) | |
| return _pool(h.permute(0, 2, 1), mask) | |
| class InceptionModule(nn.Module): | |
| def __init__(self, in_channels, n_filters=32, kernel_sizes=(9, 19, 39), bottleneck=32): | |
| super().__init__() | |
| self.bottleneck = nn.Conv1d(in_channels, bottleneck, 1, bias=False) | |
| self.convs = nn.ModuleList([nn.Conv1d(bottleneck, n_filters, k, padding=(k - 1) // 2, | |
| bias=False) for k in kernel_sizes]) | |
| self.maxpool_conv = nn.Sequential(nn.MaxPool1d(3, stride=1, padding=1), | |
| nn.Conv1d(in_channels, n_filters, 1, bias=False)) | |
| self.bn = nn.BatchNorm1d(n_filters * (len(kernel_sizes) + 1)) | |
| self.relu = nn.ReLU() | |
| def forward(self, x): | |
| b = self.bottleneck(x) | |
| out = torch.cat([c(b) for c in self.convs] + [self.maxpool_conv(x)], dim=1) | |
| return self.relu(self.bn(out)) | |
| class InceptionBlock(nn.Module): | |
| def __init__(self, in_channels, n_filters=32, depth=3): | |
| super().__init__() | |
| n_out = n_filters * 4 | |
| self.modules_list = nn.ModuleList([InceptionModule(in_channels if i == 0 else n_out, | |
| n_filters) for i in range(depth)]) | |
| self.use_residual = in_channels != n_out | |
| if self.use_residual: | |
| self.residual = nn.Sequential(nn.Conv1d(in_channels, n_out, 1, bias=False), | |
| nn.BatchNorm1d(n_out)) | |
| self.relu = nn.ReLU() | |
| def forward(self, x): | |
| res = x | |
| for mod in self.modules_list: | |
| x = mod(x) | |
| if self.use_residual: | |
| res = self.residual(res) | |
| return self.relu(x + res) | |
| class InceptionTimeBackbone(nn.Module): | |
| """``hidden_dim`` is accepted for a uniform interface and unused (the | |
| width is ``4 * n_filters``), as in the submission code.""" | |
| def __init__(self, input_dim, hidden_dim=128, n_filters=32, num_blocks=2, depth=3): | |
| super().__init__() | |
| blocks, in_ch = [], input_dim | |
| for _ in range(num_blocks): | |
| blocks.append(InceptionBlock(in_ch, n_filters, depth)) | |
| in_ch = n_filters * 4 | |
| self.blocks = nn.ModuleList(blocks) | |
| self.output_dim = n_filters * 4 | |
| def forward(self, x, mask=None): | |
| h = x.permute(0, 2, 1) | |
| for b in self.blocks: | |
| h = b(h) | |
| return _pool(h, mask) | |
| BACKBONES = {"cnn": CNN1DBackbone, "lstm": LSTMBackbone, "transformer": TransformerBackbone, | |
| "tinyhar": TinyHARBackbone, "inceptiontime": InceptionTimeBackbone} | |
| def get_backbone(name: str, input_dim: int, hidden_dim: int = 128) -> nn.Module: | |
| try: | |
| return BACKBONES[name](input_dim, hidden_dim) | |
| except KeyError: | |
| raise ValueError(f"unknown backbone {name!r}; known: {sorted(BACKBONES)}") from None | |
| class BackboneClassifier(nn.Module): | |
| """One backbone on the whole input + linear head (TinyHAR / InceptionTime rows).""" | |
| def __init__(self, backbone: nn.Module, num_classes: int, dropout: float = 0.0): | |
| super().__init__() | |
| self.backbone = backbone | |
| self.head = (nn.Sequential(nn.Dropout(dropout), nn.Linear(backbone.output_dim, num_classes)) | |
| if dropout > 0 else nn.Linear(backbone.output_dim, num_classes)) | |
| def forward(self, x, mask=None): | |
| return self.head(self.backbone(x, mask)) | |
| # --------------------------------------------------------------------------- | |
| # fusion models (proj_dim = 0: raw features; per-modality width scaling) | |
| # --------------------------------------------------------------------------- | |
| def per_modality_hidden(mod_dim: int, base_hidden: int) -> int: | |
| if mod_dim >= 128: | |
| return max(base_hidden, 48) | |
| if mod_dim >= 32: | |
| return base_hidden | |
| return max(16, base_hidden // 2) | |
| def _branch(backbone, raw_dim, hidden, proj_dim): | |
| if proj_dim > 0: | |
| proj = nn.Sequential(nn.Linear(raw_dim, proj_dim), nn.LayerNorm(proj_dim), nn.ReLU()) | |
| return proj, get_backbone(backbone, proj_dim, hidden) | |
| return nn.Identity(), get_backbone(backbone, raw_dim, per_modality_hidden(raw_dim, hidden)) | |
| class _Branches(nn.Module): | |
| """Per-modality (projector, backbone[, classifier]) shared by the fusion models.""" | |
| def __init__(self, backbone, modality_dims, num_classes, hidden, proj_dim, classifiers=True): | |
| super().__init__() | |
| self.mod_dims = dict(modality_dims) | |
| self.projectors, self.backbones = nn.ModuleList(), nn.ModuleList() | |
| self.classifiers = nn.ModuleList() | |
| for d in self.mod_dims.values(): | |
| p, b = _branch(backbone, d, hidden, proj_dim) | |
| self.projectors.append(p) | |
| self.backbones.append(b) | |
| if classifiers: | |
| self.classifiers.append(nn.Sequential(nn.Dropout(0.5), | |
| nn.Linear(b.output_dim, num_classes))) | |
| def features(self, x, mask): | |
| return [self.backbones[i](self.projectors[i](x[..., s:e]), mask) | |
| for i, (s, e) in enumerate(offsets(self.mod_dims).values())] | |
| class SingleModel(nn.Module): | |
| """Early fusion (or a single modality): one backbone on the concatenation.""" | |
| def __init__(self, backbone, input_dim, num_classes, hidden=128): | |
| super().__init__() | |
| self.backbone = get_backbone(backbone, input_dim, hidden) | |
| self.classifier = nn.Sequential(nn.Dropout(0.5), | |
| nn.Linear(self.backbone.output_dim, num_classes)) | |
| def forward(self, x, mask=None): | |
| return self.classifier(self.backbone(x, mask)) | |
| class LateFusionModel(_Branches): | |
| def __init__(self, backbone, modality_dims, num_classes, hidden=64, proj_dim=0, | |
| late_agg="mean"): | |
| super().__init__(backbone, modality_dims, num_classes, hidden, proj_dim) | |
| self.late_agg = late_agg | |
| if late_agg == "learned": | |
| self.modality_logits = nn.Parameter(torch.zeros(len(self.mod_dims))) | |
| self.temperature = nn.Parameter(torch.ones(1)) | |
| elif late_agg not in ("mean", "confidence"): | |
| raise ValueError(f"unknown late_agg {late_agg!r}") | |
| def forward(self, x, mask=None): | |
| stacked = torch.stack([c(f) for c, f in zip(self.classifiers, self.features(x, mask))]) | |
| if self.late_agg == "confidence": | |
| probs = F.softmax(stacked, dim=-1) | |
| ent = -(probs * (probs + 1e-8).log()).sum(dim=-1) | |
| return (stacked * F.softmax(-ent, dim=0).unsqueeze(-1)).sum(dim=0) | |
| if self.late_agg == "learned": | |
| w = F.softmax(self.modality_logits / self.temperature, dim=0) | |
| return (stacked * w.view(-1, 1, 1)).sum(dim=0) | |
| return stacked.mean(dim=0) | |
| class AttentionFusionModel(_Branches): | |
| def __init__(self, backbone, modality_dims, num_classes, hidden=64, proj_dim=0): | |
| super().__init__(backbone, modality_dims, num_classes, hidden, proj_dim, classifiers=False) | |
| self.feat_projections = nn.ModuleList([ | |
| nn.Linear(b.output_dim, hidden) if b.output_dim != hidden else nn.Identity() | |
| for b in self.backbones]) | |
| nhead = 4 if hidden % 4 == 0 else (2 if hidden % 2 == 0 else 1) | |
| self.cross_attn = nn.TransformerEncoderLayer(d_model=hidden, nhead=nhead, | |
| dim_feedforward=hidden * 2, dropout=0.1, | |
| batch_first=True) | |
| self.classifier = nn.Sequential(nn.Dropout(0.5), nn.Linear(hidden, num_classes)) | |
| def forward(self, x, mask=None): | |
| toks = torch.stack([p(f) for p, f in zip(self.feat_projections, self.features(x, mask))], | |
| dim=1) | |
| return self.classifier(self.cross_attn(toks).mean(dim=1)) | |
| class WeightedLateFusionModel(_Branches): | |
| def __init__(self, backbone, modality_dims, num_classes, hidden=64, proj_dim=0): | |
| super().__init__(backbone, modality_dims, num_classes, hidden, proj_dim) | |
| self.modality_weights = nn.Parameter(torch.ones(len(self.mod_dims))) | |
| def forward(self, x, mask=None): | |
| stacked = torch.stack([c(f) for c, f in zip(self.classifiers, self.features(x, mask))]) | |
| return (stacked * F.softmax(self.modality_weights, dim=0).view(-1, 1, 1)).sum(dim=0) | |
| class GatedLateFusionModel(_Branches): | |
| def __init__(self, backbone, modality_dims, num_classes, hidden=64, proj_dim=0): | |
| super().__init__(backbone, modality_dims, num_classes, hidden, proj_dim) | |
| total = sum(b.output_dim for b in self.backbones) | |
| self.gate = nn.Sequential(nn.Linear(total, 32), nn.ReLU(), | |
| nn.Linear(32, len(self.mod_dims))) | |
| def forward(self, x, mask=None): | |
| feats = self.features(x, mask) | |
| logits = torch.stack([c(f) for c, f in zip(self.classifiers, feats)], dim=1) | |
| g = F.softmax(self.gate(torch.cat(feats, dim=1)), dim=1) | |
| return (logits * g.unsqueeze(-1)).sum(dim=1) | |
| class StackingFusionModel(_Branches): | |
| def __init__(self, backbone, modality_dims, num_classes, hidden=64, proj_dim=0): | |
| super().__init__(backbone, modality_dims, num_classes, hidden, proj_dim) | |
| self.meta_learner = nn.Sequential(nn.Linear(len(self.mod_dims) * num_classes, 32), | |
| nn.ReLU(), nn.Dropout(0.5), nn.Linear(32, num_classes)) | |
| def forward(self, x, mask=None): | |
| logits = [c(f) for c, f in zip(self.classifiers, self.features(x, mask))] | |
| return self.meta_learner(torch.cat(logits, dim=1)) | |
| class ProductOfExpertsModel(_Branches): | |
| """Sum of per-modality log-probabilities (used directly as logits).""" | |
| def forward(self, x, mask=None): | |
| return sum(F.log_softmax(c(f), dim=1) | |
| for c, f in zip(self.classifiers, self.features(x, mask))) | |
| class MoEFusionModel(_Branches): | |
| def __init__(self, backbone, modality_dims, num_classes, hidden=64, proj_dim=0): | |
| super().__init__(backbone, modality_dims, num_classes, hidden, proj_dim) | |
| self.top_k = min(2, len(self.mod_dims)) | |
| self.router = nn.Linear(sum(b.output_dim for b in self.backbones), len(self.mod_dims)) | |
| def forward(self, x, mask=None): | |
| feats = self.features(x, mask) | |
| logits = torch.stack([c(f) for c, f in zip(self.classifiers, feats)], dim=1) | |
| vals, idx = self.router(torch.cat(feats, dim=1)).topk(self.top_k, dim=1) | |
| sel = logits.gather(1, idx.unsqueeze(-1).expand(-1, -1, logits.size(-1))) | |
| return (sel * F.softmax(vals, dim=1).unsqueeze(-1)).sum(dim=1) | |
| class FeatureConcatFusionModel(_Branches): | |
| def __init__(self, backbone, modality_dims, num_classes, hidden=64, proj_dim=0): | |
| super().__init__(backbone, modality_dims, num_classes, hidden, proj_dim, classifiers=False) | |
| total = sum(b.output_dim for b in self.backbones) | |
| self.classifier = nn.Sequential(nn.LayerNorm(total), nn.Dropout(0.5), | |
| nn.Linear(total, hidden), nn.ReLU(), nn.Dropout(0.3), | |
| nn.Linear(hidden, num_classes)) | |
| def forward(self, x, mask=None): | |
| return self.classifier(torch.cat(self.features(x, mask), dim=1)) | |
| FUSIONS = {"late": LateFusionModel, "attention": AttentionFusionModel, | |
| "weighted_late": WeightedLateFusionModel, "gated_late": GatedLateFusionModel, | |
| "stacking": StackingFusionModel, "product": ProductOfExpertsModel, | |
| "moe": MoEFusionModel, "feat_concat": FeatureConcatFusionModel} | |
| def build_fusion_model(backbone: str, fusion: str, modality_dims: Mapping[str, int], | |
| num_classes: int, hidden: int = 128, proj_dim: int = 0, | |
| late_agg: str = "mean") -> nn.Module: | |
| dims = dict(modality_dims) | |
| if fusion == "early": | |
| if proj_dim: | |
| raise ValueError("early fusion takes raw features (proj_dim must be 0)") | |
| return SingleModel(backbone, sum(dims.values()), num_classes, hidden) | |
| if fusion == "late": | |
| return LateFusionModel(backbone, dims, num_classes, hidden, proj_dim, late_agg) | |
| if fusion not in FUSIONS: | |
| raise ValueError(f"unknown fusion {fusion!r}; known: early, {', '.join(sorted(FUSIONS))}") | |
| return FUSIONS[fusion](backbone, dims, num_classes, hidden, proj_dim) | |