-
Notifications
You must be signed in to change notification settings - Fork 239
/
array.py
2984 lines (2313 loc) · 95 KB
/
array.py
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
"""CL device arrays."""
# pylint:disable=unexpected-keyword-arg # for @elwise_kernel_runner
__copyright__ = "Copyright (C) 2009 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
from functools import reduce
import numpy as np
import pyopencl.elementwise as elementwise
import pyopencl as cl
from pyopencl.compyte.array import (
as_strided as _as_strided,
f_contiguous_strides as _f_contiguous_strides,
c_contiguous_strides as _c_contiguous_strides,
equal_strides as _equal_strides,
ArrayFlags as _ArrayFlags,
get_common_dtype as _get_common_dtype_base)
from pyopencl.characterize import has_double_support
from pyopencl import cltypes
from numbers import Number
SCALAR_CLASSES = (Number, np.bool_, bool)
_COMMON_DTYPE_CACHE = {}
def _get_common_dtype(obj1, obj2, queue):
if queue is None:
raise ValueError("PyOpenCL array has no queue; call .with_queue() to "
"add one in order to be able to perform operations")
dsupport = has_double_support(queue.device)
cache_key = None
o1_dtype = obj1.dtype
try:
cache_key = (o1_dtype, obj2.dtype, dsupport)
return _COMMON_DTYPE_CACHE[cache_key]
except KeyError:
pass
except AttributeError:
# obj2 doesn't have a dtype
try:
tobj2 = type(obj2)
cache_key = (o1_dtype, tobj2, dsupport)
# Integers are weird, sized, and signed. Don't pretend that 'int'
# is enough information to decide what should happen.
if tobj2 != int:
return _COMMON_DTYPE_CACHE[cache_key]
except KeyError:
pass
result = _get_common_dtype_base(obj1, obj2, dsupport)
# we succeeded in constructing the cache key
if cache_key is not None:
_COMMON_DTYPE_CACHE[cache_key] = result
return result
def _get_truedivide_dtype(obj1, obj2, queue):
# the dtype of the division result obj1 / obj2
allow_double = has_double_support(queue.device)
x1 = obj1 if np.isscalar(obj1) else np.ones(1, obj1.dtype)
x2 = obj2 if np.isscalar(obj2) else np.ones(1, obj2.dtype)
result = (x1/x2).dtype
if not allow_double:
if result == np.float64:
result = np.dtype(np.float32)
elif result == np.complex128:
result = np.dtype(np.complex64)
return result
def _get_broadcasted_binary_op_result(obj1, obj2, cq,
dtype_getter=_get_common_dtype):
if obj1.shape == obj2.shape:
return obj1._new_like_me(dtype_getter(obj1, obj2, cq),
cq)
elif obj1.shape == ():
return obj2._new_like_me(dtype_getter(obj1, obj2, cq),
cq)
elif obj2.shape == ():
return obj1._new_like_me(dtype_getter(obj1, obj2, cq),
cq)
else:
raise NotImplementedError("Broadcasting binary operator with shapes:"
f" {obj1.shape}, {obj2.shape}.")
class InconsistentOpenCLQueueWarning(UserWarning):
pass
class VecLookupWarner:
def __getattr__(self, name):
from warnings import warn
warn("pyopencl.array.vec is deprecated. "
"Please use pyopencl.cltypes for OpenCL vector and scalar types",
DeprecationWarning, 2)
if name == "types":
name = "vec_types"
elif name == "type_to_scalar_and_count":
name = "vec_type_to_scalar_and_count"
return getattr(cltypes, name)
vec = VecLookupWarner()
# {{{ helper functionality
def _splay(device, n, kernel_specific_max_wg_size=None):
max_work_items = _builtin_min(128, device.max_work_group_size)
if kernel_specific_max_wg_size is not None:
from builtins import min
max_work_items = min(max_work_items, kernel_specific_max_wg_size)
min_work_items = _builtin_min(32, max_work_items)
max_groups = device.max_compute_units * 4 * 8
# 4 to overfill the device
# 8 is an Nvidia constant--that's how many
# groups fit onto one compute device
if n < min_work_items:
group_count = 1
work_items_per_group = min_work_items
elif n < (max_groups * min_work_items):
group_count = (n + min_work_items - 1) // min_work_items
work_items_per_group = min_work_items
elif n < (max_groups * max_work_items):
group_count = max_groups
grp = (n + min_work_items - 1) // min_work_items
work_items_per_group = (
(grp + max_groups - 1) // max_groups) * min_work_items
else:
group_count = max_groups
work_items_per_group = max_work_items
#print "n:%d gc:%d wipg:%d" % (n, group_count, work_items_per_group)
return (group_count*work_items_per_group,), (work_items_per_group,)
# deliberately undocumented for now
ARRAY_KERNEL_EXEC_HOOK = None
def elwise_kernel_runner(kernel_getter):
"""Take a kernel getter of the same signature as the kernel
and return a function that invokes that kernel.
Assumes that the zeroth entry in *args* is an :class:`Array`.
"""
def kernel_runner(*args, **kwargs):
repr_ary = args[0]
queue = kwargs.pop("queue", None)
implicit_queue = queue is None
if implicit_queue:
queue = repr_ary.queue
wait_for = kwargs.pop("wait_for", None)
knl = kernel_getter(*args, **kwargs)
gs, ls = repr_ary._get_sizes(queue,
knl.get_work_group_info(
cl.kernel_work_group_info.WORK_GROUP_SIZE,
queue.device))
assert isinstance(repr_ary, Array)
args = args + (repr_ary.size,)
if ARRAY_KERNEL_EXEC_HOOK is not None:
return ARRAY_KERNEL_EXEC_HOOK( # pylint: disable=not-callable
knl, queue, gs, ls, *args, wait_for=wait_for)
else:
return knl(queue, gs, ls, *args, wait_for=wait_for)
try:
from functools import update_wrapper
except ImportError:
return kernel_runner
else:
return update_wrapper(kernel_runner, kernel_getter)
class DefaultAllocator(cl.tools.DeferredAllocator):
def __init__(self, *args, **kwargs):
from warnings import warn
warn("pyopencl.array.DefaultAllocator is deprecated. "
"It will be continue to exist throughout the 2013.x "
"versions of PyOpenCL.",
DeprecationWarning, 2)
cl.tools.DeferredAllocator.__init__(self, *args, **kwargs)
# }}}
# {{{ array class
class ArrayHasOffsetError(ValueError):
"""
.. versionadded:: 2013.1
"""
def __init__(self, val="The operation you are attempting does not yet "
"support arrays that start at an offset from the beginning "
"of their buffer."):
ValueError.__init__(self, val)
class _copy_queue: # noqa
pass
_ARRAY_GET_SIZES_CACHE = {}
_BOOL_DTYPE = np.dtype(np.int8)
class Array:
"""A :class:`numpy.ndarray` work-alike that stores its data and performs
its computations on the compute device. *shape* and *dtype* work exactly
as in :mod:`numpy`. Arithmetic methods in :class:`Array` support the
broadcasting of scalars. (e.g. `array+5`)
*cq* must be a :class:`~pyopencl.CommandQueue` or a :class:`~pyopencl.Context`.
If it is a queue, *cq* specifies the queue in which the array carries out
its computations by default. If a default queue (and thereby overloaded
operators and many other niceties) are not desired, pass a
:class:`~pyopencl.Context`.
*allocator* may be `None` or a callable that, upon being called with an
argument of the number of bytes to be allocated, returns an
:class:`pyopencl.Buffer` object. (A :class:`pyopencl.tools.MemoryPool`
instance is one useful example of an object to pass here.)
.. versionchanged:: 2011.1
Renamed *context* to *cqa*, made it general-purpose.
All arguments beyond *order* should be considered keyword-only.
.. versionchanged:: 2015.2
Renamed *context* to *cq*, disallowed passing allocators through it.
.. attribute :: data
The :class:`pyopencl.MemoryObject` instance created for the memory that
backs this :class:`Array`.
.. versionchanged:: 2013.1
If a non-zero :attr:`offset` has been specified for this array,
this will fail with :exc:`ArrayHasOffsetError`.
.. attribute :: base_data
The :class:`pyopencl.MemoryObject` instance created for the memory that
backs this :class:`Array`. Unlike :attr:`data`, the base address of
*base_data* is allowed to be different from the beginning of the array.
The actual beginning is the base address of *base_data* plus
:attr:`offset` bytes.
Unlike :attr:`data`, retrieving :attr:`base_data` always succeeds.
.. versionadded:: 2013.1
.. attribute :: offset
See :attr:`base_data`.
.. versionadded:: 2013.1
.. attribute :: shape
The tuple of lengths of each dimension in the array.
.. attribute :: ndim
The number of dimensions in :attr:`shape`.
.. attribute :: dtype
The :class:`numpy.dtype` of the items in the GPU array.
.. attribute :: size
The number of meaningful entries in the array. Can also be computed by
multiplying up the numbers in :attr:`shape`.
.. attribute :: nbytes
The size of the entire array in bytes. Computed as :attr:`size` times
``dtype.itemsize``.
.. attribute :: strides
Tuple of bytes to step in each dimension when traversing an array.
.. attribute :: flags
Return an object with attributes `c_contiguous`, `f_contiguous` and
`forc`, which may be used to query contiguity properties in analogy to
:attr:`numpy.ndarray.flags`.
.. rubric:: Methods
.. automethod :: with_queue
.. automethod :: __len__
.. automethod :: reshape
.. automethod :: ravel
.. automethod :: view
.. automethod :: squeeze
.. automethod :: transpose
.. attribute :: T
.. automethod :: set
.. automethod :: get
.. automethod :: get_async
.. automethod :: copy
.. automethod :: __str__
.. automethod :: __repr__
.. automethod :: mul_add
.. automethod :: __add__
.. automethod :: __sub__
.. automethod :: __iadd__
.. automethod :: __isub__
.. automethod :: __pos__
.. automethod :: __neg__
.. automethod :: __mul__
.. automethod :: __div__
.. automethod :: __rdiv__
.. automethod :: __pow__
.. automethod :: __and__
.. automethod :: __xor__
.. automethod :: __or__
.. automethod :: __iand__
.. automethod :: __ixor__
.. automethod :: __ior__
.. automethod :: __abs__
.. automethod :: __invert__
.. UNDOC reverse()
.. automethod :: fill
.. automethod :: astype
.. autoattribute :: real
.. autoattribute :: imag
.. automethod :: conj
.. automethod :: conjugate
.. automethod :: __getitem__
.. automethod :: __setitem__
.. automethod :: setitem
.. automethod :: map_to_host
.. rubric:: Comparisons, conditionals, any, all
.. versionadded:: 2013.2
Boolean arrays are stored as :class:`numpy.int8` because ``bool``
has an unspecified size in the OpenCL spec.
.. automethod :: __bool__
Only works for device scalars. (i.e. "arrays" with ``shape == ()``.)
.. automethod :: any
.. automethod :: all
.. automethod :: __eq__
.. automethod :: __ne__
.. automethod :: __lt__
.. automethod :: __le__
.. automethod :: __gt__
.. automethod :: __ge__
.. rubric:: Event management
If an array is used from within an out-of-order queue, it needs to take
care of its own operation ordering. The facilities in this section make
this possible.
.. versionadded:: 2014.1.1
.. attribute:: events
A list of :class:`pyopencl.Event` instances that the current content of
this array depends on. User code may read, but should never modify this
list directly. To update this list, instead use the following methods.
.. automethod:: add_event
.. automethod:: finish
"""
__array_priority__ = 100
def __init__(self, cq, shape, dtype, order="C", allocator=None,
data=None, offset=0, strides=None, events=None, _flags=None,
_fast=False, _size=None, _context=None, _queue=None):
if _fast:
# Assumptions, should be disabled if not testing
if 0:
assert cq is None
assert isinstance(_context, cl.Context)
assert _queue is None or isinstance(_queue, cl.CommandQueue)
assert isinstance(shape, tuple)
assert isinstance(strides, tuple)
assert isinstance(dtype, np.dtype)
assert _size is not None
size = _size
context = _context
queue = _queue
alloc_nbytes = dtype.itemsize * size
else:
# {{{ backward compatibility
if cq is None:
context = _context
queue = _queue
elif isinstance(cq, cl.CommandQueue):
queue = cq
context = queue.context
elif isinstance(cq, cl.Context):
context = cq
queue = None
else:
raise TypeError("cq may be a queue or a context, not '%s'"
% type(cq))
if allocator is not None:
# "is" would be wrong because two Python objects are allowed
# to hold handles to the same context.
# FIXME It would be nice to check this. But it would require
# changing the allocator interface. Trust the user for now.
#assert allocator.context == context
pass
# Queue-less arrays do have a purpose in life.
# They don't do very much, but at least they don't run kernels
# in random queues.
#
# See also :meth:`with_queue`.
del cq
# }}}
# invariant here: allocator, queue set
# {{{ determine shape, size, and strides
dtype = np.dtype(dtype)
try:
size = 1
for dim in shape:
size *= dim
if dim < 0:
raise ValueError("negative dimensions are not allowed")
except TypeError:
admissible_types = (int, np.integer)
if not isinstance(shape, admissible_types):
raise TypeError("shape must either be iterable or "
"castable to an integer")
size = shape
if shape < 0:
raise ValueError("negative dimensions are not allowed")
shape = (shape,)
if isinstance(size, np.integer):
size = size.item()
if strides is None:
if order in "cC":
# inlined from compyte.array.c_contiguous_strides
if shape:
strides = [dtype.itemsize]
for s in shape[:0:-1]:
strides.append(strides[-1]*s)
strides = tuple(strides[::-1])
else:
strides = ()
elif order in "fF":
strides = _f_contiguous_strides(dtype.itemsize, shape)
else:
raise ValueError("invalid order: %s" % order)
else:
# FIXME: We should possibly perform some plausibility
# checking on 'strides' here.
strides = tuple(strides)
# }}}
assert dtype != object, \
"object arrays on the compute device are not allowed"
assert isinstance(shape, tuple)
assert isinstance(strides, tuple)
alloc_nbytes = dtype.itemsize * size
if alloc_nbytes < 0:
raise ValueError("cannot allocate CL buffer with "
"negative size")
self.queue = queue
self.shape = shape
self.dtype = dtype
self.strides = strides
self.events = [] if events is None else events
self.nbytes = alloc_nbytes
self.size = size
self.allocator = allocator
if data is None:
if alloc_nbytes == 0:
self.base_data = None
else:
if allocator is None:
if context is None and queue is not None:
context = queue.context
self.base_data = cl.Buffer(
context, cl.mem_flags.READ_WRITE, alloc_nbytes)
else:
self.base_data = self.allocator(alloc_nbytes)
else:
self.base_data = data
self.offset = offset
self.context = context
self._flags = _flags
@property
def ndim(self):
return len(self.shape)
@property
def data(self):
if self.offset:
raise ArrayHasOffsetError()
else:
return self.base_data
@property
def flags(self):
f = self._flags
if f is None:
self._flags = f = _ArrayFlags(self)
return f
def _new_with_changes(self, data, offset, shape=None, dtype=None,
strides=None, queue=_copy_queue, allocator=None):
"""
:arg data: *None* means allocate a new array.
"""
fast = True
size = self.size
if shape is None:
shape = self.shape
else:
fast = False
size = None
if dtype is None:
dtype = self.dtype
if strides is None:
strides = self.strides
if queue is _copy_queue:
queue = self.queue
if allocator is None:
allocator = self.allocator
# If we're allocating new data, then there's not likely to be
# a data dependency. Otherwise, the two arrays should probably
# share the same events list.
if data is None:
events = None
else:
events = self.events
return Array(None, shape, dtype, allocator=allocator,
strides=strides, data=data, offset=offset,
events=events,
_fast=fast, _context=self.context, _queue=queue, _size=size)
def with_queue(self, queue):
"""Return a copy of *self* with the default queue set to *queue*.
*None* is allowed as a value for *queue*.
.. versionadded:: 2013.1
"""
if queue is not None:
assert queue.context == self.context
return self._new_with_changes(self.base_data, self.offset,
queue=queue)
def _get_sizes(self, queue, kernel_specific_max_wg_size=None):
if not self.flags.forc:
raise NotImplementedError("cannot operate on non-contiguous array")
cache_key = (queue.device.int_ptr, self.size, kernel_specific_max_wg_size)
try:
return _ARRAY_GET_SIZES_CACHE[cache_key]
except KeyError:
sizes = _splay(queue.device, self.size,
kernel_specific_max_wg_size=kernel_specific_max_wg_size)
_ARRAY_GET_SIZES_CACHE[cache_key] = sizes
return sizes
def set(self, ary, queue=None, async_=None, **kwargs):
"""Transfer the contents the :class:`numpy.ndarray` object *ary*
onto the device.
*ary* must have the same dtype and size (not necessarily shape) as
*self*.
*async_* is a Boolean indicating whether the function is allowed
to return before the transfer completes. To avoid synchronization
bugs, this defaults to *False*.
.. versionchanged:: 2017.2.1
Python 3.7 makes ``async`` a reserved keyword. On older Pythons,
we will continue to accept *async* as a parameter, however this
should be considered deprecated. *async_* is the new, official
spelling.
"""
# {{{ handle 'async' deprecation
async_arg = kwargs.pop("async", None)
if async_arg is not None:
if async_ is not None:
raise TypeError("may not specify both 'async' and 'async_'")
async_ = async_arg
if async_ is None:
async_ = False
if kwargs:
raise TypeError("extra keyword arguments specified: %s"
% ", ".join(kwargs))
# }}}
assert ary.size == self.size
assert ary.dtype == self.dtype
if not ary.flags.forc:
raise RuntimeError("cannot set from non-contiguous array")
if not _equal_strides(ary.strides, self.strides, self.shape):
from warnings import warn
warn("Setting array from one with different "
"strides/storage order. This will cease to work "
"in 2013.x.",
stacklevel=2)
if self.size:
event1 = cl.enqueue_copy(queue or self.queue, self.base_data, ary,
device_offset=self.offset,
is_blocking=not async_)
self.add_event(event1)
def _get(self, queue=None, ary=None, async_=None, **kwargs):
# {{{ handle 'async' deprecation
async_arg = kwargs.pop("async", None)
if async_arg is not None:
if async_ is not None:
raise TypeError("may not specify both 'async' and 'async_'")
async_ = async_arg
if async_ is None:
async_ = False
if kwargs:
raise TypeError("extra keyword arguments specified: %s"
% ", ".join(kwargs))
# }}}
if ary is None:
ary = np.empty(self.shape, self.dtype)
if self.strides != ary.strides:
ary = _as_strided(ary, strides=self.strides)
else:
if ary.size != self.size:
raise TypeError("'ary' has non-matching size")
if ary.dtype != self.dtype:
raise TypeError("'ary' has non-matching type")
if self.shape != ary.shape:
from warnings import warn
warn("get() between arrays of different shape is deprecated "
"and will be removed in PyCUDA 2017.x",
DeprecationWarning, stacklevel=2)
assert self.flags.forc, "Array in get() must be contiguous"
queue = queue or self.queue
if queue is None:
raise ValueError("Cannot copy array to host. "
"Array has no queue. Use "
"'new_array = array.with_queue(queue)' "
"to associate one.")
if self.size:
event1 = cl.enqueue_copy(queue, ary, self.base_data,
device_offset=self.offset,
wait_for=self.events, is_blocking=not async_)
self.add_event(event1)
else:
event1 = None
return ary, event1
def get(self, queue=None, ary=None, async_=None, **kwargs):
"""Transfer the contents of *self* into *ary* or a newly allocated
:class:`numpy.ndarray`. If *ary* is given, it must have the same
shape and dtype.
.. versionchanged:: 2019.1.2
Calling with `async_=True` was deprecated and replaced by
:meth:`get_async`.
The event returned by :meth:`pyopencl.enqueue_copy` is now stored into
:attr:`events` to ensure data is not modified before the copy is
complete.
.. versionchanged:: 2015.2
*ary* with different shape was deprecated.
.. versionchanged:: 2017.2.1
Python 3.7 makes ``async`` a reserved keyword. On older Pythons,
we will continue to accept *async* as a parameter, however this
should be considered deprecated. *async_* is the new, official
spelling.
"""
if async_:
from warnings import warn
warn("calling pyopencl.Array.get with `async_=True` is deprecated. "
"Please use pyopencl.Array.get_async for asynchronous "
"device-to-host transfers",
DeprecationWarning, 2)
ary, event1 = self._get(queue=queue, ary=ary, async_=async_, **kwargs)
return ary
def get_async(self, queue=None, ary=None, **kwargs):
"""
Asynchronous version of :meth:`get` which returns a tuple ``(ary, event)``
containing the host array `ary`
and the :class:`pyopencl.NannyEvent` `event` returned by
:meth:`pyopencl.enqueue_copy`.
.. versionadded:: 2019.1.2
"""
return self._get(queue=queue, ary=ary, async_=True, **kwargs)
def copy(self, queue=_copy_queue):
"""
:arg queue: The :class:`~pyopencl.CommandQueue` for the returned array.
.. versionchanged:: 2017.1.2
Updates the queue of the returned array.
.. versionadded:: 2013.1
"""
if queue is _copy_queue:
queue = self.queue
result = self._new_like_me(queue=queue)
# result.queue won't be the same as queue if queue is None.
# We force them to be the same here.
if result.queue is not queue:
result = result.with_queue(queue)
if not self.flags.forc:
raise RuntimeError("cannot copy non-contiguous array")
if self.nbytes:
event1 = cl.enqueue_copy(queue or self.queue,
result.base_data, self.base_data,
src_offset=self.offset, byte_count=self.nbytes,
wait_for=self.events)
result.add_event(event1)
return result
def __str__(self):
if self.queue is None:
return (f"<cl.Array {self.shape} of {self.dtype} "
"without queue, call with_queue()>")
return str(self.get())
def __repr__(self):
if self.queue is None:
return (f"<cl.Array {self.shape} of {self.dtype} "
f"at {id(self):x} without queue, "
"call with_queue()>")
result = repr(self.get())
if result[:5] == "array":
result = "cl.Array" + result[5:]
else:
from warnings import warn
warn("numpy.ndarray.__repr__ was expected to return a string starting "
f"with 'array'. It didn't: '{result[:10]:r}'")
return result
def safely_stringify_for_pudb(self):
return f"cl.Array {self.dtype} {self.shape}"
def __hash__(self):
raise TypeError("pyopencl arrays are not hashable.")
# {{{ kernel invocation wrappers
@staticmethod
@elwise_kernel_runner
def _axpbyz(out, afac, a, bfac, b, queue=None):
"""Compute ``out = selffac * self + otherfac*other``,
where *other* is an array."""
a_shape = a.shape
b_shape = b.shape
out_shape = out.shape
assert (a_shape == b_shape == out_shape
or (a_shape == () and b_shape == out_shape)
or (b_shape == () and a_shape == out_shape))
return elementwise.get_axpbyz_kernel(
out.context, a.dtype, b.dtype, out.dtype,
x_is_scalar=(a_shape == ()),
y_is_scalar=(b_shape == ()))
@staticmethod
@elwise_kernel_runner
def _axpbz(out, a, x, b, queue=None):
"""Compute ``z = a * x + b``, where *b* is a scalar."""
a = np.array(a)
b = np.array(b)
assert out.shape == x.shape
return elementwise.get_axpbz_kernel(out.context,
a.dtype, x.dtype, b.dtype, out.dtype)
@staticmethod
@elwise_kernel_runner
def _elwise_multiply(out, a, b, queue=None):
a_shape = a.shape
b_shape = b.shape
out_shape = out.shape
assert (a_shape == b_shape == out_shape
or (a_shape == () and b_shape == out_shape)
or (b_shape == () and a_shape == out_shape))
return elementwise.get_multiply_kernel(
a.context, a.dtype, b.dtype, out.dtype,
x_is_scalar=(a_shape == ()),
y_is_scalar=(b_shape == ())
)
@staticmethod
@elwise_kernel_runner
def _rdiv_scalar(out, ary, other, queue=None):
other = np.array(other)
assert out.shape == ary.shape
return elementwise.get_rdivide_elwise_kernel(
out.context, ary.dtype, other.dtype, out.dtype)
@staticmethod
@elwise_kernel_runner
def _div(out, self, other, queue=None):
"""Divides an array by another array."""
assert (self.shape == other.shape == out.shape
or (self.shape == () and other.shape == out.shape)
or (other.shape == () and self.shape == out.shape))
return elementwise.get_divide_kernel(self.context,
self.dtype, other.dtype, out.dtype,
x_is_scalar=(self.shape == ()),
y_is_scalar=(other.shape == ()))
@staticmethod
@elwise_kernel_runner
def _fill(result, scalar):
return elementwise.get_fill_kernel(result.context, result.dtype)
@staticmethod
@elwise_kernel_runner
def _abs(result, arg):
if arg.dtype.kind == "c":
from pyopencl.elementwise import complex_dtype_to_name
fname = "%s_abs" % complex_dtype_to_name(arg.dtype)
elif arg.dtype.kind == "f":
fname = "fabs"
elif arg.dtype.kind in ["u", "i"]:
fname = "abs"
else:
raise TypeError("unsupported dtype in _abs()")
return elementwise.get_unary_func_kernel(
arg.context, fname, arg.dtype, out_dtype=result.dtype)
@staticmethod
@elwise_kernel_runner
def _real(result, arg):
from pyopencl.elementwise import complex_dtype_to_name
fname = "%s_real" % complex_dtype_to_name(arg.dtype)
return elementwise.get_unary_func_kernel(
arg.context, fname, arg.dtype, out_dtype=result.dtype)
@staticmethod
@elwise_kernel_runner
def _imag(result, arg):
from pyopencl.elementwise import complex_dtype_to_name
fname = "%s_imag" % complex_dtype_to_name(arg.dtype)
return elementwise.get_unary_func_kernel(
arg.context, fname, arg.dtype, out_dtype=result.dtype)
@staticmethod
@elwise_kernel_runner
def _conj(result, arg):
from pyopencl.elementwise import complex_dtype_to_name
fname = "%s_conj" % complex_dtype_to_name(arg.dtype)
return elementwise.get_unary_func_kernel(
arg.context, fname, arg.dtype, out_dtype=result.dtype)
@staticmethod
@elwise_kernel_runner
def _pow_scalar(result, ary, exponent):
exponent = np.array(exponent)
return elementwise.get_pow_kernel(result.context,