UFR-Fing / src /models /mdgt /relational_pe.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
5.42 kB
"""
Relational Positional Encoding (RPE).
For every pair of minutiae (i, j) we compute a 7-dim geometric relation
vector and project it through a small MLP to obtain a learned embedding:
rᵢⱼ = [Δxᵢⱼ, Δyᵢⱼ, dᵢⱼ, cos(αᵢⱼ), sin(αᵢⱼ), cos(Δθᵢⱼ), sin(Δθᵢⱼ)] ∈ ℝ⁷
PE(i,j) = MLP_rel(rᵢⱼ) ∈ ℝᵈ
Rationale for each component:
(Δx, Δy) Raw displacement — translation-invariant by construction:
(xⱼ+t) − (xᵢ+t) = xⱼ − xᵢ. Lets the MLP learn any
spatial pattern from relative position.
dᵢⱼ Explicit Euclidean distance. Although the MLP could learn
√(Δx²+Δy²), providing it explicitly accelerates convergence
— the model doesn't have to "reinvent" the concept of distance.
(cos α, sin α) Direction angle from minutia i to j on the plane.
Combined with d, this gives a complete polar-coordinate
representation of relative position.
(cos Δθ, sin Δθ) Difference in ridge orientation — the most biometrically
discriminative feature. Two minutiae at the same distance
but different Δθ are very different fingerprint evidence.
Using (cos, sin) handles angle periodicity correctly.
"""
import torch
import torch.nn as nn
def compute_pairwise_relations(
x: torch.Tensor,
y: torch.Tensor,
theta: torch.Tensor,
) -> torch.Tensor:
"""Compute pairwise 7-dim relational features among minutiae.
Args:
x: (B, N) x-coordinates.
y: (B, N) y-coordinates.
theta: (B, N) orientations in **radians**.
Returns:
rel: (B, N, N, 7) — [Δx, Δy, d, cos α, sin α, cos Δθ, sin Δθ]
"""
# Δx, Δy — raw displacement (translation invariant)
dx = x.unsqueeze(2) - x.unsqueeze(1) # (B, N, N)
dy = y.unsqueeze(2) - y.unsqueeze(1)
# d — Euclidean distance (explicit, helps convergence)
dist = torch.sqrt(dx ** 2 + dy ** 2 + 1e-8)
# Normalize spatial features so all 7 dims are ~ [-1, 1] scale.
# Without this, pixel-scale dx/dy/dist (0–600) drown out cos/sin (−1 to 1).
# Normalization is per-sample: divide by the max distance in each sample.
scale = dist.amax(dim=(1, 2), keepdim=True).clamp(min=1.0) # (B, 1, 1)
dx_n = dx / scale
dy_n = dy / scale
dist_n = dist / scale
# α — direction angle from i to j (polar coordinate)
alpha = torch.atan2(dy, dx) # (B, N, N)
cos_alpha = torch.cos(alpha)
sin_alpha = torch.sin(alpha)
# Δθ — orientation difference (most biometric-discriminative)
dtheta = theta.unsqueeze(2) - theta.unsqueeze(1)
cos_dtheta = torch.cos(dtheta)
sin_dtheta = torch.sin(dtheta)
rel = torch.stack([
dx_n, dy_n, dist_n,
cos_alpha, sin_alpha,
cos_dtheta, sin_dtheta,
], dim=-1) # (B, N, N, 7)
return rel
class RelationalPE(nn.Module):
"""Project pairwise geometric relations into a learned embedding space.
MLP_rel: Linear(7, hidden) → LayerNorm → GELU → ... → Linear(hidden, out)
The output can be used as:
• additive attention bias (scalar per head), or
• multiplicative gate on attention logits, or
• concatenated edge features.
Parameters
----------
input_dim : raw relation dimensionality (default 7).
hidden_dim : MLP hidden width.
output_dim : final embedding size.
num_layers : depth of the projection MLP.
activation : nonlinearity name (``"gelu"`` | ``"relu"``).
"""
def __init__(
self,
input_dim: int = 7,
hidden_dim: int = 64,
output_dim: int = 64,
num_layers: int = 2,
activation: str = "gelu",
):
super().__init__()
act = nn.GELU() if activation == "gelu" else nn.ReLU()
layers: list[nn.Module] = []
dims = [input_dim] + [hidden_dim] * (num_layers - 1) + [output_dim]
for i in range(len(dims) - 1):
layers.append(nn.Linear(dims[i], dims[i + 1]))
if i < len(dims) - 2: # no act after final projection
layers.append(nn.LayerNorm(dims[i + 1]))
layers.append(act)
self.mlp = nn.Sequential(*layers)
self._init_weights()
# ------------------------------------------------------------------
def _init_weights(self):
for m in self.mlp:
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
if m.bias is not None:
nn.init.zeros_(m.bias)
# ------------------------------------------------------------------
def forward(
self,
minutiae: torch.Tensor,
) -> torch.Tensor:
"""
Args:
minutiae: (B, N, 3) — columns are (x, y, θ).
Returns:
rpe: (B, N, N, output_dim) learned relational embeddings.
"""
x = minutiae[..., 0]
y = minutiae[..., 1]
theta = minutiae[..., 2]
rel = compute_pairwise_relations(x, y, theta) # (B, N, N, 7)
rpe = self.mlp(rel) # (B, N, N, out)
return rpe