torsh-python 0.1.2

Python bindings for ToRSh - PyTorch-compatible deep learning in Rust
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
//! Core tensor implementation - PyTensor struct and fundamental operations

use crate::{device::PyDevice, dtype::PyDType, error::PyResult, py_result};
// Note: For Python bindings, we use numpy's PyArray API directly
// which handles type conversions internally (numpy uses ndarray 0.15.x)
use numpy::{
    IxDyn as NpIxDyn, PyArray1, PyArray2, PyArrayDyn, PyArrayMethods, PyUntypedArrayMethods,
};
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyList};
use torsh_core::device::DeviceType;
use torsh_tensor::Tensor;

/// Python wrapper for ToRSh Tensor (simplified version)
#[pyclass(name = "Tensor", from_py_object)]
#[derive(Clone)]
pub struct PyTensor {
    pub(crate) tensor: Tensor<f32>, // For now, default to f32
}

#[pymethods]
impl PyTensor {
    #[new]
    pub fn new(
        data: &Bound<'_, PyAny>,
        _dtype: Option<PyDType>,
        device: Option<PyDevice>,
        requires_grad: Option<bool>,
    ) -> PyResult<Self> {
        let device = device.map(|d| d.device).unwrap_or(DeviceType::Cpu);
        let requires_grad = requires_grad.unwrap_or(false);

        // Convert Python data to Rust tensor
        let tensor = if let Ok(arr) = data.clone().cast_into::<PyArray1<f32>>() {
            // 1D NumPy array
            let data = arr.to_vec()?;
            let shape = vec![data.len()];
            py_result!(Tensor::from_data(data, shape, device))?
        } else if let Ok(arr) = data.clone().cast_into::<PyArray2<f32>>() {
            // 2D NumPy array
            let data = arr.to_vec()?;
            let shape = arr.shape().to_vec();
            py_result!(Tensor::from_data(data, shape, device))?
        } else if let Ok(arr) = data.clone().cast_into::<PyArrayDyn<f32>>() {
            // N-D NumPy array
            let data = arr.to_vec()?;
            let shape = arr.shape().to_vec();
            py_result!(Tensor::from_data(data, shape, device))?
        } else if let Ok(list) = data.clone().cast_into::<PyList>() {
            // Python list - simplified version
            Self::from_py_list(&list, device)?
        } else if let Ok(scalar) = data.extract::<f32>() {
            // Scalar value
            py_result!(Tensor::from_data(vec![scalar], vec![], device))?
        } else {
            return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(
                "Unsupported data type for tensor creation",
            ));
        };

        let tensor = tensor.requires_grad_(requires_grad);

        Ok(Self { tensor })
    }

    // Basic properties
    #[getter]
    fn shape(&self) -> Vec<usize> {
        self.tensor.shape().dims().to_vec()
    }

    #[getter]
    fn ndim(&self) -> usize {
        self.tensor.ndim()
    }

    #[getter]
    pub fn numel(&self) -> usize {
        self.tensor.numel()
    }

    #[getter]
    fn dtype(&self) -> PyDType {
        PyDType::from(self.tensor.dtype())
    }

    #[getter]
    fn device(&self) -> PyDevice {
        PyDevice::from(self.tensor.device())
    }

    #[getter]
    fn requires_grad(&self) -> bool {
        self.tensor.requires_grad()
    }

    // String representation
    fn __repr__(&self) -> String {
        let binding = self.tensor.shape();
        let shape = binding.dims();
        let device_str = match self.tensor.device() {
            DeviceType::Cpu => String::new(),
            dev => format!(", device='{}'", PyDevice::from(dev)),
        };
        let grad_str = if self.tensor.requires_grad() {
            ", requires_grad=True"
        } else {
            ""
        };

        format!(
            "tensor({:?}, shape={}{}{}, dtype={})",
            // For now, just show shape info instead of actual data
            shape,
            shape
                .iter()
                .map(|d| d.to_string())
                .collect::<Vec<_>>()
                .join(", "),
            device_str,
            grad_str,
            PyDType::from(self.tensor.dtype())
        )
    }

    fn __str__(&self) -> String {
        self.__repr__()
    }

    /// Convert tensor to NumPy array with proper shape preservation
    fn numpy(&self) -> PyResult<Py<PyAny>> {
        Python::attach(|py| {
            let data = py_result!(self.tensor.to_vec())?;
            let binding = self.tensor.shape();
            let shape = binding.dims();

            // Convert shape from usize to Vec for reshape
            let shape_vec: Vec<usize> = shape.iter().copied().collect();

            match shape.len() {
                0 => {
                    // Scalar
                    Ok(data[0].into_pyobject(py)?.into_any().unbind())
                }
                1 => {
                    // 1D array - direct creation
                    let array = PyArray1::from_vec(py, data);
                    Ok(array.into_pyobject(py)?.into_any().unbind())
                }
                2 => {
                    // 2D array - create 1D and reshape
                    let array_1d = PyArray1::from_vec(py, data);
                    let array_2d = array_1d
                        .reshape([shape_vec[0], shape_vec[1]])
                        .map_err(|e| {
                            PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                                "Reshape error: {}",
                                e
                            ))
                        })?;
                    Ok(array_2d.into_pyobject(py)?.into_any().unbind())
                }
                _ => {
                    // N-D array - create 1D and reshape to dynamic dimension
                    let array_1d = PyArray1::from_vec(py, data);
                    let array_nd = array_1d.reshape(NpIxDyn(&shape_vec)).map_err(|e| {
                        PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                            "Reshape error: {}",
                            e
                        ))
                    })?;
                    Ok(array_nd.into_pyobject(py)?.into_any().unbind())
                }
            }
        })
    }

    /// Extract single scalar value from tensor
    fn item(&self) -> PyResult<f32> {
        if self.tensor.numel() != 1 {
            return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
                "Only one element tensors can be converted to Python scalars",
            ));
        }
        let data = py_result!(self.tensor.to_vec())?;
        Ok(data[0])
    }

    /// Convert tensor to nested Python lists
    fn tolist(&self) -> PyResult<Py<PyAny>> {
        Python::attach(|py| {
            let data = py_result!(self.tensor.to_vec())?;
            let binding = self.tensor.shape();
            let shape = binding.dims();

            if shape.is_empty() {
                // Scalar
                Ok(data[0].into_pyobject(py)?.into_any().unbind())
            } else {
                // Create nested lists based on tensor shape
                let nested_list = self.create_nested_list(py, &data, shape, 0, &mut 0)?;
                Ok(nested_list)
            }
        })
    }

    /// Create a copy of tensor on specified device (NumPy-compatible method)
    fn copy(&self) -> PyResult<PyTensor> {
        Ok(PyTensor {
            tensor: self.tensor.clone(),
        })
    }

    /// Get tensor stride information (NumPy-compatible)
    fn stride(&self) -> Vec<usize> {
        // For now, return a simple stride calculation
        let binding = self.tensor.shape();
        let shape = binding.dims();
        let mut strides = vec![1; shape.len()];
        for i in (0..shape.len().saturating_sub(1)).rev() {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
        strides
    }

    /// Get number of bytes per element (NumPy-compatible)
    fn itemsize(&self) -> usize {
        std::mem::size_of::<f32>()
    }

    /// Get total number of bytes (NumPy-compatible)
    fn nbytes(&self) -> usize {
        self.tensor.numel() * self.itemsize()
    }

    /// Check if tensor data is C-contiguous (NumPy-compatible)
    fn is_c_contiguous(&self) -> bool {
        self.tensor.is_contiguous()
    }

    // ===============================
    // Mathematical Operations
    // ===============================

    /// Add operation (tensor + other)
    fn add(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.add(&other.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    /// Subtract operation (tensor - other)
    fn sub(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.sub(&other.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    /// Multiply operation (tensor * other)
    fn mul(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.mul(&other.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    /// Divide operation (tensor / other)
    fn div(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.div(&other.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    /// Power operation (tensor ** exponent)
    fn pow(&self, exponent: f32) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.pow(exponent))?;
        Ok(PyTensor { tensor: result })
    }

    /// Scalar addition
    fn add_scalar(&self, scalar: f32) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.add_scalar(scalar))?;
        Ok(PyTensor { tensor: result })
    }

    /// Scalar multiplication
    fn mul_scalar(&self, scalar: f32) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.mul_scalar(scalar))?;
        Ok(PyTensor { tensor: result })
    }

    // ===============================
    // Tensor Manipulation Operations
    // ===============================

    /// Reshape tensor to new shape
    fn reshape(&self, shape: Vec<i64>) -> PyResult<PyTensor> {
        let i32_shape: Vec<i32> = shape.iter().map(|&x| x as i32).collect();
        let result = py_result!(self.tensor.reshape(&i32_shape))?;
        Ok(PyTensor { tensor: result })
    }

    /// Transpose tensor (swap dimensions)
    fn transpose(&self, dim0: i64, dim1: i64) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.transpose(dim0 as i32, dim1 as i32))?;
        Ok(PyTensor { tensor: result })
    }

    /// Transpose 2D tensor
    fn t(&self) -> PyResult<PyTensor> {
        if self.tensor.ndim() != 2 {
            return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
                "t() can only be called on 2D tensors",
            ));
        }
        self.transpose(0, 1)
    }

    /// Squeeze tensor (remove dimensions of size 1)
    fn squeeze(&self, dim: Option<i64>) -> PyResult<PyTensor> {
        let dim_to_squeeze = dim.map(|d| d as i32).unwrap_or(0i32);
        let result = py_result!(self.tensor.squeeze(dim_to_squeeze))?;
        Ok(PyTensor { tensor: result })
    }

    /// Unsqueeze tensor (add dimension of size 1)
    fn unsqueeze(&self, dim: i64) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.unsqueeze(dim as i32))?;
        Ok(PyTensor { tensor: result })
    }

    /// Flatten tensor
    fn flatten(&self, _start_dim: Option<i64>, _end_dim: Option<i64>) -> PyResult<PyTensor> {
        // For now, use basic flatten - may need different implementation
        let result = py_result!(self.tensor.flatten())?;
        Ok(PyTensor { tensor: result })
    }

    // ===============================
    // Reduction Operations
    // ===============================

    /// Sum along specified dimensions
    fn sum(&self, _dim: Option<Vec<i64>>, _keepdim: Option<bool>) -> PyResult<PyTensor> {
        // For now, use basic sum - may need different implementation
        let result = py_result!(self.tensor.sum())?;
        Ok(PyTensor { tensor: result })
    }

    /// Mean along specified dimensions
    fn mean(&self, dim: Option<Vec<i64>>, keepdim: Option<bool>) -> PyResult<PyTensor> {
        let keepdim = keepdim.unwrap_or(false);
        let result = if let Some(dims) = dim {
            let usize_dims: Vec<usize> = dims.iter().map(|&x| x as usize).collect();
            py_result!(self.tensor.mean(Some(&usize_dims), keepdim))?
        } else {
            py_result!(self.tensor.mean(None, keepdim))?
        };
        Ok(PyTensor { tensor: result })
    }

    /// Maximum along specified dimensions
    fn max(&self, dim: Option<i64>, keepdim: Option<bool>) -> PyResult<PyTensor> {
        let dim_opt = dim.map(|d| d as usize);
        let keepdim = keepdim.unwrap_or(false);
        let result = py_result!(self.tensor.max(dim_opt, keepdim))?;
        Ok(PyTensor { tensor: result })
    }

    /// Minimum along specified dimensions
    fn min(&self, _dim: Option<i64>, _keepdim: Option<bool>) -> PyResult<PyTensor> {
        // For now, use basic min - may need different implementation
        let result = py_result!(self.tensor.min())?;
        Ok(PyTensor { tensor: result })
    }

    // ===============================
    // Linear Algebra Operations
    // ===============================

    /// Matrix multiplication
    fn matmul(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.matmul(&other.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    /// Dot product (1D tensors)
    fn dot(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.dot(&other.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    // ===============================
    // Activation Functions
    // ===============================

    /// ReLU activation function
    fn relu(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.relu())?;
        Ok(PyTensor { tensor: result })
    }

    /// Sigmoid activation function
    fn sigmoid(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.sigmoid())?;
        Ok(PyTensor { tensor: result })
    }

    /// Tanh activation function
    fn tanh(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.tanh())?;
        Ok(PyTensor { tensor: result })
    }

    /// Softmax along specified dimension
    fn softmax(&self, dim: i64) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.softmax(dim as i32))?;
        Ok(PyTensor { tensor: result })
    }

    // ===============================
    // Trigonometric Functions
    // ===============================

    /// Sine function
    fn sin(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.sin())?;
        Ok(PyTensor { tensor: result })
    }

    /// Cosine function
    fn cos(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.cos())?;
        Ok(PyTensor { tensor: result })
    }

    /// Exponential function
    fn exp(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.exp())?;
        Ok(PyTensor { tensor: result })
    }

    /// Natural logarithm
    fn log(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.log())?;
        Ok(PyTensor { tensor: result })
    }

    /// Square root
    fn sqrt(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.sqrt())?;
        Ok(PyTensor { tensor: result })
    }

    /// Absolute value
    fn abs(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.abs())?;
        Ok(PyTensor { tensor: result })
    }

    // ===============================
    // Comparison Operations
    // ===============================

    /// Element-wise equality (returns f32 tensor with 0.0/1.0 values)
    fn eq(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.eq(&other.tensor))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Element-wise inequality (returns f32 tensor with 0.0/1.0 values)
    fn ne(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.ne(&other.tensor))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Element-wise less than (returns f32 tensor with 0.0/1.0 values)
    fn lt(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.lt(&other.tensor))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Element-wise greater than (returns f32 tensor with 0.0/1.0 values)
    fn gt(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.gt(&other.tensor))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Element-wise less than or equal (returns f32 tensor with 0.0/1.0 values)
    fn le(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.le(&other.tensor))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Element-wise greater than or equal (returns f32 tensor with 0.0/1.0 values)
    fn ge(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.ge(&other.tensor))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Element-wise maximum
    fn maximum(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.maximum(&other.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    /// Element-wise minimum
    fn minimum(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.minimum(&other.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    // Scalar comparison operations

    /// Scalar equality (returns f32 tensor with 0.0/1.0 values)
    fn eq_scalar(&self, value: f32) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.eq_scalar(value))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Scalar inequality (returns f32 tensor with 0.0/1.0 values)
    fn ne_scalar(&self, value: f32) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.ne_scalar(value))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Scalar less than (returns f32 tensor with 0.0/1.0 values)
    fn lt_scalar(&self, value: f32) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.lt_scalar(value))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Scalar greater than (returns f32 tensor with 0.0/1.0 values)
    fn gt_scalar(&self, value: f32) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.gt_scalar(value))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Scalar less than or equal (returns f32 tensor with 0.0/1.0 values)
    fn le_scalar(&self, value: f32) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.le_scalar(value))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    /// Scalar greater than or equal (returns f32 tensor with 0.0/1.0 values)
    fn ge_scalar(&self, value: f32) -> PyResult<PyTensor> {
        let bool_result = py_result!(self.tensor.ge_scalar(value))?;
        let float_tensor = py_result!(Self::bool_to_float_tensor(bool_result))?;
        Ok(PyTensor {
            tensor: float_tensor,
        })
    }

    // ===============================
    // Utility Methods
    // ===============================

    /// Create a copy of the tensor
    fn clone_tensor(&self) -> PyResult<PyTensor> {
        Ok(PyTensor {
            tensor: self.tensor.clone(),
        })
    }

    /// Create a detached copy (no gradients)
    fn detach(&self) -> PyResult<PyTensor> {
        Ok(PyTensor {
            tensor: self.tensor.detach(),
        })
    }

    /// Move tensor to specified device
    fn to_device(&self, device: PyDevice) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.clone().to(device.device))?;
        Ok(PyTensor { tensor: result })
    }

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

    /// Make tensor contiguous in memory
    fn contiguous(&self) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.contiguous())?;
        Ok(PyTensor { tensor: result })
    }

    // ===============================
    // Additional PyTorch-Compatible Operations
    // ===============================

    /// Clamp tensor values to specified range
    fn clamp(&self, min: Option<f32>, max: Option<f32>) -> PyResult<PyTensor> {
        let result = if let (Some(min_val), Some(max_val)) = (min, max) {
            py_result!(self.tensor.clamp(min_val, max_val))?
        } else if let Some(min_val) = min {
            // Use clamp with a very large max value for min-only clamping
            py_result!(self.tensor.clamp(min_val, f32::MAX))?
        } else if let Some(max_val) = max {
            // Use clamp with a very small min value for max-only clamping
            py_result!(self.tensor.clamp(f32::MIN, max_val))?
        } else {
            return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
                "At least one of min or max must be specified",
            ));
        };
        Ok(PyTensor { tensor: result })
    }

    /// Fill tensor with specified value (in-place operation)
    fn fill_(&mut self, value: f32) -> PyResult<PyTensor> {
        py_result!(self.tensor.fill_(value))?;
        Ok(PyTensor {
            tensor: self.tensor.clone(),
        })
    }

    /// Zero out tensor (in-place operation)
    fn zero_(&mut self) -> PyResult<PyTensor> {
        py_result!(self.tensor.zero_())?;
        Ok(PyTensor {
            tensor: self.tensor.clone(),
        })
    }

    /// Apply uniform random initialization
    fn uniform_(&mut self, from: Option<f32>, to: Option<f32>) -> PyResult<PyTensor> {
        // ✅ SciRS2 POLICY: Use scirs2_core::random for RNG
        use scirs2_core::random::{thread_rng, Distribution, Uniform};

        let from = from.unwrap_or(0.0);
        let to = to.unwrap_or(1.0);

        let mut rng = thread_rng();
        let dist = Uniform::new(from, to).map_err(|e| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                "Invalid uniform distribution parameters: {}",
                e
            ))
        })?;

        let mut data = py_result!(self.tensor.data())?;
        for val in data.iter_mut() {
            *val = dist.sample(&mut rng);
        }

        let shape = self.tensor.shape().dims().to_vec();
        let device = self.tensor.device();
        self.tensor = py_result!(torsh_tensor::Tensor::from_data(data, shape, device))?
            .requires_grad_(self.tensor.requires_grad());

        Ok(PyTensor {
            tensor: self.tensor.clone(),
        })
    }

    /// Apply normal random initialization
    fn normal_(&mut self, mean: Option<f32>, std: Option<f32>) -> PyResult<PyTensor> {
        // ✅ SciRS2 POLICY: Use scirs2_core::random for RNG
        use scirs2_core::random::{thread_rng, Distribution, Normal};

        let mean = mean.unwrap_or(0.0);
        let std = std.unwrap_or(1.0);

        let normal = Normal::new(mean as f64, std as f64).map_err(|e| {
            PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                "Invalid normal distribution parameters: {}",
                e
            ))
        })?;

        let mut rng = thread_rng();
        let mut data = py_result!(self.tensor.data())?;
        for val in data.iter_mut() {
            *val = normal.sample(&mut rng) as f32;
        }

        let shape = self.tensor.shape().dims().to_vec();
        let device = self.tensor.device();
        self.tensor = py_result!(torsh_tensor::Tensor::from_data(data, shape, device))?
            .requires_grad_(self.tensor.requires_grad());

        Ok(PyTensor {
            tensor: self.tensor.clone(),
        })
    }

    /// Repeat tensor along specified dimensions
    fn repeat(&self, repeats: Vec<usize>) -> PyResult<PyTensor> {
        let result = py_result!(self.tensor.repeat(&repeats))?;
        Ok(PyTensor { tensor: result })
    }

    /// Expand tensor to specified shape (broadcasting)
    fn expand(&self, size: Vec<i64>) -> PyResult<PyTensor> {
        let size: Vec<usize> = size.iter().map(|&x| x as usize).collect();
        let result = py_result!(self.tensor.expand(&size))?;
        Ok(PyTensor { tensor: result })
    }

    /// Expand tensor to match another tensor's shape
    fn expand_as(&self, other: &PyTensor) -> PyResult<PyTensor> {
        let other_shape: Vec<usize> = other.tensor.shape().dims().iter().map(|&x| x).collect();
        let result = py_result!(self.tensor.expand(&other_shape))?;
        Ok(PyTensor { tensor: result })
    }

    /// Select elements from tensor along specified dimension
    fn index_select(&self, dim: i64, index: &PyTensor) -> PyResult<PyTensor> {
        let index_i32 = py_result!(index.tensor.to_i32_simd())?;
        let index_i64 = py_result!(index_i32.to_i64_simd())?;
        let result = py_result!(self.tensor.index_select(dim as i32, &index_i64))?;
        Ok(PyTensor { tensor: result })
    }

    /// Gather elements from tensor
    fn gather(&self, dim: i64, index: &PyTensor) -> PyResult<PyTensor> {
        let index_i32 = py_result!(index.tensor.to_i32_simd())?;
        let index_i64 = py_result!(index_i32.to_i64_simd())?;
        let result = py_result!(self.tensor.gather(dim as usize, &index_i64))?;
        Ok(PyTensor { tensor: result })
    }

    /// Scatter elements into tensor
    fn scatter(&self, dim: i64, index: &PyTensor, src: &PyTensor) -> PyResult<PyTensor> {
        let index_i32 = py_result!(index.tensor.to_i32_simd())?;
        let index_i64 = py_result!(index_i32.to_i64_simd())?;
        let result = py_result!(self.tensor.scatter(dim as usize, &index_i64, &src.tensor))?;
        Ok(PyTensor { tensor: result })
    }

    /// Masked fill operation
    fn masked_fill(&self, mask: &PyTensor, value: f32) -> PyResult<PyTensor> {
        // ✅ Proper masked fill implementation
        let mut data = py_result!(self.tensor.data())?;
        let mask_data = py_result!(mask.tensor.data())?;

        if data.len() != mask_data.len() {
            return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
                "Mask must have the same number of elements as tensor",
            ));
        }

        for (val, &mask_val) in data.iter_mut().zip(mask_data.iter()) {
            if mask_val != 0.0 {
                *val = value;
            }
        }

        let shape = self.tensor.shape().dims().to_vec();
        let device = self.tensor.device();
        let result = py_result!(torsh_tensor::Tensor::from_data(data, shape, device))?
            .requires_grad_(self.tensor.requires_grad());

        Ok(PyTensor { tensor: result })
    }

    /// Masked select operation
    fn masked_select(&self, mask: &PyTensor) -> PyResult<PyTensor> {
        // Convert f32 mask to bool by treating non-zero as true
        let mask_data = py_result!(mask.tensor.data())?;
        let bool_data: Vec<bool> = mask_data.iter().map(|&x| x != 0.0).collect();
        let mask_bool = py_result!(torsh_tensor::Tensor::from_data(
            bool_data,
            mask.tensor.shape().dims().to_vec(),
            mask.tensor.device()
        ))?;
        let result = py_result!(self.tensor.masked_select(&mask_bool))?;
        Ok(PyTensor { tensor: result })
    }

    /// Concatenate tensors along specified dimension
    fn cat(&self, tensors: Vec<PyTensor>, dim: i64) -> PyResult<PyTensor> {
        let tensor_refs: Vec<&torsh_tensor::Tensor<f32>> =
            tensors.iter().map(|t| &t.tensor).collect();
        let result = py_result!(torsh_tensor::Tensor::cat(&tensor_refs, dim as i32))?;
        Ok(PyTensor { tensor: result })
    }

    /// Stack tensors along new dimension
    fn stack(&self, tensors: Vec<PyTensor>, dim: i64) -> PyResult<PyTensor> {
        let tensor_refs: Vec<&torsh_tensor::Tensor<f32>> =
            tensors.iter().map(|t| &t.tensor).collect();
        // Use cat as a simplified stacking implementation
        let result = py_result!(torsh_tensor::Tensor::cat(&tensor_refs, dim as i32))?;
        Ok(PyTensor { tensor: result })
    }

    /// Split tensor into chunks
    fn chunk(&self, chunks: usize, dim: i64) -> PyResult<Vec<PyTensor>> {
        // ✅ Proper chunk implementation
        let shape = self.tensor.shape().dims().to_vec();
        let dim_usize = dim as usize;

        if dim_usize >= shape.len() {
            return Err(PyErr::new::<pyo3::exceptions::PyIndexError, _>(format!(
                "Dimension {} out of range for tensor with {} dimensions",
                dim,
                shape.len()
            )));
        }

        let dim_size = shape[dim_usize];
        let chunk_size = (dim_size + chunks - 1) / chunks; // Ceiling division

        let mut result = Vec::new();
        for i in 0..chunks {
            let start = i * chunk_size;
            if start >= dim_size {
                break;
            }
            let end = std::cmp::min(start + chunk_size, dim_size);

            // Use narrow to extract chunk
            let chunk = py_result!(self.tensor.narrow(dim as i32, start as i64, end - start))?;
            result.push(PyTensor { tensor: chunk });
        }

        Ok(result)
    }

    /// Split tensor at specified sizes
    fn split(&self, split_sizes: Vec<usize>, dim: i64) -> PyResult<Vec<PyTensor>> {
        // ✅ Proper split implementation
        let shape = self.tensor.shape().dims().to_vec();
        let dim_usize = dim as usize;

        if dim_usize >= shape.len() {
            return Err(PyErr::new::<pyo3::exceptions::PyIndexError, _>(format!(
                "Dimension {} out of range for tensor with {} dimensions",
                dim,
                shape.len()
            )));
        }

        let total_size: usize = split_sizes.iter().sum();
        if total_size != shape[dim_usize] {
            return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                "Split sizes sum to {} but dimension {} has size {}",
                total_size, dim, shape[dim_usize]
            )));
        }

        let mut result = Vec::new();
        let mut start = 0;

        for &size in &split_sizes {
            let chunk = py_result!(self.tensor.narrow(dim as i32, start as i64, size))?;
            result.push(PyTensor { tensor: chunk });
            start += size;
        }

        Ok(result)
    }

    /// Permute tensor dimensions
    fn permute(&self, dims: Vec<i64>) -> PyResult<PyTensor> {
        let dims: Vec<i32> = dims.iter().map(|&x| x as i32).collect();
        let result = py_result!(self.tensor.permute(&dims))?;
        Ok(PyTensor { tensor: result })
    }

    /// Get diagonal elements
    fn diag(&self, diagonal: Option<i64>) -> PyResult<PyTensor> {
        // ✅ Proper diagonal extraction implementation

        let offset = diagonal.unwrap_or(0);
        let shape = self.tensor.shape().dims().to_vec();

        if shape.len() == 1 {
            // 1D tensor -> create diagonal matrix
            let n = shape[0];
            let size = n + offset.abs() as usize;
            let mut data = vec![0.0; size * size];
            let input_data = py_result!(self.tensor.data())?;

            for (i, &val) in input_data.iter().enumerate() {
                if offset >= 0 {
                    let row = i;
                    let col = i + offset as usize;
                    data[row * size + col] = val;
                } else {
                    let row = i + (-offset) as usize;
                    let col = i;
                    data[row * size + col] = val;
                }
            }

            let result = py_result!(torsh_tensor::Tensor::from_data(
                data,
                vec![size, size],
                self.tensor.device()
            ))?;
            Ok(PyTensor { tensor: result })
        } else if shape.len() == 2 {
            // 2D tensor -> extract diagonal
            let rows = shape[0];
            let cols = shape[1];
            let data = py_result!(self.tensor.data())?;

            let mut diag_data = Vec::new();

            if offset >= 0 {
                let offset_u = offset as usize;
                for i in 0..std::cmp::min(rows, cols.saturating_sub(offset_u)) {
                    diag_data.push(data[i * cols + i + offset_u]);
                }
            } else {
                let offset_u = (-offset) as usize;
                for i in 0..std::cmp::min(rows.saturating_sub(offset_u), cols) {
                    diag_data.push(data[(i + offset_u) * cols + i]);
                }
            }

            let diag_len = diag_data.len();
            let result = py_result!(torsh_tensor::Tensor::from_data(
                diag_data,
                vec![diag_len],
                self.tensor.device()
            ))?;
            Ok(PyTensor { tensor: result })
        } else {
            Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                "diag() only supports 1D or 2D tensors",
            ))
        }
    }

    /// Trace of matrix
    fn trace(&self) -> PyResult<PyTensor> {
        // ✅ Proper trace computation
        let shape = self.tensor.shape().dims().to_vec();

        if shape.len() != 2 {
            return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                "trace() requires a 2D tensor",
            ));
        }

        let rows = shape[0];
        let cols = shape[1];
        let min_dim = std::cmp::min(rows, cols);

        let data = py_result!(self.tensor.data())?;
        let mut trace_sum = 0.0;

        for i in 0..min_dim {
            trace_sum += data[i * cols + i];
        }

        let result = py_result!(torsh_tensor::Tensor::from_data(
            vec![trace_sum],
            vec![],
            self.tensor.device()
        ))?;

        Ok(PyTensor { tensor: result })
    }

    /// Norm calculation
    fn norm(
        &self,
        p: Option<f32>,
        _dim: Option<Vec<i64>>,
        _keepdim: Option<bool>,
    ) -> PyResult<PyTensor> {
        let _p = p.unwrap_or(2.0);
        // For now, use simple L2 norm regardless of parameters
        // TODO: Implement full norm_lp functionality when ops module is exposed
        let result = py_result!(self.tensor.norm())?;
        Ok(PyTensor { tensor: result })
    }

    /// Standard deviation
    fn std(
        &self,
        dim: Option<Vec<i64>>,
        keepdim: Option<bool>,
        unbiased: Option<bool>,
    ) -> PyResult<PyTensor> {
        let keepdim = keepdim.unwrap_or(false);
        let unbiased = unbiased.unwrap_or(true);
        let stat_mode = if unbiased {
            torsh_tensor::stats::StatMode::Sample
        } else {
            torsh_tensor::stats::StatMode::Population
        };
        let result = if let Some(dims) = dim {
            let usize_dims: Vec<usize> = dims.iter().map(|&x| x as usize).collect();
            py_result!(self.tensor.std(Some(&usize_dims), keepdim, stat_mode))?
        } else {
            py_result!(self.tensor.std(None, keepdim, stat_mode))?
        };
        Ok(PyTensor { tensor: result })
    }

    /// Variance calculation
    fn var(
        &self,
        dim: Option<Vec<i64>>,
        keepdim: Option<bool>,
        unbiased: Option<bool>,
    ) -> PyResult<PyTensor> {
        let keepdim = keepdim.unwrap_or(false);
        let unbiased = unbiased.unwrap_or(true);
        let stat_mode = if unbiased {
            torsh_tensor::stats::StatMode::Sample
        } else {
            torsh_tensor::stats::StatMode::Population
        };
        let result = if let Some(dims) = dim {
            let usize_dims: Vec<usize> = dims.iter().map(|&x| x as usize).collect();
            py_result!(self.tensor.var(Some(&usize_dims), keepdim, stat_mode))?
        } else {
            py_result!(self.tensor.var(None, keepdim, stat_mode))?
        };
        Ok(PyTensor { tensor: result })
    }

    /// Argmax operation
    fn argmax(&self, dim: Option<i64>, _keepdim: Option<bool>) -> PyResult<PyTensor> {
        let result = if let Some(d) = dim {
            py_result!(self.tensor.argmax(Some(d as i32)))?
        } else {
            py_result!(self.tensor.argmax(None))?
        };
        let result_f32 = py_result!(result.to_f32_simd())?;
        Ok(PyTensor { tensor: result_f32 })
    }

    /// Argmin operation
    fn argmin(&self, dim: Option<i64>, _keepdim: Option<bool>) -> PyResult<PyTensor> {
        let result = if let Some(d) = dim {
            py_result!(self.tensor.argmin(Some(d as i32)))?
        } else {
            py_result!(self.tensor.argmin(None))?
        };
        let result_f32 = py_result!(result.to_f32_simd())?;
        Ok(PyTensor { tensor: result_f32 })
    }
}

impl PyTensor {
    /// Convert from Python list to tensor (simplified)
    fn from_py_list(list: &Bound<'_, PyList>, device: DeviceType) -> PyResult<Tensor<f32>> {
        let mut data = Vec::new();
        let len = list.len();

        for i in 0..len {
            let item = list.get_item(i)?;
            if let Ok(val) = item.extract::<f32>() {
                data.push(val);
            } else {
                return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                    "Cannot convert item at index {} to f32",
                    i
                )));
            }
        }

        py_result!(Tensor::from_data(data, vec![len], device))
    }

    /// Helper method to create nested Python lists from tensor data
    fn create_nested_list(
        &self,
        py: Python<'_>,
        data: &[f32],
        shape: &[usize],
        dim: usize,
        index: &mut usize,
    ) -> PyResult<Py<PyAny>> {
        if dim == shape.len() - 1 {
            // Leaf dimension: create list of values
            let mut items = Vec::new();
            for _ in 0..shape[dim] {
                items.push(data[*index].into_pyobject(py)?.into_any().unbind());
                *index += 1;
            }
            Ok(items.into_pyobject(py)?.into_any().unbind())
        } else {
            // Intermediate dimension: create list of nested lists
            let mut items = Vec::new();
            for _ in 0..shape[dim] {
                let nested = self.create_nested_list(py, data, shape, dim + 1, index)?;
                items.push(nested);
            }
            Ok(items.into_pyobject(py)?.into_any().unbind())
        }
    }

    /// Convert boolean tensor to float tensor (0.0 for false, 1.0 for true)
    fn bool_to_float_tensor(
        bool_tensor: torsh_tensor::Tensor<bool>,
    ) -> torsh_core::error::Result<torsh_tensor::Tensor<f32>> {
        let bool_data = bool_tensor.data()?;
        let float_data: Vec<f32> = bool_data
            .iter()
            .map(|&b| if b { 1.0 } else { 0.0 })
            .collect();
        let shape = bool_tensor.shape().dims().to_vec();
        let device = bool_tensor.device();

        torsh_tensor::Tensor::from_data(float_data, shape, device)
    }
}