"vscode:/vscode.git/clone" did not exist on "5b26b3b0e01f5d2bf4969ce32dd0cb0b1d7e4549"
test_ndarray_subclasses.py 10.4 KB
Newer Older
dugupeiwen's avatar
dugupeiwen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
"""
Test NumPy Subclassing features
"""

import builtins
import unittest
from numbers import Number
from functools import wraps

import numpy as np
from llvmlite import ir

import numba
from numba import njit, typeof, objmode
from numba.core import cgutils, types, typing
from numba.core.pythonapi import box
from numba.core.errors import TypingError
from numba.core.registry import cpu_target
from numba.extending import (intrinsic, lower_builtin, overload_classmethod,
                             register_model, type_callable, typeof_impl,
                             register_jitable)
from numba.np import numpy_support

from numba.tests.support import TestCase, MemoryLeakMixin

# A quick util to allow logging within jit code

_logger = None


def _do_log(*args):
    if _logger is not None:
        _logger.append(args)


@register_jitable
def log(*args):
    with objmode():
        _do_log(*args)


def use_logger(fn):
    @wraps(fn)
    def core(*args, **kwargs):
        global _logger
        _logger = []
        return fn(*args, **kwargs)
    return core


class MyArray(np.ndarray):
    # Tell Numba to not seamlessly treat this type as a regular ndarray.
    __numba_array_subtype_dispatch__ = True

    # __array__ is not needed given that this is a ndarray subclass
    #
    # def __array__(self, dtype=None):
    #     return self

    # Interoperate with NumPy outside of Numba.
    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        if method == "__call__":
            N = None
            scalars = []
            for inp in inputs:
                if isinstance(inp, Number):
                    scalars.append(inp)
                elif isinstance(inp, (type(self), np.ndarray)):
                    if isinstance(inp, type(self)):
                        scalars.append(np.ndarray(inp.shape, inp.dtype, inp))
                    else:
                        scalars.append(inp)
                    if N is not None:
                        if N != inp.shape:
                            raise TypeError("inconsistent sizes")
                    else:
                        N = inp.shape
                else:
                    return NotImplemented
            ret = ufunc(*scalars, **kwargs)
            return self.__class__(ret.shape, ret.dtype, ret)
        else:
            return NotImplemented


class MyArrayType(types.Array):
    def __init__(self, dtype, ndim, layout, readonly=False, aligned=True):
        name = f"MyArray({ndim}, {dtype}, {layout})"
        super().__init__(dtype, ndim, layout, readonly=readonly,
                         aligned=aligned, name=name)

    def copy(self, *args, **kwargs):
        # This is here to future-proof.
        # The test here never uses this.
        raise NotImplementedError

    # Tell Numba typing how to combine MyArrayType with other ndarray types.
    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        if method == "__call__":
            for inp in inputs:
                if not isinstance(inp, (types.Array, types.Number)):
                    return NotImplemented
            # Ban if all arguments are MyArrayType
            if all(isinstance(inp, MyArrayType) for inp in inputs):
                return NotImplemented
            return MyArrayType
        else:
            return NotImplemented

    @property
    def box_type(self):
        return MyArray


@typeof_impl.register(MyArray)
def typeof_ta_ndarray(val, c):
    try:
        dtype = numpy_support.from_dtype(val.dtype)
    except NotImplementedError:
        raise ValueError("Unsupported array dtype: %s" % (val.dtype,))
    layout = numpy_support.map_layout(val)
    readonly = not val.flags.writeable
    return MyArrayType(dtype, val.ndim, layout, readonly=readonly)


@register_model(MyArrayType)
class MyArrayTypeModel(numba.core.datamodel.models.StructModel):
    def __init__(self, dmm, fe_type):
        ndim = fe_type.ndim
        members = [
            ('meminfo', types.MemInfoPointer(fe_type.dtype)),
            ('parent', types.pyobject),
            ('nitems', types.intp),
            ('itemsize', types.intp),
            ('data', types.CPointer(fe_type.dtype)),
            ('shape', types.UniTuple(types.intp, ndim)),
            ('strides', types.UniTuple(types.intp, ndim)),
            ('extra_field', types.intp),
        ]
        super(MyArrayTypeModel, self).__init__(dmm, fe_type, members)


@type_callable(MyArray)
def type_myarray(context):
    def typer(shape, dtype, buf):
        out = MyArrayType(
            dtype=buf.dtype, ndim=len(shape), layout=buf.layout
        )
        return out

    return typer


@lower_builtin(MyArray, types.UniTuple, types.DType, types.Array)
def impl_myarray(context, builder, sig, args):
    from numba.np.arrayobj import make_array, populate_array

    srcaryty = sig.args[-1]
    shape, dtype, buf = args

    srcary = make_array(srcaryty)(context, builder, value=buf)
    # Copy source array and remove the parent field to avoid boxer re-using
    # the original ndarray instance.
    retary = make_array(sig.return_type)(context, builder)
    populate_array(retary,
                   data=srcary.data,
                   shape=srcary.shape,
                   strides=srcary.strides,
                   itemsize=srcary.itemsize,
                   meminfo=srcary.meminfo)

    ret = retary._getvalue()
    context.nrt.incref(builder, sig.return_type, ret)
    return ret


@box(MyArrayType)
def box_array(typ, val, c):
    assert c.context.enable_nrt
    np_dtype = numpy_support.as_dtype(typ.dtype)
    dtypeptr = c.env_manager.read_const(c.env_manager.add_const(np_dtype))
    newary = c.pyapi.nrt_adapt_ndarray_to_python(typ, val, dtypeptr)
    # Steals NRT ref
    c.context.nrt.decref(c.builder, typ, val)
    return newary


@overload_classmethod(MyArrayType, "_allocate")
def _ol_array_allocate(cls, allocsize, align):
    """Implements a Numba-only classmethod on the array type.
    """
    def impl(cls, allocsize, align):
        log("LOG _ol_array_allocate", allocsize, align)
        return allocator_MyArray(allocsize, align)

    return impl


@intrinsic
def allocator_MyArray(typingctx, allocsize, align):
    def impl(context, builder, sig, args):
        context.nrt._require_nrt()
        size, align = args

        mod = builder.module
        u32 = ir.IntType(32)
        voidptr = cgutils.voidptr_t

        get_alloc_fnty = ir.FunctionType(voidptr, ())
        get_alloc_fn = cgutils.get_or_insert_function(
            mod, get_alloc_fnty, name="_nrt_get_sample_external_allocator"
        )
        ext_alloc = builder.call(get_alloc_fn, ())

        fnty = ir.FunctionType(voidptr, [cgutils.intp_t, u32, voidptr])
        fn = cgutils.get_or_insert_function(
            mod, fnty, name="NRT_MemInfo_alloc_safe_aligned_external"
        )
        fn.return_value.add_attribute("noalias")
        if isinstance(align, builtins.int):
            align = context.get_constant(types.uint32, align)
        else:
            assert align.type == u32, "align must be a uint32"
        call = builder.call(fn, [size, align, ext_alloc])
        call.name = "allocate_MyArray"
        return call

    mip = types.MemInfoPointer(types.voidptr)  # return untyped pointer
    sig = typing.signature(mip, allocsize, align)
    return sig, impl


class TestNdarraySubclasses(MemoryLeakMixin, TestCase):

    def test_myarray_return(self):
        """This tests the path to `MyArrayType.box_type`
        """
        @njit
        def foo(a):
            return a + 1

        buf = np.arange(4)
        a = MyArray(buf.shape, buf.dtype, buf)
        expected = foo.py_func(a)
        got = foo(a)
        self.assertIsInstance(got, MyArray)
        self.assertIs(type(expected), type(got))
        self.assertPreciseEqual(expected, got)

    def test_myarray_passthru(self):
        @njit
        def foo(a):
            return a

        buf = np.arange(4)
        a = MyArray(buf.shape, buf.dtype, buf)
        expected = foo.py_func(a)
        got = foo(a)
        self.assertIsInstance(got, MyArray)
        self.assertIs(type(expected), type(got))
        self.assertPreciseEqual(expected, got)

    def test_myarray_convert(self):
        @njit
        def foo(buf):
            return MyArray(buf.shape, buf.dtype, buf)

        buf = np.arange(4)
        expected = foo.py_func(buf)
        got = foo(buf)
        self.assertIsInstance(got, MyArray)
        self.assertIs(type(expected), type(got))
        self.assertPreciseEqual(expected, got)

    def test_myarray_asarray_non_jit(self):
        def foo(buf):
            converted = MyArray(buf.shape, buf.dtype, buf)
            return np.asarray(converted) + buf

        buf = np.arange(4)
        got = foo(buf)
        self.assertIs(type(got), np.ndarray)
        self.assertPreciseEqual(got, buf + buf)

    @unittest.expectedFailure
    def test_myarray_asarray(self):
        self.disable_leak_check()

        @njit
        def foo(buf):
            converted = MyArray(buf.shape, buf.dtype, buf)
            return np.asarray(converted)

        buf = np.arange(4)
        got = foo(buf)
        # the following fails because our np.asarray is returning the source
        # array type
        self.assertIs(type(got), np.ndarray)

    def test_myarray_ufunc_unsupported(self):
        @njit
        def foo(buf):
            converted = MyArray(buf.shape, buf.dtype, buf)
            return converted + converted

        buf = np.arange(4, dtype=np.float32)
        with self.assertRaises(TypingError) as raises:
            foo(buf)

        msg = ("No implementation of function",
               "add(MyArray(1, float32, C), MyArray(1, float32, C))")
        for m in msg:
            self.assertIn(m, str(raises.exception))

    @use_logger
    def test_myarray_allocator_override(self):
        """
        Checks that our custom allocator is used
        """
        @njit
        def foo(a):
            b = a + np.arange(a.size, dtype=np.float64)
            c = a + 1j
            return b, c

        buf = np.arange(4, dtype=np.float64)
        a = MyArray(buf.shape, buf.dtype, buf)

        expected = foo.py_func(a)
        got = foo(a)

        self.assertPreciseEqual(got, expected)

        logged_lines = _logger

        targetctx = cpu_target.target_context
        nb_dtype = typeof(buf.dtype)
        align = targetctx.get_preferred_array_alignment(nb_dtype)
        self.assertEqual(logged_lines, [
            ("LOG _ol_array_allocate", expected[0].nbytes, align),
            ("LOG _ol_array_allocate", expected[1].nbytes, align),
        ])


if __name__ == "__main__":
    unittest.main()