use crate::error::Error;
use crate::neural_network::Tensor;
use crate::neural_network::layers::TrainingParameters;
use crate::neural_network::layers::activation::Activation;
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::{conv_backward, conv_forward};
use crate::neural_network::layers::convolution::validation::{
validate_depth_multiplier, validate_filters, validate_input_shape_1d, validate_kernel_size_1d,
validate_strides_1d,
};
use crate::neural_network::layers::layer_weight::{LayerWeight, SeparableConv1DLayerWeight};
use crate::neural_network::layers::validation::validate_weight_shape;
use crate::neural_network::traits::{Layer, ParamGrad};
use ndarray::{Array1, Array3};
use ndarray_rand::{RandomExt, rand_distr::Uniform};
use std::borrow::Cow;
#[derive(Debug)]
pub struct SeparableConv1D {
filters: usize,
channels: usize,
kernel_size: usize,
stride: usize,
padding: PaddingType,
depth_multiplier: usize,
depthwise_weights: Array3<f32>,
pointwise_weights: Array3<f32>,
bias: Array1<f32>,
activation: Activation,
output_cache: Option<Tensor>,
input_cache: Option<Tensor>,
depthwise_output_cache: Option<Tensor>,
input_shape: Vec<usize>,
depthwise_weight_gradients: Option<Array3<f32>>,
pointwise_weight_gradients: Option<Array3<f32>>,
bias_gradients: Option<Array1<f32>>,
}
impl SeparableConv1D {
pub fn new(
filters: usize,
kernel_size: usize,
input_shape: Vec<usize>,
stride: usize,
depth_multiplier: usize,
activation: impl Into<Activation>,
) -> Result<Self, Error> {
validate_filters(filters)?;
validate_kernel_size_1d(kernel_size)?;
validate_strides_1d(stride)?;
validate_depth_multiplier(depth_multiplier)?;
validate_input_shape_1d(&input_shape, kernel_size)?;
let activation = activation.into();
activation.validate()?;
let channels = input_shape[2];
let (depthwise_weights, pointwise_weights) =
Self::init_weights_arrays(filters, channels, kernel_size, depth_multiplier, None);
let bias = Array1::zeros(filters);
Ok(SeparableConv1D {
filters,
channels,
kernel_size,
stride,
padding: PaddingType::Valid,
depth_multiplier,
depthwise_weights,
pointwise_weights,
bias,
activation,
output_cache: None,
input_cache: None,
depthwise_output_cache: None,
input_shape,
depthwise_weight_gradients: None,
pointwise_weight_gradients: None,
bias_gradients: None,
})
}
pub fn with_padding(mut self, padding: PaddingType) -> Self {
self.padding = padding;
self
}
pub fn with_random_state(mut self, random_state: u64) -> Self {
let (depthwise_weights, pointwise_weights) = Self::init_weights_arrays(
self.filters,
self.channels,
self.kernel_size,
self.depth_multiplier,
Some(random_state),
);
self.depthwise_weights = depthwise_weights;
self.pointwise_weights = pointwise_weights;
self
}
fn init_weights_arrays(
filters: usize,
channels: usize,
kernel_size: usize,
depth_multiplier: usize,
random_state: Option<u64>,
) -> (Array3<f32>, Array3<f32>) {
let depthwise_fan_in = channels * kernel_size;
let depthwise_fan_out = depth_multiplier * kernel_size;
let depthwise_bound = (6.0 / (depthwise_fan_in + depthwise_fan_out) as f32).sqrt();
let mut rng = crate::random::make_rng(random_state);
let depthwise_weights = Array3::random_using(
(kernel_size, channels, depth_multiplier),
Uniform::new(-depthwise_bound, depthwise_bound).unwrap(),
&mut rng,
);
let pointwise_fan_in = channels * depth_multiplier;
let pointwise_fan_out = filters;
let pointwise_bound = (6.0 / (pointwise_fan_in + pointwise_fan_out) as f32).sqrt();
let pointwise_weights = Array3::random_using(
(1, channels * depth_multiplier, filters),
Uniform::new(-pointwise_bound, pointwise_bound).unwrap(),
&mut rng,
);
(depthwise_weights, pointwise_weights)
}
fn calculate_output_length(&self, input_length: usize) -> usize {
match self.padding {
PaddingType::Valid => (input_length - self.kernel_size) / self.stride + 1,
PaddingType::Same => input_length.div_ceil(self.stride),
}
}
fn depthwise_geometry(&self, input_shape: &[usize]) -> DepthwiseGeometry {
let length = input_shape[1];
let out_length = self.calculate_output_length(length);
let pad = match self.padding {
PaddingType::Valid => 0,
PaddingType::Same => {
((out_length - 1) * self.stride + self.kernel_size).saturating_sub(length)
}
};
DepthwiseGeometry {
input: (1, length),
output: (1, out_length),
channels: input_shape[2],
depth_multiplier: self.depth_multiplier,
kernel: (1, self.kernel_size),
strides: (1, self.stride),
pad_before: (0, pad / 2),
}
}
fn validate_input(&self, input: &Tensor) -> Result<(), Error> {
if input.ndim() != 3 {
return Err(Error::invalid_input("input tensor is not 3D"));
}
let channels = input.shape()[2];
if channels != self.channels {
return Err(Error::dimension_mismatch(self.channels, channels));
}
Ok(())
}
fn depthwise_convolve(&self, input: &Tensor) -> Tensor {
let g = self.depthwise_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
.depthwise_weights
.as_slice()
.expect("depthwise weights must be contiguous");
let mut output = Array3::<f32>::zeros((batch_size, g.output.1, g.out_channels()));
depthwise_forward(
&g,
src,
ker,
None,
output.as_slice_mut().expect("output is contiguous"),
);
output.into_dyn()
}
fn pointwise_convolve(&self, input: &Tensor) -> Tensor {
conv_forward(
input,
self.pointwise_weights
.as_slice()
.expect("pointwise weights must be contiguous"),
self.pointwise_weights.shape(),
self.bias.as_slice().expect("bias must be contiguous"),
&[1],
PaddingType::Valid,
)
.expect("1-tap pointwise convolution geometry is always valid")
}
pub fn set_weights(
&mut self,
depthwise_weights: Array3<f32>,
pointwise_weights: Array3<f32>,
bias: Array1<f32>,
) -> Result<(), Error> {
validate_weight_shape(
"depthwise_weight",
self.depthwise_weights.shape(),
depthwise_weights.shape(),
)?;
validate_weight_shape(
"pointwise_weight",
self.pointwise_weights.shape(),
pointwise_weights.shape(),
)?;
validate_weight_shape("bias", self.bias.shape(), bias.shape())?;
self.depthwise_weights = depthwise_weights;
self.pointwise_weights = pointwise_weights;
self.bias = bias;
Ok(())
}
}
impl Layer for SeparableConv1D {
fn forward(&mut self, input: &Tensor) -> Result<Tensor, Error> {
self.validate_input(input)?;
self.input_cache = Some(input.clone());
let depthwise_output = self.depthwise_convolve(input);
let output = self.pointwise_convolve(&depthwise_output);
self.depthwise_output_cache = Some(depthwise_output);
let activated = self.activation.forward(&output)?;
self.output_cache = Some(activated.clone());
Ok(activated)
}
fn predict(&self, input: &Tensor) -> Result<Tensor, Error> {
self.validate_input(input)?;
let depthwise_output = self.depthwise_convolve(input);
let output = self.pointwise_convolve(&depthwise_output);
self.activation.forward(&output)
}
fn backward(&mut self, grad_output: &Tensor) -> Result<Tensor, Error> {
let activated = self
.output_cache
.take()
.ok_or_else(|| Error::forward_pass_not_run("SeparableConv1D"))?;
let grad_upstream = self.activation.backward(&activated, grad_output)?;
let (Some(input), Some(depthwise_output)) =
(&self.input_cache, &self.depthwise_output_cache)
else {
return Err(Error::forward_pass_not_run("SeparableConv1D"));
};
let batch_size = input.shape()[0];
let g = self.depthwise_geometry(input.shape());
let pw_grads = conv_backward(
&grad_upstream,
depthwise_output,
self.pointwise_weights
.as_slice()
.expect("pointwise weights must be contiguous"),
self.pointwise_weights.shape(),
&[1],
PaddingType::Valid,
)
.expect("1-tap pointwise convolution geometry is always valid");
self.pointwise_weight_gradients = Some(
Array3::from_shape_vec(self.pointwise_weights.raw_dim(), pw_grads.weight_grad)
.expect("pointwise weight gradient shape matches weights"),
);
self.bias_gradients = Some(Array1::from_vec(pw_grads.bias_grad));
let depthwise_grad = pw_grads.input_grad;
let input_std = input.as_standard_layout();
let src = input_std
.as_slice()
.expect("standard-layout array is contiguous");
let grad_std = depthwise_grad.as_standard_layout();
let grad = grad_std
.as_slice()
.expect("standard-layout array is contiguous");
let ker = self
.depthwise_weights
.as_slice()
.expect("depthwise weights must be contiguous");
let dw_grads = depthwise_backward(&g, src, grad, ker, batch_size);
self.depthwise_weight_gradients = Some(
Array3::from_shape_vec(self.depthwise_weights.raw_dim(), dw_grads.weight)
.expect("depthwise weight gradient shape matches weights"),
);
Ok(
Array3::from_shape_vec((batch_size, g.input.1, g.channels), dw_grads.input)
.expect("input gradient shape matches input")
.into_dyn(),
)
}
fn layer_type(&self) -> &str {
"SeparableConv1D"
}
fn output_shape(&self) -> String {
let output_length = self.calculate_output_length(self.input_shape[1]);
format!(
"({}, {}, {})",
self.input_shape[0], output_length, self.filters
)
}
fn param_count(&self) -> TrainingParameters {
TrainingParameters::Trainable(
self.depthwise_weights.len() + self.pointwise_weights.len() + self.bias.len(),
)
}
fn parameters(&mut self) -> Vec<ParamGrad<'_>> {
let Self {
depthwise_weights,
pointwise_weights,
bias,
depthwise_weight_gradients,
pointwise_weight_gradients,
bias_gradients,
..
} = self;
let mut params = Vec::new();
if let (Some(gd), Some(gp), Some(gb)) = (
depthwise_weight_gradients.as_ref(),
pointwise_weight_gradients.as_ref(),
bias_gradients.as_ref(),
) {
params.push(ParamGrad::weight(
depthwise_weights
.as_slice_mut()
.expect("depthwise weights must be contiguous"),
gd.as_slice()
.expect("depthwise weight gradient must be contiguous"),
));
params.push(ParamGrad::weight(
pointwise_weights
.as_slice_mut()
.expect("pointwise weights must be contiguous"),
gp.as_slice()
.expect("pointwise weight gradient must be contiguous"),
));
params.push(ParamGrad::no_decay(
bias.as_slice_mut().expect("bias must be contiguous"),
gb.as_slice().expect("bias gradient must be contiguous"),
));
}
params
}
fn get_weights(&self) -> LayerWeight<'_> {
LayerWeight::SeparableConv1D(SeparableConv1DLayerWeight {
depthwise_weight: Cow::Borrowed(&self.depthwise_weights),
pointwise_weight: Cow::Borrowed(&self.pointwise_weights),
bias: Cow::Borrowed(&self.bias),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::neural_network::layers::activation::linear::Linear;
use ndarray::ArrayD;
#[test]
fn separable_1d_stage_channel_order_hand_derived() {
let mut layer = SeparableConv1D::new(1, 1, vec![1, 1, 2], 1, 2, Linear::new()).unwrap();
assert_eq!(layer.depthwise_weights.shape(), &[1, 2, 2]);
assert_eq!(layer.pointwise_weights.shape(), &[1, 4, 1]);
let depthwise = Array3::from_shape_vec((1, 2, 2), vec![1.0, 10.0, 100.0, 1000.0]).unwrap();
let pointwise = Array3::from_shape_vec((1, 4, 1), vec![1.0, 2.0, 4.0, 8.0]).unwrap();
layer
.set_weights(depthwise, pointwise, Array1::zeros(1))
.unwrap();
let input = ArrayD::from_shape_vec(ndarray::IxDyn(&[1, 1, 2]), vec![2.0, 3.0]).unwrap();
let out = layer.predict(&input).unwrap();
assert_eq!(out.shape(), &[1, 1, 1]);
assert_eq!(out.iter().copied().collect::<Vec<f32>>(), vec![25242.0]);
}
#[test]
fn separable_1d_length_pass_hand_derived() {
let mut layer = SeparableConv1D::new(1, 2, vec![1, 4, 1], 1, 1, Linear::new()).unwrap();
let depthwise = Array3::from_shape_vec((2, 1, 1), vec![1.0, 1.0]).unwrap();
let pointwise = Array3::from_shape_vec((1, 1, 1), vec![3.0]).unwrap();
layer
.set_weights(depthwise, pointwise, Array1::zeros(1))
.unwrap();
let input =
ArrayD::from_shape_vec(ndarray::IxDyn(&[1, 4, 1]), vec![1.0, 2.0, 3.0, 4.0]).unwrap();
let out = layer.predict(&input).unwrap();
assert_eq!(out.shape(), &[1, 3, 1]);
assert_eq!(
out.iter().copied().collect::<Vec<f32>>(),
vec![9.0, 15.0, 21.0]
);
}
}