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 NoneInspect 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]