v9.1.1
Menu

Depthwise Separable Convolution

Implement depthwise separable convolution, a key efficiency technique in MobileNets.

Standard convolution: Cin×H×W→Cout×H′×W′C_{in} \times H \times W \rightarrow C_{out} \times H' \times W' Parameters: Cout×Cin×K×KC_{out} \times C_{in} \times K \times K

Depthwise separable breaks this into (both steps use stride 1 and no padding, so a K×KK \times K kernel shrinks each spatial side to H−K+1H - K + 1):

  1. Depthwise: Each input channel convolved separately
    • Parameters: Cin×K×KC_{in} \times K \times K
  2. Pointwise: 1×1 convolution to mix channels
    • Parameters: Cout×CinC_{out} \times C_{in}

Efficiency gain: 1Cout+1K2\frac{1}{C_{out}} + \frac{1}{K^2} of standard conv!

Example

Input
input: (1, 3, 8, 8)  # RGB image
depthwise: (3, 1, 3, 3)  # 3x3 per channel
pointwise: (16, 3, 1, 1)  # Expand to 16 channels
Output
tensor of shape (1, 16, 6, 6)
Reasoning
  • Inputs: x is a batch of 1 image with Cin=3C_{in}=3 channels on an 8×88 \times 8 grid; the depthwise kernel holds one 3×33 \times 3 filter per channel (3×1×3×33 \times 1 \times 3 \times 3); the pointwise kernel holds a weight Po,cP_{o,c} per (output, input) channel pair (16×3×1×116 \times 3 \times 1 \times 1).
  • Depthwise step: channel cc is filtered only by its own kernel, Dc(i,j)=∑u,vxc(i+u,j+v) kc(u,v)D_c(i,j) = \sum_{u,v} x_c(i+u, j+v)\,k_c(u,v). With no padding and stride 1, a 3×33 \times 3 window fits in 8−3+1=68 - 3 + 1 = 6 positions per axis: 1×3×6×61 \times 3 \times 6 \times 6, channels unmixed.
  • Pointwise step: at every pixel, yo(i,j)=∑c=13Po,c Dc(i,j)y_o(i,j) = \sum_{c=1}^{3} P_{o,c}\,D_c(i,j), which mixes the 3 channels into 16 without touching the 6×66 \times 6 grid: tensor of shape (1, 16, 6, 6).
  • Check with all-ones tensors: each depthwise value is 99, each output value is 3×9=273 \times 9 = 27.
  • Notice the savings: 3⋅9+16⋅3=753 \cdot 9 + 16 \cdot 3 = 75 weights versus 16⋅3⋅9=43216 \cdot 3 \cdot 9 = 432 for a standard conv, a ratio of 116+19≈0.174\frac{1}{16} + \frac{1}{9} \approx 0.174.

Constraints

  • input: Tensor (batch, channels, height, width)
  • depthwise_kernel: (channels, 1, k, k)
  • pointwise_kernel: (out_channels, channels, 1, 1)
  • Return: Output tensor

More from CV: Deep Learning

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.