use std::fmt;
use super::PaddingMode;
use crate::error::Result;
use crate::runtime::Runtime;
use crate::tensor::Tensor;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ConvLayout {
Nchw,
Nhwc,
}
#[non_exhaustive]
pub enum ConvActivation<'a, R: Runtime> {
None,
Relu,
LeakyRelu(f64),
Prelu(&'a Tensor<R>),
}
impl<R: Runtime> Clone for ConvActivation<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R: Runtime> Copy for ConvActivation<'_, R> {}
impl<R: Runtime> fmt::Debug for ConvActivation<'_, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None => f.write_str("None"),
Self::Relu => f.write_str("Relu"),
Self::LeakyRelu(slope) => f.debug_tuple("LeakyRelu").field(slope).finish(),
Self::Prelu(weight) => f.debug_tuple("Prelu").field(weight).finish(),
}
}
}
pub struct ConvResidual<'a, R: Runtime> {
pub tensor: &'a Tensor<R>,
pub scale: f64,
}
impl<R: Runtime> Clone for ConvResidual<'_, R> {
fn clone(&self) -> Self {
*self
}
}
impl<R: Runtime> Copy for ConvResidual<'_, R> {}
impl<R: Runtime> fmt::Debug for ConvResidual<'_, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ConvResidual")
.field("tensor", self.tensor)
.field("scale", &self.scale)
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum ConvAccumulation {
#[default]
F32,
AllowHalf,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Conv2dConfig {
pub stride: (usize, usize),
pub padding: PaddingMode,
pub dilation: (usize, usize),
pub groups: usize,
pub layout: ConvLayout,
pub accumulation: ConvAccumulation,
}
impl Conv2dConfig {
pub fn new(layout: ConvLayout) -> Self {
Self {
stride: (1, 1),
padding: PaddingMode::Valid,
dilation: (1, 1),
groups: 1,
layout,
accumulation: ConvAccumulation::F32,
}
}
pub fn with_stride(mut self, stride: (usize, usize)) -> Self {
self.stride = stride;
self
}
pub fn with_padding(mut self, padding: PaddingMode) -> Self {
self.padding = padding;
self
}
pub fn with_dilation(mut self, dilation: (usize, usize)) -> Self {
self.dilation = dilation;
self
}
pub fn with_groups(mut self, groups: usize) -> Self {
self.groups = groups;
self
}
pub fn with_accumulation(mut self, accumulation: ConvAccumulation) -> Self {
self.accumulation = accumulation;
self
}
}
pub trait FusedConvOps<R: Runtime> {
fn conv2d_fused(
&self,
input: &Tensor<R>,
weight: &Tensor<R>,
bias: Option<&Tensor<R>>,
config: &Conv2dConfig,
activation: ConvActivation<'_, R>,
residual: Option<ConvResidual<'_, R>>,
) -> Result<Tensor<R>>;
fn conv2d_fused_into(
&self,
out: &Tensor<R>,
input: &Tensor<R>,
weight: &Tensor<R>,
bias: Option<&Tensor<R>>,
config: &Conv2dConfig,
activation: ConvActivation<'_, R>,
residual: Option<ConvResidual<'_, R>>,
) -> Result<()>;
}