Skip to content

Add support for np.matmul #3804

Open
Open

Description

@stuartarchibald

Feature request

As title. Noted missing functionality from #3803.

Activity

  1. mohdkashif93 commented on Mar 1, 2019

    @mohdkashif93

    Hey, is it okay if I take this issue up ?

  2. stuartarchibald commented on Mar 1, 2019

    @stuartarchibald
    ContributorAuthor

    @mohdkashif93 Certainly! Thanks!

    As a new contributor, some instructions for getting set up for development are here and are a great place to start.

    The use of Numba's extension API @overload decorator is strongly recommended for this task, documentation is here.

    It may be useful to take a look at examples of pull requests adding support for a NumPy function that have already been done if guidance is needed... here's a couple:

    Thanks again!

  3. Quetzalcohuatl commented on Jan 7, 2020

    @Quetzalcohuatl

    Note that np.dot(a, b) where a and b are both 2D arrays, it is the same as np.matmul. And since np.dot is supported, then we win. https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html

  4. Quetzalcohuatl commented on Jan 7, 2020

    @Quetzalcohuatl

    However, more importantly the operator @ which is matrix multiplication between numpy arrays is also supported. so just use that..

  5. mohdkashif93 commented on Jan 8, 2020

    @mohdkashif93

    @Quetzalcohuatl Thanks for the heads up 👍 I will get this done quickly.

  6. stavoltafunzia commented on Apr 10, 2020

    @stavoltafunzia

    Feature request

    As title. Noted missing functionality from #3803.

    I also vote for this feature request. Unfortunately with the operator @ it's not possible to specify a pre-allocated output array.

    Edit: not needed as numpy.dot supports the output variable as argument.

  7. samaocarpenter commented on Jul 30, 2020

    @samaocarpenter

    Giving a +1 to this feature request. Having np.matmul supported in numba would be pretty great.

  8. njriasan commented on Aug 5, 2020

    @njriasan
    Contributor

    @mohdkashif93 are you still working on this. If not I'm happy to work on this feature.

  9. externalsupplierstaff commented on Jul 15, 2021

    @externalsupplierstaff
    No implementation of function Function(<built-in function matmul>) found for signature:
     
     >>> matmul(array(float64, 3d, C), readonly array(float64, 2d, F))
     
    There are 2 candidate implementations:
      - Of which 2 did not match due to:
      Overload in function 'MatMul.generic': File: numba/core/typing/npydecl.py: Line 994.
        With argument(s): '(array(float64, 3d, C), readonly array(float64, 2d, F))':
       Rejected as the implementation raised a specific error:
         TypingError: '@' only supported on 1-D and 2-D arrays
      raised from /home/francomarchesoni/miniconda3/envs/sandbox/lib/python3.9/site-packages/numba/core/typing/npydecl.py:908
    
    During: typing of intrinsic-call at /home/francomarchesoni/huawei/code/exploration/distort_and_recover/rgb2lab.py (26)
    
    File "exploration/distort_and_recover/rgb2lab.py", line 26:
    def jitrgb2lab(arr):
        <source elided>
        arr = flattened.reshape(arr.shape)
        arr = arr @ xyz_from_rgb_T
        ^
    

    However, more importantly the operator @ which is matrix multiplication between numpy arrays is also supported. so just use that..

    it seems that it doesn't work for 3d tensors 😢

  10. timhdesilva commented on Jul 28, 2021

    @timhdesilva

    Any update on this? I have the following example that does not work when I use np.matmul or the @ decorator for matrix multiplication. Any guidance on how to workaround this would be great!

    from numba import jit
    import numpy as np
    
    @jit(nopython = True)
    def smm_loop(simdata, m_data, W, perc):
        N = np.shape(simdata)[0]
        smm_objs = np.zeros((N, 1))
        for i in range(N):
            m_model = simdata[i, :].reshape((-1,1))
            if perc:
                m_diff = np.divide(m_model - m_data, m_data)
            else:
                m_diff = m_model - m_data
            val = np.matmul(np.matmul(np.transpose(m_diff), W), m_diff)
            smm_objs[i, 0] = val
        return smm_objs
    
    
    dt = np.random.rand(100,10)
    m = np.random.rand(10,1)
    W = np.identity(10)
    perc = False
    
    out = smm_loop(dt, m, W, perc)
    
  11. stavoltafunzia commented on Jul 28, 2021

    @stavoltafunzia

    Why not simply using numpy.dot as already pointed out? For 2d arrays it performs matrix multiplication.

  12. timhdesilva commented on Jul 28, 2021

    @timhdesilva

    @stavoltafunzia - Thanks for the response! When attempting to do so with the following code:

    from numba import jit
    import numpy as np
    
    @jit(nopython = True)
    def smm_loop(simdata, m_data, W, perc):
        N = np.shape(simdata)[0]
        smm_objs = np.zeros((N, 1))
        for i in range(N):
            m_model = simdata[i, :].reshape((-1,1))
            if perc:
                m_diff = np.divide(m_model - m_data, m_data)
            else:
                m_diff = m_model - m_data
            # val = np.matmul(np.matmul(np.transpose(m_diff), W), m_diff)
            val = np.dot(np.dot(np.transpose(m_diff), W), m_diff)
            smm_objs[i, 0] = val
        return smm_objs
    
    
    dt = np.random.rand(100,10)
    m = np.random.rand(10,1)
    W = np.identity(10)
    perc = False
    
    out = smm_loop(dt, m, W, perc)
    

    I get the following error:

    Traceback (most recent call last):
    
      File "<ipython-input-1-c37f901b015f>", line 25, in <module>
        out = smm_loop(dt, m, W, perc)
    
      File "/Users/timdesilva/opt/anaconda3/lib/python3.8/site-packages/numba/core/dispatcher.py", line 420, in _compile_for_args
        error_rewrite(e, 'typing')
    
      File "/Users/timdesilva/opt/anaconda3/lib/python3.8/site-packages/numba/core/dispatcher.py", line 361, in error_rewrite
        raise e.with_traceback(None)
    
    TypingError: No implementation of function Function(<built-in function setitem>) found for signature:
     
    setitem(array(float64, 2d, C), Tuple(int64, Literal[int](0)), array(float64, 2d, C))
     
    There are 16 candidate implementations:
      - Of which 16 did not match due to:
      Overload of function 'setitem': File: <numerous>: Line N/A.
        With argument(s): '(array(float64, 2d, C), UniTuple(int64 x 2), array(float64, 2d, C))':
       No match.
    
    During: typing of setitem at <ipython-input-1-c37f901b015f> (16)
    
  13. gmarkall commented on Jul 28, 2021

    @gmarkall
    Member

    This is about the line:

    smm_objs[i, 0] = val

    You may need to unroll this assignment with a for loop, as it looks like assigning an array to a slice is not supported.

  14. timhdesilva commented on Jul 29, 2021

    @timhdesilva

    Hi @gmarkall. Thanks for the response! After fixing that problem by using smm_objs[i,0] = val[0][0], I run into the following error:

    
      File "/Users/timdesilva/Dropbox (MIT)/Code and Data/Python Functions/fxns_smm.py", line 47, in SMM
        out = smm_loop(dt, m, W, perc)
    
      File "/Users/timdesilva/opt/anaconda3/lib/python3.8/site-packages/numba/core/dispatcher.py", line 420, in _compile_for_args
        error_rewrite(e, 'typing')
    
      File "/Users/timdesilva/opt/anaconda3/lib/python3.8/site-packages/numba/core/dispatcher.py", line 361, in error_rewrite
        raise e.with_traceback(None)
    
    TypingError: - Resolution failure for literal arguments:
    reshape() supports contiguous array only
    - Resolution failure for non-literal arguments:
    reshape() supports contiguous array only
    
    During: resolving callee type: BoundFunction(array.reshape for array(float64, 1d, A))
    During: typing of call at /Users/timdesilva/Dropbox (MIT)/Code and Data/Python Functions/fxns_smm.py (11)
    

    Thanks again so much for your help!

  15. gmarkall commented on Jul 30, 2021

    @gmarkall
    Member

    Can you please move the discussion to https://numba.discourse.group? This issue is for tracking addition of support for np.matmul. Once you've created the topic there, please link to it and we can continue.

  16. Ryandry1st commented on Jan 4, 2023

    @Ryandry1st

    Revisiting this issue. While matmul support is often not critical as noted above, support for 3D tensor multiplication is an extremely lacking feature. Furthermore, because many numba operations do not support axis arguments and einsum is not supported either, it is very difficult to efficiently write numba code with 3D tensor multiplies. I believe this is a significant missing feature.

    Also note that np.dot support does not allow for 3D tensors either, even if one did the appropriate sum(dot()) product.

    EDIT: It should also be noted that numpy has efficient 3D tensor matmul BLAS operations because I found there was significant performance improvements using plain numpy over Numba with prange, sum loop to approximate the matmul functionality. This is not always the case depending on the sizes of the tensors (small tensors -> numpy is more performant, large tensors-> numba performannt) and depends on the hardware, but it highlights that there is valuable performance to be gained from tensor matmul in Numba.

  17. duburcqa commented on Dec 2, 2024

    @duburcqa

    Any update on this issue ? I agree that this feature is very much needed.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions