-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathtile_kernel.cpp
More file actions
6125 lines (5222 loc) · 230 KB
/
Copy pathtile_kernel.cpp
File metadata and controls
6125 lines (5222 loc) · 230 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: Apache-2.0
#include "tile_kernel.h"
#include "check.h"
#include "compiled_host.h"
#include "cuda_loader.h"
#include "cuda_helper.h"
#include "hash_map.h"
#include "ipc_util.h"
#include "launch_helper.h"
#include "py.h"
#include "ref_ptr.h"
#include "stream_buffer.h"
#include "tensor_map.h"
#include "vec.h"
#include <cuda.h>
#include <dlpack.h>
#include <array>
#include <memory>
#include <algorithm>
#include <optional>
#include <utility>
static PyObject* g___cuda_array_interface___pyunicode;
static PyObject* g_typestr_pyunicode;
static PyObject* g_shape_pyunicode;
static PyObject* g_data_pyunicode;
static PyObject* g_strides_pyunicode;
static PyObject* g___dlpack___pyunicode;
static PyObject* g_compile_pyunicode;
static PyObject* g_dynamic_shared_memory_bytes_pyunicode;
static PyObject* g_cooperative_pyunicode;
static PyObject* g_block_in_cluster_count_pyunicode;
static PyObject* g_preferred_block_in_cluster_count_pyunicode;
static PyObject* g_programmatic_dependent_launch_pyunicode;
static PyObject* g___dataclass_fields___pyunicode;
static PyObject* g_torch_pyunicode;
static PyObject* g_cupy_pyunicode;
static PyObject* g_cuda_stream_pyunicode;
static PyObject* g_ptr_pyunicode;
static PyObject* g_numba_cuda_pyunicode;
static PyObject* g_cuda_bindings_driver_pyunicode;
static PyObject* g_enum_Enum_type;
static PyObject* g_default_tile_context;
static constexpr const char* kFakeArrayDTypeAttr = "_cuda_lang_fake_array_dtype";
static constexpr const char* kFakeArrayNdimAttr = "_cuda_lang_fake_array_ndim";
static constexpr const char* kFakePointerDTypeAttr = "_cuda_lang_fake_pointer_dtype";
static constexpr const char* kTensorMapBytesAttr = "_cuda_lang_tensor_map_bytes";
static constexpr const char* kNativeSourceDTypeAttr = "_native_source_dtype";
static PyObject* get_datatype_module(GlobalLock&) {
static PyObject* m;
if (!m) m = PyImport_ImportModule("cuda.tile._datatype");
return m;
}
static PyTypeObject* get_dtype_class(GlobalLock& lock) {
static PyTypeObject* c;
static bool cached;
if (!cached) {
cached = true;
PyObject* datatype_mod = get_datatype_module(lock);
if (!datatype_mod) return nullptr;
PyPtr dtype_class = getattr(datatype_mod, "DType");
if (!dtype_class) return nullptr;
if (!PyType_Check(dtype_class.get())) return nullptr;
c = reinterpret_cast<PyTypeObject*>(dtype_class.release());
}
return c;
}
static PyObject* get_signature_module(GlobalLock&) {
static PyObject* m;
if (!m) m = PyImport_ImportModule("cuda.tile.compilation._signature");
return m;
}
namespace { struct ImportedTypeChecker {
PyTypeObject* cached_super_type_;
bool is_cached_;
// Check whether `sub_ty` is a subtype of
// "super_module_name[.super_submodule_name].super_type_name"
// without importing the `super_module_name`.
bool is_subtype_of(PyTypeObject* sub_ty,
PyObject* super_module_name,
const char* super_submodule_name, // may be null
const char* super_type_name) {
if (!is_cached_) {
// Use PyImport_GetModule() rather than PyImport_Import() to avoid importing the module.
// If the module is not in sys.modules, then there is no way there can be a subtype
// of a type defined in that module.
ErrorGuard guard;
PyPtr mod = steal(PyImport_GetModule(super_module_name));
// Can't flip is_cached_ to true just yet -- the module may get imported later.
if (!mod) return false;
is_cached_ = true;
if (super_submodule_name) {
mod = try_getattr(mod, super_submodule_name);
if (!mod) return false;
}
PyPtr item = try_getattr(mod, super_type_name);
if (!item || !PyType_Check(item.get()))
return false;
cached_super_type_ = reinterpret_cast<PyTypeObject*>(item.get());
}
return cached_super_type_ && PyType_IsSubtype(sub_ty, cached_super_type_);
}
}; }
static bool is_torch_tensor_subtype(PyTypeObject* ty, GlobalLock&) {
static ImportedTypeChecker checker;
return checker.is_subtype_of(ty, g_torch_pyunicode, nullptr, "Tensor");
}
static bool is_torch_cuda_stream_subtype(PyTypeObject* ty, GlobalLock&) {
static ImportedTypeChecker checker;
return checker.is_subtype_of(ty, g_torch_pyunicode, "cuda", "Stream");
}
static bool is_cupy_cuda_stream_subtype(PyTypeObject* ty, GlobalLock&) {
static ImportedTypeChecker checker;
return checker.is_subtype_of(ty, g_cupy_pyunicode, "cuda", "Stream");
}
static bool is_numba_cuda_driver_stream_subtype(PyTypeObject* ty, GlobalLock&) {
static ImportedTypeChecker checker;
return checker.is_subtype_of(ty, g_numba_cuda_pyunicode, "driver", "Stream");
}
static bool is_cuda_bindings_driver_custream_subtype(PyTypeObject* ty, GlobalLock&) {
static ImportedTypeChecker checker;
return checker.is_subtype_of(ty, g_cuda_bindings_driver_pyunicode, nullptr, "CUstream");
}
static PyObject* try_get_torch_to_dlpack_func(GlobalLock&) {
static PyObject* func;
static bool cached;
if (!cached) {
cached = true;
if (PyPtr torch_C = try_import("torch._C"))
func = try_getattr(torch_C, "_to_dlpack").release();
}
return func;
}
constexpr uint8_t BYTE_BITWIDTH = 8;
constexpr uint8_t DIVISOR_16 = 16;
constexpr uint8_t TMA_MAX_NDIM = 5;
namespace { union ArraySpecializationBits {
struct {
bool baseptr_16byte_aligned : 1;
bool disjoint_elements : 1;
unsigned stride_16byte_divisible : TMA_MAX_NDIM;
unsigned stride_one : TMA_MAX_NDIM;
unsigned shape_divisible_by_16 : TMA_MAX_NDIM;
unsigned shape_one : TMA_MAX_NDIM;
};
uint64_t u64;
bool is_stride_16byte_divisible(size_t dim) const {
return dim < TMA_MAX_NDIM && ((stride_16byte_divisible >> dim) & 1);
}
bool is_stride_one(size_t dim) const {
return dim < TMA_MAX_NDIM && ((stride_one >> dim) & 1);
}
bool is_shape_divisible_by_16(size_t dim) const {
return dim < TMA_MAX_NDIM && ((shape_divisible_by_16 >> dim) & 1);
}
bool is_shape_one(size_t dim) const {
return dim < TMA_MAX_NDIM && ((shape_one >> dim) & 1);
}
}; }
static_assert(sizeof(ArraySpecializationBits) == 8);
#ifdef CUDA_TILE_ENABLE_DEV_FEATURES
#define ENABLE_CCONV_V3
#endif
enum class CallConvVersion {
CutilePython_V1 = 1,
CutilePython_V2 = 2,
#ifdef ENABLE_CCONV_V3
CutilePython_V3 = 3,
#endif
};
namespace { struct CallingConvention {
CallConvVersion version;
inline bool operator== (const CallingConvention& other) const {
return version == other.version;
}
static PyTypeObject pytype;
}; }
static PyObject* CallingConvention_get_name(PyObject* self, void*) {
CallingConvention& cconv = py_unwrap<CallingConvention>(self);
return to_pyunicode("cutile_python_v", static_cast<int>(cconv.version)).release();
}
static PyObject* CallingConvention_get_code(PyObject* self, void*) {
CallingConvention& cconv = py_unwrap<CallingConvention>(self);
return to_pyunicode("t", static_cast<int>(cconv.version)).release();
}
static PyObject* CallingConvention_get_version(PyObject* self, void*) {
CallingConvention& cconv = py_unwrap<CallingConvention>(self);
return PyLong_FromLong(static_cast<long>(cconv.version));
}
static PyObject* CallingConvention_repr(PyObject* self) {
PyPtr name = getattr(self, "name");
if (!name) return nullptr;
PyPtr code = getattr(self, "code");
if (!code) return nullptr;
return to_pyunicode("CallingConvention(", use_repr(name), ", ", use_repr(code), ")").release();
}
static PyGetSetDef CallingConvention_getsetters[] = {
{"name", CallingConvention_get_name, nullptr},
{"code", CallingConvention_get_code, nullptr},
{"version", CallingConvention_get_version, nullptr},
{} // sentinel
};
static PyPtr get_cconv(CallConvVersion version) {
PyObject* ret = CallingConvention::pytype.tp_new(&CallingConvention::pytype, nullptr, nullptr);
if (!ret) return {};
CallingConvention& cconv = py_unwrap<CallingConvention>(ret);
cconv.version = version;
return steal(ret);
}
static PyObject* get_cached_cconv(CallConvVersion version, PyObject** cache) {
if (!*cache) {
PyPtr cconv = get_cconv(version);
if (!cconv) return nullptr;
*cache = cconv.release();
}
return Py_NewRef(*cache);
}
static PyObject* CallingConvention_cutile_python_v1(PyObject*, PyObject*) {
static PyObject* c;
GlobalLock lock;
return get_cached_cconv(CallConvVersion::CutilePython_V1, &c);
}
static PyObject* CallingConvention_cutile_python_v2(PyObject*, PyObject*) {
static PyObject* c;
GlobalLock lock;
return get_cached_cconv(CallConvVersion::CutilePython_V2, &c);
}
#ifdef ENABLE_CCONV_V3
static PyObject* CallingConvention_cutile_python_v3(PyObject*, PyObject*) {
static PyObject* c;
GlobalLock lock;
return get_cached_cconv(CallConvVersion::CutilePython_V3, &c);
}
#endif
static PyPtr parse_cutile_python_calling_convention(const char* s) {
if (s[0] == '1' && !s[1])
return get_cconv(CallConvVersion::CutilePython_V1);
if (s[0] == '2' && !s[1])
return get_cconv(CallConvVersion::CutilePython_V2);
#ifdef ENABLE_CCONV_V3
if (s[0] == '3' && !s[1])
return get_cconv(CallConvVersion::CutilePython_V3);
#endif
return {};
}
static PyObject* CallingConvention_from_code(PyObject*, PyObject* args) {
const char* code;
if (!PyArg_ParseTuple(args, "s", &code))
return nullptr;
if (code[0] == 't') {
PyPtr ret = parse_cutile_python_calling_convention(code + 1);
if (ret) return ret.release();
}
raise(PyExc_ValueError, "Unknown calling convention code '", code, "'");
return nullptr;
}
static PyMethodDef CallingConvention_methods[] = {
{"from_code", CallingConvention_from_code, METH_VARARGS | METH_STATIC, nullptr},
{"cutile_python_v1", CallingConvention_cutile_python_v1, METH_NOARGS | METH_STATIC,
"cutile_python_v1()\n"
"--\n\n"
"Returns the ``cutile_python_v1`` calling convention.\n\n"
},
{"cutile_python_v2", CallingConvention_cutile_python_v2, METH_NOARGS | METH_STATIC,
"cutile_python_v2()\n"
"--\n\n"
"Returns the ``cutile_python_v2`` calling convention.\n\n"
},
#ifdef ENABLE_CCONV_V3
{"cutile_python_v3", CallingConvention_cutile_python_v3, METH_NOARGS | METH_STATIC,
"cutile_python_v3()\n"
"--\n\n"
"Returns the ``cutile_python_v3`` calling convention.\n\n"
},
#endif
{} // sentinel
};
PyTypeObject CallingConvention::pytype = {
.tp_name = "cuda.tile.compilation.CallingConvention",
.tp_basicsize = sizeof(PythonWrapper<CallingConvention>),
.tp_dealloc = pywrapper_dealloc<CallingConvention>,
.tp_repr = CallingConvention_repr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_richcompare = pywrapper_richcompare_via_operator_equals<CallingConvention>,
.tp_methods = CallingConvention_methods,
.tp_getset = CallingConvention_getsetters,
.tp_new = pywrapper_new<CallingConvention>,
};
static Status enable_maximum_dynamic_shared_memory(const DriverApi *driver,
const CUkernel kernel,
const char *func_name) {
int device_count;
CUresult res = driver->cuDeviceGetCount(&device_count);
if (res != CUDA_SUCCESS) {
return raise(PyExc_RuntimeError, "Failed to get device count: ",
get_cuda_error(driver, res));
}
for (int device_ordinal = 0; device_ordinal < device_count;
device_ordinal++) {
CUdevice device;
res = driver->cuDeviceGet(&device, device_ordinal);
if (res != CUDA_SUCCESS) {
return raise(PyExc_RuntimeError, "Failed to get device ", device_ordinal, ": ",
get_cuda_error(driver, res));
}
int max_smem;
res = driver->cuDeviceGetAttribute(
&max_smem, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN,
device);
if (res != CUDA_SUCCESS) {
return raise(PyExc_RuntimeError,
"Failed to get maximum shared memory for device ", device_ordinal, ": ",
get_cuda_error(driver, res));
}
int static_smem;
res = driver->cuKernelGetAttribute(
&static_smem, CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES, kernel, device);
if (res != CUDA_SUCCESS) {
return raise(PyExc_RuntimeError,
"Failed to get static shared memory for kernel ", func_name, ": ",
get_cuda_error(driver, res));
}
if (max_smem < static_smem) {
// If the user's program uses more static shared memory than the
// current device has available, then we cannot request enough
// shared memory. If the user has another device capable of running
// their program, they must run on that device and errors will be
// reported at launch time.
continue;
}
int largest_possible_dynamic_smem = max_smem - static_smem;
res = driver->cuKernelSetAttribute(
CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
largest_possible_dynamic_smem, kernel, device);
if (res != CUDA_SUCCESS) {
return raise(PyExc_RuntimeError,
"Failed to set dynamic shared memory for kernel ", func_name, ": ",
get_cuda_error(driver, res));
}
}
return OK;
}
// X(Name, #Attrs, MinStack, StackEffect)
#define FOREACH_SIZE_OPCODE(X) \
X(Const, 1, 0, 1) \
X(KernelArgI32, 1, 0, 1) \
X(KernelArgI64, 1, 0, 1) \
X(Add, 0, 2, -1) \
X(Mul, 0, 2, -1) \
X(RoundUpToPow2, 1, 1, 0)
#define SIZE_OPCODE_ENUM_ENTRY(name, _nattr, _min_st, _stack_eff) \
name,
enum class SizeOpcode : uint8_t {
FOREACH_SIZE_OPCODE(SIZE_OPCODE_ENUM_ENTRY)
};
#define SIZE_OPCODE_PARSE(name, nattr, min_st, stack_eff) \
if (!PyUnicode_CompareWithASCIIString(opcode_str, #name)) { \
*num_attrs = nattr; \
*min_stack = min_st; \
*stack_effect = stack_eff; \
return SizeOpcode::name; \
}
static Result<SizeOpcode> size_opcode_parse(PyObject* opcode_str,
int* num_attrs, int* min_stack, int* stack_effect) {
FOREACH_SIZE_OPCODE(SIZE_OPCODE_PARSE);
return raise(PyExc_ValueError, "Invalid opcode string ", use_repr(opcode_str));
}
namespace { struct HostProgram {
enum { kMaxStackDepth = 32 };
Vec<SizeOpcode> opcodes;
Vec<int64_t> op_attrs;
}; }
namespace { struct HoistedTensorMap {
enum { kMaxRank = 5 };
CUtensorMapDataType data_type;
uint32_t rank;
uint32_t base_ptr_param_idx;
HostProgram shape_stride_program;
uint32_t box_dim[kMaxRank];
uint32_t traversal_steps[kMaxRank];
CUtensorMapInterleave interleave;
CUtensorMapSwizzle swizzle;
CUtensorMapL2promotion l2_promotion;
CUtensorMapFloatOOBfill oob_fill;
}; }
struct TileKernel {
CudaKernel cukernel;
HostProgram dyn_smem_size_prog;
Vec<HoistedTensorMap> hoisted_tensor_maps;
// For an identity constant (e.g., Enum values), the key of KernelMap contains the constant's
// address encoded as an int64_t. Just by itself, this is prone to the ABA problem:
// if the constant is freed, another object could be allocated at the same address.
// Thus, for each such constant, we store a reference to it.
Vec<PyPtr> constant_refs;
};
struct KernelImage {
PyPtr cubin;
PyPtr symbol;
};
using KernelMap = HashMap<Vec<int64_t>, TileKernel>;
using HostProgramMap = HashMap<Vec<int64_t>, PyPtr>;
static ArenaOffset arena_alloc_words(Arena& arena, size_t count) {
ArenaOffset offset = arena.size();
arena.resize(offset + count);
return offset;
}
static void** make_launch_params(LaunchHelper& helper) {
helper.launch_params.clear();
helper.launch_params.reserve(helper.cuarg_offsets.size());
for (ArenaOffset offset : helper.cuarg_offsets)
helper.launch_params.push_back(&helper.arena[offset]);
return helper.launch_params.data();
}
template <size_t AlignmentBytes>
static void arena_pad_to_alignment(Arena& arena) {
static_assert(AlignmentBytes % sizeof(Word) == 0);
constexpr size_t AlignmentWords = AlignmentBytes / sizeof(Word);
size_t padded_size = ((arena.size() + AlignmentWords - 1) / AlignmentWords)
* AlignmentWords;
arena.resize(padded_size);
}
static ArenaOffset push_single_word_cuarg(LaunchHelper& helper, Word word) {
ArenaOffset offset = arena_alloc_words(helper.arena, 1);
helper.arena[offset] = word;
helper.cuarg_offsets.push_back(offset);
return offset;
}
static ProtectedByGlobalLock<LaunchHelper*> g_helper_freelist;
namespace { struct LaunchHelperDeleter {
void operator() (LaunchHelper* helper) const {
GlobalLock lock;
LaunchHelper*& freelist = g_helper_freelist.get(lock);
helper->pyarg_refs.clear();
helper->next_free = freelist;
freelist = helper;
}
}; }
using LaunchHelperPtr = std::unique_ptr<LaunchHelper, LaunchHelperDeleter>;
static LaunchHelperPtr launch_helper_get(GlobalLock& lock) {
LaunchHelper*& freelist = g_helper_freelist.get(lock);
if (freelist) {
LaunchHelper* ret = freelist;
freelist = ret->next_free;
ret->pyarg_types_breadth_first.clear();
ret->pyarg_objs_breadth_first.clear();
ret->leaf_pyarg_objs.clear();
ret->can_specialize_for_shape = true;
return LaunchHelperPtr(ret);
} else {
return LaunchHelperPtr(new LaunchHelper());
}
}
namespace { struct DataclassInfo : SimpleRefcount<DataclassInfo> {
PyPtr dataclass;
Vec<PyPtr> field_names;
DataclassInfo(PyPtr dataclass, Vec<PyPtr> field_names)
: dataclass(std::move(dataclass)), field_names(std::move(field_names))
{ }
}; }
struct AggregateArgType {
enum Kind {
Tuple,
#ifdef ENABLE_CCONV_V3
Dataclass
#endif
};
Kind kind;
RefPtr<DataclassInfo> dataclass_info;
bool operator== (const AggregateArgType& other) const {
if (kind != other.kind) return false;
switch (kind) {
case Kind::Tuple:
return true;
#ifdef ENABLE_CCONV_V3
case Kind::Dataclass:
return dataclass_info->dataclass == other.dataclass_info->dataclass;
#endif
}
CHECK(false);
}
};
// Kinds of constant values that are allowed as kernel arguments.
#define FOREACH_CONSTANT_KIND(X) \
X(Bool) \
X(Int) \
X(Float) \
X(None_) \
X(String) \
X(Enum) \
X(NativeDType) \
X(ForeignDType)
#define CONSTANT_KIND_ENTRY(name) name,
enum class ConstantKind : uint8_t {
FOREACH_CONSTANT_KIND(CONSTANT_KIND_ENTRY)
};
#define CONSTANT_KIND_NAME_STR(name) #name,
static const char g_constant_kind_names[][16] = {
FOREACH_CONSTANT_KIND(CONSTANT_KIND_NAME_STR)
};
static PyObject* g_constant_kind_enum;
static PyPtr define_constant_kind_enum() {
PyPtr entries = steal(PyDict_New());
if (!entries) return {};
for (size_t i = 0; i < std::extent_v<decltype(g_constant_kind_names)>; ++i) {
PyPtr value = steal(PyLong_FromUnsignedLongLong(i));
if (!value) return {};
if (PyDict_SetItemString(entries.get(), g_constant_kind_names[i], value.get()))
return {};
}
return steal(PyObject_CallFunction(
g_enum_Enum_type, "sO", "ConstantKind", entries.get()));
}
struct ParameterKind {
enum Category : uint8_t {
ConstantBool,
ConstantInt,
ConstantFloat,
ConstantNone,
IdentityConstant, // constant that can be compared via object identity, e.g. an Enum value
Array,
Pointer,
Stream,
TensorMap,
Boolean,
Integer,
Float,
List,
AggregateBegin,
AggregateEnd,
};
Category category;
AggregateArgType agg_type; // Only set when `category == AggregateBegin`
bool operator== (const ParameterKind& other) const {
if (category != other.category) return false;
return category == AggregateBegin ? agg_type == other.agg_type : true;
}
bool operator!= (const ParameterKind& other) const {
return !(*this == other);
}
};
struct ArgumentFamily : SimpleRefcount<ArgumentFamily> {
Vec<ParameterKind> param_kinds;
KernelMap kernels_by_constants;
HostProgramMap host_programs_by_constants;
explicit ArgumentFamily(Vec<ParameterKind>&& param_kinds)
: param_kinds(std::move(param_kinds))
{}
};
enum class PythonArgKind : uint8_t {
ConstantBool,
ConstantInt,
ConstantFloat,
ConstantNone,
ConstantString,
IdentityConstant,
ForeignDTypeConstant,
// A torch.Tensor that we can access via torch._C._to_dlpack
TorchTensorDlpack,
// An object with __dlpack__ method
DlpackArray,
// An object with __cuda_array_interface__
CudaArray,
// Internal fake array used when creating a compiled-host native launch site.
FakeArray,
// Internal fake pointer used when creating a compiled-host native launch site.
FakePointer,
// A CUDA stream wrapper supported by parse_stream().
Stream,
// A cuda.lang tiled tensor-map descriptor.
TensorMap,
// Python `bool`,
PyBool,
// Python `int`,
PyLong,
// Python `float`
PyFloat,
// Python `list`
PyList,
};
static inline PythonArgKind constant_kind_as_arg_kind(ConstantKind kind) {
switch (kind) {
case ConstantKind::Bool: return PythonArgKind::ConstantBool;
case ConstantKind::Int: return PythonArgKind::ConstantInt;
case ConstantKind::Float: return PythonArgKind::ConstantFloat;
case ConstantKind::None_: return PythonArgKind::ConstantNone;
case ConstantKind::String: return PythonArgKind::ConstantString;
case ConstantKind::Enum: return PythonArgKind::IdentityConstant;
case ConstantKind::NativeDType: return PythonArgKind::IdentityConstant;
case ConstantKind::ForeignDType: return PythonArgKind::ForeignDTypeConstant;
}
CHECK_UNREACHABLE;
}
static ParameterKind::Category param_category_from_pyarg_kind(PythonArgKind k) {
switch (k) {
case PythonArgKind::ConstantBool: return ParameterKind::ConstantBool;
case PythonArgKind::ConstantInt: return ParameterKind::ConstantInt;
case PythonArgKind::ConstantFloat: return ParameterKind::ConstantFloat;
case PythonArgKind::ConstantNone: return ParameterKind::ConstantNone;
case PythonArgKind::ConstantString: return ParameterKind::IdentityConstant;
case PythonArgKind::IdentityConstant: return ParameterKind::IdentityConstant;
case PythonArgKind::ForeignDTypeConstant: return ParameterKind::IdentityConstant;
case PythonArgKind::TorchTensorDlpack: return ParameterKind::Array;
case PythonArgKind::DlpackArray: return ParameterKind::Array;
case PythonArgKind::CudaArray: return ParameterKind::Array;
case PythonArgKind::FakeArray: return ParameterKind::Array;
case PythonArgKind::FakePointer: return ParameterKind::Pointer;
case PythonArgKind::Stream: return ParameterKind::Stream;
case PythonArgKind::TensorMap: return ParameterKind::TensorMap;
case PythonArgKind::PyBool: return ParameterKind::Boolean;
case PythonArgKind::PyLong: return ParameterKind::Integer;
case PythonArgKind::PyFloat: return ParameterKind::Float;
case PythonArgKind::PyList: return ParameterKind::List;
}
CHECK_UNREACHABLE;
}
static constexpr int u8_pair(uint8_t x, uint8_t y) {
return x | (y << 8);
}
#define FOREACH_DLPACK_DTYPE(X) \
X(kDLBool, 8, "bool_") \
\
X(kDLInt, 8, "int8") \
X(kDLInt, 16, "int16") \
X(kDLInt, 32, "int32") \
X(kDLInt, 64, "int64") \
\
X(kDLUInt, 8, "uint8") \
X(kDLUInt, 16, "uint16") \
X(kDLUInt, 32, "uint32") \
X(kDLUInt, 64, "uint64") \
\
X(kDLFloat, 16, "float16") \
X(kDLFloat, 32, "float32") \
X(kDLFloat, 64, "float64") \
\
X(kDLBfloat, 16, "bfloat16") \
\
X(kDLFloat8_e4m3fn, 8, "float8_e4m3fn") \
X(kDLFloat8_e5m2, 8, "float8_e5m2") \
X(kDLFloat8_e8m0fnu, 8, "float8_e8m0fnu")
#define DLPACK_DTYPE_NAME_CASE(code, bits, name) \
case u8_pair(code, bits): return name;
static Result<const char*> dtype_name(DLDataType dtype) {
if (dtype.lanes != 1)
return raise(PyExc_TypeError, "Array dtypes with multiple lanes are not supported");
switch (u8_pair(dtype.code, dtype.bits)) {
FOREACH_DLPACK_DTYPE(DLPACK_DTYPE_NAME_CASE)
default:
return raise(PyExc_TypeError, "Unsupported array dtype");
}
}
static PyPtr dtype_to_python(DLDataType dtype, GlobalLock& lock) {
PyObject* dtype_module = get_datatype_module(lock);
if (!dtype_module) return {};
Result<const char*> name = dtype_name(dtype);
if (!name.is_ok()) return {};
return getattr(dtype_module, *name);
}
#define DLPACK_DTYPE_NAME(_code, _bits, name) name,
#define DLPACK_DTYPE_TYPE(code, bits, _name) {code, bits, 1},
static constexpr char dlpack_dtype_names[][16] = { FOREACH_DLPACK_DTYPE(DLPACK_DTYPE_NAME) };
static constexpr DLDataType dlpack_dtypes[] = { FOREACH_DLPACK_DTYPE(DLPACK_DTYPE_TYPE) };
static Result<std::optional<DLDataType>> dtype_from_python(PyObject* dtype) {
PyPtr py_name = getattr(dtype, "name");
if (!py_name) return ErrorRaised;
constexpr size_t n = std::extent_v<decltype(dlpack_dtype_names)>;
static_assert(n == std::extent_v<decltype(dlpack_dtypes)>);
for (size_t i = 0; i < n; ++i) {
if (!PyUnicode_CompareWithASCIIString(py_name.get(), dlpack_dtype_names[i]))
return {dlpack_dtypes[i]};
}
return {std::nullopt};
}
struct ForeignDTypeInfo {
std::optional<DLDataType> dlpack_dtype;
PyPtr native_dtype;
};
enum ForeignDtypeKind {
kTorch = 1,
kNumpy = 2,
kMlDTypes = 8
};
static constexpr
struct { char name[16]; DLDataType type; int lib_mask; } foreign_dtype_table[] = {
{"bool", {kDLBool, 8, 1}, kTorch },
{"bool_", {kDLBool, 8, 1}, kNumpy },
{"uint8", {kDLUInt, 8, 1}, kTorch | kNumpy },
{"uint16", {kDLUInt, 16, 1}, kTorch | kNumpy },
{"uint32", {kDLUInt, 32, 1}, kTorch | kNumpy},
{"uint64", {kDLUInt, 64, 1}, kTorch | kNumpy},
{"int8", {kDLInt, 8, 1}, kTorch | kNumpy},
{"int16", {kDLInt, 16, 1}, kTorch | kNumpy},
{"int32", {kDLInt, 32, 1}, kTorch | kNumpy},
{"int64", {kDLInt, 64, 1}, kTorch | kNumpy},
{"float16", {kDLFloat, 16, 1}, kTorch | kNumpy},
{"float32", {kDLFloat, 32, 1}, kTorch | kNumpy},
{"float64", {kDLFloat, 64, 1}, kTorch | kNumpy},
{"bfloat16", {kDLBfloat, 16, 1}, kTorch | kMlDTypes},
{"float8_e4m3fn", {kDLFloat8_e4m3fn, 8, 1}, kTorch | kMlDTypes},
{"float8_e5m2", {kDLFloat8_e5m2, 8, 1}, kTorch | kMlDTypes},
{"float8_e8m0fnu", {kDLFloat8_e8m0fnu, 8, 1}, kTorch | kMlDTypes}
};
static void register_foreign_dtypes_common(PyObject* foreign_module,
PyObject* numpy_dtype_class,
ForeignDtypeKind bit,
HashMap<PyPtr, ForeignDTypeInfo>* registry,
GlobalLock& lock) {
for (const auto& entry : foreign_dtype_table) {
if (!(entry.lib_mask & bit)) continue;
PyPtr foreign_pyobj = try_getattr(foreign_module, entry.name);
if (!foreign_pyobj) continue;
ErrorGuard guard;
PyPtr native_pyobj = dtype_to_python(entry.type, lock);
if (!native_pyobj) continue;
registry->insert(foreign_pyobj, ForeignDTypeInfo{entry.type, native_pyobj});
if (numpy_dtype_class) {
PyPtr numpy_dtype_desc = steal(
PyObject_CallOneArg(numpy_dtype_class, foreign_pyobj.get()));
if (numpy_dtype_desc)
registry->insert(std::move(numpy_dtype_desc),
ForeignDTypeInfo{entry.type, std::move(native_pyobj)});
}
}
}
static void register_torch_dtypes(HashMap<PyPtr, ForeignDTypeInfo>* registry,
GlobalLock& lock) {
PyPtr torch = try_import("torch");
if (torch)
register_foreign_dtypes_common(torch.get(), nullptr, kTorch, registry, lock);
}
static void register_numpy_and_ml_dtypes(HashMap<PyPtr, ForeignDTypeInfo>* registry,
GlobalLock& lock) {
PyPtr numpy = try_import("numpy");
if (!numpy) return;
PyPtr numpy_dtype_class = try_getattr(numpy, "dtype");
register_foreign_dtypes_common(numpy.get(), numpy_dtype_class.get(), kNumpy, registry, lock);
PyPtr ml_dtypes = try_import("ml_dtypes");
if (ml_dtypes)
register_foreign_dtypes_common(ml_dtypes.get(), numpy_dtype_class.get(), kMlDTypes,
registry, lock);
}
static HashMap<PyPtr, ForeignDTypeInfo>* get_foreign_dtype_registry(GlobalLock& lock) {
static HashMap<PyPtr, ForeignDTypeInfo>* registry;
if (!registry) {
auto reg = std::make_unique<HashMap<PyPtr, ForeignDTypeInfo>>();
register_torch_dtypes(reg.get(), lock);
register_numpy_and_ml_dtypes(reg.get(), lock);
registry = reg.release();
}
return registry;
}
static PyObject* foreign_dtype_object_register(PyObject* self, PyObject* args) {
PyObject* foreign_dtype;
PyObject* native_dtype;
if (!PyArg_ParseTuple(args, "OO", &foreign_dtype, &native_dtype))
return nullptr;
Result<std::optional<DLDataType>> dtype_res = dtype_from_python(native_dtype);
if (!dtype_res.is_ok()) return nullptr;
GlobalLock lock;
get_foreign_dtype_registry(lock)->insert(newref(foreign_dtype),
ForeignDTypeInfo{*dtype_res, newref(native_dtype)});
return Py_NewRef(Py_None);
}
static PyObject* foreign_dtype_object_to_native(PyObject* self, PyObject* object) {
GlobalLock lock;
HashMap<PyPtr, ForeignDTypeInfo>::Item* item = get_foreign_dtype_registry(lock)->find(object);
return Py_NewRef(item ? item->value.native_dtype.get() : Py_None);
}
static std::optional<ConstantKind> classify_constant(PyObject* obj, bool kernel_arg,
GlobalLock& lock) {
if (PyBool_Check(obj))
return ConstantKind::Bool;
if (PyLong_Check(obj))
return ConstantKind::Int;
if (PyFloat_Check(obj))
return ConstantKind::Float;
#ifndef ENABLE_CCONV_V3
if (!kernel_arg) {
#endif
if (obj == Py_None)
return ConstantKind::None_;
if (PyUnicode_CheckExact(obj))
return ConstantKind::String;
if (PyObject_TypeCheck(obj, reinterpret_cast<PyTypeObject*>(g_enum_Enum_type)))
return ConstantKind::Enum;
if (Py_IS_TYPE(obj, get_dtype_class(lock)))
return ConstantKind::NativeDType;
if (get_foreign_dtype_registry(lock)->find(obj))
return ConstantKind::ForeignDType;
#ifndef ENABLE_CCONV_V3
}
#endif
return std::nullopt;
}
static PyObject* py_classify_constant(PyObject* self, PyObject* args) {
PyObject* obj;
int kernel_arg;
if (!PyArg_ParseTuple(args, "Op", &obj, &kernel_arg))
return nullptr;
GlobalLock lock;
std::optional<ConstantKind> res = classify_constant(obj, kernel_arg, lock);
if (!res.has_value())
return Py_NewRef(Py_None);
return PyObject_GetAttrString(g_constant_kind_enum,
g_constant_kind_names[static_cast<size_t>(*res)]);
}
enum class StreamKind;
static std::optional<StreamKind> try_classify_stream_type(PyTypeObject* ty, GlobalLock& lock);
static Result<CUstream> parse_stream(PyObject* py_stream, GlobalLock& lock);
static std::optional<PythonArgKind> classify_nonconstant_arg(PyObject* arg, GlobalLock& lock) {
if (PyBool_Check(arg))
return PythonArgKind::PyBool;
if (PyLong_Check(arg))
return PythonArgKind::PyLong;
if (PyFloat_Check(arg))
return PythonArgKind::PyFloat;
if (PyList_Check(arg))
return PythonArgKind::PyList;