Implement a multi-channel grouped conv2d with stride, padding and dilation
Why it matters Every CNN layer is a conv2d like this; grouped and depthwise convs are the same code with a different groups value.
Real conv layers mix many input channels, and ResNeXt, MobileNet and ConvNeXt use groups. One function covers them all.
Write conv2d_grouped(x, w, b, stride=1, padding=0, dilation=1, groups=1). x is (C_in, H, W), w is (C_out, C_in // groups, kh, kw), b is (C_out,). Zero-pad x by padding on every side. Output channel o belongs to group o // (C_out // groups) and only sees that group's C_in // groups input channels. Kernel taps are dilation apart. Output size is Ho = (H + 2 * padding - dilation * (kh - 1) - 1) // stride + 1, and the same for Wo. Return a (C_out, Ho, Wo) float array (cross-correlation, no kernel flip).
def conv2d_grouped(x, w, b, stride=1, padding=0, dilation=1, groups=1)Example
x = ones((2, 3, 3)), w = ones((2, 1, 2, 2)), b = [0, 10], groups = 2 gives [[[4, 4], [4, 4]], [[14, 14], [14, 14]]].
Understand the idea
A conv layer slides a small filter over the image. With several input channels, the filter has one slice per input channel and the results are added. Groups split the channels into independent teams: each output channel only looks at its own team's inputs, which cuts the cost by the number of groups. Dilation spaces the filter taps apart to see wider without more weights; stride skips positions; padding adds a zero border.
Tiny example: two input channels of ones, groups = 2, one 2x2 kernel of ones per output. Each output channel sees only one input channel: 4 ones, so 4, plus bias 0 or 10.
Rule: out[o, i, j] = b[o] + sum over the group's channels and taps of x[c, i*s + u*d, j*s + v*d] * w[o, c, u, v].
ResNeXt uses groups, MobileNet uses groups = C_in (depthwise), and DeepLab uses dilation.
Shapes and data flow
x (C_in,H,W), w (C_out, C_in/g, kh, kw) -> out (C_out, Ho, Wo)