/
_kernel.pyx
1661 lines (1429 loc) · 56 KB
/
_kernel.pyx
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import string
import warnings
import numpy
import cupy
from cupy.cuda import compiler
from cupy import _util
cimport cython # NOQA
from libcpp cimport vector
from cupy.cuda cimport device
from cupy.cuda cimport function
from cupy.cuda cimport memory
from cupy.cuda cimport texture
from cupy._core cimport _accelerator
from cupy._core cimport _carray
from cupy._core cimport _scalar
from cupy._core._dtype cimport get_dtype, _raise_if_invalid_cast
from cupy._core._memory_range cimport may_share_bounds
from cupy._core._scalar import get_typename as _get_typename
from cupy._core cimport core
from cupy._core.core cimport _convert_object_with_cuda_array_interface
from cupy._core.core cimport _ndarray_init
from cupy._core.core cimport compile_with_cache
from cupy._core.core cimport _ndarray_base
from cupy._core cimport internal
from cupy_backends.cuda.api cimport runtime
try:
import cupy_backends.cuda.libs.cutensor as cuda_cutensor
except ImportError:
cuda_cutensor = None
from cupy._core import _fusion_thread_local
cdef inline bint _contains_zero(const shape_t& v) except? -1:
for i in range(v.size()):
if v[i] == 0:
return True
return False
@_util.memoize(for_each_device=True)
def _get_warpsize():
device_id = runtime.getDevice()
return runtime.getDeviceProperties(device_id)['warpSize']
cdef str _get_simple_elementwise_kernel_code(
tuple params, tuple arginfos, str operation, str name,
_TypeMap type_map, str preamble, str loop_prep='', str after_loop=''):
# No loop unrolling due to avoid 64-bit division
module_code = string.Template('''
${typedef_preamble}
${preamble}
extern "C" __global__ void ${name}(${params}) {
${loop_prep};
#pragma unroll 1
CUPY_FOR(i, _ind.size()) {
_ind.set(i);
${operation};
}
${after_loop};
}
''').substitute(
typedef_preamble=type_map.get_typedef_code(),
params=_get_kernel_params(params, arginfos),
operation=operation,
name=name,
preamble=preamble,
loop_prep=loop_prep,
after_loop=after_loop)
return module_code
cdef function.Function _get_simple_elementwise_kernel_from_code(
str name, str code, tuple options=()):
module = compile_with_cache(code, options)
return module.get_function(name)
cdef function.Function _get_simple_elementwise_kernel(
tuple params, tuple arginfos, str operation, str name,
_TypeMap type_map, str preamble, str loop_prep='', str after_loop='',
tuple options=()):
code = _get_simple_elementwise_kernel_code(
params, arginfos, operation, name, type_map, preamble, loop_prep,
after_loop
)
return _get_simple_elementwise_kernel_from_code(name, code, options)
cdef inline int _get_kind_score(int kind):
if b'b' == kind:
return 0
if b'u' == kind or b'i' == kind:
return 1
if b'f' == kind or b'c' == kind:
return 2
return -1
@cython.profile(False)
cpdef inline _check_peer_access(_ndarray_base arr, int device_id):
if arr.data.device_id == device_id:
return
msg = (
f'The device where the array resides ({arr.data.device_id}) is '
f'different from the current device ({device_id}).'
)
cdef bint peer_access = device._enable_peer_access(
device_id, arr.data.device_id)
if not peer_access:
raise ValueError(
f'{msg} Peer access is unavailable between these devices.')
warnings.warn(
f'{msg} Peer access has been activated automatically.',
_util.PerformanceWarning)
cdef inline _preprocess_arg(int dev_id, arg, bint use_c_scalar):
if isinstance(arg, _ndarray_base):
s = arg
_check_peer_access(<_ndarray_base>s, dev_id)
elif isinstance(arg, texture.TextureObject):
s = arg
elif hasattr(arg, '__cuda_array_interface__'):
s = _convert_object_with_cuda_array_interface(arg)
_check_peer_access(<_ndarray_base>s, dev_id)
elif hasattr(arg, '__cupy_get_ndarray__'):
s = arg.__cupy_get_ndarray__()
_check_peer_access(<_ndarray_base>s, dev_id)
else: # scalars or invalid args
if use_c_scalar:
s = _scalar.scalar_to_c_scalar(arg)
else:
s = _scalar.scalar_to_numpy_scalar(arg)
if s is None:
raise TypeError('Unsupported type %s' % type(arg))
return s
cdef list _preprocess_args(int dev_id, args, bint use_c_scalar):
"""Preprocesses arguments for kernel invocation
- Checks device compatibility for ndarrays
- Converts Python/NumPy scalars:
- If use_c_scalar is True, into CScalars.
- If use_c_scalar is False, into NumPy scalars.
"""
cdef list ret = []
for arg in args:
ret.append(_preprocess_arg(dev_id, arg, use_c_scalar))
return ret
cdef list _preprocess_optional_args(int dev_id, args, bint use_c_scalar):
"""Preprocesses arguments for kernel invocation
- Checks device compatibility for ndarrays
- Converts Python/NumPy scalars:
- If use_c_scalar is True, into CScalars.
- If use_c_scalar is False, into NumPy scalars.
"""
cdef list ret = []
for arg in args:
if arg is None:
ret.append(None)
else:
ret.append(_preprocess_arg(dev_id, arg, use_c_scalar))
return ret
cdef class _ArgInfo:
# Holds metadata of an argument.
# This class is immutable and used as a part of hash keys.
def __init__(self, *args):
arg_kind, typ, dtype, ndim, c_contiguous, index_32_bits = args
self._init(arg_kind, typ, dtype, ndim, c_contiguous, index_32_bits)
cdef _ArgInfo _init(
self,
_ArgKind arg_kind,
type typ,
object dtype,
int ndim,
bint c_contiguous,
bint index_32_bits):
self.arg_kind = arg_kind
self.type = typ
self.dtype = dtype
self.ndim = ndim
self.c_contiguous = c_contiguous
self.index_32_bits = index_32_bits
@staticmethod
cdef _ArgInfo from_arg(object arg):
typ = type(arg)
if issubclass(typ, _ndarray_base):
return _ArgInfo.from_ndarray(arg)
if typ is _scalar.CScalar:
return _ArgInfo.from_scalar(arg)
if typ is _carray.Indexer:
return _ArgInfo.from_indexer(arg)
if typ is memory.MemoryPointer:
return _ArgInfo.from_memptr(arg)
if typ is texture.TextureObject:
return _ArgInfo.from_texture(arg)
assert False, typ
@staticmethod
cdef _ArgInfo from_ndarray(_ndarray_base arg):
cdef _ArgInfo ret = _ArgInfo.__new__(_ArgInfo)
ret._init(
ARG_KIND_NDARRAY,
type(arg),
arg.dtype.type,
arg._shape.size(),
arg._c_contiguous,
arg._index_32_bits)
return ret
@staticmethod
cdef _ArgInfo from_scalar(_scalar.CScalar arg):
cdef _ArgInfo ret = _ArgInfo.__new__(_ArgInfo)
dtype = arg.get_numpy_type()
ret._init(ARG_KIND_SCALAR, _scalar.CScalar, dtype, 0, True, True)
return ret
@staticmethod
cdef _ArgInfo from_indexer(_carray.Indexer arg):
cdef _ArgInfo ret = _ArgInfo.__new__(_ArgInfo)
ret._init(
ARG_KIND_INDEXER, _carray.Indexer, None, arg.ndim, True,
arg._index_32_bits)
return ret
@staticmethod
cdef _ArgInfo from_memptr(memory.MemoryPointer arg):
cdef _ArgInfo ret = _ArgInfo.__new__(_ArgInfo)
ret._init(
ARG_KIND_POINTER, memory.MemoryPointer, None, 0, True, True)
return ret
@staticmethod
cdef _ArgInfo from_texture(texture.TextureObject arg):
cdef _ArgInfo ret = _ArgInfo.__new__(_ArgInfo)
ret._init(
ARG_KIND_TEXTURE, texture.TextureObject, None, 0, True, True)
return ret
def __hash__(self):
return hash((self.arg_kind, self.type, self.dtype, self.ndim,
self.c_contiguous, self.index_32_bits))
def __eq__(self, other):
cdef _ArgInfo oth
if not isinstance(other, _ArgInfo):
return False
oth = other
return (
self.arg_kind == oth.arg_kind
and self.type is oth.type
and self.dtype == oth.dtype
and self.ndim == oth.ndim
and self.c_contiguous == oth.c_contiguous
and self.index_32_bits == oth.index_32_bits)
def __repr__(self):
return '<_ArgInfo({})>'.format(
' '.join([
'arg_kind={!r}'.format(self.arg_kind),
'type={!r}'.format(self.type),
'dtype={!r}'.format(self.dtype),
'ndim={!r}'.format(self.ndim),
'c_contiguous={!r}'.format(self.c_contiguous),
'index_32_bits={!r}'.format(self.index_32_bits),
]))
cdef _ArgInfo as_ndarray_with_ndim(self, int ndim):
# Returns an ndarray _ArgInfo with altered ndim.
# If ndim is the same, self is returned untouched.
assert self.arg_kind == ARG_KIND_NDARRAY
if self.ndim == ndim:
return self
return _ArgInfo(
ARG_KIND_NDARRAY, self.dtype, self.dtype, ndim, False, False)
cdef bint is_ndarray(self):
return self.arg_kind == ARG_KIND_NDARRAY
cdef bint is_scalar(self):
return self.arg_kind == ARG_KIND_SCALAR
cdef str get_c_type(self):
# Returns the C type representation.
if self.arg_kind == ARG_KIND_NDARRAY:
return 'CArray<%s, %d, %d, %d>' % (
_get_typename(self.dtype), self.ndim,
self.c_contiguous, self.index_32_bits)
if self.arg_kind == ARG_KIND_SCALAR:
return _get_typename(self.dtype)
if self.arg_kind == ARG_KIND_INDEXER:
return 'CIndexer<%d, %d>' % (self.ndim, self.index_32_bits)
if self.arg_kind == ARG_KIND_TEXTURE:
return 'cudaTextureObject_t'
assert False
cdef str get_param_c_type(self, ParameterInfo p):
# Returns the C type representation in the global function's
# parameter list.
cdef str ctyp = self.get_c_type()
if p.is_const:
return 'const ' + ctyp
return ctyp
cdef str get_c_var_name(self, ParameterInfo p):
if self.arg_kind in (ARG_KIND_NDARRAY, ARG_KIND_POINTER) and not p.raw:
return '_raw_' + p.name
return p.name
cdef tuple _get_arginfos(list args):
return tuple([_ArgInfo.from_arg(a) for a in args])
cdef str _get_kernel_params(tuple params, tuple arginfos):
cdef ParameterInfo p
cdef _ArgInfo arginfo
assert len(params) == len(arginfos)
lst = []
for i in range(len(params)):
p = params[i]
arginfo = arginfos[i]
lst.append('{} {}'.format(
arginfo.get_param_c_type(p),
arginfo.get_c_var_name(p)))
return ', '.join(lst)
cdef shape_t _reduce_dims(list args, tuple params, const shape_t& shape):
""" Remove contiguous stride to optimize CUDA kernel."""
cdef _ndarray_base arr
if shape.size() <= 1 or len(args) == 0:
return shape
if len(args) == 1: # fast path for reduction
a = args[0]
if (<ParameterInfo>params[0]).raw or not isinstance(a, _ndarray_base):
return shape
arr = a
arr = arr.reduced_view()
if arr is a:
return shape
else:
args[0] = arr
return arr._shape
return _reduced_view_core(args, params, shape)
cdef shape_t _reduced_view_core(list args, tuple params, const shape_t& shape):
cdef int i, ax, last_ax, ndim
cdef Py_ssize_t total_size
cdef shape_t vecshape, newshape, newstrides
cdef vector.vector[int] array_indexes, axes
cdef vector.vector[int] strides_indexes
cdef ParameterInfo p
cdef _ndarray_base arr
ndim = shape.size()
array_indexes.reserve(len(args))
strides_indexes.reserve(len(args))
for i in range(len(args)):
p = params[i]
if p.raw:
continue
a = args[i]
if isinstance(a, _ndarray_base):
array_indexes.push_back(i)
arr = a
if not arr._c_contiguous:
if ndim == 2: # short cut
return shape
strides_indexes.push_back(i)
if array_indexes.size() == 0:
return shape
if strides_indexes.size() == 0:
# The input arrays are all c_contiguous
i = array_indexes[0]
arr = args[i]
total_size = arr.size
newshape.assign(<Py_ssize_t>1, total_size)
newstrides.resize(1)
for i in array_indexes:
arr = args[i]
newstrides[0] = arr.dtype.itemsize
# TODO(niboshi): Confirm update_x_contiguity flags
args[i] = arr._view(
type(arr), newshape, newstrides, False, True, arr)
return newshape
axes.reserve(ndim)
vecshape.reserve(ndim)
for ax in range(ndim):
vecshape.push_back(shape[ax])
last_ax = -1
for ax in range(ndim):
if vecshape[ax] == 1:
continue
if last_ax < 0:
last_ax = ax
continue
for i in strides_indexes:
arr = args[i]
if arr._strides[ax] * vecshape[ax] != arr._strides[last_ax]:
axes.push_back(last_ax)
break
else:
vecshape[ax] *= vecshape[last_ax]
last_ax = ax
if last_ax >= 0:
axes.push_back(last_ax)
if <int>axes.size() == ndim:
return shape
newshape.reserve(axes.size())
newstrides.reserve(axes.size())
for ax in axes:
newshape.push_back(vecshape[ax])
for i in array_indexes:
arr = args[i]
newstrides.clear()
for ax in axes:
newstrides.push_back(arr._strides[ax])
# TODO(niboshi): Confirm update_x_contiguity flags
args[i] = arr._view(type(arr), newshape, newstrides, False, True, arr)
return newshape
cdef class ParameterInfo:
def __init__(self, str param, bint is_const):
self.name = None
self.dtype = None
self.ctype = None
self.raw = False
self.is_const = is_const
s = tuple([i for i in param.split() if len(i) != 0])
if len(s) < 2:
raise Exception('Syntax error: %s' % param)
t, self.name = s[-2:]
if t == 'CIndexer':
pass
elif len(t) == 1:
self.ctype = t
else:
dtype = get_dtype(t)
self.dtype = dtype.type
if dtype.name != t:
raise ValueError('Wrong type %s' % t)
self.ctype = _get_typename(self.dtype)
for i in s[:-2]:
if i == 'raw':
self.raw = True
elif i == '_non_const':
self.is_const = False
else:
raise Exception('Unknown keyword "%s"' % i)
def __hash__(self):
return hash((
self.name, self.dtype, self.ctype, self.raw, self.is_const))
def __eq__(self, other):
cdef ParameterInfo oth
if not isinstance(other, ParameterInfo):
return False
oth = other
return (
self.name == oth.name
and self.dtype == oth.dtype
and self.ctype == oth.ctype
and self.raw == oth.raw
and self.is_const == oth.is_const)
def __repr__(self):
return '<ParameterInfo({})>'.format(
' '.join([
'name={!r}'.format(self.name),
'dtype={!r}'.format(self.dtype),
'ctype={!r}'.format(self.ctype),
'raw={!r}'.format(self.raw),
'is_const={!r}'.format(self.is_const),
]))
@_util.memoize()
def _get_param_info(str s, is_const):
if len(s) == 0:
return ()
return tuple([ParameterInfo(i, is_const) for i in s.strip().split(',')])
@_util.memoize()
def _decide_params_type(in_params, out_params, in_args_dtype, out_args_dtype):
return _decide_params_type_core(in_params, out_params, in_args_dtype,
out_args_dtype)
cdef class _TypeMap:
def __init__(self, pairs):
self._pairs = pairs
def __hash__(self):
return hash(self._pairs)
def __eq__(self, other):
if not isinstance(other, _TypeMap):
return False
return self._pairs == (<_TypeMap>other)._pairs
def __str__(self):
return '<_TypeMap {}>'.format(self._pairs)
cdef str get_typedef_code(self):
# Returns a code fragment of typedef statements used as preamble.
return ''.join([
'typedef %s %s;\n' % (_get_typename(ctype2), ctype1)
for ctype1, ctype2 in self._pairs])
cdef tuple _decide_params_type_core(
tuple in_params, tuple out_params, tuple in_args_dtype,
tuple out_args_dtype):
type_dict = {}
if out_args_dtype:
assert len(out_params) == len(out_args_dtype)
for p, a in zip(out_params, out_args_dtype):
if a is None:
raise TypeError('Output arguments must be cupy.ndarray')
if p.dtype is not None:
if get_dtype(a) != get_dtype(p.dtype):
raise TypeError(
'Type is mismatched. %s %s %s' % (p.name, a, p.dtype))
elif p.ctype in type_dict:
t = type_dict[p.ctype]
if get_dtype(t) != get_dtype(a):
raise TypeError(
'Type is mismatched. %s %s %s %s' % (
p.name, a, t, p.ctype))
else:
type_dict[p.ctype] = a
assert len(in_params) == len(in_args_dtype)
unknown_ctype = [] # TODO(leofang): remove this as it's unused?
for p, a in zip(in_params, in_args_dtype):
if a is None:
if p.dtype is None:
unknown_ctype.append(p.ctype)
else:
if p.dtype is not None:
if numpy.dtype(a) != numpy.dtype(p.dtype):
raise TypeError(
'Type is mismatched. %s %s %s' % (p.name, a, p.dtype))
elif p.ctype in type_dict:
t = type_dict[p.ctype]
if numpy.dtype(t) != numpy.dtype(a):
raise TypeError(
'Type is mismatched. %s %s %s %s' % (
p.name, a, t, p.ctype))
else:
type_dict[p.ctype] = a
in_types = tuple([type_dict[p.ctype] if p.dtype is None else p.dtype
for p in in_params])
out_types = tuple([type_dict[p.ctype] if p.dtype is None else p.dtype
for p in out_params])
type_map = _TypeMap(tuple(sorted(type_dict.items())))
return in_types, out_types, type_map
cdef list _broadcast(list args, tuple params, bint use_size, shape_t& shape):
# `shape` is an output argument
cdef Py_ssize_t i
cdef ParameterInfo p
cdef bint any_nonraw_array = False
# Collect non-raw arrays
value = []
for i, a in enumerate(args):
p = params[i]
if not p.raw and isinstance(a, _ndarray_base):
# Non-raw array
any_nonraw_array = True
value.append(a)
else:
value.append(None)
if use_size:
if any_nonraw_array:
raise ValueError('Specified \'size\' can be used only '
'if all of the ndarray are \'raw\'.')
else:
if not any_nonraw_array:
raise ValueError('Loop size is undecided.')
# Perform broadcast.
# Note that arrays in `value` are replaced with broadcasted ones.
internal._broadcast_core(value, shape)
# Restore raw arrays and scalars from the original list.
for i, a in enumerate(value):
if a is None:
value[i] = args[i]
return value
cdef _numpy_can_cast = numpy.can_cast
cdef list _get_out_args_from_optionals(
subtype, list out_args, tuple out_types, const shape_t& out_shape, casting,
obj
):
cdef _ndarray_base arr
while len(out_args) < len(out_types):
out_args.append(None)
for i, a in enumerate(out_args):
if a is None:
out_args[i] = _ndarray_init(
subtype, out_shape, out_types[i], obj)
continue
if not isinstance(a, _ndarray_base):
raise TypeError(
'Output arguments type must be cupy.ndarray')
arr = a
if not internal.vector_equal(arr._shape, out_shape):
raise ValueError('Out shape is mismatched')
out_type = get_dtype(out_types[i])
_raise_if_invalid_cast(out_type, arr.dtype, casting, "output operand")
return out_args
cdef _copy_in_args_if_needed(list in_args, list out_args):
# `in_args` is an input and output argument
cdef _ndarray_base inp, out
for i in range(len(in_args)):
a = in_args[i]
if isinstance(a, _ndarray_base):
inp = a
for out in out_args:
if inp is not out and may_share_bounds(inp, out):
in_args[i] = inp.copy()
break
cdef list _get_out_args_with_params(
list out_args, tuple out_types, const shape_t& out_shape,
tuple out_params, bint is_size_specified):
cdef ParameterInfo p
cdef _ndarray_base arr
if not out_args:
for p in out_params:
if p.raw and not is_size_specified:
raise ValueError('Output array size is Undecided')
return [_ndarray_init(
cupy.ndarray, out_shape, t, None) for t in out_types]
for i, p in enumerate(out_params):
a = out_args[i]
if not isinstance(a, _ndarray_base):
raise TypeError(
'Output arguments type must be cupy.ndarray')
arr = a
if not p.raw and not internal.vector_equal(arr._shape, out_shape):
raise ValueError('Out shape is mismatched')
return out_args
@_util.memoize()
def _get_elementwise_kernel_code(
tuple arginfos, _TypeMap type_map,
tuple params, str operation, str name,
str preamble, str loop_prep='', str after_loop='', tuple options=()):
cdef _ArgInfo arginfo
op = []
for p, arginfo in zip(params, arginfos):
if arginfo.is_ndarray() and not p.raw:
if p.is_const:
fmt = 'const {t} &{n} = _raw_{n}[_ind.get()];'
else:
fmt = '{t} &{n} = _raw_{n}[_ind.get()];'
op.append(fmt.format(t=p.ctype, n=p.name))
op.append(operation)
operation = '\n'.join(op)
return _get_simple_elementwise_kernel_code(
params, arginfos, operation, name, type_map,
preamble, loop_prep, after_loop)
@_util.memoize(for_each_device=True)
def _get_elementwise_kernel(
tuple arginfos, _TypeMap type_map,
tuple params, str operation, str name,
str preamble, str loop_prep='', str after_loop='', tuple options=()):
cdef str code = _get_elementwise_kernel_code(
arginfos, type_map, params, operation, name, preamble, loop_prep,
after_loop
)
return _get_simple_elementwise_kernel_from_code(name, code, options)
cdef class ElementwiseKernel:
"""User-defined elementwise kernel.
This class can be used to define an elementwise kernel with or without
broadcasting.
The kernel is compiled at an invocation of the
:meth:`~ElementwiseKernel.__call__` method,
which is cached for each device.
The compiled binary is also cached into a file under the
``$HOME/.cupy/kernel_cache/`` directory with a hashed file name. The cached
binary is reused by other processes.
Args:
in_params (str): Input argument list.
out_params (str): Output argument list.
operation (str): The body in the loop written in CUDA-C/C++.
name (str): Name of the kernel function. It should be set for
readability of the performance profiling.
reduce_dims (bool): If ``False``, the shapes of array arguments are
kept within the kernel invocation. The shapes are reduced
(i.e., the arrays are reshaped without copy to the minimum
dimension) by default. It may make the kernel fast by reducing the
index calculations.
options (tuple): Compile options passed to NVRTC. For details, see
https://docs.nvidia.com/cuda/nvrtc/index.html#group__options.
preamble (str): Fragment of the CUDA-C/C++ code that is inserted at the
top of the cu file.
no_return (bool): If ``True``, __call__ returns ``None``.
return_tuple (bool): If ``True``, __call__ always returns tuple of
array even if single value is returned.
loop_prep (str): Fragment of the CUDA-C/C++ code that is inserted at
the top of the kernel function definition and above the ``for``
loop.
after_loop (str): Fragment of the CUDA-C/C++ code that is inserted at
the bottom of the kernel function definition.
"""
cdef:
readonly tuple in_params
readonly tuple out_params
readonly Py_ssize_t nin
readonly Py_ssize_t nout
readonly Py_ssize_t nargs
readonly tuple params
readonly object operation
readonly str name
readonly str __name__
readonly bint reduce_dims
readonly object preamble
readonly bint no_return
readonly bint return_tuple
readonly dict kwargs
readonly dict _params_type_memo
readonly dict _elementwise_kernel_memo
readonly dict _cached_codes
def __init__(self, in_params, out_params, operation,
name='kernel', reduce_dims=True, preamble='',
no_return=False, return_tuple=False, **kwargs):
if not compiler.is_valid_kernel_name(name):
raise ValueError(
'Invalid kernel name: "%s"' % name)
self.in_params = _get_param_info(in_params, True)
self.out_params = _get_param_info(out_params, False)
self.nin = len(self.in_params)
self.nout = len(self.out_params)
self.nargs = self.nin + self.nout
param_rest = _get_param_info('CIndexer _ind', False)
self.params = self.in_params + self.out_params + param_rest
self.operation = operation
self.name = name
self.reduce_dims = reduce_dims
self.preamble = preamble
self.no_return = no_return
self.return_tuple = return_tuple
self.kwargs = kwargs
self._params_type_memo = {}
self._cached_codes = {}
names = [p.name for p in self.in_params + self.out_params]
if 'i' in names:
raise ValueError('Can not use \'i\' as a parameter name')
self._elementwise_kernel_memo = {}
# This is for profiling mechanisms to auto infer a name
self.__name__ = name
def __call__(self, *args, **kwargs):
"""Compiles and invokes the elementwise kernel.
The compilation runs only if the kernel is not cached. Note that the
kernels with different argument dtypes or dimensions are not
compatible. It means that single ElementwiseKernel object may be
compiled into multiple kernel binaries.
Args:
args: Arguments of the kernel.
size (int): Range size of the indices. By default, the range size
is automatically determined from the result of broadcasting.
This parameter must be specified if and only if all ndarrays
are `raw` and the range size cannot be determined
automatically.
block_size (int): Number of threads per block. By default, the
value is set to 128.
Returns:
If ``no_return`` has not set, arrays are returned according to the
``out_params`` argument of the ``__init__`` method.
If ``no_return`` has set, ``None`` is returned.
"""
cdef function.Function kern
cdef Py_ssize_t size, i
cdef list in_args, out_args
cdef tuple in_types, out_types
cdef shape_t shape
size = kwargs.pop('size', -1)
stream = kwargs.pop('stream', None)
block_size = kwargs.pop('block_size', 128)
if len(kwargs):
raise TypeError('Wrong arguments %s' % kwargs)
if block_size <= 0:
raise ValueError('block_size must be greater than zero')
n_args = len(args)
if n_args != self.nin and n_args != self.nargs:
raise TypeError(
'Wrong number of arguments for {!r}. '
'It must be either {} or {} (with outputs), '
'but given {}.'.format(
self.name, self.nin, self.nargs, n_args))
for arg in args:
if hasattr(arg, '__cupy_override_elementwise_kernel__'):
return arg.__cupy_override_elementwise_kernel__(
self, *args, **kwargs)
dev_id = device.get_device_id()
arg_list = _preprocess_args(dev_id, args, True)
out_args = arg_list[self.nin:]
# _broadcast updates shape
in_args = _broadcast(
arg_list, self.params, size != -1, shape)[:self.nin]
in_ndarray_types = []
for a in in_args:
if isinstance(a, _ndarray_base):
t = a.dtype.type
elif isinstance(a, texture.TextureObject):
t = 'cudaTextureObject_t'
else:
t = None
in_ndarray_types.append(t)
in_ndarray_types = tuple(in_ndarray_types)
out_ndarray_types = tuple([a.dtype.type for a in out_args])
in_types, out_types, type_map = self._decide_params_type(
in_ndarray_types, out_ndarray_types)
is_size_specified = False
if size != -1:
shape.assign(1, size)
is_size_specified = True
out_args = _get_out_args_with_params(
out_args, out_types, shape, self.out_params, is_size_specified)
if self.no_return:
ret = None
elif not self.return_tuple and self.nout == 1:
ret = out_args[0]
else:
ret = tuple(out_args)
if _contains_zero(shape):
return ret
for i, x in enumerate(in_args):
if type(x) is _scalar.CScalar:
(<_scalar.CScalar>x).apply_dtype(in_types[i])
inout_args = in_args + out_args
if self.reduce_dims:
shape = _reduce_dims(inout_args, self.params, shape)
indexer = _carray._indexer_init(shape)
inout_args.append(indexer)
arginfos = _get_arginfos(inout_args)
kern = self._get_elementwise_kernel(dev_id, arginfos, type_map)
kern.linear_launch(indexer.size, inout_args, shared_mem=0,
block_max_size=block_size, stream=stream)
return ret
cpdef tuple _decide_params_type(
self, tuple in_args_dtype, tuple out_args_dtype):
key = (in_args_dtype, out_args_dtype)
ret = self._params_type_memo.get(key, None)
if ret is not None:
return ret
ret = _decide_params_type_core(
self.in_params, self.out_params, in_args_dtype, out_args_dtype)
self._params_type_memo[key] = ret
return ret
cpdef function.Function _get_elementwise_kernel(
self, int dev_id, tuple arginfos, _TypeMap type_map):
key = (
dev_id,
arginfos,
type_map)
kern = self._elementwise_kernel_memo.get(key, None)
if kern is not None:
return kern
kern = _get_elementwise_kernel(
arginfos, type_map, self.params, self.operation,
self.name, self.preamble, **self.kwargs)
# Store the compiled kernel in the cache.
# Potentially overwrite a duplicate cache entry because
# _get_elementwise_kernel() may include IO wait.
in_types = []
for x in arginfos:
if x.type is cupy.ndarray:
in_types.append(cupy.dtype(x.dtype).char)
in_types = tuple(in_types)
if in_types not in self._cached_codes:
code = _get_elementwise_kernel_code(
arginfos, type_map, self.params, self.operation,
self.name, self.preamble, **self.kwargs)
self._cached_codes[in_types] = code
self._elementwise_kernel_memo[key] = kern
return kern
@property
def cached_codes(self):
"""Returns a dict that has input types as keys and codes values.
This proprety method is for debugging purpose.
The return value is not guaranteed to keep backward compatibility.
"""
if len(self._cached_codes) == 0:
warnings.warn(
'No codes are cached because compilation is deferred until '
'the first function call.')
return dict([(k, v) for k, v in self._cached_codes.items()])
@property
def cached_code(self):
"""Returns `next(iter(self.cached_codes.values()))`.
This proprety method is for debugging purpose.
The return value is not guaranteed to keep backward compatibility.
"""
codes = self._cached_codes
if len(codes) > 1:
warnings.warn(
'The input types of the kernel could not be inferred. '
'Please use `.cached_codes` instead.')
return next(iter(codes.values()))
cdef str fix_cast_expr(src_type, dst_type, str expr):
src_kind = get_dtype(src_type).kind
dst_kind = get_dtype(dst_type).kind
if src_kind == dst_kind:
return expr
if src_kind == 'b':
# HIP has an issue with bool conversions detailed below
if runtime._is_hip_environment: