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
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
/// GPU Activation Operations
/// GPU活性化演算
use crate::error::{RusTorchError, RusTorchResult};
#[cfg(any(
    feature = "coreml",
    feature = "coreml-hybrid",
    feature = "coreml-fallback"
))]
use crate::gpu::hybrid_executor::HybridExecution;
#[cfg(any(
    feature = "coreml",
    feature = "coreml-hybrid",
    feature = "coreml-fallback"
))]
use crate::gpu::{DeviceType, OpType};
use crate::tensor::Tensor;
use ndarray::ScalarOperand;
use num_traits::{Float, FromPrimitive};

/// GPU activation operations trait
/// GPU活性化演算トレイト
pub trait GpuActivation<T: Float + FromPrimitive + ScalarOperand + 'static> {
    /// GPU ReLU activation
    /// GPU ReLU活性化
    fn gpu_relu(&self) -> RusTorchResult<Tensor<T>>;

    /// GPU Sigmoid activation
    /// GPU Sigmoid活性化
    fn gpu_sigmoid(&self) -> RusTorchResult<Tensor<T>>;

    /// GPU Tanh activation
    /// GPU Tanh活性化
    fn gpu_tanh(&self) -> RusTorchResult<Tensor<T>>;

    /// GPU Softmax activation
    /// GPU Softmax活性化
    fn gpu_softmax(&self, dim: isize) -> RusTorchResult<Tensor<T>>;

    /// GPU GELU activation
    /// GPU GELU活性化
    fn gpu_gelu(&self) -> RusTorchResult<Tensor<T>>;

    /// GPU Leaky ReLU activation
    /// GPU Leaky ReLU活性化
    fn gpu_leaky_relu(&self, negative_slope: f64) -> RusTorchResult<Tensor<T>>;

    /// GPU ELU activation
    /// GPU ELU活性化
    fn gpu_elu(&self, alpha: f64) -> RusTorchResult<Tensor<T>>;

    /// GPU Swish activation
    /// GPU Swish活性化
    fn gpu_swish(&self) -> RusTorchResult<Tensor<T>>;
}

#[cfg(any(
    feature = "coreml",
    feature = "coreml-hybrid",
    feature = "coreml-fallback"
))]
impl<T: Float + FromPrimitive + ScalarOperand + Send + Sync + 'static> GpuActivation<T>
    for Tensor<T>
{
    fn gpu_relu(&self) -> RusTorchResult<Tensor<T>> {
        // Use hybrid execution for CoreML + GPU fallback
        #[cfg(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        ))]
        {
            use crate::gpu::hybrid_executor::HybridExecution;
            use crate::gpu::{coreml::CoreMLActivation, OpType};

            return self.hybrid_operation(OpType::Activation, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML ReLU implementation
                        self.coreml_relu()
                    }
                    super::DeviceType::Cuda(_) => {
                        // CUDA ReLU not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "CUDA ReLU not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Metal(_) => {
                        // Use Metal GPU ReLU implementation
                        self.relu_metal()
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL ReLU not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL ReLU not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback implementation
                        self.relu_fallback()
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for activation".to_string(),
                    )),
                }
            });
        }

        #[cfg(not(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        )))]
        {
            // For non-CoreML builds, use CPU fallback directly
            self.relu_fallback()
        }
    }

    fn gpu_sigmoid(&self) -> RusTorchResult<Tensor<T>> {
        // Use hybrid execution for CoreML + GPU fallback
        #[cfg(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        ))]
        {
            use crate::gpu::hybrid_executor::HybridExecution;
            use crate::gpu::{coreml::CoreMLActivation, OpType};

            return self.hybrid_operation(OpType::Activation, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML Sigmoid implementation
                        self.coreml_sigmoid()
                    }
                    super::DeviceType::Cuda(_) => {
                        // CUDA Sigmoid not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "CUDA Sigmoid not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Metal(_) => {
                        // Use Metal GPU Sigmoid implementation
                        self.sigmoid_metal()
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL Sigmoid not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL Sigmoid not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback
                        self.sigmoid_fallback()
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for activation".to_string(),
                    )),
                }
            });
        }

        #[cfg(not(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        )))]
        {
            // For non-CoreML builds, use CPU fallback directly
            self.sigmoid_fallback()
        }
    }

    fn gpu_tanh(&self) -> RusTorchResult<Tensor<T>> {
        // Use hybrid execution for CoreML + GPU fallback
        #[cfg(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        ))]
        {
            use crate::gpu::hybrid_executor::HybridExecution;
            use crate::gpu::{coreml::CoreMLActivation, OpType};

            return self.hybrid_operation(OpType::Activation, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML Tanh implementation
                        self.coreml_tanh()
                    }
                    super::DeviceType::Cuda(_) => {
                        // CUDA Tanh not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "CUDA Tanh not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Metal(_) => {
                        // Use Metal GPU Tanh implementation
                        self.tanh_metal()
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL Tanh not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL Tanh not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback
                        Ok(self.tanh())
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for activation".to_string(),
                    )),
                }
            });
        }

        #[cfg(not(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        )))]
        {
            // For non-CoreML builds, use CPU fallback directly
            Ok(self.tanh())
        }
    }

    fn gpu_softmax(&self, dim: isize) -> RusTorchResult<Tensor<T>> {
        // Use hybrid execution for CoreML + GPU fallback
        #[cfg(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        ))]
        {
            use crate::gpu::hybrid_executor::HybridExecution;
            use crate::gpu::{coreml::CoreMLActivation, OpType};

            return self.hybrid_operation(OpType::Activation, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML Softmax implementation
                        self.coreml_softmax(dim)
                    }
                    super::DeviceType::Cuda(_) => {
                        // CUDA Softmax not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "CUDA Softmax not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Metal(_) => {
                        // Metal Softmax not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "Metal Softmax not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL Softmax not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL Softmax not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback
                        self.softmax_fallback(dim)
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for activation".to_string(),
                    )),
                }
            });
        }

        #[cfg(not(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        )))]
        {
            // For non-CoreML builds, use CPU fallback directly
            self.softmax_fallback(dim)
        }
    }

    fn gpu_gelu(&self) -> RusTorchResult<Tensor<T>> {
        // Use hybrid execution for CoreML + GPU fallback
        #[cfg(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        ))]
        {
            use crate::gpu::hybrid_executor::HybridExecution;
            use crate::gpu::{coreml::CoreMLActivation, OpType};

            return self.hybrid_operation(OpType::Activation, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML GELU implementation
                        self.coreml_gelu()
                    }
                    super::DeviceType::Cuda(_) => {
                        // CUDA GELU not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "CUDA GELU not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Metal(_) => {
                        // Use Metal GPU GELU implementation
                        self.gelu_metal()
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL GELU not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL GELU not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback
                        self.gelu_fallback()
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for activation".to_string(),
                    )),
                }
            });
        }

        #[cfg(not(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        )))]
        {
            // For non-CoreML builds, use CPU fallback directly
            self.gelu_fallback()
        }
    }

    fn gpu_leaky_relu(&self, negative_slope: f64) -> RusTorchResult<Tensor<T>> {
        // Use hybrid execution for CoreML + GPU fallback
        #[cfg(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        ))]
        {
            use crate::gpu::hybrid_executor::HybridExecution;
            use crate::gpu::{coreml::CoreMLActivation, OpType};

            return self.hybrid_operation(OpType::Activation, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML Leaky ReLU implementation
                        self.coreml_leaky_relu(negative_slope)
                    }
                    super::DeviceType::Cuda(_) => {
                        // CUDA Leaky ReLU not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "CUDA Leaky ReLU not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Metal(_) => {
                        // Use Metal GPU Leaky ReLU implementation
                        self.leaky_relu_metal(negative_slope)
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL Leaky ReLU not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL Leaky ReLU not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback
                        self.leaky_relu_fallback(negative_slope)
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for activation".to_string(),
                    )),
                }
            });
        }

        #[cfg(not(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        )))]
        {
            // For non-CoreML builds, use CPU fallback directly
            self.leaky_relu_fallback(negative_slope)
        }
    }

    fn gpu_elu(&self, alpha: f64) -> RusTorchResult<Tensor<T>> {
        // Use hybrid execution for CoreML + GPU fallback
        #[cfg(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        ))]
        {
            use crate::gpu::hybrid_executor::HybridExecution;
            use crate::gpu::{coreml::CoreMLActivation, OpType};

            return self.hybrid_operation(OpType::Activation, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML ELU implementation
                        self.coreml_elu(alpha)
                    }
                    super::DeviceType::Cuda(_) => {
                        // CUDA ELU not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "CUDA ELU not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Metal(_) => {
                        // Use Metal GPU ELU implementation
                        self.elu_metal(alpha)
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL ELU not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL ELU not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback
                        self.elu_fallback(alpha)
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for activation".to_string(),
                    )),
                }
            });
        }

        #[cfg(not(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        )))]
        {
            // For non-CoreML builds, use CPU fallback directly
            self.elu_fallback(alpha)
        }
    }

    fn gpu_swish(&self) -> RusTorchResult<Tensor<T>> {
        // Use hybrid execution for CoreML + GPU fallback
        #[cfg(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        ))]
        {
            use crate::gpu::hybrid_executor::HybridExecution;
            use crate::gpu::{coreml::CoreMLActivation, OpType};

            return self.hybrid_operation(OpType::Activation, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML Swish implementation
                        self.coreml_swish()
                    }
                    super::DeviceType::Cuda(_) => {
                        // CUDA Swish not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "CUDA Swish not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Metal(_) => {
                        // Use Metal GPU Swish implementation
                        self.swish_metal()
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL Swish not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL Swish not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback
                        self.swish_fallback()
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for activation".to_string(),
                    )),
                }
            });
        }

        #[cfg(not(any(
            feature = "coreml",
            feature = "coreml-hybrid",
            feature = "coreml-fallback"
        )))]
        {
            // For non-CoreML builds, use CPU fallback directly
            self.swish_fallback()
        }
    }
}

// Non-CoreML implementation of GpuActivation trait
// 非CoreML用のGpuActivation trait実装
#[cfg(not(any(
    feature = "coreml",
    feature = "coreml-hybrid",
    feature = "coreml-fallback"
)))]
impl<T: Float + FromPrimitive + ScalarOperand + Send + Sync + 'static> GpuActivation<T>
    for Tensor<T>
{
    fn gpu_relu(&self) -> RusTorchResult<Tensor<T>> {
        self.relu_fallback()
    }

    fn gpu_sigmoid(&self) -> RusTorchResult<Tensor<T>> {
        self.sigmoid_fallback()
    }

    fn gpu_tanh(&self) -> RusTorchResult<Tensor<T>> {
        Ok(self.tanh())
    }

    fn gpu_softmax(&self, dim: isize) -> RusTorchResult<Tensor<T>> {
        self.softmax_fallback(dim)
    }

    fn gpu_gelu(&self) -> RusTorchResult<Tensor<T>> {
        self.gelu_fallback()
    }

    fn gpu_leaky_relu(&self, negative_slope: f64) -> RusTorchResult<Tensor<T>> {
        self.leaky_relu_fallback(negative_slope)
    }

    fn gpu_elu(&self, alpha: f64) -> RusTorchResult<Tensor<T>> {
        self.elu_fallback(alpha)
    }

    fn gpu_swish(&self) -> RusTorchResult<Tensor<T>> {
        self.swish_fallback()
    }
}

// Fallback implementations for tensor activation operations
// テンソル活性化演算のフォールバック実装
impl<T: Float + FromPrimitive + ScalarOperand + Send + Sync + 'static> Tensor<T> {
    /// CPU fallback ReLU implementation
    /// CPU フォールバック ReLU 実装
    pub fn relu_fallback(&self) -> RusTorchResult<Tensor<T>> {
        let result_data = self.data.mapv(|x| x.max(T::zero()));
        Ok(Tensor::from_ndarray(result_data))
    }

    /// CPU fallback Sigmoid implementation
    /// CPU フォールバック Sigmoid 実装
    pub fn sigmoid_fallback(&self) -> RusTorchResult<Tensor<T>> {
        let result_data = self.data.mapv(|x| T::one() / (T::one() + (-x).exp()));
        Ok(Tensor::from_ndarray(result_data))
    }

    /// CPU fallback Softmax implementation
    /// CPU フォールバック Softmax 実装
    pub fn softmax_fallback(&self, dim: isize) -> RusTorchResult<Tensor<T>> {
        // Simple softmax implementation - subtract max for numerical stability
        let max_val = self.data.fold(T::neg_infinity(), |acc, &x| acc.max(x));
        let exp_data = self.data.mapv(|x| (x - max_val).exp());
        let sum = exp_data.sum();
        let result_data = exp_data.mapv(|x| x / sum);
        Ok(Tensor::from_ndarray(result_data))
    }

    /// CPU fallback GELU implementation
    /// CPU フォールバック GELU 実装
    pub fn gelu_fallback(&self) -> RusTorchResult<Tensor<T>> {
        let sqrt_2_pi = T::from(0.7978845608).unwrap(); // sqrt(2/π)
        let result_data = self.data.mapv(|x| {
            let tanh_arg = sqrt_2_pi * (x + T::from(0.044715).unwrap() * x.powi(3));
            T::from(0.5).unwrap() * x * (T::one() + tanh_arg.tanh())
        });
        Ok(Tensor::from_ndarray(result_data))
    }

    /// CPU fallback Leaky ReLU implementation
    /// CPU フォールバック Leaky ReLU 実装
    pub fn leaky_relu_fallback(&self, negative_slope: f64) -> RusTorchResult<Tensor<T>> {
        let slope = T::from(negative_slope).unwrap();
        let result_data = self
            .data
            .mapv(|x| if x > T::zero() { x } else { slope * x });
        Ok(Tensor::from_ndarray(result_data))
    }

    /// CPU fallback ELU implementation
    /// CPU フォールバック ELU 実装
    pub fn elu_fallback(&self, alpha: f64) -> RusTorchResult<Tensor<T>> {
        let alpha_val = T::from(alpha).unwrap();
        let result_data = self.data.mapv(|x| {
            if x > T::zero() {
                x
            } else {
                alpha_val * (x.exp() - T::one())
            }
        });
        Ok(Tensor::from_ndarray(result_data))
    }

    /// CPU fallback Swish implementation
    /// CPU フォールバック Swish 実装
    pub fn swish_fallback(&self) -> RusTorchResult<Tensor<T>> {
        let result_data = self.data.mapv(|x| x / (T::one() + (-x).exp()));
        Ok(Tensor::from_ndarray(result_data))
    }

    /// Metal GPU ReLU implementation
    /// Metal GPU ReLU実装
    #[cfg(feature = "metal")]
    pub fn relu_metal(&self) -> RusTorchResult<Tensor<T>> {
        use crate::gpu::metal_kernels::metal_relu_f32;

        let input_data: Vec<f32> = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap_or(0.0))
            .collect();
        let mut output_data = vec![0.0f32; input_data.len()];

        metal_relu_f32(&input_data, &mut output_data)?;

        let output_tensor_data: Vec<T> = output_data.iter().map(|&x| T::from(x).unwrap()).collect();
        Ok(Tensor::from_vec(output_tensor_data, self.shape().to_vec()))
    }

    /// Metal GPU Sigmoid implementation
    /// Metal GPU Sigmoid実装
    #[cfg(feature = "metal")]
    pub fn sigmoid_metal(&self) -> RusTorchResult<Tensor<T>> {
        use crate::gpu::metal_kernels::metal_sigmoid_f32;

        let input_data: Vec<f32> = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap_or(0.0))
            .collect();
        let mut output_data = vec![0.0f32; input_data.len()];

        metal_sigmoid_f32(&input_data, &mut output_data)?;

        let output_tensor_data: Vec<T> = output_data.iter().map(|&x| T::from(x).unwrap()).collect();
        Ok(Tensor::from_vec(output_tensor_data, self.shape().to_vec()))
    }

    /// Metal GPU Tanh implementation
    /// Metal GPU Tanh実装
    #[cfg(feature = "metal")]
    pub fn tanh_metal(&self) -> RusTorchResult<Tensor<T>> {
        use crate::gpu::metal_kernels::metal_tanh_f32;

        let input_data: Vec<f32> = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap_or(0.0))
            .collect();
        let mut output_data = vec![0.0f32; input_data.len()];

        metal_tanh_f32(&input_data, &mut output_data)?;

        let output_tensor_data: Vec<T> = output_data.iter().map(|&x| T::from(x).unwrap()).collect();
        Ok(Tensor::from_vec(output_tensor_data, self.shape().to_vec()))
    }

    /// Metal GPU GELU implementation
    /// Metal GPU GELU実装
    #[cfg(feature = "metal")]
    pub fn gelu_metal(&self) -> RusTorchResult<Tensor<T>> {
        use crate::gpu::metal_kernels::metal_gelu_f32;

        let input_data: Vec<f32> = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap_or(0.0))
            .collect();
        let mut output_data = vec![0.0f32; input_data.len()];

        metal_gelu_f32(&input_data, &mut output_data)?;

        let output_tensor_data: Vec<T> = output_data.iter().map(|&x| T::from(x).unwrap()).collect();
        Ok(Tensor::from_vec(output_tensor_data, self.shape().to_vec()))
    }

    /// Metal GPU Leaky ReLU implementation
    /// Metal GPU Leaky ReLU実装
    #[cfg(feature = "metal")]
    pub fn leaky_relu_metal(&self, negative_slope: f64) -> RusTorchResult<Tensor<T>> {
        use crate::gpu::metal_kernels::metal_leaky_relu_f32;

        let input_data: Vec<f32> = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap_or(0.0))
            .collect();
        let mut output_data = vec![0.0f32; input_data.len()];

        metal_leaky_relu_f32(&input_data, &mut output_data, negative_slope as f32)?;

        let output_tensor_data: Vec<T> = output_data.iter().map(|&x| T::from(x).unwrap()).collect();
        Ok(Tensor::from_vec(output_tensor_data, self.shape().to_vec()))
    }

    /// Metal GPU ELU implementation
    /// Metal GPU ELU実装
    #[cfg(feature = "metal")]
    pub fn elu_metal(&self, alpha: f64) -> RusTorchResult<Tensor<T>> {
        use crate::gpu::metal_kernels::metal_elu_f32;

        let input_data: Vec<f32> = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap_or(0.0))
            .collect();
        let mut output_data = vec![0.0f32; input_data.len()];

        metal_elu_f32(&input_data, &mut output_data, alpha as f32)?;

        let output_tensor_data: Vec<T> = output_data.iter().map(|&x| T::from(x).unwrap()).collect();
        Ok(Tensor::from_vec(output_tensor_data, self.shape().to_vec()))
    }

    /// Metal GPU Swish implementation
    /// Metal GPU Swish実装
    #[cfg(feature = "metal")]
    pub fn swish_metal(&self) -> RusTorchResult<Tensor<T>> {
        use crate::gpu::metal_kernels::metal_swish_f32;

        let input_data: Vec<f32> = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap_or(0.0))
            .collect();
        let mut output_data = vec![0.0f32; input_data.len()];

        metal_swish_f32(&input_data, &mut output_data)?;

        let output_tensor_data: Vec<T> = output_data.iter().map(|&x| T::from(x).unwrap()).collect();
        Ok(Tensor::from_vec(output_tensor_data, self.shape().to_vec()))
    }

    // Non-Metal fallback implementations for missing Metal methods
    #[cfg(not(feature = "metal"))]
    pub fn relu_metal(&self) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    #[cfg(not(feature = "metal"))]
    pub fn sigmoid_metal(&self) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    #[cfg(not(feature = "metal"))]
    pub fn tanh_metal(&self) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    #[cfg(not(feature = "metal"))]
    pub fn gelu_metal(&self) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    #[cfg(not(feature = "metal"))]
    pub fn leaky_relu_metal(&self, _negative_slope: f64) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    #[cfg(not(feature = "metal"))]
    pub fn elu_metal(&self, _alpha: f64) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    #[cfg(not(feature = "metal"))]
    pub fn swish_metal(&self) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }
}

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

    #[test]
    fn test_gpu_relu_fallback() {
        let data = vec![-1.0, 0.0, 1.0, 2.0];
        let tensor = Tensor::<f32>::from_vec(data, vec![2, 2]);

        let result = tensor.gpu_relu().unwrap();
        let result_data = result.as_slice().unwrap().to_vec();

        assert_eq!(result_data, vec![0.0, 0.0, 1.0, 2.0]);
    }

    #[test]
    fn test_gpu_sigmoid_fallback() {
        let data = vec![0.0, 1.0];
        let tensor = Tensor::<f32>::from_vec(data, vec![2]);

        let result = tensor.gpu_sigmoid().unwrap();
        let result_data = result.as_slice().unwrap().to_vec();

        // Sigmoid(0) = 0.5, Sigmoid(1) ≈ 0.731
        assert!((result_data[0] - 0.5).abs() < 0.001);
        assert!((result_data[1] - 0.731).abs() < 0.01);
    }

    #[test]
    fn test_gpu_tanh_fallback() {
        let data = vec![0.0, 1.0];
        let tensor = Tensor::<f32>::from_vec(data, vec![2]);

        let result = tensor.gpu_tanh().unwrap();
        let result_data = result.as_slice().unwrap().to_vec();

        // Tanh(0) = 0, Tanh(1) ≈ 0.762
        assert!((result_data[0] - 0.0).abs() < 0.001);
        assert!((result_data[1] - 0.762).abs() < 0.01);
    }
}