pub fn conv2d_backward_kernel<F>(
input: &ArrayView4<'_, F>,
grad_output: &ArrayView4<'_, F>,
kernelshape: (usize, usize, usize, usize),
stride: (usize, usize),
padding: (usize, usize),
dilation: (usize, usize),
) -> LinalgResult<Array4<F>>
Expand description
Apply backward pass of convolution operation for kernel gradient
This function computes the gradient of the kernel in a convolutional layer given the gradient of the output and the input.
§Arguments
input
- Input tensor of shape (batchsize, in_channels, height, width)grad_output
- Gradient of the output tensor of shape (batchsize, out_channels_, output_h, output_w)kernelshape
- Shape of the kernel tensor (out_channels_, in_channels, kernel_h, kernel_w)stride
- Stride as (stride_height, stride_width)padding
- Padding as (padding_height, padding_width)dilation
- Dilation as (dilation_height, dilation_width)
§Returns
- Gradient of the kernel tensor of shape (out_channels_, in_channels, kernel_h, kernel_w)
§Examples
use scirs2_core::ndarray::Array4;
use scirs2_linalg::convolution::{conv2d_im2col, conv2d_backward_kernel};
// Simple example with smaller dimensions
let input = Array4::<f32>::zeros((1, 1, 4, 4));
let kernelshape = (1, 1, 2, 2);
// Forward pass to get output shape
let kernel = Array4::<f32>::zeros(kernelshape);
let output = conv2d_im2col(
&input.view(),
&kernel.view(),
None,
(1, 1), // stride
(0, 0), // padding
(1, 1), // dilation
).unwrap();
// Backward pass - grad_output must match forward output shape
let grad_output = Array4::<f32>::ones(output.dim());
let grad_kernel = conv2d_backward_kernel(
&input.view(),
&grad_output.view(),
kernelshape,
(1, 1),
(0, 0),
(1, 1),
).unwrap();
// Gradient shape matches kernel shape
assert_eq!(grad_kernel.shape(), &[1, 1, 2, 2]);