Implement hard swish

Why it matters On-device models such as MobileNetV3 use hard swish because it needs no exp.

Mobile vision models replace swish with a cheap piecewise-linear version.

Write hard_swish(x). Return x * relu6(x + 3) / 6, where relu6(v) = min(max(v, 0), 6).

Signaturedef hard_swish(x)

Example

hard_swish([-4, 0, 1, 4]) is [0, 0, 0.6667, 4].

Understand the idea

Swish (x times sigmoid(x)) works well but sigmoid is costly on phones. Hard swish replaces the sigmoid with a straight-line gate that is 0 below -3, 1 above 3, and rises linearly in between. It is just a few adds, a clamp and a multiply. Worked example: x = -3 gives relu6(0) = 0, so the output is 0. x = -1 gives relu6(2) = 2, so the output is -1 * 2 / 6 = -0.333. x = 2 gives relu6(5) = 5, so the output is 2 * 5 / 6 = 1.667. x = 5 gives relu6(8) = 6, so the output is 5 * 6 / 6 = 5. Rule: hard_swish(x) = x * relu6(x + 3) / 6, where relu6(v) = min(max(v, 0), 6). The cap at 6 is what makes the output exactly x for x >= 3; without it, large inputs grow like x squared. Inputs can be scalars or arrays, so use element-wise operations. Used in: MobileNetV3 and other efficient vision models built for mobile hardware.

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

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

  • Sample 1: examplehard_swish([-4, 0, 1, 4])
  • Sample 2: edgeshard_swish([-3, 3, 10])
  • Test 3: gridhard_swish(np.linspace(-5, 5, 11))