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
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
//! Unified error handling for RusTorch
//! RusTorchの統一エラーハンドリング

use std::fmt;

/// Common result type for RusTorch operations (統一済み)
/// RusTorch操作の共通結果型 (統一済み)
pub type RusTorchResult<T> = crate::error::RusTorchResult<T>;

/// Unified error type for all RusTorch operations
/// 全RusTorch操作の統一エラー型
#[derive(Debug)]
pub enum RusTorchError {
    /// Tensor operation errors
    /// テンソル操作エラー
    TensorError(TensorError),

    /// GPU operation errors
    /// GPU操作エラー
    GpuError(GpuError),

    /// Distributed operation errors
    /// 分散操作エラー
    DistributedError(DistributedError),

    /// Neural network operation errors
    /// ニューラルネットワーク操作エラー
    NeuralNetworkError(NeuralNetworkError),

    /// Optimization errors
    /// 最適化エラー
    OptimizationError(OptimizationError),

    /// Data loading errors
    /// データローディングエラー
    DataError(DataError),

    /// Memory management errors
    /// メモリ管理エラー
    MemoryError(MemoryError),

    /// I/O errors
    /// I/Oエラー
    IoError(std::io::Error),

    /// Generic errors
    /// 汎用エラー
    Generic(String),
}

/// Tensor-specific errors
/// テンソル固有エラー
#[derive(Debug, Clone)]
pub enum TensorError {
    /// Tensor shape mismatch error
    /// テンソル形状不一致エラー
    ShapeMismatch {
        /// Expected shape
        /// 期待される形状
        expected: Vec<usize>,
        /// Actual shape
        /// 実際の形状
        actual: Vec<usize>,
    },
    /// Tensor dimension mismatch error
    /// テンソル次元不一致エラー
    DimensionMismatch {
        /// Left tensor shape
        /// 左テンソルの形状
        lhs: Vec<usize>,
        /// Right tensor shape
        /// 右テンソルの形状
        rhs: Vec<usize>,
    },
    /// Insufficient tensor dimensions error
    /// テンソル次元不足エラー
    InsufficientDimensions {
        /// Required dimensions
        /// 必要な次元数
        required: usize,
        /// Actual dimensions
        /// 実際の次元数
        actual: usize,
    },
    /// Invalid tensor shape
    /// 無効なテンソル形状
    InvalidShape(Vec<usize>),
    /// Invalid tensor index
    /// 無効なテンソルインデックス
    InvalidIndex(Vec<usize>),
    /// Invalid tensor operation
    /// 無効なテンソル操作
    InvalidOperation(String),
    /// Empty tensor error
    /// 空のテンソルエラー
    EmptyTensor,
    /// Data type error
    /// データ型エラー
    DataTypeError(String),
}

/// GPU-specific errors
/// GPU固有エラー
#[derive(Debug, Clone)]
pub enum GpuError {
    /// GPU device not found
    /// GPUデバイスが見つからない
    DeviceNotFound(usize),
    /// GPU device not supported
    /// GPUデバイスがサポートされていない
    DeviceNotSupported(String),
    /// GPU memory allocation failed
    /// GPUメモリ割り当て失敗
    MemoryAllocationFailed(usize),
    /// GPU memory transfer failed
    /// GPUメモリ転送失敗
    MemoryTransferFailed(String),
    /// GPU kernel compilation failed
    /// GPUカーネルコンパイル失敗
    KernelCompilationFailed(String),
    /// GPU kernel execution failed
    /// GPUカーネル実行失敗
    KernelExecutionFailed(String),
    /// GPU context creation failed
    /// GPUコンテキスト作成失敗
    ContextCreationFailed(String),
    /// Invalid GPU device
    /// 無効なGPUデバイス
    InvalidDevice(String),
    /// GPU out of memory
    /// GPUメモリ不足
    OutOfMemory,
    /// GPU driver error
    /// GPUドライバーエラー
    DriverError(String),
}

/// Distributed computing errors
/// 分散コンピューティングエラー
#[derive(Debug, Clone)]
pub enum DistributedError {
    /// Distributed backend not supported
    /// 分散バックエンドがサポートされていない
    BackendNotSupported(String),
    /// Communication failed
    /// 通信失敗
    CommunicationFailed(String),
    /// Process group error
    /// プロセスグループエラー
    ProcessGroupError(String),
    /// Synchronization failed
    /// 同期失敗
    SynchronizationFailed(String),
    /// Node connection failed
    /// ノード接続失敗
    NodeConnectionFailed(String),
    /// Invalid rank
    /// 無効なランク
    InvalidRank(i32),
    /// Invalid world size
    /// 無効なワールドサイズ
    InvalidWorldSize(i32),
    /// Timeout error
    /// タイムアウトエラー
    TimeoutError(String),
    /// Network error
    /// ネットワークエラー
    NetworkError(String),
}

/// Neural network errors
/// ニューラルネットワークエラー
#[derive(Debug, Clone)]
pub enum NeuralNetworkError {
    /// Neural network layer error
    /// ニューラルネットワークレイヤーエラー
    LayerError(String),
    /// Activation function error
    /// 活性化関数エラー
    ActivationError(String),
    /// Loss function error
    /// 損失関数エラー
    LossError(String),
    /// Forward pass error
    /// 順伝播エラー
    ForwardPassError(String),
    /// Backward pass error
    /// 逆伝播エラー
    BackwardPassError(String),
    /// Parameter error
    /// パラメータエラー
    ParameterError(String),
    /// Model error
    /// モデルエラー
    ModelError(String),
}

/// Optimization errors
/// 最適化エラー
#[derive(Debug, Clone)]
pub enum OptimizationError {
    /// Optimizer error
    /// オプティマイザーエラー
    OptimizerError(String),
    /// Learning rate scheduler error
    /// 学習率スケジューラーエラー
    SchedulerError(String),
    /// Gradient calculation error
    /// 勾配計算エラー
    GradientError(String),
    /// Convergence error
    /// 収束エラー
    ConvergenceError(String),
    /// Learning rate error
    /// 学習率エラー
    LearningRateError(String),
}

/// Data loading errors
/// データローディングエラー
#[derive(Debug, Clone)]
pub enum DataError {
    /// Dataset error
    /// データセットエラー
    DatasetError(String),
    /// Data loader error
    /// データローダーエラー
    DataLoaderError(String),
    /// Batch processing error
    /// バッチ処理エラー
    BatchError(String),
    /// Data transformation error
    /// データ変換エラー
    TransformError(String),
    /// File operation error
    /// ファイル操作エラー
    FileError(String),
}

/// Memory management errors
/// メモリ管理エラー
#[derive(Debug, Clone)]
pub enum MemoryError {
    /// Memory allocation failed
    /// メモリ割り当て失敗
    AllocationFailed(usize),
    /// Memory deallocation failed
    /// メモリ解放失敗
    DeallocationFailed(String),
    /// Memory alignment error
    /// メモリアライメントエラー
    AlignmentError(usize),
    /// Memory pool exhausted
    /// メモリプール枯渇
    PoolExhausted,
    /// Invalid memory pointer
    /// 無効なメモリポインタ
    InvalidPointer,
    /// Memory leak detected
    /// メモリリーク検出
    MemoryLeak(String),
}

impl fmt::Display for RusTorchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RusTorchError::TensorError(e) => write!(f, "Tensor error: {}", e),
            RusTorchError::GpuError(e) => write!(f, "GPU error: {}", e),
            RusTorchError::DistributedError(e) => write!(f, "Distributed error: {}", e),
            RusTorchError::NeuralNetworkError(e) => write!(f, "Neural network error: {}", e),
            RusTorchError::OptimizationError(e) => write!(f, "Optimization error: {}", e),
            RusTorchError::DataError(e) => write!(f, "Data error: {}", e),
            RusTorchError::MemoryError(e) => write!(f, "Memory error: {}", e),
            RusTorchError::IoError(e) => write!(f, "I/O error: {}", e),
            RusTorchError::Generic(msg) => write!(f, "Error: {}", msg),
        }
    }
}

impl fmt::Display for TensorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TensorError::ShapeMismatch { expected, actual } => {
                write!(
                    f,
                    "Shape mismatch: expected {:?}, got {:?}",
                    expected, actual
                )
            }
            TensorError::DimensionMismatch { lhs, rhs } => {
                write!(f, "Dimension mismatch: {:?} vs {:?}", lhs, rhs)
            }
            TensorError::InsufficientDimensions { required, actual } => {
                write!(
                    f,
                    "Insufficient dimensions: required {}, got {}",
                    required, actual
                )
            }
            TensorError::InvalidShape(shape) => write!(f, "Invalid shape: {:?}", shape),
            TensorError::InvalidIndex(index) => write!(f, "Invalid index: {:?}", index),
            TensorError::InvalidOperation(op) => write!(f, "Invalid operation: {}", op),
            TensorError::EmptyTensor => write!(f, "Operation on empty tensor"),
            TensorError::DataTypeError(msg) => write!(f, "Data type error: {}", msg),
        }
    }
}

impl fmt::Display for GpuError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GpuError::DeviceNotFound(id) => write!(f, "GPU device {} not found", id),
            GpuError::DeviceNotSupported(device) => {
                write!(f, "GPU device not supported: {}", device)
            }
            GpuError::MemoryAllocationFailed(size) => {
                write!(f, "GPU memory allocation failed: {} bytes", size)
            }
            GpuError::MemoryTransferFailed(msg) => write!(f, "GPU memory transfer failed: {}", msg),
            GpuError::KernelCompilationFailed(msg) => {
                write!(f, "GPU kernel compilation failed: {}", msg)
            }
            GpuError::KernelExecutionFailed(msg) => {
                write!(f, "GPU kernel execution failed: {}", msg)
            }
            GpuError::ContextCreationFailed(msg) => {
                write!(f, "GPU context creation failed: {}", msg)
            }
            GpuError::InvalidDevice(device) => write!(f, "Invalid GPU device: {}", device),
            GpuError::OutOfMemory => write!(f, "GPU out of memory"),
            GpuError::DriverError(msg) => write!(f, "GPU driver error: {}", msg),
        }
    }
}

impl fmt::Display for DistributedError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DistributedError::BackendNotSupported(backend) => {
                write!(f, "Distributed backend not supported: {}", backend)
            }
            DistributedError::CommunicationFailed(msg) => {
                write!(f, "Distributed communication failed: {}", msg)
            }
            DistributedError::ProcessGroupError(msg) => {
                write!(f, "Process group error: {}", msg)
            }
            DistributedError::SynchronizationFailed(msg) => {
                write!(f, "Synchronization failed: {}", msg)
            }
            DistributedError::NodeConnectionFailed(msg) => {
                write!(f, "Node connection failed: {}", msg)
            }
            DistributedError::InvalidRank(rank) => write!(f, "Invalid rank: {}", rank),
            DistributedError::InvalidWorldSize(size) => write!(f, "Invalid world size: {}", size),
            DistributedError::TimeoutError(msg) => write!(f, "Timeout error: {}", msg),
            DistributedError::NetworkError(msg) => write!(f, "Network error: {}", msg),
        }
    }
}

impl fmt::Display for NeuralNetworkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NeuralNetworkError::LayerError(msg) => write!(f, "Layer error: {}", msg),
            NeuralNetworkError::ActivationError(msg) => write!(f, "Activation error: {}", msg),
            NeuralNetworkError::LossError(msg) => write!(f, "Loss error: {}", msg),
            NeuralNetworkError::ForwardPassError(msg) => write!(f, "Forward pass error: {}", msg),
            NeuralNetworkError::BackwardPassError(msg) => write!(f, "Backward pass error: {}", msg),
            NeuralNetworkError::ParameterError(msg) => write!(f, "Parameter error: {}", msg),
            NeuralNetworkError::ModelError(msg) => write!(f, "Model error: {}", msg),
        }
    }
}

impl fmt::Display for OptimizationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OptimizationError::OptimizerError(msg) => write!(f, "Optimizer error: {}", msg),
            OptimizationError::SchedulerError(msg) => write!(f, "Scheduler error: {}", msg),
            OptimizationError::GradientError(msg) => write!(f, "Gradient error: {}", msg),
            OptimizationError::ConvergenceError(msg) => write!(f, "Convergence error: {}", msg),
            OptimizationError::LearningRateError(msg) => write!(f, "Learning rate error: {}", msg),
        }
    }
}

impl fmt::Display for DataError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DataError::DatasetError(msg) => write!(f, "Dataset error: {}", msg),
            DataError::DataLoaderError(msg) => write!(f, "DataLoader error: {}", msg),
            DataError::BatchError(msg) => write!(f, "Batch error: {}", msg),
            DataError::TransformError(msg) => write!(f, "Transform error: {}", msg),
            DataError::FileError(msg) => write!(f, "File error: {}", msg),
        }
    }
}

impl fmt::Display for MemoryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MemoryError::AllocationFailed(size) => {
                write!(f, "Memory allocation failed: {} bytes", size)
            }
            MemoryError::DeallocationFailed(msg) => {
                write!(f, "Memory deallocation failed: {}", msg)
            }
            MemoryError::AlignmentError(alignment) => {
                write!(f, "Memory alignment error: {} bytes", alignment)
            }
            MemoryError::PoolExhausted => write!(f, "Memory pool exhausted"),
            MemoryError::InvalidPointer => write!(f, "Invalid memory pointer"),
            MemoryError::MemoryLeak(msg) => write!(f, "Memory leak detected: {}", msg),
        }
    }
}

impl std::error::Error for RusTorchError {}
impl std::error::Error for TensorError {}
impl std::error::Error for GpuError {}
impl std::error::Error for DistributedError {}
impl std::error::Error for NeuralNetworkError {}
impl std::error::Error for OptimizationError {}
impl std::error::Error for DataError {}
impl std::error::Error for MemoryError {}

// Conversion implementations for backward compatibility
impl From<std::io::Error> for RusTorchError {
    fn from(err: std::io::Error) -> Self {
        RusTorchError::IoError(err)
    }
}

impl From<TensorError> for RusTorchError {
    fn from(err: TensorError) -> Self {
        RusTorchError::TensorError(err)
    }
}

impl From<GpuError> for RusTorchError {
    fn from(err: GpuError) -> Self {
        RusTorchError::GpuError(err)
    }
}

impl From<DistributedError> for RusTorchError {
    fn from(err: DistributedError) -> Self {
        RusTorchError::DistributedError(err)
    }
}

impl From<NeuralNetworkError> for RusTorchError {
    fn from(err: NeuralNetworkError) -> Self {
        RusTorchError::NeuralNetworkError(err)
    }
}

impl From<OptimizationError> for RusTorchError {
    fn from(err: OptimizationError) -> Self {
        RusTorchError::OptimizationError(err)
    }
}

impl From<DataError> for RusTorchError {
    fn from(err: DataError) -> Self {
        RusTorchError::DataError(err)
    }
}

impl From<MemoryError> for RusTorchError {
    fn from(err: MemoryError) -> Self {
        RusTorchError::MemoryError(err)
    }
}

// ParallelError has been unified into RusTorchError - no conversion needed

/// Helper macros for error creation
/// エラー作成用ヘルパーマクロ
/// Macro for creating tensor errors easily
/// テンソルエラーを簡単に作成するためのマクロ
#[macro_export]
macro_rules! tensor_error {
    ($variant:ident) => {
        RusTorchError::TensorError(TensorError::$variant)
    };
    ($variant:ident, $($arg:expr),+) => {
        RusTorchError::TensorError(TensorError::$variant { $($arg),+ })
    };
}

/// Macro for creating GPU errors easily
/// GPUエラーを簡単に作成するためのマクロ
#[macro_export]
macro_rules! gpu_error {
    ($variant:ident) => {
        RusTorchError::GpuError(GpuError::$variant)
    };
    ($variant:ident, $arg:expr) => {
        RusTorchError::GpuError(GpuError::$variant($arg))
    };
}

/// Macro for creating distributed errors easily
/// 分散エラーを簡単に作成するためのマクロ
#[macro_export]
macro_rules! distributed_error {
    ($variant:ident, $arg:expr) => {
        RusTorchError::DistributedError(DistributedError::$variant($arg))
    };
}

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

    #[test]
    fn test_error_display() {
        let tensor_err = RusTorchError::TensorError(TensorError::EmptyTensor);
        assert!(tensor_err.to_string().contains("empty tensor"));

        let gpu_err = RusTorchError::GpuError(GpuError::OutOfMemory);
        assert!(gpu_err.to_string().contains("out of memory"));
    }

    #[test]
    fn test_error_conversion() {
        let tensor_err = TensorError::EmptyTensor;
        let rustorch_err: RusTorchError = tensor_err.into();
        matches!(rustorch_err, RusTorchError::TensorError(_));
    }

    #[test]
    fn test_error_macros() {
        let err = tensor_error!(EmptyTensor);
        matches!(err, RusTorchError::TensorError(TensorError::EmptyTensor));

        let err = gpu_error!(OutOfMemory);
        matches!(err, RusTorchError::GpuError(GpuError::OutOfMemory));
    }
}