Storing and computing with 32-bit floats is expensive at inference time — most of that precision is unnecessary for a model that's already trained. Implement symmetric (zero-point-free) INT8 quantization and dequantization for a single tensor: find a scale that maps the tensor's largest-magnitude value to the INT8 range, quantize, and reconstruct an approximation.
scale = max(|x|) / 127
q = clip(round(x / scale), -127, 127)
x_hat = q * scale
scale = max(abs(x)) / 127, with scale = 0 handled explicitly when the tensor is all zeros.[-127, 127] as integers.q * scale.Guard against an all-zero tensor: if max|x| is 0, scale should be treated as 0 and every quantized value is 0, avoiding a division by zero. Round-then-clip, in that order — clipping before rounding can shift a borderline value across the boundary incorrectly.
Click "Run Tests" to test your implementation