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, theRangeObserver,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. - QAvg
Pool2D - Average pooling over
PHxPWwindows at stridesSH,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 beCA + 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>). - QConv2D
PerChannel QConv2Dwith one requantizer per filter, the per-channel weight quantization TFLite applies to convolutions (C++QConv2DPerChannel).- QDense
- A quantized fully connected layer with
INint8 inputs andOUTint8 outputs (C++QDense<int8_t, int8_t, int32_t, int8_t, IN, OUT>). - QDense
PerChannel - A quantized fully connected layer with one
Requantizerper output: the per-channel weight quantization TFLite applies to dense layers by default (C++QPointwiseConv2DPerChannelover a 1x1 input, which is a dense layer). Otherwise the same asQDense. - QDepthwise
Conv2D - A quantized depthwise 2D convolution: one
KHxKWfilter 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 oni16real and imaginary buffers (C++QFFT1D<N>). - QGlobal
AvgPool2D - 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. - QGru
Cell - One time step of a quantized GRU cell with
INint8 inputs andHIDhidden units (C++QGRUCell), the reset-before-multiply variant: - QLstm
Cell - One time step of a quantized LSTM cell with
INint8 inputs andHIDhidden units (C++QLSTMCell), in the TFLite / CMSIS-NN quantization model. - QMax
Pool2D - Max pooling over
PHxPWwindows at stridesSH,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 encodesscale_a * scale_b / scale_out(calibration::build_mul_requantizer). - QPad2D
- Explicit spatial padding of an NHWC tensor with a constant (C++
QPad2D, TFLite PAD):PTrows above,PBbelow,PLcolumns on the left andPRon the right, each holdingpad_valuein every channel. The convolution layers pad by themselves; this is for models with a separate PAD operator. The output must beH + PT + PBbyW + PL + PR, or the call does not compile. - QPointwise
Conv2D - 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 sameC-to-Fdense layer; weights areweights[filter][channel]. - QPointwise
Conv2D PerChannel QPointwiseConv2Dwith one requantizer per filter (C++QPointwiseConv2DPerChannel). For a single pixel this isQDensePerChannel.- QRFft1D
- A quantized real-input FFT of length
N(C++QRFFT1D<N>):Nreali16samples in, theN / 2 + 1bins that are not redundant out, scaled by1/NlikeQFft1D::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_s8also reproduces), in gemmlowp fixed point (C++QSoftmaxFixedPoint1D). - Requantizer
- Rescales an
i32accumulator to int8 storage (C++Requantizer<int32_t, int8_t>).
Constants§
- LUT_
SIZE - Entries in an int8 activation lookup table: one per int8 input.
Traits§
- Cell
Storage - The storage of a
QLstmCell’s cell state:i8(the default) ori16. Ani16cell 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
xin an activation lookup table: -128 maps to 0, 0 to 128 and 127 to 255 (C++qActivationLUTIndex). - multiply_
by_ quantized_ multiplier - Rescale an
i32by a Q0.31multiplierand a power-of-twoshift, without zero point or saturation to storage (gemmlowp’s “MultiplyByQuantizedMultiplier”, C++multiplyByQuantizedMultiplier). A negativeshiftleft-shiftsxfirst, saturating to thei32range; 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], whereq_sixis 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). Anexponentof zero or less returnsx; 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, withi32::MIN * i32::MINsaturated toi32::MAX(C++saturatingRoundingDoublingHighMul).