use crate::error::Error;
use crate::neural_network::layers::ParamCounts;
use crate::neural_network::layers::activation::{Activation, ActivationCache};
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 GELU {
pub(super) approximate: bool,
built: Option<Shape>,
}
impl GELU {
pub fn new() -> Self {
GELU {
approximate: false,
built: None,
}
}
pub fn with_approximate(mut self, approximate: bool) -> Self {
self.approximate = approximate;
self
}
}
impl Default for GELU {
fn default() -> Self {
Self::new()
}
}
impl LayerBase for GELU {
fn layer_type(&self) -> &str {
"GELU"
}
built_layer_shape_functions!();
no_trainable_parameters_layer_functions!();
}
impl UnaryLayer for GELU {
fn build(&mut self, input: &Shape) -> Result<(), Error> {
let Some(built) = start_build(&self.built, "GELU", 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> {
if input.is_empty() {
return Err(Error::empty_input("input tensor"));
}
let activation = Activation::GELU {
approximate: self.approximate,
};
if !ctx.is_training() {
return activation.forward(input);
}
let (output, cache) = activation.forward_train(input.clone())?;
ctx.push_cache("GELU", cache);
Ok(output)
}
fn backward(&self, grad_output: &Tensor, ctx: &mut Ctx) -> Result<Tensor, Error> {
let cache: ActivationCache = ctx.pop_cache("GELU")?;
Activation::GELU {
approximate: self.approximate,
}
.backward(&cache, grad_output)
}
}