rustorch 0.6.29

Production-ready PyTorch-compatible deep learning library in Rust with special mathematical functions (gamma, Bessel, error functions), statistical distributions, Fourier transforms (FFT/RFFT), matrix decomposition (SVD/QR/LU/eigenvalue), automatic differentiation, neural networks, computer vision transforms, complete GPU acceleration (CUDA/Metal/OpenCL), SIMD optimizations, parallel processing, WebAssembly browser support, comprehensive distributed learning support, and performance validation
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
//! Python bindings for tensor operations
//! テンソル操作のPythonバインディング

use crate::python::common::{conversions, to_py_err, validation};
use crate::tensor::device::Device;
use crate::tensor::operations::zero_copy::TensorIterOps;
use crate::tensor::Tensor;
use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1, ToPyArray};
use pyo3::exceptions::*;
use pyo3::prelude::*;

/// Python wrapper for RusTorch Tensor
/// RusTorch TensorのPythonラッパー
#[pyclass]
#[derive(Clone)]
pub struct PyTensor {
    pub(crate) tensor: Tensor<f32>,
}

#[pymethods]
impl PyTensor {
    #[new]
    pub fn new(data: Vec<f32>, shape: Vec<usize>) -> PyResult<Self> {
        use crate::python::common::validation::validate_dimensions;
        validate_dimensions(&shape)?;
        let tensor = Tensor::from_vec(data, shape);
        Ok(PyTensor { tensor })
    }

    /// Create PyTensor from NumPy array
    /// NumPy配列からPyTensorを作成
    #[staticmethod]
    pub fn from_numpy(array: PyReadonlyArray1<f32>) -> PyResult<Self> {
        use crate::python::common::conversions::pyarray_to_vec;
        let data = pyarray_to_vec(array);
        let shape = vec![data.len()];
        crate::python::common::validation::validate_dimensions(&shape)?;
        let tensor = Tensor::from_vec(data, shape);
        Ok(PyTensor { tensor })
    }

    /// Create zeros tensor
    /// ゼロテンソルを作成
    #[staticmethod]
    pub fn zeros(shape: Vec<usize>) -> PyResult<Self> {
        use crate::python::common::validation::validate_dimensions;
        validate_dimensions(&shape)?;
        let tensor = Tensor::zeros(&shape);
        Ok(PyTensor { tensor })
    }

    /// Create ones tensor
    /// ワンテンソルを作成
    #[staticmethod]
    pub fn ones(shape: Vec<usize>) -> PyResult<Self> {
        use crate::python::common::validation::validate_dimensions;
        validate_dimensions(&shape)?;
        let tensor = Tensor::ones(&shape);
        Ok(PyTensor { tensor })
    }

    /// Create random tensor
    /// ランダムテンソルを作成
    #[staticmethod]
    pub fn randn(shape: Vec<usize>) -> PyResult<Self> {
        use crate::python::common::validation::validate_dimensions;
        validate_dimensions(&shape)?;
        let tensor = Tensor::randn(&shape);
        Ok(PyTensor { tensor })
    }

    /// Create tensor from range
    /// 範囲からテンソルを作成
    #[staticmethod]
    pub fn arange(start: f32, end: f32, step: f32) -> PyResult<Self> {
        if step <= 0.0 {
            return Err(PyValueError::new_err("Step must be positive"));
        }
        if start >= end {
            return Err(PyValueError::new_err("Start must be less than end"));
        }

        let size = ((end - start) / step).ceil() as usize;
        let data: Vec<f32> = (0..size).map(|i| start + i as f32 * step).collect();
        let shape = vec![size];
        let tensor = Tensor::from_vec(data, shape);
        Ok(PyTensor { tensor })
    }

    /// Get tensor shape
    /// テンソル形状を取得
    pub fn shape(&self) -> Vec<usize> {
        self.tensor.shape().to_vec()
    }

    /// Get tensor data as Vec<f32>
    /// テンソルデータをVec<f32>として取得
    pub fn data(&self) -> Vec<f32> {
        self.tensor.iter().cloned().collect()
    }

    /// Convert tensor to vector (alias for data)
    /// テンソルをベクトルに変換(dataのエイリアス)
    pub fn to_vec(&self) -> PyResult<Vec<f32>> {
        Ok(self.data())
    }

    /// Convert PyTensor to NumPy array
    /// PyTensorをNumPy配列に変換
    pub fn numpy<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<f32>> {
        use crate::python::common::conversions::vec_to_pyarray;
        let data = self.data();
        vec_to_pyarray(data, py)
    }

    /// Get number of dimensions
    /// 次元数を取得
    pub fn ndim(&self) -> usize {
        self.tensor.shape().len()
    }

    /// Get total number of elements
    /// 要素の総数を取得
    pub fn numel(&self) -> usize {
        self.tensor.shape().iter().product()
    }

    /// Reshape tensor
    /// テンソルの形状を変更
    pub fn reshape(&self, shape: Vec<usize>) -> PyResult<Self> {
        use crate::python::common::{to_py_err, validation::validate_dimensions};
        validate_dimensions(&shape)?;

        let current_elements = self.numel();
        let new_elements: usize = shape.iter().product();
        if current_elements != new_elements {
            return Err(PyValueError::new_err(format!(
                "Cannot reshape tensor with {} elements to shape with {} elements",
                current_elements, new_elements
            )));
        }

        match self.tensor.reshape(&shape) {
            Ok(tensor) => Ok(PyTensor { tensor }),
            Err(e) => Err(to_py_err(e)),
        }
    }

    /// Transpose tensor
    /// テンソルを転置
    pub fn transpose(&self) -> PyResult<Self> {
        use crate::python::common::to_py_err;
        match self.tensor.transpose() {
            Ok(tensor) => Ok(PyTensor { tensor }),
            Err(e) => Err(to_py_err(e)),
        }
    }

    /// Add two tensors
    /// テンソル加算
    pub fn __add__(&self, other: &PyTensor) -> PyResult<Self> {
        if self.shape() != other.shape() {
            return Err(PyValueError::new_err(
                "Tensor shapes must match for addition",
            ));
        }
        let result_tensor = &self.tensor + &other.tensor;
        Ok(PyTensor {
            tensor: result_tensor,
        })
    }

    /// Subtract two tensors
    /// テンソル減算
    pub fn __sub__(&self, other: &PyTensor) -> PyResult<Self> {
        if self.shape() != other.shape() {
            return Err(PyValueError::new_err(
                "Tensor shapes must match for subtraction",
            ));
        }
        let result_tensor = &self.tensor - &other.tensor;
        Ok(PyTensor {
            tensor: result_tensor,
        })
    }

    /// Multiply two tensors
    /// テンソル乗算
    pub fn __mul__(&self, other: &PyTensor) -> PyResult<Self> {
        if self.shape() != other.shape() {
            return Err(PyValueError::new_err(
                "Tensor shapes must match for multiplication",
            ));
        }
        let result_tensor = &self.tensor * &other.tensor;
        Ok(PyTensor {
            tensor: result_tensor,
        })
    }

    /// Matrix multiplication
    /// 行列乗算
    pub fn __matmul__(&self, other: &PyTensor) -> PyResult<Self> {
        let self_shape = self.shape();
        let other_shape = other.shape();

        // Basic matrix multiplication shape validation
        if self_shape.len() < 2 || other_shape.len() < 2 {
            return Err(PyValueError::new_err(
                "Matrix multiplication requires at least 2D tensors",
            ));
        }

        let self_cols = self_shape[self_shape.len() - 1];
        let other_rows = other_shape[other_shape.len() - 2];

        if self_cols != other_rows {
            return Err(PyValueError::new_err(format!(
                "Matrix multiplication shape mismatch: {} vs {}",
                self_cols, other_rows
            )));
        }

        // For now, use element-wise multiplication as placeholder
        let result_tensor = &self.tensor * &other.tensor;
        Ok(PyTensor {
            tensor: result_tensor,
        })
    }

    /// Dot product (alias for matmul)
    /// ドット積(matmulのエイリアス)
    pub fn dot(&self, other: &PyTensor) -> PyResult<Self> {
        self.__matmul__(other)
    }

    /// Sum all elements
    /// 全要素の合計
    pub fn sum(&self) -> f32 {
        self.tensor.iter().sum()
    }

    /// Mean of all elements
    /// 全要素の平均
    pub fn mean(&self) -> f32 {
        let sum: f32 = self.tensor.iter().sum();
        sum / self.numel() as f32
    }

    /// Maximum value
    /// 最大値
    pub fn max(&self) -> f32 {
        self.tensor.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b))
    }

    /// Minimum value
    /// 最小値
    pub fn min(&self) -> f32 {
        self.tensor.iter().fold(f32::INFINITY, |a, &b| a.min(b))
    }

    // Linear Algebra Operations
    // 線形代数演算

    /// Singular Value Decomposition
    /// 特異値分解
    pub fn svd(&self, compute_uv: Option<bool>) -> PyResult<(PyTensor, PyTensor, PyTensor)> {
        use crate::python::common::to_py_err;
        let _compute_uv = compute_uv.unwrap_or(true);

        match self.tensor.svd() {
            Ok((u, s, vt)) => Ok((
                PyTensor { tensor: u },
                PyTensor { tensor: s },
                PyTensor { tensor: vt },
            )),
            Err(e) => Err(to_py_err(e)),
        }
    }

    /// QR Decomposition
    /// QR分解
    pub fn qr(&self) -> PyResult<(PyTensor, PyTensor)> {
        use crate::python::common::to_py_err;
        match self.tensor.qr() {
            Ok((q, r)) => Ok((PyTensor { tensor: q }, PyTensor { tensor: r })),
            Err(e) => Err(to_py_err(e)),
        }
    }

    /// Eigenvalue decomposition
    /// 固有値分解
    pub fn eig(&self) -> PyResult<(PyTensor, PyTensor)> {
        use crate::python::common::to_py_err;
        match self.tensor.eigh() {
            Ok((eigenvalues, eigenvectors)) => Ok((
                PyTensor {
                    tensor: eigenvalues,
                },
                PyTensor {
                    tensor: eigenvectors,
                },
            )),
            Err(e) => Err(to_py_err(e)),
        }
    }

    /// Matrix determinant
    /// 行列式
    pub fn det(&self) -> PyResult<f32> {
        use crate::python::common::to_py_err;
        match self.tensor.det() {
            Ok(det) => Ok(det),
            Err(e) => Err(to_py_err(e)),
        }
    }

    /// Matrix inverse
    /// 逆行列
    pub fn inverse(&self) -> PyResult<PyTensor> {
        use crate::python::common::to_py_err;
        match self.tensor.inverse() {
            Ok(tensor) => Ok(PyTensor { tensor }),
            Err(e) => Err(to_py_err(e)),
        }
    }

    /// Matrix norm
    /// 行列ノルム
    pub fn norm(&self, ord: Option<String>) -> PyResult<f32> {
        let _ord = ord.unwrap_or_else(|| "fro".to_string());
        // Use simplified norm computation
        let norm_value = self.tensor.norm();
        Ok(norm_value)
    }

    /// String representation
    /// 文字列表現
    pub fn __repr__(&self) -> String {
        format!("PyTensor(shape={:?}, data={:?})", self.shape(), {
            let data = self.data();
            if data.len() <= 10 {
                format!("{:?}", data)
            } else {
                format!("{:?}...", &data[..10])
            }
        })
    }

    /// String representation (same as __repr__)
    /// 文字列表現(__repr__と同じ)
    pub fn __str__(&self) -> String {
        self.__repr__()
    }

    /// Clone the object
    /// オブジェクトのクローン
    pub fn __copy__(&self) -> Self {
        self.clone()
    }

    /// Deep copy the object
    /// オブジェクトの深いコピー
    pub fn __deepcopy__(&self, _memo: &Bound<'_, pyo3::types::PyDict>) -> Self {
        self.clone()
    }
}

/// Python wrapper for Device
/// DeviceのPythonラッパー
#[pyclass]
pub struct PyDevice {
    pub(crate) device: Device,
}

#[pymethods]
impl PyDevice {
    /// Create CPU device
    /// CPUデバイスを作成
    #[staticmethod]
    pub fn cpu() -> Self {
        PyDevice {
            device: Device::Cpu,
        }
    }

    /// Create CUDA device
    /// CUDAデバイスを作成
    #[staticmethod]
    pub fn cuda(index: Option<usize>) -> PyResult<Self> {
        let index = index.unwrap_or(0);
        // Simplified CUDA device creation
        let device = Device::Cuda(index);
        Ok(PyDevice { device })
    }

    /// Create Metal device (for Apple Silicon)
    /// Metalデバイスを作成(Apple Silicon用)
    #[staticmethod]
    pub fn metal() -> PyResult<Self> {
        // Simplified Metal device creation
        let device = Device::Mps;
        Ok(PyDevice { device })
    }

    /// Check if device is available
    /// デバイスが利用可能かチェック
    pub fn is_available(&self) -> bool {
        // Simplified availability check
        match self.device {
            Device::Cpu => true,
            Device::Cuda(_) => false, // Simplified - would check CUDA availability
            Device::Mps => cfg!(target_os = "macos"),
            Device::Wasm => cfg!(target_arch = "wasm32"),
        }
    }

    /// Get device type as string
    /// デバイスタイプを文字列として取得
    pub fn type_(&self) -> String {
        match self.device {
            Device::Cpu => "cpu".to_string(),
            Device::Cuda(_) => "cuda".to_string(),
            Device::Mps => "mps".to_string(),
            Device::Wasm => "wasm".to_string(),
        }
    }

    /// String representation
    /// 文字列表現
    pub fn __repr__(&self) -> String {
        match self.device {
            Device::Cpu => "device(type='cpu')".to_string(),
            Device::Cuda(index) => format!("device(type='cuda', index={})", index),
            Device::Mps => "device(type='mps')".to_string(),
            Device::Wasm => "device(type='wasm')".to_string(),
        }
    }
}

// Additional tensor creation functions
// 追加のテンソル作成関数

/// Create tensor from Python list
/// Pythonリストからテンソルを作成
#[pyfunction]
pub fn tensor(data: Vec<f32>, shape: Option<Vec<usize>>) -> PyResult<PyTensor> {
    let shape = shape.unwrap_or_else(|| vec![data.len()]);
    PyTensor::new(data, shape)
}

/// Create identity matrix
/// 単位行列を作成
#[pyfunction]
pub fn eye(n: usize) -> PyResult<PyTensor> {
    let mut data = vec![0.0; n * n];
    for i in 0..n {
        data[i * n + i] = 1.0;
    }
    PyTensor::new(data, vec![n, n])
}