1use crate::{BackendResult, Buffer, Device};
8use torsh_core::dtype::DType;
9
10#[cfg(not(feature = "std"))]
11use alloc::{boxed::Box, vec::Vec};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ConvolutionType {
16 Conv1D,
18 Conv2D,
20 Conv3D,
22 DepthwiseConv2D,
24 SeparableConv2D,
26 ConvTranspose2D,
28 DilatedConv2D,
30 GroupedConv2D,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum ConvolutionAlgorithm {
37 Auto,
39 Direct,
41 Im2col,
43 Winograd,
45 FftBased,
47 Optimized,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum PaddingMode {
54 Valid,
56 Same,
58 Custom,
60}
61
62#[derive(Debug, Clone)]
64pub struct ConvolutionConfig {
65 pub conv_type: ConvolutionType,
67 pub input_dims: Vec<usize>,
69 pub output_dims: Vec<usize>,
71 pub kernel_dims: Vec<usize>,
73 pub strides: Vec<usize>,
75 pub padding: Vec<usize>,
77 pub dilation: Vec<usize>,
79 pub groups: usize,
81 pub padding_mode: PaddingMode,
83 pub dtype: DType,
85 pub algorithm: ConvolutionAlgorithm,
87}
88
89impl ConvolutionConfig {
90 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 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 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 pub fn with_algorithm(mut self, algorithm: ConvolutionAlgorithm) -> Self {
150 self.algorithm = algorithm;
151 self
152 }
153
154 pub fn with_dtype(mut self, dtype: DType) -> Self {
156 self.dtype = dtype;
157 self
158 }
159
160 pub fn with_dilation(mut self, dilation: Vec<usize>) -> Self {
162 self.dilation = dilation;
163 self
164 }
165
166 pub fn input_elements(&self) -> usize {
168 self.input_dims.iter().product()
169 }
170
171 pub fn output_elements(&self) -> usize {
173 self.output_dims.iter().product()
174 }
175
176 pub fn kernel_elements(&self) -> usize {
178 self.kernel_dims.iter().product()
179 }
180
181 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 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 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 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#[async_trait::async_trait]
228pub trait ConvolutionOps: Send + Sync {
229 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 #[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 #[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 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 #[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 fn select_algorithm(&self, config: &ConvolutionConfig) -> ConvolutionAlgorithm;
313
314 fn supports_convolution(&self) -> bool;
316
317 fn supported_conv_types(&self) -> Vec<ConvolutionType>;
319
320 fn supported_algorithms(&self) -> Vec<ConvolutionAlgorithm>;
322}
323
324#[derive(Debug, Clone)]
326pub struct ConvolutionPerformanceHints {
327 pub small_kernel_algorithm: ConvolutionAlgorithm,
329 pub large_kernel_algorithm: ConvolutionAlgorithm,
331 pub fft_threshold: usize,
333 pub winograd_threshold: usize,
335 pub tile_size: (usize, usize),
337 pub memory_bandwidth: f32,
339 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
357pub 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 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
514pub mod algorithms {
516 use super::*;
517
518 pub struct DirectConvolution;
520
521 impl DirectConvolution {
522 #[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 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 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 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 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 pub struct Im2colConvolution;
679
680 impl Im2colConvolution {
681 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 pub struct WinogradConvolution;
752
753 impl WinogradConvolution {
754 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 k_h == 3 && k_w == 3 && s_h == 1 && s_w == 1
761 }
762
763 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 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 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 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); 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}