baracuda-cutensor 0.0.1-alpha.68

Safe Rust wrappers for NVIDIA cuTENSOR. Scaffolding at v0.1.
Documentation
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
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
//! Safe Rust wrappers for NVIDIA cuTENSOR (v2 API).
//!
//! cuTENSOR is NVIDIA's high-performance tensor-primitive library —
//! einsum-style contractions, element-wise ops, reductions, and
//! permutations. This crate wraps the full v2 host API surface.
//!
//! # Concepts
//!
//! - [`Handle`] — per-process library handle; owns the plan cache.
//! - [`TensorDescriptor`] — shape + strides + dtype for one tensor.
//! - [`OperationDescriptor`] — an *un*-compiled op (contraction,
//!   reduction, elementwise binary/trinary, permutation). Created via
//!   [`Contraction::new`], [`Reduction::new`], [`ElementwiseBinary::new`],
//!   [`ElementwiseTrinary::new`], or [`Permutation::new`].
//! - [`PlanPreference`] — algorithm selection + JIT mode.
//! - [`Plan`] — compiled op, bound to a workspace size.
//! - [`Plan::contract`] / [`Plan::reduce`] / etc. — execute the plan.
//!
//! # Example — `D = α · A ⊗ B + β · C` (matmul via contraction)
//!
//! Einstein notation: `D[m,n] = A[m,k] · B[k,n]`. Mode IDs identify the
//! shared `k` index — pick any distinct integers per mode.
//!
//! ```no_run
//! use baracuda_cutensor::*;
//!
//! # fn demo() -> Result<(), Error> {
//! let handle = Handle::new()?;
//! let m = 64i64; let n = 64i64; let k = 32i64;
//! let a = TensorDescriptor::new(&handle, &[m, k], None, DataType::F32, 128)?;
//! let b = TensorDescriptor::new(&handle, &[k, n], None, DataType::F32, 128)?;
//! let c = TensorDescriptor::new(&handle, &[m, n], None, DataType::F32, 128)?;
//! let modes_a = &[0i32, 2]; // [m, k]
//! let modes_b = &[2, 1];     // [k, n]
//! let modes_c = &[0, 1];     // [m, n]
//! let op = unsafe {
//!     Contraction::new(&handle, &a, modes_a, &b, modes_b, &c, modes_c, &c, modes_c,
//!         core::ptr::null())
//! }?;
//! let pref = PlanPreference::default_for(&handle)?;
//! let ws = op.estimate_workspace(&pref, WorkspaceKind::Default)?;
//! let plan = Plan::new(&op, &pref, ws)?;
//! # Ok(()) }
//! ```
//!
//! # Example — reduce along an axis (sum over `k`)
//!
//! `D[m] = Σ_k A[m, k]`. Modes present in `A` but absent from `D` are
//! reduced with the chosen [`BinaryOp`] (`Add` for sum).
//!
//! ```no_run
//! use baracuda_cutensor::*;
//!
//! # fn demo() -> Result<(), Error> {
//! let handle = Handle::new()?;
//! let m = 128i64; let k = 64i64;
//! let a = TensorDescriptor::new(&handle, &[m, k], None, DataType::F32, 128)?;
//! let d = TensorDescriptor::new(&handle, &[m],    None, DataType::F32, 128)?;
//!
//! let modes_a = &[0i32, 1]; // [m, k]
//! let modes_d = &[0i32];     // [m]
//! let op = unsafe {
//!     Reduction::new(&handle, &a, modes_a, &d, modes_d, &d, modes_d,
//!         BinaryOp::Add, core::ptr::null())
//! }?;
//! let pref = PlanPreference::default_for(&handle)?;
//! let ws = op.estimate_workspace(&pref, WorkspaceKind::Default)?;
//! let _plan = Plan::new(&op, &pref, ws)?;
//! # Ok(()) }
//! ```
//!
//! # Example — element-wise `D = A + C` via [`ElementwiseBinary`]
//!
//! Same modes on every operand, no contraction or reduction — just a
//! fused per-element op with optional unary pre-ops on each input.
//!
//! ```no_run
//! use baracuda_cutensor::*;
//!
//! # fn demo() -> Result<(), Error> {
//! let handle = Handle::new()?;
//! let n = 1024i64;
//! let a = TensorDescriptor::new(&handle, &[n], None, DataType::F32, 128)?;
//! let c = TensorDescriptor::new(&handle, &[n], None, DataType::F32, 128)?;
//! let d = TensorDescriptor::new(&handle, &[n], None, DataType::F32, 128)?;
//!
//! let modes = &[0i32];
//! let op = unsafe {
//!     ElementwiseBinary::new(
//!         &handle,
//!         &a, modes, UnaryOp::Identity,
//!         &c, modes, UnaryOp::Identity,
//!         &d, modes,
//!         BinaryOp::Add,
//!         core::ptr::null(),
//!     )
//! }?;
//! let pref = PlanPreference::default_for(&handle)?;
//! let _plan = Plan::new(&op, &pref, /* workspace */ 0)?;
//! # Ok(()) }
//! ```

#![warn(missing_debug_implementations)]

use core::ffi::c_void;
use std::ffi::CString;

use baracuda_cutensor_sys::{
    cutensor, cutensorAlgo, cutensorDataType, cutensorHandle_t, cutensorJitMode,
    cutensorOperationDescriptor_t, cutensorOperator, cutensorPlanPreference_t, cutensorPlan_t,
    cutensorStatus_t, cutensorTensorDescriptor_t, cutensorWorksizePreference,
};

/// Error type for cuTENSOR operations.
pub type Error = baracuda_core::Error<cutensorStatus_t>;
/// Result alias.
pub type Result<T, E = Error> = core::result::Result<T, E>;

#[inline]
fn check(status: cutensorStatus_t) -> Result<()> {
    Error::check(status)
}

/// Verify cuTENSOR is loadable on this host.
pub fn probe() -> Result<()> {
    cutensor()?;
    Ok(())
}

/// Encoded integer version from `cutensorGetVersion`. Decode as
/// `major = v / 10000, minor = (v / 100) % 100, patch = v % 100`.
pub fn version() -> Result<usize> {
    let c = cutensor()?;
    let cu = c.cutensor_get_version()?;
    Ok(unsafe { cu() })
}

/// cuTENSOR's view of the CUDART version it was built against.
pub fn cudart_version() -> Result<usize> {
    let c = cutensor()?;
    let cu = c.cutensor_get_cudart_version()?;
    Ok(unsafe { cu() })
}

/// Set the cuTENSOR logger verbosity (0 = off, 1 = error, 2 = trace).
pub fn set_log_level(level: i32) -> Result<()> {
    let c = cutensor()?;
    let cu = c.cutensor_logger_set_level()?;
    check(unsafe { cu(level) })
}

/// Bitmask of log categories (API calls, hints, traces, …). Full value
/// list in cuTENSOR headers.
pub fn set_log_mask(mask: i32) -> Result<()> {
    let c = cutensor()?;
    let cu = c.cutensor_logger_set_mask()?;
    check(unsafe { cu(mask) })
}

/// Open a log file path for cuTENSOR output.
pub fn open_log_file(path: &str) -> Result<()> {
    let cpath = std::ffi::CString::new(path).map_err(|_| Error::Status {
        status: cutensorStatus_t::INVALID_VALUE,
    })?;
    let c = cutensor()?;
    let cu = c.cutensor_logger_open_file()?;
    check(unsafe { cu(cpath.as_ptr()) })
}

/// Force-disable all cuTENSOR logging (tightest possible quiet).
pub fn force_disable_logging() -> Result<()> {
    let c = cutensor()?;
    let cu = c.cutensor_logger_force_disable()?;
    check(unsafe { cu() })
}

/// Element dtype for tensor descriptors.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum DataType {
    /// IEEE-754 half-precision (`f16`).
    F16,
    /// Brain float (`bf16`).
    BF16,
    /// Single-precision float (`f32`).
    F32,
    /// Double-precision float (`f64`).
    F64,
    /// Single-precision complex (real + imag `f32`).
    ComplexF32,
    /// Double-precision complex (real + imag `f64`).
    ComplexF64,
    /// Signed 8-bit integer.
    I8,
    /// Unsigned 8-bit integer.
    U8,
    /// Signed 32-bit integer.
    I32,
    /// Unsigned 32-bit integer.
    U32,
}

impl DataType {
    #[inline]
    fn raw(self) -> i32 {
        match self {
            DataType::F16 => cutensorDataType::R_16F,
            DataType::BF16 => cutensorDataType::R_16BF,
            DataType::F32 => cutensorDataType::R_32F,
            DataType::F64 => cutensorDataType::R_64F,
            DataType::ComplexF32 => cutensorDataType::C_32F,
            DataType::ComplexF64 => cutensorDataType::C_64F,
            DataType::I8 => cutensorDataType::R_8I,
            DataType::U8 => cutensorDataType::R_8U,
            DataType::I32 => cutensorDataType::R_32I,
            DataType::U32 => cutensorDataType::R_32U,
        }
    }
}

/// Per-operand unary operator (applied to A/B/C before the main op).
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum UnaryOp {
    /// No-op; pass the operand through unchanged.
    Identity,
    /// Square root.
    Sqrt,
    /// Rectified linear unit (`max(0, x)`).
    Relu,
    /// Complex conjugate (no-op for real types).
    Conj,
    /// Reciprocal (`1 / x`).
    Rcp,
    /// Logistic sigmoid (`1 / (1 + exp(-x))`).
    Sigmoid,
    /// Hyperbolic tangent.
    Tanh,
}

impl UnaryOp {
    #[inline]
    fn raw(self) -> i32 {
        match self {
            UnaryOp::Identity => cutensorOperator::IDENTITY,
            UnaryOp::Sqrt => cutensorOperator::SQRT,
            UnaryOp::Relu => cutensorOperator::RELU,
            UnaryOp::Conj => cutensorOperator::CONJ,
            UnaryOp::Rcp => cutensorOperator::RCP,
            UnaryOp::Sigmoid => cutensorOperator::SIGMOID,
            UnaryOp::Tanh => cutensorOperator::TANH,
        }
    }
}

/// Binary combining operator (used between operands in elementwise /
/// reduction ops).
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum BinaryOp {
    /// Sum (`a + b`).
    Add,
    /// Product (`a * b`).
    Mul,
    /// Element-wise maximum.
    Max,
    /// Element-wise minimum.
    Min,
}

impl BinaryOp {
    #[inline]
    fn raw(self) -> i32 {
        match self {
            BinaryOp::Add => cutensorOperator::ADD,
            BinaryOp::Mul => cutensorOperator::MUL,
            BinaryOp::Max => cutensorOperator::MAX,
            BinaryOp::Min => cutensorOperator::MIN,
        }
    }
}

/// cuTENSOR library handle.
#[derive(Debug)]
pub struct Handle {
    handle: cutensorHandle_t,
}

unsafe impl Send for Handle {}

impl Handle {
    /// Create a new cuTENSOR handle (`cutensorCreate`).
    pub fn new() -> Result<Self> {
        let c = cutensor()?;
        let cu = c.cutensor_create()?;
        let mut h: cutensorHandle_t = core::ptr::null_mut();
        check(unsafe { cu(&mut h) })?;
        Ok(Self { handle: h })
    }

    /// Raw `cutensorHandle_t`. Use with care.
    #[inline]
    pub fn as_raw(&self) -> cutensorHandle_t {
        self.handle
    }

    /// Resize the internal plan cache — larger = more cached plans,
    /// faster re-invocations. Default is 64.
    pub fn resize_plan_cache(&self, num_entries: u32) -> Result<()> {
        let c = cutensor()?;
        let cu = c.cutensor_handle_resize_plan_cache()?;
        check(unsafe { cu(self.handle, num_entries) })
    }

    /// Persist the plan cache to disk.
    pub fn write_plan_cache_to_file(&self, path: &str) -> Result<()> {
        let cpath = CString::new(path).map_err(|_| Error::Status {
            status: cutensorStatus_t::INVALID_VALUE,
        })?;
        let c = cutensor()?;
        let cu = c.cutensor_handle_write_plan_cache_to_file()?;
        check(unsafe { cu(self.handle, cpath.as_ptr()) })
    }

    /// Read a previously-written plan cache from disk.
    pub fn read_plan_cache_from_file(&self, path: &str) -> Result<()> {
        let cpath = CString::new(path).map_err(|_| Error::Status {
            status: cutensorStatus_t::INVALID_VALUE,
        })?;
        let c = cutensor()?;
        let cu = c.cutensor_handle_read_plan_cache_from_file()?;
        check(unsafe { cu(self.handle, cpath.as_ptr()) })
    }

    /// Persist the **kernel cache** (compiled binary kernels) to disk.
    /// Separate from plan cache — kernel cache survives across planner
    /// changes.
    pub fn write_kernel_cache_to_file(&self, path: &str) -> Result<()> {
        let cpath = CString::new(path).map_err(|_| Error::Status {
            status: cutensorStatus_t::INVALID_VALUE,
        })?;
        let c = cutensor()?;
        let cu = c.cutensor_write_kernel_cache_to_file()?;
        check(unsafe { cu(self.handle, cpath.as_ptr()) })
    }

    /// Read a previously-written kernel cache from disk.
    pub fn read_kernel_cache_from_file(&self, path: &str) -> Result<()> {
        let cpath = CString::new(path).map_err(|_| Error::Status {
            status: cutensorStatus_t::INVALID_VALUE,
        })?;
        let c = cutensor()?;
        let cu = c.cutensor_read_kernel_cache_from_file()?;
        check(unsafe { cu(self.handle, cpath.as_ptr()) })
    }

    /// Fetch cuTENSOR's pre-defined `CUTENSOR_COMPUTE_DESC_32F` descriptor.
    /// Pass this (or one of the sibling accessors) as `compute_desc` to
    /// any op constructor.
    pub fn compute_desc_32f(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_32f()?)
    }
    /// Fetch `CUTENSOR_COMPUTE_DESC_64F` — double-precision accumulator.
    pub fn compute_desc_64f(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_64f()?)
    }
    /// Fetch `CUTENSOR_COMPUTE_DESC_16F` — half-precision accumulator.
    pub fn compute_desc_16f(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_16f()?)
    }
    /// Fetch `CUTENSOR_COMPUTE_DESC_16BF` — bf16 accumulator.
    pub fn compute_desc_16bf(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_16bf()?)
    }
    /// Fetch `CUTENSOR_COMPUTE_DESC_TF32` — TF32 tensor-core accumulator.
    pub fn compute_desc_tf32(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_tf32()?)
    }
    /// Fetch `CUTENSOR_COMPUTE_DESC_3XTF32` — 3xTF32 emulation for f32.
    pub fn compute_desc_3xtf32(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_3xtf32()?)
    }
    /// Fetch `CUTENSOR_COMPUTE_DESC_4X16F` — 4x f16 mixed-precision.
    pub fn compute_desc_4x16f(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_4x16f()?)
    }
    /// Fetch `CUTENSOR_COMPUTE_DESC_8XINT8` — packed int8 tensor cores.
    pub fn compute_desc_8xint8(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_8xint8()?)
    }
    /// Fetch `CUTENSOR_COMPUTE_DESC_9X16BF` — bf16 stochastic-rounding mode.
    pub fn compute_desc_9x16bf(&self) -> Result<*const c_void> {
        Ok(cutensor()?.compute_desc_9x16bf()?)
    }
}

/// A custom [compute descriptor]. Prefer the pre-defined ones
/// ([`Handle::compute_desc_32f`], …) unless you need attribute
/// customization.
#[derive(Debug)]
pub struct ComputeDescriptor<'h> {
    desc: baracuda_cutensor_sys::cutensorComputeDescriptor_t,
    _handle: &'h Handle,
}

impl<'h> ComputeDescriptor<'h> {
    /// Create a new compute descriptor
    /// (`cutensorCreateComputeDescriptor`).
    pub fn new(handle: &'h Handle) -> Result<Self> {
        let c = cutensor()?;
        let cu = c.cutensor_create_compute_descriptor()?;
        let mut desc: baracuda_cutensor_sys::cutensorComputeDescriptor_t = core::ptr::null();
        check(unsafe { cu(handle.as_raw(), &mut desc as *mut _ as *mut _) })?;
        Ok(Self {
            desc,
            _handle: handle,
        })
    }

    /// Raw `cutensorComputeDescriptor_t`. Use with care.
    #[inline]
    pub fn as_raw(&self) -> baracuda_cutensor_sys::cutensorComputeDescriptor_t {
        self.desc
    }

    /// # Safety
    ///
    /// `value` points at a buffer of `size_bytes` matching `attr`.
    pub unsafe fn set_attribute(
        &self,
        attr: i32,
        value: *const c_void,
        size_bytes: usize,
    ) -> Result<()> { unsafe {
        let c = cutensor()?;
        let cu = c.cutensor_compute_descriptor_set_attribute()?;
        check(cu(
            self._handle.as_raw(),
            self.desc,
            attr,
            value,
            size_bytes,
        ))
    }}

    /// # Safety
    ///
    /// `value` points at a writable buffer of `size_bytes`.
    pub unsafe fn get_attribute(
        &self,
        attr: i32,
        value: *mut c_void,
        size_bytes: usize,
    ) -> Result<()> { unsafe {
        let c = cutensor()?;
        let cu = c.cutensor_compute_descriptor_get_attribute()?;
        check(cu(
            self._handle.as_raw(),
            self.desc,
            attr,
            value,
            size_bytes,
        ))
    }}
}

impl Drop for ComputeDescriptor<'_> {
    fn drop(&mut self) {
        if let Ok(c) = cutensor() {
            if let Ok(cu) = c.cutensor_destroy_compute_descriptor() {
                let _ = unsafe { cu(self.desc) };
            }
        }
    }
}

/// A block-sparse tensor descriptor (cuTENSOR 2.x). Used on the A
/// operand of a [`BlockSparseContraction`].
#[derive(Debug)]
pub struct BlockSparseTensorDescriptor<'h> {
    desc: baracuda_cutensor_sys::cutensorBlockSparseTensorDescriptor_t,
    _handle: &'h Handle,
}

impl<'h> BlockSparseTensorDescriptor<'h> {
    /// Build a block-sparse tensor:
    ///
    /// - `extents` — full dense shape
    /// - `block_size` — size per dim of each non-zero block (same length as extents)
    /// - `strides` — optional custom strides; `None` = packed
    /// - `block_indices` — array of `num_modes × block_count` ints identifying
    ///   the non-zero block locations (index per mode per block)
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        handle: &'h Handle,
        extents: &[i64],
        block_size: &[i64],
        strides: Option<&[i64]>,
        block_indices: &[i32],
        dtype: DataType,
        alignment_bytes: u32,
    ) -> Result<Self> {
        assert_eq!(block_size.len(), extents.len());
        if let Some(s) = strides {
            assert_eq!(s.len(), extents.len());
        }
        let num_modes = extents.len() as u32;
        let block_count = (block_indices.len() / extents.len()) as i64;
        let c = cutensor()?;
        let cu = c.cutensor_create_block_sparse_tensor_descriptor()?;
        let mut desc: baracuda_cutensor_sys::cutensorBlockSparseTensorDescriptor_t =
            core::ptr::null_mut();
        check(unsafe {
            cu(
                handle.as_raw(),
                &mut desc,
                num_modes,
                extents.as_ptr(),
                block_size.as_ptr(),
                strides.map_or(core::ptr::null(), |s| s.as_ptr()),
                block_count,
                block_indices.as_ptr(),
                dtype.raw(),
                alignment_bytes,
            )
        })?;
        Ok(Self {
            desc,
            _handle: handle,
        })
    }

    /// Raw `cutensorBlockSparseTensorDescriptor_t`. Use with care.
    #[inline]
    pub fn as_raw(&self) -> baracuda_cutensor_sys::cutensorBlockSparseTensorDescriptor_t {
        self.desc
    }
}

impl Drop for BlockSparseTensorDescriptor<'_> {
    fn drop(&mut self) {
        if let Ok(c) = cutensor() {
            if let Ok(cu) = c.cutensor_destroy_block_sparse_tensor_descriptor() {
                let _ = unsafe { cu(self.desc) };
            }
        }
    }
}

/// Block-sparse contraction: the A operand is block-sparse, B/C/D dense.
#[derive(Debug)]
pub struct BlockSparseContraction;

impl BlockSparseContraction {
    /// # Safety
    ///
    /// `compute_desc` must be null or a live `cutensorComputeDescriptor_t`.
    #[allow(clippy::too_many_arguments, clippy::new_ret_no_self)]
    pub unsafe fn new<'h>(
        handle: &'h Handle,
        a: &BlockSparseTensorDescriptor<'h>,
        modes_a: &[i32],
        b: &TensorDescriptor<'h>,
        modes_b: &[i32],
        c: &TensorDescriptor<'h>,
        modes_c: &[i32],
        d: &TensorDescriptor<'h>,
        modes_d: &[i32],
        compute_desc: *const c_void,
    ) -> Result<OperationDescriptor<'h>> { unsafe {
        let lib = cutensor()?;
        let cu = lib.cutensor_create_block_sparse_contraction()?;
        let mut desc: cutensorOperationDescriptor_t = core::ptr::null_mut();
        check(cu(
            handle.as_raw(),
            &mut desc,
            a.as_raw(),
            modes_a.as_ptr(),
            cutensorOperator::IDENTITY,
            b.as_raw(),
            modes_b.as_ptr(),
            cutensorOperator::IDENTITY,
            c.as_raw(),
            modes_c.as_ptr(),
            cutensorOperator::IDENTITY,
            d.as_raw(),
            modes_d.as_ptr(),
            compute_desc,
        ))?;
        Ok(OperationDescriptor {
            desc,
            handle,
            kind: OpKind::BlockSparseContraction,
        })
    }}
}

/// A ternary contraction op: `E[mE] = α·op_a(A)·op_b(B)·op_c(C) + β·op_d(D)`.
#[derive(Debug)]
pub struct TrinaryContraction;

impl TrinaryContraction {
    /// # Safety
    ///
    /// `compute_desc` must be null or a live `cutensorComputeDescriptor_t`.
    #[allow(clippy::too_many_arguments, clippy::new_ret_no_self)]
    pub unsafe fn new<'h>(
        handle: &'h Handle,
        a: &TensorDescriptor<'h>,
        modes_a: &[i32],
        b: &TensorDescriptor<'h>,
        modes_b: &[i32],
        c: &TensorDescriptor<'h>,
        modes_c: &[i32],
        d: &TensorDescriptor<'h>,
        modes_d: &[i32],
        e: &TensorDescriptor<'h>,
        modes_e: &[i32],
        compute_desc: *const c_void,
    ) -> Result<OperationDescriptor<'h>> { unsafe {
        let lib = cutensor()?;
        let cu = lib.cutensor_create_contraction_trinary()?;
        let mut desc: cutensorOperationDescriptor_t = core::ptr::null_mut();
        check(cu(
            handle.as_raw(),
            &mut desc,
            a.as_raw(),
            modes_a.as_ptr(),
            cutensorOperator::IDENTITY,
            b.as_raw(),
            modes_b.as_ptr(),
            cutensorOperator::IDENTITY,
            c.as_raw(),
            modes_c.as_ptr(),
            cutensorOperator::IDENTITY,
            d.as_raw(),
            modes_d.as_ptr(),
            cutensorOperator::IDENTITY,
            e.as_raw(),
            modes_e.as_ptr(),
            compute_desc,
        ))?;
        Ok(OperationDescriptor {
            desc,
            handle,
            kind: OpKind::TrinaryContraction,
        })
    }}
}

impl Drop for Handle {
    fn drop(&mut self) {
        if let Ok(c) = cutensor() {
            if let Ok(cu) = c.cutensor_destroy() {
                let _ = unsafe { cu(self.handle) };
            }
        }
    }
}

/// A tensor descriptor: modes + extents + dtype + stride layout.
#[derive(Debug)]
pub struct TensorDescriptor<'h> {
    desc: cutensorTensorDescriptor_t,
    _handle: &'h Handle,
}

impl<'h> TensorDescriptor<'h> {
    /// `extents[i]` is the size along mode `i`. `strides = None` gets a
    /// row-major packed layout.
    pub fn new(
        handle: &'h Handle,
        extents: &[i64],
        strides: Option<&[i64]>,
        dtype: DataType,
        alignment_bytes: u32,
    ) -> Result<Self> {
        let c = cutensor()?;
        let cu = c.cutensor_create_tensor_descriptor()?;
        let num_modes = extents.len() as u32;
        if let Some(s) = strides {
            assert_eq!(s.len(), extents.len(), "strides length mismatch");
        }
        let mut desc: cutensorTensorDescriptor_t = core::ptr::null_mut();
        check(unsafe {
            cu(
                handle.as_raw(),
                &mut desc,
                num_modes,
                extents.as_ptr(),
                strides.map_or(core::ptr::null(), |s| s.as_ptr()),
                dtype.raw(),
                alignment_bytes,
            )
        })?;
        Ok(Self {
            desc,
            _handle: handle,
        })
    }

    /// Raw `cutensorTensorDescriptor_t`. Use with care.
    #[inline]
    pub fn as_raw(&self) -> cutensorTensorDescriptor_t {
        self.desc
    }

    /// Low-level tensor-descriptor attribute setter.
    ///
    /// # Safety
    ///
    /// `buf` must point at `size_bytes` matching `attr`.
    pub unsafe fn set_attribute(
        &self,
        attr: i32,
        buf: *const c_void,
        size_bytes: usize,
    ) -> Result<()> { unsafe {
        let c = cutensor()?;
        let cu = c.cutensor_tensor_descriptor_set_attribute()?;
        check(cu(self._handle.as_raw(), self.desc, attr, buf, size_bytes))
    }}
}

impl Drop for TensorDescriptor<'_> {
    fn drop(&mut self) {
        if let Ok(c) = cutensor() {
            if let Ok(cu) = c.cutensor_destroy_tensor_descriptor() {
                let _ = unsafe { cu(self.desc) };
            }
        }
    }
}

/// Internal: what kind of op a descriptor wraps — needed to dispatch
/// the right `execute` path on the compiled [`Plan`].
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum OpKind {
    Contraction,
    TrinaryContraction,
    BlockSparseContraction,
    Reduction,
    ElementwiseBinary,
    ElementwiseTrinary,
    Permutation,
}

/// An un-compiled operation descriptor. Users typically create these
/// through constructors on [`Contraction`], [`Reduction`],
/// [`ElementwiseBinary`], [`ElementwiseTrinary`], or [`Permutation`].
#[derive(Debug)]
pub struct OperationDescriptor<'h> {
    desc: cutensorOperationDescriptor_t,
    handle: &'h Handle,
    kind: OpKind,
}

impl<'h> OperationDescriptor<'h> {
    /// Raw `cutensorOperationDescriptor_t`. Use with care.
    #[inline]
    pub fn as_raw(&self) -> cutensorOperationDescriptor_t {
        self.desc
    }

    /// Estimate the scratch workspace required by a plan built from
    /// this descriptor + `pref`.
    pub fn estimate_workspace(
        &self,
        pref: &PlanPreference<'h>,
        kind: WorkspaceKind,
    ) -> Result<u64> {
        let c = cutensor()?;
        let cu = c.cutensor_estimate_workspace_size()?;
        let mut size: u64 = 0;
        check(unsafe {
            cu(
                self.handle.as_raw(),
                self.desc,
                pref.as_raw(),
                kind.raw(),
                &mut size,
            )
        })?;
        Ok(size)
    }

    /// Estimated runtime in milliseconds for this op at the given
    /// algorithm (`cutensorAlgo::DEFAULT` for auto).
    pub fn estimate_runtime(&self, pref: &PlanPreference<'h>, algo: i32) -> Result<f32> {
        let c = cutensor()?;
        let cu = c.cutensor_operation_estimate_runtime()?;
        let mut ms: f32 = 0.0;
        check(unsafe {
            cu(
                self.handle.as_raw(),
                self.desc,
                pref.as_raw(),
                algo,
                &mut ms,
            )
        })?;
        Ok(ms)
    }

    /// Number of algorithms cuTENSOR has for this op shape.
    pub fn num_algos(&self) -> Result<i32> {
        let c = cutensor()?;
        let cu = c.cutensor_operation_num_algos()?;
        let mut n: i32 = 0;
        check(unsafe { cu(self.desc, &mut n) })?;
        Ok(n)
    }

    /// Low-level attribute getter (for attributes not exposed as typed fns).
    ///
    /// # Safety
    ///
    /// `buf` must be writable for `size_bytes` matching `attr`.
    pub unsafe fn get_attribute(
        &self,
        attr: i32,
        buf: *mut c_void,
        size_bytes: usize,
    ) -> Result<()> { unsafe {
        let c = cutensor()?;
        let cu = c.cutensor_operation_descriptor_get_attribute()?;
        check(cu(self.handle.as_raw(), self.desc, attr, buf, size_bytes))
    }}

    /// Low-level attribute setter.
    ///
    /// # Safety
    ///
    /// `buf` must point at a buffer of `size_bytes` matching `attr`.
    pub unsafe fn set_attribute(
        &self,
        attr: i32,
        buf: *const c_void,
        size_bytes: usize,
    ) -> Result<()> { unsafe {
        let c = cutensor()?;
        let cu = c.cutensor_operation_descriptor_set_attribute()?;
        check(cu(self.handle.as_raw(), self.desc, attr, buf, size_bytes))
    }}
}

impl Drop for OperationDescriptor<'_> {
    fn drop(&mut self) {
        if let Ok(c) = cutensor() {
            if let Ok(cu) = c.cutensor_destroy_operation_descriptor() {
                let _ = unsafe { cu(self.desc) };
            }
        }
    }
}

/// A contraction op: `D[mD] = α * op_a(A[mA]) * op_b(B[mB]) + β * op_c(C[mC])`.
#[derive(Debug)]
pub struct Contraction;

impl Contraction {
    /// Build a contraction descriptor.
    ///
    /// `compute_desc` is an opaque pointer — pass `core::ptr::null()`
    /// for the library default (compute-type matches C's dtype).
    ///
    /// # Safety
    ///
    /// `compute_desc` must be null or a valid `cutensorComputeDescriptor_t`.
    #[allow(clippy::too_many_arguments, clippy::new_ret_no_self)]
    pub unsafe fn new<'h>(
        handle: &'h Handle,
        a: &TensorDescriptor<'h>,
        modes_a: &[i32],
        b: &TensorDescriptor<'h>,
        modes_b: &[i32],
        c: &TensorDescriptor<'h>,
        modes_c: &[i32],
        d: &TensorDescriptor<'h>,
        modes_d: &[i32],
        compute_desc: *const c_void,
    ) -> Result<OperationDescriptor<'h>> { unsafe {
        let cu_lib = cutensor()?;
        let cu = cu_lib.cutensor_create_contraction()?;
        let mut desc: cutensorOperationDescriptor_t = core::ptr::null_mut();
        check(cu(
            handle.as_raw(),
            &mut desc,
            a.as_raw(),
            modes_a.as_ptr(),
            cutensorOperator::IDENTITY,
            b.as_raw(),
            modes_b.as_ptr(),
            cutensorOperator::IDENTITY,
            c.as_raw(),
            modes_c.as_ptr(),
            cutensorOperator::IDENTITY,
            d.as_raw(),
            modes_d.as_ptr(),
            compute_desc,
        ))?;
        Ok(OperationDescriptor {
            desc,
            handle,
            kind: OpKind::Contraction,
        })
    }}
}

/// A reduction op: `D[mD] = reduce(A[mA])` with user-chosen reduce op.
#[derive(Debug)]
pub struct Reduction;

impl Reduction {
    /// Build a reduction. `modes_d` is a subset of `modes_a` — all
    /// modes in `a` that do NOT appear in `d` are reduced. `op_reduce`
    /// is ADD for sum, MUL for product, MAX/MIN for min-max.
    ///
    /// # Safety
    ///
    /// `compute_desc` must be null or valid.
    #[allow(clippy::too_many_arguments, clippy::new_ret_no_self)]
    pub unsafe fn new<'h>(
        handle: &'h Handle,
        a: &TensorDescriptor<'h>,
        modes_a: &[i32],
        c: &TensorDescriptor<'h>,
        modes_c: &[i32],
        d: &TensorDescriptor<'h>,
        modes_d: &[i32],
        op_reduce: BinaryOp,
        compute_desc: *const c_void,
    ) -> Result<OperationDescriptor<'h>> { unsafe {
        let lib = cutensor()?;
        let cu = lib.cutensor_create_reduction()?;
        let mut desc: cutensorOperationDescriptor_t = core::ptr::null_mut();
        check(cu(
            handle.as_raw(),
            &mut desc,
            a.as_raw(),
            modes_a.as_ptr(),
            cutensorOperator::IDENTITY,
            c.as_raw(),
            modes_c.as_ptr(),
            cutensorOperator::IDENTITY,
            d.as_raw(),
            modes_d.as_ptr(),
            op_reduce.raw(),
            compute_desc,
        ))?;
        Ok(OperationDescriptor {
            desc,
            handle,
            kind: OpKind::Reduction,
        })
    }}
}

/// Elementwise binary op: `D[mD] = (α * op_a(A[mA])) op_ac (γ * op_c(C[mC]))`.
#[derive(Debug)]
pub struct ElementwiseBinary;

impl ElementwiseBinary {
    /// # Safety
    ///
    /// `compute_desc` must be null or valid.
    #[allow(clippy::too_many_arguments, clippy::new_ret_no_self)]
    pub unsafe fn new<'h>(
        handle: &'h Handle,
        a: &TensorDescriptor<'h>,
        modes_a: &[i32],
        op_a: UnaryOp,
        c: &TensorDescriptor<'h>,
        modes_c: &[i32],
        op_c: UnaryOp,
        d: &TensorDescriptor<'h>,
        modes_d: &[i32],
        op_ac: BinaryOp,
        compute_desc: *const c_void,
    ) -> Result<OperationDescriptor<'h>> { unsafe {
        let lib = cutensor()?;
        let cu = lib.cutensor_create_elementwise_binary()?;
        let mut desc: cutensorOperationDescriptor_t = core::ptr::null_mut();
        check(cu(
            handle.as_raw(),
            &mut desc,
            a.as_raw(),
            modes_a.as_ptr(),
            op_a.raw(),
            c.as_raw(),
            modes_c.as_ptr(),
            op_c.raw(),
            d.as_raw(),
            modes_d.as_ptr(),
            op_ac.raw(),
            compute_desc,
        ))?;
        Ok(OperationDescriptor {
            desc,
            handle,
            kind: OpKind::ElementwiseBinary,
        })
    }}
}

/// Elementwise trinary op:
/// `D[mD] = ((α * op_a(A) op_ab β * op_b(B)) op_abc γ * op_c(C))`.
#[derive(Debug)]
pub struct ElementwiseTrinary;

impl ElementwiseTrinary {
    /// # Safety
    ///
    /// `compute_desc` must be null or valid.
    #[allow(clippy::too_many_arguments, clippy::new_ret_no_self)]
    pub unsafe fn new<'h>(
        handle: &'h Handle,
        a: &TensorDescriptor<'h>,
        modes_a: &[i32],
        op_a: UnaryOp,
        b: &TensorDescriptor<'h>,
        modes_b: &[i32],
        op_b: UnaryOp,
        c: &TensorDescriptor<'h>,
        modes_c: &[i32],
        op_c: UnaryOp,
        d: &TensorDescriptor<'h>,
        modes_d: &[i32],
        op_ab: BinaryOp,
        op_abc: BinaryOp,
        compute_desc: *const c_void,
    ) -> Result<OperationDescriptor<'h>> { unsafe {
        let lib = cutensor()?;
        let cu = lib.cutensor_create_elementwise_trinary()?;
        let mut desc: cutensorOperationDescriptor_t = core::ptr::null_mut();
        check(cu(
            handle.as_raw(),
            &mut desc,
            a.as_raw(),
            modes_a.as_ptr(),
            op_a.raw(),
            b.as_raw(),
            modes_b.as_ptr(),
            op_b.raw(),
            c.as_raw(),
            modes_c.as_ptr(),
            op_c.raw(),
            d.as_raw(),
            modes_d.as_ptr(),
            op_ab.raw(),
            op_abc.raw(),
            compute_desc,
        ))?;
        Ok(OperationDescriptor {
            desc,
            handle,
            kind: OpKind::ElementwiseTrinary,
        })
    }}
}

/// Tensor permutation (axis shuffle + optional unary op):
/// `B[mB] = α * op_a(A[mA])`.
#[derive(Debug)]
pub struct Permutation;

impl Permutation {
    /// # Safety
    ///
    /// `compute_desc` must be null or valid.
    #[allow(clippy::too_many_arguments, clippy::new_ret_no_self)]
    pub unsafe fn new<'h>(
        handle: &'h Handle,
        a: &TensorDescriptor<'h>,
        modes_a: &[i32],
        op_a: UnaryOp,
        b: &TensorDescriptor<'h>,
        modes_b: &[i32],
        compute_desc: *const c_void,
    ) -> Result<OperationDescriptor<'h>> { unsafe {
        let lib = cutensor()?;
        let cu = lib.cutensor_create_permutation()?;
        let mut desc: cutensorOperationDescriptor_t = core::ptr::null_mut();
        check(cu(
            handle.as_raw(),
            &mut desc,
            a.as_raw(),
            modes_a.as_ptr(),
            op_a.raw(),
            b.as_raw(),
            modes_b.as_ptr(),
            compute_desc,
        ))?;
        Ok(OperationDescriptor {
            desc,
            handle,
            kind: OpKind::Permutation,
        })
    }}
}

/// Plan preferences — algorithm selection + JIT mode.
#[derive(Debug)]
pub struct PlanPreference<'h> {
    pref: cutensorPlanPreference_t,
    _handle: &'h Handle,
}

impl<'h> PlanPreference<'h> {
    /// Build a plan-preference (`cutensorCreatePlanPreference`)
    /// requesting `algo` (e.g. `cutensorAlgo::DEFAULT`) and `jit_mode`.
    pub fn new(handle: &'h Handle, algo: i32, jit_mode: i32) -> Result<Self> {
        let c = cutensor()?;
        let cu = c.cutensor_create_plan_preference()?;
        let mut p: cutensorPlanPreference_t = core::ptr::null_mut();
        check(unsafe { cu(handle.as_raw(), &mut p, algo, jit_mode) })?;
        Ok(Self {
            pref: p,
            _handle: handle,
        })
    }

    /// Default preferences — library's best guess at algorithm, JIT off.
    pub fn default_for(handle: &'h Handle) -> Result<Self> {
        Self::new(handle, cutensorAlgo::DEFAULT, cutensorJitMode::NONE)
    }

    /// Raw `cutensorPlanPreference_t`. Use with care.
    #[inline]
    pub fn as_raw(&self) -> cutensorPlanPreference_t {
        self.pref
    }

    /// Set a plan-preference attribute (see cuTENSOR's
    /// `cutensorPlanPreferenceAttribute_t`).
    ///
    /// # Safety
    ///
    /// `value` must point at a buffer of at least `size_bytes` for the
    /// attribute kind being set.
    pub unsafe fn set_attribute(
        &self,
        attr: i32,
        value: *const c_void,
        size_bytes: usize,
    ) -> Result<()> { unsafe {
        let c = cutensor()?;
        let cu = c.cutensor_plan_preference_set_attribute()?;
        check(cu(
            self._handle.as_raw(),
            self.pref,
            attr,
            value,
            size_bytes,
        ))
    }}

    /// Read a plan-preference attribute.
    ///
    /// # Safety
    ///
    /// `value` must be writable for `size_bytes` matching `attr`.
    pub unsafe fn get_attribute(
        &self,
        attr: i32,
        value: *mut c_void,
        size_bytes: usize,
    ) -> Result<()> { unsafe {
        let c = cutensor()?;
        let cu = c.cutensor_plan_preference_get_attribute()?;
        check(cu(
            self._handle.as_raw(),
            self.pref,
            attr,
            value,
            size_bytes,
        ))
    }}
}

impl Drop for PlanPreference<'_> {
    fn drop(&mut self) {
        if let Ok(c) = cutensor() {
            if let Ok(cu) = c.cutensor_destroy_plan_preference() {
                let _ = unsafe { cu(self.pref) };
            }
        }
    }
}

/// Workspace-size preference tier.
#[derive(Copy, Clone, Debug)]
pub enum WorkspaceKind {
    /// Smallest workspace the algorithm can run with.
    Min,
    /// Library default — balanced size vs. performance.
    Default,
    /// Largest workspace the algorithm will ever need.
    Max,
}

impl WorkspaceKind {
    #[inline]
    fn raw(self) -> i32 {
        match self {
            WorkspaceKind::Min => cutensorWorksizePreference::MIN,
            WorkspaceKind::Default => cutensorWorksizePreference::DEFAULT,
            WorkspaceKind::Max => cutensorWorksizePreference::MAX,
        }
    }
}

/// A compiled operation plan. Dispatch to the matching `execute` method
/// based on the op kind that built it.
#[derive(Debug)]
pub struct Plan<'h> {
    plan: cutensorPlan_t,
    handle: &'h Handle,
    kind: OpKind,
}

impl<'h> Plan<'h> {
    /// Compile an operation descriptor into a plan.
    /// `workspace_size_limit` bytes — pass the estimate.
    pub fn new(
        op: &OperationDescriptor<'h>,
        pref: &PlanPreference<'h>,
        workspace_size_limit: u64,
    ) -> Result<Self> {
        let c = cutensor()?;
        let cu = c.cutensor_create_plan()?;
        let mut p: cutensorPlan_t = core::ptr::null_mut();
        check(unsafe {
            cu(
                op.handle.as_raw(),
                &mut p,
                op.as_raw(),
                pref.as_raw(),
                workspace_size_limit,
            )
        })?;
        Ok(Self {
            plan: p,
            handle: op.handle,
            kind: op.kind,
        })
    }

    /// Raw `cutensorPlan_t`. Use with care.
    #[inline]
    pub fn as_raw(&self) -> cutensorPlan_t {
        self.plan
    }

    /// Execute a contraction plan. Aborts if `self` wasn't built from a
    /// [`Contraction`] descriptor.
    ///
    /// # Safety
    ///
    /// All device pointers must be live, tensor-descriptor-conforming,
    /// and aligned. `workspace` must be at least the estimated size.
    #[allow(clippy::too_many_arguments)]
    pub unsafe fn contract(
        &self,
        alpha: *const c_void,
        a: *const c_void,
        b: *const c_void,
        beta: *const c_void,
        c: *const c_void,
        d: *mut c_void,
        workspace: *mut c_void,
        workspace_bytes: u64,
        stream: *mut c_void,
    ) -> Result<()> { unsafe {
        assert_eq!(self.kind, OpKind::Contraction, "plan is not a contraction");
        let lib = cutensor()?;
        let cu = lib.cutensor_contract()?;
        check(cu(
            self.handle.as_raw(),
            self.plan,
            alpha,
            a,
            b,
            beta,
            c,
            d,
            workspace,
            workspace_bytes,
            stream,
        ))
    }}

    /// Execute a reduction plan.
    ///
    /// # Safety
    ///
    /// Same as [`Self::contract`].
    #[allow(clippy::too_many_arguments)]
    pub unsafe fn reduce(
        &self,
        alpha: *const c_void,
        a: *const c_void,
        beta: *const c_void,
        c: *const c_void,
        d: *mut c_void,
        workspace: *mut c_void,
        workspace_bytes: u64,
        stream: *mut c_void,
    ) -> Result<()> { unsafe {
        assert_eq!(self.kind, OpKind::Reduction, "plan is not a reduction");
        let lib = cutensor()?;
        let cu = lib.cutensor_reduce()?;
        check(cu(
            self.handle.as_raw(),
            self.plan,
            alpha,
            a,
            beta,
            c,
            d,
            workspace,
            workspace_bytes,
            stream,
        ))
    }}

    /// Execute an elementwise-binary plan.
    ///
    /// # Safety
    ///
    /// Same as [`Self::contract`].
    #[allow(clippy::too_many_arguments)]
    pub unsafe fn elementwise_binary(
        &self,
        alpha: *const c_void,
        a: *const c_void,
        gamma: *const c_void,
        c: *const c_void,
        d: *mut c_void,
        stream: *mut c_void,
    ) -> Result<()> { unsafe {
        assert_eq!(
            self.kind,
            OpKind::ElementwiseBinary,
            "plan is not an elementwise-binary"
        );
        let lib = cutensor()?;
        let cu = lib.cutensor_elementwise_binary_execute()?;
        check(cu(
            self.handle.as_raw(),
            self.plan,
            alpha,
            a,
            gamma,
            c,
            d,
            stream,
        ))
    }}

    /// Execute an elementwise-trinary plan.
    ///
    /// # Safety
    ///
    /// Same as [`Self::contract`].
    #[allow(clippy::too_many_arguments)]
    pub unsafe fn elementwise_trinary(
        &self,
        alpha: *const c_void,
        a: *const c_void,
        beta: *const c_void,
        b: *const c_void,
        gamma: *const c_void,
        c: *const c_void,
        d: *mut c_void,
        stream: *mut c_void,
    ) -> Result<()> { unsafe {
        assert_eq!(
            self.kind,
            OpKind::ElementwiseTrinary,
            "plan is not an elementwise-trinary"
        );
        let lib = cutensor()?;
        let cu = lib.cutensor_elementwise_trinary_execute()?;
        check(cu(
            self.handle.as_raw(),
            self.plan,
            alpha,
            a,
            beta,
            b,
            gamma,
            c,
            d,
            stream,
        ))
    }}

    /// Execute a permutation plan.
    ///
    /// # Safety
    ///
    /// Same as [`Self::contract`].
    pub unsafe fn permute(
        &self,
        alpha: *const c_void,
        a: *const c_void,
        b: *mut c_void,
        stream: *mut c_void,
    ) -> Result<()> { unsafe {
        assert_eq!(self.kind, OpKind::Permutation, "plan is not a permutation");
        let lib = cutensor()?;
        let cu = lib.cutensor_permute()?;
        check(cu(self.handle.as_raw(), self.plan, alpha, a, b, stream))
    }}

    /// Execute a block-sparse contraction plan.
    ///
    /// # Safety
    ///
    /// Same as [`Self::contract`]; `a` must be a block-sparse device
    /// buffer matching the `BlockSparseTensorDescriptor` passed to
    /// [`BlockSparseContraction::new`].
    #[allow(clippy::too_many_arguments)]
    pub unsafe fn contract_block_sparse(
        &self,
        alpha: *const c_void,
        a: *const c_void,
        b: *const c_void,
        beta: *const c_void,
        c: *const c_void,
        d: *mut c_void,
        workspace: *mut c_void,
        workspace_bytes: u64,
        stream: *mut c_void,
    ) -> Result<()> { unsafe {
        assert_eq!(
            self.kind,
            OpKind::BlockSparseContraction,
            "plan is not a block-sparse contraction"
        );
        let lib = cutensor()?;
        let cu = lib.cutensor_block_sparse_contract()?;
        check(cu(
            self.handle.as_raw(),
            self.plan,
            alpha,
            a,
            b,
            beta,
            c,
            d,
            workspace,
            workspace_bytes,
            stream,
        ))
    }}

    /// Execute a trinary-contraction plan:
    /// `E = α·op_a(A)·op_b(B)·op_c(C) + β·op_d(D)`.
    ///
    /// # Safety
    ///
    /// Same as [`Self::contract`].
    #[allow(clippy::too_many_arguments)]
    pub unsafe fn contract_trinary(
        &self,
        alpha: *const c_void,
        a: *const c_void,
        b: *const c_void,
        c: *const c_void,
        beta: *const c_void,
        d: *const c_void,
        e: *mut c_void,
        workspace: *mut c_void,
        workspace_bytes: u64,
        stream: *mut c_void,
    ) -> Result<()> { unsafe {
        assert_eq!(
            self.kind,
            OpKind::TrinaryContraction,
            "plan is not a trinary-contraction"
        );
        let lib = cutensor()?;
        let cu = lib.cutensor_contract_trinary()?;
        check(cu(
            self.handle.as_raw(),
            self.plan,
            alpha,
            a,
            b,
            c,
            beta,
            d,
            e,
            workspace,
            workspace_bytes,
            stream,
        ))
    }}
}

impl Drop for Plan<'_> {
    fn drop(&mut self) {
        if let Ok(c) = cutensor() {
            if let Ok(cu) = c.cutensor_destroy_plan() {
                let _ = unsafe { cu(self.plan) };
            }
        }
    }
}