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_2d,
validate_kernel_size_2d, validate_strides_2d, validate_valid_kernel_fits,
};
use crate::neural_network::layers::shape_helpers::calculate_output_shape_2d;
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, Array4};
#[derive(Debug)]
pub struct DepthwiseConv2D {
channels: usize,
depth_multiplier: usize,
kernel_size: (usize, usize),
strides: (usize, usize),
dilation_rate: (usize, usize),
padding: PaddingType,
weights: Array4<f32>,
bias: Array1<f32>,
activation: Activation,
built: Option<Shape>,
random_state: Option<u64>,
use_bias: bool,
}
impl DepthwiseConv2D {
pub fn new(
kernel_size: (usize, usize),
strides: (usize, usize),
activation: impl Into<Activation>,
) -> Result<Self, Error> {
validate_kernel_size_2d(kernel_size)?;
validate_strides_2d(strides)?;
let activation = activation.into();
activation.validate()?;
Ok(Self {
channels: 0,
depth_multiplier: 1,
kernel_size,
strides,
dilation_rate: (1, 1),
padding: PaddingType::Valid,
weights: Array4::zeros((0, 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, usize)) -> Result<Self, Error> {
let dilation = [dilation_rate.0, dilation_rate.1];
validate_dilation(&dilation)?;
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 (kernel_height, kernel_width) = self.kernel_size;
let mut rng = crate::random::make_rng(self.random_state);
self.weights = Initializer::GlorotUniform.draw(
(
kernel_height,
kernel_width,
self.channels,
self.depth_multiplier,
),
Fans::conv(
self.channels,
self.depth_multiplier,
kernel_height * kernel_width,
),
&mut rng,
);
self.bias = Array1::zeros(self.channels * self.depth_multiplier);
}
fn calculate_padding(
&self,
input_height: usize,
input_width: usize,
output_height: usize,
output_width: usize,
) -> (usize, usize) {
match self.padding {
PaddingType::Valid => (0, 0),
PaddingType::Same => {
let (keff_h, keff_w) = self.effective_kernel_size();
let pad_h =
((output_height - 1) * self.strides.0 + keff_h).saturating_sub(input_height);
let pad_w =
((output_width - 1) * self.strides.1 + keff_w).saturating_sub(input_width);
(pad_h, pad_w)
}
}
}
pub fn with_use_bias(mut self, use_bias: bool) -> Self {
self.use_bias = use_bias;
self
}
pub fn set_weights(
&mut self,
weights: Array4<f32>,
bias: impl Into<Option<Array1<f32>>>,
) -> Result<(), Error> {
if self.built.is_none() {
return Err(Error::not_built("DepthwiseConv2D"));
}
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]) -> DepthwiseGeometry {
let (height, width) = (input_shape[1], input_shape[2]);
let output_shape = calculate_output_shape_2d(
input_shape,
self.effective_kernel_size(),
self.strides,
&self.padding,
);
let (out_height, out_width) = (output_shape[1], output_shape[2]);
let (pad_h, pad_w) = self.calculate_padding(height, width, out_height, out_width);
DepthwiseGeometry {
input: (height, width),
output: (out_height, out_width),
channels: self.channels,
depth_multiplier: self.depth_multiplier,
kernel: self.kernel_size,
strides: self.strides,
dilation: self.dilation_rate,
pad_before: (pad_h / 2, pad_w / 2),
}
}
fn effective_kernel_size(&self) -> (usize, usize) {
(
effective_kernel(self.kernel_size.0, self.dilation_rate.0),
effective_kernel(self.kernel_size.1, self.dilation_rate.1),
)
}
fn convolve(&self, input: &Tensor) -> Result<Tensor, Error> {
validate_built_input(&self.built, "DepthwiseConv2D", input.shape())?;
validate_valid_kernel_fits(
self.padding.into(),
&[self.kernel_size.0, self.kernel_size.1],
&[self.dilation_rate.0, self.dilation_rate.1],
&input.shape()[1..3],
)?;
let g = self.geometry(input.shape());
let batch_size = input.shape()[0];
let out_channels = g.out_channels();
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 = Array4::<f32>::zeros((batch_size, g.output.0, g.output.1, out_channels));
depthwise_forward(
&g,
src,
ker,
bias,
output.as_slice_mut().expect("output is contiguous"),
);
Ok(output.into_dyn())
}
}
struct DepthwiseConv2DCache {
input: Tensor,
activation: ActivationCache,
}
impl LayerBase for DepthwiseConv2D {
fn layer_type(&self) -> &str {
"DepthwiseConv2D"
}
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 DepthwiseConv2D {
fn build(&mut self, input: &Shape) -> Result<(), Error> {
let Some(built) = start_build(&self.built, "DepthwiseConv2D", input)? else {
return Ok(());
};
built.check_rank("DepthwiseConv2D", 4)?;
let (batch, tail) = built.split_batch("DepthwiseConv2D")?;
let mut dims = vec![batch.unwrap_or(1)];
dims.extend(tail);
validate_input_shape_2d(&dims)?;
self.compute_output_shape(&built)?;
self.channels = dims[3];
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("DepthwiseConv2D"));
}
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(
"DepthwiseConv2D",
DepthwiseConv2DCache {
input: input.clone(),
activation,
},
);
Ok(activated)
}
fn backward(&self, grad_output: &Tensor, ctx: &mut Ctx) -> Result<Tensor, Error> {
let cache: DepthwiseConv2DCache = ctx.pop_cache("DepthwiseConv2D")?;
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",
Array4::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(
Array4::from_shape_vec((batch_size, g.input.0, 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("DepthwiseConv2D", 4)?;
let (batch, tail) = input.split_batch("DepthwiseConv2D")?;
let (height, width) = (tail[0], tail[1]);
let channels = tail[2];
if self.built.is_some() && channels != self.channels {
return Err(Error::dimension_mismatch(self.channels, channels));
}
let (keff_h, keff_w) = self.effective_kernel_size();
let (out_height, out_width) = match self.padding {
PaddingType::Valid => (
valid_output_size("DepthwiseConv2D", "height", height, keff_h, self.strides.0)?,
valid_output_size("DepthwiseConv2D", "width", width, keff_w, self.strides.1)?,
),
PaddingType::Same => (
height.div_ceil(self.strides.0),
width.div_ceil(self.strides.1),
),
};
Ok(Shape::from_batch(
batch,
&[out_height, out_width, channels * self.depth_multiplier],
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::neural_network::layers::activation::linear::Linear;
use ndarray::ArrayD;
#[test]
fn depthwise_forward_keeps_channels_separate_hand_derived() {
let mut layer = DepthwiseConv2D::new((2, 2), (1, 1), Linear::new()).unwrap();
layer.build(&Shape::known(&[1, 3, 3, 2])).unwrap();
let weights =
Array4::from_shape_vec((2, 2, 2, 1), vec![1.0, 2.0, 1.0, 2.0, 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, 3, 3, 2]),
vec![
1.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0, 1.0, 5.0, 1.0, 6.0, 1.0, 7.0, 1.0, 8.0, 1.0, 9.0, 1.0, ],
)
.unwrap();
let out = layer.forward(&input, &mut Ctx::inference()).unwrap();
assert_eq!(out.shape(), &[1, 2, 2, 2]);
assert_eq!(
out.iter().copied().collect::<Vec<f32>>(),
vec![12.0, 8.0, 16.0, 8.0, 24.0, 8.0, 28.0, 8.0]
);
}
#[test]
fn depthwise_depth_multiplier_output_channel_order() {
let mut layer = DepthwiseConv2D::new((1, 1), (1, 1), Linear::new())
.unwrap()
.with_depth_multiplier(2)
.unwrap();
layer.build(&Shape::known(&[1, 1, 1, 2])).unwrap();
assert_eq!(layer.weights.shape(), &[1, 1, 2, 2]);
let weights = Array4::from_shape_vec((1, 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, 1, 2]), vec![2.0, 3.0]).unwrap();
let out = layer.forward(&input, &mut Ctx::inference()).unwrap();
assert_eq!(out.shape(), &[1, 1, 1, 4]);
assert_eq!(
out.iter().copied().collect::<Vec<f32>>(),
vec![2.0, 20.0, 300.0, 3000.0]
);
}
}