faiss icon indicating copy to clipboard operation
faiss copied to clipboard

New metric for binary index

Open hadim opened this issue 5 years ago • 7 comments

We are trying to include new metrics into faiss. It has been pretty straightforward for float index but the binary index seems to be tight to the Hamming distance. Does faiss rely on Hamming only for binary index or is that possible to add additional distance functions to it?

ping @maclandrol

hadim avatar Apr 30 '21 20:04 hadim

Also related to https://github.com/facebookresearch/faiss/issues/1299 since we are mostly looking for Jaccard with binary index. Binary index is important for us to control the size of the index.

hadim avatar Apr 30 '21 20:04 hadim

There is no explicit reliance on Hamming distance, but efficient implementation on CPU/GPU is possible for Hamming distance as one can leverage the bit population count instructions in doing so (e.g., popc(a xor b)).

I suppose Jaccard similarity on binary vectors can be implemented as popc(a and b) / popc(a or b), so that should be efficient as well. Other functions may not be as easily implementable.

The binary indexes at the moment do not have an interface that allows changing the metric, though.

wickedfoo avatar Apr 30 '21 21:04 wickedfoo

Indeed Jaccard can leverage popcount. As you said the main blocker for us at the moment is that the current interface does not allow changing the metric easily.

At least it's good to know there is no particular reliance on Hamming distance. Thanks!

hadim avatar Apr 30 '21 21:04 hadim

Right the distance_type in IndexBinary is the same as for the regular float Index

https://github.com/facebookresearch/faiss/blob/master/faiss/IndexBinary.h#L49

which is a bit messy (METRIC_L2 is understood as Hamming distance).

It is possible to add other metric types, and implement them for a subset of indexes. The issue with Jaccard is that it's not integer and search functions return int32_t distances, so it would require a different interface, which is tricky.

mdouze avatar May 05 '21 21:05 mdouze

Has this been done?

NinaCalvi avatar Sep 13 '22 13:09 NinaCalvi

@mdouze Hi, in IndexBinaryFlat, nor in BinaryHNSW, IVF or Hash, in none of these Jaccard metric works. Am I missing something?

mireklzicar avatar Jul 19 '23 19:07 mireklzicar

no jaccard is implemented only for a subset of the float indexes.

mdouze avatar Jul 21 '23 04:07 mdouze