| 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. |
| """ |
| |
| 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)) |
| _, idx = sim.topk(k, dim=-1, largest=True) |
| else: |
| |
| inner = torch.bmm(x, x.transpose(1, 2)) |
| xx = (x * x).sum(dim=-1, keepdim=True) |
| dist = xx + xx.transpose(1, 2) - 2.0 * inner |
| _, idx = dist.topk(k, dim=-1, largest=False) |
| 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 |
|
|
| |
| |
| 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) |
| adj_b = _to_adj(idx_b) |
|
|
| intersection = (adj_a * adj_b).sum(dim=-1) |
| union = ((adj_a + adj_b) > 0).float().sum(dim=-1) |
|
|
| jaccard = intersection / union.clamp(min=1.0) |
| divergence = 1.0 - jaccard |
|
|
| 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 |
|
|
|
|
| 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) |
| x_exp = x.unsqueeze(1).expand(B, N, N, D) |
| return torch.gather(x_exp, 2, idx_exp) |
|
|