trustformers-core 0.1.1

Core traits and utilities for TrustformeRS
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
//! Tensor constructor functions.
//!
//! This module contains functions for creating new tensors with various
//! initialization patterns.

use super::{DType, Tensor};
use crate::errors::{Result, TrustformersError};
use scirs2_core::ndarray::{ArrayD, IxDyn}; // SciRS2 Policy compliant
use scirs2_core::random::{thread_rng, Distribution, Normal};
use scirs2_core::RngExt;
use scirs2_core::{Complex, Complex32, Complex64}; // SciRS2 Policy compliant (root level)

impl Tensor {
    /// Creates a new 1D tensor from a vector of data.
    ///
    /// # Arguments
    ///
    /// * `data` - A vector of f32 values
    ///
    /// # Returns
    ///
    /// A 1D tensor containing the provided data.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tensor = Tensor::new(vec![1.0, 2.0, 3.0, 4.0])?;
    /// assert_eq!(tensor.shape(), vec![4]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(data: Vec<f32>) -> Result<Self> {
        Ok(Tensor::F32(
            ArrayD::from_shape_vec(IxDyn(&[data.len()]), data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor from data with a specific shape.
    ///
    /// This is an alias for `from_vec` for backward compatibility with tests.
    ///
    /// # Arguments
    ///
    /// * `data` - A vector of f32 values
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor with the specified shape containing the provided data.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tensor = Tensor::with_shape(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2])?;
    /// assert_eq!(tensor.shape(), vec![2, 2]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_shape(data: Vec<f32>, shape: Vec<usize>) -> Result<Self> {
        Self::from_vec(data, &shape)
    }

    /// Creates a tensor from i64 data with a specific shape.
    ///
    /// # Arguments
    ///
    /// * `data` - A vector of i64 values
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor with the specified shape containing the provided i64 data.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tensor = Tensor::from_vec_i64(vec![1, 2, 3, 4], &[2, 2])?;
    /// assert_eq!(tensor.shape(), vec![2, 2]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_vec_i64(data: Vec<i64>, shape: &[usize]) -> Result<Self> {
        if data.len() != shape.iter().product::<usize>() {
            return Err(TrustformersError::shape_error(
                "Data length doesn't match shape".into(),
            ));
        }
        Ok(Tensor::I64(
            ArrayD::from_shape_vec(IxDyn(shape), data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor filled with zeros.
    ///
    /// # Arguments
    ///
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor of the specified shape filled with zeros.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tensor = Tensor::zeros(&[2, 3])?;
    /// assert_eq!(tensor.shape(), vec![2, 3]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn zeros(shape: &[usize]) -> Result<Self> {
        Ok(Tensor::F32(ArrayD::zeros(IxDyn(shape))))
    }

    /// Creates a tensor filled with ones.
    ///
    /// # Arguments
    ///
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor of the specified shape filled with ones.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tensor = Tensor::ones(&[2, 3])?;
    /// assert_eq!(tensor.shape(), vec![2, 3]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn ones(shape: &[usize]) -> Result<Self> {
        Ok(Tensor::F32(ArrayD::ones(IxDyn(shape))))
    }

    /// Creates a tensor filled with random values from a normal distribution.
    ///
    /// # Arguments
    ///
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor filled with random values from N(0, 1).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tensor = Tensor::randn(&[2, 3])?;
    /// assert_eq!(tensor.shape(), vec![2, 3]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn randn(shape: &[usize]) -> Result<Self> {
        let normal =
            Normal::new(0.0, 1.0).expect("Normal(0.0, 1.0) distribution parameters are valid");
        let mut rng = thread_rng();
        let size = shape.iter().product();
        let data: Vec<f32> = (0..size).map(|_| normal.sample(&mut rng)).collect();
        Ok(Tensor::F32(
            ArrayD::from_shape_vec(IxDyn(shape), data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor filled with zeros with the same shape as the input tensor.
    ///
    /// # Arguments
    ///
    /// * `tensor` - The tensor to match shape from
    ///
    /// # Returns
    ///
    /// A tensor of the same shape filled with zeros.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let input = Tensor::randn(&[2, 3])?;
    /// let zeros = Tensor::zeros_like(&input)?;
    /// assert_eq!(zeros.shape(), vec![2, 3]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn zeros_like(tensor: &Tensor) -> Result<Self> {
        Self::zeros(&tensor.shape())
    }

    /// Creates a tensor filled with ones with the same shape as the input tensor.
    ///
    /// # Arguments
    ///
    /// * `tensor` - The tensor to match shape from
    ///
    /// # Returns
    ///
    /// A tensor of the same shape filled with ones.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let input = Tensor::randn(&[2, 3])?;
    /// let ones = Tensor::ones_like(&input)?;
    /// assert_eq!(ones.shape(), vec![2, 3]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn ones_like(tensor: &Tensor) -> Result<Self> {
        Self::ones(&tensor.shape())
    }

    /// Creates a tensor from data with specified shape.
    ///
    /// # Arguments
    ///
    /// * `data` - A vector of f32 values
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor containing the provided data reshaped to the specified shape.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
    /// let tensor = Tensor::from_data(data, &[2, 3])?;
    /// assert_eq!(tensor.shape(), vec![2, 3]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_data(data: Vec<f32>, shape: &[usize]) -> Result<Self> {
        let expected_size: usize = shape.iter().product();
        if data.len() != expected_size {
            return Err(TrustformersError::shape_error(format!(
                "Data length {} does not match expected size {} for shape {:?}",
                data.len(),
                expected_size,
                shape
            )));
        }
        Ok(Tensor::F32(
            ArrayD::from_shape_vec(IxDyn(shape), data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor from a slice with specified shape.
    ///
    /// # Arguments
    ///
    /// * `data` - A slice of f32 values
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor containing the provided data reshaped to the specified shape.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
    /// let tensor = Tensor::from_slice(&data, &[2, 3])?;
    /// assert_eq!(tensor.shape(), vec![2, 3]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_slice(data: &[f32], shape: &[usize]) -> Result<Self> {
        let expected_size: usize = shape.iter().product();
        if data.len() != expected_size {
            return Err(TrustformersError::shape_error(format!(
                "Data length {} does not match expected size {} for shape {:?}",
                data.len(),
                expected_size,
                shape
            )));
        }
        Ok(Tensor::F32(
            ArrayD::from_shape_vec(IxDyn(shape), data.to_vec())
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor filled with random values with the same shape as the input tensor.
    ///
    /// # Arguments
    ///
    /// * `tensor` - The tensor to match shape from
    ///
    /// # Returns
    ///
    /// A tensor of the same shape filled with random values from N(0, 1).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use trustformers_core::tensor::Tensor;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let input = Tensor::zeros(&[2, 3])?;
    /// let random = Tensor::randn_like(&input)?;
    /// assert_eq!(random.shape(), vec![2, 3]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn randn_like(tensor: &Tensor) -> Result<Self> {
        Self::randn(&tensor.shape())
    }

    /// Creates a tensor filled with zeros (f64 precision).
    pub fn zeros_f64(shape: &[usize]) -> Result<Self> {
        Ok(Tensor::F64(ArrayD::zeros(IxDyn(shape))))
    }

    /// Creates a tensor filled with zeros (i64 integers).
    pub fn zeros_i64(shape: &[usize]) -> Result<Self> {
        Ok(Tensor::I64(ArrayD::zeros(IxDyn(shape))))
    }

    /// Creates a tensor filled with zeros (complex f32).
    pub fn zeros_c32(shape: &[usize]) -> Result<Self> {
        Ok(Tensor::C32(ArrayD::zeros(IxDyn(shape))))
    }

    /// Creates a tensor filled with zeros (complex f64).
    pub fn zeros_c64(shape: &[usize]) -> Result<Self> {
        Ok(Tensor::C64(ArrayD::zeros(IxDyn(shape))))
    }

    /// Creates a tensor filled with zeros (f16 precision).
    pub fn zeros_f16(shape: &[usize]) -> Result<Self> {
        let total_size: usize = shape.iter().product();
        let data = vec![half::f16::ZERO; total_size];
        Ok(Tensor::F16(ArrayD::from_shape_vec(IxDyn(shape), data)?))
    }

    /// Creates a tensor filled with zeros (bf16 precision).
    pub fn zeros_bf16(shape: &[usize]) -> Result<Self> {
        let total_size: usize = shape.iter().product();
        let data = vec![half::bf16::ZERO; total_size];
        Ok(Tensor::BF16(ArrayD::from_shape_vec(IxDyn(shape), data)?))
    }

    /// Creates a tensor filled with zeros (complex f16).
    pub fn zeros_cf16(shape: &[usize]) -> Result<Self> {
        let total_size: usize = shape.iter().product();
        let data = vec![Complex::new(half::f16::ZERO, half::f16::ZERO); total_size];
        Ok(Tensor::CF16(ArrayD::from_shape_vec(IxDyn(shape), data)?))
    }

    /// Creates a tensor filled with zeros (complex bf16).
    pub fn zeros_cbf16(shape: &[usize]) -> Result<Self> {
        let total_size: usize = shape.iter().product();
        let data = vec![Complex::new(half::bf16::ZERO, half::bf16::ZERO); total_size];
        Ok(Tensor::CBF16(ArrayD::from_shape_vec(IxDyn(shape), data)?))
    }

    /// Creates a complex tensor from real and imaginary parts.
    ///
    /// # Arguments
    ///
    /// * `real` - Real part values
    /// * `imag` - Imaginary part values
    /// * `shape` - The desired shape
    ///
    /// # Returns
    ///
    /// A complex tensor with the specified real and imaginary parts.
    pub fn complex(real: Vec<f32>, imag: Vec<f32>, shape: &[usize]) -> Result<Self> {
        if real.len() != imag.len() {
            return Err(TrustformersError::shape_error(
                "Real and imaginary parts must have the same length".into(),
            ));
        }

        let complex_data: Vec<Complex32> =
            real.into_iter().zip(imag).map(|(r, i)| Complex32::new(r, i)).collect();

        Ok(Tensor::C32(
            ArrayD::from_shape_vec(IxDyn(shape), complex_data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a complex tensor from real and imaginary parts (f64 precision).
    pub fn complex_f64(real: Vec<f64>, imag: Vec<f64>, shape: &[usize]) -> Result<Self> {
        if real.len() != imag.len() {
            return Err(TrustformersError::shape_error(
                "Real and imaginary parts must have the same length".into(),
            ));
        }

        let complex_data: Vec<Complex64> =
            real.into_iter().zip(imag).map(|(r, i)| Complex64::new(r, i)).collect();

        Ok(Tensor::C64(
            ArrayD::from_shape_vec(IxDyn(shape), complex_data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor from a vector with explicit shape.
    ///
    /// # Arguments
    ///
    /// * `data` - The data vector
    /// * `shape` - The desired shape
    ///
    /// # Returns
    ///
    /// A tensor with the specified data and shape.
    pub fn from_vec(data: Vec<f32>, shape: &[usize]) -> Result<Self> {
        if data.len() != shape.iter().product::<usize>() {
            return Err(TrustformersError::shape_error(
                "Data length doesn't match shape".into(),
            ));
        }
        Ok(Tensor::F32(
            ArrayD::from_shape_vec(IxDyn(shape), data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor from a Vec with explicit dtype.
    /// TEMPORARY: Uses ndarray. Will be replaced with SciRS2-Core.
    ///
    /// # Arguments
    ///
    /// * `data` - The data as a `Vec<f64>`
    /// * `shape` - The desired shape
    /// * `dtype` - The desired data type
    pub fn from_vec_with_dtype(data: Vec<f64>, shape: &[usize], dtype: DType) -> Result<Self> {
        if data.len() != shape.iter().product::<usize>() {
            return Err(TrustformersError::shape_error(
                "Data length doesn't match shape".into(),
            ));
        }

        match dtype {
            DType::F32 => {
                let data_f32: Vec<f32> = data.iter().map(|&x| x as f32).collect();
                Ok(Tensor::F32(
                    ArrayD::from_shape_vec(IxDyn(shape), data_f32)
                        .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
                ))
            },
            DType::F64 => Ok(Tensor::F64(
                ArrayD::from_shape_vec(IxDyn(shape), data)
                    .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
            )),
            DType::I64 => {
                let data_i64: Vec<i64> = data.iter().map(|&x| x as i64).collect();
                Ok(Tensor::I64(
                    ArrayD::from_shape_vec(IxDyn(shape), data_i64)
                        .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
                ))
            },
            _ => Err(TrustformersError::tensor_op_error(
                &format!("Unsupported dtype {:?} for from_vec_with_dtype", dtype),
                "from_vec_with_dtype",
            )),
        }
    }

    /// Creates a tensor filled with a constant value.
    ///
    /// # Arguments
    ///
    /// * `value` - The constant value to fill with
    /// * `shape` - The desired shape
    ///
    /// # Returns
    ///
    /// A tensor filled with the constant value.
    pub fn full(value: f32, shape: Vec<usize>) -> Result<Self> {
        let arr = ArrayD::from_elem(IxDyn(&shape), value);
        Ok(Tensor::F32(arr))
    }

    /// Creates a tensor filled with a constant value with specified dtype.
    ///
    /// # Arguments
    ///
    /// * `shape` - Shape of the tensor as a slice
    /// * `value` - The fill value (will be cast to target dtype)
    /// * `dtype` - Target data type
    ///
    /// # Returns
    ///
    /// A tensor filled with the constant value.
    ///
    /// # Note
    ///
    /// TEMPORARY: Uses ndarray - will be replaced with SciRS2-Core in future migration
    pub fn full_with_dtype(shape: &[usize], value: f64, dtype: DType) -> Result<Self> {
        match dtype {
            DType::F32 => {
                let arr = ArrayD::from_elem(IxDyn(shape), value as f32);
                Ok(Tensor::F32(arr))
            },
            DType::F64 => {
                let arr = ArrayD::from_elem(IxDyn(shape), value);
                Ok(Tensor::F64(arr))
            },
            DType::I64 => {
                let arr = ArrayD::from_elem(IxDyn(shape), value as i64);
                Ok(Tensor::I64(arr))
            },
            _ => Err(TrustformersError::tensor_op_error(
                &format!("Unsupported dtype {:?} for full_with_dtype", dtype),
                "full_with_dtype",
            )),
        }
    }

    /// Creates a scalar tensor.
    ///
    /// # Arguments
    ///
    /// * `value` - The scalar value
    ///
    /// # Returns
    ///
    /// A 0-dimensional tensor containing the scalar value.
    pub fn scalar(value: f32) -> Result<Self> {
        Ok(Tensor::F32(ArrayD::from_elem(IxDyn(&[]), value)))
    }

    /// Creates an identity matrix tensor.
    ///
    /// # Arguments
    ///
    /// * `n` - The size of the identity matrix (n x n)
    ///
    /// # Returns
    ///
    /// An n x n identity matrix tensor.
    pub fn eye_f32(n: usize) -> Result<Self> {
        let mut data = vec![0.0f32; n * n];
        for i in 0..n {
            data[i * n + i] = 1.0;
        }
        Ok(Tensor::F32(
            ArrayD::from_shape_vec(IxDyn(&[n, n]), data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor filled with ones (f16 precision).
    pub fn ones_f16(shape: &[usize]) -> Result<Self> {
        let total_size: usize = shape.iter().product();
        let data = vec![half::f16::ONE; total_size];
        Ok(Tensor::F16(ArrayD::from_shape_vec(IxDyn(shape), data)?))
    }

    /// Creates a tensor filled with ones (bf16 precision).
    pub fn ones_bf16(shape: &[usize]) -> Result<Self> {
        let total_size: usize = shape.iter().product();
        let data = vec![half::bf16::ONE; total_size];
        Ok(Tensor::BF16(ArrayD::from_shape_vec(IxDyn(shape), data)?))
    }

    /// Creates a tensor filled with random values from a normal distribution (f16 precision).
    pub fn randn_f16(shape: &[usize]) -> Result<Self> {
        let normal =
            Normal::new(0.0, 1.0).expect("Normal(0.0, 1.0) distribution parameters are valid");
        let mut rng = thread_rng();
        let size = shape.iter().product();
        let data: Vec<half::f16> =
            (0..size).map(|_| half::f16::from_f32(normal.sample(&mut rng))).collect();
        Ok(Tensor::F16(
            ArrayD::from_shape_vec(IxDyn(shape), data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor filled with random values from a normal distribution (bf16 precision).
    pub fn randn_bf16(shape: &[usize]) -> Result<Self> {
        let normal =
            Normal::new(0.0, 1.0).expect("Normal(0.0, 1.0) distribution parameters are valid");
        let mut rng = thread_rng();
        let size = shape.iter().product();
        let data: Vec<half::bf16> =
            (0..size).map(|_| half::bf16::from_f32(normal.sample(&mut rng))).collect();
        Ok(Tensor::BF16(
            ArrayD::from_shape_vec(IxDyn(shape), data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a complex tensor from real and imaginary parts (f16 precision).
    pub fn complex_f16(real: Vec<f32>, imag: Vec<f32>, shape: &[usize]) -> Result<Self> {
        if real.len() != imag.len() {
            return Err(TrustformersError::shape_error(
                "Real and imaginary parts must have the same length".into(),
            ));
        }

        let complex_data: Vec<Complex<half::f16>> = real
            .into_iter()
            .zip(imag)
            .map(|(r, i)| Complex::new(half::f16::from_f32(r), half::f16::from_f32(i)))
            .collect();

        Ok(Tensor::CF16(
            ArrayD::from_shape_vec(IxDyn(shape), complex_data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a complex tensor from real and imaginary parts (bf16 precision).
    pub fn complex_bf16(real: Vec<f32>, imag: Vec<f32>, shape: &[usize]) -> Result<Self> {
        if real.len() != imag.len() {
            return Err(TrustformersError::shape_error(
                "Real and imaginary parts must have the same length".into(),
            ));
        }

        let complex_data: Vec<Complex<half::bf16>> = real
            .into_iter()
            .zip(imag)
            .map(|(r, i)| Complex::new(half::bf16::from_f32(r), half::bf16::from_f32(i)))
            .collect();

        Ok(Tensor::CBF16(
            ArrayD::from_shape_vec(IxDyn(shape), complex_data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor with specified data type.
    ///
    /// # Arguments
    ///
    /// * `dtype` - The desired data type
    /// * `shape` - The desired shape
    ///
    /// # Returns
    ///
    /// A zero tensor with the specified data type and shape.
    pub fn zeros_dtype(dtype: DType, shape: &[usize]) -> Result<Self> {
        match dtype {
            DType::F32 => Self::zeros(shape),
            DType::F64 => Self::zeros_f64(shape),
            DType::F16 => Self::zeros_f16(shape),
            DType::BF16 => Self::zeros_bf16(shape),
            DType::I64 => Self::zeros_i64(shape),
            DType::C32 => Self::zeros_c32(shape),
            DType::C64 => Self::zeros_c64(shape),
            DType::CF16 => Self::zeros_cf16(shape),
            DType::CBF16 => Self::zeros_cbf16(shape),
            _ => Err(TrustformersError::tensor_op_error(
                &format!("Unsupported data type for zeros: {:?}", dtype),
                "Tensor::zeros_dtype",
            )),
        }
    }

    /// Creates a tensor filled with ones with explicit dtype.
    ///
    /// # Arguments
    ///
    /// * `dtype` - The data type for the tensor
    /// * `shape` - The shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor filled with ones of the specified data type.
    pub fn ones_dtype(dtype: DType, shape: &[usize]) -> Result<Self> {
        match dtype {
            DType::F32 => Self::ones(shape),
            DType::F64 => Ok(Tensor::F64(ArrayD::ones(IxDyn(shape)))),
            DType::F16 => Self::ones_f16(shape),
            DType::BF16 => Self::ones_bf16(shape),
            DType::I64 => Ok(Tensor::I64(ArrayD::ones(IxDyn(shape)))),
            _ => Err(TrustformersError::tensor_op_error(
                &format!("Unsupported data type for ones: {:?}", dtype),
                "Tensor::ones_dtype",
            )),
        }
    }

    /// Creates a tensor filled with a scalar value (alternative signature).
    ///
    /// # Arguments
    ///
    /// * `shape` - The shape of the tensor
    /// * `value` - The value to fill the tensor with
    ///
    /// # Returns
    ///
    /// A tensor filled with the specified value.
    pub fn full_with_shape(shape: &[usize], value: f32) -> Result<Self> {
        let array = ArrayD::from_elem(IxDyn(shape), value);
        Ok(Tensor::F32(array))
    }

    /// Creates a tensor from a slice of f64 values with specified shape.
    ///
    /// # Arguments
    ///
    /// * `data` - A slice of f64 values
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor containing the provided data reshaped to the specified shape.
    pub fn from_slice_f64(data: &[f64], shape: &[usize]) -> Result<Self> {
        let expected_size: usize = shape.iter().product();
        if data.len() != expected_size {
            return Err(TrustformersError::shape_error(format!(
                "Data length {} does not match expected size {} for shape {:?}",
                data.len(),
                expected_size,
                shape
            )));
        }
        Ok(Tensor::F64(
            ArrayD::from_shape_vec(IxDyn(shape), data.to_vec())
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor from a slice of i64 values with specified shape.
    ///
    /// # Arguments
    ///
    /// * `data` - A slice of i64 values
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor containing the provided data reshaped to the specified shape.
    pub fn from_slice_i64(data: &[i64], shape: &[usize]) -> Result<Self> {
        let expected_size: usize = shape.iter().product();
        if data.len() != expected_size {
            return Err(TrustformersError::shape_error(format!(
                "Data length {} does not match expected size {} for shape {:?}",
                data.len(),
                expected_size,
                shape
            )));
        }
        Ok(Tensor::I64(
            ArrayD::from_shape_vec(IxDyn(shape), data.to_vec())
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor from a slice of i32 values with specified shape.
    ///
    /// # Arguments
    ///
    /// * `data` - A slice of i32 values
    /// * `shape` - The desired shape of the tensor
    ///
    /// # Returns
    ///
    /// A tensor containing the provided data reshaped to the specified shape.
    pub fn from_slice_i32(data: &[i32], shape: &[usize]) -> Result<Self> {
        let expected_size: usize = shape.iter().product();
        if data.len() != expected_size {
            return Err(TrustformersError::shape_error(format!(
                "Data length {} does not match expected size {} for shape {:?}",
                data.len(),
                expected_size,
                shape
            )));
        }
        // Create i64 tensor since there's no I32 variant in the Tensor enum
        let i64_data: Vec<i64> = data.iter().map(|&x| x as i64).collect();
        Ok(Tensor::I64(
            ArrayD::from_shape_vec(IxDyn(shape), i64_data)
                .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
        ))
    }

    /// Creates a tensor from a scalar value.
    ///
    /// # Arguments
    ///
    /// * `value` - The scalar value
    /// * `dtype` - The data type for the tensor
    ///
    /// # Returns
    ///
    /// A 0-dimensional (scalar) tensor.
    pub fn from_scalar(value: f32, dtype: DType) -> Result<Self> {
        match dtype {
            DType::F32 => Ok(Tensor::F32(ArrayD::from_elem(IxDyn(&[]), value))),
            DType::F64 => Ok(Tensor::F64(ArrayD::from_elem(IxDyn(&[]), value as f64))),
            DType::I64 => Ok(Tensor::I64(ArrayD::from_elem(IxDyn(&[]), value as i64))),
            _ => Err(TrustformersError::tensor_op_error(
                &format!("Unsupported dtype {:?} for from_scalar", dtype),
                "from_scalar",
            )),
        }
    }

    /// Creates a tensor with a range of values.
    ///
    /// # Arguments
    ///
    /// * `start` - Start value (inclusive)
    /// * `end` - End value (exclusive)
    /// * `dtype` - The data type for the tensor
    ///
    /// # Returns
    ///
    /// A 1D tensor with values from start to end-1.
    pub fn range(start: i64, end: i64, dtype: DType) -> Result<Self> {
        if start >= end {
            return Err(TrustformersError::tensor_op_error(
                "Start must be less than end for range",
                "range",
            ));
        }
        match dtype {
            DType::I64 => {
                let data: Vec<i64> = (start..end).collect();
                Ok(Tensor::I64(
                    ArrayD::from_shape_vec(IxDyn(&[data.len()]), data)
                        .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
                ))
            },
            DType::F32 => {
                let data: Vec<f32> = (start..end).map(|x| x as f32).collect();
                Ok(Tensor::F32(
                    ArrayD::from_shape_vec(IxDyn(&[data.len()]), data)
                        .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
                ))
            },
            DType::F64 => {
                let data: Vec<f64> = (start..end).map(|x| x as f64).collect();
                Ok(Tensor::F64(
                    ArrayD::from_shape_vec(IxDyn(&[data.len()]), data)
                        .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
                ))
            },
            _ => Err(TrustformersError::tensor_op_error(
                &format!("Unsupported dtype {:?} for range", dtype),
                "range",
            )),
        }
    }

    /// Creates a tensor filled with random integers in the range [low, high).
    ///
    /// # Arguments
    ///
    /// * `low` - Lower bound (inclusive)
    /// * `high` - Upper bound (exclusive)
    /// * `shape` - Shape of the tensor
    /// * `dtype` - Data type of the tensor
    ///
    /// # Returns
    ///
    /// A tensor filled with random integers.
    pub fn randint(low: i64, high: i64, shape: &[usize], dtype: DType) -> Result<Self> {
        use scirs2_core::random::rng; // SciRS2 Policy compliant (updated API)

        if low >= high {
            return Err(TrustformersError::tensor_op_error(
                "low must be less than high for randint",
                "randint",
            ));
        }

        let mut rng = rng(); // Use updated scirs2-core API
        let size: usize = shape.iter().product();

        match dtype {
            DType::I64 => {
                let data: Vec<i64> = (0..size).map(|_| rng.random_range(low..high)).collect(); // Updated API
                Ok(Tensor::I64(
                    ArrayD::from_shape_vec(IxDyn(shape), data)
                        .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
                ))
            },
            DType::F32 => {
                let data: Vec<f32> =
                    (0..size).map(|_| rng.random_range(low..high) as f32).collect(); // Updated API
                Ok(Tensor::F32(
                    ArrayD::from_shape_vec(IxDyn(shape), data)
                        .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
                ))
            },
            DType::F64 => {
                let data: Vec<f64> =
                    (0..size).map(|_| rng.random_range(low..high) as f64).collect(); // Updated API
                Ok(Tensor::F64(
                    ArrayD::from_shape_vec(IxDyn(shape), data)
                        .map_err(|e| TrustformersError::shape_error(e.to_string()))?,
                ))
            },
            _ => Err(TrustformersError::tensor_op_error(
                &format!("Unsupported dtype {:?} for randint", dtype),
                "randint",
            )),
        }
    }
}

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

    #[test]
    fn test_new_1d_tensor() -> Result<()> {
        let t = Tensor::new(vec![1.0, 2.0, 3.0])?;
        assert_eq!(t.shape(), vec![3]);
        assert_eq!(t.dtype(), DType::F32);
        Ok(())
    }

    #[test]
    fn test_new_empty_tensor() -> Result<()> {
        let t = Tensor::new(vec![])?;
        assert_eq!(t.shape(), vec![0]);
        Ok(())
    }

    #[test]
    fn test_with_shape_2d() -> Result<()> {
        let t = Tensor::with_shape(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2])?;
        assert_eq!(t.shape(), vec![2, 2]);
        Ok(())
    }

    #[test]
    fn test_with_shape_mismatch() {
        let result = Tensor::with_shape(vec![1.0, 2.0, 3.0], vec![2, 2]);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_vec_i64() -> Result<()> {
        let t = Tensor::from_vec_i64(vec![10, 20, 30, 40], &[2, 2])?;
        assert_eq!(t.shape(), vec![2, 2]);
        assert_eq!(t.dtype(), DType::I64);
        Ok(())
    }

    #[test]
    fn test_from_vec_i64_shape_mismatch() {
        let result = Tensor::from_vec_i64(vec![1, 2, 3], &[2, 2]);
        assert!(result.is_err());
    }

    #[test]
    fn test_zeros() -> Result<()> {
        let t = Tensor::zeros(&[3, 4])?;
        assert_eq!(t.shape(), vec![3, 4]);
        let data = t.data()?;
        for val in &data {
            assert!((val - 0.0).abs() < 1e-7);
        }
        Ok(())
    }

    #[test]
    fn test_ones() -> Result<()> {
        let t = Tensor::ones(&[2, 3])?;
        assert_eq!(t.shape(), vec![2, 3]);
        let data = t.data()?;
        for val in &data {
            assert!((val - 1.0).abs() < 1e-7);
        }
        Ok(())
    }

    #[test]
    fn test_zeros_like() -> Result<()> {
        let orig = Tensor::ones(&[3, 5])?;
        let z = Tensor::zeros_like(&orig)?;
        assert_eq!(z.shape(), vec![3, 5]);
        let data = z.data()?;
        for val in &data {
            assert!((val - 0.0).abs() < 1e-7);
        }
        Ok(())
    }

    #[test]
    fn test_ones_like() -> Result<()> {
        let orig = Tensor::zeros(&[4, 2])?;
        let o = Tensor::ones_like(&orig)?;
        assert_eq!(o.shape(), vec![4, 2]);
        let data = o.data()?;
        for val in &data {
            assert!((val - 1.0).abs() < 1e-7);
        }
        Ok(())
    }

    #[test]
    fn test_from_data() -> Result<()> {
        let t = Tensor::from_data(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3])?;
        assert_eq!(t.shape(), vec![2, 3]);
        Ok(())
    }

    #[test]
    fn test_from_data_shape_mismatch() {
        let result = Tensor::from_data(vec![1.0, 2.0], &[3, 3]);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_slice() -> Result<()> {
        let data = [1.0, 2.0, 3.0, 4.0];
        let t = Tensor::from_slice(&data, &[4])?;
        assert_eq!(t.shape(), vec![4]);
        Ok(())
    }

    #[test]
    fn test_from_slice_shape_mismatch() {
        let data = [1.0, 2.0];
        let result = Tensor::from_slice(&data, &[5]);
        assert!(result.is_err());
    }

    #[test]
    fn test_randn() -> Result<()> {
        let t = Tensor::randn(&[10, 10])?;
        assert_eq!(t.shape(), vec![10, 10]);
        assert_eq!(t.dtype(), DType::F32);
        Ok(())
    }

    #[test]
    fn test_randn_like() -> Result<()> {
        let orig = Tensor::zeros(&[5, 3])?;
        let r = Tensor::randn_like(&orig)?;
        assert_eq!(r.shape(), vec![5, 3]);
        Ok(())
    }

    #[test]
    fn test_zeros_f64() -> Result<()> {
        let t = Tensor::zeros_f64(&[2, 2])?;
        assert_eq!(t.shape(), vec![2, 2]);
        assert_eq!(t.dtype(), DType::F64);
        Ok(())
    }

    #[test]
    fn test_zeros_i64() -> Result<()> {
        let t = Tensor::zeros_i64(&[3])?;
        assert_eq!(t.shape(), vec![3]);
        assert_eq!(t.dtype(), DType::I64);
        Ok(())
    }

    #[test]
    fn test_zeros_c32() -> Result<()> {
        let t = Tensor::zeros_c32(&[2, 3])?;
        assert_eq!(t.shape(), vec![2, 3]);
        assert_eq!(t.dtype(), DType::C32);
        Ok(())
    }

    #[test]
    fn test_zeros_c64() -> Result<()> {
        let t = Tensor::zeros_c64(&[4])?;
        assert_eq!(t.shape(), vec![4]);
        assert_eq!(t.dtype(), DType::C64);
        Ok(())
    }

    #[test]
    fn test_zeros_f16() -> Result<()> {
        let t = Tensor::zeros_f16(&[2, 2])?;
        assert_eq!(t.shape(), vec![2, 2]);
        assert_eq!(t.dtype(), DType::F16);
        Ok(())
    }

    #[test]
    fn test_zeros_bf16() -> Result<()> {
        let t = Tensor::zeros_bf16(&[3, 3])?;
        assert_eq!(t.shape(), vec![3, 3]);
        assert_eq!(t.dtype(), DType::BF16);
        Ok(())
    }

    #[test]
    fn test_complex_c32() -> Result<()> {
        let t = Tensor::complex(vec![1.0, 2.0], vec![3.0, 4.0], &[2])?;
        assert_eq!(t.shape(), vec![2]);
        assert_eq!(t.dtype(), DType::C32);
        Ok(())
    }

    #[test]
    fn test_complex_c32_length_mismatch() {
        let result = Tensor::complex(vec![1.0], vec![2.0, 3.0], &[2]);
        assert!(result.is_err());
    }

    #[test]
    fn test_complex_f64() -> Result<()> {
        let t = Tensor::complex_f64(vec![1.0, 2.0], vec![3.0, 4.0], &[2])?;
        assert_eq!(t.shape(), vec![2]);
        assert_eq!(t.dtype(), DType::C64);
        Ok(())
    }

    #[test]
    fn test_full() -> Result<()> {
        let t = Tensor::full(std::f32::consts::PI, vec![2, 3])?;
        assert_eq!(t.shape(), vec![2, 3]);
        let data = t.data()?;
        for val in &data {
            assert!((val - std::f32::consts::PI).abs() < 1e-5);
        }
        Ok(())
    }

    #[test]
    fn test_full_with_dtype_f32() -> Result<()> {
        let t = Tensor::full_with_dtype(&[3, 2], 5.0, DType::F32)?;
        assert_eq!(t.shape(), vec![3, 2]);
        assert_eq!(t.dtype(), DType::F32);
        Ok(())
    }

    #[test]
    fn test_full_with_dtype_f64() -> Result<()> {
        let t = Tensor::full_with_dtype(&[2], 7.0, DType::F64)?;
        assert_eq!(t.dtype(), DType::F64);
        Ok(())
    }

    #[test]
    fn test_full_with_dtype_i64() -> Result<()> {
        let t = Tensor::full_with_dtype(&[4], 42.0, DType::I64)?;
        assert_eq!(t.dtype(), DType::I64);
        Ok(())
    }

    #[test]
    fn test_scalar() -> Result<()> {
        let t = Tensor::scalar(std::f32::consts::E)?;
        assert_eq!(t.shape(), Vec::<usize>::new());
        assert_eq!(t.dtype(), DType::F32);
        Ok(())
    }

    #[test]
    fn test_eye_f32() -> Result<()> {
        let t = Tensor::eye_f32(3)?;
        assert_eq!(t.shape(), vec![3, 3]);
        let data = t.data()?;
        // Check diagonal is 1, off-diagonal is 0
        for i in 0..3 {
            for j in 0..3 {
                let expected = if i == j { 1.0 } else { 0.0 };
                assert!((data[i * 3 + j] - expected).abs() < 1e-7);
            }
        }
        Ok(())
    }

    #[test]
    fn test_from_vec_with_dtype_f32() -> Result<()> {
        let t = Tensor::from_vec_with_dtype(vec![1.0, 2.0, 3.0], &[3], DType::F32)?;
        assert_eq!(t.dtype(), DType::F32);
        assert_eq!(t.shape(), vec![3]);
        Ok(())
    }

    #[test]
    fn test_from_vec_with_dtype_f64() -> Result<()> {
        let t = Tensor::from_vec_with_dtype(vec![1.0, 2.0], &[2], DType::F64)?;
        assert_eq!(t.dtype(), DType::F64);
        Ok(())
    }

    #[test]
    fn test_zeros_dtype_various() -> Result<()> {
        for dtype in &[DType::F32, DType::F64, DType::I64, DType::C32, DType::C64] {
            let t = Tensor::zeros_dtype(*dtype, &[2, 2])?;
            assert_eq!(t.dtype(), *dtype);
            assert_eq!(t.shape(), vec![2, 2]);
        }
        Ok(())
    }

    #[test]
    fn test_ones_dtype_f32() -> Result<()> {
        let t = Tensor::ones_dtype(DType::F32, &[3])?;
        assert_eq!(t.dtype(), DType::F32);
        let data = t.data()?;
        for val in &data {
            assert!((val - 1.0).abs() < 1e-7);
        }
        Ok(())
    }

    #[test]
    fn test_full_with_shape() -> Result<()> {
        let t = Tensor::full_with_shape(&[2, 4], 9.9)?;
        assert_eq!(t.shape(), vec![2, 4]);
        let data = t.data()?;
        for val in &data {
            assert!((val - 9.9).abs() < 1e-5);
        }
        Ok(())
    }

    #[test]
    fn test_from_slice_f64() -> Result<()> {
        let data = [1.0f64, 2.0, 3.0, 4.0];
        let t = Tensor::from_slice_f64(&data, &[2, 2])?;
        assert_eq!(t.shape(), vec![2, 2]);
        assert_eq!(t.dtype(), DType::F64);
        Ok(())
    }

    #[test]
    fn test_from_slice_i64() -> Result<()> {
        let data = [10i64, 20, 30];
        let t = Tensor::from_slice_i64(&data, &[3])?;
        assert_eq!(t.shape(), vec![3]);
        assert_eq!(t.dtype(), DType::I64);
        Ok(())
    }

    #[test]
    fn test_from_slice_i32() -> Result<()> {
        let data = [1i32, 2, 3, 4];
        let t = Tensor::from_slice_i32(&data, &[4])?;
        assert_eq!(t.shape(), vec![4]);
        // Stored as I64
        assert_eq!(t.dtype(), DType::I64);
        Ok(())
    }

    #[test]
    fn test_from_scalar_f32() -> Result<()> {
        let t = Tensor::from_scalar(42.0, DType::F32)?;
        assert_eq!(t.shape(), Vec::<usize>::new());
        assert_eq!(t.dtype(), DType::F32);
        Ok(())
    }

    #[test]
    fn test_from_scalar_f64() -> Result<()> {
        let t = Tensor::from_scalar(std::f32::consts::PI, DType::F64)?;
        assert_eq!(t.dtype(), DType::F64);
        Ok(())
    }

    #[test]
    fn test_range_i64() -> Result<()> {
        let t = Tensor::range(0, 5, DType::I64)?;
        assert_eq!(t.shape(), vec![5]);
        assert_eq!(t.dtype(), DType::I64);
        Ok(())
    }

    #[test]
    fn test_range_f32() -> Result<()> {
        let t = Tensor::range(1, 4, DType::F32)?;
        assert_eq!(t.shape(), vec![3]);
        assert_eq!(t.dtype(), DType::F32);
        Ok(())
    }

    #[test]
    fn test_range_invalid() {
        let result = Tensor::range(5, 2, DType::I64);
        assert!(result.is_err());
    }

    #[test]
    fn test_randint_i64() -> Result<()> {
        let t = Tensor::randint(0, 10, &[5], DType::I64)?;
        assert_eq!(t.shape(), vec![5]);
        assert_eq!(t.dtype(), DType::I64);
        Ok(())
    }

    #[test]
    fn test_randint_invalid_range() {
        let result = Tensor::randint(10, 5, &[3], DType::I64);
        assert!(result.is_err());
    }

    #[test]
    fn test_3d_tensor_construction() -> Result<()> {
        let data: Vec<f32> = (0..24).map(|i| i as f32).collect();
        let t = Tensor::from_data(data, &[2, 3, 4])?;
        assert_eq!(t.shape(), vec![2, 3, 4]);
        assert_eq!(t.ndim(), 3);
        Ok(())
    }

    #[test]
    fn test_ones_f16() -> Result<()> {
        let t = Tensor::ones_f16(&[2, 2])?;
        assert_eq!(t.shape(), vec![2, 2]);
        assert_eq!(t.dtype(), DType::F16);
        Ok(())
    }

    #[test]
    fn test_ones_bf16() -> Result<()> {
        let t = Tensor::ones_bf16(&[3])?;
        assert_eq!(t.shape(), vec![3]);
        assert_eq!(t.dtype(), DType::BF16);
        Ok(())
    }
}