HyperbolicDistance drops the first spatial coordinate from the Lorentz product
Problem
HyperbolicDistance constructs a new time coordinate from all spatial features but computes the spatial dot product from columns 1 onward. The first spatial feature is therefore included on only one side of the Lorentz product. Identical nonzero embeddings can be farther away than different prototypes, and permuting feature coordinates changes distances.
Reproduction
Against the inspected source revision:
import torch
from flair.nn.distance.hyperbolic import HyperbolicDistance
query = torch.tensor([[3.0, 0.0]], dtype=torch.float64)
prototypes = torch.tensor([[0.1, 0.0], [3.0, 0.0]], dtype=torch.float64)
distances = HyperbolicDistance()(query, prototypes)
print("squared distances:", distances.tolist())
print("closest prototype:", distances.argmin(-1).item())
print("identical prototype index:", 1)Observed before the candidate change:
squared distances: [[3.3258426634466094, 8.959383006572914]]
closest prototype: 0
identical prototype index: 1Proposed change
Use all spatial coordinates for the spatial dot product. Retain the existing arccosh numerical floor, and correct the forward docstring to describe hyperbolic rather than Euclidean distance.
Verification
Before: 13 failed, 2 passed. Candidate: 15 passed, no skipped cases.
Explicit Lorentz-projection reference; one/two/seven dimensions; float32/float64; identical points at the existing numerical floor; nearest-prototype counterexample; coordinate permutation; gradients and symmetry.
The complete distance module was imported with real PyTorch. Nearest-prototype tests use the returned distance matrix; no NLP model training or full Flair suite was run.
Source: flair/nn/distance/hyperbolic.py, Git blob be9deca9ebe32cd770e1e56fdbdc13963afea20a; branch master. Python 3.13.5, Linux; exact dependency versions accompany the test logs.
Searches: PR: HyperbolicDistance; Issue: hyperbolic. Issue #1486 discusses embedding evaluation, not the omitted-coordinate defect.
Candidate source patch
diff --git a/flair/nn/distance/hyperbolic.py b/flair/nn/distance/hyperbolic.py
--- a/flair/nn/distance/hyperbolic.py
+++ b/flair/nn/distance/hyperbolic.py
@@ -75,7 +75,7 @@
"""Implement a HyperbolicDistance object."""
def forward(self, mat_1: Tensor, mat_2: Tensor) -> Tensor:
- """Returns the squared euclidean distance between each element in mat_1 and each element in mat_2.
+ """Returns squared hyperbolic distances between the spatial embeddings.
Parameters
----------
@@ -96,7 +96,7 @@
# Compute bilinear form
left = mat_1_x_0.mm(mat_2_x_0.t()) # n_1 x n_2
- right = mat_1[:, 1:].mm(mat_2[:, 1:].t()) # n_1 x n_2
+ right = mat_1.mm(mat_2.t()) # n_1 x n_2
# Arcosh
return arccosh(left - right).pow(2)Could a maintainer confirm this scope for a follow-up PR?
Source: flairNLP/flair