internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: numba/numba

Issue:
CUDA local array should be allocated at entry block
https://github.com/numba/numba/issues/1341#issuecomment-134612689



Discussion:

Resolving patch:
diff --git a/numba/cuda/cudaimpl.py b/numba/cuda/cudaimpl.py
--- a/numba/cuda/cudaimpl.py
+++ b/numba/cuda/cudaimpl.py
@@ -351,7 +351,7 @@ def _generic_array(context, builder, shape, dtype, symbol_name, addrspace,
         # Special case local addrespace allocation to use alloca
         # NVVM is smart enough to only use local memory if no register is
         # available
-        dataptr = builder.alloca(laryty, name=symbol_name)
+        dataptr = cgutils.alloca_once(builder, laryty, name=symbol_name)
     else:
         lmod = builder.module
 


Test patch:
Repository: numba/numba

Issue:
serialization of "import mod as m"
Using Numba 0.22.1 with Numpy 1.10.0 and Python 3.5.0

``` python
import numpy as np

import numba
@numba.jit
def foo():
    return np.zeros(2)

import pickle
pfoo = pickle.dumps(foo)
foo2 = pickle.loads(pfoo) 
```

results in 

```
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-4-d4f01e1ced19> in <module>()
      8 import pickle
      9 pfoo = pickle.dumps(foo)
---> 10 foo2 = pickle.loads(pfoo)

/xvdb/anaconda3/lib/python3.5/site-packages/numba/serialize.py in _rebuild_module(name)
     36     if name is None:
     37         raise ImportError("cannot import None")
---> 38     __import__(name)
     39     return sys.modules[name]
     40 

ImportError: No module named 'np'
```

This is an issue eg when the jit'ed function needs to be serialized to be executed on IPython parallel engines.

Also note that 

```
import numpy

import numba
@numba.jit
def foo():
    return numpy.zeros(2)

import pickle
pfoo = pickle.dumps(foo)
foo2 = pickle.loads(pfoo) 
```

works fine.

Thanks to MinRK for the test case.



Discussion:

Resolving patch:
diff --git a/numba/serialize.py b/numba/serialize.py
--- a/numba/serialize.py
+++ b/numba/serialize.py
@@ -52,7 +52,7 @@ def _get_function_globals_for_reduction(func):
     for k, v in globs.items():
         # Make modules picklable by name
         if isinstance(v, ModuleType):
-            globs[k] = _ModuleRef(k)
+            globs[k] = _ModuleRef(v.__name__)
     # Remember the module name so that the function gets a proper __module__
     # when rebuilding.  This is used to recreate the environment.
     globs['__name__'] = func.__module__


Test patch:
diff --git a/numba/tests/serialize_usecases.py b/numba/tests/serialize_usecases.py
--- a/numba/tests/serialize_usecases.py
+++ b/numba/tests/serialize_usecases.py
@@ -53,6 +53,15 @@ def other_function(x, y):
 def get_global_objmode(x):
     return K * x
 
+import numpy as np
+import numpy.random as nprand
+
+@jit(nopython=True)
+def get_renamed_module(x):
+    nprand.seed(42)
+    return np.cos(x), nprand.random()
+
+
 def closure_calling_other_function(x):
     @jit(nopython=True)
     def inner(y, z):
diff --git a/numba/tests/test_serialize.py b/numba/tests/test_serialize.py
--- a/numba/tests/test_serialize.py
+++ b/numba/tests/test_serialize.py
@@ -90,6 +90,13 @@ def test_call_dyn_func_objmode(self):
         # Same with an object mode function
         self.run_with_protocols(self.check_call, dyn_func_objmode, 36, (6,))
 
+    def test_renamed_module(self):
+        # Issue #1559: using a renamed module (e.g. `import numpy as np`)
+        # should not fail serializing
+        expected = get_renamed_module(0.0)
+        self.run_with_protocols(self.check_call, get_renamed_module,
+                                expected, (0.0,))
+
     def test_other_process(self):
         """
         Check that reconstructing doesn't depend on resources already
Repository: numba/numba

Issue:
remove deprecated usage of llvmlite get_pointer_to_function()
```
---> 31 from numba import jit, types
     32 

/usr/local/anaconda/lib/python2.7/site-packages/numba/__init__.py in <module>()
     22 
     23 # Re export vectorize decorators
---> 24 from .npyufunc import vectorize, guvectorize
     25 
     26 # Re export from_dtype

/usr/local/anaconda/lib/python2.7/site-packages/numba/npyufunc/__init__.py in <module>()
      1 # -*- coding: utf-8 -*-
      2 from __future__ import print_function, division, absolute_import
----> 3 from .decorators import Vectorize, GUVectorize, vectorize, guvectorize
      4 from ._internal import PyUFunc_None, PyUFunc_Zero, PyUFunc_One
      5 from . import _internal, array_exprs

/usr/local/anaconda/lib/python2.7/site-packages/numba/npyufunc/decorators.py in <module>()
      4 from . import _internal, dufunc
      5 from .ufuncbuilder import UFuncBuilder, GUFuncBuilder
----> 6 from .parallel import ParallelUFuncBuilder
      7 
      8 from numba.cuda.vectorizers import CUDAVectorize, CUDAGUFuncVectorize

/usr/local/anaconda/lib/python2.7/site-packages/numba/npyufunc/parallel.py in <module>()
    249 
    250 
--> 251 _init()
    252 
    253 _DYLD_WORKAROUND_SET = 'NUMBA_DYLD_WORKAROUND' in os.environ

/usr/local/anaconda/lib/python2.7/site-packages/numba/npyufunc/parallel.py in _init()
    243     set_cas = CFUNCTYPE(None, c_void_p)(lib.set_cas)
    244 
--> 245     engine, cas_ptr = _make_cas_function()
    246     set_cas(c_void_p(cas_ptr))
    247 

/usr/local/anaconda/lib/python2.7/site-packages/numba/npyufunc/parallel.py in _make_cas_function()
    218     tm = target.create_target_machine()
    219     engine = ll.create_mcjit_compiler(llmod, tm)
--> 220     ptr = engine.get_pointer_to_function(llfn)
    221     return engine, ptr
    222 

/usr/local/anaconda/lib/python2.7/site-packages/llvmlite/binding/executionengine.py in get_pointer_to_function(self, gv)
     61     def get_pointer_to_function(self, gv):
     62         warnings.warn(".get_pointer_to_function() is deprecated.  Use "
---> 63                       ".get_function_address() instead.", DeprecationWarning)
     64         ptr = ffi.lib.LLVMPY_GetPointerToGlobal(self, gv)
     65         if ptr is None:

DeprecationWarning: .get_pointer_to_function() is deprecated.  Use .get_function_address() instead.
```



Discussion:

Resolving patch:
diff --git a/numba/npyufunc/parallel.py b/numba/npyufunc/parallel.py
--- a/numba/npyufunc/parallel.py
+++ b/numba/npyufunc/parallel.py
@@ -398,12 +398,11 @@ def _make_cas_function():
 
     # Build & Link
     llmod = ll.parse_assembly(str(mod))
-    llfn = llmod.get_function(fn.name)
 
     target = ll.Target.from_default_triple()
     tm = target.create_target_machine()
     engine = ll.create_mcjit_compiler(llmod, tm)
-    ptr = engine.get_pointer_to_function(llfn)
+    ptr = engine.get_function_address(fn.name)
     return engine, ptr
 
 


Test patch:
Repository: numba/numba

Issue:
Serious bug in numba 0.23.1 prevents numpy recarrays to be used
In numba 0.23.1 the access of recarrays stopped working. 

Example:

``` python
from numba import njit
import numpy as np

@njit
def test(a):
    a[0].x = 0

a = np.array([(1.0, )], dtype=[('x', float)]).view(np.recarray)
test(a)
```

Worked fine with numba 0.22.1. But now an exception is thrown:

``` python
LoweringError: Internal error:
KeyError: 0
File "tmp.py", line 6 
```

I am using Miniconda Python 2.7 on Windows 7 64-bit.



Discussion:
The error also occurs under Ubuntu LTS 14.04 and Miniconda Python 2.7

I can confirm this bug for the code @DavidLP provided as well as some other simple test cases on OSX using numba 0.23.1 as well. 

Uh, this is a regression indeed. In the meantime, a possible workaround is to reverse the lookup order (that is use `a.x[0]` instead of `a[0].x`). Another workaround is to pass the index as an argument (instead of the constant `0`).


Resolving patch:
diff --git a/numba/targets/arrayobj.py b/numba/targets/arrayobj.py
--- a/numba/targets/arrayobj.py
+++ b/numba/targets/arrayobj.py
@@ -1545,7 +1545,11 @@ def array_record_getattr(context, builder, typ, value, attr):
 
 @lower_builtin('static_getitem', types.Array, types.Const)
 def array_record_getitem(context, builder, sig, args):
-    return array_record_getattr(context, builder, sig.args[0], args[0], args[1])
+    index = args[1]
+    if not isinstance(index, str):
+        # This will fallback to normal getitem
+        raise NotImplementedError
+    return array_record_getattr(context, builder, sig.args[0], args[0], index)
 
 
 @lower_getattr_generic(types.Record)


Test patch:
diff --git a/numba/tests/test_record_dtype.py b/numba/tests/test_record_dtype.py
--- a/numba/tests/test_record_dtype.py
+++ b/numba/tests/test_record_dtype.py
@@ -25,6 +25,10 @@ def get_xx(ary, i):
         return ary[i][item]
     return get_xx
 
+# Issue #1664: constant index lookup should fall back to regular getitem
+def get_zero_a(ary, _unused):
+    return ary[0].a
+
 getitem_a = make_getitem('a')
 getitem_b = make_getitem('b')
 getitem_c = make_getitem('c')
@@ -38,6 +42,9 @@ def get_b_subarray(ary, i):
 def get_c_subarray(ary, i):
     return ary.c[i]
 
+def get_a_zero(ary, _unused):
+    return ary.a[0]
+
 def make_getitem_subarray(item):
     # This also exercises constant lookup from a closure variable
     def get_xx_subarray(ary, i):
@@ -308,6 +315,8 @@ def test_get_a(self):
         self._test_get_equal(get_a_subarray)
         self._test_get_equal(getitem_a)
         self._test_get_equal(getitem_a_subarray)
+        self._test_get_equal(get_a_zero)
+        self._test_get_equal(get_zero_a)
 
     def test_get_b(self):
         self._test_get_equal(get_b)
Repository: numba/numba

Issue:
sum() of boolean array is wrong
```
>>> def sum(x): return x.sum()
>>> jitted_sum = jit(nopython=True)(sum)
>>> a = np.bool_([1,0,1])
>>> a
array([ True, False,  True], dtype=bool)
>>> sum(a)
2
>>> jitted_sum(a)
True
```



Discussion:

Resolving patch:
diff --git a/numba/typing/arraydecl.py b/numba/typing/arraydecl.py
--- a/numba/typing/arraydecl.py
+++ b/numba/typing/arraydecl.py
@@ -427,6 +427,8 @@ def _expand_integer(ty):
             return max(types.intp, ty)
         else:
             return max(types.uintp, ty)
+    elif isinstance(ty, types.Boolean):
+        return types.intp
     else:
         return ty
 
@@ -447,7 +449,7 @@ def generic_expand_cumulative(self, args, kws):
 def generic_hetero_real(self, args, kws):
     assert not args
     assert not kws
-    if self.this.dtype in types.integer_domain:
+    if isinstance(self.this.dtype, (types.Integer, types.Boolean)):
         return signature(types.float64, recvr=self.this)
     return signature(self.this.dtype, recvr=self.this)
 


Test patch:
diff --git a/numba/tests/test_array_reductions.py b/numba/tests/test_array_reductions.py
--- a/numba/tests/test_array_reductions.py
+++ b/numba/tests/test_array_reductions.py
@@ -81,9 +81,17 @@ def array_median_global(arr):
 
 
 def base_test_arrays(dtype):
-    a1 = np.arange(10, dtype=dtype) + 1
-    a2 = np.arange(10, dtype=dtype).reshape(2, 5) + 1
-    a3 = (np.arange(60, dtype=dtype))[::2].reshape((2, 5, 3), order='A')
+    if dtype == np.bool_:
+        def factory(n):
+            assert n % 2 == 0
+            return np.bool_([0, 1] * (n // 2))
+    else:
+        def factory(n):
+            return np.arange(n, dtype=dtype) + 1
+
+    a1 = factory(10)
+    a2 = factory(10).reshape(2, 5)
+    a3 = (factory(60))[::2].reshape((2, 5, 3), order='A')
 
     return [a1, a2, a3]
 
@@ -94,6 +102,8 @@ def full_test_arrays(dtype):
     if dtype == np.float32:
         array_list += [a / 10 for a in array_list]
 
+    for a in array_list:
+        assert a.dtype == np.dtype(dtype)
     return array_list
 
 def run_comparative(compare_func, test_array):
@@ -362,11 +372,12 @@ def install_generated_tests(cls):
                            array_max, array_max_global,
                            array_argmin, array_argmin_global,
                            array_argmax, array_argmax_global]
-        dtypes_to_test = [np.int32, np.float32]
+        dtypes_to_test = [np.int32, np.float32, np.bool_]
 
         # Install tests on class
         for dt in dtypes_to_test:
-            for red_func, test_array in product(reduction_funcs, full_test_arrays(dt)):
+            test_arrays = full_test_arrays(dt)
+            for red_func, test_array in product(reduction_funcs, test_arrays):
                 # Create the name for the test function
                 test_name = "test_{0}_{1}_{2}d".format(red_func.__name__, test_array.dtype.name, test_array.ndim)
Repository: numba/numba

Issue:
Emit DeprecationWarning for Python 2.6, Python 3.3 and NumPy 1.6
We need to generate a DeprecationWarning if Numba is imported and Python 2.6 or 3.3, or NumPy 1.6 is present.  The warning should alert the user that support for these versions will be dropped in Numba 0.25.

We should also put a warning about this in our Getting Started - Compatibility page.



Discussion:

Resolving patch:
diff --git a/numba/__init__.py b/numba/__init__.py
--- a/numba/__init__.py
+++ b/numba/__init__.py
@@ -2,7 +2,9 @@
 Expose top-level symbols that are safe for import *
 """
 from __future__ import print_function, division, absolute_import
+
 import re
+import sys
 
 from . import runtests, decorators
 from . import errors, special, types, config
@@ -83,7 +85,32 @@ def _ensure_llvm():
 
     check_jit_execution()
 
+
+def _ensure_pynumpy():
+    """
+    Make sure Python and Numpy have supported versions.
+    """
+    import warnings
+    from . import numpy_support
+
+    pyver = sys.version_info[:2]
+    strver = "%d.%d" % pyver
+    if pyver in ((2, 6), (3, 3)):
+        warnings.warn("Support for Python %d.%d will be dropped in Numba 0.25"
+                      % pyver, DeprecationWarning)
+    if pyver < (2, 6) or ((3,) <= pyver < (3, 3)):
+        raise ImportError("Numba needs Python 2.6 or greater, or 3.3 or greater")
+
+    np_version = numpy_support.version[:2]
+    if np_version == (1, 6):
+        warnings.warn("Support for Numpy %d.%d will be dropped in Numba 0.25"
+                      % np_version, DeprecationWarning)
+    if np_version < (1, 6):
+        raise ImportError("Numba needs Numpy 1.6 or greater")
+
+
 _ensure_llvm()
+_ensure_pynumpy()
 
 
 from ._version import get_versions


Test patch:
Repository: numba/numba

Issue:
Numba nopython mode returns incorrect results
Python version: '3.5.1 |Continuum Analytics, Inc.| (default, Dec  7 2015, 11:16:01) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]'
Numba version: 0.25.0

I'm experiencing some errors with numba - below is an MRE.

This code (without jit) 

``` python
from pylab import *
from numba import jit

mktarr = array([86])
styarr = array([100]);
indarr = array([150])
# @jit(nopython=True, nogil=True)
def factor_type(x):
    for a in mktarr:
        if x == a: 
            return 0
    for a in styarr:
        if x == a: 
            return 1
    for a in indarr:
        if x == a: 
            return 2
    return -1
factor_type( 86 )
```

returns as expected:
`0`

but

``` python
@jit(nopython=True, nogil=True)
def factor_type(x):
    for a in mktarr:
        if x == a: 
            return 0
    for a in styarr:
        if x == a: 
            return 1
    for a in indarr:
        if x == a: 
            return 2
    return -1
factor_type( 86 )
```

returns `-1`. This problem persists with or without nopython.

Any suggestions ?



Discussion:
Something went wrong in the lowering of the constant array.

The `mktarr` is initialized as:

``` llvm
@.const.array.data = internal constant [86 x i8] zeroinitializer
```

(`86` bytes of initialized to zero)


Resolving patch:
diff --git a/numba/targets/base.py b/numba/targets/base.py
--- a/numba/targets/base.py
+++ b/numba/targets/base.py
@@ -791,7 +791,9 @@ def make_constant_array(self, builder, typ, ary):
         # Handle data: reify the flattened array in "C" order as a
         # global array of bytes.
         flat = ary.flatten()
-        consts = Constant.array(Type.int(8), bytearray(flat))
+        # Note: we use `bytearray(flat.data)` instead of `bytearray(flat)` to
+        #       workaround issue #1850 which is due to numpy issue #3147
+        consts = Constant.array(Type.int(8), bytearray(flat.data))
         data = cgutils.global_constant(builder, ".const.array.data", consts)
 
         # Handle shape


Test patch:
diff --git a/numba/tests/test_arrayconst.py b/numba/tests/test_arrayconst.py
--- a/numba/tests/test_arrayconst.py
+++ b/numba/tests/test_arrayconst.py
@@ -23,15 +23,19 @@
 def getitem1(i):
     return a1[i]
 
+
 def getitem2(i):
     return a2[i]
 
+
 def getitem3(i):
     return a3[i]
 
+
 def getitem4(i):
     return a4[i]
 
+
 def getitem5(i):
     return a5[i]
 
@@ -79,6 +83,20 @@ def test_write_to_global_array(self):
         with self.assertRaises(TypingError):
             compile_isolated(pyfunc, ())
 
+    def test_issue_1850(self):
+        """
+        This issue is caused by an unresolved bug in numpy since version 1.6.
+        See numpy GH issue #3147.
+        """
+        constarr = np.array([86])
+
+        def pyfunc():
+            return constarr[0]
+
+        cres = compile_isolated(pyfunc, ())
+        out = cres.entry_point()
+        self.assertEqual(out, 86)
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: numba/numba

Issue:
Failure in CUDA tests
I get the following failure deterministically when running `./runtests.py -vf numba.cuda.tests` (although the exact integer value varies from run to run):

```
======================================================================
ERROR: test_cuda_driver_occupancy (numba.cuda.tests.cudadrv.test_cuda_driver.TestCudaDriver)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/antoine/numba/numba/cuda/tests/cudadrv/test_cuda_driver.py", line 117, in test_cuda_driver_occupancy
    module = self.context.create_module_ptx(self.ptx)
  File "/home/antoine/numba/numba/cuda/cudadrv/driver.py", line 646, in create_module_ptx
    return self.create_module_image(image)
  File "/home/antoine/numba/numba/cuda/cudadrv/driver.py", line 649, in create_module_image
    self.trashing.service()
  File "/home/antoine/numba/numba/servicelib/service.py", line 30, in service
    next(self._task)
  File "/home/antoine/numba/numba/cuda/cudadrv/driver.py", line 321, in process
    cb()
  File "/home/antoine/numba/numba/cuda/cudadrv/driver.py", line 779, in cleanup
    del modules[handle.value]
KeyError: 47652304
```



Discussion:
According to `git bisect`, this was introduced in 0d67b645aadc667e26d3243d2e48779f8394524f.


Resolving patch:
diff --git a/numba/cuda/cudadrv/driver.py b/numba/cuda/cudadrv/driver.py
--- a/numba/cuda/cudadrv/driver.py
+++ b/numba/cuda/cudadrv/driver.py
@@ -775,8 +775,16 @@ def _module_finalizer(context, handle):
 
     def core():
         def cleanup():
-            if modules:
-                del modules[handle.value]
+            # All modules are owned by their parent Context.
+            # A Module is either released by a call to
+            # Context.unload_module, which clear the handle (pointer) mapping
+            # (checked by the following assertion), or, by Context.reset().
+            # Both releases the sole reference to the Module and trigger the
+            # finalizer for the Module instance.  The actual call to
+            # cuModuleUnload is deferred to the trashing service to avoid
+            # further corruption of the CUDA context if a fatal error has
+            # occurred in the CUDA driver.
+            assert handle.value not in modules
             driver.cuModuleUnload(handle)
 
         trashing.add_trash(cleanup)
@@ -1038,14 +1046,8 @@ def __init__(self, context, handle, info_log, finalizer=None):
         self.handle = handle
         self.info_log = info_log
         self.finalizer = finalizer
-        self.is_managed = self.finalizer is not None
-
-    def __del__(self):
-        try:
-            if self.is_managed:
-                self.finalizer()
-        except:
-            traceback.print_exc()
+        if self.finalizer is not None:
+            self._finalizer = utils.finalize(self, finalizer)
 
     def unload(self):
         self.context.unload_module(self)


Test patch:
Repository: numba/numba

Issue:
Numba UnicodeEncodeError after importing unicode_literals 
Taking example below from numba documentation with the only addition of `unicode_literals` import and the doc string that contains unicode characters:

```
from __future__ import unicode_literals
from numba import jit
from numpy import arange

# jit decorator tells Numba to compile this function.
# The argument types will be inferred by Numba when function is called.
@jit
def sum2d(arr):
    """ – """
    M, N = arr.shape
    result = 0.0
    for i in range(M):
        for j in range(N):
            result += arr[i,j]
    return result

a = arange(9).reshape(3,3)
print(sum2d(a))
```

Gives an error below. The error appears only after `unicode_literals` is imported:

```
raise patched_exception
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 1: ordinal not in range(128)

D:\Anaconda\envs\py2k\lib\site-packages\numba\compiler.py:257: UnicodeEncodeError
```

`python = 2.7.11`
`numba = 0.25.0`



Discussion:

Resolving patch:
diff --git a/numba/targets/cpu.py b/numba/targets/cpu.py
--- a/numba/targets/cpu.py
+++ b/numba/targets/cpu.py
@@ -156,9 +156,12 @@ def get_executable(self, library, fndesc, env):
         baseptr = library.get_pointer_to_function(fndesc.llvm_func_name)
         fnptr = library.get_pointer_to_function(fndesc.llvm_cpython_wrapper_name)
 
+        # Note: we avoid reusing the original docstring to avoid encoding
+        # issues on Python 2, see issue #1908
+        doc = "compiled wrapper for %r" % (fndesc.qualname,)
         cfunc = _dynfunc.make_function(fndesc.lookup_module(),
                                        fndesc.qualname.split('.')[-1],
-                                       fndesc.doc, fnptr, env,
+                                       doc, fnptr, env,
                                        # objects to keepalive with the function
                                        (library,)
                                        )


Test patch:
diff --git a/numba/tests/test_unicode_literals.py b/numba/tests/test_unicode_literals.py
new file mode 100644
--- /dev/null
+++ b/numba/tests/test_unicode_literals.py
@@ -0,0 +1,32 @@
+from __future__ import print_function, unicode_literals
+
+import sys
+
+import numpy as np
+
+import numba.unittest_support as unittest
+from numba import utils, jit
+from .support import TestCase
+
+
+def docstring_usecase():
+    """\u00e9"""
+    return 1
+
+
+@unittest.skipIf(sys.version_info >= (3,), "Python 2-specific test")
+class TestFutureUnicodeLiterals(TestCase):
+    """
+    Test issues with unicode_literals on Python 2.
+    """
+
+    def test_docstring(self):
+        """
+        Test non-ASCII docstring (issue #1908).
+        """
+        cfunc = jit(nopython=True)(docstring_usecase)
+        self.assertPreciseEqual(cfunc(), 1)
+
+
+if __name__ == '__main__':
+    unittest.main()