Backpropagate through fake quantization with a learned scale

MediumQuantizationPro

Why it matters QAT with straight-through gradients and learned step sizes is how low-bit models recover accuracy that post-training quantization loses.

Quantization-aware training inserts a fake-quant op: quantize and immediately dequantize in float. Rounding has zero gradient almost everywhere, so training uses the straight-through estimator, and the scale itself can be learned.

Write fake_quant_backward(x, s, grad_y, qmin=-128, qmax=127). Let v = x / s. Forward: y = clip(round(v), qmin, qmax) * s. Backward:
- grad_x = grad_y where qmin <= v <= qmax, else 0 (straight-through inside the range, blocked when clipped).
- grad_s = sum of grad_y * g where g = round(v) - v inside the range, g = qmin below it, g = qmax above it.
Return (y, grad_x, grad_s) with grad_s as a float.

Signaturedef fake_quant_backward(x, s, grad_y, qmin=-128, qmax=127)

Example

x [0.26, 3.0, -0.1], s 0.1, grad_y [1, 1, 1], qmin -8, qmax 7 gives y [0.3, 0.7, -0.1], grad_x [1, 0, 1], grad_s 7.4 up to float rounding.

Understand the idea

Rounding is a staircase: flat almost everywhere, so its true gradient is zero and nothing would learn. The straight-through estimator pretends the staircase is a ramp inside the allowed range, so gradients pass as if no rounding happened, but it keeps the flat walls at the ends where values are clipped. Worked example: s = 0.1, range [-8, 7]. x = 0.26 gives v = 2.6, round 3, y = 0.3, gradient passes. x = 3.0 gives v = 30, clipped to 7, y = 0.7, gradient blocked. For the scale, inside terms add round(v) - v: 3 - 2.6 = 0.4 and -1 - (-1) = 0; the clipped value adds qmax = 7; total 7.4. Rule: dy/dx = 1 inside else 0; dy/ds = round(v) - v inside, qmin or qmax outside. This lets the network learn both weights and step sizes for 4-bit and 8-bit deployment.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplefake_quant_backward([0.26, 3.0, -0.1], 0.1, [1, 1, 1], -8, 7)
  • Sample 2: below rangefake_quant_backward([-2.0, 0.04, 0.5], 0.2, [0.5, -1.0, 2.0], -4, 3)