File size: 4,005 Bytes
dadf189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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))