-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathspmm_coo.py
More file actions
1558 lines (1451 loc) · 47.5 KB
/
Copy pathspmm_coo.py
File metadata and controls
1558 lines (1451 loc) · 47.5 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
"""Native COO SpMM kernels, route helpers, and internal benchmark entry points."""
from ._common import *
from .spmm_csr import (
SUPPORTED_SPMM_VALUE_DTYPES,
_select_spmm_alg1_warp_and_factor,
_spmm_coo_reference_tolerance,
_spmm_relative_threshold,
_spmm_validation_metrics,
)
SPMM_COO_OP_NON = 0
SPMM_COO_OP_TRANS = 1
SPMM_COO_OP_CONJ_TRANS = 2
SPMM_COO_OP_NAMES = {
SPMM_COO_OP_NON: "non",
SPMM_COO_OP_TRANS: "trans",
SPMM_COO_OP_CONJ_TRANS: "conj",
}
_SPMM_COO_OP_NAME_TO_CODE = {name: code for code, name in SPMM_COO_OP_NAMES.items()}
def _normalize_spmm_coo_op(op=None, transpose=False):
if op is None:
return SPMM_COO_OP_TRANS if bool(transpose) else SPMM_COO_OP_NON
if isinstance(op, str):
token = op.strip().lower()
if token not in _SPMM_COO_OP_NAME_TO_CODE:
raise ValueError("op must be one of: 0=non, 1=trans, 2=conj")
return _SPMM_COO_OP_NAME_TO_CODE[token]
try:
op_code = int(op)
except (TypeError, ValueError) as exc:
raise ValueError("op must be one of: 0=non, 1=trans, 2=conj") from exc
if op_code not in SPMM_COO_OP_NAMES:
raise ValueError("op must be one of: 0=non, 1=trans, 2=conj")
return op_code
def _spmm_coo_op_to_name(op):
return SPMM_COO_OP_NAMES[_normalize_spmm_coo_op(op)]
def _spmm_coo_op_transposes(op):
return _normalize_spmm_coo_op(op) in (SPMM_COO_OP_TRANS, SPMM_COO_OP_CONJ_TRANS)
def _materialize_spmm_coo_op(data, row, col, shape, op_code):
if op_code == SPMM_COO_OP_NON:
return data, row, col, shape
data_op = data
if op_code == SPMM_COO_OP_CONJ_TRANS and _is_complex_dtype(data.dtype):
data_op = data.conj()
if hasattr(data_op, "resolve_conj"):
data_op = data_op.resolve_conj()
return data_op, col, row, (int(shape[1]), int(shape[0]))
def _normalize_dense_layout(layout):
token = "row" if layout is None else str(layout).strip().lower()
if token in ("auto", "default"):
return "row"
if token in ("row", "row_major", "row-major", "c", "c_order"):
return "row"
if token in (
"col",
"column",
"col_major",
"column_major",
"col-major",
"column-major",
"f",
"fortran",
):
return "col"
raise ValueError("dense_layout must be one of: auto, row, col")
def _is_col_major_2d(tensor):
return (
torch.is_tensor(tensor)
and tensor.ndim == 2
and tensor.stride(0) == 1
and tensor.stride(1) >= max(1, int(tensor.shape[0]))
)
def _dense_layout_name(tensor):
if not torch.is_tensor(tensor) or tensor.ndim != 2:
return "unknown"
if tensor.is_contiguous():
return "row"
if _is_col_major_2d(tensor):
return "col"
return "strided"
def _empty_dense_layout(shape, dtype, device, layout):
layout = _normalize_dense_layout(layout)
rows, cols = int(shape[0]), int(shape[1])
if layout == "col":
return torch.empty_strided(
(rows, cols),
(1, max(1, rows)),
dtype=dtype,
device=device,
)
return torch.empty((rows, cols), dtype=dtype, device=device)
def _zeros_dense_layout(shape, dtype, device, layout):
out = _empty_dense_layout(shape, dtype, device, layout)
out.zero_()
return out
def _materialize_dense_layout(tensor, layout):
layout = _normalize_dense_layout(layout)
if tensor.ndim != 2:
raise ValueError("dense layout materialization expects a 2D tensor")
if layout == "row":
return tensor.contiguous()
if _is_col_major_2d(tensor):
return tensor
out = _empty_dense_layout(tensor.shape, tensor.dtype, tensor.device, layout)
out.copy_(tensor)
return out
def _spmm_coo_compute_dtype(value_dtype):
if _is_complex_dtype(value_dtype):
return torch.complex128 if value_dtype == torch.complex64 else value_dtype
if value_dtype in (torch.float16, torch.bfloat16):
return torch.float32
if value_dtype == torch.float32:
return torch.float64
return value_dtype
def _sort_coo_lex_inplace(data, row, col, n_cols):
row64 = row.to(torch.int64)
col64 = col.to(torch.int64)
if data.numel() == 0:
return data.contiguous(), row64, col64
key = row64 * max(1, int(n_cols)) + col64
order = torch.argsort(key)
return (
data[order].contiguous(),
row64[order].contiguous(),
col64[order].contiguous(),
)
def _coalesce_coo_entries(data, row, col, shape):
"""Merge duplicate (row, col) by summing values (PyTorch COO coalesce)."""
n_rows, n_cols = int(shape[0]), int(shape[1])
if data.numel() == 0:
z = torch.empty(0, dtype=torch.int64, device=data.device)
return data.contiguous(), z, z.clone()
row64 = row.to(torch.int64)
col64 = col.to(torch.int64)
coo = torch.sparse_coo_tensor(
torch.stack([row64, col64]),
data,
size=(n_rows, n_cols),
device=data.device,
dtype=data.dtype,
).coalesce()
idx = coo.indices()
return coo.values().contiguous(), idx[0].contiguous(), idx[1].contiguous()
def _build_torch_sparse_coo(data, row, col, shape):
"""Coalesced CUDA COO tensor for ``torch.sparse.mm`` (indices int64)."""
n_rows, n_cols = int(shape[0]), int(shape[1])
if data.numel() == 0:
empty_idx = torch.empty((2, 0), dtype=torch.int64, device=data.device)
return torch.sparse_coo_tensor(
empty_idx,
data,
size=(n_rows, n_cols),
device=data.device,
dtype=data.dtype,
)
row_i = row.to(torch.int64)
col_i = col.to(torch.int64)
indices = torch.stack([row_i, col_i])
return torch.sparse_coo_tensor(
indices,
data,
size=(n_rows, n_cols),
device=data.device,
dtype=data.dtype,
).coalesce()
def _build_random_coo(n_rows, n_cols, nnz, value_dtype, index_dtype, device):
nnz = int(nnz)
if nnz < 0:
raise ValueError("nnz must be non-negative")
if int(n_rows) < 0 or int(n_cols) < 0:
raise ValueError("matrix dimensions must be non-negative")
if index_dtype not in SUPPORTED_INDEX_DTYPES:
raise TypeError("index_dtype must be torch.int32 or torch.int64")
if value_dtype not in SUPPORTED_SPMM_VALUE_DTYPES:
raise TypeError("value_dtype is not supported by COO SpMM")
data = _build_random_dense(nnz, value_dtype, device)
if nnz == 0:
row = torch.empty((0,), dtype=index_dtype, device=device)
col = torch.empty((0,), dtype=index_dtype, device=device)
return data, row, col
if n_rows == 0 or n_cols == 0:
raise ValueError("nnz must be 0 when either matrix dimension is zero")
row = torch.randint(0, int(n_rows), (nnz,), dtype=index_dtype, device=device)
col = torch.randint(0, int(n_cols), (nnz,), dtype=index_dtype, device=device)
return data, row, col
def _prepare_spmm_coo_canonical_prepared(
data,
row,
col,
B,
n_rows,
n_cols,
n_dense_cols,
dense_layout="row",
):
dense_layout = _normalize_dense_layout(dense_layout)
output_dtype = data.dtype
compute_dtype = _spmm_coo_compute_dtype(output_dtype)
data_compute = data if compute_dtype == output_dtype else data.to(compute_dtype)
B_compute = B if compute_dtype == output_dtype else B.to(compute_dtype)
B_compute = _materialize_dense_layout(B_compute, dense_layout)
canonical_data, canonical_row, canonical_col = _coalesce_coo_entries(
data_compute,
row,
col,
(n_rows, n_cols),
)
canonical_data, canonical_row, canonical_col = _sort_coo_lex_inplace(
canonical_data,
canonical_row,
canonical_col,
n_cols,
)
return (
canonical_data,
canonical_row,
canonical_col,
B_compute,
n_rows,
n_cols,
n_dense_cols,
output_dtype,
compute_dtype,
)
def _prepare_spmm_coo_canonical_inputs(data, row, col, B, shape, dense_layout="row"):
data, kernel_row, kernel_col, B, n_rows, n_cols, n_dense_cols = _prepare_spmm_coo_inputs(
data, row, col, B, shape, dense_layout=dense_layout
)
return _prepare_spmm_coo_canonical_prepared(
data,
kernel_row,
kernel_col,
B,
n_rows,
n_cols,
n_dense_cols,
dense_layout=dense_layout,
)
def _seg_starts_from_sorted_rows(row_i32, nnz, device):
if nnz == 0:
return None
diff = row_i32[1:] != row_i32[:-1]
breaks = torch.nonzero(diff, as_tuple=False).flatten().to(torch.int32) + 1
return torch.cat(
[
torch.zeros(1, dtype=torch.int32, device=device),
breaks,
torch.tensor([nnz], dtype=torch.int32, device=device),
]
)
@triton.jit
def _spmm_coo_rowrun_real_kernel(
data_ptr,
row_ptr,
col_ptr,
b_ptr,
c_ptr,
seg_starts_ptr,
n_segs,
n_dense_cols,
stride_bk,
stride_bn,
stride_cm,
stride_cn,
BLOCK_N: tl.constexpr,
BLOCK_NNZ: tl.constexpr,
ACC_DTYPE: tl.constexpr,
):
seg = tl.program_id(0)
pid_n = tl.program_id(1)
if seg >= n_segs:
return
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
mask_n = offs_n < n_dense_cols
start = tl.load(seg_starts_ptr + seg)
end = tl.load(seg_starts_ptr + seg + 1)
row_nnz = end - start
row_id = tl.load(row_ptr + start)
acc = tl.zeros([BLOCK_N], dtype=ACC_DTYPE)
for chunk_start in tl.range(0, row_nnz, BLOCK_NNZ):
for kk in tl.static_range(0, BLOCK_NNZ):
idx = start + chunk_start + kk
valid = idx < end
a_val = tl.load(data_ptr + idx, mask=valid, other=0.0)
a_col = tl.load(col_ptr + idx, mask=valid, other=0)
b_vals = tl.load(
b_ptr + a_col * stride_bk + offs_n * stride_bn,
mask=mask_n & valid,
other=0.0,
)
acc = acc + a_val.to(ACC_DTYPE) * b_vals.to(ACC_DTYPE)
tl.store(c_ptr + row_id * stride_cm + offs_n * stride_cn, acc, mask=mask_n)
@triton.jit
def _spmm_coo_rowrun_complex_kernel(
data_ri_ptr,
row_ptr,
col_ptr,
b_ri_ptr,
c_ri_ptr,
seg_starts_ptr,
n_segs,
n_dense_cols,
stride_bk,
stride_bn,
stride_br,
stride_cm,
stride_cn,
stride_cr,
BLOCK_N: tl.constexpr,
BLOCK_NNZ: tl.constexpr,
ACC_DTYPE: tl.constexpr,
):
seg = tl.program_id(0)
pid_n = tl.program_id(1)
if seg >= n_segs:
return
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
mask_n = offs_n < n_dense_cols
start = tl.load(seg_starts_ptr + seg)
end = tl.load(seg_starts_ptr + seg + 1)
row_nnz = end - start
row_id = tl.load(row_ptr + start)
acc_re = tl.zeros([BLOCK_N], dtype=ACC_DTYPE)
acc_im = tl.zeros([BLOCK_N], dtype=ACC_DTYPE)
for chunk_start in tl.range(0, row_nnz, BLOCK_NNZ):
for kk in tl.static_range(0, BLOCK_NNZ):
idx = start + chunk_start + kk
valid = idx < end
a_re = tl.load(data_ri_ptr + idx * 2, mask=valid, other=0.0)
a_im = tl.load(data_ri_ptr + idx * 2 + 1, mask=valid, other=0.0)
a_col = tl.load(col_ptr + idx, mask=valid, other=0)
b_re = tl.load(
b_ri_ptr + a_col * stride_bk + offs_n * stride_bn,
mask=mask_n & valid,
other=0.0,
)
b_im = tl.load(
b_ri_ptr + a_col * stride_bk + offs_n * stride_bn + stride_br,
mask=mask_n & valid,
other=0.0,
)
acc_re = acc_re + a_re.to(ACC_DTYPE) * b_re.to(ACC_DTYPE) - a_im.to(ACC_DTYPE) * b_im.to(ACC_DTYPE)
acc_im = acc_im + a_re.to(ACC_DTYPE) * b_im.to(ACC_DTYPE) + a_im.to(ACC_DTYPE) * b_re.to(ACC_DTYPE)
tl.store(c_ri_ptr + row_id * stride_cm + offs_n * stride_cn, acc_re, mask=mask_n)
tl.store(
c_ri_ptr + row_id * stride_cm + offs_n * stride_cn + stride_cr,
acc_im,
mask=mask_n,
)
@triton.jit
def _spmm_coo_atomic_real_kernel(
data_ptr,
row_ptr,
col_ptr,
b_ptr,
c_ptr,
nnz,
n_dense_cols,
stride_bk,
stride_bn,
stride_cm,
stride_cn,
ACC_DTYPE: tl.constexpr,
):
idx = tl.program_id(0)
dense_col = tl.program_id(1)
if idx >= nnz or dense_col >= n_dense_cols:
return
row_k = tl.load(row_ptr + idx)
col_k = tl.load(col_ptr + idx)
val_k = tl.load(data_ptr + idx)
b_val = tl.load(b_ptr + col_k * stride_bk + dense_col * stride_bn)
tl.atomic_add(
c_ptr + row_k * stride_cm + dense_col * stride_cn,
val_k.to(ACC_DTYPE) * b_val.to(ACC_DTYPE),
sem="relaxed",
)
@triton.jit
def _spmm_coo_atomic_complex_kernel(
data_ri_ptr,
row_ptr,
col_ptr,
b_ri_ptr,
c_ri_ptr,
nnz,
n_dense_cols,
stride_bk,
stride_bn,
stride_br,
stride_cm,
stride_cn,
stride_cr,
ACC_DTYPE: tl.constexpr,
):
idx = tl.program_id(0)
dense_col = tl.program_id(1)
if idx >= nnz or dense_col >= n_dense_cols:
return
row_k = tl.load(row_ptr + idx)
col_k = tl.load(col_ptr + idx)
a_re = tl.load(data_ri_ptr + idx * 2)
a_im = tl.load(data_ri_ptr + idx * 2 + 1)
b_re = tl.load(b_ri_ptr + col_k * stride_bk + dense_col * stride_bn)
b_im = tl.load(b_ri_ptr + col_k * stride_bk + dense_col * stride_bn + stride_br)
contrib_re = a_re.to(ACC_DTYPE) * b_re.to(ACC_DTYPE) - a_im.to(ACC_DTYPE) * b_im.to(ACC_DTYPE)
contrib_im = a_re.to(ACC_DTYPE) * b_im.to(ACC_DTYPE) + a_im.to(ACC_DTYPE) * b_re.to(ACC_DTYPE)
tl.atomic_add(
c_ri_ptr + row_k * stride_cm + dense_col * stride_cn,
contrib_re,
sem="relaxed",
)
tl.atomic_add(
c_ri_ptr + row_k * stride_cm + dense_col * stride_cn + stride_cr,
contrib_im,
sem="relaxed",
)
def _prepare_spmm_coo_inputs(data, row, col, B, shape, dense_layout="row"):
dense_layout = _normalize_dense_layout(dense_layout)
if len(shape) != 2:
raise ValueError("shape must be a 2-tuple: (n_rows, n_cols)")
if data.ndim != 1 or row.ndim != 1 or col.ndim != 1:
raise ValueError("data, row, and col must be 1D tensors")
if B.ndim != 2:
raise ValueError("B must be a 2D dense tensor")
n_rows, n_cols = int(shape[0]), int(shape[1])
if n_rows < 0 or n_cols < 0:
raise ValueError("shape dimensions must be non-negative")
if data.numel() != row.numel() or data.numel() != col.numel():
raise ValueError("data, row, and col must have the same length (nnz)")
if B.shape[0] != n_cols:
raise ValueError(f"B.shape[0] must be n_cols={n_cols}, got {B.shape[0]}")
if not all(t.is_cuda for t in (data, row, col, B)):
raise ValueError("data, row, col, and B must be CUDA tensors")
if not all(t.device == data.device for t in (row, col, B)):
raise ValueError("data, row, col, and B must be on the same CUDA device")
if data.dtype not in SUPPORTED_SPMM_VALUE_DTYPES:
raise TypeError(
"data dtype must be one of: float16, bfloat16, float32, float64, complex64, complex128"
)
if B.dtype != data.dtype:
raise TypeError("B dtype must match data dtype")
if row.dtype not in SUPPORTED_INDEX_DTYPES:
raise TypeError("row dtype must be torch.int32 or torch.int64")
if col.dtype not in SUPPORTED_INDEX_DTYPES:
raise TypeError("col dtype must be torch.int32 or torch.int64")
nnz = data.numel()
if nnz > _INDEX_LIMIT_INT32:
raise ValueError("nnz exceeds the int32 range supported by the Triton COO kernel")
if nnz > 0:
min_row = int(row.min().item())
max_row = int(row.max().item())
min_col = int(col.min().item())
max_col = int(col.max().item())
if min_row < 0 or max_row >= n_rows:
raise IndexError("row indices out of range for n_rows")
if min_col < 0 or max_col >= n_cols:
raise IndexError("col indices out of range for n_cols")
if max_row > _INDEX_LIMIT_INT32:
raise ValueError(
"row indices exceed the int32 range supported by the Triton kernel"
)
if max_col > _INDEX_LIMIT_INT32:
raise ValueError(
"column indices exceed the int32 range supported by the Triton kernel"
)
data = data.contiguous()
row = row.contiguous()
col = col.contiguous()
B = _materialize_dense_layout(B, dense_layout)
kernel_row = row.to(torch.int32) if row.dtype == torch.int64 else row
kernel_col = col.to(torch.int32) if col.dtype == torch.int64 else col
return data, kernel_row, kernel_col, B, n_rows, n_cols, int(B.shape[1])
def _resolve_spmm_coo_launch_config(n_dense_cols, nnz, block_n=None, block_nnz=256):
warp_size, factor = _select_spmm_alg1_warp_and_factor(n_dense_cols)
if block_n is None:
block_n = warp_size * factor
if block_nnz is None:
block_nnz = 256
if block_n <= 0 or block_nnz <= 0:
raise ValueError("block_n and block_nnz must be positive when provided")
return {
"block_n": int(block_n),
"block_nnz": int(block_nnz),
"required_nnz_tiles": int(triton.cdiv(nnz, block_nnz) if nnz > 0 else 0),
"heuristic_warp_size": int(warp_size),
"heuristic_factor": int(factor),
}
def _triton_spmm_coo_rowrun_impl(
data,
row,
col,
B,
n_rows,
n_dense_cols,
block_n,
block_nnz,
output_dtype,
out=None,
dense_layout="row",
seg_starts=None,
):
device = data.device
dtype = data.dtype
dense_layout = _normalize_dense_layout(dense_layout)
if out is not None:
if out.shape != (int(n_rows), int(n_dense_cols)) or out.dtype != output_dtype:
raise ValueError("out shape/dtype must match result")
if out.device != device:
raise ValueError("out must be on the same CUDA device as data")
if n_rows == 0 or n_dense_cols == 0 or B.shape[0] == 0 or data.numel() == 0:
if out is not None:
out.zero_()
return out
return _zeros_dense_layout((n_rows, n_dense_cols), output_dtype, device, dense_layout)
if seg_starts is None:
seg_starts = _seg_starts_from_sorted_rows(row, int(data.numel()), device)
n_segs = int(seg_starts.numel()) - 1 if seg_starts is not None else 0
if n_segs == 0:
if out is not None:
out.zero_()
return out
return _zeros_dense_layout((n_rows, n_dense_cols), output_dtype, device, dense_layout)
grid = (n_segs, triton.cdiv(n_dense_cols, block_n))
if not _is_complex_dtype(dtype):
C_compute = (
out
if out is not None and dtype == output_dtype
else _zeros_dense_layout((n_rows, n_dense_cols), dtype, device, dense_layout)
)
if C_compute is out:
C_compute.zero_()
acc_dtype = tl.float64 if dtype == torch.float64 else tl.float32
_spmm_coo_rowrun_real_kernel[grid](
data,
row,
col,
B,
C_compute,
seg_starts,
n_segs,
n_dense_cols,
B.stride(0),
B.stride(1),
C_compute.stride(0),
C_compute.stride(1),
BLOCK_N=block_n,
BLOCK_NNZ=block_nnz,
ACC_DTYPE=acc_dtype,
)
if dtype != output_dtype:
C_cast = C_compute.to(output_dtype)
if out is not None:
out.copy_(C_cast)
return out
if dense_layout == "col":
C_out = _empty_dense_layout((n_rows, n_dense_cols), output_dtype, device, dense_layout)
C_out.copy_(C_cast)
return C_out
return C_cast
return C_compute
data_ri = torch.view_as_real(data).contiguous().reshape(-1)
B_ri = torch.view_as_real(B)
C_compute = (
out
if out is not None and dtype == output_dtype
else _zeros_dense_layout(
(n_rows, n_dense_cols),
dtype,
device,
dense_layout,
)
)
if C_compute is out:
C_compute.zero_()
C_ri = torch.view_as_real(C_compute)
acc_dtype = tl.float64 if B_ri.dtype == torch.float64 else tl.float32
_spmm_coo_rowrun_complex_kernel[grid](
data_ri,
row,
col,
B_ri,
C_ri,
seg_starts,
n_segs,
n_dense_cols,
B_ri.stride(0),
B_ri.stride(1),
B_ri.stride(2),
C_ri.stride(0),
C_ri.stride(1),
C_ri.stride(2),
BLOCK_N=block_n,
BLOCK_NNZ=block_nnz,
ACC_DTYPE=acc_dtype,
)
if dtype != output_dtype:
C_cast = C_compute.to(output_dtype)
if out is not None:
out.copy_(C_cast)
return out
if dense_layout == "col":
C_out = _empty_dense_layout((n_rows, n_dense_cols), output_dtype, device, dense_layout)
C_out.copy_(C_cast)
return C_out
return C_cast
return C_compute
def _triton_spmm_coo_atomic_impl(
data,
row,
col,
B,
n_rows,
n_dense_cols,
block_n,
block_nnz,
output_dtype,
out=None,
dense_layout="row",
):
device = data.device
dtype = data.dtype
dense_layout = _normalize_dense_layout(dense_layout)
if out is not None:
if out.shape != (int(n_rows), int(n_dense_cols)) or out.dtype != output_dtype:
raise ValueError("out shape/dtype must match result")
if out.device != device:
raise ValueError("out must be on the same CUDA device as data")
if n_rows == 0 or n_dense_cols == 0 or B.shape[0] == 0 or data.numel() == 0:
if out is not None:
out.zero_()
return out
return _zeros_dense_layout((n_rows, n_dense_cols), output_dtype, device, dense_layout)
nnz = int(data.numel())
if nnz == 0:
if out is not None:
out.zero_()
return out
return _zeros_dense_layout((n_rows, n_dense_cols), output_dtype, device, dense_layout)
if not _is_complex_dtype(dtype):
C_compute = (
out
if out is not None and dtype == output_dtype
else _zeros_dense_layout((n_rows, n_dense_cols), dtype, device, dense_layout)
)
if C_compute is out:
C_compute.zero_()
acc_dtype = tl.float64 if dtype == torch.float64 else tl.float32
_spmm_coo_atomic_real_kernel[(nnz, n_dense_cols)](
data,
row,
col,
B,
C_compute,
nnz,
n_dense_cols,
B.stride(0),
B.stride(1),
C_compute.stride(0),
C_compute.stride(1),
ACC_DTYPE=acc_dtype,
)
if dtype != output_dtype:
C_cast = C_compute.to(output_dtype)
if out is not None:
out.copy_(C_cast)
return out
if dense_layout == "col":
C_out = _empty_dense_layout((n_rows, n_dense_cols), output_dtype, device, dense_layout)
C_out.copy_(C_cast)
return C_out
return C_cast
return C_compute
data_ri = torch.view_as_real(data).contiguous().reshape(-1)
B_ri = torch.view_as_real(B)
C_compute = (
out
if out is not None and dtype == output_dtype
else _zeros_dense_layout(
(n_rows, n_dense_cols),
dtype,
device,
dense_layout,
)
)
if C_compute is out:
C_compute.zero_()
C_ri = torch.view_as_real(C_compute)
acc_dtype = tl.float64 if B_ri.dtype == torch.float64 else tl.float32
_spmm_coo_atomic_complex_kernel[(nnz, n_dense_cols)](
data_ri,
row,
col,
B_ri,
C_ri,
nnz,
n_dense_cols,
B_ri.stride(0),
B_ri.stride(1),
B_ri.stride(2),
C_ri.stride(0),
C_ri.stride(1),
C_ri.stride(2),
ACC_DTYPE=acc_dtype,
)
if dtype != output_dtype:
C_cast = C_compute.to(output_dtype)
if out is not None:
out.copy_(C_cast)
return out
if dense_layout == "col":
C_out = _empty_dense_layout((n_rows, n_dense_cols), output_dtype, device, dense_layout)
C_out.copy_(C_cast)
return C_out
return C_cast
return C_compute
def _normalize_spmm_coo_route(route):
route = "rowrun" if route is None else str(route).lower()
if route not in ("rowrun", "atomic"):
raise ValueError("route must be 'rowrun' or 'atomic'")
return route
def _triton_spmm_coo_impl(
data,
row,
col,
B,
n_rows,
n_dense_cols,
block_n,
block_nnz,
route="rowrun",
output_dtype=None,
out=None,
dense_layout="row",
):
route = _normalize_spmm_coo_route(route)
dense_layout = _normalize_dense_layout(dense_layout)
resolved_output_dtype = output_dtype if output_dtype is not None else data.dtype
if route == "rowrun":
return _triton_spmm_coo_rowrun_impl(
data,
row,
col,
B,
n_rows,
n_dense_cols,
block_n,
block_nnz,
output_dtype=resolved_output_dtype,
out=out,
dense_layout=dense_layout,
)
return _triton_spmm_coo_atomic_impl(
data,
row,
col,
B,
n_rows,
n_dense_cols,
block_n,
block_nnz,
output_dtype=resolved_output_dtype,
out=out,
dense_layout=dense_layout,
)
def _run_spmm_coo_canonical_route(
canonical_data,
canonical_row,
canonical_col,
canonical_B,
n_rows,
n_dense_cols,
output_dtype,
block_n=None,
block_nnz=256,
out=None,
return_time=False,
route="rowrun",
dense_layout="row",
):
route = _normalize_spmm_coo_route(route)
dense_layout = _normalize_dense_layout(dense_layout)
launch = _resolve_spmm_coo_launch_config(
n_dense_cols,
canonical_data.numel(),
block_n=block_n,
block_nnz=block_nnz,
)
if out is not None:
if not out.is_cuda:
raise ValueError("out must be a CUDA tensor")
if out.device != canonical_data.device:
raise ValueError("out must be on the same CUDA device as the inputs")
if out.shape != (n_rows, n_dense_cols) or out.dtype != output_dtype:
raise ValueError("out shape/dtype must match result")
torch.cuda.synchronize()
t0 = time.perf_counter()
C = _triton_spmm_coo_impl(
canonical_data,
canonical_row,
canonical_col,
canonical_B,
n_rows,
n_dense_cols,
block_n=launch["block_n"],
block_nnz=launch["block_nnz"],
route=route,
output_dtype=output_dtype,
out=out,
dense_layout=dense_layout,
)
torch.cuda.synchronize()
elapsed_ms = (time.perf_counter() - t0) * 1000.0
if return_time:
return C, elapsed_ms
return C
def _run_spmm_coo_route(
data,
row,
col,
B,
shape,
block_n=None,
block_nnz=256,
out=None,
return_time=False,
return_meta=False,
route="rowrun",
op=None,
transpose=None,
dense_layout="row",
):
route = _normalize_spmm_coo_route(route)
dense_layout = _normalize_dense_layout(dense_layout)
op_explicit = op is not None
op_code = _normalize_spmm_coo_op(
op,
transpose=False if transpose is None else bool(transpose),
)
if (
op_explicit
and transpose is not None
and bool(transpose) != _spmm_coo_op_transposes(op_code)
):
raise ValueError("transpose conflicts with op")
op_name = _spmm_coo_op_to_name(op_code)
if block_n is not None and block_n <= 0:
raise ValueError("block_n must be positive when provided")
if block_nnz is not None and block_nnz <= 0:
raise ValueError("block_nnz must be positive when provided")
do_timing = bool(return_time or return_meta)
symbolic_ms = 0.0 if do_timing else None
compute_ms = None
op_total_ms = None
if do_timing:
torch.cuda.synchronize()
t0 = time.perf_counter()
data, row, col, shape = _materialize_spmm_coo_op(data, row, col, shape, op_code)
if do_timing:
torch.cuda.synchronize()
symbolic_ms = (time.perf_counter() - t0) * 1000.0 if _spmm_coo_op_transposes(op_code) else 0.0
(
canonical_data,
canonical_row,
canonical_col,
canonical_B,
n_rows,
_,
n_dense_cols,
output_dtype,
_,
) = _prepare_spmm_coo_canonical_inputs(
data,
row,
col,
B,
shape,
dense_layout=dense_layout,
)
result = _run_spmm_coo_canonical_route(
canonical_data,
canonical_row,
canonical_col,
canonical_B,
n_rows,
n_dense_cols,
output_dtype,
block_n=block_n,
block_nnz=block_nnz,
out=out,
return_time=do_timing,
route=route,
dense_layout=dense_layout,
)
if do_timing:
C, compute_ms = result
op_total_ms = symbolic_ms + compute_ms
else:
C = result
meta = None
if return_meta:
meta = {
"op": op_name,
"route": route,
"symbolic_ms": symbolic_ms,
"compute_ms": compute_ms,
"op_total_ms": op_total_ms,
"dense_layout": dense_layout,
"b_stride": tuple(int(v) for v in canonical_B.stride()),
"c_stride": tuple(int(v) for v in C.stride()),
"output_layout": _dense_layout_name(C),
}
if return_time and return_meta:
return C, op_total_ms, meta
if return_time:
return C, op_total_ms
if return_meta:
return C, meta
return C