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
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
extern crate alloc;
use crate::axes::IntoAxes;
use crate::dtype::DType;
use crate::error::ZyxError;
use crate::scalar::Scalar;
use crate::shape::Shape;
use crate::utils::SizedIterator;
use crate::{backend::Backend, node::Node};
use alloc::{boxed::Box, collections::BTreeSet, vec::Vec};
use core::{
    cmp::Ordering,
    iter::repeat,
    ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, SubAssign},
};

/// Id of tensor.
#[derive(Clone, Copy, PartialOrd, PartialEq, Ord, Eq, Debug)]
pub struct Id(usize);

/// Create new id.
pub const fn id(id: usize) -> Id {
    Id(id)
}

impl Id {
    /// Convert id to usize
    pub const fn i(self) -> usize {
        self.0
    }
}

impl core::fmt::Display for Id {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{:?}", self))
    }
}

impl SubAssign<usize> for Id {
    fn sub_assign(&mut self, rhs: usize) {
        self.0 -= rhs;
    }
}

/// Into i64 range, used for indexing
pub trait IntoRange: Clone {
    /// Convert self to range i64, if it is scalar, it gets converted to x..x+1
    fn into_range(self) -> Range<i64>;
}

impl IntoRange for RangeFull {
    fn into_range(self) -> Range<i64> {
        0..i64::MAX
    }
}

impl IntoRange for RangeFrom<i64> {
    fn into_range(self) -> Range<i64> {
        self.start..i64::MAX
    }
}

impl IntoRange for RangeTo<i64> {
    fn into_range(self) -> Range<i64> {
        0..self.end
    }
}

impl IntoRange for RangeInclusive<i64> {
    fn into_range(self) -> Range<i64> {
        *self.start()..*self.end() + 1
    }
}

impl IntoRange for RangeToInclusive<i64> {
    fn into_range(self) -> Range<i64> {
        0..self.end + 1
    }
}

impl IntoRange for Range<i64> {
    fn into_range(self) -> Range<i64> {
        self
    }
}

impl IntoRange for i64 {
    fn into_range(self) -> Range<i64> {
        self..self + 1
    }
}

/// Implemented for objects that can be used to index tensors.
pub trait IntoIndex {
    /// Convert self to tensor index.
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>>;
}

impl<I: IntoRange> IntoIndex for &[I] {
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        self.iter().cloned().map(IntoRange::into_range)
    }
}

impl<I0: IntoRange> IntoIndex for I0 {
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        [self.into_range()].into_iter()
    }
}

impl<I0: IntoRange, I1: IntoRange> IntoIndex for (I0, I1) {
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        [self.0.into_range(), self.1.into_range()].into_iter()
    }
}

impl<I0: IntoRange, I1: IntoRange, I2: IntoRange> IntoIndex for (I0, I1, I2) {
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        [
            self.0.into_range(),
            self.1.into_range(),
            self.2.into_range(),
        ]
        .into_iter()
    }
}

impl<I0: IntoRange, I1: IntoRange, I2: IntoRange, I3: IntoRange> IntoIndex for (I0, I1, I2, I3) {
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        [
            self.0.into_range(),
            self.1.into_range(),
            self.2.into_range(),
            self.3.into_range(),
        ]
        .into_iter()
    }
}

impl<I0: IntoRange, I1: IntoRange, I2: IntoRange, I3: IntoRange, I4: IntoRange> IntoIndex
    for (I0, I1, I2, I3, I4)
{
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        [
            self.0.into_range(),
            self.1.into_range(),
            self.2.into_range(),
            self.3.into_range(),
            self.4.into_range(),
        ]
        .into_iter()
    }
}

impl<I0: IntoRange, I1: IntoRange, I2: IntoRange, I3: IntoRange, I4: IntoRange, I5: IntoRange>
    IntoIndex for (I0, I1, I2, I3, I4, I5)
{
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        [
            self.0.into_range(),
            self.1.into_range(),
            self.2.into_range(),
            self.3.into_range(),
            self.4.into_range(),
            self.5.into_range(),
        ]
        .into_iter()
    }
}

impl<
        I0: IntoRange,
        I1: IntoRange,
        I2: IntoRange,
        I3: IntoRange,
        I4: IntoRange,
        I5: IntoRange,
        I6: IntoRange,
    > IntoIndex for (I0, I1, I2, I3, I4, I5, I6)
{
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        [
            self.0.into_range(),
            self.1.into_range(),
            self.2.into_range(),
            self.3.into_range(),
            self.4.into_range(),
            self.5.into_range(),
            self.6.into_range(),
        ]
        .into_iter()
    }
}

impl<
        I0: IntoRange,
        I1: IntoRange,
        I2: IntoRange,
        I3: IntoRange,
        I4: IntoRange,
        I5: IntoRange,
        I6: IntoRange,
        I7: IntoRange,
    > IntoIndex for (I0, I1, I2, I3, I4, I5, I6, I7)
{
    fn into_index(self) -> impl IntoIterator<Item = Range<i64>> {
        [
            self.0.into_range(),
            self.1.into_range(),
            self.2.into_range(),
            self.3.into_range(),
            self.4.into_range(),
            self.5.into_range(),
            self.6.into_range(),
            self.7.into_range(),
        ]
        .into_iter()
    }
}

/// A range of axes that can be used for flattening tensors.
pub trait FlattenAxes {
    /// Get flatten axes
    fn into_flatten_axes(self, rank: usize) -> impl IntoIterator<Item = i64>;
}

impl FlattenAxes for RangeFrom<i64> {
    fn into_flatten_axes(self, rank: usize) -> impl IntoIterator<Item = i64> {
        debug_assert!(
            if self.start > 0 {
                (self.start as usize) < rank
            } else {
                ((-self.start) as usize) <= rank
            },
            "Cannot use {self:?} as flatten axes."
        );
        self.start..i64::MAX
    }
}

impl FlattenAxes for RangeTo<i64> {
    fn into_flatten_axes(self, rank: usize) -> impl IntoIterator<Item = i64> {
        debug_assert!(
            if self.end > 0 {
                (self.end as usize) < rank
            } else {
                ((-self.end) as usize) <= rank
            },
            "Cannot use {self:?} as flatten axes."
        );
        0..self.end
    }
}

impl FlattenAxes for RangeToInclusive<i64> {
    fn into_flatten_axes(self, rank: usize) -> impl IntoIterator<Item = i64> {
        debug_assert!(
            if self.end > 0 {
                (self.end as usize) < rank
            } else {
                ((-self.end) as usize) <= rank
            },
            "Cannot use {self:?} as flatten axes."
        );
        0..self.end + 1
    }
}

impl FlattenAxes for RangeFull {
    fn into_flatten_axes(self, rank: usize) -> impl IntoIterator<Item = i64> {
        0..rank as i64
    }
}

/// Tensor is the core object of zyx.
/// It is multidimensional array.
pub struct Tensor<B: Backend> {
    id: Id,
    backend: B,
}

impl<B: Backend> Clone for Tensor<B> {
    fn clone(&self) -> Self {
        self.backend.retain(self.id);
        tensor(self.id, self.backend)
    }
}

impl<B: Backend> Drop for Tensor<B> {
    fn drop(&mut self) {
        //std::println!("Dropping tensor {}", self.id);
        self.backend.release(self.id).unwrap();
    }
}

impl<B: Backend> core::fmt::Debug for Tensor<B> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_fmt(format_args!("{self}"))
        //f.write_fmt(format_args!("Tensor {{ id = {:?} }}", self.id))
    }
}

impl<B: Backend> core::fmt::Display for Tensor<B> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // TODO don't print the whole tensor if it is too big
        let precision = if let Some(precision) = f.precision() {
            precision
        } else {
            3
        };
        let res = match self.dtype() {
            DType::F32 => {
                if let Ok(data) = &self.to_vec::<f32>() {
                    tensor_to_string(data, &self.shape(), precision, f.width())
                } else {
                    "f32 tensor failed to realize".into()
                }
            }
            DType::F64 => {
                if let Ok(data) = &self.to_vec::<f64>() {
                    tensor_to_string(data, &self.shape(), precision, f.width())
                } else {
                    "f64 tensor failed to realize".into()
                }
            }
            DType::I32 => {
                if let Ok(data) = &self.to_vec::<i32>() {
                    tensor_to_string(data, &self.shape(), precision, f.width())
                } else {
                    "i32 tensor failed to realize".into()
                }
            }
        };
        f.write_fmt(format_args!(
            "Tensor {} {}\n{res}",
            self.shape(),
            self.dtype()
        ))
    }
}

fn tensor_to_string<T: core::fmt::Display>(
    data: &[T],
    shape: &Shape,
    precision: usize,
    width: Option<usize>,
) -> alloc::string::String {
    use core::fmt::Write;
    let n = shape.numel();
    let ndim = shape.rank();
    let mut res = alloc::string::String::new();
    if data.is_empty() {
        return "[]".into();
    }
    // get maximal width of single value
    let mut w = 0;
    if let Some(width) = width {
        w = width;
    } else {
        for x in data {
            let l = alloc::format!("{x:>.precision$}").len();
            if l > w {
                w = l;
            }
        }
    }
    let d0 = shape[-1];
    for (i, x) in data.iter().enumerate() {
        {
            let mut var = 1;
            let mut r = ndim;
            while r > 0 {
                if i % (n / var) == 0 {
                    res += &(" ".repeat(ndim - r) + "[".repeat(r - 1).as_str());
                    break;
                }
                var *= shape[ndim - r];
                r -= 1;
            }
        }
        let _ = write!(res, "{x:>w$.precision$}");
        if (i + 1) % d0 != 0usize {
            res += "  ";
        }
        {
            let mut var = 1;
            let mut r = ndim;
            while r > 0 {
                if (i + 1) % (n / var) == 0 {
                    res += &"]".repeat(r - 1);
                    break;
                }
                var *= shape[ndim - r];
                r -= 1;
            }
        }
        if (i + 1) % d0 == 0usize && i != n - 1 {
            res += "\n";
        }
    }
    res
}

/// Create new tensor from id and backend.
/// Used mostly internally in tensor and in backends.
pub const fn tensor<B: Backend>(id: Id, backend: B) -> Tensor<B> {
    Tensor { id, backend }
}

impl<B: Backend> Tensor<B> {
    // Metadata
    /// Tensor's unique identification.
    /// All tensors on one backend will always have different ids.
    pub fn id(&self) -> Id {
        self.id
    }

    /// Returns the [shape](Shape) of the self tensor.
    /// ```
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
    /// assert_eq!(x.shape(), [2, 3]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn shape(&self) -> Shape {
        self.backend.shape(self.id)
    }

    /// Returns number of elements in the self tensor.
    /// ```
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
    /// assert_eq!(x.numel(), 6);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn numel(&self) -> usize {
        self.shape().numel()
    }

    /// Returns the [dtype](DType) of the self tensor.
    /// ```
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
    /// assert_eq!(x.dtype(), zyx_opencl::DType::I32);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn dtype(&self) -> DType {
        self.backend.dtype(self.id)
    }

    /// Returns the rank of the self tensor. This is the number of tensor's dimensions.
    /// ```
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
    /// assert_eq!(x.rank(), 2);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn rank(&self) -> usize {
        self.shape().rank()
    }

    /// Returns the [backend](Backend) of the self tensor.
    /// ```
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
    /// let y = x.backend().randn([2, 4, 3], zyx_opencl::DType::F32);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn backend(&self) -> B {
        self.backend
    }

    /// Detach gradient tape from tensor.
    /// This means that resulting tensor is a shallow copy of self,
    /// but it's gradient will be ones. Result of this operation
    /// can only be differentiated by itself.
    /// ```rust
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([2, 3]);
    /// let y = &x + &x;
    /// let g = y.backward([&x]).pop().unwrap().unwrap();
    /// assert_eq!(g, [2, 2]);
    /// let z = y.detach();
    /// let g = z.backward([&z]).pop().unwrap().unwrap();
    /// assert_eq!(g, [1, 1]);
    /// let g = z.backward([&x]).pop().unwrap();
    /// assert_eq!(g, None);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn detach(&self) -> Tensor<B> {
        // It should be possible to just be optimize this away.
        tensor(
            self.backend.push(Node::Detach(self.id)).unwrap(),
            self.backend,
        )
    }

    /*
    /// Probably just add no_grad, that is all tensors coming from no_grad tensor
    /// are not differentiable, unless some other parameter in those ops is differentiable.
    #[must_use]
    pub fn no_grad(&self) {
        // TODO
        //self.backend.no_grad(self.id);
    }*/

    // Access methods
    /// Load tensor from backend into vector
    /// ```
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
    /// let xvec: Vec<i32> = x.to_vec()?;
    /// assert_eq!(xvec, vec![2, 3, 1, 4, 1, 3]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    pub fn to_vec<T: Scalar>(&self) -> Result<Vec<T>, ZyxError> {
        if T::dtype() != self.dtype() {
            return Err(ZyxError::InvalidDType {
                expected: T::dtype(),
                found: self.dtype(),
            });
        }
        self.backend.load(self.id)
    }

    /// Returns first element stored in this tensor.
    /// Usually used for tensors with exactly one element.
    /// Error is returned if self tensor contains zero elements
    /// or if backend returns error.
    /// ```
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
    /// let xitem: i32 = x.item()?;
    /// assert_eq!(xitem, 2);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    pub fn item<T: Scalar>(&self) -> Result<T, ZyxError> {
        self.backend
            .load::<T>(self.id)?
            .first()
            .ok_or(ZyxError::IndexOutOfBounds { index: 0, len: 0 })
            .cloned()
    }

    // Backpropagation
    /// Returns gradients of self w.r.t. sources.
    /// ```rust
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([3., 2., 1.]);
    /// let y = x.exp() + &x;
    /// let x_grad = y.backward([&x]).into_iter().next().unwrap().unwrap();
    /// assert_eq!(x_grad, [21.0855369, 8.3890561, 3.7182818]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn backward<'a>(
        &'a self,
        sources: impl IntoIterator<Item = &'a Tensor<B>>,
    ) -> Vec<Option<Tensor<B>>>
    where
        B: 'a,
    {
        let sources: Vec<&Tensor<B>> = sources.into_iter().collect();
        let grads = self
            .backend
            .backward(self.id, &sources.iter().map(|t| t.id).collect())
            .unwrap();
        sources
            .into_iter()
            .map(move |x: &Tensor<B>| grads.get(&x.id).cloned())
            .map(move |x| x.map(|x| tensor(x, self.backend)))
            .collect()
    }

    // Unary ops
    /// Cast self into dtype.
    /// ```rust
    /// # use zyx_opencl::DType;
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[3, 4, 2], [4, 5, 2]]);
    /// let y = x.cast(DType::F32);
    /// assert_eq!(y.dtype(), DType::F32);
    /// assert_eq!(y, [[3f32, 4., 2.], [4., 5., 2.]]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn cast(&self, dtype: DType) -> Tensor<B> {
        tensor(
            self.backend.push(Node::Cast(self.id, dtype)).unwrap(),
            self.backend,
        )
    }

    /// Returns a new tensor with the rectified linear unit function applied to the elements of self.
    #[must_use]
    pub fn relu(&self) -> Tensor<B> {
        tensor(
            self.backend.push(Node::ReLU(self.id)).unwrap(),
            self.backend,
        )
    }

    /// Returns a new tensor with the sine of the elements of self.
    #[must_use]
    pub fn sin(&self) -> Tensor<B> {
        tensor(self.backend.push(Node::Sin(self.id)).unwrap(), self.backend)
    }

    /// Returns a new tensor with the cosine of the elements of self.
    #[must_use]
    pub fn cos(&self) -> Tensor<B> {
        tensor(self.backend.push(Node::Cos(self.id)).unwrap(), self.backend)
    }

    /// Returns a new tensor with the natural logarithm of the elements of self.
    /// Due to performance reasons, this function does not check if self fits
    /// into domain of ln(x). Result on out of domain numbers is implementation
    /// defined (when x <= 0).
    #[must_use]
    pub fn ln(&self) -> Tensor<B> {
        tensor(self.backend.push(Node::Ln(self.id)).unwrap(), self.backend)
    }

    /// Returns a new tensor with the exponential of the elements of self.
    #[must_use]
    pub fn exp(&self) -> Tensor<B> {
        tensor(self.backend.push(Node::Exp(self.id)).unwrap(), self.backend)
    }

    /// Returns a new tensor with the hyperbolic tangent of the elements of self.
    #[must_use]
    pub fn tanh(&self) -> Tensor<B> {
        tensor(
            self.backend.push(Node::Tanh(self.id)).unwrap(),
            self.backend,
        )
    }

    /// Returns a new tensor with the square root of the elements of self.
    /// Due to performance reasons, this function does not check if self fits
    /// into domain of ln(x). Result on out of domain numbers is implementation
    /// defined (when x < 0).
    #[must_use]
    pub fn sqrt(&self) -> Tensor<B> {
        tensor(
            self.backend.push(Node::Sqrt(self.id)).unwrap(),
            self.backend,
        )
    }

    /// Returns 1/self
    #[must_use]
    pub fn reciprocal(&self) -> Tensor<B> {
        self.backend().ones(self.shape(), self.dtype()).unwrap() / self
    }

    /// Returns 1/self.sqrt()
    #[must_use]
    pub fn rsqrt(&self) -> Tensor<B> {
        self.reciprocal().sqrt()
    }

    /// Returns a new tensor with each element of self randomly zeroed with given probability.
    #[must_use]
    pub fn dropout(&self, probability: impl Scalar) -> Tensor<B> {
        self.backend()
            .tensor(probability)
            .unwrap()
            .cmplt(self.backend().uniform(self.shape(), 0.0..1.0).unwrap())
            * self
    }

    /// Returns a new tensor with the absolute value of the elements of self.
    #[must_use]
    pub fn abs(&self) -> Tensor<B> {
        self.relu() + (-self).relu()
    }

    /// Returns a new tensor with the sigmoid (logistic function) of the elements of self.
    #[must_use]
    pub fn sigmoid(&self) -> Tensor<B> {
        let one = self.backend().ones(1, self.dtype()).unwrap();
        &one / (&one + (-self).exp())
    }

    /// Returns a new tensor with the swish/silu of the elements of self.
    #[must_use]
    pub fn swish(&self) -> Tensor<B> {
        self * self.sigmoid()
    }

    /// Returns a new tensor with the mish of the elements of self.
    #[must_use]
    pub fn mish(&self) -> Tensor<B> {
        self * self.softplus(1, 20).tanh()
    }

    /// Returns a new tensor with the softplus of the elements of self.
    #[must_use]
    pub fn softplus(&self, beta: impl Scalar, threshold: impl Scalar) -> Tensor<B> {
        let x = self * beta.clone();
        x.cmplt(threshold)
            .where_(((x).exp() + 1).ln() * beta.reciprocal(), x)
    }

    /// Returns a new tensor with the tangent of the elements of self.
    #[must_use]
    pub fn tan(&self) -> Tensor<B> {
        self.sin() / self.cos()
    }

    /// Returns a new tensor with the leaky relu of the elements of self.
    #[must_use]
    pub fn leaky_relu(&self, neg_slope: impl Scalar) -> Tensor<B> {
        self.relu() - (self * (-self.backend.tensor(neg_slope).unwrap())).relu()
    }

    /// Returns a new tensor with the elu of the elements of self.
    #[must_use]
    pub fn elu(&self, alpha: impl Scalar) -> Tensor<B> {
        self.relu() - (1f32.into_tensor(self.backend) - self.exp()).relu() * alpha
    }

    /// Returns a new tensor with the selu of the elements of self.
    #[must_use]
    pub fn selu(&self) -> Tensor<B> {
        1.0507009873554804934193349852946f32
            * (self.relu()
                - (1.6732632423543772848170429916717f32
                    * (self.backend.ones(1, self.dtype()).unwrap() - self.exp()))
                .relu())
    }

    /// Returns a new tensor with the celu of the elements of self.
    #[must_use]
    pub fn celu(&self, alpha: impl Scalar) -> Tensor<B> {
        self.relu()
            - ((self.backend.ones(1, self.dtype()).unwrap() - (self / alpha.clone()).exp()) * alpha)
                .relu()
    }

    /// Returns a new tensor with the gelu of the elements of self.
    #[must_use]
    pub fn gelu(&self) -> Tensor<B> {
        self * 0.5f32
            * (((self + self.pow(3f32) * 0.044_715f32) * (2f32 / core::f32::consts::PI).sqrt())
                .tanh()
                + 1f32)
    }

    /// Returns a new tensor with the quick gelu of the elements of self.
    #[must_use]
    pub fn quick_gelu(&self) -> Tensor<B> {
        self * (1.702f32 * self).sigmoid()
    }

    /// Returns a new tensor with the softmax of the elements of self.
    #[must_use]
    pub fn softmax(&self, axes: impl IntoAxes) -> Tensor<B> {
        let axes = axes.into_axes(self.rank());
        let e = (self - self.max(axes.clone())).exp();
        &e / e.sum(axes)
    }

    /// Returns a new tensor with the log softmax of the elements of self.
    #[must_use]
    pub fn ln_softmax(&self, axes: impl IntoAxes) -> Tensor<B> {
        let axes = axes.into_axes(self.rank());
        let m = self - self.max(axes.clone());
        &m - m.exp().sum(axes).ln()
    }

    // Loss functions, all losses are without reduce
    /// Measures the mean absolute error (MAE) between each element in the input self and target.
    #[must_use]
    pub fn l1_loss(&self, target: impl IntoTensor<B>) -> Tensor<B> {
        (self - target).abs()
    }

    /// Measures the mean squared error (MSE) between each element in the input self and target.
    #[must_use]
    pub fn mse_loss(&self, target: impl IntoTensor<B>) -> Tensor<B> {
        (self - target).pow(2)
    }

    /// Computes the cross entropy loss between self logits and target.
    /// This function expects self to contain probabilities for each class.
    #[must_use]
    pub fn cross_entropy_loss(&self, target: impl IntoTensor<B>, axes: impl IntoAxes) -> Tensor<B> {
        self.ln_softmax(axes) * target
    }

    // Binary ops
    /// Exponentiation on self
    #[must_use]
    pub fn pow(&self, exponent: impl IntoTensor<B>) -> Tensor<B> {
        let exponent = self.backend.tensor(exponent).unwrap();
        if exponent.numel() == 1 {
            let dtype = exponent.dtype();
            if !dtype.is_floating() {
                // TODO other int dtypes
                if exponent.item::<i32>().unwrap() == 2i32 {
                    return self * self;
                } else if exponent.item::<i32>().unwrap() == 3i32 {
                    return self * self * self;
                }
            }
        }
        if self.dtype().is_floating() {
            return (exponent * self.ln()).exp();
        }
        self.clone().binary_op(exponent, BOp::Pow)
    }

    /// Elementwise compare less than between self and rhs
    #[must_use]
    pub fn cmplt(&self, rhs: impl IntoTensor<B>) -> Tensor<B> {
        self.clone().binary_op(rhs, BOp::Cmplt)
    }

    /// Returns a new tensor with the true values replaced with if_true and the false values replaced with if_false.
    #[must_use]
    pub fn where_(&self, if_true: impl IntoTensor<B>, if_false: impl IntoTensor<B>) -> Tensor<B> {
        let x = self.clone();
        let y = self.backend.tensor(if_true).unwrap();
        let z = self.backend.tensor(if_false).unwrap();
        let (x, y) = Tensor::broadcast(x, y);
        let (x, z) = Tensor::broadcast(x, z);
        let (y, z) = Tensor::broadcast(y, z);
        tensor(
            self.backend.push(Node::Where(x.id, y.id, z.id)).unwrap(),
            self.backend,
        )
    }

    /// Returns cosine_similarity between self and rhs, computed along axes.
    #[must_use]
    pub fn cosine_similarity(&self, rhs: impl IntoTensor<B>, eps: impl IntoTensor<B>) -> Tensor<B> {
        let rhs = self.backend.tensor(rhs).unwrap();
        let eps = self.backend.tensor(eps).unwrap();
        let x = self.pow(2).sqrt() * rhs.pow(2).sqrt();
        self * rhs / x.cmplt(&eps).where_(eps, x)
    }

    /// Dot product (mathematical multiplication) of self and rhs.
    /// ```rust
    /// # use zyx_opencl::DType;
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[3, 4, 2], [4, 5, 2]]);
    /// let y = dev.tensor([[3], [1], [4]]);
    /// assert_eq!(x.dot(y), [[21], [25]]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn dot(&self, rhs: impl IntoTensor<B>) -> Tensor<B> {
        let y = self.backend.tensor(rhs).unwrap().transpose();
        let xshape = self.shape();
        let yshape = y.shape();
        let yrank = yshape.rank();
        debug_assert_eq!(
            xshape[-1], yshape[-1],
            //yshape[-(yrank.min(2) as i64)],
            "Cannot dot tensors with shapes {xshape} and {yshape}"
        );
        let x_shape = xshape[0..-1]
            .iter()
            .copied()
            .chain([1])
            .chain([xshape[-1]])
            .collect::<Box<[usize]>>();
        let y_shape = yshape[0..-2]
            .iter()
            .copied()
            .chain([1])
            .chain(yshape[-(yrank.min(2) as i64)..yrank as i64].iter().copied())
            .collect::<Box<[usize]>>();
        //std::println!("{x_shape:?}");
        //std::println!("{y_shape:?}");
        (self.reshape(x_shape) * y.reshape(y_shape))
            .sum(-1)
            .reshape(
                xshape[0..-1]
                    .iter()
                    .copied()
                    .chain([yshape[-2]])
                    .collect::<Box<[usize]>>(),
            )
    }

    // Movement ops
    /// Reshape self to shape.
    /// # Panics
    /// Following must hold:
    /// self.numel() == shape.numel()
    #[must_use]
    pub fn reshape(&self, shape: impl Into<Shape>) -> Tensor<B> {
        let shape = shape.into();
        debug_assert_eq!(
            self.shape().numel(),
            shape.numel(),
            "Cannot reshape tensor with shape {} to {shape}",
            self.shape()
        );
        tensor(
            self.backend.push(Node::Reshape(self.id, shape)).unwrap(),
            self.backend,
        )
    }

    /// Expand self into bigger shape
    #[must_use]
    pub fn expand(&self, shape: impl Into<Shape>) -> Tensor<B> {
        let shape = shape.into();
        let sh = self.shape();
        debug_assert!(
            shape
                .iter()
                .rev()
                .enumerate()
                .all(|(i, d)| if sh.rank() > i {
                    *d == sh[sh.rank() - i - 1] || sh[sh.rank() - i - 1] == 1
                } else {
                    true
                }),
            "Can't expand tensor with shape {sh} to {shape}"
        );
        tensor(
            self.backend.push(Node::Expand(self.id, shape)).unwrap(),
            self.backend,
        )
    }

    /// Constant padding
    ///
    /// This can both add and remove values from tensor. Negative padding removes values, positive padding
    /// adds values.
    ///
    /// Pad last dimension by (1, 2)
    /// ```rust
    /// use zyx_opencl;
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3],
    ///                     [4, 1]]);
    /// let z = x.pad([(1, 2)], 0);
    /// std::println!("{}", z);
    /// assert_eq!(z, [[0, 2, 3, 0, 0],
    ///                [0, 4, 1, 0, 0]]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    /// Pad last dimension by (2, -1) and second last dimension by (1, 1)
    /// ```rust
    /// # use zyx_opencl;
    /// # let dev = zyx_opencl::device()?;
    /// # let x = dev.tensor([[2, 3],
    /// #                     [4, 1]]);
    /// let z = x.pad([(2, -1), (1, 1)], 0);
    /// println!("z: {z}");
    /// assert_eq!(z, [[0, 0, 0],
    ///                [0, 0, 2],
    ///                [0, 0, 4],
    ///                [0, 0, 0]]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    ///
    /// # Panics
    /// T must be of the same dtype as Tensor's dtype, otherwise this function panics.
    #[must_use]
    pub fn pad(
        &self,
        padding: impl IntoIterator<Item = (i64, i64)>,
        value: impl IntoTensor<B>,
    ) -> Tensor<B> {
        let dtype = self.dtype();
        let value = self.backend.tensor(value).unwrap();
        debug_assert_eq!(
            value.dtype(),
            dtype,
            "Cannot pad tensor with dtype {} with value of dtype {}",
            dtype,
            value.dtype()
        );
        let padding: Box<[(i64, i64)]> = padding.into_iter().collect();
        let sh = self.shape();
        debug_assert!(
            padding.len() <= sh.rank()
                && padding
                    .iter()
                    .zip(sh.iter().rev())
                    .all(|((lp, rp), d)| if *lp < 0 {
                        ((-*lp) as usize) <= *d
                    } else {
                        true
                    } && if *rp < 0 {
                        ((-*rp) as usize) <= *d
                    } else {
                        true
                    }),
            "Cannot pad tensor with shape {sh} with padding {padding:?}"
        );
        let psh = sh.clone().pad(&padding);
        let t0 = tensor(
            self.backend
                .push(Node::Pad(self.id, padding.clone(), psh.clone()))
                .unwrap(),
            self.backend,
        );
        if value.numel() == 1
            && match dtype {
                DType::F32 => value.item::<f32>().unwrap().is_equal(0f32),
                DType::F64 => value.item::<f64>().unwrap().is_equal(0f64),
                DType::I32 => value.item::<i32>().unwrap().is_equal(0i32),
            }
        {
            t0
        } else {
            t0 + tensor(
                self.backend
                    .push(Node::Pad(
                        self.backend.ones(sh, dtype).unwrap().id,
                        padding,
                        psh.clone(),
                    ))
                    .unwrap(),
                self.backend,
            )
            .where_(
                self.backend.zeros(self.shape(), self.dtype()).unwrap(),
                value,
            )
        }
    }

    /// Reorder axes of self
    #[must_use]
    pub fn permute(&self, axes: impl IntoAxes) -> Tensor<B> {
        let axes = axes.into_axes(self.rank());
        let shape = self.shape().permute(&axes);
        debug_assert!(
            axes.len() == shape.rank(),
            "Cannot permute tensor with shape {shape} with axes {axes}"
        );
        tensor(
            self.backend
                .push(Node::Permute(self.id, axes, shape))
                .unwrap(),
            self.backend,
        )
    }

    /// Swap last two axes of self.
    /// If self has rank == 1 and numel == n, then result will have shape /[n, 1/]
    #[must_use]
    pub fn transpose(&self) -> Tensor<B> {
        let mut rank = self.rank();
        let x = if rank == 1 {
            let n = self.numel();
            rank = 2;
            self.reshape([1, n])
        } else {
            self.clone()
        };
        let mut axes: Vec<usize> = (0..rank).collect();
        axes.swap(rank - 1, rank - 2);
        x.permute(axes)
    }

    /// Flatten. Joins axes into one dimension,
    #[must_use]
    pub fn flatten(&self, axes: impl FlattenAxes) -> Tensor<B> {
        let sh = self.shape();
        let n = sh.numel();
        let rank = sh.rank();
        let mut ld = 1;
        let mut first_dims = false;
        for a in axes.into_flatten_axes(rank) {
            let a = if a > 0 {
                a as usize
            } else {
                (a + rank as i64) as usize
            };
            if a == 0 {
                first_dims = true;
            }
            ld *= sh[a];
        }
        if first_dims {
            self.reshape([ld, n / ld])
        } else {
            self.reshape([n / ld, ld])
        }
    }

    // Reduce ops
    /// Reduce self by summing along axes. Shape is not squeezed.
    /// ```rust
    /// use zyx_opencl;
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3], [4, 1]]);
    /// let z = x.sum(-1);
    /// assert_eq!(z.shape(), [2, 1]);
    /// let z = x.sum(0);
    /// assert_eq!(z.shape(), [1, 2]);
    /// let z = x.sum(..);
    /// assert_eq!(z.shape(), [1, 1]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn sum(&self, axes: impl IntoAxes) -> Tensor<B> {
        let axes = axes.into_axes(self.rank());
        let shape = self.shape().reduce(&axes);
        let mut uniq = BTreeSet::new();
        debug_assert!(
            axes.into_iter().all(move |x| uniq.insert(x)),
            "Cannot sum tensor with shape {:?} by axes {:?}, because axes contain duplicates.",
            self.shape(),
            axes
        );
        tensor(
            self.backend.push(Node::Sum(self.id, axes, shape)).unwrap(),
            self.backend,
        )
    }

    /// Reduce self by maximizing along axes. Shape is not squeezed.
    /// ```rust
    /// use zyx_opencl;
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3], [4, 1]]);
    /// let z = x.max(-1);
    /// assert_eq!(z.shape(), [2, 1]);
    /// let z = x.max(0);
    /// assert_eq!(z.shape(), [1, 2]);
    /// let z = x.max(..);
    /// assert_eq!(z.shape(), [1, 1]);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn max(&self, axes: impl IntoAxes) -> Tensor<B> {
        let axes = axes.into_axes(self.rank());
        let shape = self.shape().reduce(&axes);
        let mut uniq = BTreeSet::new();
        debug_assert!(
            axes.into_iter().all(move |x| uniq.insert(x)),
            "Cannot sum tensor with shape {:?} by axes {:?}, because axes contain duplicates.",
            self.shape(),
            axes
        );
        for a in &axes {
            debug_assert!(
                *a < shape.rank(),
                "Cannot sum tensor with shape {:?} by axes {:?}, because some axes are greater than rank.",
                self.shape(),
                axes
            );
        }
        tensor(
            self.backend.push(Node::Max(self.id, axes, shape)).unwrap(),
            self.backend,
        )
    }

    /// Reduce self by calculating mean along axes
    #[must_use]
    pub fn mean(&self, axes: impl IntoAxes) -> Tensor<B> {
        let shape = self.shape();
        let axes = axes.into_axes(shape.rank());
        self.sum(axes.clone()) / axes.iter().copied().map(|a| shape[a]).product::<usize>() as i32
    }

    /// Reduce self by calculating variance along axes
    #[must_use]
    pub fn var(&self, axes: impl IntoAxes) -> Tensor<B> {
        let axes = axes.into_axes(self.rank());
        (self - self.mean(axes.clone())).pow(2).sum(axes)
    }

    /// Reduce self by calculating standard deviation along axes
    #[must_use]
    pub fn std(&self, axes: impl IntoAxes) -> Tensor<B> {
        self.var(axes).sqrt()
    }

    /// Reduce self by calculating norm along axes
    #[must_use]
    pub fn norm(&self, axes: impl IntoAxes, p: impl Scalar) -> Tensor<B> {
        self.pow(p.clone()).sum(axes).pow(p.reciprocal())
    }

    /// Reduce self by calculating product of elements along axes
    #[must_use]
    pub fn product(&self, axes: impl IntoAxes) -> Tensor<B> {
        self.ln().sum(axes).exp()
    }

    /// Get elements on diagonal of square matrix
    #[must_use]
    pub fn diagonal(&self) -> Tensor<B> {
        let n: usize = self.shape()[-1];
        self.flatten(..)
            .pad([(0, n as i64)], 0)
            .reshape([n, n + 1])
            .get((.., 0))
    }

    /*
    /// QR decompose function
    #[must_use]
    fn qr_decompose(&self) -> (Tensor<B>, Tensor<B>) {
        assert_eq!(self.rank(), 2, "QR decomposition only works for 2d matrices.");
        let dtype = self.dtype();
        assert!(dtype.is_floating(), "QR decomposition only works with floating point tensors.");
        let [n, m] = self.shape().try_into().unwrap();
        let u_temp = self.get((.., 0));
        let mut q = Vec::new();
        q.push(u_temp / u_temp.norm(()));
        for i in 1..n {
            let mut u_temp = self.get((.., i));
            // TODO all those dot operations should be fused into one by using expand and reshape and such.
            for j in 0..i {
                let q_temp = q.get((.., j));
                u_temp = u_temp - self.get((.., i)).dot(&q_temp) * &q_temp;
            }
            q.push(u_temp / u_temp.norm(.., 2));
        }
        let q = Tensor::cat(q, 0);
        let r = q.dot(self);
        return (q, r)
    }*/

    /// Tensor indexing.
    ///
    /// Tensors can be indexed by tuples of any combination of values or ranges of i64.
    /// If indexing along more than 8 dimensions, use \&\[Range\<i64\>\] or \&\[i64\]
    /// ```rust
    /// use zyx_opencl;
    /// let dev = zyx_opencl::device()?;
    /// let x = dev.tensor([[2, 3, 4],
    ///                     [4, 1, 8]]);
    /// let y: i32 = x.get((-1, -3)).item()?;
    /// assert_eq!(y, 4);
    /// # Ok::<(), zyx_opencl::ZyxError>(())
    /// ```
    #[must_use]
    pub fn get(&self, index: impl IntoIndex) -> Tensor<B> {
        // TODO asserts
        let shape = self.shape();
        let padding: Vec<(i64, i64)> = index
            .into_index()
            .into_iter()
            .zip(shape.iter())
            .map(|(r, d)| {
                (
                    if r.start >= 0 {
                        -r.start
                    } else {
                        -r.start - *d as i64
                    },
                    if r.end == i64::MAX {
                        0
                    } else if r.end > 0 {
                        -(*d as i64 - r.end)
                    } else {
                        r.end
                    },
                )
            })
            .collect();
        //std::println!("Get padding: {padding:?}");
        let n = shape.rank() - padding.len();
        self.pad(
            padding
                .into_iter()
                .chain(repeat((0, 0)).take(n))
                .collect::<Vec<(i64, i64)>>()
                .into_iter()
                .rev(),
            0,
        )
    }

    /// Concatenate multiple tensors together along dim.
    // ```rust
    // # use zyx_opencl;
    // # use zyx_opencl::Tensor;
    // let dev = zyx_opencl::device()?;
    // let x = dev.tensor([[2, 3, 4], [4, 1, 8]]);
    // let y = dev.tensor([[2, 3], [4, 1]]);
    // let z = Tensor::cat([&x, &y], -1);
    // // assert_eq!(z, []);
    // # Ok::<(), zyx_opencl::ZyxError>(())
    // ```
    #[must_use]
    pub fn cat<'a>(tensors: impl IntoIterator<Item = &'a Tensor<B>>, dim: i64) -> Tensor<B>
    where
        B: 'a,
    {
        let tensors: Vec<&Tensor<B>> = tensors.into_iter().collect();
        let shape = tensors[0].shape();
        let rank = shape.rank();
        let dim = if dim < 0 { dim + rank as i64 } else { dim } as usize;
        // Dimension check
        for tensor in &tensors {
            for (i, (d1, d2)) in shape.iter().zip(tensor.shape().iter()).enumerate() {
                if i != dim {
                    debug_assert_eq!(*d1, *d2, "Cannot concatenate these tensors.");
                }
            }
        }
        let mut offset = 0i64;
        let mut res = tensors[0]
            .backend
            .zeros(tensors[0].shape(), tensors[0].dtype())
            .unwrap();
        for tensor in tensors {
            res = res
                + tensor.pad(
                    repeat((0i64, 0i64))
                        .take(rank - dim - 1)
                        .chain([(offset, 0i64)]),
                    0,
                );
            offset += tensor.shape()[dim] as i64;
        }
        res
    }

    // TODO Cholesky and QR solve functions that are backend accelerated

    /*
    /// Stack multiple tensors into one
    #[must_use]
    pub fn stack<'a>(tensors: impl IntoIterator<Item = &'a Tensor<B>>, dim: i64) -> Tensor<B>
    where
        B: 'a
    {
        todo!()
    }*/

    /*
    /// Split self into multiple tensors along dim with given sizes.
    // TODO example
    #[must_use]
    pub fn split(&self, sizes: &[usize], dim: i64) -> Vec<Tensor<B>> {
        // just use negative padding
        todo!()
    }*/

    //#[must_use]
    //pub fn pool(&self)

    //#[must_use]
    //pub fn conv(&self)
}

enum BOp {
    Add,
    Sub,
    Mul,
    Div,
    Pow,
    Cmplt,
}

// Private helper functions
impl<B: Backend> Tensor<B> {
    #[must_use]
    fn binary_op(self, rhs: impl IntoTensor<B>, op: BOp) -> Tensor<B> {
        let rhs = rhs.into_tensor(self.backend);
        let (x, y) = Tensor::broadcast(self, rhs);
        tensor(
            x.backend
                .push(match op {
                    BOp::Add => Node::Add(x.id, y.id),
                    BOp::Sub => Node::Sub(x.id, y.id),
                    BOp::Mul => Node::Mul(x.id, y.id),
                    BOp::Div => Node::Div(x.id, y.id),
                    BOp::Pow => Node::Pow(x.id, y.id),
                    BOp::Cmplt => Node::Cmplt(x.id, y.id),
                })
                .unwrap(),
            x.backend,
        )
    }

    /// Braodcasts to synchronize shapes and casts to synchronize dtypss
    /// This does both automatic expand AND automatic casting between dtypes.
    // TODO Both of these can be disable by changing a setting in the backend.
    #[must_use]
    fn broadcast(mut x: Tensor<B>, mut y: Tensor<B>) -> (Tensor<B>, Tensor<B>) {
        /*assert_eq!(
            graph.dtype(xid),
            graph.dtype(yid),
            "{op} parameters {xid} and {yid} have different dtypes: {} and {}",
            graph.dtype(xid),
            graph.dtype(yid)
        );*/
        // Now we just do implicit conversions. Not exactly rust style, but it's convenient.
        // We can later add option for backend to disable these implicit conversions.
        match (x.dtype(), y.dtype()) {
            (DType::F32, DType::I32) => y = y.cast(DType::F32),
            (DType::F32, DType::F64) => x = x.cast(DType::F64),
            (DType::I32, DType::F32) => x = x.cast(DType::F32),
            (DType::I32, DType::F64) => x = x.cast(DType::F64),
            (DType::F64, DType::F32) => y = y.cast(DType::F64),
            (DType::F64, DType::I32) => y = y.cast(DType::F64),
            _ => {}
        }
        let mut x_shape = x.shape();
        let mut y_shape = y.shape();

        for (x, y) in x_shape.iter().rev().zip(y_shape.iter().rev()) {
            if x != y {
                debug_assert!(
                    *x == 1 || *y == 1,
                    "Left and right tensor shapes can not be broadcasted: {x_shape} and {y_shape}"
                );
            }
        }

        let rx = x_shape.rank();
        let ry = y_shape.rank();
        match rx.cmp(&ry) {
            Ordering::Less => {
                x_shape = repeat(1)
                    .take(ry - rx)
                    .chain(x_shape.into_iter().copied())
                    .collect::<Vec<usize>>()
                    .into();
            }
            Ordering::Greater => {
                y_shape = repeat(1)
                    .take(rx - ry)
                    .chain(y_shape.into_iter().copied())
                    .collect::<Vec<usize>>()
                    .into();
            }
            Ordering::Equal => {}
        }
        let mut eshape = Vec::new();
        for (x, y) in x_shape.into_iter().zip(y_shape.into_iter()) {
            eshape.push(*x.max(y));
        }
        let eshape: Shape = eshape.into();
        if x_shape != eshape {
            x = x.expand(eshape.clone());
        }
        if y_shape != eshape {
            y = y.expand(eshape);
        }
        (x, y)
    }
}

impl<B: Backend> core::ops::Neg for Tensor<B> {
    type Output = Tensor<B>;
    fn neg(self) -> Self::Output {
        tensor(self.backend.push(Node::Neg(self.id)).unwrap(), self.backend)
    }
}

impl<B: Backend> core::ops::Neg for &Tensor<B> {
    type Output = Tensor<B>;
    fn neg(self) -> Self::Output {
        tensor(self.backend.push(Node::Neg(self.id)).unwrap(), self.backend)
    }
}

impl<B: Backend, IT: IntoTensor<B>> core::ops::Add<IT> for &Tensor<B> {
    type Output = Tensor<B>;
    fn add(self, rhs: IT) -> Self::Output {
        self.clone().binary_op(rhs, BOp::Add)
    }
}

impl<B: Backend, IT: IntoTensor<B>> core::ops::Add<IT> for Tensor<B> {
    type Output = Tensor<B>;
    fn add(self, rhs: IT) -> Self::Output {
        self.binary_op(rhs, BOp::Add)
    }
}

impl<B: Backend, IT: IntoTensor<B>> core::ops::Sub<IT> for &Tensor<B> {
    type Output = Tensor<B>;
    fn sub(self, rhs: IT) -> Self::Output {
        self.clone().binary_op(rhs, BOp::Sub)
    }
}

impl<B: Backend, IT: IntoTensor<B>> core::ops::Sub<IT> for Tensor<B> {
    type Output = Tensor<B>;
    fn sub(self, rhs: IT) -> Self::Output {
        self.binary_op(rhs, BOp::Sub)
    }
}

impl<B: Backend, IT: IntoTensor<B>> core::ops::Mul<IT> for &Tensor<B> {
    type Output = Tensor<B>;
    fn mul(self, rhs: IT) -> Self::Output {
        self.clone().binary_op(rhs, BOp::Mul)
    }
}

impl<B: Backend> core::ops::Mul<Tensor<B>> for f32 {
    type Output = Tensor<B>;
    fn mul(self, rhs: Tensor<B>) -> Self::Output {
        rhs * self
    }
}

impl<B: Backend> core::ops::Mul<&Tensor<B>> for f32 {
    type Output = Tensor<B>;
    fn mul(self, rhs: &Tensor<B>) -> Self::Output {
        rhs * self
    }
}

impl<B: Backend> core::ops::Mul<Tensor<B>> for f64 {
    type Output = Tensor<B>;
    fn mul(self, rhs: Tensor<B>) -> Self::Output {
        rhs * self
    }
}

impl<B: Backend> core::ops::Mul<&Tensor<B>> for f64 {
    type Output = Tensor<B>;
    fn mul(self, rhs: &Tensor<B>) -> Self::Output {
        rhs * self
    }
}

impl<B: Backend> core::ops::Mul<Tensor<B>> for i32 {
    type Output = Tensor<B>;
    fn mul(self, rhs: Tensor<B>) -> Self::Output {
        rhs * self
    }
}

impl<B: Backend> core::ops::Mul<&Tensor<B>> for i32 {
    type Output = Tensor<B>;
    fn mul(self, rhs: &Tensor<B>) -> Self::Output {
        rhs * self
    }
}

impl<B: Backend, IT: IntoTensor<B>> core::ops::Mul<IT> for Tensor<B> {
    type Output = Tensor<B>;
    fn mul(self, rhs: IT) -> Self::Output {
        self.binary_op(rhs, BOp::Mul)
    }
}

impl<B: Backend, IT: IntoTensor<B>> core::ops::Div<IT> for &Tensor<B> {
    type Output = Tensor<B>;
    fn div(self, rhs: IT) -> Self::Output {
        self.clone().binary_op(rhs, BOp::Div)
    }
}

impl<B: Backend, IT: IntoTensor<B>> core::ops::Div<IT> for Tensor<B> {
    type Output = Tensor<B>;
    fn div(self, rhs: IT) -> Self::Output {
        self.binary_op(rhs, BOp::Div)
    }
}

impl<B: Backend> core::ops::Div<Tensor<B>> for f32 {
    type Output = Tensor<B>;
    fn div(self, rhs: Tensor<B>) -> Self::Output {
        rhs.backend.tensor(self).unwrap().binary_op(rhs, BOp::Div)
    }
}

impl<B: Backend> core::ops::Div<&Tensor<B>> for f32 {
    type Output = Tensor<B>;
    fn div(self, rhs: &Tensor<B>) -> Self::Output {
        rhs.backend.tensor(self).unwrap().binary_op(rhs, BOp::Div)
    }
}

impl<B: Backend> core::ops::Div<Tensor<B>> for f64 {
    type Output = Tensor<B>;
    fn div(self, rhs: Tensor<B>) -> Self::Output {
        rhs.backend.tensor(self).unwrap().binary_op(rhs, BOp::Div)
    }
}

impl<B: Backend> core::ops::Div<&Tensor<B>> for f64 {
    type Output = Tensor<B>;
    fn div(self, rhs: &Tensor<B>) -> Self::Output {
        rhs.backend.tensor(self).unwrap().binary_op(rhs, BOp::Div)
    }
}

impl<B: Backend> core::ops::Div<Tensor<B>> for i32 {
    type Output = Tensor<B>;
    fn div(self, rhs: Tensor<B>) -> Self::Output {
        rhs.backend.tensor(self).unwrap().binary_op(rhs, BOp::Div)
    }
}

impl<B: Backend> core::ops::Div<&Tensor<B>> for i32 {
    type Output = Tensor<B>;
    fn div(self, rhs: &Tensor<B>) -> Self::Output {
        rhs.backend.tensor(self).unwrap().binary_op(rhs, BOp::Div)
    }
}

/// Objects must implement this to be convertible into tensor
pub trait IntoTensor<B: Backend> {
    /// Convert self into tensor
    fn into_tensor(self, backend: B) -> Tensor<B>;
}

impl<B: Backend> IntoTensor<B> for Tensor<B> {
    fn into_tensor(self, _backend: B) -> Tensor<B> {
        // TODO assert self.backend == backend
        self
    }
}

impl<B: Backend> IntoTensor<B> for &Tensor<B> {
    fn into_tensor(self, _backend: B) -> Tensor<B> {
        // TODO assert self.backend == backend
        self.clone()
    }
}

impl<B: Backend, T: Scalar> IntoTensor<B> for Range<T>
where
    Range<T>: Iterator<Item = T> + ExactSizeIterator,
{
    fn into_tensor(self, backend: B) -> Tensor<B> {
        tensor(backend.store(self).unwrap(), backend)
    }
}

impl<B: Backend, T: Scalar> IntoTensor<B> for Vec<T> {
    fn into_tensor(self, backend: B) -> Tensor<B> {
        tensor(backend.store(self).unwrap(), backend)
    }
}

impl<B: Backend, T: Scalar> IntoTensor<B> for &'static [T] {
    fn into_tensor(self, backend: B) -> Tensor<B> {
        tensor(backend.store(self.iter().cloned()).unwrap(), backend)
    }
}

impl<B: Backend, T: Scalar> IntoTensor<B> for T {
    fn into_tensor(self, backend: B) -> Tensor<B> {
        tensor(backend.store([self]).unwrap(), backend)
    }
}

impl<B: Backend, T: Scalar, const D0: usize> IntoTensor<B> for [T; D0] {
    fn into_tensor(self, backend: B) -> Tensor<B> {
        tensor(backend.store(self).unwrap(), backend)
    }
}

impl<B: Backend, T: Scalar, const D0: usize, const D1: usize> IntoTensor<B> for [[T; D1]; D0] {
    fn into_tensor(self, backend: B) -> Tensor<B> {
        tensor(
            backend
                .store(self.into_iter().flatten().make_sized(D0 * D1))
                .unwrap(),
            backend,
        )
        .reshape([D0, D1])
    }
}

impl<B: Backend, T: Scalar, const D0: usize, const D1: usize, const D2: usize> IntoTensor<B>
    for [[[T; D2]; D1]; D0]
{
    fn into_tensor(self, backend: B) -> Tensor<B> {
        tensor(
            backend
                .store(
                    self.into_iter()
                        .flatten()
                        .flatten()
                        .make_sized(D0 * D1 * D2),
                )
                .unwrap(),
            backend,
        )
        .reshape([D0, D1, D2])
    }
}

impl<B: Backend, IT: IntoTensor<B> + Clone> PartialEq<IT> for Tensor<B> {
    fn eq(&self, other: &IT) -> bool {
        let other = self.backend.tensor(other.clone()).unwrap();
        let dtype = self.dtype();
        self.shape() == other.shape()
            && dtype == other.dtype()
            && match dtype {
                DType::F32 => self
                    .to_vec::<f32>()
                    .unwrap()
                    .into_iter()
                    .zip(other.to_vec::<f32>().unwrap())
                    .all(|(x, y)| x.is_equal(y)),
                DType::F64 => self
                    .to_vec::<f64>()
                    .unwrap()
                    .into_iter()
                    .zip(other.to_vec::<f64>().unwrap())
                    .all(|(x, y)| x.is_equal(y)),
                DType::I32 => self
                    .to_vec::<i32>()
                    .unwrap()
                    .into_iter()
                    .zip(other.to_vec::<i32>().unwrap())
                    .all(|(x, y)| x.is_equal(y)),
            }
    }
}