You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
On numpy current master (da6e4c7), np.matmul is apparently not using BLAS:
>>> import numpy as np
>>> x = np.random.rand(5, 512, 512)
>>> %timeit np.matmul(x, x)
1 loops, best of 3: 526 ms per loop
>>> def xmul(a, b):
... out = np.empty_like(a)
... for j in range(a.shape[0]):
... out[j] = np.dot(a[j], b[j])
... return out
>>> %timeit xmul(x, x)
10 loops, best of 3: 28 ms per loop
Of course, it's a preliminary feature, but probably best to have an issue for this.
Reacted by Forest Gregg, Grigoriy Armeev, Danica J. Sutherland, jakirkham, Laurent Sorber, Juan Luis Cano Rodríguez and Jiacong Fang
My current project's run time is bottle-necked by matmul. It's not too bad, but any idea how much faster it would be when properly interfaced to BLAS/MKL? I'm mostly multiplying (10000,9,9) by (10000,9,9).
Doing lots of small (9x9) matrix multiplies is actually a case where using a fancy BLAS library might make you slower. The fancy BLAS stuff wins by carefully controlling which parts of your matrices are in cache when, so if your entire matrices fit in cache then there isn't much improvement possible, and they can actually slow things down by trying to be clever and adding overhead.
That said, it's probably worth trying a manual loop like in the first comment in this thread and seeing how fast it goes in your case!
I actually just tested it on my machine, calling mkl cblas_dgemm_multiply through ctypes, and found that A @ B takes ~37ms, while the actual call to cblas_dgemm_multiply takes ~1.2ms - a 30x speedup! Unfortunately, naively turning that result (which is an array of pointers) into a Python structure takes ~183ms, so you'd have to speed that processing up if you wanted to use it. :)
You mean MKL's proprietary cblas_dgemm_batch, right? Even sticking to ctypes that could probably be sped up a lot by taking advantage of the fact that that those arrays full of pointers could be fully constructed by calls to np.arange.
Okay, I tried the first suggestion from @njsmith, and replaced my matmul with OP's xmul. This causes my project to run about 50% faster. According to prun, about 95% of my project is spent in xmul.
A @ B takes ~37ms, while the actual call to cblas_dgemm_multiply takes ~1.2ms - a 30x speedup!
This sounds like it could help me quite a bit if I keep everything in c arrays until the end of the algorithm.
If matmul is still using einsum, it is probably worth checking if this is still slow because einsum now uses BLAS routines for some cases if possible thanks to PR ( #9425 ). Should add this is only master; so, it is not yet released, but scheduled for 1.14.0.
@jakirkham Yes, the optimization algorithm does not currently support looped GEMM. It is unclear if it should or not as speed increases compared to the overhead of detection vary greatly depending on the size of the problem. Happy to write this in, just be aware overhead can become a problem as we write more special cases.
@eric-wieser I have checked that the strides, dtype and memory order as seen from .flags are the same in both versions.
Here's the newbie code that I use for both 1.16rc and 1.15:
import numpy as np
from timeit import default_timer as dt
x = np.random.rand(5000,4,4)
y = np.random.rand(5000,4,1)
start = dt()
for i in range(15000):
z = np.matmul(x, y)
print(dt()-start)
Generally BLAS is targeted at larger matrices. Many BLASes like OpenBLAS have a notable startup cost, which is usually amortized over these larger matrices. Though perhaps not for your use case.
It would be nice if OpenBLAS would handle small matrices better. It's certainly possible – they can see the size, and decide to do something small and simple if their normal heavy-weight setup isn't going to be worthwhile. I wouldn't hold my breath though; this has been a weakness of theirs for years.
If you need optimal speed for large stacks of small matrices on numpy right now, I'd try np.einsum (e.g. z = np.einsum("ink,ikm", x, y)), or possibly trying the anaconda builds of numpy that use MKL, to check if MKL handles the small matrices better than OpenBLAS does.
Reacted by jakirkham, Lee Loong, XU GUODONG and Jiacong Fang
thanks @jakirkham and @njsmith . I replaced matmul with einsum and now I could get the same performance regardless of which version I use. Thanks guys!
Activity
djsutherland commentedon Nov 25, 2016
The problem is that
matmuljust callseinsumfor the stacked case. Setting it up to use BLAS for each matrix multiply would be useful.bordingj commentedon Dec 22, 2016
intel MKL supports ?gemm_batch
ihincks commentedon Jun 6, 2017
My current project's run time is bottle-necked by
matmul. It's not too bad, but any idea how much faster it would be when properly interfaced to BLAS/MKL? I'm mostly multiplying(10000,9,9)by(10000,9,9).njsmith commentedon Jun 6, 2017
Doing lots of small (9x9) matrix multiplies is actually a case where using a fancy BLAS library might make you slower. The fancy BLAS stuff wins by carefully controlling which parts of your matrices are in cache when, so if your entire matrices fit in cache then there isn't much improvement possible, and they can actually slow things down by trying to be clever and adding overhead.
That said, it's probably worth trying a manual loop like in the first comment in this thread and seeing how fast it goes in your case!
djsutherland commentedon Jun 6, 2017
I actually just tested it on my machine, calling mkl
cblas_dgemm_multiplythrough ctypes, and found thatA @ Btakes ~37ms, while the actual call tocblas_dgemm_multiplytakes ~1.2ms - a 30x speedup! Unfortunately, naively turning that result (which is an array of pointers) into a Python structure takes ~183ms, so you'd have to speed that processing up if you wanted to use it. :)https://gist.github.com/45d05765c6291e79489c8c31e1ca99ba
njsmith commentedon Jun 7, 2017
You mean MKL's proprietary
cblas_dgemm_batch, right? Even sticking to ctypes that could probably be sped up a lot by taking advantage of the fact that that those arrays full of pointers could be fully constructed by calls tonp.arange.djsutherland commentedon Jun 7, 2017
Yep, that's what i was calling. Good point about
arange, though I wasn't counting that time, just the actual function call.ihincks commentedon Jun 7, 2017
Thanks for the tips! I will give things a whirl tomorrow.
djsutherland commentedon Jun 7, 2017
Two updates about my example code there:
Reconstructing
Cwas idiotic; there's already aCarray. :)I tried to switch the pointer array construction to be faster as
; that seemed to work in terms of accessing things, but when I called the function it didn't actually change
C. Not sure what's going on there.ihincks commentedon Jun 7, 2017
Okay, I tried the first suggestion from @njsmith, and replaced my
matmulwith OP'sxmul. This causes my project to run about 50% faster. According to prun, about 95% of my project is spent inxmul.This sounds like it could help me quite a bit if I keep everything in c arrays until the end of the algorithm.
jakirkham commentedon Nov 19, 2017
If
matmulis still usingeinsum, it is probably worth checking if this is still slow becauseeinsumnow uses BLAS routines for some cases if possible thanks to PR ( #9425 ). Should add this is onlymaster; so, it is not yet released, but scheduled for 1.14.0.jakirkham commentedon Mar 31, 2018
FTR retested this with NumPy 1.14.2 to see if this is still an issue given the changes to
einsumand it is still there. This uses @pv's original code.Example:
Environment:
Edit: Added explicit
einsumtest to compare with.jakirkham commentedon Apr 23, 2018
@dgasmith, do you have any idea why
einsumdoesn't appear to use BLAS in my example above? Is my formulation problematic for some reason?dgasmith commentedon Apr 24, 2018
@jakirkham Yes, the optimization algorithm does not currently support looped GEMM. It is unclear if it should or not as speed increases compared to the overhead of detection vary greatly depending on the size of the problem. Happy to write this in, just be aware overhead can become a problem as we write more special cases.
8 remaining items
gnool commentedon Dec 22, 2018
@eric-wieser I have checked that the strides, dtype and memory order as seen from .flags are the same in both versions.
Here's the newbie code that I use for both 1.16rc and 1.15:
jakirkham commentedon Dec 22, 2018
If you run the code below, what does this say?
python -c "from numpy.distutils import __config__; print(__config__.blas_opt_info)"gnool commentedon Dec 22, 2018
@jakirkham
{'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}jakirkham commentedon Dec 22, 2018
Generally BLAS is targeted at larger matrices. Many BLASes like OpenBLAS have a notable startup cost, which is usually amortized over these larger matrices. Though perhaps not for your use case.
Have you looked at BLIS? Users have noted this works well for small matrices.
njsmith commentedon Dec 22, 2018
It would be nice if OpenBLAS would handle small matrices better. It's certainly possible – they can see the size, and decide to do something small and simple if their normal heavy-weight setup isn't going to be worthwhile. I wouldn't hold my breath though; this has been a weakness of theirs for years.
There's some discussion of adding a standard batched GEMM interface to the next version of BLAS, but I wouldn't hold my breath on that either: https://docs.google.com/document/d/1DY4ImZT1coqri2382GusXgBTTTVdBDvtD5I14QHp9OE/edit#
If you need optimal speed for large stacks of small matrices on numpy right now, I'd try
np.einsum(e.g.z = np.einsum("ink,ikm", x, y)), or possibly trying the anaconda builds of numpy that use MKL, to check if MKL handles the small matrices better than OpenBLAS does.jakirkham commentedon Dec 22, 2018
Do you know if there was an issue raised about optimizing OpenBLAS for smaller matrices?
jakirkham commentedon Dec 22, 2018
As to the MKL point, you may be on to something. Ran across this article, which suggested MKL may do better for small matrices.
njsmith commentedon Dec 22, 2018
not off the top of my head
gnool commentedon Dec 22, 2018
thanks @jakirkham and @njsmith . I replaced matmul with einsum and now I could get the same performance regardless of which version I use. Thanks guys!
njsmith commentedon Dec 22, 2018
Cool!
Anyway, this issue was originally about
matmulnot using BLAS, and now it does, so closing.Add rewrite for matmul when only one of the inputs has batched dimens…
Add rewrite for matmul when only one of the inputs has batched dimens…
Add rewrite for matmul when only one of the inputs has batched dimens…
Add rewrite for matmul when only one of the inputs has batched dimens…