-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
stubs.py
902 lines (619 loc) · 21.8 KB
/
stubs.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
"""
This scripts specifies all PTX special objects.
"""
import numpy as np
from collections import defaultdict
import functools
import itertools
from inspect import Signature, Parameter
class Stub(object):
'''
A stub object to represent special objects that are meaningless
outside the context of a CUDA kernel
'''
_description_ = '<ptx special value>'
__slots__ = () # don't allocate __dict__
def __new__(cls):
raise NotImplementedError("%s is not instantiable" % cls)
def __repr__(self):
return self._description_
def stub_function(fn):
'''
A stub function to represent special functions that are meaningless
outside the context of a CUDA kernel
'''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
raise NotImplementedError("%s cannot be called from host code" % fn)
return wrapped
#-------------------------------------------------------------------------------
# Thread and grid indices and dimensions
class Dim3(Stub):
'''A triple, (x, y, z)'''
_description_ = '<Dim3>'
@property
def x(self):
pass
@property
def y(self):
pass
@property
def z(self):
pass
class threadIdx(Dim3):
'''
The thread indices in the current thread block. Each index is an integer
spanning the range from 0 inclusive to the corresponding value of the
attribute in :attr:`numba.cuda.blockDim` exclusive.
'''
_description_ = '<threadIdx.{x,y,z}>'
class blockIdx(Dim3):
'''
The block indices in the grid of thread blocks. Each index is an integer
spanning the range from 0 inclusive to the corresponding value of the
attribute in :attr:`numba.cuda.gridDim` exclusive.
'''
_description_ = '<blockIdx.{x,y,z}>'
class blockDim(Dim3):
'''
The shape of a block of threads, as declared when instantiating the kernel.
This value is the same for all threads in a given kernel launch, even if
they belong to different blocks (i.e. each block is "full").
'''
_description_ = '<blockDim.{x,y,z}>'
class gridDim(Dim3):
'''
The shape of the grid of blocks. This value is the same for all threads in
a given kernel launch.
'''
_description_ = '<gridDim.{x,y,z}>'
class warpsize(Stub):
'''
The size of a warp. All architectures implemented to date have a warp size
of 32.
'''
_description_ = '<warpsize>'
class laneid(Stub):
'''
This thread's lane within a warp. Ranges from 0 to
:attr:`numba.cuda.warpsize` - 1.
'''
_description_ = '<laneid>'
#-------------------------------------------------------------------------------
# Array creation
class shared(Stub):
'''
Shared memory namespace
'''
_description_ = '<shared>'
@stub_function
def array(shape, dtype):
'''
Allocate a shared array of the given *shape* and *type*. *shape* is
either an integer or a tuple of integers representing the array's
dimensions. *type* is a :ref:`Numba type <numba-types>` of the
elements needing to be stored in the array.
The returned array-like object can be read and written to like any
normal device array (e.g. through indexing).
'''
class local(Stub):
'''
Local memory namespace
'''
_description_ = '<local>'
@stub_function
def array(shape, dtype):
'''
Allocate a local array of the given *shape* and *type*. The array is
private to the current thread, and resides in global memory. An
array-like object is returned which can be read and written to like any
standard array (e.g. through indexing).
'''
class const(Stub):
'''
Constant memory namespace
'''
@stub_function
def array_like(ndarray):
'''
Create a const array from *ndarry*. The resulting const array will have
the same shape, type, and values as *ndarray*.
'''
# -------------------------------------------------------------------------------
# warp level operations
class syncwarp(Stub):
'''
syncwarp(mask=0xFFFFFFFF)
Synchronizes a masked subset of threads in a warp.
'''
_description_ = '<warp_sync()>'
class shfl_sync_intrinsic(Stub):
'''
shfl_sync_intrinsic(mask, mode, value, mode_offset, clamp)
Nvvm intrinsic for shuffling data across a warp
docs.nvidia.com/cuda/nvvm-ir-spec/index.html#nvvm-intrin-warp-level-datamove
'''
_description_ = '<shfl_sync()>'
class vote_sync_intrinsic(Stub):
'''
vote_sync_intrinsic(mask, mode, predictate)
Nvvm intrinsic for performing a reduce and broadcast across a warp
docs.nvidia.com/cuda/nvvm-ir-spec/index.html#nvvm-intrin-warp-level-vote
'''
_description_ = '<vote_sync()>'
class match_any_sync(Stub):
'''
match_any_sync(mask, value)
Nvvm intrinsic for performing a compare and broadcast across a warp.
Returns a mask of threads that have same value as the given value from
within the masked warp.
'''
_description_ = '<match_any_sync()>'
class match_all_sync(Stub):
'''
match_all_sync(mask, value)
Nvvm intrinsic for performing a compare and broadcast across a warp.
Returns a tuple of (mask, pred), where mask is a mask of threads that have
same value as the given value from within the masked warp, if they
all have the same value, otherwise it is 0. Pred is a boolean of whether
or not all threads in the mask warp have the same warp.
'''
_description_ = '<match_all_sync()>'
class activemask(Stub):
'''
activemask()
Returns a 32-bit integer mask of all currently active threads in the
calling warp. The Nth bit is set if the Nth lane in the warp is active when
activemask() is called. Inactive threads are represented by 0 bits in the
returned mask. Threads which have exited the kernel are always marked as
inactive.
'''
_description_ = '<activemask()>'
class lanemask_lt(Stub):
'''
lanemask_lt()
Returns a 32-bit integer mask of all lanes (including inactive ones) with
ID less than the current lane.
'''
_description_ = '<lanemask_lt()>'
# -------------------------------------------------------------------------------
# memory fences
class threadfence_block(Stub):
'''
A memory fence at thread block level
'''
_description_ = '<threadfence_block()>'
class threadfence_system(Stub):
'''
A memory fence at system level: across devices
'''
_description_ = '<threadfence_system()>'
class threadfence(Stub):
'''
A memory fence at device level
'''
_description_ = '<threadfence()>'
#-------------------------------------------------------------------------------
# bit manipulation
class popc(Stub):
"""
popc(x)
Returns the number of set bits in x.
"""
class brev(Stub):
"""
brev(x)
Returns the reverse of the bit pattern of x. For example, 0b10110110
becomes 0b01101101.
"""
class clz(Stub):
"""
clz(x)
Returns the number of leading zeros in z.
"""
class ffs(Stub):
"""
ffs(x)
Returns the position of the first (least significant) bit set to 1 in x,
where the least significant bit position is 1. ffs(0) returns 0.
"""
#-------------------------------------------------------------------------------
# comparison and selection instructions
class selp(Stub):
"""
selp(a, b, c)
Select between source operands, based on the value of the predicate source
operand.
"""
#-------------------------------------------------------------------------------
# single / double precision arithmetic
class fma(Stub):
"""
fma(a, b, c)
Perform the fused multiply-add operation.
"""
class cbrt(Stub):
""""
cbrt(a)
Perform the cube root operation.
"""
#-------------------------------------------------------------------------------
# atomic
class atomic(Stub):
"""Namespace for atomic operations
"""
_description_ = '<atomic>'
class add(Stub):
"""add(ary, idx, val)
Perform atomic ``ary[idx] += val``. Supported on int32, float32, and
float64 operands only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class sub(Stub):
"""sub(ary, idx, val)
Perform atomic ``ary[idx] -= val``. Supported on int32, float32, and
float64 operands only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class and_(Stub):
"""and_(ary, idx, val)
Perform atomic ``ary[idx] &= val``. Supported on int32, int64, uint32
and uint64 operands only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class or_(Stub):
"""or_(ary, idx, val)
Perform atomic ``ary[idx] |= val``. Supported on int32, int64, uint32
and uint64 operands only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class xor(Stub):
"""xor(ary, idx, val)
Perform atomic ``ary[idx] ^= val``. Supported on int32, int64, uint32
and uint64 operands only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class inc(Stub):
"""inc(ary, idx, val)
Perform atomic ``ary[idx] += 1`` up to val, then reset to 0. Supported
on uint32, and uint64 operands only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class dec(Stub):
"""dec(ary, idx, val)
Performs::
ary[idx] = (value if (array[idx] == 0) or
(array[idx] > value) else array[idx] - 1)
Supported on uint32, and uint64 operands only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class exch(Stub):
"""exch(ary, idx, val)
Perform atomic ``ary[idx] = val``. Supported on int32, int64, uint32 and
uint64 operands only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class max(Stub):
"""max(ary, idx, val)
Perform atomic ``ary[idx] = max(ary[idx], val)``.
Supported on int32, int64, uint32, uint64, float32, float64 operands
only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class min(Stub):
"""min(ary, idx, val)
Perform atomic ``ary[idx] = min(ary[idx], val)``.
Supported on int32, int64, uint32, uint64, float32, float64 operands
only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class nanmax(Stub):
"""nanmax(ary, idx, val)
Perform atomic ``ary[idx] = max(ary[idx], val)``.
NOTE: NaN is treated as a missing value such that:
nanmax(NaN, n) == n, nanmax(n, NaN) == n
Supported on int32, int64, uint32, uint64, float32, float64 operands
only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class nanmin(Stub):
"""nanmin(ary, idx, val)
Perform atomic ``ary[idx] = min(ary[idx], val)``.
NOTE: NaN is treated as a missing value, such that:
nanmin(NaN, n) == n, nanmin(n, NaN) == n
Supported on int32, int64, uint32, uint64, float32, float64 operands
only.
Returns the old value at the index location as if it is loaded
atomically.
"""
class compare_and_swap(Stub):
"""compare_and_swap(ary, old, val)
Conditionally assign ``val`` to the first element of an 1D array ``ary``
if the current value matches ``old``.
Supported on int32, int64, uint32, uint64 operands only.
Returns the old value as if it is loaded atomically.
"""
class cas(Stub):
"""cas(ary, idx, old, val)
Conditionally assign ``val`` to the element ``idx`` of an array
``ary`` if the current value of ``ary[idx]`` matches ``old``.
Supported on int32, int64, uint32, uint64 operands only.
Returns the old value as if it is loaded atomically.
"""
#-------------------------------------------------------------------------------
# timers
class nanosleep(Stub):
'''
nanosleep(ns)
Suspends the thread for a sleep duration approximately close to the delay
`ns`, specified in nanoseconds.
'''
_description_ = '<nansleep()>'
#-------------------------------------------------------------------------------
# Floating point 16
class fp16(Stub):
"""Namespace for fp16 operations
"""
_description_ = '<fp16>'
class hadd(Stub):
"""hadd(a, b)
Perform fp16 addition, (a + b) in round to nearest mode. Supported
on fp16 operands only.
Returns the fp16 result of the addition.
"""
class hsub(Stub):
"""hsub(a, b)
Perform fp16 subtraction, (a - b) in round to nearest mode. Supported
on fp16 operands only.
Returns the fp16 result of the subtraction.
"""
class hmul(Stub):
"""hmul(a, b)
Perform fp16 multiplication, (a * b) in round to nearest mode. Supported
on fp16 operands only.
Returns the fp16 result of the multiplication.
"""
class hdiv(Stub):
"""hdiv(a, b)
Perform fp16 division, (a / b) in round to nearest mode. Supported
on fp16 operands only.
Returns the fp16 result of the division
"""
class hfma(Stub):
"""hfma(a, b, c)
Perform fp16 multiply and accumulate, (a * b) + c in round to nearest
mode. Supported on fp16 operands only.
Returns the fp16 result of the multiplication.
"""
class hneg(Stub):
"""hneg(a)
Perform fp16 negation, -(a). Supported on fp16 operands only.
Returns the fp16 result of the negation.
"""
class habs(Stub):
"""habs(a)
Perform fp16 absolute value, |a|. Supported on fp16 operands only.
Returns the fp16 result of the absolute value.
"""
class hsin(Stub):
"""hsin(a)
Calculate sine in round to nearest even mode. Supported on fp16
operands only.
Returns the sine result.
"""
class hcos(Stub):
"""hsin(a)
Calculate cosine in round to nearest even mode. Supported on fp16
operands only.
Returns the cosine result.
"""
class hlog(Stub):
"""hlog(a)
Calculate natural logarithm in round to nearest even mode. Supported
on fp16 operands only.
Returns the natural logarithm result.
"""
class hlog10(Stub):
"""hlog10(a)
Calculate logarithm base 10 in round to nearest even mode. Supported
on fp16 operands only.
Returns the logarithm base 10 result.
"""
class hlog2(Stub):
"""hlog2(a)
Calculate logarithm base 2 in round to nearest even mode. Supported
on fp16 operands only.
Returns the logarithm base 2 result.
"""
class hexp(Stub):
"""hexp(a)
Calculate natural exponential, exp(a), in round to nearest mode.
Supported on fp16 operands only.
Returns the natural exponential result.
"""
class hexp10(Stub):
"""hexp10(a)
Calculate exponential base 10 (10 ** a) in round to nearest mode.
Supported on fp16 operands only.
Returns the exponential base 10 result.
"""
class hexp2(Stub):
"""hexp2(a)
Calculate exponential base 2 (2 ** a) in round to nearest mode.
Supported on fp16 operands only.
Returns the exponential base 2 result.
"""
class hfloor(Stub):
"""hfloor(a)
Calculate the floor, the largest integer less than or equal to 'a'.
Supported on fp16 operands only.
Returns the floor result.
"""
class hceil(Stub):
"""hceil(a)
Calculate the ceil, the smallest integer greater than or equal to 'a'.
Supported on fp16 operands only.
Returns the ceil result.
"""
class hsqrt(Stub):
"""hsqrt(a)
Calculate the square root of the input argument in round to nearest
mode. Supported on fp16 operands only.
Returns the square root result.
"""
class hrsqrt(Stub):
"""hrsqrt(a)
Calculate the reciprocal square root of the input argument in round
to nearest even mode. Supported on fp16 operands only.
Returns the reciprocal square root result.
"""
class hrcp(Stub):
"""hrcp(a)
Calculate the reciprocal of the input argument in round to nearest
even mode. Supported on fp16 operands only.
Returns the reciprocal result.
"""
class hrint(Stub):
"""hrint(a)
Round the input argument to nearest integer value. Supported on fp16
operands only.
Returns the rounded result.
"""
class htrunc(Stub):
"""htrunc(a)
Truncate the input argument to its integer portion. Supported
on fp16 operands only.
Returns the truncated result.
"""
class heq(Stub):
"""heq(a, b)
Perform fp16 comparison, (a == b). Supported
on fp16 operands only.
Returns True if a and b are equal and False otherwise.
"""
class hne(Stub):
"""hne(a, b)
Perform fp16 comparison, (a != b). Supported
on fp16 operands only.
Returns True if a and b are not equal and False otherwise.
"""
class hge(Stub):
"""hge(a, b)
Perform fp16 comparison, (a >= b). Supported
on fp16 operands only.
Returns True if a is >= b and False otherwise.
"""
class hgt(Stub):
"""hgt(a, b)
Perform fp16 comparison, (a > b). Supported
on fp16 operands only.
Returns True if a is > b and False otherwise.
"""
class hle(Stub):
"""hle(a, b)
Perform fp16 comparison, (a <= b). Supported
on fp16 operands only.
Returns True if a is <= b and False otherwise.
"""
class hlt(Stub):
"""hlt(a, b)
Perform fp16 comparison, (a < b). Supported
on fp16 operands only.
Returns True if a is < b and False otherwise.
"""
class hmax(Stub):
"""hmax(a, b)
Perform fp16 maximum operation, max(a,b) Supported
on fp16 operands only.
Returns a if a is greater than b, returns b otherwise.
"""
class hmin(Stub):
"""hmin(a, b)
Perform fp16 minimum operation, min(a,b). Supported
on fp16 operands only.
Returns a if a is less than b, returns b otherwise.
"""
#-------------------------------------------------------------------------------
# vector types
def make_vector_type_stubs():
"""Make user facing objects for vector types"""
vector_type_stubs = []
vector_type_prefix = (
"int8",
"int16",
"int32",
"int64",
"uint8",
"uint16",
"uint32",
"uint64",
"float32",
"float64"
)
vector_type_element_counts = (1, 2, 3, 4)
vector_type_attribute_names = ("x", "y", "z", "w")
for prefix, nelem in itertools.product(
vector_type_prefix, vector_type_element_counts
):
type_name = f"{prefix}x{nelem}"
attr_names = vector_type_attribute_names[:nelem]
vector_type_stub = type(
type_name, (Stub,),
{
**{attr: lambda self: None for attr in attr_names},
**{
"_description_": f"<{type_name}>",
"__signature__": Signature(parameters=[
Parameter(
name=attr_name, kind=Parameter.POSITIONAL_ONLY
) for attr_name in attr_names[:nelem]
]),
"__doc__": f"A stub for {type_name} to be used in "
"CUDA kernels."
},
**{"aliases": []}
}
)
vector_type_stubs.append(vector_type_stub)
return vector_type_stubs
def map_vector_type_stubs_to_alias(vector_type_stubs):
"""For each of the stubs, create its aliases.
For example: float64x3 -> double3
"""
# C-compatible type mapping, see:
# https://numpy.org/devdocs/reference/arrays.scalars.html#integer-types
base_type_to_alias = {
"char": f"int{np.dtype(np.byte).itemsize * 8}",
"short": f"int{np.dtype(np.short).itemsize * 8}",
"int": f"int{np.dtype(np.intc).itemsize * 8}",
"long": f"int{np.dtype(np.int_).itemsize * 8}",
"longlong": f"int{np.dtype(np.longlong).itemsize * 8}",
"uchar": f"uint{np.dtype(np.ubyte).itemsize * 8}",
"ushort": f"uint{np.dtype(np.ushort).itemsize * 8}",
"uint": f"uint{np.dtype(np.uintc).itemsize * 8}",
"ulong": f"uint{np.dtype(np.uint).itemsize * 8}",
"ulonglong": f"uint{np.dtype(np.ulonglong).itemsize * 8}",
"float": f"float{np.dtype(np.single).itemsize * 8}",
"double": f"float{np.dtype(np.double).itemsize * 8}"
}
base_type_to_vector_type = defaultdict(list)
for stub in vector_type_stubs:
base_type_to_vector_type[stub.__name__[:-2]].append(stub)
for alias, base_type in base_type_to_alias.items():
vector_type_stubs = base_type_to_vector_type[base_type]
for stub in vector_type_stubs:
nelem = stub.__name__[-1]
stub.aliases.append(f"{alias}{nelem}")
_vector_type_stubs = make_vector_type_stubs()
map_vector_type_stubs_to_alias(_vector_type_stubs)