Fold an eval-mode batch norm into the preceding linear layer

Why it matters ONNX, TensorRT and mobile converters fold batch norm this way to make inference faster.

At inference, batch norm is just a fixed scale and shift, so deployment tools merge it into the previous layer and delete it.

Write fold_bn(W, b, gamma, beta, mean, var, eps=1e-5). The layer is z = x @ W + b with W of shape (d_in, d_out), followed by eval-mode batch norm y = gamma * (z - mean) / sqrt(var + eps) + beta, where all BN vectors are (d_out,). Return (W_new, b_new) such that x @ W_new + b_new equals y for every x.

Signaturedef fold_bn(W, b, gamma, beta, mean, var, eps=1e-5)

Example

W = [[2]], b = [1], gamma = [3], beta = [0.5], mean = [1], var = [3.99999] (eps 1e-5, so sqrt is 2) gives W_new [[3.0]] and b_new [0.5].

Understand the idea

At test time batch norm uses fixed running statistics, so it is no longer anything clever: just multiply by a number and add a number, per output unit. A linear layer is also multiply and add. Two multiply-and-adds in a row can be merged into one, the same way a 10% discount followed by a 20% discount is one 28% discount.

Tiny example: z = 2x + 1, then BN with gamma 3, mean 1, std 2, beta 0.5: y = 3 * (2x + 1 - 1) / 2 + 0.5 = 3x + 0.5. So W_new = 3 and b_new = 0.5.

Rule: s = gamma / sqrt(var + eps); W_new = W * s; b_new = (b - mean) * s + beta.

Model export tools for phones and GPUs apply this to every conv plus batch norm pair before deployment.

Shapes and data flow

W (d_in, d_out) * s (1, d_out); b, mean, beta, s (d_out,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplefold_bn([[2.0]], [1.0], [3.0], [0.5], [1.0], [3.99999])
  • Sample 2: check equal_check(rng_fold)
  • Test 3: matrixfold_bn([[1.0, 2.0], [0.0, -1.0]], [0.5, 0.0], [1.0, 2.0], [0.0, 1.0], [0.5, -1.0], [1.0, 4.0])