use crate::error::Error;
use crate::neural_network::layers::ParamCounts;
use crate::neural_network::layers::convolution::PaddingType;
use crate::neural_network::layers::pooling::pooling_engine::{
PoolKind, windowed_pool_backward, windowed_pool_forward,
};
use crate::neural_network::layers::pooling::validation::{
validate_pool_size_1d, validate_stride_1d,
};
use crate::neural_network::layers::pooling::{
layer_base_functions_pooling, layer_functions_1d_pooling,
};
use crate::neural_network::layers::shape_helpers::calculate_output_shape_1d_pooling;
use crate::neural_network::layers::validation::validate_built_input;
use crate::neural_network::traits::{LayerBase, UnaryLayer};
use crate::neural_network::{Ctx, Shape, Tensor};
#[derive(Debug)]
pub struct MaxPooling1D {
pool_size: usize,
stride: usize,
built: Option<Shape>,
padding: PaddingType,
}
impl MaxPooling1D {
pub fn new(pool_size: usize) -> Self {
MaxPooling1D {
pool_size,
stride: pool_size,
built: None,
padding: PaddingType::Valid,
}
}
pub fn with_stride(mut self, stride: usize) -> Result<Self, Error> {
validate_stride_1d(stride)?;
self.stride = stride;
Ok(self)
}
pub fn with_padding(mut self, padding: PaddingType) -> Self {
self.padding = padding;
self
}
}
struct MaxPooling1DCache {
input_shape: Vec<usize>,
argmax: Vec<usize>,
}
impl LayerBase for MaxPooling1D {
fn layer_type(&self) -> &str {
"MaxPooling1D"
}
layer_base_functions_pooling!();
}
impl UnaryLayer for MaxPooling1D {
fn forward(&self, input: &Tensor, ctx: &mut Ctx) -> Result<Tensor, Error> {
validate_built_input(&self.built, "MaxPooling1D", input.shape())?;
let (output, argmax) = windowed_pool_forward(
input,
&[self.pool_size],
&[self.stride],
PoolKind::Max,
self.padding,
);
if ctx.is_training() {
ctx.push_cache(
"MaxPooling1D",
MaxPooling1DCache {
input_shape: input.shape().to_vec(),
argmax: argmax.expect("PoolKind::Max always tracks the arg-max"),
},
);
}
Ok(output)
}
fn backward(&self, grad_output: &Tensor, ctx: &mut Ctx) -> Result<Tensor, Error> {
let cache: MaxPooling1DCache = ctx.pop_cache("MaxPooling1D")?;
Ok(windowed_pool_backward(
grad_output,
&cache.input_shape,
&[self.pool_size],
&[self.stride],
PoolKind::Max,
Some(&cache.argmax),
self.padding,
))
}
layer_functions_1d_pooling!("MaxPooling1D");
}