REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Train through per-channel fake quantization and saturation

Implement symmetric signed per-output-channel fake quantization of floating [out,in] weights with qmax=2**(bits-1)-1 and qmin=-qmax, bits in 2..8. Infer detached scales=max(abs(channel))/qmax with floor 1e-8, or accept explicit finite positive detached [out] scales. Round ties to even, simulate quantize/dequantize in floating point and use straight-through rounding with zero gradient outside the clipping interval. Return a floating tensor; this is QAT simulation, not a packed int8 kernel or a speed benchmark.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Train through per-channel fake quantization and saturation →

Your task

Implement symmetric signed per-output-channel fake quantization of floating [out,in] weights with qmax=2**(bits-1)-1 and qmin=-qmax, bits in 2..8. Infer detached scales=max(abs(channel))/qmax with floor 1e-8, or accept explicit finite positive detached [out] scales. Round ties to even, simulate quantize/dequantize in floating point and use straight-through rounding with zero gradient outside the clipping interval. Return a floating tensor; this is QAT simulation, not a packed int8 kernel or a speed benchmark.

Starter

import torch

def fake_quant_weight(weight, bits=8, scales=None):
    # TODO: implement fake_quant_weight under the declared contract.
    return None
Inspect the worked answer
import torch

def fake_quant_weight(weight, bits=8, scales=None):
    if weight.ndim!=2 or 0 in weight.shape or not weight.is_floating_point() or not torch.isfinite(weight).all():raise ValueError('Expected finite floating nonempty [out, in] weights.')
    if type(bits)!=int or not 2<=bits<=8:raise ValueError('Use an integer precision from 2 through 8.')
    maximum=2**(bits-1)-1
    if scales is None:
        scale=(weight.detach().abs().amax(1)/maximum).clamp_min(1e-8)
    else:
        if scales.shape!=(len(weight),) or not torch.isfinite(scales).all() or (scales<=0).any():raise ValueError('Expected positive finite per-channel scales.')
        scale=scales.detach().clone()
    scaled=weight/scale[:,None]
    clipped=scaled.clamp(-maximum,maximum)
    straight=clipped+(clipped.round()-clipped).detach()
    return straight*scale[:,None]

About this algorithm

How Train through per-channel fake quantization and saturation works

The idea

Quantization stores weights as small integers, such as 8-bit ones, to make a model smaller and faster. Rounding changes the weights, and a model trained in full precision can lose accuracy when it is rounded afterwards. Quantization-aware training lets the model see the rounding while it trains: the forward pass uses weights that were scaled, clipped, rounded and scaled back, still stored as floats.

Rounding has a gradient of zero almost everywhere, which would stop learning. The straight-through estimator gets around that. clipped + (clipped.round() - clipped).detach() has the rounded value in the forward pass and the gradient of clipped in the backward pass. Weights that fall outside the clipping range get zero gradient. Each output channel has its own scale, so a row of small weights keeps its resolution.

How it works

  1. Validate a finite floating [out, in] weight and an integer bits from 2 to 8, then set maximum = 2 ** (bits - 1) - 1.
  2. Take each row's scale as its largest absolute value divided by maximum, detached and at least 1e-8, or use the explicit scales.
  3. Divide each row by its scale and clamp the result to the range from -maximum to maximum.
  4. Form clipped + (clipped.round() - clipped).detach(), where round sends ties to the even integer.
  5. Multiply by the scale again and return a float tensor whose values sit on each row's integer grid.

What it costs

Per call
O(out · in)
Levels
2^bits - 1 per channel
Storage
still float, not int8

Fake quantization adds a few elementwise operations to each forward pass and saves nothing during training; the size and speed gains come later, when the weights are exported as integers.

Where it is used

  • PyTorch's torch.ao.quantization inserts FakeQuantize modules for quantization-aware training, with per-channel observers available for weights.
  • Jacob and co-authors at Google described this training scheme in 2018 for integer-only inference with TensorFlow Lite on phones.
  • The TensorFlow Model Optimization Toolkit has a quantization-aware training API that produces models for 8-bit TensorFlow Lite deployment.

Watch out for

  • Calling round() without the straight-through trick: its gradient is zero, so the weights never update.
  • Computing the scale without detach(), which sends an extra gradient into the largest weight of every row.
  • Using one scale for the whole matrix: a row of small weights then collapses onto very few levels, or onto zero.