Skip to main content

incin_core/nn/
avg_pool2d.rs

1use crate::backend_authoring::Execute;
2use crate::dist::placement::Local;
3use crate::err::{Error, Result};
4use crate::exec::Capabilities;
5use crate::exec::catalog::{AvgPool2dAttributes, op};
6use crate::exec::context::ExecutionContext;
7use crate::exec::dispatch;
8use crate::exec::request::TensorHandle;
9use crate::nn::{Module, TrainMode};
10use crate::shapes::ShapeValue;
11use crate::shapes::{DynShape, Shape};
12use crate::tensor::base::Tensor;
13
14use typenum::Unsigned;
15
16#[derive(Debug, Clone)]
17/// `AvgPool2d`.
18pub struct AvgPool2d<K: Unsigned, S: Unsigned, P: Unsigned = typenum::U0, D: Unsigned = typenum::U1>
19{
20    _phantom: core::marker::PhantomData<(K, S, P, D)>,
21}
22
23impl<K: Unsigned, S: Unsigned, P: Unsigned, D: Unsigned, B: crate::tensor::backend::VariableBackend>
24    crate::nn::VisitParameters<B> for AvgPool2d<K, S, P, D>
25{
26    fn visit_parameters<V: crate::nn::ParameterVisitor<B>>(
27        &self,
28        _: &crate::nn::StatePath,
29        _: &mut V,
30    ) -> Result<()> {
31        Ok(())
32    }
33}
34
35impl<K: Unsigned, S: Unsigned, P: Unsigned, D: Unsigned> AvgPool2d<K, S, P, D> {
36    /// Creates a new instance with default (statically inferred) shape arguments.
37    pub fn new() -> Result<Self> {
38        Ok(Self {
39            _phantom: core::marker::PhantomData,
40        })
41    }
42}
43
44/// Stateless - no training-dependent behavior, opts in with the trait's
45/// default no-op so it can appear inside a `Sequential` alongside layers
46/// that do have one (e.g. `Dropout`).
47impl<K: Unsigned, S: Unsigned, P: Unsigned, D: Unsigned> TrainMode for AvgPool2d<K, S, P, D> {}
48
49impl<
50    I: Shape + DynShape + crate::shapes::Pool2dShape<K, S, P, D>,
51    K: Unsigned,
52    S: Unsigned,
53    P: Unsigned,
54    D: Unsigned,
55    B: crate::tensor::backend::VariableBackend + Execute<op::AvgPool2d>,
56> Module<Tensor<I, B>> for AvgPool2d<K, S, P, D>
57where
58    B: Capabilities,
59    <B as Execute<op::AvgPool2d>>::Output: Into<B::Storage<f32>>,
60{
61    /// The output tensor type produced by this module's forward pass.
62    type Output = Tensor<I::Output, B>;
63    /// The error type returned if the forward pass fails.
64    type Error = Error;
65
66    #[inline]
67    /// Runs the forward pass of this module on the given input.
68    fn forward(&self, x: Tensor<I, B>) -> core::result::Result<Self::Output, Error> {
69        let shape = <I as crate::shapes::Pool2dShape<K, S, P, D>>::compute_output_shape(
70            &x.shape_buf_value(),
71        )?;
72        let shape = ShapeValue::<I::Output>::try_new(shape).map_err(Error::Shape)?;
73        let inputs = [TensorHandle::from_storage::<B, f32, Local>(x.inner())];
74        let context = ExecutionContext::from_scope(B::default());
75        let out = dispatch::execute_shaped::<op::AvgPool2d, B, I::Output>(
76            &context,
77            AvgPool2dAttributes {
78                kernel: [K::USIZE; 2],
79                stride: [S::USIZE; 2],
80                padding: [P::USIZE; 2],
81            },
82            &inputs,
83            &shape,
84        )?
85        .into();
86        Tensor::from_parts(
87            out,
88            shape.shape_buf().clone(),
89            x._dtype,
90            x._device.clone(),
91            core::marker::PhantomData,
92        )
93    }
94}