use crate::error::Error;
use crate::neural_network::layers::ParamCounts;
use crate::neural_network::layers::upsampling::resize_engine::{
upsample_backward, upsample_forward, upsample_output_shape, validate_factors,
};
use crate::neural_network::layers::upsampling::{Factor3D, Interpolation};
use crate::neural_network::layers::validation::start_build;
use crate::neural_network::layers::{
built_layer_shape_functions, no_trainable_parameters_layer_functions,
};
use crate::neural_network::traits::{LayerBase, UnaryLayer};
use crate::neural_network::{Ctx, Shape, Tensor};
#[derive(Debug)]
pub struct UpSampling3D {
size: Factor3D,
built: Option<Shape>,
}
impl UpSampling3D {
pub fn new(size: impl Into<Factor3D>) -> Result<Self, Error> {
let size = size.into();
validate_factors(&size.0)?;
Ok(UpSampling3D { size, built: None })
}
}
impl LayerBase for UpSampling3D {
fn layer_type(&self) -> &str {
"UpSampling3D"
}
built_layer_shape_functions!();
no_trainable_parameters_layer_functions!();
}
impl UnaryLayer for UpSampling3D {
fn build(&mut self, input: &Shape) -> Result<(), Error> {
let Some(built) = start_build(&self.built, "UpSampling3D", input)? else {
return Ok(());
};
self.compute_output_shape(&built)?;
self.built = Some(built);
Ok(())
}
fn forward(&self, input: &Tensor, ctx: &mut Ctx) -> Result<Tensor, Error> {
let output = upsample_forward(
input,
&self.size.0,
Interpolation::Nearest,
5,
"UpSampling3D",
)?;
if ctx.is_training() {
ctx.push_cache("UpSampling3D", input.shape().to_vec());
}
Ok(output)
}
fn backward(&self, grad_output: &Tensor, ctx: &mut Ctx) -> Result<Tensor, Error> {
let input_shape: Vec<usize> = ctx.pop_cache("UpSampling3D")?;
upsample_backward(
grad_output,
Some(input_shape.as_slice()),
&self.size.0,
Interpolation::Nearest,
"UpSampling3D",
)
}
fn compute_output_shape(&self, input: &Shape) -> Result<Shape, Error> {
upsample_output_shape(input, &self.size.0, "UpSampling3D")
}
}