Repository navigation
Closed
Description
In a followup of issue #8213 , it looks like using n_jobs > 1 in Eucledian pairwise_distances makes computations slower instead of speeding them up.
Steps to reproduce
from sklearn.metrics import pairwise_distances
import numpy as np
np.random.seed(99999)
n_dim = 200
for n_train, n_test in [(1000, 100000),
(10000, 10000),
(100000, 1000)]:
print('\n# n_train={}, n_test={}, n_dim={}\n'.format(
n_train, n_test, n_dim))
X_train = np.random.rand(n_train, n_dim)
X_test = np.random.rand(n_test, n_dim)
for n_jobs in [1, 2]:
print('n_jobs=', n_jobs, ' => ', end='')
%timeit pairwise_distances(X_train, X_test, 'euclidean',
n_jobs=n_jobs, squared=True)which on a 2 core CPU returns,
# n_train=1000, n_test=100000, n_dim=200
n_jobs= 1 => 1 loop, best of 3: 1.92 s per loop
n_jobs= 2 => 1 loop, best of 3: 4.95 s per loop
# n_train=10000, n_test=10000, n_dim=200
n_jobs= 1 => 1 loop, best of 3: 1.89 s per loop
n_jobs= 2 => 1 loop, best of 3: 4.74 s per loop
# n_train=100000, n_test=1000, n_dim=200
n_jobs= 1 => 1 loop, best of 3: 2 s per loop
n_jobs= 2 => 1 loop, best of 3: 5.6 s per loop
While for small datasets, it would make sens that the parallel processing would not improve performance due to the multiprocessing etc overhead, this is by no mean a small dataset. And the compute time does not decrease when using e.g. n_jobs=4 on a 4 core CPU.
This also holds for other number of dimensions,
n_dim=10
# n_train=1000, n_test=100000, n_dim=10
n_jobs= 1 => 1 loop, best of 3: 873 ms per loop
n_jobs= 2 => 1 loop, best of 3: 4.25 s per loop
n_dim=1000
# n_train=1000, n_test=100000, n_dim=1000
n_jobs= 1 => 1 loop, best of 3: 6.56 s per loop
n_jobs= 2 => 1 loop, best of 3: 8.56 s per loop
Running benchmarks/bench_plot_parallel_pairwise.py also yields similar results,

This might affect a number of estimators / metrics where pairwise_distances is used.
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
I also get similar results with scikit-learn 0.17.1
Reacted by Carlos De la Guardia
Metadata
Metadata
Assignees
Labels
No labels
Activity
jnothman commentedon Jan 20, 2017
rth commentedon Jan 20, 2017
Yes, I know, I tried to do a quick parallellization of
pariwise_distances(..., n_jobs=1),and this yields comparable performance, so it must be as you say that
n_jobswould better improve non-eucledian distances etc that take longer to compute.I have tried
n_featuresin [10, 200, 1000] in my original post above (sorry called itn_dim), in all casesn_jobs > 1makes things slower. Including for large arraysX [100000, 1000],Y [1000, 1000]which are reaching the limit of what I can compute with 8 GB RAM.The question is that if
n_jobsalways makes pairwise euclidean distances slower, no mattern_samples,n_features(as that's what all the benchmarks suggest so far), then some warning should probably be printed to the user ifn_jobs > 1is used? Particularly since euclidean distance is the default (and probably the most frequent used) distance metric.Also when
benchmarks/bench_plot_parallel_pairwise.pywas added by @mblondel in 3b8f54e , I imagine it aimed to demonstrate that usingn_jobs > 1could speed up Eucledian / RBF distance calculations (couldn't find any plots / PR from that time). When I run this benchmark now, it illustrates that usingn_jobs > 1makes things slower (cf images in the original post above), which doesn't really make sens to show on a benchmark...rth commentedon Jan 20, 2017
It looks like the cost of memory copies is the issue here. For instance, if we rewrite the parallel calculations to save the results to a shared array (adapted from this joblib example) in this gist, we get the results below (on a 8 core Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz),
so while the compute time of
pairwise_distanceskeeps increasing as you use more CPU cores, using a shared array to store the results allows to at least to see some improvement with larger number of CPU cores (though the scaling is not great and it still does not beat single core performance)...jnothman commentedon Jan 21, 2017
rth commentedon Jan 23, 2017
You are right, looks like joblib with the multiprocesssing backend would do the automatic memapping of input array anyway if they are larger than 1MB.
True, I should have copied data to memory and closed the mmap file before deleting it...
ogrisel commentedon Feb 8, 2017
@rth I wonder if this case would not run faster with the threading backend of joblib. Can you please re-run your benchmarks with this backend as a new option?
ogrisel commentedon Feb 8, 2017
You should also run the tests on a larger machines with 16 cores to see the scalability profile when n_jobs is increased.
rth commentedon Feb 8, 2017
@ogrisel I looked a bit more into this, and considered the influence of 3 parameters,
['multiprocessing', 'threading']MKL_NUM_THREADin[1, 8]to disable multithreading in numpy (when using default conda install)this benchmarks the
_parallel_pairwisefunctio, run for['euclidean', 'cosine', 'l1']metrics.(n_x, n_y, n_dim)inn_dimis multiplied by 10 to account for lower density.The benchmark script can be found in this gist. Here are the results for the runs, using an Intel(R) Xeon(R) CPU E5-2666 v3 @ 2.90GHz),
At least for this dataset of medium size (X array: 0.08 GB, Y array 0.08 GB, result array 0.8 GB), the conclusions appear to be that,
n_jobs=1yields the best performancen_jobsin this use casen_jobs=1significantly* setting the number of numpy threads with
MKL_NUM_THREADdoesn't seem to have an impact* pre-allocating the result array, and providing it to joblib so it would be memmaped appears to work worse than doing the same thing but creating the mmemaped file by hand (see comment above).
Looks like everything is memory bound, and globally using more cores does not help. Will try testing scipy metrics (e.g.
jaccard) next..rth commentedon Feb 8, 2017
Parallelizing the jacckard distance works much better, because the computations take much longer and are not memory bound anymore. The choice of the parallel backend doesn't seem to matter in this case,
Here is a sample script to estimate relative compute time of different metrics,
which produces,
maybe it could be worth raising a warning when the
pairwise_distancesis used with faster metrics['euclidean', 'l2', 'cosine']andn_jobs > 1, saying that using the latter option may lead to worse performance?jnothman commentedon Feb 8, 2017
rth commentedon Feb 8, 2017
True, but which part of the docs?
pairwise_distancesthat allow a user providedn_jobsparameter are used (directly or indirectly viaNearestNeighbors) in,silhouette_scoreLocalOutlierFactorDBSCANNearestNeighborsKNeighborsClassifierKNeighborsRegressorIsomapkneighbors_graphmean_shiftLabelPropagationwhich means that, if this issue is confirmed, using
n_jobs > 1may potentially render those estimators / functions (significantly) slower.I imagine the impact of this is somewhat limited by the fact that NearestNeighbors would use by default kd_tree or ball_tree algorithm (cf. #8213) , even in cases when brute force with
pairwise_distanceswould have been more efficient, but that's another issue..jnothman commentedon Feb 9, 2017
lesteve commentedon Feb 9, 2017
I had a look at this a few weeks ago and AFAICT the reason may be that
sklearn.metrics.pairwise._parallel_pairwisedoes:For the auto memmapping to be more useful I think it should do:
GaelVaroquaux commentedon Feb 9, 2017
rth commentedon Feb 9, 2017
Thanks @lesteve , I'll test that option.
Also would you have an opinion why auto memmapping the output array (results with
'mmap_result': Truehere ) has significanly worse performance in this case than creating the memmap file by hand and providing it to joblib (results here). Though in the latter case I was usingsquared=Trueoption, so maybe that has an impact. Or maybe I missed something else...lesteve commentedon Feb 9, 2017
Hmmm not off the top of my head I have to say.
ogrisel commentedon Feb 9, 2017
As threading is not impacted by the GIL for those workloads, there is really no point in using multiprocessing + memmaping: that is just a waste of disk access and memory (multiprocessing + memmaping still does at least one memory copy that is not required when threading).
The fact that cosine / euclidean do not get a speed up with n_jobs=1 is because those workloads are memory bound. It might be possible to find clever ways to block the data differently depending on the dimensions but I think it's primarily BLAS level 1 and 2 operations that dominate and those are memory bound.
So +1 for using the threading backend by default and issueing a warning when using n_jobs>1 on memory bound metrics.
rth commentedon Feb 9, 2017
Thanks @ogrisel I'll submit a PR. Need to check that threading performs as well or better for all metrics though..
It is interesting that BLAS level 1 and level 2 operations (dot product, matrix vector multiplications, ..) are memory bound. I imagine this would also explain why parallelizing the predict method (e.g. in linear models) may not yield any speed up (related issues #7448, #7635)...
ogrisel commentedon Feb 9, 2017
Yes indeed I mean level 1 and 2: vec x vec and mat x vec are memory bound. Only vec x vec is has an algorithmic intensity large enough to benefit from multi cores. But it also depends on how it's "blocked". MKL and OpenBLAS do it for us though.
ogrisel commentedon Feb 10, 2017
Actually for cosine similarities and and euclidean distances there is a level 3 GEMM involved. So at least this step should benefit from multicore without running into the memory bandwidth limit. But the BLAS implementation (MKL or OpenBLAS) should have no problem to multithread that part and there is probably no point in trying to manually handle the parallelism at a coarser level for those GEMM based distances.
jnothman commentedon May 30, 2018
Switching whether to use threading bases on the choice of metric may make sense
rth commentedon Mar 1, 2019
This is resolved by using a threading backend for
pariwise_distancescalculations in #13310