use crate::backend_authoring::Execute;
use crate::dist::placement::Local;
use crate::err::{Error, Result};
use crate::exec::Capabilities;
use crate::exec::catalog::{AvgPool2dAttributes, op};
use crate::exec::context::ExecutionContext;
use crate::exec::dispatch;
use crate::exec::request::TensorHandle;
use crate::nn::{Module, TrainMode};
use crate::shapes::ShapeValue;
use crate::shapes::{DynShape, Shape};
use crate::tensor::base::Tensor;
use typenum::Unsigned;
#[derive(Debug, Clone)]
pub struct AvgPool2d<K: Unsigned, S: Unsigned, P: Unsigned = typenum::U0, D: Unsigned = typenum::U1>
{
_phantom: core::marker::PhantomData<(K, S, P, D)>,
}
impl<K: Unsigned, S: Unsigned, P: Unsigned, D: Unsigned, B: crate::tensor::backend::VariableBackend>
crate::nn::VisitParameters<B> for AvgPool2d<K, S, P, D>
{
fn visit_parameters<V: crate::nn::ParameterVisitor<B>>(
&self,
_: &crate::nn::StatePath,
_: &mut V,
) -> Result<()> {
Ok(())
}
}
impl<K: Unsigned, S: Unsigned, P: Unsigned, D: Unsigned> AvgPool2d<K, S, P, D> {
pub fn new() -> Result<Self> {
Ok(Self {
_phantom: core::marker::PhantomData,
})
}
}
impl<K: Unsigned, S: Unsigned, P: Unsigned, D: Unsigned> TrainMode for AvgPool2d<K, S, P, D> {}
impl<
I: Shape + DynShape + crate::shapes::Pool2dShape<K, S, P, D>,
K: Unsigned,
S: Unsigned,
P: Unsigned,
D: Unsigned,
B: crate::tensor::backend::VariableBackend + Execute<op::AvgPool2d>,
> Module<Tensor<I, B>> for AvgPool2d<K, S, P, D>
where
B: Capabilities,
<B as Execute<op::AvgPool2d>>::Output: Into<B::Storage<f32>>,
{
type Output = Tensor<I::Output, B>;
type Error = Error;
#[inline]
fn forward(&self, x: Tensor<I, B>) -> core::result::Result<Self::Output, Error> {
let shape = <I as crate::shapes::Pool2dShape<K, S, P, D>>::compute_output_shape(
&x.shape_buf_value(),
)?;
let shape = ShapeValue::<I::Output>::try_new(shape).map_err(Error::Shape)?;
let inputs = [TensorHandle::from_storage::<B, f32, Local>(x.inner())];
let context = ExecutionContext::from_scope(B::default());
let out = dispatch::execute_shaped::<op::AvgPool2d, B, I::Output>(
&context,
AvgPool2dAttributes {
kernel: [K::USIZE; 2],
stride: [S::USIZE; 2],
padding: [P::USIZE; 2],
},
&inputs,
&shape,
)?
.into();
Tensor::from_parts(
out,
shape.shape_buf().clone(),
x._dtype,
x._device.clone(),
core::marker::PhantomData,
)
}
}