Repository navigation
Expand file tree
/
Copy pathdispatcher.py
More file actions
2729 lines (2335 loc) · 95.9 KB
/
Copy pathdispatcher.py
File metadata and controls
2729 lines (2335 loc) · 95.9 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
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause
import numpy as np
import os
import pickle
import sys
import ctypes
import collections
import functools
import types as pytypes
import weakref
from contextlib import ExitStack
from abc import abstractmethod
import uuid
import re
from warnings import warn
from cuda.core import launch, LaunchConfig
from numba.cuda.core import errors
from numba.cuda._compat import CUDA_CORE_GE_1_0
from numba.cuda import serialize, utils
from numba import cuda
from numba.cuda import launchconfig
from numba.cuda.np import numpy_support
from numba.cuda.core.compiler_lock import global_compiler_lock
from numba.cuda.typeconv.rules import default_type_manager
from numba.cuda.typing.templates import fold_arguments
from numba.cuda.typing.typeof import Purpose, typeof
from numba.cuda import typing, types
from numba.cuda.types import ext_types
from numba.cuda.api import get_current_device
from numba.cuda.args import wrap_arg
from numba.cuda.core.bytecode import get_code_object
from numba.cuda.compiler import (
compile_cuda,
CUDACompiler,
kernel_fixup,
compile_extra,
compile_ir,
)
from numba.cuda.core import sigutils, config, entrypoints
from numba.cuda.flags import Flags
from numba.cuda.cudadrv import driver, nvvm
from numba.cuda.locks import module_init_lock
from numba.cuda.core.caching import Cache, CacheImpl, NullCache
from numba.cuda.descriptor import cuda_target
from numba.cuda.errors import (
missing_launch_config_msg,
normalize_kernel_dimensions,
)
from numba.cuda.cudadrv.linkable_code import LinkableCode
from numba.cuda.cudadrv.devices import get_context
from numba.cuda.memory_management.nrt import rtsys, NRT_LIBRARY
import numba.cuda.core.event as ev
from numba.cuda.cext import _dispatcher
_LAUNCH_CONFIG_KW = "__numba_cuda_launch_config__"
_NO_LAUNCH_CONFIG_CACHE_KEY = "__numba_cuda_no_launch_config__"
cuda_fp16_math_funcs = [
"hsin",
"hcos",
"hlog",
"hlog10",
"hlog2",
"hexp",
"hexp10",
"hexp2",
"hsqrt",
"hrsqrt",
"hfloor",
"hceil",
"hrcp",
"hrint",
"htrunc",
"hdiv",
]
reshape_funcs = ["nocopy_empty_reshape", "numba_attempt_nocopy_reshape"]
class _Kernel(serialize.ReduceMixin):
"""
CUDA Kernel specialized for a given set of argument types. When called, this
object launches the kernel on the device.
"""
NRT_functions = [
"NRT_Allocate",
"NRT_MemInfo_init",
"NRT_MemInfo_new",
"NRT_Free",
"NRT_dealloc",
"NRT_MemInfo_destroy",
"NRT_MemInfo_call_dtor",
"NRT_MemInfo_data_fast",
"NRT_MemInfo_alloc_aligned",
"NRT_Allocate_External",
"NRT_decref",
"NRT_incref",
]
@global_compiler_lock
def __init__(
self,
py_func,
argtypes,
link=None,
debug=False,
lineinfo=False,
inline=False,
forceinline=False,
fastmath=False,
extensions=None,
max_registers=None,
lto=False,
opt=True,
device=False,
launch_bounds=None,
shared_memory_carveout=None,
):
if device:
raise RuntimeError("Cannot compile a device function as a kernel")
super().__init__()
# _DispatcherBase.nopython_signatures() expects this attribute to be
# present, because it assumes an overload is a CompileResult. In the
# CUDA target, _Kernel instances are stored instead, so we provide this
# attribute here to avoid duplicating nopython_signatures() in the CUDA
# target with slight modifications.
self.objectmode = False
# The finalizer constructed by _DispatcherBase._make_finalizer also
# expects overloads to be a CompileResult. It uses the entry_point to
# remove a CompileResult from a target context. However, since we never
# insert kernels into a target context (there is no need because they
# cannot be called by other functions, only through the dispatcher) it
# suffices to pretend we have an entry point of None.
self.entry_point = None
self.py_func = py_func
self.argtypes = argtypes
self.debug = debug
self.lineinfo = lineinfo
self.extensions = extensions or []
self.launch_bounds = launch_bounds
nvvm_options = {"fastmath": fastmath, "opt": 3 if opt else 0}
if debug:
nvvm_options["g"] = None
cc = get_current_device().compute_capability
cres = compile_cuda(
self.py_func,
types.void,
self.argtypes,
debug=self.debug,
lineinfo=lineinfo,
forceinline=forceinline,
fastmath=fastmath,
nvvm_options=nvvm_options,
cc=cc,
max_registers=max_registers,
lto=lto,
)
self.launch_config_sensitive = bool(
getattr(cres, "metadata", None)
and cres.metadata.get("launch_config_sensitive", False)
)
tgt_ctx = cres.target_context
lib = cres.library
kernel = lib.get_function(cres.fndesc.llvm_func_name)
lib._entry_name = cres.fndesc.llvm_func_name
kernel_fixup(kernel, self.debug)
nvvm.set_launch_bounds(kernel, launch_bounds)
if shared_memory_carveout is not None:
self.shared_memory_carveout = self._parse_carveout(
shared_memory_carveout
)
else:
self.shared_memory_carveout = None
if not link:
link = []
asm = lib.get_asm_str()
# The code library contains functions that require cooperative launch.
self.cooperative = lib.use_cooperative
# We need to link against cudadevrt if grid sync is being used.
if self.cooperative:
lib.needs_cudadevrt = True
def link_to_library_functions(
library_functions, library_path, prefix=None
):
"""
Dynamically links to library functions by searching for their names
in the specified library and linking to the corresponding source
file.
"""
if prefix is not None:
library_functions = [
f"{prefix}{fn}" for fn in library_functions
]
found_functions = [fn for fn in library_functions if f"{fn}" in asm]
if found_functions:
basedir = os.path.dirname(os.path.abspath(__file__))
source_file_path = os.path.join(basedir, library_path)
link.append(source_file_path)
return found_functions
# Link to the helper library functions if needed
link_to_library_functions(reshape_funcs, "reshape_funcs.cu")
self.maybe_link_nrt(link, tgt_ctx, asm)
for filepath in link:
lib.add_linking_file(filepath)
# populate members
self.entry_name = kernel.name
self.signature = cres.signature
self._type_annotation = cres.type_annotation
self._codelibrary = lib
self.call_helper = cres.call_helper
# The following are referred to by the cache implementation. Note:
# - There are no referenced environments in CUDA.
# - Kernels don't have lifted code.
self.target_context = tgt_ctx
self.fndesc = cres.fndesc
self.environment = cres.environment
self._referenced_environments = []
self.lifted = []
def maybe_link_nrt(self, link, tgt_ctx, asm):
"""
Add the NRT source code to the link if the neccesary conditions are met.
NRT must be enabled for the CUDATargetContext, and either NRT functions
must be detected in the kernel asm or an NRT enabled LinkableCode object
must be passed.
"""
if not tgt_ctx.enable_nrt:
return
all_nrt = "|".join(self.NRT_functions)
pattern = (
r"\.extern\s+\.func\s+(?:\s*\(.+\)\s*)?("
+ all_nrt
+ r")\s*\([^)]*\)\s*;"
)
link_nrt = False
nrt_in_asm = re.findall(pattern, asm)
if len(nrt_in_asm) > 0:
link_nrt = True
if not link_nrt:
for file in link:
if isinstance(file, LinkableCode):
if file.nrt:
link_nrt = True
break
if link_nrt:
link.append(NRT_LIBRARY)
@property
def library(self):
return self._codelibrary
@property
def type_annotation(self):
return self._type_annotation
def _find_referenced_environments(self):
return self._referenced_environments
@property
def codegen(self):
return self.target_context.codegen()
@property
def argument_types(self):
return tuple(self.signature.args)
@classmethod
def _rebuild(
cls,
cooperative,
name,
signature,
codelibrary,
debug,
lineinfo,
call_helper,
extensions,
shared_memory_carveout=None,
launch_config_sensitive=False,
):
"""
Rebuild an instance.
"""
instance = cls.__new__(cls)
# invoke parent constructor
super(cls, instance).__init__()
# populate members
instance.entry_point = None
instance.cooperative = cooperative
instance.entry_name = name
instance.signature = signature
instance._type_annotation = None
instance._codelibrary = codelibrary
instance.debug = debug
instance.lineinfo = lineinfo
instance.call_helper = call_helper
instance.extensions = extensions
instance.shared_memory_carveout = shared_memory_carveout
instance.launch_config_sensitive = launch_config_sensitive
return instance
def _reduce_states(self):
"""
Reduce the instance for serialization.
Compiled definitions are serialized in PTX form.
Type annotation are discarded.
Thread, block and shared memory configuration are serialized.
Stream information is discarded.
"""
return dict(
cooperative=self.cooperative,
name=self.entry_name,
signature=self.signature,
codelibrary=self._codelibrary,
debug=self.debug,
lineinfo=self.lineinfo,
call_helper=self.call_helper,
extensions=self.extensions,
shared_memory_carveout=self.shared_memory_carveout,
launch_config_sensitive=self.launch_config_sensitive,
)
def _parse_carveout(self, carveout):
if isinstance(carveout, int):
return carveout
carveout_map = {"default": -1, "maxl1": 0, "maxshared": 100}
return carveout_map[str(carveout).lower()]
@module_init_lock
def initialize_once(self, mod):
if not mod.initialized:
mod.setup()
def bind(self):
"""
Force binding to current CUDA context
"""
cufunc = self._codelibrary.get_cufunc()
self.initialize_once(cufunc.module)
if self.shared_memory_carveout is not None:
cufunc.set_shared_memory_carveout(self.shared_memory_carveout)
if (
hasattr(self, "target_context")
and self.target_context.enable_nrt
and config.CUDA_NRT_STATS
):
rtsys.ensure_initialized()
rtsys.set_memsys_to_module(cufunc.module)
# We don't know which stream the kernel will be launched on, so
# we force synchronize here.
cuda.synchronize()
@property
def regs_per_thread(self):
"""
The number of registers used by each thread for this kernel.
"""
return self._codelibrary.get_cufunc().attrs.regs
@property
def const_mem_size(self):
"""
The amount of constant memory used by this kernel.
"""
return self._codelibrary.get_cufunc().attrs.const
@property
def shared_mem_per_block(self):
"""
The amount of shared memory used per block for this kernel.
"""
return self._codelibrary.get_cufunc().attrs.shared
@property
def max_threads_per_block(self):
"""
The maximum allowable threads per block.
"""
return self._codelibrary.get_cufunc().attrs.maxthreads
@property
def local_mem_per_thread(self):
"""
The amount of local memory used per thread for this kernel.
"""
return self._codelibrary.get_cufunc().attrs.local
def inspect_llvm(self):
"""
Returns the LLVM IR for this kernel.
"""
return self._codelibrary.get_llvm_str()
def inspect_asm(self, cc):
"""
Returns the PTX code for this kernel.
"""
return self._codelibrary.get_asm_str(cc=cc)
def inspect_lto_ptx(self, cc):
"""
Returns the PTX code for the external functions linked to this kernel.
"""
return self._codelibrary.get_lto_ptx(cc=cc)
def inspect_sass_cfg(self):
"""
Returns the CFG of the SASS for this kernel.
Requires nvdisasm to be available on the PATH.
"""
return self._codelibrary.get_sass_cfg()
def inspect_sass(self):
"""
Returns the SASS code for this kernel.
Requires nvdisasm to be available on the PATH.
"""
return self._codelibrary.get_sass()
def inspect_types(self, file=None):
"""
Produce a dump of the Python source of this function annotated with the
corresponding Numba IR and type information. The dump is written to
*file*, or *sys.stdout* if *file* is *None*.
"""
if self._type_annotation is None:
raise ValueError("Type annotation is not available")
if file is None:
file = sys.stdout
print("%s %s" % (self.entry_name, self.argument_types), file=file)
print("-" * 80, file=file)
print(self._type_annotation, file=file)
print("=" * 80, file=file)
def max_cooperative_grid_blocks(self, blockdim, dynsmemsize=0):
"""
Calculates the maximum number of blocks that can be launched for this
kernel in a cooperative grid in the current context, for the given block
and dynamic shared memory sizes.
:param blockdim: Block dimensions, either as a scalar for a 1D block, or
a tuple for 2D or 3D blocks.
:param dynsmemsize: Dynamic shared memory size in bytes.
:return: The maximum number of blocks in the grid.
"""
ctx = get_context()
cufunc = self._codelibrary.get_cufunc()
if isinstance(blockdim, tuple):
blockdim = functools.reduce(lambda x, y: x * y, blockdim)
active_per_sm = ctx.get_active_blocks_per_multiprocessor(
cufunc, blockdim, dynsmemsize
)
sm_count = ctx.device.MULTIPROCESSOR_COUNT
return active_per_sm * sm_count
def launch(self, args, griddim, blockdim, stream=0, sharedmem=0):
# Prepare kernel
cufunc = self._codelibrary.get_cufunc()
if self.debug:
excname = cufunc.name + "__errcode__"
excmem, excsz = cufunc.module.get_global_symbol(excname)
assert excsz == ctypes.sizeof(ctypes.c_int)
excval = ctypes.c_int()
excmem.memset(0, stream=stream)
# Prepare arguments
retr = [] # hold functors for writeback
kernelargs = []
for t, v in zip(self.argument_types, args):
self._prepare_args(t, v, stream, retr, kernelargs)
# Invoke kernel
if CUDA_CORE_GE_1_0:
config = LaunchConfig(
grid=griddim,
block=blockdim,
shmem_size=sharedmem,
is_cooperative=self.cooperative,
)
else:
config = LaunchConfig(
grid=griddim,
block=blockdim,
shmem_size=sharedmem,
cooperative_launch=self.cooperative,
)
kernel = cufunc.kernel
launch(stream, config, kernel, *kernelargs)
if self.debug:
driver.device_to_host(ctypes.addressof(excval), excmem, excsz)
if excval.value != 0:
# An error occurred
def load_symbol(name):
mem, sz = cufunc.module.get_global_symbol(
"%s__%s__" % (cufunc.name, name)
)
val = ctypes.c_int()
driver.device_to_host(ctypes.addressof(val), mem, sz)
return val.value
tid = [load_symbol("tid" + i) for i in "zyx"]
ctaid = [load_symbol("ctaid" + i) for i in "zyx"]
code = excval.value
exccls, exc_args, loc = self.call_helper.get_exception(code)
# Prefix the exception message with the source location
if loc is None:
locinfo = ""
else:
sym, filepath, lineno = loc
filepath = os.path.abspath(filepath)
locinfo = "In function %r, file %s, line %s, " % (
sym,
filepath,
lineno,
)
# Prefix the exception message with the thread position
prefix = "%stid=%s ctaid=%s" % (locinfo, tid, ctaid)
if exc_args:
exc_args = ("%s: %s" % (prefix, exc_args[0]),) + exc_args[
1:
]
else:
exc_args = (prefix,)
raise exccls(*exc_args)
# retrieve auto converted arrays
for wb in retr:
wb()
def _prepare_args(self, ty, val, stream, retr, kernelargs):
"""
Convert arguments to ctypes and append to kernelargs
"""
# map the arguments using any extension you've registered
for extension in reversed(self.extensions):
ty, val = extension.prepare_args(ty, val, stream=stream, retr=retr)
if isinstance(ty, types.Array):
devary = wrap_arg(val).to_device(retr, stream)
meminfo = parent = 0
kernelargs.append(meminfo)
kernelargs.append(parent)
# non-pointer-arguments-without-ctypes might be dicey, since we're
# assuming shape, strides, size, and itemsize fit into intptr_t
# however, this saves a noticeable amount of overhead in kernel
# invocation
kernelargs.append(devary.size)
kernelargs.append(itemsize := devary.dtype.itemsize)
kernelargs.append(devary.ptr)
kernelargs.extend(shape := devary.shape)
kernelargs.extend(
(layout := devary._layout).strides_in_bytes
or numpy_support.strides_from_shape(
shape=shape,
itemsize=itemsize,
c_contiguous=layout.is_contiguous_c,
f_contiguous=layout.is_contiguous_f,
)
)
elif isinstance(ty, types.CPointer):
# Pointer arguments should be a pointer-sized integer
kernelargs.append(val)
elif isinstance(ty, types.Integer):
cval = getattr(ctypes, "c_%s" % ty)(val)
kernelargs.append(cval)
elif ty == types.float16:
cval = ctypes.c_uint16(np.float16(val).view(np.uint16))
kernelargs.append(cval)
elif ty == types.float64:
cval = ctypes.c_double(val)
kernelargs.append(cval)
elif ty == types.float32:
cval = ctypes.c_float(val)
kernelargs.append(cval)
elif ty == types.boolean:
kernelargs.append(val)
elif ty == types.complex64:
kernelargs.append(ctypes.c_float(val.real))
kernelargs.append(ctypes.c_float(val.imag))
elif ty == types.complex128:
kernelargs.append(ctypes.c_double(val.real))
kernelargs.append(ctypes.c_double(val.imag))
elif isinstance(ty, (types.NPDatetime, types.NPTimedelta)):
kernelargs.append(ctypes.c_int64(val.view(np.int64)))
elif isinstance(ty, types.Record):
devrec = wrap_arg(val).to_device(retr, stream)
kernelargs.append(devrec.ptr)
elif isinstance(ty, types.BaseTuple):
assert len(ty) == len(val)
for t, v in zip(ty, val):
self._prepare_args(t, v, stream, retr, kernelargs)
elif isinstance(ty, types.EnumMember):
try:
self._prepare_args(
ty.dtype, val.value, stream, retr, kernelargs
)
except NotImplementedError:
raise NotImplementedError(ty, val)
else:
raise NotImplementedError(ty, val)
class ForAll:
def __init__(self, dispatcher, ntasks, tpb, stream, sharedmem):
if ntasks < 0:
raise ValueError(
"Can't create ForAll with negative task count: %s" % ntasks
)
self.dispatcher = dispatcher
self.ntasks = ntasks
self.thread_per_block = tpb
self.stream = stream
self.sharedmem = sharedmem
def __call__(self, *args):
if self.ntasks == 0:
return
if self.dispatcher.specialized:
specialized = self.dispatcher
else:
specialized = self.dispatcher.specialize(*args)
blockdim = self._compute_thread_per_block(specialized)
griddim = (self.ntasks + blockdim - 1) // blockdim
return specialized[griddim, blockdim, self.stream, self.sharedmem](
*args
)
def _compute_thread_per_block(self, dispatcher):
tpb = self.thread_per_block
# Prefer user-specified config
if tpb != 0:
return tpb
# Else, ask the driver to give a good config
else:
ctx = get_context()
# Dispatcher is specialized, so there's only one definition - get
# it so we can get the cufunc from the code library
kernel = next(iter(dispatcher.overloads.values()))
kwargs = dict(
func=kernel._codelibrary.get_cufunc(),
b2d_func=0, # dynamic-shared memory is constant to blksz
memsize=self.sharedmem,
blocksizelimit=1024,
)
_, tpb = ctx.get_max_potential_block_size(**kwargs)
return tpb
class _LaunchConfiguration:
"""Configured CUDA kernel launch metadata.
The ``pre_launch_callbacks`` list may be used to register host-side
callbacks that run immediately before kernel launch with
``(kernel, launch_config)``.
Callbacks must not invoke CUDA APIs or launch CUDA work. That use is not
supported, is not tested, and has undefined behavior; it may deadlock or
fail in other ways.
"""
def __init__(self, dispatcher, griddim, blockdim, stream, sharedmem):
self.dispatcher = dispatcher
self.griddim = griddim
self.blockdim = blockdim
self.stream = driver._to_core_stream(stream)
self.sharedmem = sharedmem
self.pre_launch_callbacks = []
self._kernel_launch_config_sensitive = None
if (
config.CUDA_LOW_OCCUPANCY_WARNINGS
and not config.DISABLE_PERFORMANCE_WARNINGS
):
# Warn when the grid has fewer than 128 blocks. This number is
# chosen somewhat heuristically - ideally the minimum is 2 times
# the number of SMs, but the number of SMs varies between devices -
# some very small GPUs might only have 4 SMs, but an H100-SXM5 has
# 132. In general kernels should be launched with large grids
# (hundreds or thousands of blocks), so warning when fewer than 128
# blocks are used will likely catch most beginner errors, where the
# grid tends to be very small (single-digit or low tens of blocks).
min_grid_size = 128
grid_size = griddim[0] * griddim[1] * griddim[2]
if grid_size < min_grid_size:
msg = (
f"Grid size {grid_size} will likely result in GPU "
"under-utilization due to low occupancy."
)
warn(errors.NumbaPerformanceWarning(msg))
def __call__(self, *args):
return self.dispatcher.call(args, self)
def _is_kernel_launch_config_sensitive(self):
"""Return True if this kernel was marked as launch-config sensitive."""
return bool(self._kernel_launch_config_sensitive)
@property
def args(self):
return _dispatcher.get_current_launch_args()
def _push_args(self, args):
return _dispatcher.swap_current_launch_args(args)
def _pop_args(self, prev):
_dispatcher.swap_current_launch_args(prev)
def __getstate__(self):
state = self.__dict__.copy()
state["stream"] = int(state["stream"].handle)
if state["pre_launch_callbacks"]:
raise pickle.PicklingError(
"Cannot pickle configured launches with pre-launch callbacks"
)
return state
def __setstate__(self, state):
handle = state.pop("stream")
self.__dict__.update(state)
self.stream = driver._to_core_stream(handle)
if "pre_launch_callbacks" not in self.__dict__:
self.pre_launch_callbacks = []
class CUDACacheImpl(CacheImpl):
def reduce(self, kernel):
return kernel._reduce_states()
def rebuild(self, target_context, payload):
return _Kernel._rebuild(**payload)
def check_cachable(self, cres):
# CUDA Kernels are always cachable - the reasons for an entity not to
# be cachable are:
#
# - The presence of lifted loops, or
# - The presence of dynamic globals.
#
# neither of which apply to CUDA kernels.
return True
class CUDACache(Cache):
"""
Implements a cache that saves and loads CUDA kernels and compile results.
"""
_impl_class = CUDACacheImpl
def __init__(self, py_func):
self._launch_config_key = None
self._launch_config_sensitive_flag = None
super().__init__(py_func)
marker_name = f"{self._impl.filename_base}.lcs"
self._launch_config_marker_path = os.path.join(
self._cache_path, marker_name
)
def _index_key(self, sig, codegen):
key = super()._index_key(sig, codegen)
if self._launch_config_key is None:
return key
return key + (("launch_config", self._launch_config_key),)
def set_launch_config_key(self, key):
self._launch_config_key = key
def is_launch_config_sensitive(self):
if self._launch_config_sensitive_flag is None:
self._launch_config_sensitive_flag = os.path.exists(
self._launch_config_marker_path
)
return self._launch_config_sensitive_flag
def mark_launch_config_sensitive(self):
if self._launch_config_sensitive_flag is True:
return True
try:
self._impl.locator.ensure_cache_path()
with open(self._launch_config_marker_path, "a"):
pass
except OSError:
self._launch_config_sensitive_flag = False
return False
self._launch_config_sensitive_flag = True
return True
def flush(self):
super().flush()
try:
os.unlink(self._launch_config_marker_path)
except FileNotFoundError:
pass
self._launch_config_sensitive_flag = None
def load_overload(self, sig, target_context):
# Loading an overload refreshes the context to ensure it is initialized.
with utils.numba_target_override():
return super().load_overload(sig, target_context)
class OmittedArg:
"""
A placeholder for omitted arguments with a default value.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return "omitted arg(%r)" % (self.value,)
@property
def _numba_type_(self):
return types.Omitted(self.value)
class CompilingCounter:
"""
A simple counter that increment in __enter__ and decrement in __exit__.
"""
def __init__(self):
self.counter = 0
def __enter__(self):
assert self.counter >= 0
self.counter += 1
def __exit__(self, *args, **kwargs):
self.counter -= 1
assert self.counter >= 0
def __bool__(self):
return self.counter > 0
__nonzero__ = __bool__
class _DispatcherBase(_dispatcher.Dispatcher):
"""
Common base class for dispatcher Implementations.
"""
__numba__ = "py_func"
def __init__(
self, arg_count, py_func, pysig, can_fallback, exact_match_required
):
self._tm = default_type_manager
# A mapping of signatures to compile results
self.overloads = collections.OrderedDict()
self.py_func = py_func
# other parts of Numba assume the old Python 2 name for code object
self.func_code = get_code_object(py_func)
# but newer python uses a different name
self.__code__ = self.func_code
# a place to keep an active reference to the types of the active call
self._types_active_call = set()
# Default argument values match the py_func
self.__defaults__ = py_func.__defaults__
argnames = tuple(pysig.parameters)
default_values = self.py_func.__defaults__ or ()
defargs = tuple(OmittedArg(val) for val in default_values)
try:
lastarg = list(pysig.parameters.values())[-1]
except IndexError:
has_stararg = False
else:
has_stararg = lastarg.kind == lastarg.VAR_POSITIONAL
_dispatcher.Dispatcher.__init__(
self,
self._tm.get_pointer(),
arg_count,
self._fold_args,
argnames,
defargs,
can_fallback,
has_stararg,
exact_match_required,
)
self.doc = py_func.__doc__
self._compiling_counter = CompilingCounter()
weakref.finalize(self, self._make_finalizer())
def _compilation_chain_init_hook(self):
"""
This will be called ahead of any part of compilation taking place (this
even includes being ahead of working out the types of the arguments).
This permits activities such as initialising extension entry points so
that the compiler knows about additional externally defined types etc
before it does anything.
"""
entrypoints.init_all()
def _reset_overloads(self):
self._clear()
self.overloads.clear()
def _make_finalizer(self):
"""
Return a finalizer function that will release references to
related compiled functions.
"""
overloads = self.overloads
targetctx = self.targetctx
# Early-bind utils.shutting_down() into the function's local namespace
# (see issue #689)
def finalizer(shutting_down=utils.shutting_down):
# The finalizer may crash at shutdown, skip it (resources
# will be cleared by the process exiting, anyway).
if shutting_down():
return
# This function must *not* hold any reference to self:
# we take care to bind the necessary objects in the closure.
for cres in overloads.values():
try:
targetctx.remove_user_function(cres.entry_point)
except KeyError: # noqa: PERF203
pass
return finalizer
@property
def signatures(self):
"""
Returns a list of compiled function signatures.
"""
return list(self.overloads)
@property
def nopython_signatures(self):
return [
cres.signature
for cres in self.overloads.values()
if not cres.objectmode