File size: 4,817 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
122
123
124
125
126
127
128
129
130
131
132
133
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)