-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathviews.py
More file actions
1351 lines (1106 loc) · 43.2 KB
/
views.py
File metadata and controls
1351 lines (1106 loc) · 43.2 KB
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
from __future__ import annotations
import ctypes
import importlib
import math
from enum import Enum
import os
import sys
from types import ModuleType
from typing import Dict, Generic, Iterator, List, Optional, Tuple, TypeVar, Union
import numpy as np
import pykokkos as pk
from pykokkos.bindings import kokkos
import pykokkos.kokkos_manager as km
from pykokkos.runtime import runtime_singleton
from .data_types import (
DataType,
DataTypeClass,
real,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
double,
float32,
float64,
complex64,
complex128,
)
from .data_types import float as pk_float
from .layout import get_default_layout, Layout
from .memory_space import get_default_memory_space, MemorySpace
from .hierarchical import TeamMember
ARRAY_REQ_ATTR = ["dtype", "data", "shape", "flags"]
class Trait(Enum):
Atomic = kokkos.Atomic
TraitDefault = None
RandomAccess = kokkos.RandomAccess
Restrict = kokkos.Restrict
Unmanaged = kokkos.Unmanaged
class ViewTypeInfo:
"""
Contains type information for a view that is used by a functor
"""
def __init__(
self,
*,
space: Optional[MemorySpace] = None,
layout: Optional[Layout] = None,
trait: Optional[Trait] = None,
):
"""
ViewTypeInfo constructor
:param space: the memory space of the view
:param layout: the layout of the view
:param trait: the memory trait of the view
"""
self.space: Optional[MemorySpace] = space
self.layout: Optional[Layout] = layout
self.trait: Optional[Trait] = trait
class ViewType:
"""
Base class of all view types. Implements methods needed for container objects and some Kokkos specific methods.
"""
data: np.ndarray
shape: Tuple[int]
dtype: DataType
space: MemorySpace
layout: Layout
trait: Trait
size: int
def rank(self) -> int:
"""
The number of dimensions
:returns: an int representing the number of dimensions
"""
return len(self.shape)
def extent(self, dimension: int) -> int:
"""
The length of a specific dimension
:param dimension: the dimension for which the length is needed
:returns: an int representing the length of the specified dimension
"""
if dimension >= self.rank() and not (dimension == 0 and self.shape == ()):
raise ValueError('"dimension" must be less than the view\'s rank')
if self.shape == ():
return 0
return self.shape[dimension]
def fill(self, value: Union[int, float, complex, complex64, complex128]) -> None:
"""
Sets all elements to a scalar value
:param value: the scalar value
"""
if isinstance(value, (complex, complex64, complex128)):
value = (
np.complex64(value.real, value.imag)
if self.dtype is complex64
else np.complex128(value.real, value.imag)
)
if self.trait is Trait.Unmanaged:
self.xp_array.fill(value)
else:
self.data.fill(value)
def __getitem__(
self, key: Union[int, TeamMember, slice, Tuple]
) -> Union[int, float, Subview]:
"""
Overloads the indexing operator accessing the View
:param key: the specified index. Can be an int, slice, or a Tuple of ints and slices
:returns: a primitive type value if key is an int, a Subview otherwise
"""
if "PK_FUSION" in os.environ:
runtime_singleton.runtime.flush_data(self)
if self.shape == () and key == 0:
return self.data
if isinstance(key, int) or isinstance(key, TeamMember):
if self.trait is Trait.Unmanaged:
return_val = self.xp_array[key]
else:
return_val = self.data[key]
if self.dtype is complex64:
return_val = complex64(return_val.real, return_val.imag)
elif self.dtype is complex128:
return_val = complex128(return_val.real, return_val.imag)
return return_val
length: int = 1 if isinstance(key, slice) else len(key)
if length != self.rank():
raise ValueError("Please include slices for all dimensions")
subview = Subview(self, key)
return subview
def __setitem__(
self,
key: Union[int, TeamMember],
value: Union[int, float, complex, complex64, complex128],
) -> None:
"""
Overloads the indexing operator setting an item in the View.
:param key: the specified index. Can be an int or TeamMember.
:param value: the new value at the index.
"""
if "PK_FUSION" in os.environ:
runtime_singleton.runtime.flush_data(self)
if isinstance(value, (complex, complex64, complex128)):
value = (
np.complex64(value.real, value.imag)
if self.dtype is complex64
else np.complex128(value.real, value.imag)
)
if self.trait is Trait.Unmanaged:
self.xp_array[key] = value
else:
self.data[key] = value
def __bool__(self):
# TODO: more complete implementation
if self.shape == (1,) or self.shape == ():
return bool(self.data)
def __len__(self) -> int:
"""
Implements the len() function
:returns: the length of the first dimension
"""
# NOTE: careful with 0-D treatments and __bool__
# related handling; you can have shape () and
# still be True for example...
if len(self.shape) == 0:
if self.data != 0:
return 1
else:
return 0
return self.shape[0]
def __iter__(self) -> Iterator:
"""
Implements iteration for Subview
:returns: an iterator over the data
"""
if "PK_FUSION" in os.environ:
runtime_singleton.runtime.flush_data(self)
if self.data.ndim > 0:
if self.trait is Trait.Unmanaged:
return (n for n in self.xp_array)
return (n for n in self.data)
else:
# 0-D case returns empty generator
return zip()
def __str__(self) -> str:
"""
Implements the str() function
:returns: the string representation of the data
"""
if "PK_FUSION" in os.environ:
runtime_singleton.runtime.flush_data(self)
if self.trait is Trait.Unmanaged:
return str(self.xp_array)
return str(self.data)
def __deepcopy__(self, memo):
"""
Implements the deepcopy() function as a shallow copy
"""
return self
def _scalarfunc(self, func):
if "PK_FUSION" in os.environ:
runtime_singleton.runtime.flush_data(self)
# based on approach used in
# numpy/lib/user_array.py for
# handling scalar conversions
if self.ndim == 0 or (self.ndim == 1 and self.size == 1):
val = self[0]
# Handle case where val might be a numpy/cupy array (0-D array)
if hasattr(val, "item"):
return func(val.item())
return func(val)
else:
raise TypeError(
"only single element arrays can be converted to Python scalars."
)
def __float__(self):
return self._scalarfunc(float)
def __int__(self):
return self._scalarfunc(int)
class View(ViewType):
def __init__(
self,
shape: Union[List[int], Tuple[int]],
dtype: Union[DataTypeClass, type] = real,
space: MemorySpace = MemorySpace.MemorySpaceDefault,
layout: Layout = Layout.LayoutDefault,
trait: Trait = Trait.TraitDefault,
array: Optional[np.ndarray] = None,
cp_array=None,
):
"""
View constructor.
:param shape: the shape of the view as a list or tuple of integers
:param dtype: the data type of the view, either a pykokkos DataType or "int" or "float".
:param space: the memory space of the view. Will be set to the execution space of the view by default.
:param layout: the layout of the view in memory.
:param trait: the memory trait of the view
:param array: the numpy array if trait is Unmanaged
:param cp_array: the cupy array if trait is Unmanaged
"""
self._init_view(shape, dtype, space, layout, trait, array, cp_array)
try:
from pykokkos import _view_registry
_view_registry.add(self)
except (ImportError, AttributeError):
pass
def resize(self, dimension: int, size: int) -> None:
"""
Resizes a dimension of the view
:param dimension: the dimension to be resized
:param size: the new size
"""
if dimension >= self.rank() and not (dimension == 0 and self.shape == ()):
raise ValueError(
f"Cannot resize dimension {dimension} since rank = {self.rank()}"
)
if self.shape != () and self.shape[dimension] == size:
return
old_data: np.ndarray = self.data
shape_list: List[int] = list(self.shape)
if shape_list == []:
shape_list.append(size)
else:
shape_list[dimension] = size
self.shape = tuple(shape_list)
is_cpu: bool = self.space is MemorySpace.HostSpace
kokkos_lib: ModuleType = km.get_kokkos_module(is_cpu)
self.array = kokkos_lib.array(
"",
self.shape,
None,
None,
self.dtype.value,
self.space.value,
self.layout.value,
self.trait.value,
)
self.data = np.array(self.array, copy=False)
smaller: np.ndarray = old_data if old_data.size < self.data.size else self.data
data_slice = tuple([slice(0, i) for i in smaller.shape])
self.data[data_slice] = old_data[data_slice]
def set_precision(self, dtype: Union[DataTypeClass, type]) -> None:
"""
Set the precision of the View, reallocating it
:param dtype: the data type of the view, either a pykokkos DataType or "int" or "float".
"""
old_data: np.ndarray = self.data
self._init_view(self.shape, dtype, self.space, self.layout, self.trait)
np.copyto(self.data, old_data, casting="unsafe")
def _init_view(
self,
shape: Union[List[int], Tuple[int]],
dtype: Union[DataTypeClass, type] = real,
space: MemorySpace = MemorySpace.MemorySpaceDefault,
layout: Layout = Layout.LayoutDefault,
trait: Trait = Trait.TraitDefault,
array: Optional[np.ndarray] = None,
cp_array=None,
) -> None:
"""
Initialize the view
:param shape: the shape of the view as a list or tuple of integers
:param dtype: the data type of the view, either a pykokkos DataType or "int" or "float".
:param space: the memory space of the view. Will be set to the execution space of the view by default.
:param layout: the layout of the view in memory.
:param trait: the memory trait of the view
:param array: the numpy array if trait is Unmanaged
:param cp_array: the cupy array if trait is Unmanaged
"""
self.shape: Tuple[int] = tuple(shape)
self.size: int = math.prod(shape)
self.ndim: int = len(shape)
self.dtype: Optional[DataType] = self._get_type(dtype)
if self.dtype is None:
sys.exit(f"ERROR: Invalid dtype {dtype}")
if space is MemorySpace.MemorySpaceDefault:
space = get_default_memory_space(km.get_default_space())
if layout is Layout.LayoutDefault:
layout = get_default_layout(space)
# only allow CudaSpace/HIPSpace view for cupy arrays
if (
space in {MemorySpace.CudaSpace, MemorySpace.HIPSpace}
) and trait is not trait.Unmanaged:
space = MemorySpace.HostSpace
self.space: MemorySpace = space
self.layout: Layout = layout
self.trait: Trait = trait
is_cpu: bool = self.space is MemorySpace.HostSpace
kokkos_lib: ModuleType = km.get_kokkos_module(is_cpu)
if self.dtype in {DataType.float, pk_float}:
self.dtype = float32
elif self.dtype in {DataType.double, double}:
self.dtype = float64
if trait is trait.Unmanaged:
if array is not None and array.ndim == 0:
# TODO: we don't really support 0-D under the hood--use
# NumPy/CuPy for now...
self.array = array
# For cupy arrays, store reference to xp_array
if cp_array is not None:
self.xp_array = cp_array
else:
self.xp_array = array
else:
if array.dtype == np.bool_:
array = array.astype(np.uint8)
self.array = kokkos_lib.unmanaged_array(
array,
dtype=self.dtype.value,
space=self.space.value,
layout=self.layout.value,
)
# Store a reference here in case the array goes out of
# scope and gets garbage collected, which would
# invalidate the data. Currently, this happens when
# calling asarray()
self.orig_array = array
if cp_array is not None:
self.xp_array = cp_array
else:
self.xp_array = array
else:
if len(self.shape) == 0:
shape = [1]
self.array = kokkos_lib.array(
"",
shape,
None,
None,
self.dtype.value,
space.value,
layout.value,
trait.value,
)
# For 0-D cupy arrays stored in self.array, get numpy version for self.data
if hasattr(self, "array") and hasattr(self.array, "get"):
# It's a cupy array, convert to numpy for self.data
self.data = self.array.get()
else:
self.data = np.array(self.array, copy=False)
def _get_type(self, dtype: Union[DataType, type]) -> Optional[DataType]:
"""
Get the data type from a DataType or a type that is a subclass of
DataTypeClass or a primitive type
:param dtype: the input data type :returns: a DataType Enum
"""
if isinstance(dtype, DataType):
if dtype is DataType.real:
return km.get_default_precision()
return dtype
if issubclass(dtype, DataTypeClass):
if dtype is real:
return DataType[km.get_default_precision().__name__]
if dtype == DataType.int64:
dtype = int64
return dtype
if dtype is int:
return int32
if dtype is float:
return double
return None
def __eq__(self, other):
if isinstance(other, float):
new_other = pk.View((), dtype=pk.double)
new_other[:] = other
elif isinstance(other, bool):
new_other = pk.View((), dtype=pk.bool)
new_other[:] = other
elif isinstance(other, int):
if self.ndim == 0:
ret = pk.View((), dtype=pk.bool)
ret[:] = int(self) == other
return ret
if 0 <= other <= 255:
other_dtype = pk.uint8
elif 0 <= other <= 65535:
other_dtype = pk.uint16
elif 0 <= other <= 4294967295:
other_dtype = pk.uint32
elif 0 <= other <= 18446744073709551615:
other_dtype = pk.uint64
elif -128 <= other <= 127:
other_dtype = pk.int8
elif -32768 <= other <= 32767:
other_dtype = pk.int16
elif -2147483648 <= other <= 2147483647:
other_dtype = pk.int32
elif -9223372036854775808 <= other <= 9223372036854775807:
other_dtype = pk.int64
new_other = pk.View((), dtype=other_dtype)
new_other[:] = other
elif isinstance(other, pk.View):
new_other = other
else:
raise ValueError("unexpected types!")
result_np = np.equal(np.array(self), np.array(new_other))
result = pk.View(result_np.shape, dtype=pk.bool)
result[:] = result_np
return result
def __hash__(self):
try:
hash_value = hash(self.array)
except TypeError:
hash_value = hash(self.array.data.tobytes())
return hash_value
def __index__(self) -> int:
return int(self.data[0])
def __array__(self, dtype=None):
return self.data
def __pos__(self):
return pk.positive(self)
@staticmethod
def _get_dtype_name(type_name: str) -> str:
"""
Get the type name of the Kokkos view object as a string
:param type_name: the string representation of the array type, of the form
'pykokkos.bindings.luzhou.libpykokkos.KokkosView_double_LayoutRight_HostSpace_1'
:returns: the dtype of the Kokkos View
"""
dtype: str = type_name.split(".")[-1].split("_")[1]
return dtype
class Subview(ViewType):
"""
A Subview wraps the "data" member of a View (or Subview) and references a slice of that data.
Subviews are passed to C++ as unmanaged views.
This class contains the Python implementation of a subview. The user is not meant to call
the constructor directly, instead they should slice the original View object.
"""
def __init__(
self, parent_view: Union[Subview, View], data_slice: Union[slice, Tuple]
):
"""
Subview constructor.
:param parent_view: the View or Subview that is meant to be sliced
:param data_slice: the slice of the parent_view
"""
self.parent_view: Union[Subview, View] = parent_view
self.base_view: View = self._get_base_view(parent_view)
self.data: np.ndarray = parent_view.data[data_slice]
self.dtype = parent_view.dtype
if parent_view.trait is Trait.Unmanaged:
self.xp_array = parent_view.xp_array[data_slice]
is_cpu: bool = self.parent_view.space is MemorySpace.HostSpace
kokkos_lib: ModuleType = km.get_kokkos_module(is_cpu)
self.space: MemorySpace = parent_view.space
self.layout: Layout = parent_view.layout
self.trait: Trait = parent_view.trait
if self.data is not None and self.data.ndim == 0:
# TODO: we don't really support 0-D under the hood--use
# NumPy for now...
self.array = self.data
else:
self.array = kokkos_lib.array(
self.data,
dtype=parent_view.dtype.value,
space=parent_view.space.value,
layout=parent_view.layout.value,
trait=kokkos.Unmanaged,
)
self.shape: Tuple[int] = self.data.shape
if self.data.shape == (0,):
self.data = np.array([], dtype=self.data.dtype)
self.shape = ()
self.parent_slice: List[Union[int, slice]]
self.parent_slice = self._create_slice(data_slice)
self.ndim = self.data.ndim
self.size = self.data.size
def _create_slice(self, data_slice: Union[slice, Tuple]) -> List[Union[int, slice]]:
"""
Transforms the slice into a list, removing all None values for start and stop
:returns: a list of integers and slices representing the full slice
"""
parent_slice: List[Union[int, slice]] = []
if isinstance(data_slice, slice):
data_slice = (data_slice,)
for i, s in enumerate(data_slice):
if isinstance(s, slice):
start: int = 0 if s.start is None else s.start
stop: int = self.parent_view.extent(i) if s.stop is None else s.stop
parent_slice.append(slice(start, stop, None))
elif isinstance(s, int):
parent_slice.append(s)
return parent_slice
def _get_base_view(self, parent_view: Union[Subview, View]) -> View:
"""
Gets the base view (first ancestor) of the Subview
:param parent_view: the direct ancestor of the Subview
:returns: the View object representing the base view
"""
base_view: View
if isinstance(parent_view, View):
base_view = parent_view
else:
base_view = parent_view.base_view
return base_view
def __eq__(self, other):
if isinstance(other, float):
new_other = pk.View((), dtype=pk.double)
new_other[:] = other
elif isinstance(other, bool):
new_other = pk.View((), dtype=pk.bool)
new_other[:] = other
elif isinstance(other, int):
if self.ndim == 0:
ret = pk.View((), dtype=pk.bool)
ret[:] = int(self) == other
return ret
if 0 <= other <= 255:
other_dtype = pk.uint8
elif 0 <= other <= 65535:
other_dtype = pk.uint16
elif 0 <= other <= 4294967295:
other_dtype = pk.uint32
elif 0 <= other <= 18446744073709551615:
other_dtype = pk.uint64
elif -128 <= other <= 127:
other_dtype = pk.int8
elif -32768 <= other <= 32767:
other_dtype = pk.int16
elif -2147483648 <= other <= 2147483647:
other_dtype = pk.int32
elif -9223372036854775808 <= other <= 9223372036854775807:
other_dtype = pk.int64
new_other = pk.View((), dtype=other_dtype)
new_other[:] = other
elif isinstance(other, pk.Subview):
new_other = other
else:
raise ValueError("unexpected types!")
result_np = np.equal(np.array(self), np.array(new_other))
result = pk.View(result_np.shape, dtype=pk.bool)
result[:] = result_np
return result
def __add__(self, other):
if isinstance(other, float):
result = self[0] + other
return result
def __mul__(self, other):
if isinstance(other, float):
result = self[0] * other
return result
elif isinstance(other, Subview):
if self.size == 1 and other.size == 1:
result = self[0] * other[0]
return result
def __hash__(self):
hash_value = hash(self.array)
return hash_value
def from_numpy(
array: np.ndarray,
space: Optional[MemorySpace] = None,
layout: Optional[Layout] = None,
cp_array=None,
) -> ViewType:
"""
Create a PyKokkos View from a numpy array
:param array: the numpy array
:param space: an optional argument for memory space (used by from_array)
:param layout: an optional argument for layout (used by from_array)
:param cp_array: the original cupy array (used by from_array)
:returns: a PyKokkos View wrapping the array
"""
dtype: DataTypeClass
np_dtype = array.dtype.type
if np_dtype is np.void and cp_array is not None:
# This means that this is a cupy array passed through
# from_array(). When this happens, if the cupy array was
# originally a complex number dtype, np_dtype will be void. We
# should therefore retreive the data type from cp_array.
np_dtype = cp_array.dtype.type
if np_dtype is np.int8:
dtype = int8
elif np_dtype is np.int16:
dtype = int16
elif np_dtype is np.int32:
dtype = int32
elif np_dtype is np.int64:
dtype = int64
elif np_dtype is np.uint8:
dtype = uint8
elif np_dtype is np.uint16:
dtype = uint16
elif np_dtype is np.uint32:
dtype = uint32
elif np_dtype is np.uint64:
dtype = uint64
elif np_dtype is np.float32:
dtype = DataType.float # PyKokkos float
elif np_dtype is np.float64:
dtype = float64
elif np_dtype is np.bool_:
dtype = uint8
elif np_dtype is np.complex64:
dtype = complex64
elif np_dtype is np.complex128:
dtype = complex128
else:
raise RuntimeError(f"ERROR: unsupported numpy datatype {np_dtype}")
if layout is None and array.ndim > 1:
if array.flags["F_CONTIGUOUS"]:
layout = Layout.LayoutLeft
else:
layout = Layout.LayoutRight
if space is None:
space = MemorySpace.MemorySpaceDefault
if layout is None:
layout = Layout.LayoutDefault
# TODO: pykokkos support for 0-D arrays?
# temporary/terrible hack here for array API testing..
if array.ndim == 0:
ret_list = ()
if np_dtype == np.bool_:
# For bool, convert to uint8
if cp_array is not None:
# Get the array module from cp_array's type
array_module = importlib.import_module(
type(cp_array).__module__.split(".")[0]
)
scalar_val = 1 if array == 1 else 0
array = array_module.array(scalar_val, dtype=np.uint8)
else:
scalar_val = 1 if array == 1 else 0
array = np.array(scalar_val, dtype=np.uint8)
else:
# For other dtypes, recreate the array with proper dtype
if cp_array is not None:
# Get the array module from cp_array's type
array_module = importlib.import_module(
type(cp_array).__module__.split(".")[0]
)
scalar_val = array.item()
array = array_module.array(scalar_val, dtype=np_dtype)
else:
array = np.array(array, dtype=np_dtype)
else:
ret_list = list((array.shape))
return View(
ret_list,
dtype,
space=space,
trait=Trait.Unmanaged,
array=array,
layout=layout,
cp_array=cp_array,
)
class ctypes_complex64(ctypes.Structure):
_fields_ = [("real", ctypes.c_float), ("imag", ctypes.c_float)]
class ctypes_complex128(ctypes.Structure):
_fields_ = [("real", ctypes.c_double), ("imag", ctypes.c_double)]
def from_array(array) -> ViewType:
"""
Create a PyKokkos View from a cupy (or other numpy-like) array
:param array: the numpy-like array
"""
# Handle 0-D arrays separately to avoid ctypes issues
if array.ndim == 0:
# For 0-D arrays, use the scalar value directly
scalar_val = array.item()
np_array = np.array(scalar_val, dtype=array.dtype.type)
memory_space: MemorySpace
if km.get_gpu_framework() is pk.Cuda:
memory_space = MemorySpace.CudaSpace
elif km.get_gpu_framework() is pk.HIP:
memory_space = MemorySpace.HIPSpace
else:
memory_space = MemorySpace.HostSpace
return from_numpy(np_array, memory_space, Layout.LayoutDefault, array)
np_dtype = array.dtype.type
if np_dtype is np.int8:
ctype = ctypes.c_int8
if np_dtype is np.int16:
ctype = ctypes.c_int16
elif np_dtype is np.int32:
ctype = ctypes.c_int32
elif np_dtype is np.int64:
ctype = ctypes.c_int64
elif np_dtype is np.uint8:
ctype = ctypes.c_uint8
elif np_dtype is np.uint16:
ctype = ctypes.c_uint16
elif np_dtype is np.uint32:
ctype = ctypes.c_uint32
elif np_dtype is np.uint64:
ctype = ctypes.c_uint64
elif np_dtype is np.float32:
ctype = ctypes.c_float
elif np_dtype is np.float64:
ctype = ctypes.c_double
elif np_dtype is np.bool_:
ctype = ctypes.c_uint8
elif np_dtype is np.complex64:
ctype = ctypes_complex64
elif np_dtype is np.complex128:
ctype = ctypes_complex128
else:
raise RuntimeError(f"ERROR: unsupported numpy datatype {np_dtype}")
# Inspired by
# https://stackoverflow.com/questions/23930671/how-to-create-n-dim-numpy-array-from-a-pointer
ptr = array.data.ptr
ptr = ctypes.cast(ptr, ctypes.POINTER(ctype))
np_array = np.ctypeslib.as_array(ptr, shape=array.shape)
if np_dtype in {np.complex64, np.complex128}:
# This sets the arrays dtype to numpy's complex number types.
# Without this the type would be np.void.
np_array = np_array.view(np_dtype)
# need to select the layout here since the np_array flags do not
# preserve the original flags
layout: Layout
if array.flags["F_CONTIGUOUS"]:
layout = Layout.LayoutLeft
else:
layout = Layout.LayoutRight
memory_space: MemorySpace
if km.get_gpu_framework() is pk.Cuda:
memory_space = MemorySpace.CudaSpace
elif km.get_gpu_framework() is pk.HIP:
memory_space = MemorySpace.HIPSpace
return from_numpy(np_array, memory_space, layout, array)
def is_array(array) -> bool:
"""
Check if an object conforms to enough numpy array standards to be treated as an array
Using the function from_array() as a standard for bare minimum needed to
to convert any array into a numpy array
:param array: the array of unknown type
:returns: a true/false if object is an array-like struct
"""
test_attr = dir(array)
if not set(ARRAY_REQ_ATTR).issubset(set(test_attr)):
return False
for d in ARRAY_REQ_ATTR:
if callable(getattr(array, d, None)):
return False
return True
def array(
array, space: Optional[MemorySpace] = None, layout: Optional[Layout] = None
) -> ViewType:
"""
Create a PyKokkos View from a generic array
:param array: the data (array?) of unknown type
:param space: an optional argument for memory space (used by from_array)
:param layout: an optional argument for layout (used by from_array)
:returns: a PyKokkos View wrapping the array
"""
# if numpy array, use from_numpy()
if isinstance(array, np.ndarray) or np.isscalar(array):
return from_numpy(array, space, layout)
# test if the input array can duck-type to a numpy-like array
# and run from_array to preprocess the array to numpy
if is_array(array):
return from_array(array)
# try converting the input data to numpy and using that route to convert
return from_numpy(np.asarray(array), space, layout)
# asarray is required for comformance with the array API:
# https://data-apis.org/array-api/2021.12/API_specification/creation_functions.html#objects-in-api
def asarray(obj, /, *, dtype=None, device=None, copy=None):
# TODO: proper implementation/design
# for now, let's cheat and use NumPy asarray() followed
# by pykokkos from_numpy()
if not isinstance(obj, list) and obj in {pk.e, pk.pi, pk.inf, pk.nan}:
if dtype is None:
dtype = pk.float64
view = pk.View([1], dtype=dtype)
view[:] = obj
return view
if dtype is not None:
arr = np.asarray(obj, dtype=dtype.np_equiv)
else:
arr = np.asarray(obj)
ret = from_numpy(arr)
return ret
def _get_largest_type(
type_list: List[DataTypeClass], type_info: Callable
) -> DataTypeClass:
largest_type = type_list[0]
for dtype in type_list[1:]: