torsh-backend 0.1.2

Backend abstraction layer for ToRSh
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
//! Convolution operations for all backends
//!
//! This module provides a unified interface for convolution operations across all backends,
//! with optimized implementations for each platform including direct convolution,
//! Winograd algorithm, FFT-based convolution, and im2col-based approaches.

use crate::{BackendResult, Buffer, Device};
use torsh_core::dtype::DType;

#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, vec::Vec};

/// Convolution operation type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConvolutionType {
    /// 1D convolution
    Conv1D,
    /// 2D convolution (most common)
    Conv2D,
    /// 3D convolution
    Conv3D,
    /// Depthwise convolution
    DepthwiseConv2D,
    /// Separable convolution
    SeparableConv2D,
    /// Transposed convolution (deconvolution)
    ConvTranspose2D,
    /// Dilated convolution
    DilatedConv2D,
    /// Grouped convolution
    GroupedConv2D,
}

/// Convolution algorithm implementation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConvolutionAlgorithm {
    /// Auto-select best algorithm
    Auto,
    /// Direct convolution implementation
    Direct,
    /// Im2col + GEMM approach
    Im2col,
    /// Winograd algorithm for small kernels
    Winograd,
    /// FFT-based convolution for large kernels
    FftBased,
    /// Optimized backend-specific implementation
    Optimized,
}

/// Padding mode for convolution
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaddingMode {
    /// No padding
    Valid,
    /// Zero padding to maintain output size
    Same,
    /// Custom padding
    Custom,
}

/// Convolution configuration
#[derive(Debug, Clone)]
pub struct ConvolutionConfig {
    /// Convolution type
    pub conv_type: ConvolutionType,
    /// Input dimensions [batch, channels, height, width] for 2D
    pub input_dims: Vec<usize>,
    /// Output dimensions [batch, channels, height, width] for 2D
    pub output_dims: Vec<usize>,
    /// Kernel dimensions [out_channels, in_channels, height, width] for 2D
    pub kernel_dims: Vec<usize>,
    /// Stride in each dimension
    pub strides: Vec<usize>,
    /// Padding in each dimension
    pub padding: Vec<usize>,
    /// Dilation in each dimension
    pub dilation: Vec<usize>,
    /// Number of groups for grouped convolution
    pub groups: usize,
    /// Padding mode
    pub padding_mode: PaddingMode,
    /// Data type
    pub dtype: DType,
    /// Preferred algorithm
    pub algorithm: ConvolutionAlgorithm,
}

impl ConvolutionConfig {
    /// Create a new 2D convolution configuration
    pub fn conv2d(
        batch_size: usize,
        in_channels: usize,
        out_channels: usize,
        input_size: (usize, usize),
        kernel_size: (usize, usize),
        stride: (usize, usize),
        padding: (usize, usize),
    ) -> Self {
        let (in_h, in_w) = input_size;
        let (k_h, k_w) = kernel_size;
        let (s_h, s_w) = stride;
        let (p_h, p_w) = padding;

        // Calculate output dimensions
        let out_h = (in_h + 2 * p_h - k_h) / s_h + 1;
        let out_w = (in_w + 2 * p_w - k_w) / s_w + 1;

        Self {
            conv_type: ConvolutionType::Conv2D,
            input_dims: vec![batch_size, in_channels, in_h, in_w],
            output_dims: vec![batch_size, out_channels, out_h, out_w],
            kernel_dims: vec![out_channels, in_channels, k_h, k_w],
            strides: vec![s_h, s_w],
            padding: vec![p_h, p_w],
            dilation: vec![1, 1],
            groups: 1,
            padding_mode: PaddingMode::Custom,
            dtype: DType::F32,
            algorithm: ConvolutionAlgorithm::Auto,
        }
    }

    /// Create a depthwise convolution configuration
    pub fn depthwise_conv2d(
        batch_size: usize,
        channels: usize,
        input_size: (usize, usize),
        kernel_size: (usize, usize),
        stride: (usize, usize),
        padding: (usize, usize),
    ) -> Self {
        let mut config = Self::conv2d(
            batch_size,
            channels,
            channels,
            input_size,
            kernel_size,
            stride,
            padding,
        );
        config.conv_type = ConvolutionType::DepthwiseConv2D;
        config.groups = channels;
        config.kernel_dims = vec![channels, 1, kernel_size.0, kernel_size.1];
        config
    }

    /// Set the algorithm preference
    pub fn with_algorithm(mut self, algorithm: ConvolutionAlgorithm) -> Self {
        self.algorithm = algorithm;
        self
    }

    /// Set the data type
    pub fn with_dtype(mut self, dtype: DType) -> Self {
        self.dtype = dtype;
        self
    }

    /// Set dilation
    pub fn with_dilation(mut self, dilation: Vec<usize>) -> Self {
        self.dilation = dilation;
        self
    }

    /// Calculate total input elements
    pub fn input_elements(&self) -> usize {
        self.input_dims.iter().product()
    }

    /// Calculate total output elements
    pub fn output_elements(&self) -> usize {
        self.output_dims.iter().product()
    }

    /// Calculate total kernel elements
    pub fn kernel_elements(&self) -> usize {
        self.kernel_dims.iter().product()
    }

    /// Get input buffer size in bytes
    pub fn input_buffer_size(&self) -> usize {
        let element_size = match self.dtype {
            DType::F32 => 4,
            DType::F64 => 8,
            DType::F16 => 2,
            _ => 4,
        };
        self.input_elements() * element_size
    }

    /// Get output buffer size in bytes
    pub fn output_buffer_size(&self) -> usize {
        let element_size = match self.dtype {
            DType::F32 => 4,
            DType::F64 => 8,
            DType::F16 => 2,
            _ => 4,
        };
        self.output_elements() * element_size
    }

    /// Get kernel buffer size in bytes
    pub fn kernel_buffer_size(&self) -> usize {
        let element_size = match self.dtype {
            DType::F32 => 4,
            DType::F64 => 8,
            DType::F16 => 2,
            _ => 4,
        };
        self.kernel_elements() * element_size
    }

    /// Check if the configuration is valid
    pub fn is_valid(&self) -> bool {
        !self.input_dims.is_empty()
            && !self.output_dims.is_empty()
            && !self.kernel_dims.is_empty()
            && self.input_dims.iter().all(|&d| d > 0)
            && self.output_dims.iter().all(|&d| d > 0)
            && self.kernel_dims.iter().all(|&d| d > 0)
            && self.groups > 0
    }
}

/// Convolution operations trait
#[async_trait::async_trait]
pub trait ConvolutionOps: Send + Sync {
    /// Execute a convolution operation
    async fn convolution(
        &self,
        device: &Device,
        input: &Buffer,
        kernel: &Buffer,
        bias: Option<&Buffer>,
        output: &Buffer,
        config: &ConvolutionConfig,
    ) -> BackendResult<()>;

    /// Execute a 2D convolution
    async fn conv2d(
        &self,
        device: &Device,
        input: &Buffer,
        kernel: &Buffer,
        bias: Option<&Buffer>,
        output: &Buffer,
        stride: (usize, usize),
        padding: (usize, usize),
        dilation: (usize, usize),
    ) -> BackendResult<()>;

    /// Execute a depthwise convolution
    async fn depthwise_conv2d(
        &self,
        device: &Device,
        input: &Buffer,
        kernel: &Buffer,
        bias: Option<&Buffer>,
        output: &Buffer,
        stride: (usize, usize),
        padding: (usize, usize),
    ) -> BackendResult<()>;

    /// Execute a transposed convolution
    async fn conv_transpose2d(
        &self,
        device: &Device,
        input: &Buffer,
        kernel: &Buffer,
        bias: Option<&Buffer>,
        output: &Buffer,
        stride: (usize, usize),
        padding: (usize, usize),
        output_padding: (usize, usize),
    ) -> BackendResult<()>;

    /// Execute a grouped convolution
    async fn grouped_conv2d(
        &self,
        device: &Device,
        input: &Buffer,
        kernel: &Buffer,
        bias: Option<&Buffer>,
        output: &Buffer,
        groups: usize,
        stride: (usize, usize),
        padding: (usize, usize),
    ) -> BackendResult<()>;

    /// Get the best algorithm for given configuration
    fn select_algorithm(&self, config: &ConvolutionConfig) -> ConvolutionAlgorithm;

    /// Check if convolution operations are supported
    fn supports_convolution(&self) -> bool;

    /// Get supported convolution types
    fn supported_conv_types(&self) -> Vec<ConvolutionType>;

    /// Get supported algorithms
    fn supported_algorithms(&self) -> Vec<ConvolutionAlgorithm>;
}

/// Performance characteristics for algorithm selection
#[derive(Debug, Clone)]
pub struct ConvolutionPerformanceHints {
    /// Optimal algorithm for small kernels (3x3, 5x5)
    pub small_kernel_algorithm: ConvolutionAlgorithm,
    /// Optimal algorithm for large kernels (7x7, 9x9+)
    pub large_kernel_algorithm: ConvolutionAlgorithm,
    /// Threshold for switching to FFT-based convolution
    pub fft_threshold: usize,
    /// Threshold for using Winograd algorithm
    pub winograd_threshold: usize,
    /// Preferred tile size for tiled algorithms
    pub tile_size: (usize, usize),
    /// Memory bandwidth in GB/s
    pub memory_bandwidth: f32,
    /// Compute throughput in GOPS
    pub compute_throughput: f32,
}

impl Default for ConvolutionPerformanceHints {
    fn default() -> Self {
        Self {
            small_kernel_algorithm: ConvolutionAlgorithm::Winograd,
            large_kernel_algorithm: ConvolutionAlgorithm::FftBased,
            fft_threshold: 7,
            winograd_threshold: 6,
            tile_size: (16, 16),
            memory_bandwidth: 50.0,
            compute_throughput: 100.0,
        }
    }
}

/// Default convolution operations implementation
pub struct DefaultConvolutionOps {
    performance_hints: ConvolutionPerformanceHints,
}

impl DefaultConvolutionOps {
    pub fn new() -> Self {
        Self {
            performance_hints: ConvolutionPerformanceHints::default(),
        }
    }

    pub fn with_performance_hints(mut self, hints: ConvolutionPerformanceHints) -> Self {
        self.performance_hints = hints;
        self
    }
}

#[async_trait::async_trait]
impl ConvolutionOps for DefaultConvolutionOps {
    async fn convolution(
        &self,
        _device: &Device,
        _input: &Buffer,
        _kernel: &Buffer,
        _bias: Option<&Buffer>,
        _output: &Buffer,
        _config: &ConvolutionConfig,
    ) -> BackendResult<()> {
        Err(torsh_core::error::TorshError::BackendError(
            "Convolution operations not implemented for this backend".to_string(),
        ))
    }

    async fn conv2d(
        &self,
        _device: &Device,
        _input: &Buffer,
        _kernel: &Buffer,
        _bias: Option<&Buffer>,
        _output: &Buffer,
        _stride: (usize, usize),
        _padding: (usize, usize),
        _dilation: (usize, usize),
    ) -> BackendResult<()> {
        Err(torsh_core::error::TorshError::BackendError(
            "Conv2D operations not implemented for this backend".to_string(),
        ))
    }

    async fn depthwise_conv2d(
        &self,
        _device: &Device,
        _input: &Buffer,
        _kernel: &Buffer,
        _bias: Option<&Buffer>,
        _output: &Buffer,
        _stride: (usize, usize),
        _padding: (usize, usize),
    ) -> BackendResult<()> {
        Err(torsh_core::error::TorshError::BackendError(
            "Depthwise convolution not implemented for this backend".to_string(),
        ))
    }

    async fn conv_transpose2d(
        &self,
        _device: &Device,
        _input: &Buffer,
        _kernel: &Buffer,
        _bias: Option<&Buffer>,
        _output: &Buffer,
        _stride: (usize, usize),
        _padding: (usize, usize),
        _output_padding: (usize, usize),
    ) -> BackendResult<()> {
        Err(torsh_core::error::TorshError::BackendError(
            "Transposed convolution not implemented for this backend".to_string(),
        ))
    }

    async fn grouped_conv2d(
        &self,
        _device: &Device,
        _input: &Buffer,
        _kernel: &Buffer,
        _bias: Option<&Buffer>,
        _output: &Buffer,
        _groups: usize,
        _stride: (usize, usize),
        _padding: (usize, usize),
    ) -> BackendResult<()> {
        Err(torsh_core::error::TorshError::BackendError(
            "Grouped convolution not implemented for this backend".to_string(),
        ))
    }

    fn select_algorithm(&self, config: &ConvolutionConfig) -> ConvolutionAlgorithm {
        if config.algorithm != ConvolutionAlgorithm::Auto {
            return config.algorithm;
        }

        // Auto-select based on kernel size and configuration
        match config.conv_type {
            ConvolutionType::Conv2D => {
                if config.kernel_dims.len() >= 4 {
                    let kernel_h = config.kernel_dims[2];
                    let kernel_w = config.kernel_dims[3];
                    let kernel_size = kernel_h.max(kernel_w);

                    if kernel_size <= self.performance_hints.winograd_threshold {
                        ConvolutionAlgorithm::Winograd
                    } else if kernel_size >= self.performance_hints.fft_threshold {
                        ConvolutionAlgorithm::FftBased
                    } else {
                        ConvolutionAlgorithm::Im2col
                    }
                } else {
                    ConvolutionAlgorithm::Direct
                }
            }
            ConvolutionType::DepthwiseConv2D => ConvolutionAlgorithm::Direct,
            ConvolutionType::SeparableConv2D => ConvolutionAlgorithm::Direct,
            _ => ConvolutionAlgorithm::Im2col,
        }
    }

    fn supports_convolution(&self) -> bool {
        false
    }

    fn supported_conv_types(&self) -> Vec<ConvolutionType> {
        vec![]
    }

    fn supported_algorithms(&self) -> Vec<ConvolutionAlgorithm> {
        vec![ConvolutionAlgorithm::Direct]
    }
}

impl Default for DefaultConvolutionOps {
    fn default() -> Self {
        Self::new()
    }
}

/// Convolution algorithm implementations
pub mod algorithms {
    use super::*;

    /// Direct convolution implementation
    pub struct DirectConvolution;

    impl DirectConvolution {
        /// Perform 2D convolution using direct approach
        pub fn conv2d_direct(
            input: &[f32],
            kernel: &[f32],
            output: &mut [f32],
            input_dims: &[usize],
            kernel_dims: &[usize],
            output_dims: &[usize],
            stride: (usize, usize),
            padding: (usize, usize),
        ) -> BackendResult<()> {
            let (batch, in_channels, in_h, in_w) =
                (input_dims[0], input_dims[1], input_dims[2], input_dims[3]);
            let (out_channels, _, k_h, k_w) = (
                kernel_dims[0],
                kernel_dims[1],
                kernel_dims[2],
                kernel_dims[3],
            );
            let (_, _, out_h, out_w) = (
                output_dims[0],
                output_dims[1],
                output_dims[2],
                output_dims[3],
            );
            let (s_h, s_w) = stride;
            let (p_h, p_w) = padding;

            for b in 0..batch {
                for oc in 0..out_channels {
                    for oh in 0..out_h {
                        for ow in 0..out_w {
                            let mut sum = 0.0;

                            for ic in 0..in_channels {
                                for kh in 0..k_h {
                                    for kw in 0..k_w {
                                        let ih = oh * s_h + kh;
                                        let iw = ow * s_w + kw;

                                        if ih >= p_h
                                            && iw >= p_w
                                            && ih < in_h + p_h
                                            && iw < in_w + p_w
                                        {
                                            let input_h = ih - p_h;
                                            let input_w = iw - p_w;

                                            if input_h < in_h && input_w < in_w {
                                                let input_idx = b * in_channels * in_h * in_w
                                                    + ic * in_h * in_w
                                                    + input_h * in_w
                                                    + input_w;
                                                let kernel_idx = oc * in_channels * k_h * k_w
                                                    + ic * k_h * k_w
                                                    + kh * k_w
                                                    + kw;

                                                sum += input[input_idx] * kernel[kernel_idx];
                                            }
                                        }
                                    }
                                }
                            }

                            let output_idx = b * out_channels * out_h * out_w
                                + oc * out_h * out_w
                                + oh * out_w
                                + ow;
                            output[output_idx] = sum;
                        }
                    }
                }
            }

            Ok(())
        }
    }

    /// Im2col convolution implementation
    pub struct Im2colConvolution;

    impl Im2colConvolution {
        /// Convert input to column matrix for GEMM-based convolution
        pub fn im2col(
            input: &[f32],
            output: &mut [f32],
            input_dims: &[usize],
            kernel_size: (usize, usize),
            stride: (usize, usize),
            padding: (usize, usize),
        ) -> BackendResult<()> {
            let (batch, channels, height, width) =
                (input_dims[0], input_dims[1], input_dims[2], input_dims[3]);
            let (k_h, k_w) = kernel_size;
            let (s_h, s_w) = stride;
            let (p_h, p_w) = padding;

            let out_h = (height + 2 * p_h - k_h) / s_h + 1;
            let out_w = (width + 2 * p_w - k_w) / s_w + 1;

            for b in 0..batch {
                for c in 0..channels {
                    for kh in 0..k_h {
                        for kw in 0..k_w {
                            for oh in 0..out_h {
                                for ow in 0..out_w {
                                    let ih = oh * s_h + kh;
                                    let iw = ow * s_w + kw;

                                    let value = if ih >= p_h
                                        && iw >= p_w
                                        && ih < height + p_h
                                        && iw < width + p_w
                                    {
                                        let input_h = ih - p_h;
                                        let input_w = iw - p_w;

                                        if input_h < height && input_w < width {
                                            let input_idx = b * channels * height * width
                                                + c * height * width
                                                + input_h * width
                                                + input_w;
                                            input[input_idx]
                                        } else {
                                            0.0
                                        }
                                    } else {
                                        0.0
                                    };

                                    let col_idx =
                                        (b * channels * k_h * k_w + c * k_h * k_w + kh * k_w + kw)
                                            * out_h
                                            * out_w
                                            + oh * out_w
                                            + ow;

                                    if col_idx < output.len() {
                                        output[col_idx] = value;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Ok(())
        }
    }

    /// Winograd convolution implementation
    pub struct WinogradConvolution;

    impl WinogradConvolution {
        /// Check if Winograd can be applied
        pub fn can_apply(kernel_size: (usize, usize), stride: (usize, usize)) -> bool {
            let (k_h, k_w) = kernel_size;
            let (s_h, s_w) = stride;

            // Winograd is most effective for 3x3 kernels with stride 1
            k_h == 3 && k_w == 3 && s_h == 1 && s_w == 1
        }

        /// Perform Winograd convolution (simplified F(2,3) implementation)
        pub fn conv2d_winograd(
            input: &[f32],
            kernel: &[f32],
            output: &mut [f32],
            input_dims: &[usize],
            kernel_dims: &[usize],
            output_dims: &[usize],
        ) -> BackendResult<()> {
            // For now, fall back to direct convolution
            // A full Winograd implementation would involve complex matrix transformations
            DirectConvolution::conv2d_direct(
                input,
                kernel,
                output,
                input_dims,
                kernel_dims,
                output_dims,
                (1, 1),
                (1, 1),
            )
        }
    }
}

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

    #[test]
    fn test_convolution_config_creation() {
        let config = ConvolutionConfig::conv2d(1, 3, 16, (32, 32), (3, 3), (1, 1), (1, 1));

        assert_eq!(config.conv_type, ConvolutionType::Conv2D);
        assert_eq!(config.input_dims, vec![1, 3, 32, 32]);
        assert_eq!(config.output_dims, vec![1, 16, 32, 32]);
        assert_eq!(config.kernel_dims, vec![16, 3, 3, 3]);
        assert!(config.is_valid());
    }

    #[test]
    fn test_depthwise_config_creation() {
        let config = ConvolutionConfig::depthwise_conv2d(1, 16, (32, 32), (3, 3), (1, 1), (1, 1));

        assert_eq!(config.conv_type, ConvolutionType::DepthwiseConv2D);
        assert_eq!(config.groups, 16);
        assert_eq!(config.kernel_dims, vec![16, 1, 3, 3]);
        assert!(config.is_valid());
    }

    #[test]
    fn test_algorithm_selection() {
        let ops = DefaultConvolutionOps::new();

        // Small kernel should prefer Winograd
        let small_kernel_config =
            ConvolutionConfig::conv2d(1, 3, 16, (32, 32), (3, 3), (1, 1), (1, 1));
        assert_eq!(
            ops.select_algorithm(&small_kernel_config),
            ConvolutionAlgorithm::Winograd
        );

        // Large kernel should prefer FFT
        let large_kernel_config =
            ConvolutionConfig::conv2d(1, 3, 16, (32, 32), (9, 9), (1, 1), (4, 4));
        assert_eq!(
            ops.select_algorithm(&large_kernel_config),
            ConvolutionAlgorithm::FftBased
        );
    }

    #[test]
    fn test_buffer_size_calculations() {
        let config = ConvolutionConfig::conv2d(2, 3, 16, (32, 32), (3, 3), (1, 1), (1, 1));

        assert_eq!(config.input_elements(), 2 * 3 * 32 * 32);
        assert_eq!(config.output_elements(), 2 * 16 * 32 * 32);
        assert_eq!(config.kernel_elements(), 16 * 3 * 3 * 3);

        assert_eq!(config.input_buffer_size(), 2 * 3 * 32 * 32 * 4); // F32 = 4 bytes
        assert_eq!(config.output_buffer_size(), 2 * 16 * 32 * 32 * 4);
        assert_eq!(config.kernel_buffer_size(), 16 * 3 * 3 * 3 * 4);
    }

    #[test]
    fn test_winograd_applicability() {
        assert!(algorithms::WinogradConvolution::can_apply((3, 3), (1, 1)));
        assert!(!algorithms::WinogradConvolution::can_apply((5, 5), (1, 1)));
        assert!(!algorithms::WinogradConvolution::can_apply((3, 3), (2, 2)));
    }
}