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
//! GPU Convolution Operations
//! GPU畳み込み演算
//!
//! This module provides GPU-accelerated convolution operations including
//! cuDNN integration for CUDA and Metal Performance Shaders for Apple Silicon.

use crate::backends::ConvolutionParams;
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 Convolution trait for convolution operations with hybrid execution
/// ハイブリッド実行による GPU 畳み込み trait
pub trait GpuConvolution<T: Float + FromPrimitive + ScalarOperand + Send + Sync + 'static> {
    /// GPU-accelerated 2D convolution with automatic device selection
    /// 自動デバイス選択によるGPU加速2D畳み込み
    fn gpu_conv2d(&self, kernel: &Self, params: &ConvolutionParams) -> RusTorchResult<Tensor<T>>;

    /// GPU-accelerated transposed convolution (deconvolution)
    /// GPU加速転置畳み込み(逆畳み込み)
    fn gpu_conv_transpose2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
    ) -> RusTorchResult<Tensor<T>>;

    /// GPU-accelerated depthwise separable convolution
    /// GPU加速深度分離可能畳み込み
    fn gpu_depthwise_conv2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
    ) -> RusTorchResult<Tensor<T>>;

    /// GPU-accelerated grouped convolution
    /// GPU加速グループ畳み込み
    fn gpu_grouped_conv2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
        groups: usize,
    ) -> RusTorchResult<Tensor<T>>;

    /// GPU-accelerated 3D convolution
    /// GPU加速3D畳み込み
    fn gpu_conv3d(&self, kernel: &Self, params: &ConvolutionParams) -> RusTorchResult<Tensor<T>>;
}

#[cfg(any(
    feature = "coreml",
    feature = "coreml-hybrid",
    feature = "coreml-fallback"
))]
impl<T: Float + FromPrimitive + ScalarOperand + Send + Sync + 'static> GpuConvolution<T>
    for Tensor<T>
{
    fn gpu_conv2d(&self, kernel: &Self, params: &ConvolutionParams) -> 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::CoreMLConvolution, OpType};

            return self.hybrid_operation(OpType::Convolution, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // Use CoreML convolution implementation
                        let stride = &[params.stride[0], params.stride[1]];
                        let padding = &[params.padding[0], params.padding[1]];
                        self.coreml_conv2d(kernel, stride, padding)
                    }
                    super::DeviceType::Cuda(_) => {
                        // Use CUDA convolution implementation
                        self.conv2d_cuda(kernel, params)
                    }
                    super::DeviceType::Metal(_) => {
                        // Use actual Metal GPU convolution implementation
                        self.conv2d_metal(kernel, params)
                    }
                    super::DeviceType::OpenCL(_) => {
                        // OpenCL convolution not implemented - return error instead of CPU fallback
                        Err(RusTorchError::UnsupportedOperation(
                            "OpenCL convolution not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback implementation
                        self.conv2d_fallback(kernel, params)
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for convolution".to_string(),
                    )),
                }
            });
        }

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

    fn gpu_conv_transpose2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
    ) -> 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::CoreMLConvolution, OpType};

            return self.hybrid_operation(OpType::Convolution, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // CoreML transpose convolution not yet implemented
                        self.conv_transpose2d_fallback(kernel, params)
                    }
                    super::DeviceType::Cuda(_) => {
                        // Use CUDA transpose convolution implementation - fallback to CPU
                        self.conv_transpose2d_fallback(kernel, params)
                    }
                    super::DeviceType::Metal(_) => {
                        // Metal transpose convolution not yet implemented
                        Err(RusTorchError::UnsupportedOperation(
                            "Metal transpose convolution not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::OpenCL(_) => {
                        // Use OpenCL transpose convolution implementation - fallback to CPU
                        self.conv_transpose2d_fallback(kernel, params)
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback implementation
                        self.conv_transpose2d_fallback(kernel, params)
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for transpose convolution".to_string(),
                    )),
                }
            });
        }

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

    fn gpu_depthwise_conv2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
    ) -> 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::CoreMLConvolution, OpType};

            return self.hybrid_operation(OpType::Convolution, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // CoreML depthwise convolution not yet implemented
                        self.depthwise_conv2d_fallback(kernel, params)
                    }
                    super::DeviceType::Cuda(_) => {
                        // Use CUDA depthwise convolution implementation - fallback to CPU
                        self.depthwise_conv2d_fallback(kernel, params)
                    }
                    super::DeviceType::Metal(_) => {
                        // Metal depthwise convolution not yet implemented
                        Err(RusTorchError::UnsupportedOperation(
                            "Metal depthwise convolution not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::OpenCL(_) => {
                        // Use OpenCL depthwise convolution implementation - fallback to CPU
                        self.depthwise_conv2d_fallback(kernel, params)
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback implementation
                        self.depthwise_conv2d_fallback(kernel, params)
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for depthwise convolution".to_string(),
                    )),
                }
            });
        }

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

    fn gpu_grouped_conv2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
        groups: usize,
    ) -> 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::CoreMLConvolution, OpType};

            return self.hybrid_operation(OpType::Convolution, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // CoreML grouped convolution not yet implemented
                        self.grouped_conv2d_fallback(kernel, params, groups)
                    }
                    super::DeviceType::Cuda(_) => {
                        // Use CUDA grouped convolution implementation - fallback to CPU
                        self.grouped_conv2d_fallback(kernel, params, groups)
                    }
                    super::DeviceType::Metal(_) => {
                        // Metal grouped convolution not yet implemented
                        Err(RusTorchError::UnsupportedOperation(
                            "Metal grouped convolution not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::OpenCL(_) => {
                        // Use OpenCL grouped convolution implementation - fallback to CPU
                        self.grouped_conv2d_fallback(kernel, params, groups)
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback implementation
                        self.grouped_conv2d_fallback(kernel, params, groups)
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for grouped convolution".to_string(),
                    )),
                }
            });
        }

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

    fn gpu_conv3d(&self, kernel: &Self, params: &ConvolutionParams) -> 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::CoreMLConvolution, OpType};

            return self.hybrid_operation(OpType::Convolution, |device| {
                match device {
                    super::DeviceType::CoreML(_) => {
                        // CoreML 3D convolution not yet implemented
                        self.conv3d_fallback(kernel, params)
                    }
                    super::DeviceType::Cuda(_) => {
                        // Use CUDA 3D convolution implementation - fallback to CPU
                        self.conv3d_fallback(kernel, params)
                    }
                    super::DeviceType::Metal(_) => {
                        // Metal 3D convolution not yet implemented
                        Err(RusTorchError::UnsupportedOperation(
                            "Metal 3D convolution not yet implemented".to_string(),
                        ))
                    }
                    super::DeviceType::OpenCL(_) => {
                        // Use OpenCL 3D convolution implementation - fallback to CPU
                        self.conv3d_fallback(kernel, params)
                    }
                    super::DeviceType::Cpu => {
                        // CPU fallback implementation
                        self.conv3d_fallback(kernel, params)
                    }
                    _ => Err(RusTorchError::UnsupportedDevice(
                        "Unsupported device for 3D convolution".to_string(),
                    )),
                }
            });
        }

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

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

    fn gpu_conv_transpose2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
    ) -> RusTorchResult<Tensor<T>> {
        self.conv_transpose2d_fallback(kernel, params)
    }

    fn gpu_depthwise_conv2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
    ) -> RusTorchResult<Tensor<T>> {
        self.depthwise_conv2d_fallback(kernel, params)
    }

    fn gpu_grouped_conv2d(
        &self,
        kernel: &Self,
        params: &ConvolutionParams,
        groups: usize,
    ) -> RusTorchResult<Tensor<T>> {
        self.grouped_conv2d_fallback(kernel, params, groups)
    }

    fn gpu_conv3d(&self, kernel: &Self, params: &ConvolutionParams) -> RusTorchResult<Tensor<T>> {
        self.conv3d_fallback(kernel, params)
    }
}

// Fallback implementations for convolution operations
// 畳み込み演算のフォールバック実装
impl<T: Float + FromPrimitive + ScalarOperand + Send + Sync + 'static> Tensor<T> {
    fn conv2d_fallback(&self, kernel: &Self, params: &ConvolutionParams) -> RusTorchResult<Self> {
        // Try Metal implementation first if available
        #[cfg(feature = "metal")]
        {
            return self.conv2d_metal(kernel, params);
        }

        #[cfg(not(feature = "metal"))]
        {
            // CPU fallback implementation
            let output_height = (self.shape()[2] + 2 * params.padding[0] - kernel.shape()[2])
                / params.stride[0]
                + 1;
            let output_width = (self.shape()[3] + 2 * params.padding[1] - kernel.shape()[3])
                / params.stride[1]
                + 1;

            // Simple placeholder implementation
            let output_size = self.shape()[0] * kernel.shape()[0] * output_height * output_width;
            let output_data = vec![T::zero(); output_size];

            // Create output tensor shape: [batch, output_channels, output_height, output_width]
            let output_shape = vec![
                self.shape()[0],
                kernel.shape()[0],
                output_height,
                output_width,
            ];

            Ok(Tensor::from_vec(output_data, output_shape))
        }
    }

    /// Metal GPU convolution implementation
    /// Metal GPU 畳み込み実装
    #[cfg(feature = "metal")]
    fn conv2d_metal(&self, kernel: &Self, params: &ConvolutionParams) -> RusTorchResult<Self> {
        use crate::gpu::metal_kernels::metal_conv2d_f32;

        // Convert tensors to f32 for Metal kernel
        let input_data = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap())
            .collect::<Vec<f32>>();
        let kernel_data = kernel
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap())
            .collect::<Vec<f32>>();

        // Get tensor dimensions
        let input_shape = self.data.shape();
        let kernel_shape = kernel.data.shape();

        if input_shape.len() != 4 || kernel_shape.len() != 4 {
            return Err(RusTorchError::InvalidOperation {
                operation: "conv2d_metal".to_string(),
                message: "Input and kernel must be 4D tensors [N, C, H, W]".to_string(),
            });
        }

        let batch_size = input_shape[0];
        let input_channels = input_shape[1];
        let input_height = input_shape[2];
        let input_width = input_shape[3];

        let output_channels = kernel_shape[0];
        let kernel_height = kernel_shape[2];
        let kernel_width = kernel_shape[3];

        // Calculate output dimensions
        let output_height =
            (input_height + 2 * params.padding[0] - kernel_height) / params.stride[0] + 1;
        let output_width =
            (input_width + 2 * params.padding[1] - kernel_width) / params.stride[1] + 1;

        let output_size = batch_size * output_channels * output_height * output_width;
        let mut output_data = vec![0.0f32; output_size];

        // Process each batch
        for batch in 0..batch_size {
            let input_batch_start = batch * input_channels * input_height * input_width;
            let input_batch_end = input_batch_start + input_channels * input_height * input_width;
            let input_batch = &input_data[input_batch_start..input_batch_end];

            let output_batch_start = batch * output_channels * output_height * output_width;
            let output_batch_end =
                output_batch_start + output_channels * output_height * output_width;
            let output_batch = &mut output_data[output_batch_start..output_batch_end];

            // Call Metal convolution
            metal_conv2d_f32(
                input_batch,
                &kernel_data,
                output_batch,
                input_height,
                input_width,
                input_channels,
                output_channels,
                kernel_height,
                kernel_width,
                params.stride[0],
                params.stride[1],
                params.padding[0],
                params.padding[1],
            )
            .map_err(|e| RusTorchError::InvalidOperation {
                operation: "conv2d_metal".to_string(),
                message: format!("Metal convolution failed: {}", e),
            })?;
        }

        // Convert result back to tensor
        let result_data: Vec<T> = output_data
            .into_iter()
            .map(|x| T::from_f32(x).unwrap())
            .collect();

        let output_shape = vec![batch_size, output_channels, output_height, output_width];

        Ok(Tensor::from_vec(result_data, output_shape))
    }

    #[cfg(not(feature = "metal"))]
    fn conv2d_metal(&self, _kernel: &Self, _params: &ConvolutionParams) -> RusTorchResult<Self> {
        Err(RusTorchError::UnsupportedDevice(
            "Metal not available".to_string(),
        ))
    }

    /// CUDA GPU convolution implementation
    /// CUDA GPU畳み込み実装
    #[cfg(feature = "cuda")]
    fn conv2d_cuda(&self, kernel: &Self, params: &ConvolutionParams) -> RusTorchResult<Self> {
        use crate::gpu::cuda_kernels::cuda_conv2d_f32;

        // Convert tensors to f32 for CUDA kernel
        let input_data = self
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap())
            .collect::<Vec<f32>>();
        let kernel_data = kernel
            .data
            .iter()
            .map(|&x| x.to_f32().unwrap())
            .collect::<Vec<f32>>();

        // Get tensor dimensions
        let input_shape = self.data.shape();
        let kernel_shape = kernel.data.shape();

        if input_shape.len() != 4 || kernel_shape.len() != 4 {
            return Err(RusTorchError::InvalidOperation {
                operation: "conv2d_cuda".to_string(),
                message: "Input and kernel must be 4D tensors [N, C, H, W]".to_string(),
            });
        }

        let batch_size = input_shape[0];
        let input_channels = input_shape[1];
        let input_height = input_shape[2];
        let input_width = input_shape[3];

        let output_channels = kernel_shape[0];
        let kernel_height = kernel_shape[2];
        let kernel_width = kernel_shape[3];

        // Calculate output dimensions
        let output_height =
            (input_height + 2 * params.padding[0] - kernel_height) / params.stride[0] + 1;
        let output_width =
            (input_width + 2 * params.padding[1] - kernel_width) / params.stride[1] + 1;

        let output_size = batch_size * output_channels * output_height * output_width;
        let mut output_data = vec![0.0f32; output_size];

        // Process each batch
        for b in 0..batch_size {
            let batch_input_start = b * input_channels * input_height * input_width;
            let batch_input_end = batch_input_start + input_channels * input_height * input_width;
            let batch_input = &input_data[batch_input_start..batch_input_end];

            let batch_output_start = b * output_channels * output_height * output_width;
            let batch_output_end =
                batch_output_start + output_channels * output_height * output_width;
            let batch_output = &mut output_data[batch_output_start..batch_output_end];

            // Call CUDA convolution for this batch
            cuda_conv2d_f32(
                batch_input,
                &kernel_data,
                batch_output,
                input_height,
                input_width,
                input_channels,
                output_channels,
                kernel_height,
                kernel_width,
                params.stride[0],
                params.stride[1],
                params.padding[0],
                params.padding[1],
            )
            .map_err(|e| RusTorchError::InvalidOperation {
                operation: "conv2d_cuda".to_string(),
                message: format!("CUDA convolution failed: {}", e),
            })?;
        }

        // Convert result back to tensor
        let result_data: Vec<T> = output_data
            .into_iter()
            .map(|x| T::from_f32(x).unwrap())
            .collect();

        let output_shape = vec![batch_size, output_channels, output_height, output_width];

        Ok(Tensor::from_vec(result_data, output_shape))
    }

    #[cfg(not(feature = "cuda"))]
    fn conv2d_cuda(&self, _kernel: &Self, _params: &ConvolutionParams) -> RusTorchResult<Self> {
        Err(RusTorchError::UnsupportedDevice(
            "CUDA not available".to_string(),
        ))
    }

    /// CPU fallback transpose convolution implementation
    /// CPU フォールバック転置畳み込み実装
    pub fn conv_transpose2d_fallback(
        &self,
        _kernel: &Self,
        _params: &ConvolutionParams,
    ) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::TensorOp {
            message: "Transpose convolution fallback not yet implemented".to_string(),
            source: None,
        })
    }

    /// CPU fallback depthwise convolution implementation
    /// CPU フォールバック深度分離畳み込み実装
    pub fn depthwise_conv2d_fallback(
        &self,
        _kernel: &Self,
        _params: &ConvolutionParams,
    ) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::TensorOp {
            message: "Depthwise convolution fallback not yet implemented".to_string(),
            source: None,
        })
    }

    /// CPU fallback grouped convolution implementation
    /// CPU フォールバック グループ畳み込み実装
    pub fn grouped_conv2d_fallback(
        &self,
        _kernel: &Self,
        _params: &ConvolutionParams,
        _groups: usize,
    ) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::TensorOp {
            message: "Grouped convolution fallback not yet implemented".to_string(),
            source: None,
        })
    }

    /// CPU fallback 3D convolution implementation
    /// CPU フォールバック 3D 畳み込み実装
    pub fn conv3d_fallback(
        &self,
        _kernel: &Self,
        _params: &ConvolutionParams,
    ) -> RusTorchResult<Tensor<T>> {
        Err(RusTorchError::TensorOp {
            message: "3D convolution fallback not yet implemented".to_string(),
            source: None,
        })
    }
}

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

    #[test]
    fn test_conv2d_fallback_basic() {
        // Create a simple 2x2 input with 1 channel
        let input_data = vec![1.0, 2.0, 3.0, 4.0];
        let input = Tensor::<f32>::from_vec(input_data, vec![1, 1, 2, 2]);

        // Create a 2x2 kernel
        let kernel_data = vec![1.0, 0.0, 0.0, 1.0];
        let kernel = Tensor::<f32>::from_vec(kernel_data, vec![1, 1, 2, 2]);

        let params = ConvolutionParams {
            kernel_size: vec![2, 2],
            stride: vec![1, 1],
            padding: vec![0, 0],
            dilation: vec![1, 1],
            groups: 1,
        };

        let result = input.conv2d_fallback(&kernel, &params).unwrap();
        let result_shape = result.shape();

        // Output should be 1x1x1x1 with value 5.0 (1*1 + 4*1)
        assert_eq!(result_shape, &[1, 1, 1, 1]);
        assert_eq!(result.as_slice().unwrap()[0], 5.0);
    }

    #[test]
    fn test_gpu_conv2d_fallback() {
        let input_data = vec![1.0, 2.0, 3.0, 4.0];
        let input = Tensor::<f32>::from_vec(input_data, vec![1, 1, 2, 2]);

        let kernel_data = vec![1.0, 0.0, 0.0, 1.0];
        let kernel = Tensor::<f32>::from_vec(kernel_data, vec![1, 1, 2, 2]);

        let params = ConvolutionParams {
            kernel_size: vec![2, 2],
            stride: vec![1, 1],
            padding: vec![0, 0],
            dilation: vec![1, 1],
            groups: 1,
        };

        // Should fallback to CPU implementation
        let result = input.gpu_conv2d(&kernel, &params).unwrap();
        let result_shape = result.shape();

        assert_eq!(result_shape, &[1, 1, 1, 1]);
        assert_eq!(result.as_slice().unwrap()[0], 5.0);
    }
}