Skip to main content

Module int8

Module int8 

Source
Expand description

Int8 affine-quantized inference, ported from tinymind (C++) cpp/qaffine.hpp, cpp/qdense.hpp, cpp/qconv2d.hpp, cpp/qdepthwiseconv2d.hpp, cpp/qpointwiseconv2d.hpp, cpp/qpool2d.hpp, cpp/qadd.hpp, cpp/qmul.hpp, cpp/qpad.hpp, cpp/qconcat.hpp, cpp/qactivations.hpp, cpp/qsoftmax_fixedpoint.hpp, cpp/qlstm.hpp, cpp/qgru.hpp and cpp/qfft1d.hpp.

This is the TFLite / CMSIS-NN quantization model, separate from the Q-format QValue pipeline: a real value is scale * (q - zero_point), with int8 activations (asymmetric, any zero point), int8 weights (symmetric, zero point 0) and int32 biases and accumulators. Everything here is pure integer arithmetic at run time; turning float scales into the integer parameters is host-side work, in calibration (std feature).

A layer computes acc[o] = bias[o] + sum_i weight[o][i] * (input[i] - input_zero_point) in i32, then a Requantizer rescales acc to the output tensor’s int8 grid with a fixed-point multiplier, adds the output zero point and saturates.

Layers run fastest as const or static items, as the importers generate them: the compiler then folds their weights and requantizers into the code. A layer built from values known only at run time gives the same results more slowly; on a Cortex-M4 a convolution over one input channel took about twice as long.

§Convolution and pooling

QConv2D (and QConv2DPerChannel), QDepthwiseConv2D, QPointwiseConv2D (and QPointwiseConv2DPerChannel), QMaxPool2D, QAvgPool2D and QGlobalAvgPool2D work on NHWC tensors without the batch axis, as nested arrays: an input is [[[i8; C]; W]; H], indexed [row][column][channel]. Kernel, strides and padding are const parameters of the layer; the input and output sizes come from the arrays passed to forward, which writes into a caller-owned output so tensors can share buffers. The output must have the size the layer produces, (H + PT + PB - KH) / SH + 1 rows and likewise columns, or the call does not compile; an invalid layer (a zero stride, a kernel larger than the padded input) does not compile either. Padding holds the input zero point, as TFLite pads, so a padded tap contributes nothing. Pooling keeps the input’s scale and zero point: no requantizer.

A convolution over two or more input channels widens its input rows and each filter’s weights to 16 bits and adds the products in pairs. On cores with the DSP extension (Cortex-M4, M7, M33), LLVM can turn each pair into one SMLAD instruction, from this plain Rust, but by default it gives up on long unrolled sums. Building with -C llvm-args=-arm-parallel-dsp-load-limit=512 (in the target’s rustflags) lets it pair them: on an STM32F411 the MLPerf Tiny ResNet-8 then takes 35% fewer cycles. It is an LLVM internal option, not a stable Rust one.

use tinymind::int8::{QConv2D, QMaxPool2D, Requantizer};

// Eight 3x3 filters over a 20x20 single-channel input, then 2x2 max pooling.
static WEIGHTS: [[[[i8; 1]; 3]; 3]; 8] = [[[[1]; 3]; 3]; 8];
const RQ: Requantizer = Requantizer { multiplier: 1 << 30, shift: 3, zero_point: 0, qmin: -128, qmax: 127 };
let conv: QConv2D<'_, 1, 3, 3, 8> =
    QConv2D { weights: &WEIGHTS, biases: None, input_zero_point: 0, requantizer: RQ };

let input = [[[2i8; 1]; 20]; 20];
let mut features = [[[0i8; 8]; 18]; 18]; // 3x3, stride 1, no padding: 18 x 18
conv.forward(&input, &mut features);
let mut pooled = [[[0i8; 8]; 9]; 9]; // 2x2 windows: 9 x 9
QMaxPool2D::<2, 2>.forward(&features, &mut pooled);
// Each window sums nine 2s; the requantizer scales by 1/16: 18/16 rounds to 1.
assert_eq!(pooled[0][0], [1; 8]);

An output of the wrong size does not compile:

ⓘ
let input = [[[2i8; 1]; 20]; 20];
let mut features = [[[0i8; 8]; 17]; 18]; // 17 columns: the layer makes 18
conv.forward(&input, &mut features);

QAdd adds two tensors of the same shape with their own scales and zero points (TFLite ADD), for residual connections, and QMul multiplies them (TFLite MUL, squeeze-and-excite gating). QPad2D pads a tensor with a constant and QConcat joins two along the channel axis.

§Recurrent cells

QLstmCell and QGruCell run one time step of an int8 LSTM or GRU cell, updating the caller’s hidden state (and the LSTM’s cell state, i8 or i16) in place; the caller runs the time loop over a sequence. Weights are gate-major, [gate][unit][input]: PyTorch’s nn.LSTM stacks its gates in the same order (i, f, g, o), so its weight matrices map onto them directly (add its two bias vectors, bias_ih and bias_hh, before quantizing them). The GRU applies its reset gate before the recurrent multiply, as Keras does with reset_after=False (whose kernels store the gates as update, reset, new, so reorder them); PyTorch’s nn.GRU and Keras’ default apply it after, which is a different function. The gate activations come from 256-entry sigmoid and tanh tables with fixed output grids; calibration builds the tables and the rescaling parameters from float scales.

§FFT

QFft1D is a radix-2 FFT for vibration, audio or IMU front ends: 16-bit samples, Q1.15 twiddle tables borrowed from flash, in place on the caller’s real and imaginary buffers. Its bin magnitudes come out in i32, ready for a Requantizer onto an int8 grid; calibration builds the twiddle tables. QRFft1D takes real samples, the usual case for sensors: from the same tables it computes the N / 2 + 1 bins that are not redundant with about half the work.

§Equivalence with tinymind (C++)

Results match tinymind (C++) bit for bit, and through it TFLite’s reference kernels for the layers TFLite has (the recurrent cells’ table-based gates are tinymind (C++)’s own, not TFLite’s integer LSTM kernel). Where the C++ would hit undefined behaviour (an i32 accumulator overflow, a shift out of its documented range), this port wraps or clamps instead, so every function is total and none panics.

Modules§

calibration
Host-side calibration: turning float scales into the integer parameters the int8 layers use (C++ quantizeMultiplier, buildRequantizer, quantize, dequantize, buildQSigmoidLUT, buildQTanhLUT, buildQSoftmaxFixedPointParams, computeAffineParamsAsymmetric, computeAffineParamsSymmetric, computePerChannelSymmetricScales, the RangeObserver, buildQAddParams, buildRescaler, buildQMulRequantizer, buildQLSTMParams, buildQGRUParams, quantizeQLSTMBiases, quantizeQGRUBiases, buildQFFTTwiddles).

Structs§

QAdd
Elementwise addition of two int8 tensors with their own scales and zero points, into a third (C++ QAdd, TFLite ADD): the skip connections of ResNet and MobileNet-V2.
QAvgPool2D
Average pooling over PH x PW windows at strides SH, SW (default: the window size), no padding: the window’s sum divided by its area, rounded half away from zero, then clamped to [qmin, qmax] (C++ QAvgPool2D).
QConcat
Concatenation of two NHWC tensors along the channel axis (C++ QConcat2_2D, TFLite CONCATENATION on the last axis): the output’s channels are the first input’s, then the second’s, each rescaled onto the output grid by its own requantizer (calibration::build_rescaler). The output’s channel count must be CA + CB, or the call does not compile.
QConv2D
A quantized 2D convolution with one requantizer for the whole output (C++ QConv2D<int8_t, int8_t, int32_t, int8_t, H, W, C, KH, KW, SH, SW, F, PT, PB, PL, PR>).
QConv2DPerChannel
QConv2D with one requantizer per filter, the per-channel weight quantization TFLite applies to convolutions (C++ QConv2DPerChannel).
QDense
A quantized fully connected layer with IN int8 inputs and OUT int8 outputs (C++ QDense<int8_t, int8_t, int32_t, int8_t, IN, OUT>).
QDensePerChannel
A quantized fully connected layer with one Requantizer per output: the per-channel weight quantization TFLite applies to dense layers by default (C++ QPointwiseConv2DPerChannel over a 1x1 input, which is a dense layer). Otherwise the same as QDense.
QDepthwiseConv2D
A quantized depthwise 2D convolution: one KH x KW filter per channel, channels never mixed, one requantizer per channel as TFLite requires (C++ QDepthwiseConv2D).
QFft1D
A quantized radix-2 decimation-in-time FFT of length N, in place on i16 real and imaginary buffers (C++ QFFT1D<N>).
QGlobalAvgPool2D
Global average pooling: one value per channel, the mean over every pixel, rounded and clamped as in QAvgPool2D (C++ QGlobalAvgPool2D). Its output can feed a dense head in place of a large flatten-to-dense layer.
QGruCell
One time step of a quantized GRU cell with IN int8 inputs and HID hidden units (C++ QGRUCell), the reset-before-multiply variant:
QLstmCell
One time step of a quantized LSTM cell with IN int8 inputs and HID hidden units (C++ QLSTMCell), in the TFLite / CMSIS-NN quantization model.
QMaxPool2D
Max pooling over PH x PW windows at strides SH, SW (default: the window size, non-overlapping), no padding (C++ QMaxPool2D).
QMul
Elementwise multiplication of two int8 tensors with their own zero points (C++ QMul, TFLite MUL): squeeze-and-excite gating in MobileNet-V3 and EfficientNet. out = requantize((a - zp_a) * (b - zp_b)), where the requantizer encodes scale_a * scale_b / scale_out (calibration::build_mul_requantizer).
QPad2D
Explicit spatial padding of an NHWC tensor with a constant (C++ QPad2D, TFLite PAD): PT rows above, PB below, PL columns on the left and PR on the right, each holding pad_value in every channel. The convolution layers pad by themselves; this is for models with a separate PAD operator. The output must be H + PT + PB by W + PL + PR, or the call does not compile.
QPointwiseConv2D
A quantized 1x1 (“pointwise”) convolution, the channel-mixing half of a depthwise-separable block, with one requantizer for the whole output (C++ QPointwiseConv2D). Every pixel goes through the same C-to-F dense layer; weights are weights[filter][channel].
QPointwiseConv2DPerChannel
QPointwiseConv2D with one requantizer per filter (C++ QPointwiseConv2DPerChannel). For a single pixel this is QDensePerChannel.
QRFft1D
A quantized real-input FFT of length N (C++ QRFFT1D<N>): N real i16 samples in, the N / 2 + 1 bins that are not redundant out, scaled by 1/N like QFft1D::forward.
QSoftmax
Int8 softmax over a row of logits, bit-exact with TFLite’s int8 softmax (the TFLite Micro reference kernel, which CMSIS-NN’s arm_softmax_s8 also reproduces), in gemmlowp fixed point (C++ QSoftmaxFixedPoint1D).
Requantizer
Rescales an i32 accumulator to int8 storage (C++ Requantizer<int32_t, int8_t>).

Constants§

LUT_SIZE
Entries in an int8 activation lookup table: one per int8 input.

Traits§

CellStorage
The storage of a QLstmCell’s cell state: i8 (the default) or i16. An i16 cell state has 256 times the resolution, for long sequences. Sealed: the crate implements it.
Tensor
An int8 tensor for the elementwise layers (QAdd, QMul): [i8; N], [[i8; C]; W] or [[[i8; C]; W]; H], read as its elements in memory order. Sealed: the crate implements it.

Functions§

apply_lut
Apply a 256-entry int8 lookup table, such as a sigmoid or tanh table built by calibration::build_sigmoid_lut (C++ qApplyLUT).
lut_index
Index of x in an activation lookup table: -128 maps to 0, 0 to 128 and 127 to 255 (C++ qActivationLUTIndex).
multiply_by_quantized_multiplier
Rescale an i32 by a Q0.31 multiplier and a power-of-two shift, without zero point or saturation to storage (gemmlowp’s “MultiplyByQuantizedMultiplier”, C++ multiplyByQuantizedMultiplier). A negative shift left-shifts x first, saturating to the i32 range; a positive one divides the product with rounding.
qrelu
Quantized ReLU: clamp at the tensor’s zero point, which represents 0.0 (C++ qrelu).
qrelu6
Quantized ReLU6: clamp to [zero_point, q_six], where q_six is 6.0 in the tensor’s grid (C++ qrelu6).
rounding_divide_by_pot
x / 2^exponent, rounded to nearest with gemmlowp’s tie rule (C++ roundingDivideByPOT). An exponent of zero or less returns x; the documented range ends at 31, and larger exponents are treated as 31.
saturating_rounding_doubling_high_mul
Saturating rounding doubling high multiply: (a * b + 2^30) >> 31, the Q0.31 multiply of gemmlowp and TFLite, with i32::MIN * i32::MIN saturated to i32::MAX (C++ saturatingRoundingDoublingHighMul).