Int8 in Firmware

A tiny chip must add up 144 small products to get one output of a neural network. Keep the running total in a 32-bit register and it matches the float answer. Keep it in a 16-bit register and the total wraps around, like a car odometer, and the answer is wrong.

Learn how a quantized layer really computes on a Cortex-M: scale, zero point, the int32 accumulator, integer-only requantization, the places overflow hides, and how to prove your C matches Python.

Start on 32 bits, then press the 16-bit buttons: one wraps, one saturates (stops at the limit). Drag the number of products to see where the total breaks. Watch the purple running sum chase the blue float line. Then we build every step by hand.

You need a little C and the idea that a neural layer is a pile of multiply and add. The tinyML lessons on quantization I and quantization II help, but we restate what we use.

Built from primary sources: the LiteRT 8-bit quantization spec, Jacob et al., Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference, and the source of CMSIS-NN, gemmlowp and TensorFlow Lite. The devices are models that run in your browser, not a chip.

Add up one output

144

Illustrative data: seeded random activations (after a ReLU, so the input minus its zero point lies in 0 to 255) and weights in −30 to 60. The accumulator rules are the real ones: 16-bit limits are −32,768 and 32,767. The output scale is chosen so the exact answer lands near the top of the int8 range.

Chapter 0

Why a Float Network Does Not Fit

See what a trained network costs in bytes and cycles, and why shrinking it to int8 is a job for firmware, not only for Python

You train a keyword spotter on your laptop. It listens for “go” and “stop”, and Python reports 94% accuracy on the test clips. You convert the model, flash it to a board, and play the same clips. The board gets 61%. Nothing crashed. No error message appeared. The numbers are simply different (the accuracy figures here are made up, to show the shape of the problem).

This lesson is about that gap. To close it, you need to know exactly what the chip computes. So we start with what a chip can and cannot do.

Two kinds of number

A float is a number stored with a movable decimal point, such as 0.0371 or 12,400.5. The common size, float32, takes 4 bytes. It can hold tiny and huge values in the same format. Think of a ruler that stretches to fit what you measure.

An integer is a whole number with no decimal point. An int8 takes 1 byte and holds one of 256 values, from −128 to 127. Think of a ruler with exactly 256 fixed ticks. It is small and fast, and it cannot hold a fraction.

A register is a tiny slot inside the processor where one number sits while the chip works on it. On an Arm Cortex-M, an integer register is 32 bits wide. That width matters for the rest of this lesson.

What a microcontroller gives you

A microcontroller (MCU) is a whole small computer on one chip: a processor, flash memory for code, and RAM for working data. Two numbers decide whether a network fits. The first is flash size, because the weights live there. The second is RAM size, because the layer outputs live there.

Take the nRF52840, a Cortex-M4 at 64 MHz. Nordic lists 1 MB of flash and 256 KB of RAM, and a floating point unit. The micro:bit v2 uses the nRF52833: 512 KB of flash and 128 KB of RAM, also a Cortex-M4 with an FPU. The Raspberry Pi RP2040 has two Cortex-M0+ cores at up to 133 MHz and 264 kB of on-chip SRAM. It has no on-chip flash at all. Code runs from external flash over a QSPI bus, up to 16 MB.

The M4 parts have a unit for float math, so a float network would run, slowly and with a lot of memory. The Cortex-M0+ has no such unit. It would do every float multiply in software, which takes many instructions. So the first cost of float is time, and the second is bytes. The next device shows the bytes.

Will the weights fit?

Each bar is a weight store against one chip’s flash. Pick float32 or int8, then drag the number of weights. A bar turns red when the weights no longer fit.

250

Flash sizes: nRF52840 1 MB, nRF52833 512 KB (Nordic product pages), RP2040 up to 16 MB of external QSPI flash (Raspberry Pi documentation). The weight counts are illustrative. We count 1 MB as 1,048,576 bytes and ignore code, scales and biases.

On real hardware. Take an nRF52840 DK. Build your firmware twice, once with the weights as float32 and once as int8, and read the flash size that the build reports. Compare both with the 1 MB of flash on the chip.

Drag the weights to 250 thousand. As float32 they take 1,000,000 bytes, about 95% of the nRF52840’s flash, and they do not fit the micro:bit chip at all. As int8 they take 250,000 bytes. The same network is four times smaller. That is the first reason to quantize.

The second reason is speed and energy

The Cortex-M4 has a set of DSP instructions. One of them, SMLAD, multiplies two pairs of 16-bit values and adds both products to a 32-bit sum in one instruction. The CMSIS-NN library, Arm’s int8 kernel library, uses it in its convolution. Integer math also moves fewer bytes, and moving bytes costs energy. Chapter 6 shows the kernel.

Why the gap appears

Quantizing is not a free copy. You replace each 32-bit float with an 8-bit integer plus a recipe to get the float back. The recipe is two numbers, a scale and a zero point. Every step of the layer must then work on integers while keeping track of the recipe.

Three things can go wrong, and they match the three symptoms of the 61%. A rounding step can be off by one. An internal sum can overflow its register. A zero point can be left out. Each one is a quiet bug: the code runs and the answers are slightly or badly wrong. You cannot see it by reading the output. You need a test that compares the chip with Python, number by number. Chapter 7 builds that test.

We will do one output of one convolution by hand, in integers, and compare it with the float answer. Then we turn that hand calculation into C.

The road

  1. Scale and zero point: the recipe that turns 256 ticks into real numbers.
  2. One output by hand: every multiply and add of an int8 convolution, in an int32 sum.
  3. Requantize without floats: scale the sum back to int8 using only integer math.
  4. Where overflow hides: the accumulator, the multiplier, the shift and the cast.
  5. Per-channel scales, bias and the clamp: the details real layers add.
  6. The kernel on a Cortex-M: widen, SMLAD, requantize, saturate.
  7. Parity with Python: a test that proves your C matches the reference.
  8. Field Guide: the numbers, a checklist, the core code.
A model has 250 thousand weights. Which change shrinks its flash use by four times with the least change to the layer code?

Chapter 1

Scale and Zero Point

Turn 256 whole-number ticks into real measurements with two numbers, and see the error that costs

Picture a kitchen scale with a display that shows only whole numbers from 0 to 255. You want to weigh flour in grams, and the flour never goes above 255 g. Easy: each tick is one gram. Now you want to weigh a letter. It weighs 3.4 g. The scale reads 3 or 4 and nothing in between.

You fix it with a rule printed on the scale: each tick is 0.05 g. Now 255 ticks cover 0 to 12.75 g, and the letter reads 68. The display stays a whole number. The rule gives the real weight. That rule is the whole idea of quantization.

The rule has two numbers

A scale is the real size of one tick. A zero point is the tick that stands for the real value 0. Sometimes your measurements go negative, such as a sensor that reads from −1.0 to 3.0. Then you slide the ticks so that 0 lands on a whole tick. The zero point records where.

With these two numbers, a stored integer q means this real value:

r
The real number the integer stands for, as the float model would hold it.
S
The scale: the real size of one tick. A float, one per tensor (or one per channel, see Chapter 5).
q
The stored integer. In int8 it lies in −128 to 127.
Z
The zero point: the integer that stands for real 0.

The LiteRT quantization spec writes the same rule as real_value = (int8_value − zero_point) × scale. Jacob and colleagues, who built this scheme for TensorFlow Lite, write it as r = S(q − Z). It is the same rule.

Finding S and Z from a range

You choose them from the range of real values you expect. Say the layer output goes from rmin to rmax. The 256 ticks must cover that range, so the scale is the range divided by the 255 gaps between the ticks. Then you pick Z so that real 0 lands on a tick.

S = (rmax − rmin) / 255    Z = round(−128 − rmin / S)

Work it for the sensor range −1.0 to 3.0. The range is 4.0, so S = 4.0 / 255 = 0.015686. Next, rmin / S = −1.0 / 0.015686 = −63.75. So Z = round(−128 + 63.75) = round(−64.25) = −64. Real 0 is the tick −64.

Now store the real value 0.5. First 0.5 / 0.015686 = 31.875, which rounds to 32. Add the zero point: q = 32 + (−64) = −32. Read it back: 0.015686 × (−32 − (−64)) = 0.015686 × 32 = 0.50196. The error is 0.00196. It can never be more than half a tick, here 0.00784.

Why the zero point matters

Many layers pad their input with real zeros at the image or signal edge. If real 0 is not exactly a tick, every padded value carries a small error, and that error repeats at every position. Making Z a whole integer in range makes real 0 exact. The paper requires this property for that reason.

Weights use a simpler form. The LiteRT spec says activations are int8 in −128 to 127 with any zero point. It says weights are symmetric: the zero point is forced to 0, and the range is −127 to 127. With Z = 0, the rule is r = S × q. The scale is max|w| / 127. Dropping −128 keeps the range balanced around 0. Chapter 2 shows what that saves.

Pick a range, store a number

The row of ticks is the 256 integers. Choose how the range is made, move the range ends, then move the teal value. Watch where it lands and how far the stored tick is from it.

−1.0
3.0
0.50

Formulas as in the LiteRT spec and the paper: scale from the range, zero point rounded to a whole tick in −128 to 127, weights symmetric with range −127 to 127. The tick row is drawn thinned on narrow screens. Values outside the range clip to the end tick.

On real hardware. Take an STM32 Nucleo board with a Cortex-M4 part such as the STM32L476. Quantize one tensor in Python, flash the int8 values with S and Z, and print S times (q minus Z) over the serial port. Compare each value with the Python float. No gap may exceed half a tick.

Try a range that is too wide, say −8 to 8, and store 0.5. The ticks are now 0.063 apart, and the error grows. A wide range wastes ticks on values you never see. A narrow range clips the ones you do see. Choosing the range is called calibration, and quantization II compares methods for it. Here we take S and Z as given by the converter.

How big is the error, and what does it cost?

Rounding to the nearest tick means the stored value is never more than half a tick from the true one. Half a tick is S / 2. For the range −1.0 to 3.0 that is 0.0078. For the wide range −8 to 8 the scale is 16 / 255 = 0.0627, so half a tick is 0.0314. The wide range makes every stored value four times less exact, even for values near 0.5.

Values outside the range have a different fate. They clip to the end tick, and the error there can be large. A narrow range keeps ordinary values exact but clips the rare big ones. A wide range clips nothing but blurs everything. Every quantized network is a bet on where to put that range for each tensor.

Rounding error is not a bug. It is the price of 8 bits, and the network was trained to tolerate it. The bugs in this lesson are different: they are errors far bigger than half a tick, which come from a wrong formula and not from rounding. Keeping the two apart is the skill of the whole lesson.

A tensor spans real values −1.0 to 3.0 with S = 0.015686 and Z = −64. The stored integer is −10. What real value does it mean?

Chapter 2

One Output by Hand

Do the multiplies and adds of an int8 convolution yourself, in whole numbers, and match the float answer

A convolution output is a short sum. Take a 3 by 3 patch of the input and a 3 by 3 filter. Multiply each input by its weight, nine times. Add the nine products. Add a bias. That is one output number. A real layer repeats this for every position and every filter, but each one is this nine-term sum.

In float, you would do sum += x * w and be done. In int8, x and w are tick numbers, not real values. So we have to ask: what do the tick numbers multiply to?

Derive the integer sum

Start from the real sum. Each real input is S1 (q1 − Z1) and each real weight is S2 (q2 − Z2). The real product is the two multiplied together. The output has its own scale S3 and zero point Z3. Set the real output equal to the stored output and solve for q3:

q3
The stored int8 output for this position.
Z3
The output zero point.
M
One real number that folds the three scales into a single factor. The paper reports that, by experiment, it always lies between 0 and 1. Chapter 3 turns it into integer math.

The sum inside is pure integers: a subtraction, a multiply, an add. The scales do not appear in it. They wait outside, in M. This is why integer-only inference works. The hard part is one multiply by M at the end.

Weights have Z2 = 0 (Chapter 1), so the sum is simply the input minus its zero point, times the weight. If both zero points were non-zero, expanding the product gives four terms, two of which depend on the data. Setting the weight zero point to 0 removes two of them. That is the saving of symmetric weights.

The bias

A layer adds a real bias b to the sum. The bias must live in the same units as the sum, which are S1 × S2 per tick. So we store it as an integer with exactly that scale. The paper states it: the bias is int32 with scale S1S2 and zero point 0. The LiteRT spec says the same for CONV_2D: an int32 bias, per axis, with scale input_scale × weight_scale and zero point 0. We add it straight into the int32 sum.

A worked example

Use these illustrative numbers. Input: S1 = 0.05, Z1 = −10. Weights: S2 = 0.02, Z2 = 0. Output: S3 = 0.1, Z3 = −5. Real bias 0.3, so the stored bias is 0.3 / (0.05 × 0.02) = 0.3 / 0.001 = 300. The input patch has stored values −10, 20, 35 / 12, 50, 8 / −3, 27, 60. The weights are 12, −25, 40 / −8, 55, −17 / 30, 5, −22.

Step 1: subtract Z1 from each input. The nine differences are 0, 30, 45, 22, 60, 18, 7, 37, 70. Step 2: multiply each by its weight. The products are 0, −750, 1800, −176, 3300, −306, 210, 185, −1540. Step 3: add them in a 32-bit sum. The running total ends at 2723. Step 4: add the stored bias 300. The sum is 3023.

Step 5: multiply by M = 0.05 × 0.02 / 0.1 = 0.01. That gives 30.23, which rounds to 30. Step 6: add Z3. The stored output is 30 + (−5) = 25.

Check it against the float way. The real inputs are 0.05 times the differences, the real weights are 0.02 times the stored weights, and the real products add to 2.723. Add the real bias 0.3 for 3.023. The stored output 25 means 0.1 × (25 + 5) = 3.0. The error is 0.023, less than half of one output tick (0.05). The integers carried everything correctly. Only the final rounding lost anything.

Use the device to step through it yourself. It uses exactly these numbers.

Step the nine multiply-adds

Press Next product to add one term to the int32 sum. When all nine are in, the bias, the multiplier and the output zero point finish the job. Then press Forget Z1 and run it again.


    

Illustrative numbers (scales, zero points, patch and filter are made up for this lesson). The arithmetic is exact: every product and the sum are integers, the multiply by M uses the real M = 0.01 here, and Chapter 3 replaces that multiply by integer-only math.

On real hardware. Take an nRF52840 DK. Copy the nine inputs and nine weights of this chapter into two C arrays, run the loop above, and print the int32 sum over the serial port. You should read 3,023. Delete the subtraction of the zero point and read the new, wrong sum.

Now see it as C. The inner loop of an int8 convolution is this short:

cint32_t acc = bias;                          // int32, bias scale = S1 * S2
for (int i = 0; i < 9; i++) {
    acc += (int32_t)(x[i] - zx) * w[i];     // zx is Z1, w[i] is int8 with Z2 = 0
}
// acc is now in units of S1*S2; Chapter 3 scales it to int8

This is the same shape as the TensorFlow Lite reference kernel, which accumulates filter_val * (input_val + input_offset). There input_offset is stored as the negative of Z1, so adding it subtracts the zero point (the source comments it as r = s(q − Z)). Note the cast to int32_t before the multiply. In C, a bare int8_t times an int8_t is promoted to int, so this case is safe. In a 16-bit variable it would not be. Chapter 4 follows that thread.

In the worked example the integer sum, with bias, is 3023 and M is 0.01. What is the stored output?

Chapter 3

Requantize Without Floats

Scale a 32-bit sum back to int8 by a real number M, using only integer multiply, shift and round

Your sum is 3023. You must multiply it by 0.01 and get 30. On a Cortex-M4 you could call a float multiply and round. On a Cortex-M0+ that would run in software and take many instructions. On either chip it can give different results from another chip, because float rounding depends on the compiler and the unit. Firmware that has to match Python bit for bit wants a pure integer recipe.

This step has a name. Requantizing means taking the wide int32 sum, in units of S1 × S2, and converting it to the narrow int8 output, in units of S3. The factor is M from Chapter 2.

The trick: a fraction times a power of two

Any positive number less than 1 can be written as a number between 0.5 and 1, times a power of two. Look at 0.01. It equals 0.64 × 2−6, because 2−6 is 1/64 and 0.64/64 = 0.01. The paper writes this as M = 2−n M0, with M0 in the interval [0.5, 1) and n a non-negative integer.

This helps because both parts are cheap in integers. The power of two is a bit shift. The number M0 can be stored as a 32-bit integer by scaling it with 231. The paper says the int32 holds the value nearest to 231 M0. Because M0 is at least 0.5, that integer is at least 230, so it uses all its bits and keeps at least 30 bits of accuracy.

For M = 0.01: M0 = 0.64, and 0.64 × 231 = 1,374,389,534.72, which rounds to 1,374,389,535. The shift is 6 to the right. TensorFlow Lite stores that shift as −6, since a positive shift means a left shift. Both numbers are computed once, at conversion time, and stored next to the layer.

Apply it in two integer steps

Step A is a rounding doubling high multiply. Multiply the sum by the 32-bit M0 integer to get a 64-bit result. Then divide by 231 and round. The name says what happens: the multiply makes a number twice as wide, you keep the high half (the top 32 bits), and the factor of two comes from the 231 where a plain 232 would take the high half. gemmlowp, the library behind this, names it SaturatingRoundingDoublingHighMul. Its comment says it implements the same computation as the Arm NEON instruction VQRDMULH.

With our numbers: 3023 × 1,374,389,535 = 4,154,779,564,305. Divide by 231 (2,147,483,648) and round: 1934.72, which becomes 1935. That is 3023 × 0.64, rounded.

Step B is a rounding right shift. Divide 1935 by 26 = 64 and round to nearest: 30.23, so 30. Same answer as the real multiply by 0.01. Then you add Z3 and clamp.

Build M from integers

Choose a multiplier and a sum. The text shows M0, the shift and both steps. The dots show the leftover error of the integer result against the exact product for 400 different sums. Switch the shift from rounding to truncating and watch the dots drop.

0.0100
3,023

    

The slider sets log10 of M, from 0.0005 to about 0.89. The integer code is the TensorFlow Lite and gemmlowp recipe (frexp, 31-bit multiplier, doubling high multiply with a nudge, rounding divide by a power of two), run here with exact 64-bit BigInt math. The 400 sums are spread over the range of the sum slider.

On real hardware. Take an STM32 Nucleo board and run the requant function on the sum 3,023 with M0 = 1,374,389,535 and a right shift of 6. Print the result and expect 30. Then loop over 400 sums, compare each result with a Python round(acc * 0.01), and print the largest gap.

With the rounding shift, the leftover never exceeds about half a tick. With a plain shift, it lies between −1 and 0: the result is always rounded down, which is on average half a tick low. Over many layers a small bias like that can slide accuracy, and you will see it in Chapter 7 as a parity failure that is hard to spot by eye.

Why the middle is 64 bits

The product of a 32-bit sum and a 32-bit M0 can reach about 262. That needs a 64-bit register pair. On a Cortex-M4 one SMULL instruction produces it. The CMSIS-NN header has an optional inline assembly path (switched on by CMSIS_NN_USE_REQUANTIZE_INLINE_ASSEMBLY) that uses exactly this: smull to multiply, then a shift and an add-with-carry for the rounding. The main C source builds the same result from an int64_t product. On a Cortex-M0+ the 64-bit multiply is a short software routine. It is still integer and still exact.

Two rounding styles, one rule

CMSIS-NN’s arm_nn_requantize says it “returns (val * multiplier)/(2 ^ shift) with different rounding depending if CMSIS_NN_USE_SINGLE_ROUNDING is defined or not.” The default does the two steps above, each with its own rounding. The single-rounding build does one rounding at the end. TensorFlow Lite has the same switch, TFLITE_SINGLE_ROUNDING. The two can disagree by one tick on a few values. The rule for firmware is plain: match the reference you test against. If your Python reference uses double rounding and your chip uses single, you will see rare off-by-one mismatches that no amount of staring at the C will explain.

c// gemmlowp-style requantize, as in TFLite and CMSIS-NN (default rounding)
int32_t requant(int32_t acc, int32_t m0, int shift) {
    int left  = shift > 0 ? shift : 0;
    int right = shift > 0 ? 0 : -shift;
    int64_t ab = (int64_t)(acc * (1 << left)) * m0;       // up to ~2^62
    int32_t nudge = ab >= 0 ? (1 << 30) : (1 - (1 << 30));
    int32_t hi = (int32_t)((ab + nudge) / (1LL << 31));  // rounding doubling high mul
    return rounding_shift_right(hi, right);                    // round half away from zero
}
M = 0.01 is stored as M0 = 1,374,389,535 and a right shift of 6. What does the first step compute for a sum of 3023?

Chapter 4

Where Overflow Hides

Find the three places an integer can run out of room, measure the headroom of each, and fix them before they cost accuracy

Picture an old car odometer with five digits. At 99,999 km the next kilometre shows 00,000. The car did not break. The counter simply has no room for a sixth digit. A register behaves the same way. Add 1 to the largest value it can hold, and it wraps around. Nothing warns you.

In C, the language rules leave the result of a signed integer overflow open. On a Cortex-M the add instruction wraps in two's complement, so in practice the sum wraps. The compiler may also assume the overflow never happens and change your code in ways you did not expect. Either way, the program carries on with a wrong number. This is the worst kind of bug in quantized firmware: the output is a valid int8, only a wrong one.

Place 1: the accumulator

Each product in Chapter 2 is (x − Z1) × w. How big can it get? The difference x − Z1 reaches 255 when x and Z1 sit at opposite ends of −128 to 127. The weight reaches 127 in size, since weights use −127 to 127. So one product is at most 255 × 127 = 32,385. If the activation zero point is 0, the limit drops to 128 × 127 = 16,256.

Now add K of them. A 3 by 3 filter over 64 input channels has K = 576 terms. The worst-case sum is 576 × 32,385 = 18,653,760. Count the bits: 224 is 16,777,216 and 225 is 33,554,432, so the size needs 25 bits, and the sign adds one. That is 26 bits. A 32-bit accumulator has 6 spare bits. A 16-bit accumulator holds a single worst-case product (32,767 / 32,385 = 1) and nothing more.

Real data is rarely worst case, since products have both signs and cancel. But “rarely” is not a guarantee. After a ReLU, activations are never negative, and a filter can have many same-sign weights. That is exactly the case in the hero at the top, where the 16-bit sum wraps after a handful of terms.

The fix is the accumulator type: int32_t, always. You can verify it at build time. For each layer compute K × 32,385 and assert it is below 231 − 1. The limit is K = 66,311 terms. A fully connected layer with 4096 inputs is far below it.

Count the headroom

The purple bar is the number of bits the worst-case sum needs. The gray bars are the registers. Drag the number of terms K, and switch the input zero point. A bar that sticks out past a register means that register can overflow.

576

The worst case is exact: K times (diff times 127), bits = ceil(log2(max + 1)) + 1 for the sign. The typical bar uses seeded random activations and weights with the same ranges, so it is illustrative. The slider is log scale, 1 to 8192 terms.

Place 2: the bias and the left shift

The int32 bias goes into the same sum. It is scaled by S1 × S2, which is small, so a bias of a few real units can be a large integer. A bias near 231 in a sum that is already large overflows. Check the bias range in the converter output.

The requantize step has a left shift when M is 1 or more. The code multiplies the sum by 2left before the high multiply (see the C in Chapter 3). A sum of 230 shifted by 2 does not fit. Layers where M is below 1, which is most of them, never take this path. Still, a converter bug or a wrong scale can send one there.

The high multiply has its own corner. When both inputs equal the most negative int32, the true result is 231, which does not fit. The gemmlowp and CMSIS-NN code check for this case and return the largest int32 instead. That is called saturation: clamp to the nearest limit instead of wrapping.

Place 3: the cast back to int8

After requantizing, you add Z3. The value may now be 130, or −200. An int8 holds −128 to 127. If you write (int8_t)v, 130 becomes −126, because the cast keeps only the low 8 bits. A strong signal turns into a strong opposite signal.

So the last step of every layer is a clamp: if the value is above the top, use the top; if below the bottom, use the bottom. TensorFlow Lite does it with std::max and std::min against output_activation_min and output_activation_max. On a Cortex-M, the SSAT instruction does it in one instruction: SSAT r0, #8, r1 saturates a signed value to 8 bits. It also sets the Q flag when it clamps, a handy hint in a debugger.

Clamp or wrap

Drag the value before the cast. The warm dot is the stored int8 after a clamp. The red dot is what a bare cast keeps.

130

Exact two's complement behaviour of an 8-bit cast: the result is the low 8 bits read as signed. Clamping is what SSAT #8 and the TensorFlow Lite min/max pair do.

On real hardware. Take an nRF52840 DK. Build the worst-case vector from this chapter with only two terms, every difference 255 and every weight 127, and add it into an int32_t and an int16_t. Print both over the serial port. The int32_t holds 64,770. With GCC for Arm, the int16_t prints −766, because 64,770 minus 65,536 is −766.

Symptom, measurement, fix

The symptom: the model is fine on quiet inputs and wrong on loud ones, or accuracy drops on a few classes only. The measurement: build a debug version that tracks the largest absolute value of the sum, the bias-added sum and the value before the clamp, per layer, over your test set. Print them as a share of 231 and of 127. A layer whose sum uses more than half of 231, or whose pre-clamp value often exceeds 127 by a lot, is your suspect. The fix is one of three: widen the accumulator, add the clamp, or recalibrate the scales so the output range matches the data.

A layer has K = 576 terms, products up to 32,385, and a 16-bit accumulator. What is the safe statement?

Chapter 5

Per-Channel Scales, Bias and the Clamp

Give each filter its own scale, see why the bias scale follows, and let the output clamp do the work of ReLU

A convolution layer has many filters. Each filter makes one output channel. Picture two of them in the same layer. The first looks for faint edges, and its weights are tiny, never above 0.05. The second looks for strong blobs, and its weights go up to 2.0. They live in one weight tensor, but they have very different sizes.

If the whole tensor shares one scale, the scale must cover the biggest weight, 2.0. With symmetric int8 that gives S = 2.0 / 127 = 0.015748. Now look at the faint filter. Its largest weight, 0.05, becomes 0.05 / 0.015748 = 3.2 ticks. The whole filter squeezes into the integers −3 to 3. That is 7 levels out of 255. The filter is still there, but it is a blurry copy.

One scale per output channel

Per-channel quantization gives each filter its own scale. The faint filter gets S = 0.05 / 127 = 0.000394, and uses the full 127 ticks. The LiteRT spec asks for exactly this on convolutions: the weight tensor is int8, symmetric, and per-axis, with the quantized dimension 0 (the output channel). Activations stay per-tensor, one scale for all channels.

Share a scale, or not

Three filters, each with 27 seeded weights. Drag the size of the faint filter, then switch between one scale for all and one scale each. The bars show the weight error of each filter, and the numbers show how many of the 255 levels it uses.

0.05

Illustrative weights: seeded normal-like values, scaled so each filter’s largest weight is exactly 0.05 (adjustable), 0.4 and 2.0. Error is the root-mean-square gap between the dequantized and the original weights, divided by the root-mean-square of the original weights. Symmetric int8 with range −127 to 127.

On real hardware. Take an STM32 Nucleo board with a Cortex-M4 part such as the STM32L476. Build a layer with two very different filters, run it, and print the largest difference from your NumPy reference for each output channel. Then swap the order of the two multipliers and watch one channel go wrong.

Per-channel costs almost nothing at run time. One scale per channel means one M per channel, so the layer carries two small arrays: multiplier[c] and shift[c]. In the CMSIS-NN convolution source you can see the lookup: arm_nn_requantize(sum, output_mult_ptr[i], output_shift_ptr[i]). The inner loop is unchanged.

The bias scale follows

The sum for channel c is in units of S1 × S2c. So the bias for channel c must use the same units. The LiteRT spec writes it as (scale, zero_point) = (input0_scale × input1_scale[i], 0). Each channel gets its own bias scale. It is again an int32, added into the sum before the requantize.

The clamp does the ReLU

A ReLU sets every negative value to 0. In the integer world, real 0 is the stored value Z3. So ReLU means: any stored output below Z3 becomes Z3. That is a clamp with a lower limit of Z3. You already have a clamp at the end of every layer (Chapter 4). ReLU just moves its lower limit.

Take S3 = 0.1 and Z3 = −5. Real 0 is stored −5. A ReLU6 caps the output at real 6. The stored value for real 6 is 6 / 0.1 + (−5) = 55. So ReLU6 is a clamp to the range −5 to 55. TensorFlow Lite passes these two numbers to the kernel as output_activation_min and output_activation_max. A ReLU adds no instruction and no memory. It is free.

This also tells you why a model that ends layers in ReLU6 quantizes well. The output range is fixed at 0 to 6 by design, so the scale never depends on the data. A calibrated range, as in Chapter 1, would have to be guessed from samples.

One more identity: fold the zero point into the bias

The inner loop subtracts Z1 from every input. That is one extra operation per term. But sum of (x − Z1) × w equals sum of x × w minus Z1 times the sum of w. The second part depends only on the weights, so you compute it once per channel and fold it into the bias. Some kernels use this to skip the subtraction. Others, like the CMSIS-NN convolution, add the offset when they widen int8 to int16, so the cost is small. Know which one your library uses, because the bias you ship depends on it.

A worked example: two channels, two multipliers

Use S1 = 0.05 for the input and S3 = 0.1 for the output. The faint filter has S2 = 0.000394, so its M = 0.05 × 0.000394 / 0.1 = 0.000197. As a fraction times a power of two (Chapter 3) that is 0.8063 × 2−12, so M0 = 1,731,514,374 and a right shift of 12. The strong filter has S2 = 0.015748, so M = 0.007874 = 0.5039 × 2−6, with M0 = 1,082,196,484 and a right shift of 6.

The two filters need shifts of 12 and 6. A single shared multiplier cannot serve both. This is why the per-channel layer carries one pair of numbers for every output channel.

Symptom, measurement, fix

A common bug is an order mismatch. The converter writes the multiplier array in one channel order, and your weight array uses another. The symptom: some channels are almost right and others are wildly off, and the pattern changes if you reorder the filters. The measurement: compare the output channel by channel against the reference, and print the max difference for each channel. The wrong channels cluster where the neighbour’s multiplier is far from the right one. The fix: index the multiplier and shift arrays by the same output-channel number as the weights and the bias, and test a layer with two very different filters.

A layer ends in ReLU6 with S3 = 0.1 and Z3 = −5. Which clamp range does the kernel use?

Chapter 6

The Kernel on a Cortex-M

Read how CMSIS-NN turns the hand calculation into a tight loop: widen, pair, multiply-add, requantize, clamp

You now have every piece of the maths. A kernel is the function that runs one layer. Arm’s CMSIS-NN library has one for int8 convolution, arm_convolve_s8. It is open source, so you can read how it carries out Chapters 1 to 5. This chapter walks through its Cortex-M path with the DSP extension, as written in the library source (we shorten the code).

Step 1: lay the patch out flat

A 3 by 3 patch over 64 channels is scattered in memory. The function first copies each patch into a flat row, one after another. This is called im2col (image to column). Now one output is a dot product of two flat rows: the patch and one filter. The copy costs some RAM and some time, but it makes the inner loop simple and fast.

When the patch hangs over the image edge, the copy needs padding. The source fills those positions with (int8_t)-input_offset. Remember that input_offset is minus Z1, so the pad value is Z1, which stands for real 0. That is the zero point at work again: padding adds exactly nothing to the sum.

Step 2: widen to 16 bits, adding the offset

The inputs move from int8 to int16 as they are copied, and the input offset is added on the way. The new value is x − Z1, which lies in −255 to 255. That range does not fit in 8 bits. It fits in 16 bits easily. This is why the widening step exists: it is where the subtraction of Chapter 2 happens.

Step 3: SMLAD, two multiplies in one instruction

The Cortex-M4 and M7 (and M33 with the DSP extension) have SMLAD. It takes two registers, each holding two 16-bit values. It multiplies the low halves, multiplies the high halves, and adds both products to a 32-bit sum register. That is two multiply-adds in one instruction. The weights, still int8, are widened to int16 pairs by a helper, read_and_pad_reordered. Here is the core loop, condensed from the source:

cint32_t sum = bias[i];                          // bias first, int32
for (int c = 0; c < rhs_cols / 4; c++) {           // 4 MACs per pass
    ker_a = read_and_pad_reordered(ker_a, &k1, &k2);   // 4 int8 weights -> two int16 pairs
    sum = SMLAD(k1, arm_nn_read_q15x2_ia(&ip), sum);    // 2 MACs
    sum = SMLAD(k2, arm_nn_read_q15x2_ia(&ip), sum);    // 2 more MACs
}
sum = arm_nn_requantize(sum, mult[i], shift[i]);       // Chapter 3, per channel
sum += out_offset;                                     // + Z3
sum = MAX(sum, out_act_min);                           // clamp: Chapter 4, and ReLU: Chapter 5
sum = MIN(sum, out_act_max);
*out++ = (int8_t)sum;                                 // now the cast is safe

Every chapter of this lesson is one line of that listing. The bias starts the sum (Chapter 2). The multiply-adds fill it (Chapter 2). The requantize uses the per-channel multiplier and shift (Chapters 3 and 5). The output offset and clamp finish the job (Chapters 4 and 5). The cast is safe only because the clamp came before it.

A leftover loop in the source handles the last one to three terms when the count is not a multiple of four. It uses a plain multiply-add. If you write your own kernel, test lengths that are not multiples of four, because the edge is where bugs live.

Pair them up

Each cell is one product of a dot product. The plain loop does one per instruction. SMLAD does two. Press Run to watch the sum grow, and drag K to change the length.

24

A model of instruction counts only. It does not count loads, the widening of the weights, the loop branch or memory waits, so it is not a cycle count. For a layer with K = 576 the SMLAD loop issues 288 SMLADs against 576 plain multiply-adds.

Two caveats keep the story honest. First, fewer multiply instructions is not the same as half the time. Loads, widening and branches take cycles too, and on a given chip the memory may be the limit. Second, this path needs the DSP extension. A Cortex-M0+ has no SMLAD, so the library falls back to the plain loop in the source (the #else branch). On a chip with Arm Helium (MVE), the source has yet another path. The accelerator lesson, Accelerators on MCUs, covers those.

On real hardware. Take an nRF52840 DK. Build a layer with K = 576 two ways with the same compiler flags: your own plain loop, and CMSIS-NN with the DSP path on. Read the cycle counter around each call (the DWT cycle counter exists on Cortex-M4). Run each 100 times, take the median, and compare. Then check that the two outputs are identical byte for byte. Speed with a different answer is a bug.

For the whole network, memory planning and kernel choice, see Running a network on an MCU. For the earlier lesson on fixed-point filters and SMLAD with 16-bit audio, see Real-time DSP on a Cortex-M.

What the copy costs

The flat copy of a patch is stored as int16, two bytes per term. For K = 576 terms that is 1,152 bytes of RAM for one patch. The library asks you to provide a scratch buffer for this work, so the RAM budget of a layer is its output plus this buffer. The lesson on running a whole network shows how the tensor arena plans it. For now, remember the rule of thumb: the faster inner loop is paid for with a little RAM.

Symptom, measurement, fix

A frequent surprise is a kernel that runs but is slow. The symptom: the layer takes the time of the plain loop, not the SMLAD loop. The measurement: read the cycle counter around the call, then check the build flags. The DSP path in the source is guarded by ARM_MATH_DSP. If the build does not define it, the code takes the plain branch. The fix is to build for the right core (Cortex-M4 or M7) and define the macro your library version expects. Then re-run the parity test of Chapter 7, because the two paths must give identical bytes.

Why does the CMSIS-NN convolution widen int8 inputs to int16 and add the input offset on the way?

Chapter 7

Parity With Python

Prove your C matches the reference, layer by layer, and learn what each kind of bug looks like in the diff

Back to the keyword spotter that scored 94% in Python and 61% on the board. With what you know now, there are many places to look. Is it the zero point? The accumulator? The shift? Reading the code will not find it. You need to compare numbers. This is a test of parity: the chip and the reference give the same output for the same input.

The reference and the golden vectors

Write a reference in Python (with NumPy) that does exactly the integer steps of this lesson. It takes int8 in, uses int32 sums, applies the same M0 and shift, and clamps. It does not use floats after the weights are quantized. Run it on, say, 100 real inputs. For each layer, save the input tensor and the output tensor. These saved pairs are golden vectors: the right answers, written down.

Now feed the same inputs to the C code, and compare the outputs element by element. The simplest first run is on your laptop, compiling the same C kernels for the host. That removes the chip from the question. A mismatch there is a logic bug. A match on the host and a mismatch on the board points at the chip: a compiler option, an alignment fault, a missing DSP flag.

Three levels of agreement

Decide the pass rule before you run. There are three levels, from strict to loose.

  1. Bit exact. Every element equal, difference 0. Use this when the reference and the C use the same rounding rule. It is the right bar for a layer.
  2. Within one tick. Every difference is 0 or 1. Expect this when the two sides round differently (single against double rounding, Chapter 3). It is fine only if you know why.
  3. Same decision. The final class agrees on most inputs. This is an accuracy check on the whole model, not a parity check. It hides errors that happen to cancel.

Aim for level 1 on each layer. If you only test level 3, the 61% would have been the first sign you got, after hours of work.

Find the first layer that differs

The whole network gives a mismatch in the last layer, but the bug sits in the first layer that differs. Compare layer by layer in order. Each layer in the C starts from the reference input for that layer, not from the previous C output. Then one bad layer cannot hide behind the errors of the layers before it. The first layer with a non-zero difference is where you look. Then read the pattern of the differences. It tells you the bug.

Break the layer, read the diff

Each cell is one of 64 outputs of a layer. Green means equal to the reference. Yellow means off by one tick. Red means off by more. Switch on a bug and read the pattern, the count and the first bad index.

A model: 64 outputs of K = 72 terms from seeded random post-ReLU style activations and weights, with the real integer pipeline of Chapters 2 to 4 as the reference (32-bit sum, doubling high multiply plus rounding shift, output offset, clamp). “Single rounding” uses the TensorFlow Lite single-rounding formula, (x × M0 + 2total_shift−1) >> total_shift.

Read the patterns. Forgetting Z1 turns almost every output into a large error, because every sum is off by Z1 times the sum of the weights. A 16-bit sum is wrong on every output where the sum is large, and right where it is small. A truncating shift gives a field of off-by-one cells, all in one direction. A cast without a clamp is wrong only where the value is out of range, and wrong by a lot. Single rounding is right nearly everywhere and off by one on a few cells.

A bug you can name from a diff is a bug you can fix in minutes. That is the value of a parity test.

The test in code

python# reference: the integer pipeline, in NumPy int64 so nothing wraps by accident
def conv_ref(x, w, bias, zx, m0, shift, zo):
    acc = ((x.astype(np.int64) - zx) * w.astype(np.int64)).sum() + bias
    y = requant(acc, m0, shift) + zo            # same rounding as the C
    return np.clip(y, -128, 127).astype(np.int8)

# golden vectors: one file per layer, written as C arrays for the host test
np.save("L3_in.npy", x); np.save("L3_out.npy", conv_ref(...))
c// host or on-target test: compare, and report the FIRST difference
int first = -1, nbad = 0, maxd = 0;
for (int i = 0; i < N; i++) {
    int d = abs((int)out[i] - (int)gold[i]);
    if (d) { nbad++; if (first < 0) first = i; if (d > maxd) maxd = d; }
}
printf("layer %d: %d bad of %d, max diff %d, first at %d\n", L, nbad, N, maxd, first);

On the board, send the same line over the serial port. The nRF52840 DK and most Nucleo boards have a virtual serial port over USB, so you can read the line on your laptop. On real hardware: run the host test first, then flash the same test to the board. If the host passes and the board fails, rebuild the board code with and without the DSP flag, and compare the two reports.

The idea of a parity method is general to edge deployment. A later lesson in this series on deploying models to edge devices treats the same test across toolchains. Here it is enough to keep the rule: no layer ships until its diff is zero, or until you can say in one sentence why it is one.

Test the edges, not only the middle

Real test inputs sit in the middle of the range. Overflow lives at the edges. So add vectors that you build on purpose. Make one with every input at its extreme, so that x − Z1 is as large as possible, and every weight at 127. Make one with all zeros, one with all −128, and one with all 127. Add a vector where the input length K is not a multiple of four, so the leftover loop of Chapter 6 runs.

Here is why the first one matters. With Z1 = −128 and all inputs at 127, every difference is 255. With all weights at 127, every product is 32,385. A 16-bit sum is wrong from the second product on, and a 32-bit sum is fine for 66,311 of them. A random test may never come close to this vector. A built one finds the bug in a single run.

Keep the vectors in version control with the code. When you change a compiler, a library version or a rounding flag, run them again. A parity suite is cheap to keep and expensive to lose.

A layer’s diff against the reference is 0 or 1 on about 3% of the cells, never more, in both directions. What is the most likely cause?

Chapter 8

Field Guide: The Whole Lesson on One Page

Keep the numbers, the checklist and the core code, then follow the links to the rest of the edge ML track

You can now do an int8 layer by hand and in C. A quantized value is a tick number plus a recipe, a scale and a zero point. A convolution output is an int32 sum of (x − Z1) × w, plus an int32 bias. One multiplier M, stored as an int32 and a shift, brings the sum back to int8 with integer math. A clamp finishes the layer and makes ReLU free. Overflow hides in the accumulator, the left shift, and the final cast. A parity test against a reference finds every bug in this list.

The numbers that matter

WhatNumberSource or derivation
The rulereal = scale × (q − zero point)LiteRT quantization spec; Jacob et al.
Activation rangeint8, −128 to 127, any zero pointLiteRT spec
Weight rangeint8, −127 to 127, zero point 0, per output channel for convLiteRT spec (CONV_2D)
Biasint32, scale = input scale × weight scale, zero point 0LiteRT spec; paper eq. 11
MultiplierM = S1 S2 / S3 = 2−n M0, M0 in [0.5, 1), stored as int32 near 231 M0Paper eq. 6
Worked exampleM = 0.01 = 0.64 × 2−6, M0 = 1,374,389,535, sum 3023 gives 30Computed in Chapter 3
Largest product255 × 127 = 32,385 (16,256 if Z1 = 0)Derived in Chapter 4
Terms before int32 can overflow66,311 at 32,385 per term(231 − 1) / 32,385
A 576-term sumup to 18,653,760: 26 bits signed3 × 3 × 64 inputs; derived
SMLAD2 multiply-adds into a 32-bit sum per instructionCMSIS-NN arm_convolve_s8 source
Chip memorynRF52840 1 MB flash, 256 KB RAM; nRF52833 512 KB, 128 KB; RP2040 264 kB SRAM, external flashNordic and Raspberry Pi pages

The words

TermMeaning
ScaleThe real size of one tick.
Zero pointThe integer that stands for real 0.
AccumulatorThe wide register that holds the running sum, int32 here.
RequantizeScale the int32 sum to int8 with M, using integer math only.
SaturateClamp to the nearest limit instead of wrapping around.
Per-channelOne weight scale (and one M) for each output channel.
im2colCopy each patch into a flat row so a convolution becomes dot products.
Golden vectorA saved input and the correct output for one layer.
ParityThe chip and the reference give the same output for the same input.

A checklist before you ship a quantized layer

  1. Types. Sum is int32_t. Bias is int32_t. Weights are int8_t with zero point 0.
  2. Headroom. For every layer, K × 32,385 is below 231 − 1. Assert it in the build.
  3. Offset. The input zero point is subtracted, or folded into the bias, once, and not twice.
  4. Padding. Padded positions hold the zero point (real 0), not integer 0.
  5. Requantize. M0 and shift come from the converter. Rounding rule matches the reference (single or double).
  6. Clamp. Output offset added, then clamp to the activation range, then cast.
  7. Per-channel. Multiplier and shift arrays have one entry per output channel, in the same order as the weights.
  8. Parity. Golden vectors pass bit exact on the host, then on the board, layer by layer.

The core as code

c// One output of an int8 convolution, per-channel requantize. Follows the TFLite reference kernel.
static int32_t rdhm(int32_t a, int32_t b) {            // rounding doubling high multiply
    if (a == b && a == INT32_MIN) return INT32_MAX;
    int64_t ab = (int64_t)a * b;
    int32_t nudge = ab >= 0 ? (1 << 30) : (1 - (1 << 30));
    return (int32_t)((ab + nudge) / (1LL << 31));
}
static int32_t rshift_round(int32_t x, int n) {         // round half away from zero
    int32_t mask = (1 << n) - 1, rem = x & mask;
    int32_t thr = (mask >> 1) + (x < 0);
    return (x >> n) + (rem > thr);
}
int8_t conv_out(const int8_t *x, const int8_t *w, int K, int32_t bias,
                int32_t zx, int32_t m0, int shift, int32_t zo, int32_t lo, int32_t hi) {
    int32_t acc = bias;
    for (int i = 0; i < K; i++) acc += (int32_t)(x[i] - zx) * w[i];
    int left = shift > 0 ? shift : 0, right = shift > 0 ? 0 : -shift;
    int32_t y = rshift_round(rdhm(acc * (1 << left), m0), right) + zo;
    if (y < lo) y = lo;                                  // ReLU is lo = zo; ReLU6 sets hi too
    if (y > hi) y = hi;
    return (int8_t)y;
}

Where it sits in the field

This lesson is the arithmetic under every int8 runtime for microcontrollers: TensorFlow Lite for Microcontrollers, CMSIS-NN, and the compiled-in kernels of tools like TinyEngine. The training side, calibration and quantization-aware training, is in quantization I and quantization II. The 16-bit fixed-point audio view of the same overflow story is in Real-time DSP on a Cortex-M.

Keep going

Sources

The takeaway. An int8 layer is exact integer arithmetic with one rounding step. Every wrong answer comes from a place where the integers ran out of room, lost their zero point, or rounded a different way. Keep the sum in 32 bits, clamp before you cast, and test against a reference.

Now press Present or Teach and explain one output of an int8 convolution from memory: the subtraction of the zero point, the int32 sum, the multiplier and shift, and the clamp. Then go back to the sum at the top, set 16 bits that wrap, and explain where and why it fails.

Int8 in Firmware: Firmware from Zero to Expertise, Edge ML 2
LiteRT quantization spec · Jacob et al. 2018 · CMSIS-NN · Back to Gleams