Repository navigation
Description
Description
When running NearestNeighbor on a dense array with n_samples ~ 5000, n_features ~ 100 and n_neighbors=1, the algorithm='auto' option selects kd_tree algorithm, which is in this case the slowest algorithm of those available.
Steps/Code to Reproduce
The bechmark script nn_benchmark.py can be found below,
import os
from time import time
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize
np.random.seed(999999)
n_features = 150
algorithm = os.environ['NN_ALGORITHM']
def _create_X(n_samples):
X = np.random.randn(n_samples, n_features)
normalize(X, norm='l2', copy=False)
return X
for n_train, n_test in [(1000, 10000),
(4000, 4000),
(10000, 2000)]:
X_train = _create_X(n_train)
X_test = _create_X(n_test)
mod = NearestNeighbors(n_neighbors=1,
algorithm=algorithm,
n_jobs=1
)
t0 = time()
mod.fit(X_train)
t1 = time()
mod.kneighbors(X_test, return_distance=False)
t2 = time()
if algorithm == 'auto':
print("Actual method:", mod._fit_method)
print('Training set: n_train={}, n_features={}'.format(n_train, n_features))
print('Test set: n_test={}, t_train= {:.2f} s, t_test = {:.2f}s'.format(n_test, t1-t0, t2-t1))which can be run (on Linux) with,
NN_ALGORITHM=auto /usr/bin/time -v python nn_benchmark.py
where /usr/bin/time -v is used to track the peak RAM usage in the returned "Maximum resident set size (kbytes)" field.
Expected Results
One could expect that the nearest neighbor algorithm selection heuristics would pick a reasonable choice for this fairly standard dataset. In addition, one could also have expected for ball_tree to outperform brute force search.
Actual Results
The results of this benchmarks are given below,
| Time (s) | auto | kd_tree | ball_tree | brute |
|---|---|---|---|---|
n_train=1000, n_test=10000 |
3.9 | 3.9 | 2.69 | 0.25 |
n_train=4000, n_test=4000 |
7.5 | 7.5 | 5.55 | 0.34 |
n_train=10000, n_test=1000 |
9.6 | 9.5 | 7.48 | 0.41 |
the automatically chosen kd_tree algorithm is consistently 10-20 times slower than the brute force search.
The memory usage is another issues, where brute force search uses up to 5x more RAM ,
| auto | kd_tree | ball_tree | brute | |
|---|---|---|---|---|
| Peak RAM (MB) | 82 MB | 82 MB | 81 MB | 398 MB |
but this could be addressed by chunking the pairwise_distances calculations (issue #7287), implemented in PR #7979 .
Am I missing something ?
Versions
Linux-4.6.0-gentoo-x86_64-Intel-R-_Core-TM-_i5-6200U_CPU_@_2.30GHz-with-gentoo-2.3
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
NumPy 1.11.1
SciPy 0.18.1
Scikit-Learn 0.18.1
Activity
jnothman commentedon Jan 18, 2017
Ping @jakevdp. I think the issue here is the relatively large number of features. The trees excel at small dimensionality. Yes, I think the heuristics should incorporate number of features and have the option of choosing brute.
I assume your reported times are predict times.
I'd welcome a benchmarking script being added to
benchmarks/, with the ability to plot fit and predict time (and perhaps memory) as a function of:Test size should remain constant. Feel free to train a
DecisionTreeClassifierover the results!rth commentedon Jan 19, 2017
Thanks for your response, @jnothman !
For the KD tree, yes, but I though that ball tree was supposed to overcome that limitation, as discussed in the docs? Besides in @jakevdp benchmarks both trees appear to outperform brute force search even for
n_features=100with a sensibly similarn_trainsize. Which would have been consistent with what the scikit learn docs say,Anyway, will try to add a more extensive benchmarking script to
benchmarks/as you suggested.GaelVaroquaux commentedon Jan 19, 2017
jnothman commentedon Jan 19, 2017
jakevdp commentedon Apr 4, 2017
Keep in mind that the performance of KD trees & ball trees will also depend heavily on the intrinsic dimensionality of the data. So, for example, it might be slower than brute for dense data, but faster than brute for sparse data. Unfortunately, that's difficult to determine cheaply from the dataset itself.
rth commentedon Apr 4, 2017
@jakevdp Thanks for your response! True, but KDTree and BallTree in sckit-learn don't support sparse input I think, only LSHForest does (or something like PySparNN), so this issue would mostly affect dense arrays (for sparse ones brute forces would still be the default algorithm)...
jakevdp commentedon Apr 4, 2017
Sorry – by sparse I didn't mean sparse matrices, but sparsity of structure within the volume of the dataset. That can hugely affect the performance of tree-based searches, and it means that it's difficult to come up with an easy-to-compute heuristic to estimate performance a priori.
rth commentedon Apr 4, 2017
Aww, right, thanks for mentioning this! Then this is fairly problem specific, I'm not sure how easily one could improve over the current
algorithm="auto": I'm going to close this issue.On the other hand, it might be worth updating a bit the Nearest Negibors docs where
rth commentedon Sep 24, 2019
Re-opening as while I agree this is not a trivial task, I think we can do better than the current
algorithm="auto"setting.To give an example, TSNE on MNIST (n_samples=60_000, n_features=64) uses kd_tree as the auto-determined algorithm for NN search. In that case it takes 68 min to run TSNE single threaded (#15082). Using
algorithm='brute'computes it in 10.5 min with OMP_NUM_THREADS=1 and in 9 min using all threads by default.The current choice seems to be to use kd_tree if the metric is supported irrespective of the data dimensionality which is just wrong.
gbolmier commentedon Apr 24, 2020
@rth I have started working on this with the help of @amueller.
I have created a benchmark repository. Here are some plots from the following notebook:
As @jakevdp raised, the tricky point is not knowing the data structure we are dealing with:
However, it looks like most ML datasets aren't edge cases, so maybe we can come up with a better heuristic using information provided by
n_featuresamueller commentedon Apr 24, 2020
I think it's also worth pointing out that when (re)running the benchmarks by @jakevdp, the results are actually quite different from the asymptotics:
https://nbviewer.jupyter.org/github/gbolmier/sklearn-neighbors-benchmark/blob/master/jakevdp_benchmark/jakevdp_modified_benchmark.ipynb
Notice that for spectra and digits, the runtime for brute actually beats the trees, in contrast to what the blog post showed using asymptotics.
This clearly depends on the machine though. @gbolmier what machine did you run this on again? This is all your laptop, right?
Generally I would assume that more cores benefit the brute method.
amueller commentedon Apr 24, 2020
The take-away from the additional benchmarks above is that for most datasets, the threshold where brute wins is between 15 and 20 dimensions, and the only dataset for which this is not true is a synthetic dataset with low intrinsic dimensionality (intrinsic dimensionality is 5). Even for that, there is a cross-over point, I think it was somewhere around 70 or 100 dimensions (depending on how much noise you add to the low-dimensional structure).
We should maybe think about whether we care about the average case or about the worst case. I think the important thing is to not get catastrophic failure.
A simple heuristic would be to use brute whenever n_features > 15. That would work well on all the dataset except for the synthetic one with low intrinsic dimensionality. On that one we would get a slow-down of a factor of up to 10 if the ambient space is somewhere around 30 or 40 dimensions.
Another interesting observation: at least for the datasets we looked at, the synthetic standard normal and the synthetic low intrinsic dimensionality seem to capture the extremes of the tradeoffs and the real-world data lie between these two. Though we looked only at a few datasets.
gbolmier commentedon Apr 24, 2020
Indeed, @jakevdp used to plot an estimate of the brute force at the time, I replaced it by really calculating it, here is the difference for the digits dataset:
Yes, all on my laptop (i7-8565U CPU @ 1.80GHz, 4 physical cores).
GaelVaroquaux commentedon Apr 24, 2020
Well, that's incredibly interesting and useful. I agree with the conclusion that "A simple heuristic would be to use brute whenever n_features > 15".
Thank you for this work!
amueller commentedon May 1, 2020
@GaelVaroquaux do you think the potential loss of performance for datasets with a low intrinsic dimensionality is an issue?
@gbolmier do you want to do a PR with just that simple heuristic? It's likely to be better than what we had, and it probably shouldn't go into the release, so we'll have another 6 month of testing it.
gbolmier commentedon May 1, 2020
Agree, let's go this way!
rth commentedon May 1, 2020
Thanks for working on this @gbolmier ! Yes, performance wise the general conclusion seems reasonable.
One concern with switching to brute-force, could be size of serialized models. For instance, for estimators, that in fit, calls,
such as Isomap or LabelPropagation means that serializing the model would also require serializing the input dataset stored as an attribute internally. Could you compare the sizes of pickles between brute and non brute
NearestNeighborson a few examples?Note that current results a bit biased toward brute-force approach, because while you run
NearestNeighbors(n_jobs=1)the brute-force approach is still going to use all threads via BLAS. So you would need to setOMP_NUM_THREADSto 1 to be really comparable. But then the question is also on a reasonably sized machine whether the above conclusion still hold e.g. withn_jobs=10/ OMP_NUM_THREDS=10. Ideally theautochoice we make should work well not just for single threaded machines.Also as far as I understand in all these benchmarks the n_samples of the query is much lower to n_samples of the dataset? I wonder how often the reverse happens in the way NN is used in scikit-learn. It likely wouldn't matter for brute but it might for binary trees. If you are looking for other ideas to explore, might be worth revisit whether the defaults for
scikit-learn/sklearn/neighbors/_binary_tree.pxi
Lines 1304 to 1310 in c71a1c2
are still optimal (or we should also add some automatic switch there). The issue is that those other code paths don't release the GIL and so can't be efficiently used with
n_jobs>1, but even with 1 thread it would be interesting to know.rth commentedon May 1, 2020
Although it could be argued that n_jobs=1 by default while OMP_NUM_THREADS isn't. But it would still be good to check its impact to be sure we are not switching to brute in some regime just because its multi-threaded by default while tree methods aren't.
gbolmier commentedon May 4, 2020
Thanks a lot for the feedback @rth!
Sure, will do soon!
Depends of the number of samples used at construction time, which vary in
{10,000; 50,000; 100,000}. Number of samples used at querying time is fixed to 10,000 for all experiments.Sorry, I'm not sure to get it, could you elaborate please?
Done, see here. Got surprised, limiting to 1 thread instead of 8 (my laptop default) is actually faster by an average factor of 1.06 ± 0.02. Seems like it doesn't matter much
gbolmier commentedon May 5, 2020
Here is the comparison between the size of pickled
NearestNeighborsmodels (in MB):Turns out that
'brute'is actually slightly lighter than tree-based methodsamueller commentedon May 5, 2020
That's what I would have expected. @rth why did you expect the trees to be smaller? You'll have to store each sample in a leaf and the tree in addition to that, right?
rth commentedon May 5, 2020
Looks like I had a misconception about it, thanks for checking!
Well you likely have 4 physical CPU, so 8 is a bit of a special case since there are then 2 threads per core. For me, e.g. for
I get the following result on a machine with 12 physical CPU,
where n_threads means
OMP_NUM_THREADSfor brute andn_jobsfor ball_tree,Details
So there is some improvement for brute NN as long as less than one thread per core is used (particularly for larger n_features), but you are right it's not that significant. ball_tree scales a bit better with
n_jobs, but again it doesn't change the conclusions either.I mean that using a fixed number of samples for the query (n_query), makes the assumption that these conclusions will hold no matter the size of the query (or in particular that query time is
O(n_query)). That should be true for the methods tested, but I'm wondering if it would still be the case with other tree options e.g. withBallTree(X).query(X_q, dualtree=True). That's a bit off topic, just a side note.Anyway, overall I agree that a using
algorithm='brute'for n_feature>15 would be a reasonable default for "auto".Update NearestNeighbors 'auto' heuristic
gbolmier commentedon May 7, 2020
Thanks for all the detailed explanations @rth, that's good things to be aware of!
Indeed, it might be worth to check, will let you know if I give a try 👍
amueller commentedon May 19, 2020
Is our default using the number of hyperthreading cores? That seems to be a bad idea then, right? Also that seems like a pretty bad scaling for number of cores for brute, right?
rth commentedon May 19, 2020
It's not us, it's numpy for the dot product. Though numpy suggests it's BLAS' fault numpy/numpy#14547 (comment) and OpenMathLib/OpenBLAS#1881 has a long issue by @jeremiedbb from 2018 about it. lol.
Well the dot product scales reasonably well last time I checked, but for euclidean distances, that only accounts for a fraction of the runtime apparently, the rest of the code is not multi-threaded. It might be interesting to profile more. @jeremiedbb might have looked into it in more detail last year, not sure.
Those benchmarks were run for brute with
n_jobs=1and settingOMP_NUM_THREADS. It might be interesting to check the opposite as well (which does parallelize most computations).jeremiedbb commentedon May 19, 2020
MKL only use the physical cores while OpenBLAS uses all cores. From my experiences, I find that using all cores does not bring any speed up at all (and even slow down sometimes). But I can't say for its use outside of scikit-learn, maybe there are situations where it's better to use all cores.
I did not look at KNN, sorry :/