faiss: support METRIC_L1 and extra metrics in IndexFlat range_search (#5391)

Summary:
Pull Request resolved: https://github.com/facebookresearch/faiss/pull/5391

Fixes https://github.com/facebookresearch/faiss/issues/5353

it is marginally less performant than implementing in extra_distances to avoid the decode memcpy, but it keeps the change simple.

Reviewed By: alibeklfc

Differential Revision: D111062845

fbshipit-source-id: 76b3465d639e5f7891f46c878fe20454addd1de0
This commit is contained in:
Michael Norris
2026-07-08 14:48:18 -07:00
committed by meta-codesync[bot]
parent 4d778bc595
commit a3350f6641
2 changed files with 19 additions and 15 deletions
+2 -1
View File
@@ -77,7 +77,8 @@ void IndexFlat::range_search(
range_search_L2sqr(x, get_xb(), d, n, ntotal, radius, result, sel);
break;
default:
FAISS_THROW_MSG("metric type not supported");
IndexFlatCodes::range_search(n, x, radius, result, params);
break;
}
}
+17 -14
View File
@@ -528,23 +528,26 @@ class TestRangeSearch(unittest.TestCase):
(xt, xb, xq) = get_dataset(d, nb, nt, nq)
index = faiss.IndexFlatL2(d)
index.add(xb)
for metric, thresh in [
(faiss.METRIC_L2, 0.1),
(faiss.METRIC_L1, 0.5),
]:
index = faiss.IndexFlat(d, metric)
index.add(xb)
Dref, Iref = index.search(xq, 5)
Dref, Iref = index.search(xq, 5)
thresh = 0.1 # *squared* distance
lims, D, I = index.range_search(xq, thresh)
lims, D, I = index.range_search(xq, thresh)
for i in range(nq):
Iline = I[lims[i] : lims[i + 1]]
Dline = D[lims[i] : lims[i + 1]]
for j, dis in zip(Iref[i], Dref[i]):
if dis < thresh:
(li,) = np.where(Iline == j)
self.assertTrue(li.size == 1)
idx = li[0]
self.assertGreaterEqual(1e-4, abs(Dline[idx] - dis))
for i in range(nq):
Iline = I[lims[i] : lims[i + 1]]
Dline = D[lims[i] : lims[i + 1]]
for j, dis in zip(Iref[i], Dref[i]):
if dis < thresh:
(li,) = np.where(Iline == j)
self.assertTrue(li.size == 1)
idx = li[0]
self.assertGreaterEqual(1e-4, abs(Dline[idx] - dis))
class TestSearchAndReconstruct(unittest.TestCase):