use crate::error::Error;
use crate::neural_network::layers::ParamCounts;
use crate::neural_network::layers::activation::{Activation, ActivationCache};
use crate::neural_network::layers::conv_op_helpers::{
DepthwiseGeometry, depthwise_backward, depthwise_forward,
};
use crate::neural_network::layers::convolution::PaddingType;
use crate::neural_network::layers::convolution::convolution_engine::effective_kernel;
use crate::neural_network::layers::convolution::validation::{
valid_output_size, validate_depth_multiplier, validate_dilation, validate_input_shape_1d,
validate_kernel_size_1d, validate_strides_1d, validate_valid_kernel_fits,
};
use crate::neural_network::layers::validation::{
start_build, validate_built_input, validate_optional_weight, validate_weight_shape,
};
use crate::neural_network::layers::{built_layer_shape_functions, named_weight_layer_functions};
use crate::neural_network::traits::{LayerBase, ParamRef, UnaryLayer};
use crate::neural_network::{Ctx, Fans, Initializer, Shape, Tensor};
use ndarray::{Array1, Array3};
#[derive(Debug)]
pub struct DepthwiseConv1D {
channels: usize,
depth_multiplier: usize,
kernel_size: usize,
stride: usize,
dilation_rate: usize,
padding: PaddingType,
weights: Array3<f32>,
bias: Array1<f32>,
activation: Activation,
built: Option<Shape>,
random_state: Option<u64>,
use_bias: bool,
}
impl DepthwiseConv1D {
pub fn new(
kernel_size: usize,
stride: usize,
activation: impl Into<Activation>,
) -> Result<Self, Error> {
validate_kernel_size_1d(kernel_size)?;
validate_strides_1d(stride)?;
let activation = activation.into();
activation.validate()?;
Ok(Self {
channels: 0,
depth_multiplier: 1,
kernel_size,
stride,
dilation_rate: 1,
padding: PaddingType::Valid,
weights: Array3::zeros((0, 0, 0)),
bias: Array1::zeros(0),
activation,
built: None,
random_state: None,
use_bias: true,
})
}
pub fn with_padding(mut self, padding: PaddingType) -> Self {
self.padding = padding;
self
}
pub fn with_dilation_rate(mut self, dilation_rate: usize) -> Result<Self, Error> {
validate_dilation(&[dilation_rate])?;
self.dilation_rate = dilation_rate;
Ok(self)
}
pub fn with_depth_multiplier(mut self, depth_multiplier: usize) -> Result<Self, Error> {
validate_depth_multiplier(depth_multiplier)?;
self.depth_multiplier = depth_multiplier;
if self.built.is_some() {
self.draw_parameters();
}
Ok(self)
}
pub fn with_random_state(mut self, random_state: u64) -> Self {
self.random_state = Some(random_state);
if self.built.is_some() {
self.draw_parameters();
}
self
}
fn draw_parameters(&mut self) {
let mut rng = crate::random::make_rng(self.random_state);
self.weights = Initializer::GlorotUniform.draw(
(self.kernel_size, self.channels, self.depth_multiplier),
Fans::conv(self.channels, self.depth_multiplier, self.kernel_size),
&mut rng,
);
self.bias = Array1::zeros(self.channels * self.depth_multiplier);
}
fn calculate_output_length(&self, input_length: usize) -> Result<usize, Error> {
match self.padding {
PaddingType::Valid => valid_output_size(
"DepthwiseConv1D",
"length",
input_length,
effective_kernel(self.kernel_size, self.dilation_rate),
self.stride,
),
PaddingType::Same => Ok(input_length.div_ceil(self.stride)),
}
}
pub fn with_use_bias(mut self, use_bias: bool) -> Self {
self.use_bias = use_bias;
self
}
pub fn set_weights(
&mut self,
weights: Array3<f32>,
bias: impl Into<Option<Array1<f32>>>,
) -> Result<(), Error> {
if self.built.is_none() {
return Err(Error::not_built("DepthwiseConv1D"));
}
validate_weight_shape("kernel", self.weights.shape(), weights.shape())?;
let bias = validate_optional_weight("bias", "use_bias", self.use_bias, bias.into())?;
if let Some(bias) = bias.as_ref() {
validate_weight_shape("bias", self.bias.shape(), bias.shape())?;
}
self.weights = weights;
if let Some(bias) = bias {
self.bias = bias;
}
Ok(())
}
fn geometry(&self, input_shape: &[usize]) -> Result<DepthwiseGeometry, Error> {
let length = input_shape[1];
let out_length = self.calculate_output_length(length)?;
let keff = effective_kernel(self.kernel_size, self.dilation_rate);
let pad = match self.padding {
PaddingType::Valid => 0,
PaddingType::Same => ((out_length - 1) * self.stride + keff).saturating_sub(length),
};
Ok(DepthwiseGeometry {
input: (1, length),
output: (1, out_length),
channels: self.channels,
depth_multiplier: self.depth_multiplier,
kernel: (1, self.kernel_size),
strides: (1, self.stride),
dilation: (1, self.dilation_rate),
pad_before: (0, pad / 2),
})
}
fn convolve(&self, input: &Tensor) -> Result<Tensor, Error> {
validate_built_input(&self.built, "DepthwiseConv1D", input.shape())?;
validate_valid_kernel_fits(
self.padding.into(),
&[self.kernel_size],
&[self.dilation_rate],
&input.shape()[1..2],
)?;
let g = self.geometry(input.shape())?;
let batch_size = input.shape()[0];
let input_std = input.as_standard_layout();
let src = input_std
.as_slice()
.expect("standard-layout array is contiguous");
let ker = self.weights.as_slice().expect("weights must be contiguous");
let bias = self
.use_bias
.then(|| self.bias.as_slice().expect("bias must be contiguous"));
let mut output = Array3::<f32>::zeros((batch_size, g.output.1, g.out_channels()));
depthwise_forward(
&g,
src,
ker,
bias,
output.as_slice_mut().expect("output is contiguous"),
);
Ok(output.into_dyn())
}
}
struct DepthwiseConv1DCache {
input: Tensor,
activation: ActivationCache,
}
impl LayerBase for DepthwiseConv1D {
fn layer_type(&self) -> &str {
"DepthwiseConv1D"
}
fn param_count(&self) -> ParamCounts {
let bias = if self.use_bias { self.bias.len() } else { 0 };
ParamCounts::trainable(self.weights.len() + bias)
}
fn parameters_mut(&mut self) -> Vec<ParamRef<'_>> {
let Self {
weights,
bias,
use_bias,
..
} = self;
let mut params = vec![ParamRef::weight(
"kernel",
weights.as_slice_mut().expect("weights must be contiguous"),
)];
if *use_bias {
params.push(ParamRef::no_decay(
"bias",
bias.as_slice_mut().expect("bias must be contiguous"),
));
}
params
}
built_layer_shape_functions!();
named_weight_layer_functions!(
trainable "kernel" => weights,
trainable "bias" => bias if use_bias,
);
}
impl UnaryLayer for DepthwiseConv1D {
fn build(&mut self, input: &Shape) -> Result<(), Error> {
let Some(built) = start_build(&self.built, "DepthwiseConv1D", input)? else {
return Ok(());
};
built.check_rank("DepthwiseConv1D", 3)?;
let (batch, tail) = built.split_batch("DepthwiseConv1D")?;
let mut dims = vec![batch.unwrap_or(1)];
dims.extend(tail);
validate_input_shape_1d(&dims)?;
self.compute_output_shape(&built)?;
self.channels = dims[2];
self.built = Some(built);
self.draw_parameters();
Ok(())
}
fn forward(&self, input: &Tensor, ctx: &mut Ctx) -> Result<Tensor, Error> {
if !self.is_built() {
return Err(Error::not_built("DepthwiseConv1D"));
}
let z = self.convolve(input)?;
if !ctx.is_training() {
return self.activation.forward(&z);
}
let (activated, activation) = self.activation.forward_train(z)?;
ctx.push_cache(
"DepthwiseConv1D",
DepthwiseConv1DCache {
input: input.clone(),
activation,
},
);
Ok(activated)
}
fn backward(&self, grad_output: &Tensor, ctx: &mut Ctx) -> Result<Tensor, Error> {
let cache: DepthwiseConv1DCache = ctx.pop_cache("DepthwiseConv1D")?;
let grad_upstream = self.activation.backward(&cache.activation, grad_output)?;
let input = &cache.input;
let batch_size = input.shape()[0];
let g = self.geometry(input.shape())?;
let input_std = input.as_standard_layout();
let src = input_std
.as_slice()
.expect("standard-layout array is contiguous");
let grad_std = grad_upstream.as_standard_layout();
let grad = grad_std
.as_slice()
.expect("standard-layout array is contiguous");
let ker = self.weights.as_slice().expect("weights must be contiguous");
let grads = depthwise_backward(&g, src, grad, ker, batch_size);
ctx.add_grad(
"kernel",
Array3::from_shape_vec(self.weights.raw_dim(), grads.weight)
.expect("weight gradient shape matches weights")
.into_dyn(),
)?;
if self.use_bias {
ctx.add_grad("bias", Array1::from_vec(grads.bias).into_dyn())?;
}
Ok(
Array3::from_shape_vec((batch_size, g.input.1, g.channels), grads.input)
.expect("input gradient shape matches input")
.into_dyn(),
)
}
fn compute_output_shape(&self, input: &Shape) -> Result<Shape, Error> {
input.check_rank("DepthwiseConv1D", 3)?;
let (batch, tail) = input.split_batch("DepthwiseConv1D")?;
let channels = tail[1];
if self.built.is_some() && channels != self.channels {
return Err(Error::dimension_mismatch(self.channels, channels));
}
Ok(Shape::from_batch(
batch,
&[
self.calculate_output_length(tail[0])?,
channels * self.depth_multiplier,
],
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::neural_network::layers::activation::linear::Linear;
use ndarray::ArrayD;
#[test]
fn depthwise_1d_forward_keeps_channels_separate_hand_derived() {
let mut layer = DepthwiseConv1D::new(2, 1, Linear::new()).unwrap();
layer.build(&Shape::known(&[1, 5, 2])).unwrap();
let weights = Array3::from_shape_vec((2, 2, 1), vec![1.0, 2.0, 1.0, 2.0]).unwrap();
layer.set_weights(weights, Array1::zeros(2)).unwrap();
let input = ArrayD::from_shape_vec(
ndarray::IxDyn(&[1, 5, 2]),
vec![1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0, 1.0, 5.0, 1.0],
)
.unwrap();
let out = layer.forward(&input, &mut Ctx::inference()).unwrap();
assert_eq!(out.shape(), &[1, 4, 2]);
assert_eq!(
out.iter().copied().collect::<Vec<f32>>(),
vec![3.0, 4.0, 5.0, 4.0, 7.0, 4.0, 9.0, 4.0]
);
}
#[test]
fn depthwise_1d_depth_multiplier_output_channel_order() {
let mut layer = DepthwiseConv1D::new(1, 1, Linear::new())
.unwrap()
.with_depth_multiplier(2)
.unwrap();
layer.build(&Shape::known(&[1, 1, 2])).unwrap();
assert_eq!(layer.weights.shape(), &[1, 2, 2]);
let weights = Array3::from_shape_vec((1, 2, 2), vec![1.0, 10.0, 100.0, 1000.0]).unwrap();
layer.set_weights(weights, Array1::zeros(4)).unwrap();
let input = ArrayD::from_shape_vec(ndarray::IxDyn(&[1, 1, 2]), vec![2.0, 3.0]).unwrap();
let out = layer.forward(&input, &mut Ctx::inference()).unwrap();
assert_eq!(out.shape(), &[1, 1, 4]);
assert_eq!(
out.iter().copied().collect::<Vec<f32>>(),
vec![2.0, 20.0, 300.0, 3000.0]
);
}
}