Compare parameters and multiply-adds of standard vs depthwise separable conv

Why it matters This ratio is why MobileNet and EfficientNet run on phones.

MobileNet's main trick is replacing one k x k conv with a depthwise k x k conv plus a 1 x 1 pointwise conv. The savings are easy to compute.

Write conv_costs(c_in, c_out, k, h_out, w_out). Both designs have biases. Standard conv: params = c_out * c_in * k * k + c_out, MACs = c_out * c_in * k * k * h_out * w_out. Depthwise separable: depthwise params = c_in * k * k + c_in, pointwise params = c_in * c_out + c_out; MACs = (c_in * k * k + c_in * c_out) * h_out * w_out (bias adds are not counted). Return a dict with integer values for "standard_params", "separable_params", "standard_macs", "separable_macs".

Signaturedef conv_costs(c_in, c_out, k, h_out, w_out)

Example

conv_costs(32, 64, 3, 10, 10) gives standard_params 18496, separable_params 2432, standard_macs 1843200, separable_macs 233600.

Understand the idea

A normal conv does two jobs at once: it looks at a spatial neighbourhood and mixes channels. Depthwise separable conv splits the jobs: first each channel is filtered on its own (depthwise), then a 1 x 1 conv mixes channels (pointwise). Like a kitchen where one cook chops each ingredient separately and another combines them, instead of every cook doing everything.

Tiny example: 32 in, 64 out, 3 x 3. Standard weights 64 * 32 * 9 = 18432. Separable: 32 * 9 = 288 depthwise plus 32 * 64 = 2048 pointwise = 2336. About 8 times fewer.

Rules: standard MACs = c_out * c_in * k^2 * HW; separable MACs = (c_in * k^2 + c_in * c_out) * HW; ratio = 1/c_out + 1/k^2.

MobileNet, Xception and EfficientNet are built from these blocks.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleconv_costs(32, 64, 3, 10, 10)
  • Sample 2: mobilenet-likeconv_costs(256, 256, 3, 14, 14)
  • Test 3: 5x5conv_costs(16, 8, 5, 4, 6)