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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
use std::{
mem::{ManuallyDrop, MaybeUninit},
ptr,
};
use singe_cuda::{
data_type::{DataType, DataTypeLike},
types::{Complex32, Complex64, bf16, f4e2m1, f6e2m3, f6e3m2, f8e4m3, f8e5m2, f8ue8m0, f16},
};
use crate::{
context::{Context, ContextRef, validate_same_context},
error::{Error, Result},
sys,
tensor::{BlockSparseTensorDescriptor, TensorDescriptor},
try_ffi,
types::{Mode, OperationDescriptorAttribute, Operator},
utility::{modes_to_i32_vec, to_i32},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct ComputeDescriptor(sys::cutensorComputeDescriptor_t);
impl ComputeDescriptor {
// TODO: Not sure if these extern values are always valid.
pub const fn f16() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_16F })
}
pub const fn bf16() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_16BF })
}
pub const fn tf32() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_TF32 })
}
pub const fn tf32x3() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_3XTF32 })
}
pub const fn f32() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_32F })
}
pub const fn f64() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_64F })
}
pub const fn bf16x9() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_9X16BF })
}
pub const fn i8x8() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_8XINT8 })
}
pub const fn f16x4() -> Self {
Self(unsafe { sys::CUTENSOR_COMPUTE_DESC_4X16F })
}
pub const fn as_raw(self) -> sys::cutensorComputeDescriptor_t {
self.0
}
}
impl From<sys::cutensorComputeDescriptor_t> for ComputeDescriptor {
fn from(value: sys::cutensorComputeDescriptor_t) -> Self {
Self(value)
}
}
impl From<ComputeDescriptor> for sys::cutensorComputeDescriptor_t {
fn from(value: ComputeDescriptor) -> Self {
value.0
}
}
#[derive(Debug, Clone, Copy)]
pub struct TensorOperand<'a> {
desc: &'a TensorDescriptor,
modes: &'a [Mode],
op: Operator,
}
impl<'a> TensorOperand<'a> {
pub const fn new(desc: &'a TensorDescriptor, modes: &'a [Mode], op: Operator) -> Self {
Self { desc, modes, op }
}
pub fn identity(desc: &'a TensorDescriptor, modes: &'a [Mode]) -> Self {
Self::new(desc, modes, Operator::Identity)
}
}
#[derive(Debug, Clone, Copy)]
pub struct BlockSparseTensorOperand<'a> {
desc: &'a BlockSparseTensorDescriptor,
modes: &'a [Mode],
op: Operator,
}
impl<'a> BlockSparseTensorOperand<'a> {
pub const fn new(
desc: &'a BlockSparseTensorDescriptor,
modes: &'a [Mode],
op: Operator,
) -> Self {
Self { desc, modes, op }
}
pub fn identity(desc: &'a BlockSparseTensorDescriptor, modes: &'a [Mode]) -> Self {
Self::new(desc, modes, Operator::Identity)
}
}
#[derive(Debug)]
pub struct OperationDescriptor {
handle: sys::cutensorOperationDescriptor_t,
context: ContextRef,
output_rank: u32,
output_data_type: DataType,
signature: OperationSignature,
padding_value: Option<OwnedPaddingValue>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OperationKind {
ElementwiseTrinary {
a: DataType,
b: DataType,
c: DataType,
d: DataType,
},
ElementwiseBinary {
a: DataType,
c: DataType,
d: DataType,
},
Permutation {
a: DataType,
b: DataType,
},
Contraction {
a: DataType,
b: DataType,
c: DataType,
d: DataType,
},
Reduction {
a: DataType,
c: DataType,
d: DataType,
},
ContractionTrinary {
a: DataType,
b: DataType,
c: DataType,
d: DataType,
e: DataType,
},
BlockSparseContraction {
a_non_zero_blocks: u64,
b_non_zero_blocks: u64,
c_non_zero_blocks: u64,
d_non_zero_blocks: u64,
},
}
impl OperationKind {
pub const fn name(self) -> &'static str {
match self {
Self::ElementwiseTrinary { .. } => "elementwise_trinary",
Self::ElementwiseBinary { .. } => "elementwise_binary",
Self::Permutation { .. } => "permute",
Self::Contraction { .. } => "contract",
Self::Reduction { .. } => "reduce",
Self::ContractionTrinary { .. } => "contract_trinary",
Self::BlockSparseContraction { .. } => "block_sparse_contract",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperationSignature {
pub kind: OperationKind,
pub scalar_type: DataType,
}
#[derive(Debug, Clone, Copy)]
enum OwnedPaddingValue {
F32(f32),
F64(f64),
F16(f16),
Bf16(bf16),
F8E4M3(f8e4m3),
F8E5M2(f8e5m2),
F8UE8M0(f8ue8m0),
F6E2M3(f6e2m3),
F6E3M2(f6e3m2),
F4E2M1(f4e2m1),
I8(i8),
U8(u8),
I32(i32),
U32(u32),
Complex32(Complex32),
Complex64(Complex64),
}
impl OwnedPaddingValue {
fn from_value<T: DataTypeLike>(value: T) -> Result<Self> {
match T::data_type() {
DataType::F32 => Ok(Self::F32(unsafe { std::mem::transmute_copy(&value) })),
DataType::F64 => Ok(Self::F64(unsafe { std::mem::transmute_copy(&value) })),
DataType::F16 => Ok(Self::F16(unsafe { std::mem::transmute_copy(&value) })),
DataType::Bf16 => Ok(Self::Bf16(unsafe { std::mem::transmute_copy(&value) })),
DataType::F8E4M3 => Ok(Self::F8E4M3(unsafe { std::mem::transmute_copy(&value) })),
DataType::F8E5M2 => Ok(Self::F8E5M2(unsafe { std::mem::transmute_copy(&value) })),
DataType::F8UE8M0 => Ok(Self::F8UE8M0(unsafe { std::mem::transmute_copy(&value) })),
DataType::F6E2M3 => Ok(Self::F6E2M3(unsafe { std::mem::transmute_copy(&value) })),
DataType::F6E3M2 => Ok(Self::F6E3M2(unsafe { std::mem::transmute_copy(&value) })),
DataType::F4E2M1 => Ok(Self::F4E2M1(unsafe { std::mem::transmute_copy(&value) })),
DataType::I8 => Ok(Self::I8(unsafe { std::mem::transmute_copy(&value) })),
DataType::U8 => Ok(Self::U8(unsafe { std::mem::transmute_copy(&value) })),
DataType::I32 => Ok(Self::I32(unsafe { std::mem::transmute_copy(&value) })),
DataType::U32 => Ok(Self::U32(unsafe { std::mem::transmute_copy(&value) })),
DataType::ComplexF32 => {
Ok(Self::Complex32(unsafe { std::mem::transmute_copy(&value) }))
}
DataType::ComplexF64 => {
Ok(Self::Complex64(unsafe { std::mem::transmute_copy(&value) }))
}
data_type => Err(Error::UnsupportedScalarDataType {
name: T::rust_type_name().into(),
data_type,
}),
}
}
fn host_ptr(&self) -> *const () {
match self {
Self::F32(value) => ptr::from_ref(value).cast(),
Self::F64(value) => ptr::from_ref(value).cast(),
Self::F16(value) => ptr::from_ref(value).cast(),
Self::Bf16(value) => ptr::from_ref(value).cast(),
Self::F8E4M3(value) => ptr::from_ref(value).cast(),
Self::F8E5M2(value) => ptr::from_ref(value).cast(),
Self::F8UE8M0(value) => ptr::from_ref(value).cast(),
Self::F6E2M3(value) => ptr::from_ref(value).cast(),
Self::F6E3M2(value) => ptr::from_ref(value).cast(),
Self::F4E2M1(value) => ptr::from_ref(value).cast(),
Self::I8(value) => ptr::from_ref(value).cast(),
Self::U8(value) => ptr::from_ref(value).cast(),
Self::I32(value) => ptr::from_ref(value).cast(),
Self::U32(value) => ptr::from_ref(value).cast(),
Self::Complex32(value) => ptr::from_ref(value).cast(),
Self::Complex64(value) => ptr::from_ref(value).cast(),
}
}
fn size_bytes(&self) -> usize {
match self {
Self::F32(_) => size_of::<f32>(),
Self::F64(_) => size_of::<f64>(),
Self::F16(_) => size_of::<f16>(),
Self::Bf16(_) => size_of::<bf16>(),
Self::F8E4M3(_) => size_of::<f8e4m3>(),
Self::F8E5M2(_) => size_of::<f8e5m2>(),
Self::F8UE8M0(_) => size_of::<f8ue8m0>(),
Self::F6E2M3(_) => size_of::<f6e2m3>(),
Self::F6E3M2(_) => size_of::<f6e3m2>(),
Self::F4E2M1(_) => size_of::<f4e2m1>(),
Self::I8(_) => size_of::<i8>(),
Self::U8(_) => size_of::<u8>(),
Self::I32(_) => size_of::<i32>(),
Self::U32(_) => size_of::<u32>(),
Self::Complex32(_) => size_of::<Complex32>(),
Self::Complex64(_) => size_of::<Complex64>(),
}
}
}
impl OperationDescriptor {
/// Creates an operation descriptor that encodes an element-wise trinary operation.
///
/// The trinary operation has the following general form:
///
/// $$ D\_{\Pi^C(i\_0,i\_1,...,i\_n)} = \Phi\_{ABC}(\Phi\_{AB}(\alpha op\_A(A\_{\Pi^A(i\_0,i\_1,...,i\_n)}), \beta op\_B(B\_{\Pi^B(i\_0,i\_1,...,i\_n)})), \gamma op\_C(C\_{\Pi^C(i\_0,i\_1,...,i\_n)})) $$
///
/// Where:
///
/// * A,B,C,D are multi-mode tensors (of arbitrary data types).
/// * $\Pi^A, \Pi^B, \Pi^C$ are permutation operators that permute the modes of A, B, and C respectively.
/// * $op\_{A},op\_{B},op\_{C}$ are unary element-wise operators, such as IDENTITY and CONJUGATE.
/// * $\Phi\_{ABC}, \Phi\_{AB}$ are binary element-wise operators, such as ADD, MUL, MAX, and MIN.
///
/// Broadcasting can be achieved by omitting that mode from the respective tensor.
///
/// Modes may appear in any order.
/// The only **restrictions** are:
///
/// * modes that appear in A or B *must* also appear in the output tensor; a mode that only appears in the input would be contracted and such an operation would be covered by either [`Plan::contract`](crate::plan::Plan::contract) or [`Plan::reduce`](crate::plan::Plan::reduce).
/// * each mode may appear in each tensor at most once.
///
/// Input tensors may be read even if the value of the corresponding scalar is zero.
///
/// Examples:
///
/// * $D\_{a,b,c,d} = A\_{b,d,a,c}$
/// * $D\_{a,b,c,d} = 2.2 \cdot A\_{b,d,a,c} + 1.3 \cdot B\_{c,b,d,a}$
/// * $D\_{a,b,c,d} = 2.2 \cdot A\_{b,d,a,c} + 1.3 \cdot B\_{c,b,d,a} + C\_{a,b,c,d}$
/// * $D\_{a,b,c,d} = min((2.2 \cdot A\_{b,d,a,c} + 1.3 \cdot B\_{c,b,d,a}), C\_{a,b,c,d})$
///
/// Call [`Plan::elementwise_trinary`](crate::plan::Plan::elementwise_trinary) to perform the actual operation.
///
/// The returned descriptor frees the cuTENSOR descriptor when dropped.
///
/// Supported data-type combinations are:
///
/// | A type | B type | C type | compute descriptor |
/// | --- | --- | --- | --- |
/// | [`DataType::F16`] | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f16`] |
/// | [`DataType::F16`] | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::bf16`] |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F32`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f64`] |
///
/// This may call asynchronous CUDA functions. cuTENSOR treats descriptor
/// creation as thread-safe but not reentrant.
///
/// # Errors
///
/// Returns an error if the context cannot be bound, tensor modes do not
/// match descriptor ranks, the target architecture is unsupported or not
/// ready, cuTENSOR rejects the operand descriptors, or cuTENSOR returns a
/// null operation descriptor.
pub fn elementwise_trinary(
ctx: &Context,
lhs: TensorOperand<'_>,
rhs: TensorOperand<'_>,
aux: TensorOperand<'_>,
out: TensorOperand<'_>,
op_ab: Operator,
op_abc: Operator,
compute_descriptor: ComputeDescriptor,
) -> Result<Self> {
let context = ctx.as_context_ref();
validate_tensor_operand_context(&context, lhs, "lhs")?;
validate_tensor_operand_context(&context, rhs, "rhs")?;
validate_tensor_operand_context(&context, aux, "aux")?;
validate_tensor_operand_context(&context, out, "out")?;
validate_modes(lhs.desc.rank(), lhs.modes)?;
validate_modes(rhs.desc.rank(), rhs.modes)?;
validate_modes(aux.desc.rank(), aux.modes)?;
validate_modes(out.desc.rank(), out.modes)?;
let mode_a = modes_to_i32_vec(lhs.modes);
let mode_b = modes_to_i32_vec(rhs.modes);
let mode_c = modes_to_i32_vec(aux.modes);
let mode_d = modes_to_i32_vec(out.modes);
let mut raw = ptr::null_mut();
ctx.bind()?;
unsafe {
try_ffi!(sys::cutensorCreateElementwiseTrinary(
ctx.as_raw(),
&raw mut raw,
lhs.desc.as_raw(),
mode_a.as_ptr(),
lhs.op.into(),
rhs.desc.as_raw(),
mode_b.as_ptr(),
rhs.op.into(),
aux.desc.as_raw(),
mode_c.as_ptr(),
aux.op.into(),
out.desc.as_raw(),
mode_d.as_ptr(),
op_ab.into(),
op_abc.into(),
compute_descriptor.into(),
))?;
}
Self::from_raw(
raw,
context,
out.desc.rank(),
out.desc.data_type(),
OperationKind::ElementwiseTrinary {
a: lhs.desc.data_type(),
b: rhs.desc.data_type(),
c: aux.desc.data_type(),
d: out.desc.data_type(),
},
)
}
/// Creates an operation descriptor for an element-wise binary operation.
///
/// The binary operation has the following general form:
///
/// $$ D\_{\Pi^C(i\_0,i\_1,...,i\_n)} = \Phi\_{AC}(\alpha op\_A(A\_{\Pi^A(i\_0,i\_1,...,i\_n)}), \gamma op\_C(C\_{\Pi^C(i\_0,i\_1,...,i\_n)})) $$
///
/// Call [`Plan::elementwise_binary`](crate::plan::Plan::elementwise_binary) to perform the actual operation.
///
/// Supported data-type combinations are:
///
/// | A type | C type | compute descriptor |
/// | --- | --- | --- |
/// | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f16`] |
/// | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::bf16`] |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::F32`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F64`] | [`DataType::F32`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f64`] |
///
/// This may call asynchronous CUDA functions. cuTENSOR treats descriptor
/// creation as thread-safe but not reentrant.
///
/// # Errors
///
/// Returns an error if the context cannot be bound, tensor modes do not
/// match descriptor ranks, input and output descriptors or mode sets are
/// incompatible, a data type or operator combination is unsupported,
/// cuTENSOR rejects the operands, or cuTENSOR returns a null operation
/// descriptor.
pub fn elementwise_binary(
ctx: &Context,
a: TensorOperand<'_>,
c: TensorOperand<'_>,
d: TensorOperand<'_>,
op_ac: Operator,
compute_descriptor: ComputeDescriptor,
) -> Result<Self> {
let context = ctx.as_context_ref();
validate_tensor_operand_context(&context, a, "a")?;
validate_tensor_operand_context(&context, c, "c")?;
validate_tensor_operand_context(&context, d, "d")?;
validate_modes(a.desc.rank(), a.modes)?;
validate_modes(c.desc.rank(), c.modes)?;
validate_modes(d.desc.rank(), d.modes)?;
validate_tensor_descriptors_match(c.desc, d.desc, "elementwise binary output")?;
validate_mode_names_match(c.modes, d.modes, "elementwise binary output")?;
let mode_a = modes_to_i32_vec(a.modes);
let mode_c = modes_to_i32_vec(c.modes);
let mode_d = modes_to_i32_vec(d.modes);
let mut raw = ptr::null_mut();
ctx.bind()?;
unsafe {
try_ffi!(sys::cutensorCreateElementwiseBinary(
ctx.as_raw(),
&raw mut raw,
a.desc.as_raw(),
mode_a.as_ptr(),
a.op.into(),
c.desc.as_raw(),
mode_c.as_ptr(),
c.op.into(),
d.desc.as_raw(),
mode_d.as_ptr(),
op_ac.into(),
compute_descriptor.into(),
))?;
}
Self::from_raw(
raw,
context,
d.desc.rank(),
d.desc.data_type(),
OperationKind::ElementwiseBinary {
a: a.desc.data_type(),
c: c.desc.data_type(),
d: d.desc.data_type(),
},
)
}
/// Creates an operation descriptor for a tensor permutation.
///
/// The tensor permutation has the following general form:
///
/// $$ B\_{\Pi^B(i\_0,i\_1,...,i\_n)} = \alpha op\_A(A\_{\Pi^A(i\_0,i\_1,...,i\_n)}) $$
///
/// Consequently, tensor permutation is an out-of-place operation and a specialization of [`OperationDescriptor::elementwise_binary`].
///
/// Where:
///
/// * `A` and `B` are multi-mode tensors of arbitrary data types.
/// * $\Pi^A$ and $\Pi^B$ permute the modes of `A` and `B`, respectively.
/// * $op\_A$ is a unary element-wise operator such as identity, square, or conjugate.
///
/// Broadcasting can be achieved by omitting that mode from the respective tensor.
///
/// Modes may appear in any order.
/// The only **restrictions** are:
///
/// * modes that appear in A *must* also appear in the output tensor.
/// * each mode may appear in each tensor at most once.
///
/// Supported data-type combinations are:
///
/// | A type | B type | compute descriptor |
/// | --- | --- | --- |
/// | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f16`] |
/// | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F16`] | [`DataType::F32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F32`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::bf16`] |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::F32`] | [`DataType::F64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::F64`] | [`DataType::F32`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f64`] |
///
/// This may call asynchronous CUDA functions. cuTENSOR treats descriptor
/// creation as thread-safe but not reentrant.
///
/// # Errors
///
/// Returns an error if the context cannot be bound, tensor modes do not
/// match descriptor ranks, a requested output mode is invalid, a data type
/// or operator combination is unsupported, cuTENSOR rejects the operands,
/// or cuTENSOR returns a null operation descriptor.
pub fn permutation(
ctx: &Context,
a: TensorOperand<'_>,
b: TensorOperand<'_>,
compute_descriptor: ComputeDescriptor,
) -> Result<Self> {
let context = ctx.as_context_ref();
validate_tensor_operand_context(&context, a, "a")?;
validate_tensor_operand_context(&context, b, "b")?;
validate_modes(a.desc.rank(), a.modes)?;
validate_modes(b.desc.rank(), b.modes)?;
let mode_a = modes_to_i32_vec(a.modes);
let mode_b = modes_to_i32_vec(b.modes);
let mut raw = ptr::null_mut();
ctx.bind()?;
unsafe {
try_ffi!(sys::cutensorCreatePermutation(
ctx.as_raw(),
&raw mut raw,
a.desc.as_raw(),
mode_a.as_ptr(),
a.op.into(),
b.desc.as_raw(),
mode_b.as_ptr(),
compute_descriptor.into(),
))?;
}
Self::from_raw(
raw,
context,
b.desc.rank(),
b.desc.data_type(),
OperationKind::Permutation {
a: a.desc.data_type(),
b: b.desc.data_type(),
},
)
}
/// Creates an operation descriptor for a tensor contraction of the form $D = \alpha \mathcal{A} \mathcal{B} + \beta \mathcal{C}$.
///
/// The descriptor represents a tensor contraction of the form:
///
/// $$ \mathcal{D}\_{{modes}\_\mathcal{D}} \gets \alpha op\_\mathcal{A}(\mathcal{A}\_{{modes}\_\mathcal{A}}) op\_\mathcal{B}(B\_{{modes}\_\mathcal{B}}) + \beta op\_\mathcal{C}(\mathcal{C}\_{{modes}\_\mathcal{C}}). $$
/// Use [`Plan::create`](crate::plan::Plan::create) to select a kernel, then call [`Plan::contract`](crate::plan::Plan::contract) to execute the contraction.
///
/// The returned descriptor frees the cuTENSOR operation descriptor when dropped.
///
/// Supported data-type combinations are:
///
/// | A type | B type | C type | compute descriptor | scalar type | Tensor Core |
/// | --- | --- | --- | --- | --- | --- |
/// | [`DataType::F16`] | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] | [`DataType::F32`] | Volta+ |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::f32`] | [`DataType::F32`] | Ampere+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f32`] | [`DataType::F32`] | No |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::tf32`] | [`DataType::F32`] | Ampere+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::tf32x3`] | [`DataType::F32`] | Ampere+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::bf16`] | [`DataType::F32`] | Ampere+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f16`] | [`DataType::F32`] | Volta+ |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f64`] | [`DataType::F64`] | Ampere+ |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f32`] | [`DataType::F64`] | No |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f32`] | [`DataType::ComplexF32`] | No |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::tf32`] | [`DataType::ComplexF32`] | Ampere+ |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::tf32x3`] | [`DataType::ComplexF32`] | Ampere+ |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] | [`DataType::ComplexF64`] | Ampere+ |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f32`] | [`DataType::ComplexF64`] | No |
/// | [`DataType::F64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] | [`DataType::ComplexF64`] | No |
/// | [`DataType::ComplexF64`] | [`DataType::F64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] | [`DataType::ComplexF64`] | No |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::i8x8`] | [`DataType::F64`] | Hopper+ |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::i8x8`] | [`DataType::ComplexF64`] | Hopper+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::bf16x9`] | [`DataType::F32`] | Hopper+ |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::bf16x9`] | [`DataType::ComplexF32`] | Hopper+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f16x4`] | [`DataType::F32`] | Blackwell+ |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f16x4`] | [`DataType::ComplexF32`] | Blackwell+ |
///
/// # Errors
///
/// Returns an error if the context cannot be bound, tensor modes do not
/// match descriptor ranks, input and output descriptors or mode sets are
/// incompatible, a data type or operator combination is unsupported,
/// cuTENSOR rejects the operands, or cuTENSOR returns a null operation
/// descriptor.
pub fn contraction(
ctx: &Context,
a: TensorOperand<'_>,
b: TensorOperand<'_>,
c: TensorOperand<'_>,
d: TensorOperand<'_>,
compute_descriptor: ComputeDescriptor,
) -> Result<Self> {
let context = ctx.as_context_ref();
validate_tensor_operand_context(&context, a, "a")?;
validate_tensor_operand_context(&context, b, "b")?;
validate_tensor_operand_context(&context, c, "c")?;
validate_tensor_operand_context(&context, d, "d")?;
validate_modes(a.desc.rank(), a.modes)?;
validate_modes(b.desc.rank(), b.modes)?;
validate_modes(c.desc.rank(), c.modes)?;
validate_modes(d.desc.rank(), d.modes)?;
validate_tensor_descriptors_match(c.desc, d.desc, "contraction output")?;
validate_mode_names_match(c.modes, d.modes, "contraction output")?;
let mode_a = modes_to_i32_vec(a.modes);
let mode_b = modes_to_i32_vec(b.modes);
let mode_c = modes_to_i32_vec(c.modes);
let mode_d = modes_to_i32_vec(d.modes);
let mut raw = ptr::null_mut();
ctx.bind()?;
unsafe {
try_ffi!(sys::cutensorCreateContraction(
ctx.as_raw(),
&raw mut raw,
a.desc.as_raw(),
mode_a.as_ptr(),
a.op.into(),
b.desc.as_raw(),
mode_b.as_ptr(),
b.op.into(),
c.desc.as_raw(),
mode_c.as_ptr(),
c.op.into(),
d.desc.as_raw(),
mode_d.as_ptr(),
compute_descriptor.into(),
))?;
}
Self::from_raw(
raw,
context,
d.desc.rank(),
d.desc.data_type(),
OperationKind::Contraction {
a: a.desc.data_type(),
b: b.desc.data_type(),
c: c.desc.data_type(),
d: d.desc.data_type(),
},
)
}
/// Creates an operation descriptor for a tensor reduction of the form $D = \alpha \cdot op\_reduce(op\_A(A)) + \beta \cdot op\_C(C)$.
///
/// For example, this can reduce an entire tensor to a scalar: `C[] = alpha * A[i,j,k]`.
///
/// Can also perform partial reductions; for instance,
/// `C[i,j] = alpha * A[k,j,i]`.
/// In this case only elements along the `k` mode are contracted.
///
/// The binary `op_reduce` operator controls the kind of reduction that is performed.
/// For instance, setting `op_reduce` to [`Operator::Add`] reduces elements of A via a summation while [`Operator::Max`] would find the largest element in A.
///
/// Supported data-type combinations are:
///
/// | A type | B type | C type | compute type |
/// | --- | --- | --- | --- |
/// | [`DataType::F16`] | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f16`] |
/// | [`DataType::F16`] | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::bf16`] |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f64`] |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f32`] |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] |
///
/// # Errors
///
/// Returns an error if the context cannot be bound, tensor modes do not
/// match descriptor ranks, input and output descriptors or mode sets are
/// incompatible, a data type or reduction operator combination is
/// unsupported, cuTENSOR rejects the operands, or cuTENSOR returns a null
/// operation descriptor.
pub fn reduction(
ctx: &Context,
a: TensorOperand<'_>,
c: TensorOperand<'_>,
d: TensorOperand<'_>,
op_reduce: Operator,
compute_descriptor: ComputeDescriptor,
) -> Result<Self> {
let context = ctx.as_context_ref();
validate_tensor_operand_context(&context, a, "a")?;
validate_tensor_operand_context(&context, c, "c")?;
validate_tensor_operand_context(&context, d, "d")?;
validate_modes(a.desc.rank(), a.modes)?;
validate_modes(c.desc.rank(), c.modes)?;
validate_modes(d.desc.rank(), d.modes)?;
validate_tensor_descriptors_match(c.desc, d.desc, "reduction output")?;
validate_mode_names_match(c.modes, d.modes, "reduction output")?;
let mode_a = modes_to_i32_vec(a.modes);
let mode_c = modes_to_i32_vec(c.modes);
let mode_d = modes_to_i32_vec(d.modes);
let mut raw = ptr::null_mut();
ctx.bind()?;
unsafe {
try_ffi!(sys::cutensorCreateReduction(
ctx.as_raw(),
&raw mut raw,
a.desc.as_raw(),
mode_a.as_ptr(),
a.op.into(),
c.desc.as_raw(),
mode_c.as_ptr(),
c.op.into(),
d.desc.as_raw(),
mode_d.as_ptr(),
op_reduce.into(),
compute_descriptor.into(),
))?;
}
Self::from_raw(
raw,
context,
d.desc.rank(),
d.desc.data_type(),
OperationKind::Reduction {
a: a.desc.data_type(),
c: c.desc.data_type(),
d: d.desc.data_type(),
},
)
}
/// Creates an operation descriptor for a tensor contraction of the form $\mathcal{E} = \alpha \mathcal{A} \mathcal{B} \mathcal{C} + \beta \mathcal{D}$.
///
/// The descriptor represents a tensor contraction of the form:
///
/// $$ \mathcal{E}\_{{modes}\_\mathcal{E}} \gets \alpha op\_\mathcal{A}(\mathcal{A}\_{{modes}\_\mathcal{A}}) op\_\mathcal{B}(\mathcal{B}\_{{modes}\_\mathcal{B}}) op\_\mathcal{C}(\mathcal{C}\_{{modes}\_\mathcal{C}}) + \beta op\_\mathcal{D}(\mathcal{D}\_{{modes}\_\mathcal{D}}). $$
/// Use [`Plan::create`](crate::plan::Plan::create) to select a kernel, then call [`Plan::contract_trinary`](crate::plan::Plan::contract_trinary) to execute the contraction.
///
/// The returned descriptor frees the cuTENSOR operation descriptor when dropped.
///
/// Performance improvements are currently especially high for host-resident
/// data, also called out-of-core data, on Grace-based systems.
///
/// Supported data-type combinations are:
///
/// | A type | B type | C type | D type | compute descriptor | scalar type | Tensor Core |
/// | --- | --- | --- | --- | --- | --- | --- |
/// | [`DataType::F16`] | [`DataType::F16`] | [`DataType::F16`] | [`DataType::F16`] | [`ComputeDescriptor::f32`] | [`DataType::F32`] | Volta+ |
/// | [`DataType::Bf16`] | [`DataType::Bf16`] | [`DataType::Bf16`] | [`DataType::Bf16`] | [`ComputeDescriptor::f32`] | [`DataType::F32`] | Ampere+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f32`] | [`DataType::F32`] | No |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::tf32`] | [`DataType::F32`] | Ampere+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::tf32x3`] | [`DataType::F32`] | Ampere+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::bf16`] | [`DataType::F32`] | Ampere+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f16`] | [`DataType::F32`] | Volta+ |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f64`] | [`DataType::F64`] | Ampere+ |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f32`] | [`DataType::F64`] | No |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f32`] | [`DataType::ComplexF32`] | No |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::tf32`] | [`DataType::ComplexF32`] | Ampere+ |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::tf32x3`] | [`DataType::ComplexF32`] | Ampere+ |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] | [`DataType::ComplexF64`] | Ampere+ |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f32`] | [`DataType::ComplexF64`] | No |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::i8x8`] | [`DataType::F64`] | Hopper+ |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::i8x8`] | [`DataType::ComplexF64`] | Hopper+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::bf16x9`] | [`DataType::F32`] | Hopper+ |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::bf16x9`] | [`DataType::ComplexF32`] | Hopper+ |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f16x4`] | [`DataType::F32`] | Blackwell+ |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f16x4`] | [`DataType::ComplexF32`] | Blackwell+ |
///
/// # Errors
///
/// Returns an error if the context cannot be bound, tensor modes do not
/// match descriptor ranks, input and output descriptors or mode sets are
/// incompatible, a data type or operator combination is unsupported,
/// cuTENSOR rejects the operands, or cuTENSOR returns a null operation
/// descriptor.
pub fn contraction_trinary(
ctx: &Context,
lhs: TensorOperand<'_>,
rhs: TensorOperand<'_>,
aux: TensorOperand<'_>,
input: TensorOperand<'_>,
output: TensorOperand<'_>,
compute_descriptor: ComputeDescriptor,
) -> Result<Self> {
let context = ctx.as_context_ref();
validate_tensor_operand_context(&context, lhs, "lhs")?;
validate_tensor_operand_context(&context, rhs, "rhs")?;
validate_tensor_operand_context(&context, aux, "aux")?;
validate_tensor_operand_context(&context, input, "input")?;
validate_tensor_operand_context(&context, output, "output")?;
validate_modes(lhs.desc.rank(), lhs.modes)?;
validate_modes(rhs.desc.rank(), rhs.modes)?;
validate_modes(aux.desc.rank(), aux.modes)?;
validate_modes(input.desc.rank(), input.modes)?;
validate_modes(output.desc.rank(), output.modes)?;
validate_tensor_descriptors_match(input.desc, output.desc, "trinary contraction output")?;
validate_mode_names_match(input.modes, output.modes, "trinary contraction output")?;
let mode_a = modes_to_i32_vec(lhs.modes);
let mode_b = modes_to_i32_vec(rhs.modes);
let mode_c = modes_to_i32_vec(aux.modes);
let mode_d = modes_to_i32_vec(input.modes);
let mode_e = modes_to_i32_vec(output.modes);
let mut raw = ptr::null_mut();
ctx.bind()?;
unsafe {
try_ffi!(sys::cutensorCreateContractionTrinary(
ctx.as_raw(),
&raw mut raw,
lhs.desc.as_raw(),
mode_a.as_ptr(),
lhs.op.into(),
rhs.desc.as_raw(),
mode_b.as_ptr(),
rhs.op.into(),
aux.desc.as_raw(),
mode_c.as_ptr(),
aux.op.into(),
input.desc.as_raw(),
mode_d.as_ptr(),
input.op.into(),
output.desc.as_raw(),
mode_e.as_ptr(),
compute_descriptor.into(),
))?;
}
Self::from_raw(
raw,
context,
output.desc.rank(),
output.desc.data_type(),
OperationKind::ContractionTrinary {
a: lhs.desc.data_type(),
b: rhs.desc.data_type(),
c: aux.desc.data_type(),
d: input.desc.data_type(),
e: output.desc.data_type(),
},
)
}
/// Creates an operation descriptor for a block-sparse tensor contraction of the form $D = \alpha \mathcal{A} \mathcal{B} + \beta \mathcal{C}$.
///
/// The descriptor represents a block-sparse tensor contraction of the form:
///
/// $$ \mathcal{D}\_{{modes}\_\mathcal{D}} \gets \alpha op\_\mathcal{A}(\mathcal{A}\_{{modes}\_\mathcal{A}}) op\_\mathcal{B}(B\_{{modes}\_\mathcal{B}}) + \beta op\_\mathcal{C}(\mathcal{C}\_{{modes}\_\mathcal{C}}). $$
///
/// Only the predefined non-zero blocks of $\mathcal{D}$ that were specified in [`BlockSparseTensorDescriptor::create`] are actually computed.
/// The other blocks are omitted, even if the true result of the contraction would be non-zero.
/// Conversely, if a predefined non-zero block of $\mathcal{D}$ is present but the result of the contraction is zero for this block, explicit zeros are stored.
///
/// Currently, the data-types for the tensors `A`, `B`, `C`, and `D`, as well as the scalars $\alpha$ and $\beta$ must all be identical, and the only supported types are [`DataType::ComplexF64`], [`DataType::ComplexF32`], [`DataType::F64`], and [`DataType::F32`].
/// The compute type must match as well; currently supported combinations are:
///
/// | A type | B type | C type | D type | compute descriptor | scalar type |
/// | --- | --- | --- | --- | --- | --- |
/// | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`DataType::F32`] | [`ComputeDescriptor::f32`] | [`DataType::F32`] |
/// | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`DataType::F64`] | [`ComputeDescriptor::f64`] | [`DataType::F64`] |
/// | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`DataType::ComplexF32`] | [`ComputeDescriptor::f32`] | [`DataType::ComplexF32`] |
/// | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`DataType::ComplexF64`] | [`ComputeDescriptor::f64`] | [`DataType::ComplexF64`] |
///
/// For every mode, the segmentation of that mode must be identical in all tensors that it occurs in.
/// For example, if mode `i` of tensor `A` matches mode `j` of tensor `B`, then the section count for mode `i` in `A` must match the section count for mode `j` in `B`, and the corresponding section extents must be identical.
///
/// For example, let A, B, and C be block matrices and consider the ordinary matrix-matrix product $C\_{mn}=A\_{mk}B\_{kn}$.
/// Then:
///
/// * Mode ‘m’: C and A must have the same number of block-rows, and each block-row of C must contain the same number of rows as the corresponding block-row of A.
/// * Mode ‘n’: C and B must have the same number of block-columns of matching size.
/// * Mode ‘k’: A must have the same number of block-columns as B has block-rows, and each block-column of A must contain the same number of columns as the number of rows in the corresponding block-row of B.
///
/// `input` and `output` must use identical descriptors: the same opaque pointer must be passed, and the layouts of the input and output tensors must be identical.
///
/// See [`sys::cutensorCreatePlan`] to create the plan, [`Plan::estimate_workspace_size`](crate::plan::Plan::estimate_workspace_size) to compute the required workspace, and finally [`Plan::block_sparse_contract`](crate::plan::Plan::block_sparse_contract) to perform the actual contraction.
///
/// The returned descriptor frees the cuTENSOR operation descriptor when dropped.
///
/// # Errors
///
/// Returns an error if the context cannot be bound, block-sparse tensor
/// modes do not match descriptor ranks, input and output descriptors or
/// mode sets are incompatible, section sizes are invalid, a data type or
/// operator combination is unsupported, cuTENSOR rejects the operands, or
/// cuTENSOR returns a null operation descriptor.
pub fn block_sparse_contraction(
ctx: &Context,
a: BlockSparseTensorOperand<'_>,
b: BlockSparseTensorOperand<'_>,
c: BlockSparseTensorOperand<'_>,
d: BlockSparseTensorOperand<'_>,
compute_descriptor: ComputeDescriptor,
) -> Result<Self> {
let context = ctx.as_context_ref();
validate_block_sparse_tensor_operand_context(&context, a, "a")?;
validate_block_sparse_tensor_operand_context(&context, b, "b")?;
validate_block_sparse_tensor_operand_context(&context, c, "c")?;
validate_block_sparse_tensor_operand_context(&context, d, "d")?;
validate_modes(a.desc.mode_count(), a.modes)?;
validate_modes(b.desc.mode_count(), b.modes)?;
validate_modes(c.desc.mode_count(), c.modes)?;
validate_modes(d.desc.mode_count(), d.modes)?;
validate_block_sparse_tensor_descriptors_match(c.desc, d.desc, "block sparse output")?;
validate_mode_names_match(c.modes, d.modes, "block sparse output")?;
let mode_a = modes_to_i32_vec(a.modes);
let mode_b = modes_to_i32_vec(b.modes);
let mode_c = modes_to_i32_vec(c.modes);
let mode_d = modes_to_i32_vec(d.modes);
let mut raw = ptr::null_mut();
ctx.bind()?;
unsafe {
try_ffi!(sys::cutensorCreateBlockSparseContraction(
ctx.as_raw(),
&raw mut raw,
a.desc.as_raw(),
mode_a.as_ptr(),
a.op.into(),
b.desc.as_raw(),
mode_b.as_ptr(),
b.op.into(),
c.desc.as_raw(),
mode_c.as_ptr(),
c.op.into(),
d.desc.as_raw(),
mode_d.as_ptr(),
compute_descriptor.into(),
))?;
}
Self::from_raw(
raw,
context,
d.desc.mode_count(),
d.desc.data_type(),
OperationKind::BlockSparseContraction {
a_non_zero_blocks: a.desc.non_zero_block_count(),
b_non_zero_blocks: b.desc.non_zero_block_count(),
c_non_zero_blocks: c.desc.non_zero_block_count(),
d_non_zero_blocks: d.desc.non_zero_block_count(),
},
)
}
fn set_attribute<T>(&mut self, attr: OperationDescriptorAttribute, value: &T) -> Result<()> {
validate_operation_attribute_size(attr, size_of::<T>())?;
self.context.bind()?;
unsafe {
try_ffi!(sys::cutensorOperationDescriptorSetAttribute(
self.context.as_raw(),
self.handle,
attr.into(),
ptr::from_ref(value).cast(),
size_of::<T>() as _,
))?;
}
Ok(())
}
fn attribute<T>(&self, attr: OperationDescriptorAttribute) -> Result<T> {
validate_operation_attribute_size(attr, size_of::<T>())?;
let mut value = MaybeUninit::<T>::uninit();
self.context.bind()?;
unsafe {
try_ffi!(sys::cutensorOperationDescriptorGetAttribute(
self.context.as_raw(),
self.handle,
attr.into(),
value.as_mut_ptr().cast(),
size_of::<T>() as _,
))?;
Ok(value.assume_init())
}
}
pub fn tag(&self) -> Result<i32> {
let value = self.attribute(OperationDescriptorAttribute::Tag)?;
Ok(value)
}
pub fn set_tag(&mut self, tag: i32) -> Result<()> {
self.set_attribute(OperationDescriptorAttribute::Tag, &tag)
}
pub fn scalar_type(&self) -> Result<DataType> {
self.attribute(OperationDescriptorAttribute::ScalarType)
}
pub fn set_scalar_type(&mut self, data_type: DataType) -> Result<()> {
self.set_attribute(OperationDescriptorAttribute::ScalarType, &data_type)?;
self.signature.scalar_type = data_type;
Ok(())
}
pub fn padding_left(&self) -> Result<Vec<u32>> {
self.padding(OperationDescriptorAttribute::PaddingLeft)
}
pub fn set_padding_left(&mut self, padding: &[u32]) -> Result<()> {
self.set_padding(OperationDescriptorAttribute::PaddingLeft, padding)
}
pub fn padding_right(&self) -> Result<Vec<u32>> {
self.padding(OperationDescriptorAttribute::PaddingRight)
}
pub fn set_padding_right(&mut self, padding: &[u32]) -> Result<()> {
self.set_padding(OperationDescriptorAttribute::PaddingRight, padding)
}
pub fn set_padding_value<T: DataTypeLike>(&mut self, value: T) -> Result<()> {
if self.output_data_type != T::data_type() {
return Err(Error::ScalarDataTypeMismatch {
descriptor: self.output_data_type,
memory: T::data_type(),
});
}
let owned = OwnedPaddingValue::from_value(value)?;
self.context.bind()?;
unsafe {
try_ffi!(sys::cutensorOperationDescriptorSetAttribute(
self.context.as_raw(),
self.handle,
OperationDescriptorAttribute::PaddingValue.into(),
owned.host_ptr().cast(),
owned.size_bytes() as _,
))?;
}
self.padding_value = Some(owned);
Ok(())
}
pub fn flops(&self) -> Result<f32> {
self.attribute(OperationDescriptorAttribute::Flops)
}
pub fn moved_bytes(&self) -> Result<f32> {
self.attribute(OperationDescriptorAttribute::MovedBytes)
}
pub(crate) fn signature(&self) -> OperationSignature {
self.signature
}
pub const fn as_raw(&self) -> sys::cutensorOperationDescriptor_t {
self.handle
}
/// Consumes the descriptor and returns the raw cuTENSOR operation
/// descriptor handle without destroying it.
///
/// The caller becomes responsible for eventually destroying the returned
/// handle with cuTENSOR.
pub fn into_raw(self) -> sys::cutensorOperationDescriptor_t {
let descriptor = ManuallyDrop::new(self);
descriptor.handle
}
fn from_raw(
handle: sys::cutensorOperationDescriptor_t,
ctx: ContextRef,
output_rank: u32,
output_data_type: DataType,
kind: OperationKind,
) -> Result<Self> {
if handle.is_null() {
return Err(Error::NullHandle);
}
let scalar_type = {
let mut value = MaybeUninit::<DataType>::uninit();
ctx.bind()?;
unsafe {
try_ffi!(sys::cutensorOperationDescriptorGetAttribute(
ctx.as_raw(),
handle,
OperationDescriptorAttribute::ScalarType.into(),
value.as_mut_ptr().cast(),
size_of::<DataType>() as _,
))?;
value.assume_init()
}
};
Ok(Self {
handle,
context: ctx,
output_rank,
output_data_type,
signature: OperationSignature { kind, scalar_type },
padding_value: None,
})
}
fn padding(&self, attr: OperationDescriptorAttribute) -> Result<Vec<u32>> {
debug_assert!(matches!(
attr,
OperationDescriptorAttribute::PaddingLeft | OperationDescriptorAttribute::PaddingRight
));
let mut padding = vec![0_u32; self.output_rank as usize];
self.context.bind()?;
unsafe {
try_ffi!(sys::cutensorOperationDescriptorGetAttribute(
self.context.as_raw(),
self.handle,
attr.into(),
padding.as_mut_ptr().cast(),
size_of_val(padding.as_slice()) as _,
))?;
}
Ok(padding)
}
fn set_padding(&mut self, attr: OperationDescriptorAttribute, padding: &[u32]) -> Result<()> {
debug_assert!(matches!(
attr,
OperationDescriptorAttribute::PaddingLeft | OperationDescriptorAttribute::PaddingRight
));
if padding.len() != self.output_rank as usize {
return Err(Error::LengthMismatch {
name: "padding".into(),
expected: self.output_rank as usize,
actual: padding.len(),
});
}
for &value in padding {
to_i32(value, "padding")?;
}
let padding = padding.to_vec();
self.context.bind()?;
unsafe {
try_ffi!(sys::cutensorOperationDescriptorSetAttribute(
self.context.as_raw(),
self.handle,
attr.into(),
padding.as_ptr().cast(),
size_of_val(padding.as_slice()) as _,
))?;
}
Ok(())
}
}
impl Drop for OperationDescriptor {
fn drop(&mut self) {
if let Err(err) = self.context.bind() {
#[cfg(debug_assertions)]
eprintln!(
"failed to bind cutensor context before destroying operation descriptor: {err}"
);
}
unsafe {
if let Err(err) = try_ffi!(sys::cutensorDestroyOperationDescriptor(self.handle)) {
#[cfg(debug_assertions)]
eprintln!("failed to destroy cutensor operation descriptor: {err}");
}
}
}
}
fn validate_modes(rank: u32, modes: &[Mode]) -> Result<()> {
if rank as usize != modes.len() {
return Err(Error::TensorModeMismatch {
rank,
mode_length: modes.len(),
});
}
Ok(())
}
fn validate_tensor_operand_context(
expected: &ContextRef,
operand: TensorOperand<'_>,
name: &str,
) -> Result<()> {
validate_same_context(expected, operand.desc.context(), name)
}
fn validate_block_sparse_tensor_operand_context(
expected: &ContextRef,
operand: BlockSparseTensorOperand<'_>,
name: &str,
) -> Result<()> {
validate_same_context(expected, operand.desc.context(), name)
}
fn validate_mode_names_match(lhs: &[Mode], rhs: &[Mode], name: &str) -> Result<()> {
if lhs != rhs {
return Err(Error::ModeMismatch { name: name.into() });
}
Ok(())
}
fn validate_tensor_descriptors_match(
lhs: &TensorDescriptor,
rhs: &TensorDescriptor,
name: &str,
) -> Result<()> {
if lhs.shape() != rhs.shape()
|| lhs.strides() != rhs.strides()
|| lhs.data_type() != rhs.data_type()
|| lhs.alignment_requirement() != rhs.alignment_requirement()
{
return Err(Error::DescriptorMismatch { name: name.into() });
}
Ok(())
}
fn validate_block_sparse_tensor_descriptors_match(
lhs: &BlockSparseTensorDescriptor,
rhs: &BlockSparseTensorDescriptor,
name: &str,
) -> Result<()> {
if lhs.mode_count() != rhs.mode_count()
|| lhs.non_zero_block_count() != rhs.non_zero_block_count()
|| lhs.data_type() != rhs.data_type()
{
return Err(Error::DescriptorMismatch { name: name.into() });
}
Ok(())
}
fn validate_operation_attribute_size(
attr: OperationDescriptorAttribute,
actual: usize,
) -> Result<()> {
let expected = match attr {
OperationDescriptorAttribute::Tag => size_of::<i32>(),
OperationDescriptorAttribute::ScalarType => size_of::<sys::cutensorDataType_t>(),
OperationDescriptorAttribute::Flops | OperationDescriptorAttribute::MovedBytes => {
size_of::<f32>()
}
OperationDescriptorAttribute::PaddingLeft | OperationDescriptorAttribute::PaddingRight => {
return Ok(());
}
OperationDescriptorAttribute::PaddingValue => return Ok(()),
};
if actual != expected {
return Err(Error::OperationDescriptorInvalidAttributeSize {
attr,
expected,
actual,
});
}
Ok(())
}