/
dtypes.py
1199 lines (1014 loc) · 36.8 KB
/
dtypes.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
# Copyright 2019-2020 ETH Zurich and the DaCe authors. All rights reserved.
""" A module that contains various DaCe type definitions. """
from __future__ import print_function
import ctypes
import aenum
import inspect
import numpy
import re
from functools import wraps
from typing import Any
from dace.config import Config
from dace.registry import extensible_enum
@extensible_enum
class StorageType(aenum.AutoNumberEnum):
""" Available data storage types in the SDFG. """
Default = () #: Scope-default storage location
Register = () #: Local data on registers, stack, or equivalent memory
CPU_Pinned = () #: Host memory that can be DMA-accessed from accelerators
CPU_Heap = () #: Host memory allocated on heap
CPU_ThreadLocal = () #: Thread-local host memory
GPU_Global = () #: Global memory
GPU_Shared = () #: Shared memory
FPGA_Global = () #: Off-chip global memory (DRAM)
FPGA_Local = () #: On-chip memory (bulk storage)
FPGA_Registers = () #: On-chip memory (fully partitioned registers)
FPGA_ShiftRegister = () #: Only accessible at constant indices
@extensible_enum
class ScheduleType(aenum.AutoNumberEnum):
""" Available map schedule types in the SDFG. """
# TODO: Address different targets w.r.t. sequential
# TODO: Add per-type properties for scope nodes. Consider TargetType enum
# and a MapScheduler class
Default = () #: Scope-default parallel schedule
Sequential = () #: Sequential code (single-thread)
MPI = () #: MPI processes
CPU_Multicore = () #: OpenMP
#: Default scope schedule for GPU code. Specializes to schedule GPU_Device and GPU_Global during inference.
GPU_Default = ()
GPU_Device = () #: Kernel
GPU_ThreadBlock = () #: Thread-block code
GPU_ThreadBlock_Dynamic = () #: Allows rescheduling work within a block
GPU_Persistent = ()
FPGA_Device = ()
# A subset of GPU schedule types
GPU_SCHEDULES = [
ScheduleType.GPU_Device,
ScheduleType.GPU_ThreadBlock,
ScheduleType.GPU_ThreadBlock_Dynamic,
ScheduleType.GPU_Persistent,
]
class ReductionType(aenum.AutoNumberEnum):
""" Reduction types natively supported by the SDFG compiler. """
Custom = () #: Defined by an arbitrary lambda function
Min = () #: Minimum value
Max = () #: Maximum value
Sum = () #: Sum
Product = () #: Product
Logical_And = () #: Logical AND (&&)
Bitwise_And = () #: Bitwise AND (&)
Logical_Or = () #: Logical OR (||)
Bitwise_Or = () #: Bitwise OR (|)
Logical_Xor = () #: Logical XOR (!=)
Bitwise_Xor = () #: Bitwise XOR (^)
Min_Location = () #: Minimum value and its location
Max_Location = () #: Maximum value and its location
Exchange = () #: Set new value, return old value
# Only supported in OpenMP
Sub = () #: Subtraction (only supported in OpenMP)
Div = () #: Division (only supported in OpenMP)
@extensible_enum
class AllocationLifetime(aenum.AutoNumberEnum):
""" Options for allocation span (when to allocate/deallocate) of data. """
Scope = () #: Allocated/Deallocated on innermost scope start/end
State = () #: Allocated throughout the containing state
SDFG = () #: Allocated throughout the innermost SDFG (possibly nested)
Global = () #: Allocated throughout the entire program (outer SDFG)
Persistent = () #: Allocated throughout multiple invocations (init/exit)
@extensible_enum
class Language(aenum.AutoNumberEnum):
""" Available programming languages for SDFG tasklets. """
Python = ()
CPP = ()
OpenCL = ()
SystemVerilog = ()
class AccessType(aenum.AutoNumberEnum):
""" Types of access to an `AccessNode`. """
ReadOnly = ()
WriteOnly = ()
ReadWrite = ()
@extensible_enum
class InstrumentationType(aenum.AutoNumberEnum):
""" Types of instrumentation providers.
@note: Might be determined automatically in future versions.
"""
No_Instrumentation = ()
Timer = ()
PAPI_Counters = ()
GPU_Events = ()
# Maps from ScheduleType to default StorageType
SCOPEDEFAULT_STORAGE = {
None: StorageType.CPU_Heap,
ScheduleType.Sequential: StorageType.Register,
ScheduleType.MPI: StorageType.CPU_Heap,
ScheduleType.CPU_Multicore: StorageType.Register,
ScheduleType.GPU_Default: StorageType.GPU_Global,
ScheduleType.GPU_Persistent: StorageType.GPU_Global,
ScheduleType.GPU_Device: StorageType.GPU_Shared,
ScheduleType.GPU_ThreadBlock: StorageType.Register,
ScheduleType.GPU_ThreadBlock_Dynamic: StorageType.Register,
ScheduleType.FPGA_Device: StorageType.FPGA_Global,
}
# Maps from ScheduleType to default ScheduleType for sub-scopes
SCOPEDEFAULT_SCHEDULE = {
None: ScheduleType.CPU_Multicore,
ScheduleType.Sequential: ScheduleType.Sequential,
ScheduleType.MPI: ScheduleType.CPU_Multicore,
ScheduleType.CPU_Multicore: ScheduleType.Sequential,
ScheduleType.GPU_Default: ScheduleType.GPU_Device,
ScheduleType.GPU_Persistent: ScheduleType.GPU_Device,
ScheduleType.GPU_Device: ScheduleType.GPU_ThreadBlock,
ScheduleType.GPU_ThreadBlock: ScheduleType.Sequential,
ScheduleType.GPU_ThreadBlock_Dynamic: ScheduleType.Sequential,
ScheduleType.FPGA_Device: ScheduleType.FPGA_Device,
}
# Translation of types to C types
_CTYPES = {
None: "void",
int: "int",
float: "float",
complex: "dace::complex64",
bool: "bool",
numpy.bool: "bool",
numpy.bool_: "bool",
numpy.int8: "char",
numpy.int16: "short",
numpy.int32: "int",
numpy.int64: "long long",
numpy.uint8: "unsigned char",
numpy.uint16: "unsigned short",
numpy.uint32: "unsigned int",
numpy.uint64: "unsigned long long",
numpy.float16: "dace::float16",
numpy.float32: "float",
numpy.float64: "double",
numpy.complex64: "dace::complex64",
numpy.complex128: "dace::complex128",
}
# Translation of types to OpenCL types
_OCL_TYPES = {
None: "void",
int: "int",
float: "float",
bool: "bool",
numpy.bool: "bool",
numpy.bool_: "bool",
numpy.int8: "char",
numpy.int16: "short",
numpy.int32: "int",
numpy.int64: "long long",
numpy.uint8: "unsigned char",
numpy.uint16: "unsigned short",
numpy.uint32: "unsigned int",
numpy.uint64: "unsigned long long",
numpy.float32: "float",
numpy.float64: "double",
numpy.complex64: "complex float",
numpy.complex128: "complex double",
}
# Translation of types to OpenCL vector types
_OCL_VECTOR_TYPES = {
numpy.int8: "char",
numpy.uint8: "uchar",
numpy.int16: "short",
numpy.uint16: "ushort",
numpy.int32: "int",
numpy.uint32: "uint",
numpy.int64: "long",
numpy.uint64: "ulong",
numpy.float16: "half",
numpy.float32: "float",
numpy.float64: "double",
numpy.complex64: "complex float",
numpy.complex128: "complex double",
}
# Translation of types to ctypes types
_FFI_CTYPES = {
None: ctypes.c_void_p,
int: ctypes.c_int,
float: ctypes.c_float,
complex: ctypes.c_uint64,
bool: ctypes.c_bool,
numpy.bool: ctypes.c_bool,
numpy.bool_: ctypes.c_bool,
numpy.int8: ctypes.c_int8,
numpy.int16: ctypes.c_int16,
numpy.int32: ctypes.c_int32,
numpy.int64: ctypes.c_int64,
numpy.uint8: ctypes.c_uint8,
numpy.uint16: ctypes.c_uint16,
numpy.uint32: ctypes.c_uint32,
numpy.uint64: ctypes.c_uint64,
numpy.float16: ctypes.c_uint16,
numpy.float32: ctypes.c_float,
numpy.float64: ctypes.c_double,
numpy.complex64: ctypes.c_uint64,
numpy.complex128: ctypes.c_longdouble,
}
# Number of bytes per data type
_BYTES = {
None: 0,
int: 4,
float: 4,
complex: 8,
bool: 1,
numpy.bool: 1,
numpy.bool_: 1,
numpy.int8: 1,
numpy.int16: 2,
numpy.int32: 4,
numpy.int64: 8,
numpy.uint8: 1,
numpy.uint16: 2,
numpy.uint32: 4,
numpy.uint64: 8,
numpy.float16: 2,
numpy.float32: 4,
numpy.float64: 8,
numpy.complex64: 8,
numpy.complex128: 16,
}
class typeclass(object):
""" An extension of types that enables their use in DaCe.
These types are defined for three reasons:
1. Controlling DaCe types
2. Enabling declaration syntax: `dace.float32[M,N]`
3. Enabling extensions such as `dace.struct` and `dace.vector`
"""
def __init__(self, wrapped_type):
# Convert python basic types
if isinstance(wrapped_type, str):
try:
wrapped_type = getattr(numpy, wrapped_type)
except AttributeError:
raise ValueError("Unknown type: {}".format(wrapped_type))
config_data_types = Config.get('compiler', 'default_data_types')
if wrapped_type is int:
if config_data_types.lower() == 'python':
wrapped_type = numpy.int64
elif config_data_types.lower() == 'c':
wrapped_type = numpy.int32
else:
raise NameError(
"Unknown configuration for default_data_types: {}".format(
config_data_types))
elif wrapped_type is float:
if config_data_types.lower() == 'python':
wrapped_type = numpy.float64
elif config_data_types.lower() == 'c':
wrapped_type = numpy.float32
else:
raise NameError(
"Unknown configuration for default_data_types: {}".format(
config_data_types))
elif wrapped_type is complex:
if config_data_types.lower() == 'python':
wrapped_type = numpy.complex128
elif config_data_types.lower() == 'c':
wrapped_type = numpy.complex64
else:
raise NameError(
"Unknown configuration for default_data_types: {}".format(
config_data_types))
self.type = wrapped_type # Type in Python
self.ctype = _CTYPES[wrapped_type] # Type in C
self.ctype_unaligned = self.ctype # Type in C (without alignment)
self.dtype = self # For compatibility support with numpy
self.bytes = _BYTES[wrapped_type] # Number of bytes for this type
def __hash__(self):
return hash((self.type, self.ctype))
def to_string(self):
""" A Numpy-like string-representation of the underlying data type. """
return self.type.__name__
def as_ctypes(self):
""" Returns the ctypes version of the typeclass. """
return _FFI_CTYPES[self.type]
def as_numpy_dtype(self):
return numpy.dtype(self.type)
def is_complex(self):
if self.type == numpy.complex64 or self.type == numpy.complex128:
return True
return False
def to_json(self):
if self.type is None:
return None
return self.type.__name__
@staticmethod
def from_json(json_obj, context=None):
if json_obj is None:
return typeclass(None)
return json_to_typeclass(json_obj, context)
# Create a new type
def __call__(self, *args, **kwargs):
return self.type(*args, **kwargs)
def __eq__(self, other):
return other is not None and self.ctype == other.ctype
def __ne__(self, other):
return other is not None and self.ctype != other.ctype
def __getitem__(self, s):
""" This is syntactic sugar that allows us to define an array type
with the following syntax: dace.uint32[N,M]
:return: A data.Array data descriptor.
"""
from dace import data
if isinstance(s, list) or isinstance(s, tuple):
return data.Array(self, tuple(s))
return data.Array(self, (s, ))
def __repr__(self):
return self.ctype
@property
def base_type(self):
return self
@property
def veclen(self):
return 1
@property
def ocltype(self):
return _OCL_TYPES[self.type]
def as_arg(self, name):
return self.ctype + ' ' + name
def max_value(dtype: typeclass):
"""Get a max value literal for `dtype`."""
nptype = dtype.as_numpy_dtype()
if nptype == numpy.bool:
return True
elif numpy.issubdtype(nptype, numpy.integer):
return numpy.iinfo(nptype).max
elif numpy.issubdtype(nptype, numpy.floating):
return numpy.finfo(nptype).max
raise TypeError('Unsupported type "%s" for maximum' % dtype)
def min_value(dtype: typeclass):
"""Get a min value literal for `dtype`."""
nptype = dtype.as_numpy_dtype()
if nptype == numpy.bool:
return False
elif numpy.issubdtype(nptype, numpy.integer):
return numpy.iinfo(nptype).min
elif numpy.issubdtype(nptype, numpy.floating):
return numpy.finfo(nptype).min
raise TypeError('Unsupported type "%s" for minimum' % dtype)
def result_type_of(lhs, *rhs):
"""
Returns the largest between two or more types (dace.types.typeclass)
according to C semantics.
"""
if len(rhs) == 0:
rhs = None
elif len(rhs) > 1:
result = lhs
for r in rhs:
result = result_type_of(result, r)
return result
rhs = rhs[0]
# Extract the type if symbolic or data
from dace.data import Data
lhs = lhs.dtype if (type(lhs).__name__ == 'symbol'
or isinstance(lhs, Data)) else lhs
rhs = rhs.dtype if (type(rhs).__name__ == 'symbol'
or isinstance(rhs, Data)) else rhs
if lhs == rhs:
return lhs # Types are the same, return either
if lhs is None or lhs.type is None:
return rhs # Use RHS even if it's None
if rhs is None or rhs.type is None:
return lhs # Use LHS
# Vector types take precedence, largest vector size first
if isinstance(lhs, vector) and not isinstance(rhs, vector):
return lhs
elif not isinstance(lhs, vector) and isinstance(rhs, vector):
return rhs
elif isinstance(lhs, vector) and isinstance(rhs, vector):
if lhs.veclen == rhs.veclen:
return vector(result_type_of(lhs.vtype, rhs.vtype), lhs.veclen)
return lhs if lhs.veclen > rhs.veclen else rhs
# Extract the numpy type so we can call issubdtype on them
lhs_ = lhs.type if isinstance(lhs, typeclass) else lhs
rhs_ = rhs.type if isinstance(rhs, typeclass) else rhs
# Extract data sizes (seems the type itself doesn't expose this)
size_lhs = lhs_(0).itemsize
size_rhs = rhs_(0).itemsize
# Both are integers
if numpy.issubdtype(lhs_, numpy.integer) and numpy.issubdtype(
rhs_, numpy.integer):
# If one byte width is larger, use it
if size_lhs > size_rhs:
return lhs
elif size_lhs < size_rhs:
return rhs
# Sizes are the same
if numpy.issubdtype(lhs_, numpy.unsignedinteger):
# No matter if right is signed or not, we must return unsigned
return lhs
else:
# Left is signed, so either right is unsigned and we return that,
# or both are signed
return rhs
# At least one side is a floating point number
if numpy.issubdtype(lhs_, numpy.integer):
return rhs
if numpy.issubdtype(rhs_, numpy.integer):
return lhs
# Both sides are floating point numbers
if size_lhs > size_rhs:
return lhs
return rhs # RHS is bigger
class pointer(typeclass):
""" A data type for a pointer to an existing typeclass.
Example use:
`dace.pointer(dace.struct(x=dace.float32, y=dace.float32))`. """
def __init__(self, wrapped_typeclass):
self._typeclass = wrapped_typeclass
self.type = wrapped_typeclass.type
self.bytes = int64.bytes
self.ctype = wrapped_typeclass.ctype + "*"
self.ctype_unaligned = wrapped_typeclass.ctype_unaligned + "*"
self.dtype = self
def to_json(self):
return {'type': 'pointer', 'dtype': self._typeclass.to_json()}
@staticmethod
def from_json(json_obj, context=None):
if json_obj['type'] != 'pointer':
raise TypeError("Invalid type for pointer")
return pointer(json_to_typeclass(json_obj['dtype'], context))
def as_ctypes(self):
""" Returns the ctypes version of the typeclass. """
return ctypes.POINTER(_FFI_CTYPES[self.type])
def as_numpy_dtype(self):
return numpy.dtype(self.as_ctypes())
@property
def base_type(self):
return self._typeclass
@property
def ocltype(self):
return f"{self.base_type.ocltype}*"
class vector(typeclass):
"""
A data type for a vector-type of an existing typeclass.
Example use: `dace.vector(dace.float32, 4)` becomes float4.
"""
def __init__(self, dtype: typeclass, vector_length: int):
self.vtype = dtype
self.type = dtype.type
self._veclen = vector_length
self.bytes = dtype.bytes * vector_length
self.dtype = self
def to_json(self):
return {
'type': 'vector',
'dtype': self.vtype.to_json(),
'elements': str(self.veclen)
}
@staticmethod
def from_json(json_obj, context=None):
from dace.symbolic import pystr_to_symbolic
return vector(json_to_typeclass(json_obj['dtype'], context),
pystr_to_symbolic(json_obj['elements']))
@property
def ctype(self):
return "dace::vec<%s, %s>" % (self.vtype.ctype, self.veclen)
@property
def ocltype(self):
if self.veclen > 1:
vectype = _OCL_VECTOR_TYPES[self.type]
return f"{vectype}{self.veclen}"
else:
return self.base_type.ocltype
@property
def ctype_unaligned(self):
return self.ctype
def as_ctypes(self):
""" Returns the ctypes version of the typeclass. """
return _FFI_CTYPES[self.type] * self.veclen
def as_numpy_dtype(self):
return numpy.dtype(self.as_ctypes())
@property
def base_type(self):
return self.vtype
@property
def veclen(self):
return self._veclen
@veclen.setter
def veclen(self, val):
self._veclen = val
class struct(typeclass):
""" A data type for a struct of existing typeclasses.
Example use: `dace.struct(a=dace.int32, b=dace.float64)`.
"""
def __init__(self, name, **fields_and_types):
# self._data = fields_and_types
self.type = ctypes.Structure
self.name = name
# TODO: Assuming no alignment! Get from ctypes
# self.bytes = sum(t.bytes for t in fields_and_types.values())
self.ctype = name
self.ctype_unaligned = name
self.dtype = self
self._parse_field_and_types(**fields_and_types)
@property
def fields(self):
return self._data
def to_json(self):
return {
'type': 'struct',
'name': self.name,
'data': {k: v.to_json()
for k, v in self._data.items()},
'length': {k: v
for k, v in self._length.items()},
'bytes': self.bytes
}
@staticmethod
def from_json(json_obj, context=None):
if json_obj['type'] != "struct":
raise TypeError("Invalid type for struct")
import dace.serialize # Avoid import loop
ret = struct(json_obj['name'])
ret._data = {
k: json_to_typeclass(v, context)
for k, v in json_obj['data'].items()
}
ret._length = {k: v for k, v in json_obj['length'].items()}
ret.bytes = json_obj['bytes']
return ret
def _parse_field_and_types(self, **fields_and_types):
self._data = dict()
self._length = dict()
self.bytes = 0
for k, v in fields_and_types.items():
if isinstance(v, tuple):
t, l = v
if not isinstance(t, pointer):
raise TypeError("Only pointer types may have a length.")
if l not in fields_and_types.keys():
raise ValueError(
"Length {} not a field of struct {}".format(
l, self.name))
self._data[k] = t
self._length[k] = l
self.bytes += t.bytes
else:
if isinstance(v, pointer):
raise TypeError("Pointer types must have a length.")
self._data[k] = v
self.bytes += v.bytes
def as_ctypes(self):
""" Returns the ctypes version of the typeclass. """
# Populate the ctype fields for the struct class.
fields = []
for k, v in self._data.items():
if isinstance(v, pointer):
fields.append(
(k,
ctypes.c_void_p)) # ctypes.POINTER(_FFI_CTYPES[v.type])))
else:
fields.append((k, _FFI_CTYPES[v.type]))
fields = sorted(fields, key=lambda f: f[0])
# Create new struct class.
struct_class = type("NewStructClass", (ctypes.Structure, ),
{"_fields_": fields})
return struct_class
def as_numpy_dtype(self):
return numpy.dtype(self.as_ctypes())
def emit_definition(self):
return """struct {name} {{
{typ}
}};""".format(
name=self.name,
typ='\n'.join([
" %s %s;" % (t.ctype, tname)
for tname, t in sorted(self._data.items())
]),
)
####### Utility function ##############
def ptrtonumpy(ptr, inner_ctype, shape):
import ctypes
import numpy as np
return np.ctypeslib.as_array(
ctypes.cast(ctypes.c_void_p(ptr), ctypes.POINTER(inner_ctype)), shape)
def _atomic_counter_generator():
ctr = 0
while True:
ctr += 1
yield ctr
class callback(typeclass):
""" Looks like dace.callback([None, <some_native_type>], *types)"""
def __init__(self, return_type, *variadic_args):
self.uid = next(_atomic_counter_generator())
from dace import data
if isinstance(return_type, data.Array):
raise TypeError("Callbacks that return arrays are "
"not supported as per SDFG semantics")
self.dtype = self
self.return_type = return_type
self.input_types = []
for arg in variadic_args:
if isinstance(arg, typeclass):
pass
elif isinstance(arg, data.Data):
pass
elif isinstance(arg, str):
arg = json_to_typeclass(arg)
else:
raise TypeError("Cannot resolve type from: {}".format(arg))
self.input_types.append(arg)
self.bytes = int64.bytes
self.type = self
self.ctype = self
def as_ctypes(self):
""" Returns the ctypes version of the typeclass. """
from dace import data
return_ctype = (self.return_type.as_ctypes()
if self.return_type is not None else None)
input_ctypes = []
for some_arg in self.input_types:
if isinstance(some_arg, data.Array):
input_ctypes.append(ctypes.c_void_p)
else:
input_ctypes.append(
some_arg.as_ctypes() if some_arg is not None else None)
if input_ctypes == [None]:
input_ctypes = []
cf_object = ctypes.CFUNCTYPE(return_ctype, *input_ctypes)
return cf_object
def as_numpy_dtype(self):
return numpy.dtype(self.as_ctypes())
def as_arg(self, name):
from dace import data
return_type_cstring = (self.return_type.ctype
if self.return_type is not None else "void")
input_type_cstring = []
for arg in self.input_types:
if isinstance(arg, data.Array):
# const hack needed to prevent error in casting const int* to int*
input_type_cstring.append(arg.dtype.ctype + " const *")
else:
input_type_cstring.append(arg.ctype if arg is not None else "")
cstring = return_type_cstring + " " + "(*" + name + ")("
for index, inp_arg in enumerate(input_type_cstring):
if index > 0:
cstring = cstring + ","
cstring = cstring + inp_arg
cstring = cstring + ")"
return cstring
def get_trampoline(self, pyfunc, other_arguments):
from functools import partial
from dace import data, symbolic
arraypos = []
types_and_sizes = []
for index, arg in enumerate(self.input_types):
if isinstance(arg, data.Array):
arraypos.append(index)
types_and_sizes.append((arg.dtype.as_ctypes(), arg.shape))
if len(arraypos) == 0:
return pyfunc
def trampoline(orig_function, indices, data_types_and_sizes,
*other_inputs):
list_of_other_inputs = list(other_inputs)
for i in indices:
data_type, size = data_types_and_sizes[i]
non_symbolic_sizes = []
for s in size:
if isinstance(s, symbolic.symbol):
non_symbolic_sizes.append(other_arguments[str(s)])
else:
non_symbolic_sizes.append(s)
list_of_other_inputs[i] = ptrtonumpy(other_inputs[i], data_type,
non_symbolic_sizes)
return orig_function(*list_of_other_inputs)
return partial(trampoline, pyfunc, arraypos, types_and_sizes)
def __hash__(self):
return hash((self.uid, self.return_type, *self.input_types))
def to_json(self):
return {
'type': 'callback',
'arguments': [i.to_json() for i in self.input_types],
'returntype':
self.return_type.to_json() if self.return_type else None
}
@staticmethod
def from_json(json_obj, context=None):
if json_obj['type'] != "callback":
raise TypeError("Invalid type for callback")
rettype = json_obj['returntype']
import dace.serialize # Avoid import loop
return callback(
json_to_typeclass(rettype) if rettype else None,
*(dace.serialize.from_json(arg, context)
for arg in json_obj['arguments']))
def __str__(self):
return "dace.callback"
def __repr__(self):
return "dace.callback"
def __eq__(self, other):
if not isinstance(other, callback):
return False
return self.uid == other.uid
def __ne__(self, other):
return not self.__eq__(other)
# Helper function to determine whether a global variable is a constant
_CONSTANT_TYPES = [
type(None),
int,
float,
complex,
str,
bool,
numpy.bool_,
numpy.intc,
numpy.intp,
numpy.int8,
numpy.int16,
numpy.int32,
numpy.int64,
numpy.uint8,
numpy.uint16,
numpy.uint32,
numpy.uint64,
numpy.float16,
numpy.float32,
numpy.float64,
numpy.complex64,
numpy.complex128,
typeclass, # , type
]
def isconstant(var):
""" Returns True if a variable is designated a constant (i.e., that can be
directly generated in code).
"""
return type(var) in _CONSTANT_TYPES
bool = typeclass(numpy.bool)
bool_ = typeclass(numpy.bool_)
int8 = typeclass(numpy.int8)
int16 = typeclass(numpy.int16)
int32 = typeclass(numpy.int32)
int64 = typeclass(numpy.int64)
uint8 = typeclass(numpy.uint8)
uint16 = typeclass(numpy.uint16)
uint32 = typeclass(numpy.uint32)
uint64 = typeclass(numpy.uint64)
float16 = typeclass(numpy.float16)
float32 = typeclass(numpy.float32)
float64 = typeclass(numpy.float64)
complex64 = typeclass(numpy.complex64)
complex128 = typeclass(numpy.complex128)
DTYPE_TO_TYPECLASS = {
int: typeclass(int),
float: typeclass(float),
complex: typeclass(complex),
numpy.bool: bool,
numpy.bool_: bool_,
numpy.int8: int8,
numpy.int16: int16,
numpy.int32: int32,
numpy.int64: int64,
numpy.uint8: uint8,
numpy.uint16: uint16,
numpy.uint32: uint32,
numpy.uint64: uint64,
numpy.float16: float16,
numpy.float32: float32,
numpy.float64: float64,
numpy.complex64: complex64,
numpy.complex128: complex128,
# FIXME
numpy.longlong: int64,
numpy.ulonglong: uint64
}
TYPECLASS_TO_STRING = {
bool: "dace::bool",
bool_: "dace::bool_",
uint8: "dace::uint8",
uint16: "dace::uint16",
uint32: "dace::uint32",
uint64: "dace::uint64",
int8: "dace::int8",
int16: "dace::int16",
int32: "dace::int32",
int64: "dace::int64",
float16: "dace::float16",
float32: "dace::float32",
float64: "dace::float64",
complex64: "dace::complex64",
complex128: "dace::complex128"
}
TYPECLASS_STRINGS = [
"int",
"float",
"complex",
"bool",
"bool_",
"int8",
"int16",
"int32",
"int64",
"uint8",
"uint16",
"uint32",
"uint64",
"float16",
"float32",
"float64",
"complex64",
"complex128"
]
INTEGER_TYPES = [
bool,
bool_,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64
]
#######################################################
# Allowed types
# Lists allowed modules and maps them to C++ namespaces for code generation
_ALLOWED_MODULES = {
"builtins": "",
"dace": "dace::",
"math": "dace::math::",
"cmath": "dace::cmath::",
}
# Lists allowed modules and maps them to OpenCL
_OPENCL_ALLOWED_MODULES = {"builtins": "", "dace": "", "math": ""}
def ismodule(var):
""" Returns True if a given object is a module. """
return inspect.ismodule(var)
def ismodule(var):
""" Returns True if a given object is a module. """
return inspect.ismodule(var)
def ismoduleallowed(var):
""" Helper function to determine the source module of an object, and
whether it is allowed in DaCe programs. """
mod = inspect.getmodule(var)
try:
for m in _ALLOWED_MODULES:
if mod.__name__ == m or mod.__name__.startswith(m + "."):
return True
except AttributeError:
return False