thomasahle / tinyknn Goto Github PK
View Code? Open in Web Editor NEWA tiny approximate K-Nearest Neighbour library in Python based on Fast Product Quantization and IVF
License: GNU Affero General Public License v3.0
A tiny approximate K-Nearest Neighbour library in Python based on Fast Product Quantization and IVF
License: GNU Affero General Public License v3.0
Hello! I'm unable to run examples/glove/prepare-dataset.sh
because the repo is missing convert.py
, it appears.
PyNNDescent (https://github.com/lmcinnes/pynndescent) is able to get a lot of speed (presumably) by using numba. This should be relatively easy to add to fast_pq as well.
Currently, we do unsigned addition in the Cython code.
This is fine for distances, which are positive.
However, to support inner products/cosine similarity we need to have a signed version as well.
I'm currently testing everything with python3.11.
I tried testing with python3.9 and somehow things get stuck.
A classical way to make building the index faster, cheaper memory wise, and potentially better (bigger, but lower quality) is to use a top level product code.
Instead of just "hashing" each point to the closest centroid, hash it to "the pair of centroids" which has a sum closest to the point.
My image here shows how using multi-indexing this way reduces the mean square error: https://twitter.com/thomasahle/status/1583582672906952705?s=20
Some of the code for doing this is here: https://gist.github.com/thomasahle/4f16b19aa395f25e8fee882e3a82a4d9
Often we use PQ to estimate the distance from a full precision vector to a bunch of compressed points.
However, we can also try to compute the distance between all pairs of points in two compressed datasets (even possibly with distinct FastPQ instances).
This is relevant, for example, when inserting a batch of points into the data structure, when we quickly want to compute all the relevant close cluster centers.
Currently we compute this using full precision distance computations.
Edit: Maybe #13 is more relevant for speeding up building the index. However, supporting estimating distances between compressed datasets is still interesting and worthwhile.
For pip install .
:
tinyknn/_fast_pq.cpp:17539:320: error: can’t convert a value of type ‘int’ to vector type ‘__m128i’ {aka ‘__vector(2) long long int’} which has different size
17539 | __pyx_t_6 = __pyx_f_7tinyknn_8_fast_pq_compute_block_dists((&(*((__uint64_t *) ( /* dim=1 */ ((char *) (((__uint64_t *) ( /* dim=0 */ (__pyx_v_data.data + __pyx_t_4 * __pyx_v_data.strides[0]) )) + __pyx_t_5)) )))), ((__pyx_v_data.shape[1]) / 2), __pyx_v_tables, __pyx_v_signd); if (unlikely(__pyx_t_6 == ((__m128i)-1) && __Pyx_ErrOccurredWithGIL())) __PYX_ERR(0, 109, __pyx_L1_error)
| ^
tinyknn/_fast_pq.cpp:1498:43: note: in definition of macro ‘unlikely’
1498 | #define unlikely(x) __builtin_expect(!!(x), 0)
For pip install fast-pq
:
ValueError: 'fast_pq/_fast_pq.pyx' doesn't match any files
[end of output]
Currently we are only using the 128 bit shuffle and equivalent operations.
We could get a factor 2 speed up by using the two-lane variants. As is also described in the Quick ADC paper: https://arxiv.org/pdf/1704.07355.pdf
AVX-512 has some nice features, such as support for fast float16 operations. This might allow us to do rescoring very fast.
The Quicker ADC paper also mentions some uses of AVX-512: https://arxiv.org/pdf/1812.09162.pdf such as {5,6,7} bit lookup tables. Though I don't think any of the top libraries, like ScaNN or Faiss actually uses that.
We should have a pip package that allows people to quickly install and try the library.
Currently, only SSE is supported. It would be nice to also support AMD chips.
There is a guide for how to do this here: https://packaging.python.org/tutorials/packaging-projects/
Currently we are not using python's typing functionality.
Since 2df6a42 it is possible to store every datapoint in n
lists by building with ivf.build(n_probes=n)
.
This increases performance recall/qps quite a lot, but only when going from n=1
to n=2
, as seen in the attached figure.
The problem is probably that duplicate matches aren't handled well.
When calling ctop
from ivf, we should somehow tell it about the indices we have already collected so the distance table can focus on telling us about alternative interesting candidates.
One option is to even reuse the query_pq_sse(transformed_data, self.tables, indices, values, True)
call by calling it on multiple (transformed_data, tables)
pairs while keeping (indices, values)
fixed. That way we also would only do rescoring/pass-2 a single time on all candidates retrieved from different lists.
The issue is that
(1) the binary heap data structure we use can't recognize duplicates, and
(2) the query_pq_sse
function only knows the "local" id of a point in a list, not the global id.
To solve (2) we could pass a list with the global ids of all the points considered. This would be some extra overhead for query_pq_sse
to pass around, but perhaps not that much. And we wouldn't have to "relabel" the returned ids afterwards.
For (1) we could switch back to using insertion sort, or just try heuristically to remove some of the duplicates the heap is able to find.
Currently IVF.fit(...)
uses brute force nearest neighbours to find which clusters to insert the points into.
Instead we could use the same PQ.top(...)
method that we use to do queries to find the relevant cluster centers faster.
However, currently PQ.top(...)
doesn't support batch queries, which means this likely wouldn't be faster than brute force.
Hence the task: Find a way to do fast batch queries with QuickADC and add it to FastPQ.
Currently the same product quantizer is used for every cluster in IVF.
However, the PQ doesn't use a lot of space (it's just 16 center points), so we might as well train a separate one for the data in each cluster.
The main disadvantage is that queries would have to compute a distance table for each PQ.
It's unclear how much that currently is a bottle-neck compared to the actual pass 1 and pass 2 filtering.
An advantage is that we can quantize data[mask] - center
instead of data[mask]
as we do now.
I believe this is what QuickADC actually does.
By subtracting the "main component" of the points we thus gain the ability to scale up the scalars before we map to [-128, 127], allowing higher precision.
Product Quantization should be combined with space partitioning to get a good ann-benchmark score.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.