from __future__ import annotations """ Global pooling strategies for variable-length minutiae sets. Three options: 1. **MeanMaxPool** — concatenate global mean and global max. 2. **AttentivePool** — learned attention weights → weighted sum. 3. **MultiHeadPool** — multiple independent attention heads → concat. """ import torch import torch.nn as nn import torch.nn.functional as F class MeanMaxPool(nn.Module): """Concatenation of masked global mean-pooling and max-pooling.""" def __init__(self, embed_dim: int): super().__init__() self.output_dim = embed_dim * 2 def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor: """ Args: x: (B, N, D) mask: (B, N) bool — True for real minutiae. Returns: out: (B, 2D) """ if mask is not None: m = mask.unsqueeze(-1).float() # (B, N, 1) x_masked = x * m mean = x_masked.sum(dim=1) / m.sum(dim=1).clamp(min=1) x_masked[~mask] = float("-inf") max_val = x_masked.max(dim=1).values # replace -inf with 0 for padded-only samples (edge case) max_val = max_val.clamp(min=-1e9) else: mean = x.mean(dim=1) max_val = x.max(dim=1).values return torch.cat([mean, max_val], dim=-1) # (B, 2D) class AttentivePool(nn.Module): """Single-head attentive aggregation (Set Transformer style).""" def __init__(self, embed_dim: int, hidden_dim: int = 256): super().__init__() self.output_dim = embed_dim self.attn = nn.Sequential( nn.Linear(embed_dim, hidden_dim), nn.Tanh(), nn.Linear(hidden_dim, 1), ) def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor: """ Args: x: (B, N, D) mask: (B, N) bool Returns: out: (B, D) """ scores = self.attn(x).squeeze(-1) # (B, N) if mask is not None: scores = scores.masked_fill(~mask, float("-inf")) weights = F.softmax(scores, dim=-1) # (B, N) return (weights.unsqueeze(-1) * x).sum(dim=1) # (B, D) class MultiHeadPool(nn.Module): """PMA-style multi-head attentive pooling (Set Transformer). K learnable seed vectors cross-attend into the minutiae set. Each seed specialises in aggregating a different aspect: oₖ = Σᵢ softmax(Sₖ · hᵢᵀ / √d) · hᵢ ∈ ℝᵈ embedding = Linear(K·d, D)(concat(o₁, …, oₖ)) ∈ ℝᴰ """ def __init__(self, embed_dim: int, num_heads: int = 4, hidden_dim: int = 256): super().__init__() self.num_heads = num_heads self.output_dim = embed_dim self.scale = embed_dim ** 0.5 # K learnable seed vectors — each one "queries" the set self.seeds = nn.Parameter(torch.randn(num_heads, embed_dim) * 0.02) self.proj = nn.Linear(embed_dim * num_heads, embed_dim) def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor: """ Args: x: (B, N, D) mask: (B, N) bool Returns: out: (B, D) """ # seeds: (K, D) → (1, K, D) ; x: (B, N, D) → (B, D, N) # scores: (B, K, N) = seeds @ x^T / √d scores = torch.matmul(self.seeds.unsqueeze(0), x.transpose(1, 2)) / self.scale if mask is not None: # mask: (B, N) → (B, 1, N) scores = scores.masked_fill(~mask.unsqueeze(1), float("-inf")) weights = F.softmax(scores, dim=-1) # (B, K, N) # oₖ = Σᵢ weights(k,i) · hᵢ → (B, K, D) pooled = torch.bmm(weights, x) # (B, K, D) # concat + project: (B, K*D) → (B, D) return self.proj(pooled.reshape(x.shape[0], -1))