Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathtile_kernel.cpp
More file actions
3007 lines (2484 loc) · 108 KB
/
Copy pathtile_kernel.cpp
File metadata and controls
3007 lines (2484 loc) · 108 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 "cuda_loader.h"
#include "cuda_helper.h"
#include "hash_map.h"
#include "py.h"
#include "ref_ptr.h"
#include "stream_buffer.h"
#include "vec.h"
#include <cuda.h>
#include <dlpack.h>
#include <array>
#include <memory>
#include <algorithm>
#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_pdl_pyunicode;
static PyTypeObject* g_torch_Tensor_type;
static PyTypeObject* g_torch_cuda_Stream_type;
static PyObject* g_torch_to_dlpack_func;
static PyObject* g_default_tile_context;
static PyObject* get_datatype_module() {
static PyObject* m;
if (!m) m = PyImport_ImportModule("cuda.tile._datatype");
return m;
}
static PyObject* get_signature_module() {
static PyObject* m;
if (!m) m = PyImport_ImportModule("cuda.tile.compilation._signature");
return m;
}
#define FOREACH_TORCH_DTYPE(X) \
X(bool, 8, 1, kDLBool) \
X(uint8, 8, 1, kDLUInt) \
X(uint16, 16, 1, kDLUInt) \
X(uint32, 32, 1, kDLUInt) \
X(uint64, 64, 1, kDLUInt) \
X(int8, 8, 1, kDLInt) \
X(int16, 16, 1, kDLInt) \
X(int32, 32, 1, kDLInt) \
X(int64, 64, 1, kDLInt) \
X(float16, 16, 1, kDLFloat) \
X(float32, 32, 1, kDLFloat) \
X(float64, 64, 1, kDLFloat) \
X(bfloat16, 16, 1, kDLBfloat) \
X(float8_e4m3fn, 8, 1, kDLFloat8_e4m3fn) \
X(float8_e5m2, 8, 1, kDLFloat8_e5m2) \
X(float8_e8m0fnu, 8, 1, kDLFloat8_e8m0fnu)
#define DECLARE_TORCH_DTYPE_GLOBAL(name, bitwidth, lanes, typecode) \
static PyObject* g_torch_dtype_##name;
FOREACH_TORCH_DTYPE(DECLARE_TORCH_DTYPE_GLOBAL)
static PyTypeObject* g_cupy_cuda_Stream_type;
static PyTypeObject* g_numba_cuda_Stream_type;
static PyTypeObject* g_cuda_bindings_CUstream_type;
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;
};
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);
}
}; }
static_assert(sizeof(ArraySpecializationBits) == 8);
enum class CallConvVersion {
CutilePython_V1 = 1,
};
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 PyUnicode_FromFormat("cutile_python_v%d", cconv.version);
}
static PyObject* CallingConvention_get_code(PyObject* self, void*) {
CallingConvention& cconv = py_unwrap<CallingConvention>(self);
return PyUnicode_FromFormat("t%d", cconv.version);
}
static PyObject* CallingConvention_repr(PyObject* self) {
PyPtr name = steal(PyObject_GetAttrString(self, "name"));
if (!name) return nullptr;
PyPtr code = steal(PyObject_GetAttrString(self, "code"));
if (!code) return nullptr;
return PyUnicode_FromFormat("CallingConvention(%R, %R)", name.get(), code.get());
}
static PyGetSetDef CallingConvention_getsetters[] = {
{"name", CallingConvention_get_name, nullptr},
{"code", CallingConvention_get_code, 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* CallingConvention_cutile_python_v1(PyObject*, PyObject*) {
static PyObject* c;
if (!c) c = get_cconv(CallConvVersion::CutilePython_V1).release();
return Py_NewRef(c);
}
static PyPtr parse_cutile_python_calling_convention(const char* s) {
if (s[0] == '1' && !s[1])
return get_cconv(CallConvVersion::CutilePython_V1);
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();
}
return PyErr_Format(PyExc_ValueError, "Unknown calling convention code '%s'", code);
}
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"
},
{} // 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>,
};
// RAII wrapper around CUlibrary
namespace { class CudaLibrary {
public:
explicit CudaLibrary(const DriverApi* driver, CUlibrary lib) : driver_(driver), lib_(lib) {}
CudaLibrary(CudaLibrary&& other) : driver_(other.driver_), lib_(other.lib_) {
other.lib_ = nullptr;
}
CudaLibrary(const CudaLibrary&) = delete;
void operator=(const CudaLibrary&) = delete;
~CudaLibrary() {
if (lib_) {
CUresult res = driver_->cuLibraryUnload(lib_);
CHECK(res == CUDA_SUCCESS);
}
}
const CUlibrary& get() const {
return lib_;
}
private:
const DriverApi* driver_;
CUlibrary lib_;
}; }
static Result<CudaLibrary> load_cuda_library(const DriverApi* driver, const void* code) {
CUlibrary lib;
CUresult res = driver->cuLibraryLoadData(&lib, code, nullptr, nullptr, 0,
nullptr, nullptr, 0);
if (res == CUDA_SUCCESS)
return CudaLibrary(driver, lib);
return raise(PyExc_RuntimeError, "Failed to load CUDA library: %s",
get_cuda_error(driver, res));
}
struct CudaKernel {
CudaLibrary lib;
CUkernel kernel;
};
static Result<CudaKernel> load_cuda_kernel(const DriverApi* driver,
const char* cubin_data,
size_t cubin_size,
const char* func_name) {
(void) cubin_size;
Result<CudaLibrary> lib = load_cuda_library(driver, cubin_data);
if (!lib.is_ok()) return ErrorRaised;
CUkernel kernel;
CUresult res = driver->cuLibraryGetKernel(&kernel, lib->get(), func_name);
if (res == CUDA_SUCCESS)
return CudaKernel{std::move(*lib), kernel};
return raise(PyExc_RuntimeError, "Failed to get kernel %s from library: %s",
func_name, get_cuda_error(driver, res));
}
// 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 %R", opcode_str);
}
namespace { struct HostProgram {
enum { kMaxStackDepth = 32 };
Vec<SizeOpcode> opcodes;
Vec<int64_t> op_attrs;
}; }
namespace { struct HoistedTensorMap {
enum { kMaxRank = 5 };
CUtensorMapDataType dtype;
uint32_t item_size;
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;
};
using KernelMap = HashMap<Vec<int64_t>, TileKernel>;
struct KernelFamily : SimpleRefcount<KernelFamily> {
KernelMap kernels_by_constants;
};
using ArenaOffset = size_t;
union Word {
void* device_ptr;
int32_t i32;
int64_t i64;
size_t size;
float f32;
ArenaOffset arena_offset;
};
static_assert(sizeof(Word) == 8);
using Arena = Vec<Word, AlignedAllocation<Word, alignof(CUtensorMap)>>;
struct ListArg {
ArenaOffset base_ptr_cuarg;
size_t length;
ArenaOffset item_offsets; // [length], each word contains an `ArenaOffset` points to the item
size_t item_size_words;
};
struct LaunchHelper {
Vec<PyTypeObject*> pyarg_types;
Arena arena;
Vec<ArenaOffset> cuarg_offsets; // offsets into `arena`
Vec<void*> launch_params;
Vec<ListArg> list_args;
size_t total_list_data_size_words;
Vec<int64_t> constants;
CUcontext cuda_context;
LaunchHelper* next_free;
};
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 LaunchHelper* g_helper_freelist; // protected by the GIL or g_launch_mutex
namespace { struct LaunchHelperDeleter {
void operator() (LaunchHelper* helper) const {
helper->next_free = g_helper_freelist;
g_helper_freelist = helper;
}
}; }
#ifdef Py_GIL_DISABLED
static PyMutex g_launch_mutex = {0};
#endif
using LaunchHelperPtr = std::unique_ptr<LaunchHelper, LaunchHelperDeleter>;
static LaunchHelperPtr launch_helper_get() {
if (g_helper_freelist) {
LaunchHelper* ret = g_helper_freelist;
g_helper_freelist = ret->next_free;
return LaunchHelperPtr(ret);
} else {
return LaunchHelperPtr(new LaunchHelper());
}
}
enum class ParameterKind {
Array,
Boolean,
Integer,
Float,
List,
};
enum class PythonArgKind {
// 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,
// Python `bool`,
PyBool,
// Python `int`,
PyLong,
// Python `float`
PyFloat,
// Python `list`
PyList
};
static ParameterKind param_kind_from_pyarg_kind(PythonArgKind k) {
switch (k) {
case PythonArgKind::TorchTensorDlpack: return ParameterKind::Array;
case PythonArgKind::DlpackArray: return ParameterKind::Array;
case PythonArgKind::CudaArray: return ParameterKind::Array;
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(false);
}
static Result<PythonArgKind> classify_arg(PyObject* arg) {
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;
if (g_torch_Tensor_type && PyObject_TypeCheck(arg, g_torch_Tensor_type)) {
// Calling torch._C._to_dlpack(arg) is much faster than calling arg.__dlpack__()
// because it goes straight into C++ code, with no Python in between.
// So we always prefer that.
if (g_torch_to_dlpack_func)
return PythonArgKind::TorchTensorDlpack;
}
if (PyObject_HasAttr(arg, g___dlpack___pyunicode))
return PythonArgKind::DlpackArray;
if (PyObject_HasAttr(arg, g___cuda_array_interface___pyunicode))
return PythonArgKind::CudaArray;
return raise(PyExc_TypeError, "Unsupported argument type %s", Py_TYPE(arg)->tp_name);
}
struct PythonArgProfile {
RefPtr<KernelFamily> family;
Vec<PythonArgKind> arg_kinds;
};
// Concatenate values of two chars in a single unsigned integer
static constexpr unsigned char_pair(char x, char y) {
unsigned xu = static_cast<unsigned char>(x);
unsigned yu = static_cast<unsigned char>(y);
return ((xu << 8) | yu);
}
static Result<DLDataType> parse_typestr(PyObject* typestr) {
if (!PyUnicode_Check(typestr)) {
PyErr_SetString(PyExc_TypeError, "__cuda_array_interface__['typestr'] is not a string");
return ErrorRaised;
}
Py_ssize_t len;
const char* str = PyUnicode_AsUTF8AndSize(typestr, &len);
if (!str) return ErrorRaised;
if (len < 3) {
PyErr_Format(PyExc_TypeError, "__cuda_array_interface__['typestr'] has invalid value %S",
typestr);
return ErrorRaised;
}
// TODO: support big endian one day?
if (str[0] != '<' && str[0] != '|') {
PyErr_SetString(PyExc_TypeError, "Only little-endian types are supported");
return ErrorRaised;
}
DLDataType ret;
ret.lanes = 1;
switch (str[1]) {
case 'b': ret.code = kDLBool; break;
case 'i': ret.code = kDLInt; break;
case 'u': ret.code = kDLUInt; break;
case 'f': ret.code = kDLFloat; break;
case 'V': ret.code = kDLBfloat; break;
case 'c': ret.code = kDLComplex; break;
default:
PyErr_Format(PyExc_TypeError, "Unsupported type code %c", str[1]);
return ErrorRaised;
}
// str[3] is safe to index because there is always a NUL byte at the end
switch (char_pair(str[2], str[3])) {
case char_pair('1', '\0'): ret.bits = 8; break;
case char_pair('2', '\0'): ret.bits = 16; break;
case char_pair('4', '\0'): ret.bits = 32; break;
case char_pair('8', '\0'): ret.bits = 64; break;
case char_pair('1', '6'):
if (!str[4]) {
ret.bits = 64;
break;
}
[[fallthrough]];
default:
PyErr_Format(PyExc_TypeError, "Unsupported byte size in typestr: %s", str + 2);
return ErrorRaised;
}
return ret;
}
struct ArrayType {
DLDataType dtype;
size_t ndim;
unsigned index_bitwidth;
};
struct ArrayRepr {
ArrayType arrty;
ArenaOffset repr;
};
// This should compile to a no-op
static inline uint32_t dtype_as_uint(DLDataType dtype) {
return static_cast<uint32_t>(dtype.code)
| (static_cast<uint32_t>(dtype.bits) << 8)
| (static_cast<uint32_t>(dtype.lanes) << 16);
}
static inline DLDataType dtype_from_uint(uint32_t u) {
return DLDataType{
.code = static_cast<uint8_t>(u & 0xff),
.bits = static_cast<uint8_t>((u >> 8) & 0xff),
.lanes = static_cast<uint16_t>((u >> 16) & 0xffff),
};
}
static constexpr int u8_pair(uint8_t x, uint8_t y) {
return x | (y << 8);
}
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)) {
case u8_pair(kDLBool, 8): return "bool_";
case u8_pair(kDLInt, 8): return "int8";
case u8_pair(kDLInt, 16): return "int16";
case u8_pair(kDLInt, 32): return "int32";
case u8_pair(kDLInt, 64): return "int64";
case u8_pair(kDLUInt, 8): return "uint8";
case u8_pair(kDLUInt, 16): return "uint16";
case u8_pair(kDLUInt, 32): return "uint32";
case u8_pair(kDLUInt, 64): return "uint64";
case u8_pair(kDLFloat, 16): return "float16";
case u8_pair(kDLFloat, 32): return "float32";
case u8_pair(kDLFloat, 64): return "float64";
case u8_pair(kDLBfloat, 16): return "bfloat16";
case u8_pair(kDLFloat8_e4m3fn, 8): return "float8_e4m3fn";
case u8_pair(kDLFloat8_e5m2, 8): return "float8_e5m2";
case u8_pair(kDLFloat8_e8m0fnu, 8): return "float8_e8m0fnu";
default:
return raise(PyExc_TypeError, "Unsupported array dtype");
}
}
static PyPtr dtype_to_python(DLDataType dtype) {
PyObject* dtype_module = get_datatype_module();
if (!dtype_module) return {};
Result<const char*> name = dtype_name(dtype);
if (!name.is_ok()) return {};
return getattr(dtype_module, *name);
}
// Pack data type, array rank, and index bitwidth in a single int64_t so it
// could be used as a single constant for looking up the kernel in a family.
// Layout: [63: index_bitwidth (0=32, 1=64)] [62..32: ndim] [31..0: dtype]
static int64_t pack_array_type(const ArrayType& a) {
uint64_t dtype_u = static_cast<uint64_t>(dtype_as_uint(a.dtype));
uint64_t ndim_u = static_cast<uint64_t>(a.ndim);
uint64_t ibw_bit = (a.index_bitwidth == 64) ? 1ULL : 0ULL;
return static_cast<int64_t>(dtype_u | (ndim_u << 32) | (ibw_bit << 63));
}
static ArrayType unpack_array_type(int64_t c) {
uint64_t u = c;
uint32_t dtype = u & 0xffffffff;
uint32_t ndim = (u >> 32) & 0x7fffffff;
unsigned ibw = ((u >> 63) & 1) ? 64 : 32;
return {dtype_from_uint(dtype), ndim, ibw};
}
static Status fill_row_major_strides(unsigned index_bitwidth, Word* repr, size_t ndim) {
if (ndim == 0) return OK;
Word* shape = repr + 1 + ndim;
Word* stride = shape + ndim;
uint64_t prev_stride = 1;
(--stride)->i64 = 1;
for (size_t i = 0; i < ndim - 1; ++i) {
uint64_t new_stride = prev_stride * static_cast<uint64_t>((--shape)->i64);
if (index_bitwidth != 64 && new_stride > INT32_MAX)
return raise(PyExc_OverflowError, "stride is too big");
(--stride)->i64 = new_stride;
prev_stride = new_stride;
}
return OK;
}
static ArraySpecializationBits compute_array_specialization_bits(
const Word* array_repr, size_t ndim, unsigned dtype_bitwidth, unsigned index_bitwidth) {
ArraySpecializationBits ret = {};
void* data_ptr = array_repr[0].device_ptr;
const Word* shape_words = array_repr + 1;
const Word* stride_words = shape_words + ndim;
// Only specialize stride divisibility, stride 1 and shape divisibility for ndim <= TMA_MAX_NDIM
if (ndim <= TMA_MAX_NDIM) {
for (size_t i = 0; i < ndim; ++i) {
int64_t stride = stride_words[i].i64;
int64_t shape = shape_words[i].i64;
int64_t stride_bitwidth = stride * dtype_bitwidth;
int64_t shape_bitwidth = shape * dtype_bitwidth;
bool is_stride_byte_aligned = stride_bitwidth % BYTE_BITWIDTH == 0;
bool is_stride_16_byte_divisible =
(stride_bitwidth / BYTE_BITWIDTH) % DIVISOR_16 == 0;
bool is_shape_byte_aligned = shape_bitwidth % BYTE_BITWIDTH == 0;
bool is_shape_divisible_by_16 = shape % DIVISOR_16 == 0;
if (is_stride_byte_aligned && is_stride_16_byte_divisible)
ret.stride_16byte_divisible |= 1u << i;
if (stride == 1)
ret.stride_one |= 1u << i;
if (is_shape_byte_aligned && is_shape_divisible_by_16)
ret.shape_divisible_by_16 |= 1u << i;
}
}
// extract base pointer divisibility
intptr_t data_ptr_int = reinterpret_cast<intptr_t>(data_ptr);
ret.baseptr_16byte_aligned = data_ptr_int % DIVISOR_16 == 0;
// check elements disjoint.
// sort by stride. the smallest stride indicates the contiguous axis
// of the underlying array.
Vec<std::pair<int64_t, int64_t>> strides_and_shape(ndim);
for (size_t i = 0; i < ndim; ++i) {
strides_and_shape[i] = {stride_words[i].i64, shape_words[i].i64};
}
std::sort(strides_and_shape.begin(), strides_and_shape.end());
// disjointness check:
// - 0 dimension array elements are always disjoint.
// - >0 dimension array elements are disjoint if every stride is positive
// and greater than or equal to the product of the previous stride and
// the previous shape.
bool elems_disjoint = (ndim == 0) || (strides_and_shape[0].first > 0);
for (size_t i = 0; i + 1 < ndim; ++i) {
int64_t prev_stride = strides_and_shape[i].first;
int64_t prev_shape = strides_and_shape[i].second;
int64_t cur_stride = strides_and_shape[i + 1].first;
elems_disjoint &= (
cur_stride > 0 && cur_stride >= prev_stride * prev_shape);
}
ret.disjoint_elements = elems_disjoint;
return ret;
}
struct ConstantCursor {
const int64_t* data;
size_t len;
int64_t next() {
CHECK(len);
int64_t ret = *data;
++data, --len;
return ret;
}
};
struct ArrayTypeConstantBuilder {
void* device_ptr = nullptr;
uint64_t bits = -1;
void update(const Arena& arena, const ArrayRepr& ar) {
const Word* repr = arena.data() + ar.repr;
device_ptr = repr[0].device_ptr;
bits &= compute_array_specialization_bits(
repr, ar.arrty.ndim, ar.arrty.dtype.bits * ar.arrty.dtype.lanes,
ar.arrty.index_bitwidth).u64;
}
void finalize(const DriverApi* driver, const ArrayType& arrty, LaunchHelper& helper) {
helper.constants.push_back(pack_array_type(arrty));
if (!helper.cuda_context) {
driver->cuPointerGetAttribute(&helper.cuda_context, CU_POINTER_ATTRIBUTE_CONTEXT,
reinterpret_cast<CUdeviceptr>(device_ptr));
}
helper.constants.push_back(bits);
}
};
// Parse the constants generated by ArrayTypeConstantBuilder.finalize()
// into an ArrayConstraint object.
static PyPtr parse_array_constraint(ConstantCursor& cursor) {
ArrayType arrty = unpack_array_type(cursor.next());
ArraySpecializationBits special_bits;
special_bits.u64 = cursor.next();
unsigned index_bitwidth = arrty.index_bitwidth;
// Only int32 or int64 are supported now.
CHECK(index_bitwidth == 32 || index_bitwidth == 64);
PyObject* signature_module = get_signature_module();
if (!signature_module) return {};
PyPtr constraint_class = getattr(signature_module, "ArrayConstraint");
if (!constraint_class) return {};
PyPtr args = steal(PyTuple_New(0));
if (!args) return {};
PyPtr dtype = dtype_to_python(arrty.dtype);
if (!dtype) return {};
PyPtr index_dtype = dtype_to_python(
DLDataType{kDLInt, static_cast<uint8_t>(index_bitwidth), 1});
if (!index_dtype) return {};
PyPtr constant_strides = steal(PyTuple_New(arrty.ndim));
if (!constant_strides) return {};
PyPtr stride_divisible_by = steal(PyTuple_New(arrty.ndim));
if (!stride_divisible_by) return {};
PyPtr shape_divisible_by = steal(PyTuple_New(arrty.ndim));
if (!shape_divisible_by) return {};
PyPtr zero = steal(PyLong_FromLong(0));
if (!zero) return {};
PyPtr one = steal(PyLong_FromLong(1));
if (!one) return {};
PyPtr sixteen = steal(PyLong_FromLong(DIVISOR_16));
if (!sixteen) return {};
PyPtr stride_divisor = one;
constexpr unsigned divisor16_bits = DIVISOR_16 * BYTE_BITWIDTH;
if (divisor16_bits % arrty.dtype.bits == 0) {
stride_divisor = steal(PyLong_FromLong(divisor16_bits / arrty.dtype.bits));
if (!stride_divisor) return {};
}
for (size_t i = 0; i < arrty.ndim; ++i) {
PyObject* obj = special_bits.is_stride_one(i) ? one.get() : Py_None;
PyTuple_SET_ITEM(constant_strides.get(), i, Py_NewRef(obj));
obj = special_bits.is_stride_16byte_divisible(i) ? stride_divisor.get() : one.get();
PyTuple_SET_ITEM(stride_divisible_by.get(), i, Py_NewRef(obj));
obj = special_bits.is_shape_divisible_by_16(i) ? sixteen.get() : one.get();
PyTuple_SET_ITEM(shape_divisible_by.get(), i, Py_NewRef(obj));
}
PyPtr kwargs = steal(Py_BuildValue(
"{sO sI sO sO sO s() sO sO sO sO}",
"dtype", dtype.get(),
"ndim", static_cast<unsigned>(arrty.ndim),
"index_dtype", index_dtype.get(),
"stride_constant", constant_strides.get(),
"stride_lower_bound_incl", zero.get(),
"alias_groups",
"may_alias_internally", special_bits.disjoint_elements ? Py_False : Py_True,
"stride_divisible_by", stride_divisible_by.get(),
"shape_divisible_by", shape_divisible_by.get(),
"base_addr_divisible_by",
special_bits.baseptr_16byte_aligned ? sixteen.get() : one.get()));
if (!kwargs) return {};
return steal(PyObject_Call(constraint_class.get(), args.get(), kwargs.get()));
}
#define UNPACK_ARRAY_INTERFACE(dict, key) \
PyObject* key = PyDict_GetItemWithError((dict).get(), g_##key##_pyunicode); \
if (!key) { \
if (!PyErr_Occurred()) \
PyErr_SetString(PyExc_TypeError, \
"__cuda_array_interface__ is missing the '" #key "' key"); \
return ErrorRaised; \
}
#define ASSERT_NDIM(ndim) \
if (static_cast<uintmax_t>(ndim) > INT32_MAX) \
return raise(PyExc_TypeError, "Input array exceeds max supported dimensions: %ld > %u", \
ndim, INT32_MAX);
static Result<ArrayRepr> arrayrepr_cuda_array_iface(PyObject* pyobj, unsigned index_bitwidth,
Arena& arena) {
PyPtr dict = steal(PyObject_GetAttr(pyobj, g___cuda_array_interface___pyunicode));
if (!PyDict_Check(dict.get())) {
PyErr_SetString(PyExc_TypeError,
"__cuda_array_interface__ returned a non-dictionary object");
return ErrorRaised;
}
UNPACK_ARRAY_INTERFACE(dict, typestr);
UNPACK_ARRAY_INTERFACE(dict, shape);
UNPACK_ARRAY_INTERFACE(dict, data);
// Parse the dtype
Result<DLDataType> dtype = parse_typestr(typestr);
if (!dtype.is_ok()) return ErrorRaised;
// Parse the data pointer
if (!PyTuple_Check(data) || PyTuple_GET_SIZE(data) != 2) {
PyErr_SetString(PyExc_TypeError,
"__cuda_array_interface['data'] is not a tuple of length 2");
return ErrorRaised;
}
PyObject* data_ptr_pylong = PyTuple_GET_ITEM(data, 0);
if (!PyLong_Check(data_ptr_pylong)) {
PyErr_SetString(PyExc_TypeError, "__cuda_array_interface['data'][0] is not an integer");
return ErrorRaised;
}
intptr_t data_ptr_int = pylong_as<intptr_t>(data_ptr_pylong);
if (PyErr_Occurred()) return ErrorRaised;
Py_ssize_t ndim = PyTuple_GET_SIZE(shape);
ASSERT_NDIM(ndim);
ArenaOffset repr_offset = arena_alloc_words(arena, 1 + 2 * ndim);
arena[repr_offset].device_ptr = reinterpret_cast<void*>(data_ptr_int);
// Parse the shape
if (!PyTuple_Check(shape))
return raise(PyExc_TypeError, "__cuda_array_interface['shape'] is not a tuple");
for (Py_ssize_t i = 0; i < ndim; ++i) {
int64_t size = pylong_as<int64_t>(PyTuple_GET_ITEM(shape, i));
if (PyErr_Occurred()) return ErrorRaised;
arena[repr_offset + 1 + i].i64 = size;
}
// Parse the strides
PyObject* strides = PyDict_GetItem(dict.get(), g_strides_pyunicode);
if (PyErr_Occurred()) return ErrorRaised;
if (!strides || strides == Py_None) {
if (!fill_row_major_strides(index_bitwidth, arena.data() + repr_offset, ndim))
return ErrorRaised;
} else if (PyTuple_Check(strides)) {
// Only byte-aligned types should be supported by __cuda_array_interface__
uint8_t dtype_bytewidth = dtype->bits / BYTE_BITWIDTH;
for (Py_ssize_t i = 0; i < ndim; ++i) {
int64_t stride = pylong_as<int64_t>(PyTuple_GET_ITEM(strides, i));
if (PyErr_Occurred()) return ErrorRaised;
arena[repr_offset + 1 + ndim + i].i64 = static_cast<int64_t>(
stride / dtype_bytewidth);
}
} else {
return raise(PyExc_TypeError, "__cuda_array_interface['strides'] can only be"
" absent, None, or a tuple");
}
return ArrayRepr {
.arrty = {
.dtype = *dtype,
.ndim = static_cast<size_t>(ndim),
.index_bitwidth = index_bitwidth
},
.repr = repr_offset
};
}
static Result<ArrayRepr> arrayrepr_dlpack_common(PyObject* dlpack_capsule, unsigned index_bitwidth,
Arena& arena) {
void* ptr = PyCapsule_GetPointer(dlpack_capsule, "dltensor");
if (!ptr) return ErrorRaised;
DLManagedTensor* tensor = static_cast<DLManagedTensor*>(ptr);
if (tensor->dl_tensor.device.device_type != kDLCUDA)
return raise(PyExc_ValueError, "Input array is not on a CUDA device");
// TODO: check device ID
void* data_ptr = static_cast<char*>(tensor->dl_tensor.data) + tensor->dl_tensor.byte_offset;
uint32_t ndim = tensor->dl_tensor.ndim;
ASSERT_NDIM(ndim);
ArenaOffset repr_offset = arena_alloc_words(arena, 1 + 2 * ndim);
arena[repr_offset].device_ptr = data_ptr;
for (uint32_t i = 0; i < ndim; ++i) {
if (index_bitwidth != 64 && (tensor->dl_tensor.shape[i] < INT32_MIN
|| tensor->dl_tensor.shape[i] > INT32_MAX))
return raise(PyExc_OverflowError, "shape is too big");
arena[repr_offset + 1 + i].i64 = tensor->dl_tensor.shape[i];
}
if (!tensor->dl_tensor.strides) {
if (!fill_row_major_strides(index_bitwidth, arena.data() + repr_offset, ndim))
return ErrorRaised;
} else {
for (uint32_t i = 0; i < ndim; ++i) {
if(index_bitwidth != 64 && (tensor->dl_tensor.strides[i] < INT32_MIN
|| tensor->dl_tensor.strides[i] > INT32_MAX))
return raise(PyExc_OverflowError, "stride is too big");
arena[repr_offset + 1 + ndim + i].i64 = tensor->dl_tensor.strides[i];
}
}
ArrayRepr ret = {
.arrty = {
.dtype = tensor->dl_tensor.dtype,
.ndim = ndim,
.index_bitwidth = index_bitwidth
},
.repr = repr_offset
};
You can’t perform that action at this time.
