burn-flex 0.22.0-pre.4

A fast, portable CPU backend for the Burn framework
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
use alloc::vec::Vec;
use core::fmt;

use burn_backend::{DType, Element, TensorData, TensorMetadata};
use burn_std::sync::Arc;
use burn_std::{Bytes, Shape, bf16, f16};

use crate::{FlexDevice, layout::Layout};

/// CPU tensor primitive for the Flex backend.
///
/// Uses type-erased byte storage with runtime dtype and Arc-based sharing.
/// Clone is O(1) (refcount increment). Copy-on-write for mutations.
#[derive(Clone)]
pub struct FlexTensor {
    /// Shared byte storage. Clone increments refcount.
    data: Arc<Bytes>,
    /// Layout describing shape, strides, and offset.
    layout: Layout,
    /// Runtime data type.
    dtype: DType,
}

impl fmt::Debug for FlexTensor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FlexTensor")
            .field("shape", self.layout.shape())
            .field("dtype", &self.dtype)
            .field("contiguous", &self.layout.is_contiguous())
            .field("unique", &self.is_unique())
            .finish()
    }
}

impl FlexTensor {
    /// Create a new tensor from bytes, layout, and dtype.
    pub fn new(data: Bytes, layout: Layout, dtype: DType) -> Self {
        Self {
            data: Arc::new(data),
            layout,
            dtype,
        }
    }

    /// Create a tensor from TensorData.
    pub fn from_data(data: TensorData) -> Self {
        let shape = data.shape.clone();
        let layout = Layout::contiguous(shape);
        let dtype = data.dtype;
        Self {
            data: Arc::new(data.bytes),
            layout,
            dtype,
        }
    }

    /// Convert tensor to TensorData.
    ///
    /// If non-contiguous or shared, this will copy data.
    pub fn into_data(self) -> TensorData {
        if self.layout.is_contiguous() && self.layout.start_offset() == 0 {
            let expected_bytes = self.layout.num_elements() * dtype_size(self.dtype);
            assert!(
                expected_bytes <= self.data.len(),
                "into_data: buffer ({} bytes) too small for {} elements of {:?}",
                self.data.len(),
                self.layout.num_elements(),
                self.dtype
            );
            if self.data.len() == expected_bytes {
                // Buffer exactly matches logical size; try zero-copy unwrap
                match Arc::try_unwrap(self.data) {
                    Ok(bytes) => TensorData {
                        bytes,
                        shape: self.layout.shape().clone(),
                        dtype: self.dtype,
                    },
                    Err(arc) => {
                        let bytes = Bytes::from_bytes_vec((*arc)[..expected_bytes].to_vec());
                        TensorData {
                            bytes,
                            shape: self.layout.shape().clone(),
                            dtype: self.dtype,
                        }
                    }
                }
            } else {
                // Contiguous at offset 0 but buffer is oversized (e.g., narrowed view).
                // Truncate to exact logical size.
                let bytes = Bytes::from_bytes_vec(self.data[..expected_bytes].to_vec());
                TensorData {
                    bytes,
                    shape: self.layout.shape().clone(),
                    dtype: self.dtype,
                }
            }
        } else {
            // Non-contiguous or non-zero offset: copy to contiguous layout
            self.to_contiguous().into_data()
        }
    }

    /// Check if this tensor has exclusive ownership of its data.
    ///
    /// When true, in-place mutations are safe without copying.
    #[inline]
    pub fn is_unique(&self) -> bool {
        Arc::strong_count(&self.data) == 1
    }

    /// Get the layout.
    pub fn layout(&self) -> &Layout {
        &self.layout
    }

    /// Create a new tensor with a different layout but sharing the same data.
    ///
    /// This is a zero-copy operation used for operations like flip, transpose, etc.
    pub fn with_layout(self, layout: Layout) -> Self {
        Self {
            data: self.data,
            layout,
            dtype: self.dtype,
        }
    }

    /// Get the dtype.
    pub fn dtype(&self) -> DType {
        self.dtype
    }

    /// Check if tensor is contiguous.
    pub fn is_contiguous(&self) -> bool {
        self.layout.is_contiguous()
    }

    /// Get the raw bytes (read-only).
    pub fn bytes(&self) -> &[u8] {
        &self.data
    }

    /// Get a clone of the Arc for sharing data with a new layout.
    ///
    /// Use this for zero-copy view operations (reshape, transpose, slice).
    pub fn data_arc(&self) -> Arc<Bytes> {
        Arc::clone(&self.data)
    }

    /// Create a tensor from shared data, layout, and dtype.
    ///
    /// Use this for zero-copy view operations.
    pub fn from_arc(data: Arc<Bytes>, layout: Layout, dtype: DType) -> Self {
        Self {
            data,
            layout,
            dtype,
        }
    }

    /// Zero-copy typed view of the full storage buffer.
    ///
    /// Use with `StridedIter` for non-contiguous access, or with
    /// `layout().contiguous_offsets()` for the contiguous fast path.
    ///
    /// # Panics
    /// Panics if `E::dtype()` doesn't match the tensor's dtype.
    /// Note: Bool tensors are stored as u8, so both Bool(Native) and Bool(U8)
    /// dtypes accept u8 access.
    pub fn storage<E: Element + bytemuck::Pod>(&self) -> &[E] {
        assert!(
            E::dtype() == self.dtype
                || (matches!(
                    self.dtype,
                    DType::Bool(burn_std::BoolStore::Native | burn_std::BoolStore::U8)
                ) && E::dtype() == DType::U8),
            "storage: dtype mismatch (expected {:?}, got {:?})",
            self.dtype,
            E::dtype()
        );
        bytemuck::cast_slice(&self.data)
    }

    /// Mutable typed view with copy-on-write semantics.
    ///
    /// If the tensor is shared (refcount > 1), this will copy the data first.
    /// For in-place operations, prefer `try_storage_mut()` which returns None
    /// if shared, allowing you to choose an alternative strategy.
    ///
    /// # Panics
    /// Panics if `E::dtype()` doesn't match the tensor's dtype.
    /// Note: Bool tensors are stored as u8, so both Bool(Native) and Bool(U8)
    /// dtypes accept u8 access.
    pub fn storage_mut<E: Element + bytemuck::Pod>(&mut self) -> &mut [E] {
        assert!(
            E::dtype() == self.dtype
                || (matches!(
                    self.dtype,
                    DType::Bool(burn_std::BoolStore::Native | burn_std::BoolStore::U8)
                ) && E::dtype() == DType::U8),
            "storage_mut: dtype mismatch (expected {:?}, got {:?})",
            self.dtype,
            E::dtype()
        );
        // COW: clone data if shared
        let bytes = Arc::make_mut(&mut self.data);
        bytemuck::cast_slice_mut(bytes)
    }

    /// Try to get mutable storage without copying.
    ///
    /// Returns `Some` if tensor is uniquely owned, `None` if shared.
    /// Use this when you want to avoid the implicit copy in `storage_mut()`.
    /// Note: Bool tensors are stored as u8, so both Bool(Native) and Bool(U8)
    /// dtypes accept u8 access.
    pub fn try_storage_mut<E: Element + bytemuck::Pod>(&mut self) -> Option<&mut [E]> {
        assert!(
            E::dtype() == self.dtype
                || (matches!(
                    self.dtype,
                    DType::Bool(burn_std::BoolStore::Native | burn_std::BoolStore::U8)
                ) && E::dtype() == DType::U8),
            "try_storage_mut: dtype mismatch (expected {:?}, got {:?})",
            self.dtype,
            E::dtype()
        );
        if self.is_unique() {
            // Safe: we're the only owner
            let bytes = Arc::get_mut(&mut self.data)?;
            Some(bytemuck::cast_slice_mut(bytes))
        } else {
            None
        }
    }

    /// Get typed slice view (zero-cost if contiguous and offset is 0).
    ///
    /// Returns None if dtype doesn't match E or tensor is non-contiguous.
    pub fn as_slice<E: Element + bytemuck::Pod>(&self) -> Option<&[E]> {
        if E::dtype() != self.dtype {
            return None;
        }
        let storage: &[E] = self.storage();
        self.layout
            .contiguous_offsets()
            .map(|(start, end)| &storage[start..end])
    }

    /// Create an empty tensor with given shape and dtype.
    pub fn empty(shape: Shape, dtype: DType) -> Self {
        let num_elements = shape.num_elements();
        let elem_size = dtype_size(dtype);
        let bytes = Bytes::from_bytes_vec(alloc::vec![0u8; num_elements * elem_size]);
        let layout = Layout::contiguous(shape);
        Self {
            data: Arc::new(bytes),
            layout,
            dtype,
        }
    }

    /// Create a tensor filled with zeros.
    pub fn zeros(shape: Shape, dtype: DType) -> Self {
        Self::empty(shape, dtype)
    }

    /// Create a tensor filled with `n` copies of a typed value.
    pub fn filled_typed<E: bytemuck::Pod + Send + Sync>(
        shape: Shape,
        dtype: DType,
        value: E,
    ) -> Self {
        assert_eq!(
            dtype_size(dtype),
            core::mem::size_of::<E>(),
            "filled_typed: dtype size mismatch"
        );
        let n = shape.num_elements();
        let data = alloc::vec![value; n];
        let bytes = Bytes::from_elems(data);
        Self {
            data: Arc::new(bytes),
            layout: Layout::contiguous(shape),
            dtype,
        }
    }

    /// Copy to contiguous layout if needed, consuming `self`.
    ///
    /// Prefer this over [`Self::to_contiguous`] when you own the tensor and
    /// will mutate it through [`Self::storage_mut`]: the borrowing form has
    /// to hand back a second `Arc` handle, which makes the later
    /// copy-on-write check see a shared buffer.
    pub(crate) fn into_contiguous(self) -> Self {
        // Fast path requires the logical tensor to cover the whole buffer.
        // A contiguous prefix view (e.g. [8, 5] sliced to [5, 5]) has
        // canonical strides and offset 0 but an oversized buffer, and would
        // otherwise mislead callers that read `storage()` / `bytes()` by
        // length (e.g. the SIMD `mask_fill_*` kernels).
        if self.is_contiguous()
            && self.layout.start_offset() == 0
            && self.data.len() == self.layout.num_elements() * dtype_size(self.dtype)
        {
            return self;
        }

        // Copy data to new contiguous buffer
        match self.dtype {
            DType::F64 => self.copy_contiguous::<f64>(),
            DType::F32 => self.copy_contiguous::<f32>(),
            DType::F16 => self.copy_contiguous::<f16>(),
            DType::BF16 => self.copy_contiguous::<bf16>(),
            DType::I64 => self.copy_contiguous::<i64>(),
            DType::I32 => self.copy_contiguous::<i32>(),
            DType::I16 => self.copy_contiguous::<i16>(),
            DType::I8 => self.copy_contiguous::<i8>(),
            DType::U64 => self.copy_contiguous::<u64>(),
            DType::U32 => self.copy_contiguous::<u32>(),
            DType::U16 => self.copy_contiguous::<u16>(),
            DType::U8 => self.copy_contiguous::<u8>(),
            DType::Bool(burn_std::BoolStore::Native | burn_std::BoolStore::U8) => {
                self.copy_contiguous::<u8>()
            }
            DType::Bool(burn_std::BoolStore::U32) => {
                panic!("burn-flex: Bool(U32) storage is not yet supported")
            }
            _ => panic!("Unsupported dtype for contiguous copy: {:?}", self.dtype),
        }
    }

    /// Copy to contiguous layout if needed.
    pub fn to_contiguous(&self) -> Self {
        self.clone().into_contiguous()
    }

    fn copy_contiguous<E: Element + bytemuck::Pod>(&self) -> Self {
        let src: &[E] = bytemuck::cast_slice(&self.data);
        let n = self.layout.num_elements();
        let mut dst = Vec::with_capacity(n);

        // Squeeze size-1 dims and merge adjacent stride-contiguous
        // runs so e.g. a permuted `[N, H, W, C]` ConvNeXt layer-norm
        // input becomes a plain 2D `[H*W, C]` transpose that the
        // tiled copy below handles at near-memcpy speed. Without the
        // collapse, the 4D ND fallback scalar-walks the tensor.
        let collapsed = collapse_for_copy(self.layout.shape(), self.layout.strides());
        let (shape, strides) = collapsed.as_slices();
        let offset = self.layout.start_offset() as isize;
        let all_positive = strides.iter().all(|&s| s >= 0);

        if n == 0 {
            return Self::empty(self.layout.shape().clone(), self.dtype);
        }

        if shape.len() <= 1 {
            // 0-D scalar or 1-D run with a uniform stride (positive or negative).
            let collapsed_numel = if shape.is_empty() { 1 } else { shape[0] };
            debug_assert_eq!(n, collapsed_numel);
            // SAFETY: capacity is n; we fill every position below.
            unsafe { dst.set_len(n) };
            if shape.is_empty() {
                if n > 0 {
                    dst[0] = src[offset as usize];
                }
            } else {
                let len = shape[0];
                let stride = strides[0];
                if stride == 1 {
                    dst[..len].copy_from_slice(&src[offset as usize..offset as usize + len]);
                } else if stride == -1 {
                    let start = (offset - (len as isize - 1)) as usize;
                    let src_slice = &src[start..start + len];
                    for (slot, &val) in dst[..len].iter_mut().zip(src_slice.iter().rev()) {
                        *slot = val;
                    }
                } else {
                    for (i, slot) in dst.iter_mut().take(len).enumerate() {
                        let idx = (offset + i as isize * stride) as usize;
                        *slot = src[idx];
                    }
                }
            }
        } else if shape.len() == 2 && all_positive {
            // 2D positive-stride (transpose-like): tile both dims so
            // reads stay in cache. The loop-nesting chooser inside
            // `copy_2d_tiled` picks whichever ordering puts the
            // smaller source stride on the innermost loop.
            debug_assert_eq!(shape[0] * shape[1], n, "2D strides must cover all elements");
            // SAFETY: capacity is n; `copy_2d_tiled` writes every
            // `(row, col)` position exactly once.
            unsafe { dst.set_len(n) };
            copy_2d_tiled(
                &mut dst, src, offset, shape[0], shape[1], strides[0], strides[1],
            );
        } else if shape.len() == 2 && !all_positive {
            // 2D negative-stride (flipped): fast row-based copies.
            debug_assert_eq!(shape[0] * shape[1], n);
            unsafe { dst.set_len(n) };
            copy_2d_negative(
                &mut dst, src, offset, shape[0], shape[1], strides[0], strides[1],
            );
        } else if shape.len() >= 3 && all_positive && is_transposed_2d(shape, strides) {
            // Batched 2D transpose: iterate over leading batch dims and execute copy_2d_tiled per slice.
            unsafe { dst.set_len(n) };
            copy_batched_2d_tiled(&mut dst, src, offset, shape, strides);
        } else if all_positive && strides.last().copied() == Some(1) {
            // Since the inner stride is 1, we can bulk-copy
            // the contiguous inner run for each outer index.
            unsafe { dst.set_len(n) };
            copy_inner_contiguous_run(&mut dst, src, offset, shape, strides);
        } else {
            // General fallback: covers negative strides (flipped
            // tensors) and ND layouts that can't collapse to ≤2D.
            for idx in crate::strided_index::StridedIter::new(&self.layout) {
                dst.push(src[idx]);
            }
        }

        let bytes = Bytes::from_elems(dst);
        let layout = Layout::contiguous(self.layout.shape().clone());
        Self {
            data: Arc::new(bytes),
            layout,
            dtype: self.dtype,
        }
    }

    /// Reshape tensor. Zero-copy if contiguous.
    pub fn reshape(&self, new_shape: Shape) -> Self {
        assert_eq!(
            self.layout.num_elements(),
            new_shape.num_elements(),
            "reshape must preserve total elements"
        );

        if let Some(new_layout) = self.layout.reshape(new_shape.clone()) {
            Self {
                data: Arc::clone(&self.data),
                layout: new_layout,
                dtype: self.dtype,
            }
        } else {
            // Non-contiguous: copy first
            self.to_contiguous().reshape(new_shape)
        }
    }

    /// Transpose two dimensions. Zero-copy (metadata only).
    pub fn transpose(&self, dim1: usize, dim2: usize) -> Self {
        Self {
            data: Arc::clone(&self.data),
            layout: self.layout.transpose(dim1, dim2),
            dtype: self.dtype,
        }
    }

    /// Narrow/slice along a dimension. Zero-copy (metadata only).
    pub fn narrow(&self, dim: usize, start: usize, len: usize) -> Self {
        Self {
            data: Arc::clone(&self.data),
            layout: self.layout.narrow(dim, start, len),
            dtype: self.dtype,
        }
    }

    /// Permute dimensions according to axes. Zero-copy (metadata only).
    pub fn permute(&self, axes: &[usize]) -> Self {
        Self {
            data: Arc::clone(&self.data),
            layout: self.layout.permute(axes),
            dtype: self.dtype,
        }
    }
}

impl TensorMetadata for FlexTensor {
    type Device = FlexDevice;

    fn dtype(&self) -> DType {
        self.dtype
    }

    fn shape(&self) -> Shape {
        self.layout.shape().clone()
    }

    fn rank(&self) -> usize {
        self.layout.num_dims()
    }

    fn device(&self) -> Self::Device {
        FlexDevice
    }

    fn can_mut(&self) -> bool {
        self.is_unique()
    }
}

/// Max rank we're willing to handle without falling back to the
/// strided iterator. Burn tensors are capped at 8 dims in practice.
const COLLAPSE_MAX_RANK: usize = 8;

/// Collapsed layout result of [`collapse_for_copy`], stored in stack
/// arrays so `to_contiguous()` doesn't have to hit the allocator on
/// its hot path.
#[derive(Debug, Clone, Copy)]
struct CollapsedLayout {
    ndim: usize,
    shape: [usize; COLLAPSE_MAX_RANK],
    strides: [isize; COLLAPSE_MAX_RANK],
}

impl CollapsedLayout {
    #[inline]
    fn as_slices(&self) -> (&[usize], &[isize]) {
        (&self.shape[..self.ndim], &self.strides[..self.ndim])
    }
}

/// Collapse a shape/stride pair into the minimum-rank equivalent
/// layout for a contiguous copy:
///
/// 1. Squeeze size-1 dims (their stride never gets stepped past 0).
/// 2. Merge adjacent dims `(i, i+1)` when
///    `stride[i] == stride[i+1] * shape[i+1]`, which means the two
///    dims form a single logical run through memory.
///
/// Canonical example: a 4D ConvNeXt input `[1, 244, 224, 48]` with
/// strides `[2_623_488, 224, 1, 54656]` (from
/// `[N, C, H, W].permute([0, 2, 3, 1])`) collapses to 2D
/// `[54656, 48]` with strides `[1, 54656]`.
///
/// If the input rank exceeds [`COLLAPSE_MAX_RANK`] the result is
/// left at rank > 2 so the caller falls through to its generic
/// strided path. If the input is rank > `COLLAPSE_MAX_RANK`, we
/// return the original (un-collapsed) layout truncated, which the
/// caller will reject via its `shape.len() == 2` gate.
///
/// PRECONDITION: the caller must gate on all-positive strides before
/// using the collapsed layout. The merge rule assumes positive
/// strides and will produce iteration-order-incorrect results for
/// flipped tensors.
fn collapse_for_copy(shape: &[usize], strides: &[isize]) -> CollapsedLayout {
    let mut out = CollapsedLayout {
        ndim: 0,
        shape: [0; COLLAPSE_MAX_RANK],
        strides: [0; COLLAPSE_MAX_RANK],
    };

    // Bail out to the caller's fallback if the rank is too large to
    // fit our stack buffer. In practice this never triggers (burn
    // tensors are ≤8 dims), but leaving the `ndim` high signals the
    // caller to take the generic strided path.
    if shape.len() > COLLAPSE_MAX_RANK {
        out.ndim = shape.len().min(COLLAPSE_MAX_RANK);
        return out;
    }

    // Single forward sweep: squeeze size-1 dims and merge whenever
    // the current dim's `stride * size` equals the previous output
    // dim's stride (i.e. the two form a contiguous run).
    //
    // Use `checked_mul` so a pathological layout whose stride math
    // would overflow `isize` simply fails to merge rather than
    // wrapping into an incorrect merge decision. Real tensors can't
    // hit this (total numel is bounded by `isize::MAX`), but
    // hand-built layouts passed through the test paths could.
    for (&s, &st) in shape.iter().zip(strides.iter()) {
        if s == 1 {
            continue;
        }
        let merge = out.ndim > 0
            && st > 0
            && out.strides[out.ndim - 1] > 0
            && (s as isize)
                .checked_mul(st)
                .is_some_and(|run| out.strides[out.ndim - 1] == run);
        if merge {
            out.shape[out.ndim - 1] *= s;
            out.strides[out.ndim - 1] = st;
        } else {
            out.shape[out.ndim] = s;
            out.strides[out.ndim] = st;
            out.ndim += 1;
        }
    }

    out
}

#[inline]
fn is_transposed_2d(shape: &[usize], strides: &[isize]) -> bool {
    let rank = shape.len();
    if rank < 3 {
        return false;
    }
    let r_st = strides[rank - 2];
    let c_st = strides[rank - 1];
    (r_st == 1 && c_st > 1) || (c_st == 1 && r_st > 1 && r_st != shape[rank - 1] as isize)
}

fn copy_batched_2d_tiled<E: Copy + Send + Sync>(
    dst: &mut [E],
    src: &[E],
    offset: isize,
    shape: &[usize],
    strides: &[isize],
) {
    let rank = shape.len();
    let rows = shape[rank - 2];
    let cols = shape[rank - 1];
    let r_st = strides[rank - 2];
    let c_st = strides[rank - 1];
    let slice_len = rows * cols;

    let batch_shape = &shape[..rank - 2];
    let batch_strides = &strides[..rank - 2];
    #[cfg(feature = "rayon")]
    {
        let batch_count: usize = batch_shape.iter().product();
        if batch_count * slice_len >= crate::ops::PARALLEL_THRESHOLD && batch_count > 1 {
            use rayon::prelude::*;
            dst.par_chunks_mut(slice_len)
                .enumerate()
                .for_each(|(b, slice_dst)| {
                    let mut remaining = b;
                    let mut batch_offset = offset;
                    for d in (0..batch_shape.len()).rev() {
                        let coord = remaining % batch_shape[d];
                        remaining /= batch_shape[d];
                        batch_offset += coord as isize * batch_strides[d];
                    }
                    copy_2d_tiled(slice_dst, src, batch_offset, rows, cols, r_st, c_st);
                });
            return;
        }
    }

    for (b, slice_dst) in dst.chunks_mut(slice_len).enumerate() {
        let mut remaining = b;
        let mut batch_offset = offset;
        for d in (0..batch_shape.len()).rev() {
            let coord = remaining % batch_shape[d];
            remaining /= batch_shape[d];
            batch_offset += coord as isize * batch_strides[d];
        }
        copy_2d_tiled(slice_dst, src, batch_offset, rows, cols, r_st, c_st);
    }
}

fn copy_2d_negative<E: Copy + Send + Sync>(
    dst: &mut [E],
    src: &[E],
    offset: isize,
    rows: usize,
    cols: usize,
    row_stride: isize,
    col_stride: isize,
) {
    #[cfg(feature = "rayon")]
    let n = rows * cols;
    if row_stride < 0 && col_stride == 1 {
        #[cfg(feature = "rayon")]
        if n >= crate::ops::PARALLEL_THRESHOLD {
            use rayon::prelude::*;
            dst.par_chunks_mut(cols)
                .enumerate()
                .for_each(|(r, dst_row)| {
                    let row_src = (offset + r as isize * row_stride) as usize;
                    dst_row.copy_from_slice(&src[row_src..row_src + cols]);
                });
            return;
        }
        for r in 0..rows {
            let row_src = (offset + r as isize * row_stride) as usize;
            let dst_start = r * cols;
            dst[dst_start..dst_start + cols].copy_from_slice(&src[row_src..row_src + cols]);
        }
    } else if col_stride == -1 {
        #[cfg(feature = "rayon")]
        if n >= crate::ops::PARALLEL_THRESHOLD {
            use rayon::prelude::*;
            dst.par_chunks_mut(cols)
                .enumerate()
                .for_each(|(r, dst_row)| {
                    let row_src_end = (offset + r as isize * row_stride) as usize;
                    let row_src_start = row_src_end + 1 - cols;
                    let src_slice = &src[row_src_start..=row_src_end];
                    for (slot, &val) in dst_row.iter_mut().zip(src_slice.iter().rev()) {
                        *slot = val;
                    }
                });
            return;
        }
        for r in 0..rows {
            let row_src_end = (offset + r as isize * row_stride) as usize;
            let row_src_start = row_src_end + 1 - cols;
            let src_slice = &src[row_src_start..=row_src_end];
            let dst_row = &mut dst[r * cols..(r + 1) * cols];
            for (slot, &val) in dst_row.iter_mut().zip(src_slice.iter().rev()) {
                *slot = val;
            }
        }
    } else {
        for r in 0..rows {
            let row_base = offset + r as isize * row_stride;
            let dst_row = &mut dst[r * cols..(r + 1) * cols];
            for (c, slot) in dst_row.iter_mut().enumerate() {
                let idx = (row_base + c as isize * col_stride) as usize;
                *slot = src[idx];
            }
        }
    }
}

/// Copy a strided source into a contiguous destination by treating the
/// layout as a set of strided outer dims wrapping a contiguous inner run.
///
/// Precondition: strides are all positive and the innermost stride is 1
#[inline]
fn copy_inner_contiguous_run<E: Copy>(
    dst: &mut [E],
    src: &[E],
    offset: isize,
    shape: &[usize],
    strides: &[isize],
) {
    debug_assert!(!shape.is_empty());
    debug_assert_eq!(*strides.last().unwrap(), 1, "innermost stride must be 1");

    // We want the maximal trailing run that is contiguous in src.
    // Walk inward-out, a dim dim_idx extends the contiguous run if AND ONLY IF ("iff")
    // strides[dim_idx] == product of inner shapes seen so far.
    let mut expected_stride: isize = 1;
    let mut split = shape.len(); // first OUTER index (dims [split..] are inner)
    while split > 0 {
        let dim_idx = split - 1;
        if strides[dim_idx] == expected_stride {
            expected_stride = expected_stride
                .checked_mul(shape[dim_idx] as isize)
                .expect("contiguous run length overflows isize");
            split -= 1;
        } else {
            break;
        }
    }

    let outer_shape = &shape[..split];
    let outer_strides = &strides[..split];
    let inner_run_length: usize = shape[split..].iter().product();

    // Whole tensor is one contiguous run! We can bulk-copy the whole thing.
    if outer_shape.is_empty() {
        let src_index = offset as usize;
        dst[..inner_run_length].copy_from_slice(&src[src_index..src_index + inner_run_length]);
        return;
    }

    if inner_run_length == 0 || outer_shape.contains(&0) {
        return;
    }

    // Walk the outer index space in row-major order via an odometer:
    // each iteration ticks the rightmost counter, and so on overflow we
    // reset it and carry +1 into the dim to its left.
    // Row-major is what we want because dst is contiguous (consecutive outer-index
    // tuples land in consecutive inner_run_length slots, so we just bump
    // dst_position each step instead of recomputing it)
    // We use this instead of N nested for loops because the rank isn't
    // known at compile time.
    let mut counter = [0usize; COLLAPSE_MAX_RANK];
    let outer_dim_count = outer_shape.len();
    let mut dst_position = 0usize;

    loop {
        let mut src_start = offset;
        for dim_idx in 0..outer_dim_count {
            src_start += counter[dim_idx] as isize * outer_strides[dim_idx];
        }
        let src_index = src_start as usize;
        dst[dst_position..dst_position + inner_run_length]
            .copy_from_slice(&src[src_index..src_index + inner_run_length]);
        dst_position += inner_run_length;

        let mut dim_idx = outer_dim_count;
        loop {
            if dim_idx == 0 {
                return;
            }
            dim_idx -= 1;
            counter[dim_idx] += 1;
            if counter[dim_idx] < outer_shape[dim_idx] {
                break;
            }
            counter[dim_idx] = 0;
        }
    }
}

/// Minimum number of elements required to trigger parallel 2D tiled copy.
/// Avoids thread fork/steal overhead on ~1MB cache-resident tensors.
#[cfg(any(feature = "rayon", test))]
pub(crate) const COPY_2D_PARALLEL_THRESHOLD: usize = 1_048_576;

/// Tiled 2D copy from a strided source into a contiguous destination.
/// The loop nesting is chosen so the innermost read walks whichever
/// source stride is smaller, which keeps the hot loop in cache even
/// for transpose-like layouts.
#[inline]
fn copy_2d_tiled<E: Copy + Send + Sync>(
    dst: &mut [E],
    src: &[E],
    offset: isize,
    rows: usize,
    cols: usize,
    row_stride: isize,
    col_stride: isize,
) {
    const TILE: usize = 16;

    #[cfg(feature = "rayon")]
    if rows * cols >= COPY_2D_PARALLEL_THRESHOLD {
        use rayon::prelude::*;
        let total_tile_rows = rows.div_ceil(TILE);
        let num_threads = rayon::current_num_threads();
        let tile_rows_per_task = total_tile_rows.div_ceil(num_threads).max(1);
        let chunk_len = tile_rows_per_task * TILE * cols;

        dst.par_chunks_mut(chunk_len)
            .enumerate()
            .for_each(|(task_idx, dst_chunk)| {
                let row_start = task_idx * tile_rows_per_task * TILE;
                let chunk_rows = dst_chunk.len() / cols;
                if row_stride <= col_stride {
                    // row-inside-col: the inner loop walks `row_stride` (smaller).
                    for col_tile in (0..cols).step_by(TILE) {
                        let col_end = (col_tile + TILE).min(cols);
                        for r_tile in (0..chunk_rows).step_by(TILE) {
                            let r_end = (r_tile + TILE).min(chunk_rows);
                            for col in col_tile..col_end {
                                let col_base = offset + col as isize * col_stride;
                                for r in r_tile..r_end {
                                    let row = row_start + r;
                                    let idx = (col_base + row as isize * row_stride) as usize;
                                    // SAFETY: caller set `dst.len() == rows * cols`
                                    // and each `(r, col)` is visited once in this chunk.
                                    unsafe {
                                        *dst_chunk.get_unchecked_mut(r * cols + col) = src[idx];
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // col-inside-row: the inner loop walks `col_stride` (smaller).
                    for r_tile in (0..chunk_rows).step_by(TILE) {
                        let r_end = (r_tile + TILE).min(chunk_rows);
                        for col_tile in (0..cols).step_by(TILE) {
                            let col_end = (col_tile + TILE).min(cols);
                            for r in r_tile..r_end {
                                let row = row_start + r;
                                let row_base = offset
                                    + row as isize * row_stride
                                    + col_tile as isize * col_stride;
                                let dst_base = r * cols + col_tile;
                                for c in 0..(col_end - col_tile) {
                                    let idx = (row_base + c as isize * col_stride) as usize;
                                    // SAFETY: caller set `dst.len() == rows * cols`
                                    // and each `(r, col)` is visited once in this chunk.
                                    unsafe {
                                        *dst_chunk.get_unchecked_mut(dst_base + c) = src[idx];
                                    }
                                }
                            }
                        }
                    }
                }
            });
        return;
    }

    if row_stride <= col_stride {
        // row-inside-col: the inner loop walks `row_stride` (smaller).
        for col_tile in (0..cols).step_by(TILE) {
            let col_end = (col_tile + TILE).min(cols);
            for row_tile in (0..rows).step_by(TILE) {
                let row_end = (row_tile + TILE).min(rows);
                for col in col_tile..col_end {
                    let col_base = offset + col as isize * col_stride;
                    for row in row_tile..row_end {
                        let idx = (col_base + row as isize * row_stride) as usize;
                        // SAFETY: caller set `dst.len() == rows * cols`
                        // and each `(row, col)` is visited once.
                        unsafe {
                            *dst.get_unchecked_mut(row * cols + col) = src[idx];
                        }
                    }
                }
            }
        }
    } else {
        // col-inside-row: the inner loop walks `col_stride` (smaller).
        for row_tile in (0..rows).step_by(TILE) {
            let row_end = (row_tile + TILE).min(rows);
            for col_tile in (0..cols).step_by(TILE) {
                let col_end = (col_tile + TILE).min(cols);
                for row in row_tile..row_end {
                    let row_base =
                        offset + row as isize * row_stride + col_tile as isize * col_stride;
                    let dst_base = row * cols + col_tile;
                    for c in 0..(col_end - col_tile) {
                        let idx = (row_base + c as isize * col_stride) as usize;
                        // SAFETY: caller set `dst.len() == rows * cols`
                        // and each `(row, col)` is visited once.
                        unsafe {
                            *dst.get_unchecked_mut(dst_base + c) = src[idx];
                        }
                    }
                }
            }
        }
    }
}

/// Get the size in bytes for a dtype element.
///
/// Matches `burn_std::DType::size()` semantics: Bool(Native) and Bool(U8) are
/// 1 byte, Bool(U32) is 4 bytes. This makes buffer-size validation correct
/// regardless of which BoolStore variant the dtype carries.
///
/// # Panics
///
/// Panics if the dtype has a zero-byte element size. `burn_std::DType::size()`
/// returns 0 for sub-byte quantized dtypes (Q4F, Q4S, Q2F, Q2S, and most
/// `QuantStore::PackedNative` variants). burn-flex does not yet support these
/// packed quantization formats; passing them here would silently produce
/// empty allocations in `FlexTensor::empty`, truncated buffers in `into_data`,
/// and zero-byte memcpys in `repeat_dim`. The panic turns all three into a
/// loud, actionable failure at the dispatch boundary.
pub(crate) fn dtype_size(dtype: DType) -> usize {
    // Delegate to burn-std's canonical size to stay in sync.
    let size = dtype.size();
    assert!(
        size > 0,
        "burn-flex: dtype {:?} has zero-byte element size (sub-byte packed \
         quantization is not yet supported)",
        dtype
    );
    size
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn test_from_data_roundtrip() {
        let data = TensorData::from([1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
        let tensor = FlexTensor::from_data(data.clone());
        let result = tensor.into_data();
        assert_eq!(data.shape, result.shape);
        assert_eq!(data.dtype, result.dtype);
    }

    #[test]
    fn test_collapse_for_copy_squeezes_size1_and_merges_contig() {
        // Permuted ConvNeXt input: [1, 48, 244, 224].permute([0,2,3,1]).
        let shape = vec![1, 244, 224, 48];
        let strides = vec![2_623_488_isize, 224, 1, 54656];
        let collapsed = collapse_for_copy(&shape, &strides);
        let (s, st) = collapsed.as_slices();
        assert_eq!(s, &[54656, 48]);
        assert_eq!(st, &[1, 54656]);
    }

    #[test]
    fn test_collapse_for_copy_already_contiguous_3d() {
        let collapsed = collapse_for_copy(&[2, 3, 4], &[12, 4, 1]);
        let (s, st) = collapsed.as_slices();
        assert_eq!(s, &[24]);
        assert_eq!(st, &[1]);
    }

    #[test]
    fn test_collapse_for_copy_transpose_2d() {
        let collapsed = collapse_for_copy(&[5, 3], &[1, 5]);
        let (s, st) = collapsed.as_slices();
        assert_eq!(s, &[5, 3]);
        assert_eq!(st, &[1, 5]);
    }

    #[test]
    fn test_collapse_for_copy_all_size1() {
        let collapsed = collapse_for_copy(&[1, 1, 1], &[0, 0, 0]);
        let (s, st) = collapsed.as_slices();
        assert!(s.is_empty());
        assert!(st.is_empty());
    }

    /// Regression: an empty 1D view produced by `narrow` at a
    /// non-zero offset forces `copy_contiguous` to run (it can't
    /// early-return via the contiguous-at-offset-0 shortcut). The
    /// old `debug_assert_eq!(n, shape.product().max(1))` tripped
    /// for this shape because `.max(1)` produced 1 while the true
    /// numel is 0.
    #[test]
    fn test_to_contiguous_zero_sized_narrowed() {
        let t = FlexTensor::from_data(TensorData::new(
            (0..6).map(|i| i as f32).collect::<Vec<_>>(),
            vec![6],
        ));
        // narrow(dim, start=3, len=0): shape [0], start_offset 3.
        let empty_view = t.narrow(0, 3, 0);
        assert_eq!(empty_view.shape().to_vec(), vec![0]);
        assert_ne!(empty_view.layout().start_offset(), 0);

        let contig = empty_view.to_contiguous();
        assert_eq!(contig.shape().to_vec(), vec![0]);
        assert_eq!(contig.layout().start_offset(), 0);
        assert_eq!(contig.into_data().bytes.len(), 0);
    }

    #[test]
    fn test_to_contiguous_zero_sized_negative_stride() {
        let t = FlexTensor::from_data(TensorData::new(
            (0..6).map(|i| i as f32).collect::<Vec<_>>(),
            vec![6],
        ));
        let empty_neg = crate::ops::slice::slice(t, &[burn_std::Slice::new(3, Some(3), -1)]);
        assert_eq!(empty_neg.shape().to_vec(), vec![0]);
        let contig = empty_neg.to_contiguous();
        assert_eq!(contig.shape().to_vec(), vec![0]);
        assert_eq!(contig.into_data().bytes.len(), 0);
    }

    /// Regression for #4855: a prefix view (e.g. `narrow(dim, 0, n)`) has
    /// canonical contiguous strides and start_offset 0, but its underlying
    /// buffer is still the larger original. `to_contiguous` must materialize
    /// a right-sized copy so callers keying off `storage().len()` (like the
    /// SIMD `mask_fill_*` kernels reached from `triu`/`tril` in LU on tall
    /// matrices) don't walk past the logical shape.
    #[test]
    fn test_to_contiguous_prefix_view_shrinks_buffer() {
        let data: Vec<f32> = (0..40).map(|i| i as f32).collect();
        let t = FlexTensor::from_data(TensorData::new(data, vec![8, 5]));

        let prefix = t.narrow(0, 0, 5);
        assert_eq!(prefix.shape().to_vec(), vec![5, 5]);
        assert_eq!(prefix.layout().strides(), &[5, 1]);
        assert_eq!(prefix.layout().start_offset(), 0);
        assert!(prefix.is_contiguous());
        assert_eq!(prefix.storage::<f32>().len(), 40);

        let contig = prefix.to_contiguous();
        assert_eq!(contig.storage::<f32>().len(), 25);
        assert_eq!(contig.layout().num_elements(), 25);
        assert_eq!(
            contig.storage::<f32>(),
            &(0..5)
                .flat_map(|r| (0..5).map(move |c| (r * 5 + c) as f32))
                .collect::<Vec<_>>()[..]
        );
    }

    /// 4D permuted layout round-trips through the collapse + tiled
    /// copy path. Mirrors the ConvNeXt channels-last permute.
    #[test]
    fn test_to_contiguous_4d_permuted_matches_naive() {
        let dims = [1, 48, 4, 5];
        let n: usize = dims.iter().product();
        let data: Vec<f32> = (0..n).map(|i| i as f32).collect();
        let t = FlexTensor::from_data(TensorData::new(data.clone(), dims.to_vec()));
        let permuted = t.permute(&[0, 2, 3, 1]);
        assert!(!permuted.is_contiguous());

        let contig = permuted.to_contiguous();
        assert!(contig.is_contiguous());
        assert_eq!(contig.shape().to_vec(), vec![1, 4, 5, 48]);

        // Expected via manual strided walk of the source.
        let mut expected = Vec::with_capacity(n);
        for h in 0..4 {
            for w in 0..5 {
                for c in 0..48 {
                    let idx = c * 20 + h * 5 + w;
                    expected.push(data[idx]);
                }
            }
        }

        let result_data = contig.into_data();
        let values = result_data.as_slice::<f32>().unwrap();
        assert_eq!(values, expected.as_slice());
    }

    /// Regression: the ShuffleNet channel shuffle (reshape -> permute([0,2,1,3,4]) -> reshape)
    /// collapses to a 3D layout with stride-1 innermost.
    /// Before this fix that went into the StridedIter scalar walk in the final else in copy_contiguous
    /// Now, we use a new inner-contiguous branch that bulk-copies the trailing run
    #[test]
    fn test_to_contiguous_3d_inner_stride1_matches_naive() {
        let dims = [1, 2, 4, 3, 3]; // [N, G, C, H, W]
        let n: usize = dims.iter().product();
        let data: Vec<f32> = (0..n).map(|i| i as f32).collect();
        let t = FlexTensor::from_data(TensorData::new(data.clone(), dims.to_vec()));
        let permuted = t.permute(&[0, 2, 1, 3, 4]); // swap G and C from the original dims in the permute
        assert!(!permuted.is_contiguous());

        let contiguous_data = permuted.to_contiguous();
        assert!(contiguous_data.is_contiguous());
        assert_eq!(contiguous_data.shape().to_vec(), vec![1, 4, 2, 3, 3]);

        // Now we manually do a strided walk to be able to check that against a naive solution.
        // output[0, c, g, h, w] = input[0, g, c, h, w].
        let mut expected = Vec::with_capacity(n);
        for c in 0..4 {
            for g in 0..2 {
                for h in 0..3 {
                    for w in 0..3 {
                        let idx = g * 36 + c * 9 + h * 3 + w;
                        expected.push(data[idx]);
                    }
                }
            }
        }

        // Verify the naive solution matches (the manual strided walk).
        let result_data = contiguous_data.into_data();
        let values = result_data.as_slice::<f32>().unwrap();
        assert_eq!(values, expected.as_slice());
    }

    /// Exercise the `row_stride > col_stride` branch of the 2D tiled
    /// copy (the ConvNeXt case hits the other branch).
    #[test]
    fn test_to_contiguous_2d_row_stride_gt_col_stride() {
        // `slice(s![..;2, ..])` on a [6, 3] contiguous tensor gives a
        // [3, 3] view with strides [6, 1] that doesn't collapse, so
        // the 2D branch runs with row_stride > col_stride.
        let data: Vec<f32> = (0..18).map(|i| i as f32).collect();
        let t = FlexTensor::from_data(TensorData::new(data, vec![6, 3]));
        let stepped = crate::ops::slice::slice(
            t,
            &[
                burn_std::Slice::new(0, Some(6), 2),
                burn_std::Slice::new(0, None, 1),
            ],
        );
        // Verify the layout matches what the branch requires.
        assert_eq!(stepped.layout().shape().to_vec(), vec![3, 3]);
        assert_eq!(stepped.layout().strides(), &[6, 1]);
        assert!(!stepped.layout().is_contiguous());

        let contig = stepped.to_contiguous();
        assert!(contig.is_contiguous());
        assert_eq!(contig.shape().to_vec(), vec![3, 3]);

        let result_data = contig.into_data();
        let values = result_data.as_slice::<f32>().unwrap();
        // Expected: rows 0, 2, 4 of the original 6x3 tensor.
        let expected = vec![
            0.0f32, 1.0, 2.0, // row 0
            6.0, 7.0, 8.0, // row 2
            12.0, 13.0, 14.0, // row 4
        ];
        assert_eq!(values, expected.as_slice());
    }

    /// Exercise the `row_stride < col_stride` branch of the 2D tiled
    /// copy (e.g. transposed 2D layout).
    #[test]
    fn test_to_contiguous_2d_row_stride_lt_col_stride() {
        let data: Vec<f32> = (0..18).map(|i| i as f32).collect();
        let t = FlexTensor::from_data(TensorData::new(data, vec![3, 6]));
        let transposed = t.transpose(0, 1);
        assert_eq!(transposed.layout().strides(), &[1, 6]);
        assert!(!transposed.layout().is_contiguous());

        let contig = transposed.to_contiguous();
        assert!(contig.is_contiguous());
        assert_eq!(contig.shape().to_vec(), vec![6, 3]);

        let result_data = contig.into_data();
        let values = result_data.as_slice::<f32>().unwrap();
        let mut expected = Vec::with_capacity(18);
        for c in 0..6 {
            for r in 0..3 {
                expected.push((r * 6 + c) as f32);
            }
        }
        assert_eq!(values, expected.as_slice());
    }

    /// Parallel 2D tiled copy when `row_stride <= col_stride` (>= 1M elements).
    #[test]
    fn test_to_contiguous_2d_parallel_row_stride_le_col_stride() {
        let rows = 1024;
        let cols = 1024;
        let n = rows * cols;
        assert!(n >= COPY_2D_PARALLEL_THRESHOLD);

        let data: Vec<f32> = (0..n).map(|i| (i % 997) as f32).collect();
        let t = FlexTensor::from_data(TensorData::new(data.clone(), vec![rows, cols]));
        let transposed = t.transpose(0, 1);
        assert_eq!(transposed.layout().strides(), &[1, rows as isize]);
        assert!(!transposed.layout().is_contiguous());

        let contig = transposed.to_contiguous();
        assert!(contig.is_contiguous());
        assert_eq!(contig.shape().to_vec(), vec![cols, rows]);

        let result_data = contig.into_data();
        let values = result_data.as_slice::<f32>().unwrap();
        for r in 0..cols {
            for c in 0..rows {
                let expected = data[c * cols + r];
                assert_eq!(values[r * rows + c], expected);
            }
        }
    }

    /// Parallel 2D tiled copy when `row_stride > col_stride` (>= 1M elements).
    #[test]
    fn test_to_contiguous_2d_parallel_row_stride_gt_col_stride() {
        let rows = 1024;
        let cols = 1024;
        let n = rows * cols;
        assert!(n >= COPY_2D_PARALLEL_THRESHOLD);

        // [1024, 2048] tensor sliced to [1024, 1024] => row_stride = 2048, col_stride = 1
        let full_cols = 2048;
        let data: Vec<f32> = (0..rows * full_cols).map(|i| (i % 997) as f32).collect();
        let t = FlexTensor::from_data(TensorData::new(data.clone(), vec![rows, full_cols]));
        let sliced = crate::ops::slice::slice(
            t,
            &[
                burn_std::Slice::new(0, Some(rows as isize), 1),
                burn_std::Slice::new(0, Some(cols as isize), 1),
            ],
        );
        assert_eq!(sliced.layout().strides(), &[full_cols as isize, 1]);
        assert!(!sliced.layout().is_contiguous());

        let contig = sliced.to_contiguous();
        assert!(contig.is_contiguous());
        assert_eq!(contig.shape().to_vec(), vec![rows, cols]);

        let result_data = contig.into_data();
        let values = result_data.as_slice::<f32>().unwrap();
        for r in 0..rows {
            for c in 0..cols {
                let expected = data[r * full_cols + c];
                assert_eq!(values[r * cols + c], expected);
            }
        }
    }

    #[test]
    fn test_reshape() {
        let data = TensorData::new(vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0], vec![2, 3]);
        let tensor = FlexTensor::from_data(data);
        let reshaped = tensor.reshape(Shape::from(vec![3, 2]));
        assert_eq!(reshaped.shape().to_vec(), vec![3, 2]);
    }

    #[test]
    fn test_transpose() {
        let data = TensorData::new(vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0], vec![2, 3]);
        let tensor = FlexTensor::from_data(data);
        let transposed = tensor.transpose(0, 1);
        assert_eq!(transposed.shape().to_vec(), vec![3, 2]);
        assert!(!transposed.is_contiguous());
    }

    #[test]
    fn test_clone_is_cheap() {
        let data = TensorData::from([1.0f32, 2.0, 3.0, 4.0]);
        let tensor = FlexTensor::from_data(data);

        // Before clone, tensor is unique
        assert!(tensor.is_unique());

        // Clone shares data
        let cloned = tensor.clone();
        assert!(!tensor.is_unique());
        assert!(!cloned.is_unique());

        // Both point to same data
        assert!(core::ptr::eq(
            tensor.bytes().as_ptr(),
            cloned.bytes().as_ptr(),
        ));
    }

    #[test]
    fn test_cow_on_mutation() {
        let data = TensorData::from([1.0f32, 2.0, 3.0, 4.0]);
        let tensor = FlexTensor::from_data(data);
        let mut cloned = tensor.clone();

        // Both share data
        assert!(!tensor.is_unique());
        assert!(!cloned.is_unique());

        // Mutate cloned - triggers COW
        let storage: &mut [f32] = cloned.storage_mut();
        storage[0] = 99.0;

        // Now cloned has its own copy, tensor is unique again
        assert!(tensor.is_unique());
        assert!(cloned.is_unique());

        // Data is different
        assert_ne!(tensor.bytes().as_ptr(), cloned.bytes().as_ptr());
        assert_eq!(tensor.storage::<f32>()[0], 1.0);
        assert_eq!(cloned.storage::<f32>()[0], 99.0);
    }

    #[test]
    fn test_into_data_narrowed_at_offset_zero() {
        // [1, 2, 3, 4, 5, 6] shape [2, 3]
        let data = TensorData::new(vec![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0], vec![2, 3]);
        let tensor = FlexTensor::from_data(data);
        // narrow to first row: shape [1, 3], offset 0, contiguous
        let narrowed = tensor.narrow(0, 0, 1);
        assert!(narrowed.is_contiguous());
        assert_eq!(narrowed.layout().start_offset(), 0);

        let result = narrowed.into_data();
        assert_eq!(result.shape.to_vec(), vec![1, 3]);
        // Must have exactly 3 f32s = 12 bytes, not 24
        assert_eq!(result.bytes.len(), 3 * core::mem::size_of::<f32>());
        let values: Vec<f32> = result.try_into_vec().unwrap();
        assert_eq!(values, vec![1.0, 2.0, 3.0]);
    }

    #[test]
    fn test_reshape_preserves_offset_zero_copy() {
        let data: Vec<f32> = (0..16).map(|i| i as f32).collect();
        let tensor = FlexTensor::from_data(TensorData::new(data, vec![4, 4]));
        // Slice rows 1..3: shape [2, 4], contiguous, start_offset = 4
        let sliced = tensor.narrow(0, 1, 2);
        assert!(sliced.is_contiguous());
        assert_eq!(sliced.layout().start_offset(), 4);

        // Reshape [2, 4] -> [8] preserving non-zero offset
        let reshaped = sliced.reshape(Shape::from(vec![8]));
        assert!(reshaped.is_contiguous());
        assert_eq!(reshaped.layout().start_offset(), 4);
        assert_eq!(reshaped.shape().to_vec(), vec![8]);

        // Guarantees zero-copy pointer identity
        assert!(core::ptr::eq(
            sliced.bytes().as_ptr(),
            reshaped.bytes().as_ptr()
        ));

        let values: Vec<f32> = reshaped.into_data().try_into_vec().unwrap();
        assert_eq!(values, vec![4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]);
    }

    #[test]
    fn test_transpose_unit_dim_zero_copy() {
        // [6, 1] tensor transposed to [1, 6] has stride [1, 6].
        // Squeezing the size-1 dimension makes it contiguous!
        let data: Vec<f32> = (0..6).map(|i| i as f32).collect();
        let tensor = FlexTensor::from_data(TensorData::new(data, vec![6, 1]));
        let transposed = tensor.transpose(0, 1);
        assert_eq!(transposed.shape().to_vec(), vec![1, 6]);
        assert_eq!(transposed.layout().strides(), &[1, 1]);
        assert!(transposed.is_contiguous());

        // to_contiguous should be a no-op that reuses the existing storage
        let contig = transposed.to_contiguous();
        assert!(core::ptr::eq(
            transposed.bytes().as_ptr(),
            contig.bytes().as_ptr()
        ));
    }

    #[test]
    fn test_batched_transpose_parity() {
        // [2, 3, 4] transposed on trailing dims (1, 2) -> [2, 4, 3]
        let data: Vec<f32> = (0..24).map(|i| i as f32).collect();
        let tensor = FlexTensor::from_data(TensorData::new(data, vec![2, 3, 4]));
        let transposed = tensor.transpose(1, 2);
        assert_eq!(transposed.shape().to_vec(), vec![2, 4, 3]);
        assert!(!transposed.is_contiguous());

        let contig = transposed.to_contiguous();
        assert!(contig.is_contiguous());

        let values: Vec<f32> = contig.into_data().try_into_vec().unwrap();
        // Compute manual reference
        let mut expected = Vec::with_capacity(24);
        for b in 0..2 {
            for j in 0..4 {
                for i in 0..3 {
                    expected.push((b * 12 + i * 4 + j) as f32);
                }
            }
        }
        assert_eq!(values, expected);
    }

    #[test]
    fn test_negative_stride_flip_acceleration() {
        let data: Vec<f32> = (0..12).map(|i| i as f32).collect();
        let tensor = FlexTensor::from_data(TensorData::new(data, vec![3, 4]));
        // Negative step on axis 0: reverse rows
        let flipped = crate::ops::slice::slice(
            tensor,
            &[
                burn_std::Slice::new(0, None, -1),
                burn_std::Slice::new(0, None, 1),
            ],
        );
        assert_eq!(flipped.shape().to_vec(), vec![3, 4]);
        assert_eq!(flipped.layout().strides(), &[-4, 1]);
        assert!(!flipped.is_contiguous());

        let contig = flipped.to_contiguous();
        assert!(contig.is_contiguous());

        let values: Vec<f32> = contig.into_data().try_into_vec().unwrap();
        let expected = vec![
            8.0, 9.0, 10.0, 11.0, // row 2
            4.0, 5.0, 6.0, 7.0, // row 1
            0.0, 1.0, 2.0, 3.0, // row 0
        ];
        assert_eq!(values, expected);
    }
}