UFR-Fing / src /models /mdgt /dynamic_graph.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
4.82 kB
from __future__ import annotations
"""
Dynamic k-NN Graph Construction (DGCNN-style).
Core idea — "dynamic" graph:
At every layer the graph is rebuilt based on the *current* feature space,
NOT just the initial (x, y) coordinates.
Layer 1: neighbours = physically close minutiae (embedding ≈ projected coords)
Layer L: neighbours = *semantically* similar minutiae (learned features)
→ two minutiae far apart spatially can become neighbours if their
learned representations are similar.
Graph⁽ˡ⁾: N(i) = KNN(hᵢ⁽ˡ⁾, {hⱼ⁽ˡ⁾}ⱼ₌₁ᴺ, k)
This enables the model to discover semantic similarity beyond spatial proximity
as depth increases — a key advantage over static graph approaches.
Exported API:
knn(x, k, mask, metric) → (B, N, k) neighbour indices
gather_neighbours(x, idx) → (B, N, k, D) gathered features
graph_divergence(idx_a, idx_b, mask) → (B,) mean Jaccard distance per sample
"""
import torch
def knn(
x: torch.Tensor,
k: int,
mask: torch.Tensor | None = None,
metric: str = "euclidean",
) -> torch.Tensor:
"""Compute k-nearest-neighbour indices in feature space.
Args:
x: (B, N, D) point features — the current layer's representation.
k: number of neighbours (including self).
mask: (B, N) bool — True for real minutiae, False for padding.
Padded points are pushed infinitely far away so they are
never chosen as neighbours.
metric: ``"euclidean"`` or ``"cosine"`` distance.
Returns:
idx: (B, N, k) indices of the k nearest neighbours per node.
"""
# Push padded positions to infinity so they're never nearest
if mask is not None:
large = torch.finfo(x.dtype).max / 2
x = x.masked_fill(~mask.unsqueeze(-1), large)
if metric == "cosine":
x_norm = torch.nn.functional.normalize(x, dim=-1)
sim = torch.bmm(x_norm, x_norm.transpose(1, 2)) # (B, N, N)
_, idx = sim.topk(k, dim=-1, largest=True)
else:
# Squared Euclidean: ||a−b||² = ||a||² + ||b||² − 2⟨a,b⟩
inner = torch.bmm(x, x.transpose(1, 2)) # (B, N, N)
xx = (x * x).sum(dim=-1, keepdim=True) # (B, N, 1)
dist = xx + xx.transpose(1, 2) - 2.0 * inner # (B, N, N)
_, idx = dist.topk(k, dim=-1, largest=False) # smallest dist
return idx
def graph_divergence(
idx_a: torch.Tensor,
idx_b: torch.Tensor,
mask: torch.Tensor | None = None,
) -> torch.Tensor:
"""Measure how much the k-NN graph changed between two layers.
For each node i, computes Jaccard distance between its neighbour sets:
divergence(i) = 1 − |N_a(i) ∩ N_b(i)| / |N_a(i) ∪ N_b(i)|
Returns the mean divergence per sample in the batch.
Args:
idx_a: (B, N, k) — neighbour indices from layer l.
idx_b: (B, N, k) — neighbour indices from layer l+1.
mask: (B, N) bool — True for real minutiae. Padded nodes excluded.
Returns:
div: (B,) — mean Jaccard distance per sample (0 = identical, 1 = disjoint).
"""
B, N, k = idx_a.shape
# Convert neighbour indices to one-hot sets for intersection/union
# (B, N, k) → (B, N, N) binary adjacency via scatter
def _to_adj(idx: torch.Tensor) -> torch.Tensor:
adj = torch.zeros(B, N, N, device=idx.device, dtype=torch.float32)
src = torch.ones_like(idx, dtype=torch.float32)
adj.scatter_(2, idx, src)
return adj
adj_a = _to_adj(idx_a) # (B, N, N)
adj_b = _to_adj(idx_b)
intersection = (adj_a * adj_b).sum(dim=-1) # (B, N)
union = ((adj_a + adj_b) > 0).float().sum(dim=-1) # (B, N)
jaccard = intersection / union.clamp(min=1.0) # (B, N)
divergence = 1.0 - jaccard # (B, N)
if mask is not None:
divergence = divergence * mask.float()
div_per_sample = divergence.sum(dim=-1) / mask.float().sum(dim=-1).clamp(min=1.0)
else:
div_per_sample = divergence.mean(dim=-1)
return div_per_sample # (B,)
def gather_neighbours(
x: torch.Tensor,
idx: torch.Tensor,
) -> torch.Tensor:
"""Gather features of k neighbours for every node.
Args:
x: (B, N, D) — node features (any dimension).
idx: (B, N, k) — neighbour indices from :func:`knn`.
Returns:
out: (B, N, k, D) — neighbour features per node.
"""
B, N, D = x.shape
k = idx.shape[-1]
idx_exp = idx.unsqueeze(-1).expand(B, N, k, D) # (B, N, k, D)
x_exp = x.unsqueeze(1).expand(B, N, N, D) # (B, N, N, D)
return torch.gather(x_exp, 2, idx_exp) # (B, N, k, D)