Skip to content

Heuristics for algorithm='auto' in NearestNeighbors #8213

Closed

Description

@rth

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

  1. jnothman commented on Jan 18, 2017

    @jnothman
    Member

    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:

    • algorithm
    • training size
    • number of features
    • metric
    • number of neighbors (I assume this is a good enough proxy for radius queries)

    Test size should remain constant. Feel free to train a DecisionTreeClassifier over the results!

  2. rth commented on Jan 19, 2017

    @rth
    MemberAuthor

    Thanks for your response, @jnothman !

    I think the issue here is the relatively large number of features. The trees excel at small dimensionality.

    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=100 with a sensibly similar n_train size. Which would have been consistent with what the scikit learn docs say,

    Efficient brute-force neighbors searches can be very competitive for small data samples. However, as the number of samples N grows, the brute-force approach quickly becomes unfeasible.

    Anyway, will try to add a more extensive benchmarking script to benchmarks/ as you suggested.

  3. GaelVaroquaux commented on Jan 19, 2017

    @GaelVaroquaux
    Member
  4. jnothman commented on Jan 19, 2017

    @jnothman
    Member
  5. jakevdp commented on Apr 4, 2017

    @jakevdp
    Member

    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.

  6. rth commented on Apr 4, 2017

    @rth
    MemberAuthor

    @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)...

  7. jakevdp commented on Apr 4, 2017

    @jakevdp
    Member

    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.

  8. rth commented on Apr 4, 2017

    @rth
    MemberAuthor

    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

    • sections 1.6.4.1 - 1.6.4.3 make it sound as though brute force <worse< KDTree <worse< BallTree while it's not necessarly true
    • section 1.6.4.4 is much more nuanced, however it doesn't mention that for a given dataset, experimental benchmarks might still be the simplest way of determining the most appropriate NN algorithm...
  9. rth commented on Sep 24, 2019

    @rth
    MemberAuthor

    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.

    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.

  10. reopened this on Sep 24, 2019
  11. gbolmier commented on Apr 24, 2020

    @gbolmier
    Contributor

    @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:

    kd_tree_vs_brute_speedup_ratio

    As @jakevdp raised, the tricky point is not knowing the data structure we are dealing with:

    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.

    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_features

  12. amueller commented on Apr 24, 2020

    @amueller
    Member

    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.

  13. amueller commented on Apr 24, 2020

    @amueller
    Member

    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.

  14. gbolmier commented on Apr 24, 2020

    @gbolmier
    Contributor

    Notice that for spectra and digits, the runtime for brute actually beats the trees, in contrast to what the blog post showed using asymptotics.

    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:

    brute_force_estimated
    brute_force_computed

    This clearly depends on the machine though. @gbolmier what machine did you run this on again? This is all your laptop, right?

    Yes, all on my laptop (i7-8565U CPU @ 1.80GHz, 4 physical cores).

  15. GaelVaroquaux commented on Apr 24, 2020

    @GaelVaroquaux
    Member

    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!

  16. amueller commented on May 1, 2020

    @amueller
    Member

    @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.

  17. gbolmier commented on May 1, 2020

    @gbolmier
    Contributor

    @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.

    Agree, let's go this way!

  18. rth commented on May 1, 2020

    @rth
    MemberAuthor

    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,

       self.nn_fit = NearestNeighbors()...
    

    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 NearestNeighbors on 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 set OMP_NUM_THREADS to 1 to be really comparable. But then the question is also on a reasonably sized machine whether the above conclusion still hold e.g. with n_jobs=10 / OMP_NUM_THREDS=10. Ideally the auto choice 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

    dualtree : bool, default=False
    if True, use the dual tree formalism for the query: a tree is
    built for the query points, and the pair of trees is used to
    efficiently search this space. This can lead to better
    performance as the number of points grows large.
    breadth_first : bool, default=False
    if True, then query the nodes in a breadth-first manner.

    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.

  19. rth commented on May 1, 2020

    @rth
    MemberAuthor

    So you would need to set OMP_NUM_THREADS to 1 to be really comparable.

    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.

  20. gbolmier commented on May 4, 2020

    @gbolmier
    Contributor

    Thanks a lot for the feedback @rth!

    Could you compare the sizes of pickles between brute and non brute NearestNeighbors on a few examples?

    Sure, will do soon!

    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?

    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.

    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.

    Sorry, I'm not sure to get it, could you elaborate please?

    So you would need to set OMP_NUM_THREADS to 1 to be really comparable.

    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.

    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

  21. gbolmier commented on May 5, 2020

    @gbolmier
    Contributor

    Here is the comparison between the size of pickled NearestNeighbors models (in MB):

    n_samples n_features brute kd_tree ball_tree
    0 1000 10 0.08 0.1 0.1
    1 1000 100 0.8 0.91 0.86
    2 1000 1000 8 9.02 8.52
    3 10000 10 0.8 0.98 0.94
    4 10000 100 8 8.91 8.51
    5 10000 1000 80 88.27 84.19
    6 100000 10 8 9.59 9.26
    7 100000 100 80 87.48 84.21
    8 100000 1000 800 866.45 833.69

    Turns out that 'brute' is actually slightly lighter than tree-based methods

  22. amueller commented on May 5, 2020

    @amueller
    Member

    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?

  23. rth commented on May 5, 2020

    @rth
    MemberAuthor

    why did you expect the trees to be smaller?

    Looks like I had a misconception about it, thanks for checking!

    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.

    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

    n_samples, n_features = 50000, 30 
    n_samples_query = 2000
    

    I get the following result on a machine with 12 physical CPU,

    algorithm  ball_tree     brute                                                                                                         
    n_threads                     
    1           1.979217  1.265764
    2           2.333044  1.187280
    4           2.361583  1.171765
    8           1.897780  1.182090
    12          1.570761  1.188863
    24          1.648642  1.290348
    

    where n_threads means OMP_NUM_THREADS for brute and n_jobs for ball_tree,

    Details
    import numpy as np
    from threadpoolctl import threadpool_limits
    from sklearn.neighbors import NearestNeighbors
    from neurtu import timeit, delayed
    
    rng = np.random.RandomState(0)
    n_samples, n_features = 50000, 30 
    n_query = 2000
    
    X = rng.rand(n_samples, n_features)
    X_q = rng.rand(n_query, n_features)
    
    def fit_nn_brute_with_n_threads(X, X_q, n_thread):  
        est = NearestNeighbors(algorithm='brute')        
        with threadpool_limits(limits=n_thread, user_api='blas'): 
            est.fit(X).kneighbors(X_q, return_distance=False)
        
      
    def benchmarks(X, X_q):
        for n_thread in [1, 2, 4, 8, 12, 24]:
                t0 = time()
                tags = {'algorithm': 'brute', 'n_threads': n_thread}
                yield delayed(fit_nn_brute_with_n_threads, tags=tags)(X, X_q, n_thread)
        for n_jobs in [1, 2, 4, 8, 12, 24]:
            est = NearestNereighbors(algorithm='ball_tree', n_jobs=n_jobs)
            tags = {'algorithm': 'ball_tree', 'n_threads': n_jobs}  
            yield delayed(est, tags=tags).fit(X).kneighbors(X_q, return_distance=False)    
            
    df = timeit(benchmarks(X, X_q), repeat=3)
    print(df.loc[:, ('wall_time', 'mean')].unstack(-1).T)

    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.

    Sorry, I'm not sure to get it, could you elaborate please?

    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. with BallTree(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".

  24. added a commit that references this issue on May 7, 2020
    fcf525b
  25. gbolmier commented on May 7, 2020

    @gbolmier
    Contributor

    Thanks for all the detailed explanations @rth, that's good things to be aware of!

    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. with BallTree(X).query(X_q, dualtree=True). That's a bit off topic, just a side note.

    Indeed, it might be worth to check, will let you know if I give a try 👍

  26. amueller commented on May 19, 2020

    @amueller
    Member

    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?

  27. rth commented on May 19, 2020

    @rth
    MemberAuthor

    Is our default using the number of hyperthreading cores? That seems to be a bad idea then, right?

    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.

    Also that seems like a pretty bad scaling for number of cores for brute, right?

    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=1 and setting OMP_NUM_THREADS. It might be interesting to check the opposite as well (which does parallelize most computations).

  28. jeremiedbb commented on May 19, 2020

    @jeremiedbb
    Member

    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.

    It might be interesting to profile more. @jeremiedbb might have looked into it in more detail last year, not sure.

    I did not look at KNN, sorry :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions