IndexFlatL2 search loses results (-1 padding, then no results at all) when squared distances overflow float32
Current Behavior
IndexFlatL2::search with k=2 over a 2-point index silently returns fewer results as the scale of the (finite, representable) data grows: one slot padded with -1, then both slots -1.
Dataset p1=[1,0] (row 0), p2=[0,1] (row 1), query q=[0.6,0.8]. True squared distances are alpha²·0.8 (p1) and alpha²·0.4 (p2) — the true order (p2 first) and the count min(k, n) = 2 are invariant under the scaling:
| alpha | returned rows | distances | expected |
|---|---|---|---|
| 1 | [1, 0] |
[0.4, 0.8] |
✓ |
| 2.5e19 | [1, -1] — row 0 lost |
[2.5e38, 3.4e38 (FLT_MAX)] |
[1, 0] |
| 3e19 | [-1, -1] — both lost |
[FLT_MAX, FLT_MAX] |
[1, 0] |
Every stored vector and the query are finite float32 at each alpha; only the squared-distance intermediate (alpha²·d) exceeds the float32 range for the dropped entries. Since the true squared distances also exceed the float32 output range in the failing cases, this is partly a boundary-policy question: finite inputs do not guarantee finite outputs. But silently padding with -1 gives the caller no way to distinguish "fewer than k valid neighbors" from "results discarded".
Expected Behavior
Both points are returned at every finite alpha (with saturated or infinite distance values if necessary), or the overflow is detected and signalled. The wiki FAQ documents floating-point accuracy caveats; an explicit statement or check for this silent result-loss mode would make the boundary usable.
Steps to Reproduce
reproduce.py --output observed.json (Python 3 + faiss + numpy only) runs the three alphas, prints rows and distances, and exits non-zero unless both rows are returned each time. Deterministic; observed.json is from an actual run. Minimal core:
import numpy as np, faiss
a = 3e19
idx = faiss.IndexFlatL2(2)
idx.add(np.array([[1.0*a, 0.0], [0.0, 1.0*a]], dtype=np.float32))
D, I = idx.search(np.array([[0.6*a, 0.8*a]], dtype=np.float32), 2)
print(I, D) # [[ -1 -1 ]] [[3.4028235e+38 3.4028235e+38]]Environment
- faiss-cpu 1.15.0 (conda-forge wheel), Python 3.12, Windows 11 x64
IndexFlatL2, 2 points, k=2; behavior identical at k=1 with the α=3e19 query (returns -1)
The issue was found while checking that uniformly scaling an exact-search input preserves the neighbor identity and result count (a metamorphic relation). Related observation: with IP the overflow produces inf scores but the ordering survives (inf sorts as maximal similarity); the L2 path appears to filter overflowed distances instead, which drops the points.
Source: facebookresearch/faiss