Skip to main content

torsh_backend/
convolution.rs

1//! Convolution operations for all backends
2//!
3//! This module provides a unified interface for convolution operations across all backends,
4//! with optimized implementations for each platform including direct convolution,
5//! Winograd algorithm, FFT-based convolution, and im2col-based approaches.
6
7use crate::{BackendResult, Buffer, Device};
8use torsh_core::dtype::DType;
9
10#[cfg(not(feature = "std"))]
11use alloc::{boxed::Box, vec::Vec};
12
13/// Convolution operation type
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ConvolutionType {
16    /// 1D convolution
17    Conv1D,
18    /// 2D convolution (most common)
19    Conv2D,
20    /// 3D convolution
21    Conv3D,
22    /// Depthwise convolution
23    DepthwiseConv2D,
24    /// Separable convolution
25    SeparableConv2D,
26    /// Transposed convolution (deconvolution)
27    ConvTranspose2D,
28    /// Dilated convolution
29    DilatedConv2D,
30    /// Grouped convolution
31    GroupedConv2D,
32}
33
34/// Convolution algorithm implementation
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum ConvolutionAlgorithm {
37    /// Auto-select best algorithm
38    Auto,
39    /// Direct convolution implementation
40    Direct,
41    /// Im2col + GEMM approach
42    Im2col,
43    /// Winograd algorithm for small kernels
44    Winograd,
45    /// FFT-based convolution for large kernels
46    FftBased,
47    /// Optimized backend-specific implementation
48    Optimized,
49}
50
51/// Padding mode for convolution
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum PaddingMode {
54    /// No padding
55    Valid,
56    /// Zero padding to maintain output size
57    Same,
58    /// Custom padding
59    Custom,
60}
61
62/// Convolution configuration
63#[derive(Debug, Clone)]
64pub struct ConvolutionConfig {
65    /// Convolution type
66    pub conv_type: ConvolutionType,
67    /// Input dimensions [batch, channels, height, width] for 2D
68    pub input_dims: Vec<usize>,
69    /// Output dimensions [batch, channels, height, width] for 2D
70    pub output_dims: Vec<usize>,
71    /// Kernel dimensions [out_channels, in_channels, height, width] for 2D
72    pub kernel_dims: Vec<usize>,
73    /// Stride in each dimension
74    pub strides: Vec<usize>,
75    /// Padding in each dimension
76    pub padding: Vec<usize>,
77    /// Dilation in each dimension
78    pub dilation: Vec<usize>,
79    /// Number of groups for grouped convolution
80    pub groups: usize,
81    /// Padding mode
82    pub padding_mode: PaddingMode,
83    /// Data type
84    pub dtype: DType,
85    /// Preferred algorithm
86    pub algorithm: ConvolutionAlgorithm,
87}
88
89impl ConvolutionConfig {
90    /// Create a new 2D convolution configuration
91    pub fn conv2d(
92        batch_size: usize,
93        in_channels: usize,
94        out_channels: usize,
95        input_size: (usize, usize),
96        kernel_size: (usize, usize),
97        stride: (usize, usize),
98        padding: (usize, usize),
99    ) -> Self {
100        let (in_h, in_w) = input_size;
101        let (k_h, k_w) = kernel_size;
102        let (s_h, s_w) = stride;
103        let (p_h, p_w) = padding;
104
105        // Calculate output dimensions
106        let out_h = (in_h + 2 * p_h - k_h) / s_h + 1;
107        let out_w = (in_w + 2 * p_w - k_w) / s_w + 1;
108
109        Self {
110            conv_type: ConvolutionType::Conv2D,
111            input_dims: vec![batch_size, in_channels, in_h, in_w],
112            output_dims: vec![batch_size, out_channels, out_h, out_w],
113            kernel_dims: vec![out_channels, in_channels, k_h, k_w],
114            strides: vec![s_h, s_w],
115            padding: vec![p_h, p_w],
116            dilation: vec![1, 1],
117            groups: 1,
118            padding_mode: PaddingMode::Custom,
119            dtype: DType::F32,
120            algorithm: ConvolutionAlgorithm::Auto,
121        }
122    }
123
124    /// Create a depthwise convolution configuration
125    pub fn depthwise_conv2d(
126        batch_size: usize,
127        channels: usize,
128        input_size: (usize, usize),
129        kernel_size: (usize, usize),
130        stride: (usize, usize),
131        padding: (usize, usize),
132    ) -> Self {
133        let mut config = Self::conv2d(
134            batch_size,
135            channels,
136            channels,
137            input_size,
138            kernel_size,
139            stride,
140            padding,
141        );
142        config.conv_type = ConvolutionType::DepthwiseConv2D;
143        config.groups = channels;
144        config.kernel_dims = vec![channels, 1, kernel_size.0, kernel_size.1];
145        config
146    }
147
148    /// Set the algorithm preference
149    pub fn with_algorithm(mut self, algorithm: ConvolutionAlgorithm) -> Self {
150        self.algorithm = algorithm;
151        self
152    }
153
154    /// Set the data type
155    pub fn with_dtype(mut self, dtype: DType) -> Self {
156        self.dtype = dtype;
157        self
158    }
159
160    /// Set dilation
161    pub fn with_dilation(mut self, dilation: Vec<usize>) -> Self {
162        self.dilation = dilation;
163        self
164    }
165
166    /// Calculate total input elements
167    pub fn input_elements(&self) -> usize {
168        self.input_dims.iter().product()
169    }
170
171    /// Calculate total output elements
172    pub fn output_elements(&self) -> usize {
173        self.output_dims.iter().product()
174    }
175
176    /// Calculate total kernel elements
177    pub fn kernel_elements(&self) -> usize {
178        self.kernel_dims.iter().product()
179    }
180
181    /// Get input buffer size in bytes
182    pub fn input_buffer_size(&self) -> usize {
183        let element_size = match self.dtype {
184            DType::F32 => 4,
185            DType::F64 => 8,
186            DType::F16 => 2,
187            _ => 4,
188        };
189        self.input_elements() * element_size
190    }
191
192    /// Get output buffer size in bytes
193    pub fn output_buffer_size(&self) -> usize {
194        let element_size = match self.dtype {
195            DType::F32 => 4,
196            DType::F64 => 8,
197            DType::F16 => 2,
198            _ => 4,
199        };
200        self.output_elements() * element_size
201    }
202
203    /// Get kernel buffer size in bytes
204    pub fn kernel_buffer_size(&self) -> usize {
205        let element_size = match self.dtype {
206            DType::F32 => 4,
207            DType::F64 => 8,
208            DType::F16 => 2,
209            _ => 4,
210        };
211        self.kernel_elements() * element_size
212    }
213
214    /// Check if the configuration is valid
215    pub fn is_valid(&self) -> bool {
216        !self.input_dims.is_empty()
217            && !self.output_dims.is_empty()
218            && !self.kernel_dims.is_empty()
219            && self.input_dims.iter().all(|&d| d > 0)
220            && self.output_dims.iter().all(|&d| d > 0)
221            && self.kernel_dims.iter().all(|&d| d > 0)
222            && self.groups > 0
223    }
224}
225
226/// Convolution operations trait
227#[async_trait::async_trait]
228pub trait ConvolutionOps: Send + Sync {
229    /// Execute a convolution operation
230    async fn convolution(
231        &self,
232        device: &Device,
233        input: &Buffer,
234        kernel: &Buffer,
235        bias: Option<&Buffer>,
236        output: &Buffer,
237        config: &ConvolutionConfig,
238    ) -> BackendResult<()>;
239
240    /// Execute a 2D convolution.
241    ///
242    /// Shapes are given explicitly in NCHW layout — buffer byte-lengths alone
243    /// cannot recover a tensor's shape, so callers must supply them:
244    /// `input_shape = [N, C_in, H, W]`, `kernel_shape = [C_out, C_in, kH, kW]`.
245    #[allow(clippy::too_many_arguments)]
246    async fn conv2d(
247        &self,
248        device: &Device,
249        input: &Buffer,
250        kernel: &Buffer,
251        bias: Option<&Buffer>,
252        output: &Buffer,
253        input_shape: [usize; 4],
254        kernel_shape: [usize; 4],
255        stride: (usize, usize),
256        padding: (usize, usize),
257        dilation: (usize, usize),
258    ) -> BackendResult<()>;
259
260    /// Execute a depthwise convolution.
261    ///
262    /// `input_shape = [N, C, H, W]`, `kernel_shape = [C_out, 1, kH, kW]` where
263    /// `C_out = C * channel_multiplier` (groups are implicitly `C`).
264    #[allow(clippy::too_many_arguments)]
265    async fn depthwise_conv2d(
266        &self,
267        device: &Device,
268        input: &Buffer,
269        kernel: &Buffer,
270        bias: Option<&Buffer>,
271        output: &Buffer,
272        input_shape: [usize; 4],
273        kernel_shape: [usize; 4],
274        stride: (usize, usize),
275        padding: (usize, usize),
276        dilation: (usize, usize),
277    ) -> BackendResult<()>;
278
279    /// Execute a transposed convolution
280    async fn conv_transpose2d(
281        &self,
282        device: &Device,
283        input: &Buffer,
284        kernel: &Buffer,
285        bias: Option<&Buffer>,
286        output: &Buffer,
287        stride: (usize, usize),
288        padding: (usize, usize),
289        output_padding: (usize, usize),
290    ) -> BackendResult<()>;
291
292    /// Execute a grouped convolution.
293    ///
294    /// `input_shape = [N, C_in, H, W]`, `kernel_shape = [C_out, C_in/groups, kH, kW]`.
295    #[allow(clippy::too_many_arguments)]
296    async fn grouped_conv2d(
297        &self,
298        device: &Device,
299        input: &Buffer,
300        kernel: &Buffer,
301        bias: Option<&Buffer>,
302        output: &Buffer,
303        input_shape: [usize; 4],
304        kernel_shape: [usize; 4],
305        groups: usize,
306        stride: (usize, usize),
307        padding: (usize, usize),
308        dilation: (usize, usize),
309    ) -> BackendResult<()>;
310
311    /// Get the best algorithm for given configuration
312    fn select_algorithm(&self, config: &ConvolutionConfig) -> ConvolutionAlgorithm;
313
314    /// Check if convolution operations are supported
315    fn supports_convolution(&self) -> bool;
316
317    /// Get supported convolution types
318    fn supported_conv_types(&self) -> Vec<ConvolutionType>;
319
320    /// Get supported algorithms
321    fn supported_algorithms(&self) -> Vec<ConvolutionAlgorithm>;
322}
323
324/// Performance characteristics for algorithm selection
325#[derive(Debug, Clone)]
326pub struct ConvolutionPerformanceHints {
327    /// Optimal algorithm for small kernels (3x3, 5x5)
328    pub small_kernel_algorithm: ConvolutionAlgorithm,
329    /// Optimal algorithm for large kernels (7x7, 9x9+)
330    pub large_kernel_algorithm: ConvolutionAlgorithm,
331    /// Threshold for switching to FFT-based convolution
332    pub fft_threshold: usize,
333    /// Threshold for using Winograd algorithm
334    pub winograd_threshold: usize,
335    /// Preferred tile size for tiled algorithms
336    pub tile_size: (usize, usize),
337    /// Memory bandwidth in GB/s
338    pub memory_bandwidth: f32,
339    /// Compute throughput in GOPS
340    pub compute_throughput: f32,
341}
342
343impl Default for ConvolutionPerformanceHints {
344    fn default() -> Self {
345        Self {
346            small_kernel_algorithm: ConvolutionAlgorithm::Winograd,
347            large_kernel_algorithm: ConvolutionAlgorithm::FftBased,
348            fft_threshold: 7,
349            winograd_threshold: 6,
350            tile_size: (16, 16),
351            memory_bandwidth: 50.0,
352            compute_throughput: 100.0,
353        }
354    }
355}
356
357/// Default convolution operations implementation
358pub struct DefaultConvolutionOps {
359    performance_hints: ConvolutionPerformanceHints,
360}
361
362impl DefaultConvolutionOps {
363    pub fn new() -> Self {
364        Self {
365            performance_hints: ConvolutionPerformanceHints::default(),
366        }
367    }
368
369    pub fn with_performance_hints(mut self, hints: ConvolutionPerformanceHints) -> Self {
370        self.performance_hints = hints;
371        self
372    }
373}
374
375#[async_trait::async_trait]
376impl ConvolutionOps for DefaultConvolutionOps {
377    async fn convolution(
378        &self,
379        _device: &Device,
380        _input: &Buffer,
381        _kernel: &Buffer,
382        _bias: Option<&Buffer>,
383        _output: &Buffer,
384        _config: &ConvolutionConfig,
385    ) -> BackendResult<()> {
386        Err(torsh_core::error::TorshError::BackendError(
387            "Convolution operations not implemented for this backend".to_string(),
388        ))
389    }
390
391    #[allow(clippy::too_many_arguments)]
392    async fn conv2d(
393        &self,
394        _device: &Device,
395        _input: &Buffer,
396        _kernel: &Buffer,
397        _bias: Option<&Buffer>,
398        _output: &Buffer,
399        _input_shape: [usize; 4],
400        _kernel_shape: [usize; 4],
401        _stride: (usize, usize),
402        _padding: (usize, usize),
403        _dilation: (usize, usize),
404    ) -> BackendResult<()> {
405        Err(torsh_core::error::TorshError::BackendError(
406            "Conv2D operations not implemented for this backend".to_string(),
407        ))
408    }
409
410    #[allow(clippy::too_many_arguments)]
411    async fn depthwise_conv2d(
412        &self,
413        _device: &Device,
414        _input: &Buffer,
415        _kernel: &Buffer,
416        _bias: Option<&Buffer>,
417        _output: &Buffer,
418        _input_shape: [usize; 4],
419        _kernel_shape: [usize; 4],
420        _stride: (usize, usize),
421        _padding: (usize, usize),
422        _dilation: (usize, usize),
423    ) -> BackendResult<()> {
424        Err(torsh_core::error::TorshError::BackendError(
425            "Depthwise convolution not implemented for this backend".to_string(),
426        ))
427    }
428
429    async fn conv_transpose2d(
430        &self,
431        _device: &Device,
432        _input: &Buffer,
433        _kernel: &Buffer,
434        _bias: Option<&Buffer>,
435        _output: &Buffer,
436        _stride: (usize, usize),
437        _padding: (usize, usize),
438        _output_padding: (usize, usize),
439    ) -> BackendResult<()> {
440        Err(torsh_core::error::TorshError::BackendError(
441            "Transposed convolution not implemented for this backend".to_string(),
442        ))
443    }
444
445    #[allow(clippy::too_many_arguments)]
446    async fn grouped_conv2d(
447        &self,
448        _device: &Device,
449        _input: &Buffer,
450        _kernel: &Buffer,
451        _bias: Option<&Buffer>,
452        _output: &Buffer,
453        _input_shape: [usize; 4],
454        _kernel_shape: [usize; 4],
455        _groups: usize,
456        _stride: (usize, usize),
457        _padding: (usize, usize),
458        _dilation: (usize, usize),
459    ) -> BackendResult<()> {
460        Err(torsh_core::error::TorshError::BackendError(
461            "Grouped convolution not implemented for this backend".to_string(),
462        ))
463    }
464
465    fn select_algorithm(&self, config: &ConvolutionConfig) -> ConvolutionAlgorithm {
466        if config.algorithm != ConvolutionAlgorithm::Auto {
467            return config.algorithm;
468        }
469
470        // Auto-select based on kernel size and configuration
471        match config.conv_type {
472            ConvolutionType::Conv2D => {
473                if config.kernel_dims.len() >= 4 {
474                    let kernel_h = config.kernel_dims[2];
475                    let kernel_w = config.kernel_dims[3];
476                    let kernel_size = kernel_h.max(kernel_w);
477
478                    if kernel_size <= self.performance_hints.winograd_threshold {
479                        ConvolutionAlgorithm::Winograd
480                    } else if kernel_size >= self.performance_hints.fft_threshold {
481                        ConvolutionAlgorithm::FftBased
482                    } else {
483                        ConvolutionAlgorithm::Im2col
484                    }
485                } else {
486                    ConvolutionAlgorithm::Direct
487                }
488            }
489            ConvolutionType::DepthwiseConv2D => ConvolutionAlgorithm::Direct,
490            ConvolutionType::SeparableConv2D => ConvolutionAlgorithm::Direct,
491            _ => ConvolutionAlgorithm::Im2col,
492        }
493    }
494
495    fn supports_convolution(&self) -> bool {
496        false
497    }
498
499    fn supported_conv_types(&self) -> Vec<ConvolutionType> {
500        vec![]
501    }
502
503    fn supported_algorithms(&self) -> Vec<ConvolutionAlgorithm> {
504        vec![ConvolutionAlgorithm::Direct]
505    }
506}
507
508impl Default for DefaultConvolutionOps {
509    fn default() -> Self {
510        Self::new()
511    }
512}
513
514/// Convolution algorithm implementations
515pub mod algorithms {
516    use super::*;
517
518    /// Direct convolution implementation
519    pub struct DirectConvolution;
520
521    impl DirectConvolution {
522        /// Perform 2D convolution using a direct approach.
523        ///
524        /// Supports dilation and grouped convolution (which also subsumes
525        /// depthwise convolution, expressed as `groups == in_channels`).
526        ///
527        /// Layout conventions (NCHW): `input_dims = [N, C_in, H, W]`,
528        /// `kernel_dims = [C_out, C_in / groups, kH, kW]`,
529        /// `output_dims = [N, C_out, out_H, out_W]`. The output spatial size
530        /// must satisfy `out = (in + 2*pad - dilation*(k-1) - 1) / stride + 1`.
531        #[allow(clippy::too_many_arguments)]
532        pub fn conv2d_direct(
533            input: &[f32],
534            kernel: &[f32],
535            output: &mut [f32],
536            input_dims: &[usize],
537            kernel_dims: &[usize],
538            output_dims: &[usize],
539            stride: (usize, usize),
540            padding: (usize, usize),
541            dilation: (usize, usize),
542            groups: usize,
543        ) -> BackendResult<()> {
544            let (batch, in_channels, in_h, in_w) =
545                (input_dims[0], input_dims[1], input_dims[2], input_dims[3]);
546            let (out_channels, kernel_in_per_group, k_h, k_w) = (
547                kernel_dims[0],
548                kernel_dims[1],
549                kernel_dims[2],
550                kernel_dims[3],
551            );
552            let (_, _, out_h, out_w) = (
553                output_dims[0],
554                output_dims[1],
555                output_dims[2],
556                output_dims[3],
557            );
558            let (s_h, s_w) = stride;
559            let (p_h, p_w) = padding;
560            let (d_h, d_w) = dilation;
561
562            if groups == 0 || in_channels % groups != 0 || out_channels % groups != 0 {
563                return Err(torsh_core::error::TorshError::BackendError(format!(
564                    "grouped convolution requires groups ({}) to divide both in_channels ({}) and out_channels ({})",
565                    groups, in_channels, out_channels
566                )));
567            }
568            if d_h == 0 || d_w == 0 || s_h == 0 || s_w == 0 {
569                return Err(torsh_core::error::TorshError::BackendError(
570                    "convolution stride and dilation must be non-zero".to_string(),
571                ));
572            }
573
574            let in_per_group = in_channels / groups;
575            let out_per_group = out_channels / groups;
576
577            if kernel_in_per_group != in_per_group {
578                return Err(torsh_core::error::TorshError::BackendError(format!(
579                    "kernel in-channels per group ({}) does not match in_channels/groups ({})",
580                    kernel_in_per_group, in_per_group
581                )));
582            }
583
584            // Validate slice lengths up front so the indexed inner loop can never
585            // go out of bounds (a bounds violation must be a returned error, not a
586            // panic from deep inside the kernel).
587            if input.len() < batch * in_channels * in_h * in_w {
588                return Err(torsh_core::error::TorshError::BackendError(format!(
589                    "input buffer ({} elems) too small for [{}, {}, {}, {}]",
590                    input.len(),
591                    batch,
592                    in_channels,
593                    in_h,
594                    in_w
595                )));
596            }
597            if kernel.len() < out_channels * in_per_group * k_h * k_w {
598                return Err(torsh_core::error::TorshError::BackendError(format!(
599                    "kernel buffer ({} elems) too small for [{}, {}, {}, {}]",
600                    kernel.len(),
601                    out_channels,
602                    in_per_group,
603                    k_h,
604                    k_w
605                )));
606            }
607            if output.len() < batch * out_channels * out_h * out_w {
608                return Err(torsh_core::error::TorshError::BackendError(format!(
609                    "output buffer ({} elems) too small for [{}, {}, {}, {}]",
610                    output.len(),
611                    batch,
612                    out_channels,
613                    out_h,
614                    out_w
615                )));
616            }
617
618            for b in 0..batch {
619                for oc in 0..out_channels {
620                    // Each output channel only sees the input channels of its group.
621                    let group = oc / out_per_group;
622                    let ic_base = group * in_per_group;
623
624                    for oh in 0..out_h {
625                        for ow in 0..out_w {
626                            let mut sum = 0.0;
627
628                            for icg in 0..in_per_group {
629                                let ic = ic_base + icg;
630                                for kh in 0..k_h {
631                                    for kw in 0..k_w {
632                                        // Dilated tap position in the padded input.
633                                        let ih = oh * s_h + kh * d_h;
634                                        let iw = ow * s_w + kw * d_w;
635
636                                        if ih >= p_h
637                                            && iw >= p_w
638                                            && ih < in_h + p_h
639                                            && iw < in_w + p_w
640                                        {
641                                            let input_h = ih - p_h;
642                                            let input_w = iw - p_w;
643
644                                            if input_h < in_h && input_w < in_w {
645                                                let input_idx = b * in_channels * in_h * in_w
646                                                    + ic * in_h * in_w
647                                                    + input_h * in_w
648                                                    + input_w;
649                                                // Kernel is indexed by the in-group channel
650                                                // offset, not the absolute input channel.
651                                                let kernel_idx = oc * in_per_group * k_h * k_w
652                                                    + icg * k_h * k_w
653                                                    + kh * k_w
654                                                    + kw;
655
656                                                sum += input[input_idx] * kernel[kernel_idx];
657                                            }
658                                        }
659                                    }
660                                }
661                            }
662
663                            let output_idx = b * out_channels * out_h * out_w
664                                + oc * out_h * out_w
665                                + oh * out_w
666                                + ow;
667                            output[output_idx] = sum;
668                        }
669                    }
670                }
671            }
672
673            Ok(())
674        }
675    }
676
677    /// Im2col convolution implementation
678    pub struct Im2colConvolution;
679
680    impl Im2colConvolution {
681        /// Convert input to column matrix for GEMM-based convolution
682        pub fn im2col(
683            input: &[f32],
684            output: &mut [f32],
685            input_dims: &[usize],
686            kernel_size: (usize, usize),
687            stride: (usize, usize),
688            padding: (usize, usize),
689        ) -> BackendResult<()> {
690            let (batch, channels, height, width) =
691                (input_dims[0], input_dims[1], input_dims[2], input_dims[3]);
692            let (k_h, k_w) = kernel_size;
693            let (s_h, s_w) = stride;
694            let (p_h, p_w) = padding;
695
696            let out_h = (height + 2 * p_h - k_h) / s_h + 1;
697            let out_w = (width + 2 * p_w - k_w) / s_w + 1;
698
699            for b in 0..batch {
700                for c in 0..channels {
701                    for kh in 0..k_h {
702                        for kw in 0..k_w {
703                            for oh in 0..out_h {
704                                for ow in 0..out_w {
705                                    let ih = oh * s_h + kh;
706                                    let iw = ow * s_w + kw;
707
708                                    let value = if ih >= p_h
709                                        && iw >= p_w
710                                        && ih < height + p_h
711                                        && iw < width + p_w
712                                    {
713                                        let input_h = ih - p_h;
714                                        let input_w = iw - p_w;
715
716                                        if input_h < height && input_w < width {
717                                            let input_idx = b * channels * height * width
718                                                + c * height * width
719                                                + input_h * width
720                                                + input_w;
721                                            input[input_idx]
722                                        } else {
723                                            0.0
724                                        }
725                                    } else {
726                                        0.0
727                                    };
728
729                                    let col_idx =
730                                        (b * channels * k_h * k_w + c * k_h * k_w + kh * k_w + kw)
731                                            * out_h
732                                            * out_w
733                                            + oh * out_w
734                                            + ow;
735
736                                    if col_idx < output.len() {
737                                        output[col_idx] = value;
738                                    }
739                                }
740                            }
741                        }
742                    }
743                }
744            }
745
746            Ok(())
747        }
748    }
749
750    /// Winograd convolution implementation
751    pub struct WinogradConvolution;
752
753    impl WinogradConvolution {
754        /// Check if Winograd can be applied
755        pub fn can_apply(kernel_size: (usize, usize), stride: (usize, usize)) -> bool {
756            let (k_h, k_w) = kernel_size;
757            let (s_h, s_w) = stride;
758
759            // Winograd is most effective for 3x3 kernels with stride 1
760            k_h == 3 && k_w == 3 && s_h == 1 && s_w == 1
761        }
762
763        /// Perform Winograd convolution (simplified F(2,3) implementation)
764        pub fn conv2d_winograd(
765            input: &[f32],
766            kernel: &[f32],
767            output: &mut [f32],
768            input_dims: &[usize],
769            kernel_dims: &[usize],
770            output_dims: &[usize],
771        ) -> BackendResult<()> {
772            // For now, fall back to direct convolution
773            // A full Winograd implementation would involve complex matrix transformations
774            DirectConvolution::conv2d_direct(
775                input,
776                kernel,
777                output,
778                input_dims,
779                kernel_dims,
780                output_dims,
781                (1, 1),
782                (1, 1),
783                (1, 1),
784                1,
785            )
786        }
787    }
788}
789
790#[cfg(test)]
791mod tests {
792    use super::*;
793
794    #[test]
795    fn test_convolution_config_creation() {
796        let config = ConvolutionConfig::conv2d(1, 3, 16, (32, 32), (3, 3), (1, 1), (1, 1));
797
798        assert_eq!(config.conv_type, ConvolutionType::Conv2D);
799        assert_eq!(config.input_dims, vec![1, 3, 32, 32]);
800        assert_eq!(config.output_dims, vec![1, 16, 32, 32]);
801        assert_eq!(config.kernel_dims, vec![16, 3, 3, 3]);
802        assert!(config.is_valid());
803    }
804
805    #[test]
806    fn test_depthwise_config_creation() {
807        let config = ConvolutionConfig::depthwise_conv2d(1, 16, (32, 32), (3, 3), (1, 1), (1, 1));
808
809        assert_eq!(config.conv_type, ConvolutionType::DepthwiseConv2D);
810        assert_eq!(config.groups, 16);
811        assert_eq!(config.kernel_dims, vec![16, 1, 3, 3]);
812        assert!(config.is_valid());
813    }
814
815    #[test]
816    fn test_algorithm_selection() {
817        let ops = DefaultConvolutionOps::new();
818
819        // Small kernel should prefer Winograd
820        let small_kernel_config =
821            ConvolutionConfig::conv2d(1, 3, 16, (32, 32), (3, 3), (1, 1), (1, 1));
822        assert_eq!(
823            ops.select_algorithm(&small_kernel_config),
824            ConvolutionAlgorithm::Winograd
825        );
826
827        // Large kernel should prefer FFT
828        let large_kernel_config =
829            ConvolutionConfig::conv2d(1, 3, 16, (32, 32), (9, 9), (1, 1), (4, 4));
830        assert_eq!(
831            ops.select_algorithm(&large_kernel_config),
832            ConvolutionAlgorithm::FftBased
833        );
834    }
835
836    #[test]
837    fn test_buffer_size_calculations() {
838        let config = ConvolutionConfig::conv2d(2, 3, 16, (32, 32), (3, 3), (1, 1), (1, 1));
839
840        assert_eq!(config.input_elements(), 2 * 3 * 32 * 32);
841        assert_eq!(config.output_elements(), 2 * 16 * 32 * 32);
842        assert_eq!(config.kernel_elements(), 16 * 3 * 3 * 3);
843
844        assert_eq!(config.input_buffer_size(), 2 * 3 * 32 * 32 * 4); // F32 = 4 bytes
845        assert_eq!(config.output_buffer_size(), 2 * 16 * 32 * 32 * 4);
846        assert_eq!(config.kernel_buffer_size(), 16 * 3 * 3 * 3 * 4);
847    }
848
849    #[test]
850    fn test_winograd_applicability() {
851        assert!(algorithms::WinogradConvolution::can_apply((3, 3), (1, 1)));
852        assert!(!algorithms::WinogradConvolution::can_apply((5, 5), (1, 1)));
853        assert!(!algorithms::WinogradConvolution::can_apply((3, 3), (2, 2)));
854    }
855}