TorchLean API

NN.Floats.Quantization

Affine Quantization #

This module gives one affine quantizer for real scalars. For a positive scale $s$, zero point $z$, and integer code interval $[q_{\min},q_{\max}]$, quantization and reconstruction are

$$ Q(x)=\operatorname{clamp}\!\left(\operatorname{round}(x/s)+z,q_{\min},q_{\max}\right), \qquad D(k)=s(k-z). $$

Theorems below cover code-range safety, monotonicity, in-range code round trips, and the half-step reconstruction bound when saturation is inactive. The shape-polymorphic tensor lift belongs to the TorchLean specification adapter NN.Spec.Quantization.

The equations follow the integer-arithmetic quantization scheme used by common neural-network runtimes. See Jacob et al., "Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference," CVPR 2018, doi:10.1109/CVPR.2018.00286.

Parameters of a bounded affine quantizer.

  • scale :

    Distance between adjacent reconstructed real values.

  • zeroPoint :

    Integer code representing real zero when it lies in the code range.

  • qmin :

    Smallest stored code.

  • qmax :

    Largest stored code.

  • scale_pos : 0 < self.scale

    A quantization scale is strictly positive.

  • codeRange : self.qmin self.qmax

    The code interval is nonempty.

Instances For

    Saturate an integer to the quantizer's code interval.

    Instances For

      Integer code before saturation.

      Instances For

        Quantize a real value using the supplied integer rounding rule and saturate it to the code set.

        Instances For

          Reconstruct a real value from an integer code.

          Instances For

            Saturation always returns a valid code.

            @[simp]
            theorem TorchLean.Floats.Quantization.AffineQuantizer.clampCode_eq_self (q : AffineQuantizer) {code : } (hlo : q.qmin code) (hhi : code q.qmax) :
            q.clampCode code = code

            Saturation fixes a code already inside the representable interval.

            Every quantized scalar lies in the declared code interval.

            @[simp]

            Dequantizing the zero point gives real zero.

            Quantization is monotone for every valid integer rounding rule.

            @[simp]
            theorem TorchLean.Floats.Quantization.AffineQuantizer.quantize_dequantize (q : AffineQuantizer) (rnd : ) [NeuralValidRnd rnd] {code : } (hlo : q.qmin code) (hhi : code q.qmax) :
            q.quantize rnd (q.dequantize code) = code

            Every in-range integer code survives a dequantize/quantize round trip.

            Without saturation, nearest affine quantization has error at most half a quantization step.

            The half-step bound survives saturation whenever clipping is inactive.