121м. A convolutional network by hand: convolution, pooling, shared weights — and the same network in int8 on a Cortex-M
In 121ж–121л every network was fully connected: each neuron looks at the whole input at once and keeps its own weight for every input point. For a sensor signal that is wasteful. A knock on the housing looks the same whether it happened at the start of the window or at the end, yet a fully connected network has to learn it separately in every position. A convolutional network works differently: one small filter slides along the signal, and its weights are shared by all positions. Here such a network is built by hand in numpy, with the backward pass through convolution and pooling, compared with a fully connected network on the same task and ported to C — first in float, then in int8 with our own code and, for comparison, with the convolution from CMSIS-NN. The ready-made path through Keras and TFLite is in 118а, 119 and 121е; here is everything they do inside.
Basis: numpy 2.3.3 in the stm-ml:1 image, the script train121m.py
runs all experiments, and a repeated run produces the same files. The
data come from our own generator of accelerometer windows on a device
housing: 64 samples on three axes (100 Hz, 0.64 s), integer mg, five
classes — rest, knock, shake, double tap, tilt; the event sits at a
random place in the window. 1000 windows for training and 1000 for
testing, seed 1219. Training uses mini-batches of 20 windows, softmax
with cross-entropy (121и), 60 epochs, step 0.1. Inference in C: gcc
12.2.0 (stm-sys:1) for cross-checking, arm-none-eabi-gcc 12.2.1 and
QEMU 7.2 (stm-arm:1, the netduinoplus2 board with an STM32F405 —
the same Cortex-M4F core as the F407) for instruction counts;
CMSIS-NN 7.0.0 — sources from the Keil pack.
What it is called in the documentation
Original Meaning local receptive field the patch of the input that one convolution output depends on shared weights, parameter sharing one and the same filter at every position of the input feature map the output of one filter at all positions filter, convolution kernel k samples × the number of input channels of weights plus one bias valid convolution convolution without padding: the output is k − 1 shorter than the input global max pooling one maximum per channel over the whole window im2col unrolling the windows into rows: convolution becomes a matrix product translation invariance the answer does not depend on where the event is ping-pong buffers two buffers in turn: a layer reads from one and writes to the other
121м.1 Convolution: the local field and shared weights
The window is 64 samples on three axes. The first layer is eight filters 5 samples long: each filter sees 5 × 3 = 15 consecutive numbers, multiplies them by its 15 weights, adds a bias and passes the result through ReLU. Then the filter moves by one sample, 60 times in all: a window of length 64 holds 64 − 5 + 1 = 60 positions. The output of one filter at all positions is a feature map of length 60; eight filters give eight maps.
In C these are two nested loops — over positions and over filters — with a sum of products inside:
const float *w = W + o * K * c, *v = x + t * c; /* одни и те же K·c весов на каждом t */
float s = b[o];
for (int i = 0; i < K * c; i++)
s += w[i] * v[i];
The weight pointer w does not depend on the position t — that is
exactly what shared weights are. Only the input pointer v moves. A
two-dimensional convolution (an image, 121м.4) is the same thing,
except that a 3 × 3 filter slides along rows and columns.
What convolution costs. The same 60 × 8 output could be produced by a fully connected layer: 480 neurons, each with its own weights to all 192 inputs:
| First layer, output 60 × 8 | Parameters | Multiplications per answer |
|---|---|---|
| convolution 5 × 3 → 8 | 128 | 7200 |
| fully connected 192 → 480 | 92640 | 92160 |
There are 724 times fewer parameters: each convolution output looks at 15 inputs rather than 192, and all 60 positions share one set of weights. There are only 12.8 times fewer multiplications — every position is still computed separately. This is the main property of a convolutional network on a device: the weights take almost nothing, but the computation remains. The whole network in the figure has 685 parameters and 19740 multiplications per answer; the fully connected network 192 → 32 → 5 from 121м.2 has 6341 parameters and 6304 multiplications: 9.3 times more weights and 3.1 times less computation.
121м.2 Pooling and the global maximum
After the first convolution comes a maximum over two neighbouring samples: the 60 × 8 map becomes 30 × 8. Pooling has no weights; it halves the work of the next convolution and makes the network a little less sensitive to a shift of one sample. After the second convolution comes global pooling: each of the 12 maps of length 26 is reduced to a single number. Whether that number is a maximum or a mean matters a lot. Three networks on the same data, 60 epochs:
| Network | Parameters | Correct of 1000 in training | Correct of 1000 in testing |
|---|---|---|---|
| convolutional, global maximum | 685 | 1000 | 997 |
| convolutional, global mean | 685 | 879 | 850 |
| fully connected 192 → 32 → 5 | 6341 | 928 | 796 |
Correct answers by class in testing:
| Class | rest | knock | shake | double tap | tilt |
|---|---|---|---|---|---|
| windows | 170 | 195 | 216 | 233 | 186 |
| convolutional, maximum | 170 | 195 | 215 | 231 | 186 |
| fully connected | 170 | 91 | 210 | 141 | 184 |
A knock lasts a few samples out of 64. The filter tuned to it lights up in one or two places of the map; the maximum passes exactly that on: "somewhere in the window there was a knock". The mean spreads the response over 26 places, and a short event drowns in zero. The fully connected network is worst at telling apart exactly the short events — knock and double tap — because it has to see each of them in each position of the window, and 1000 windows are not enough for that: 928 in training, 796 in testing — it memorizes rather than generalizes.
121м.3 The backward pass through convolution and a gradient check
The backward pass (121з) through a convolution is easiest to derive from unrolling the windows into rows. Forward pass: the window of each position is a row of length k·C, all rows form a matrix, and the convolution is a single product of that matrix with the k·C × F weight matrix. From there everything is as in a fully connected layer, with one difference: the weights are shared, so their gradient is the sum of contributions from all positions and all examples of the batch:
dW = (cols.reshape(-1, cols.shape[-1]).T @ dZ.reshape(-1, F)).reshape(W.shape) # общие веса: сумма по всем местам
The gradient with respect to the input is the inverse of the unrolling: each input number landed in k different windows, and its gradient is the sum over all k:
for i in range(kh):
for j in range(kw):
dX[:, i:i + Ho, j:j + Wo, :] += dcols[:, :, :, i * kw + j, :]
Through a maximum the gradient flows only to the input that won, the others get zero; through a mean it is split equally:
np.put_along_axis(m, flat.argmax(axis=-1)[..., None], 1.0, axis=-1) # градиент — только победителю
A numerical check. An error in such code does not show in the accuracy — a network with a wrong gradient often still learns something. It is more reliable to compare with a finite difference: shift each parameter in turn by ±10⁻⁶ and divide the difference in loss by 2·10⁻⁶. A small network — a convolution from 3 to 2 channels, max over 2, a convolution from 2 to 3, a global maximum and a fully connected layer, input 12 × 2, four examples: 47 parameters, the largest relative difference between the analytic and the numerical gradient is 1.1·10⁻⁸. That is rounding error, not a formula error: a wrong index in the unrolling would give a difference of order one.
121м.4 Convolutional versus fully connected: shift and the two-dimensional case
Shift. The most telling experiment: train both networks on windows where the event starts in the first half of the allowed positions, and test on windows where it is in the second half. The network never saw such positions during training:
| Network | Correct of 1000, events in the first half (training) | Correct of 1000, events in the second half |
|---|---|---|
| convolutional, global maximum | 1000 | 986 |
| fully connected 192 → 32 → 5 | 944 | 436 |
The convolutional network barely noticed the switch: the filter responds the same way to a knock anywhere, and the global maximum does not remember where the response was. The fully connected network hardly trained its weights for the second half of the window and is wrong in half the cases there.
Two-dimensional convolution. In an image the filter is a 3 × 3 square and slides in two directions. The same 5 × 7 indicator digits as in 121ж–121л (seed 1218, 3000 training examples, 1000 test), 30 epochs:
| Network | Parameters | Multiplications | Correct of 1000 |
|---|---|---|---|
| convolution 3 × 3 → 8, ReLU, fully connected 120 → 10 | 1290 | 2280 | 932 |
| fully connected 35 → 80 → 10 | 3690 | 3600 | 958 |
Here convolution did not win. A digit on the indicator shifts by at most one dot, it has no "event at a random place", and the fully connected network simply memorizes each position — the same network in 121л also got 958. The convolution with 1290 parameters got 932: fewer weights, but lower accuracy as well. Convolution wins where the same pattern occurs at different places of the input — in a sensor signal over time, in a camera frame (121а, 121в), in a sound spectrogram (121б).
121м.5 int8: scales per layer
Quantization is as in 119.2: a real r is stored as an integer q by the rule r = s · (q − z). Weights are symmetric, one scale per layer, zero point 0. Activations are asymmetric: the scale and zero point of each layer come from the smallest and largest value over the 1000 training windows. All of this is computed by our own code, without the TFLite converter:
| Layer | Weight scale | Input: scale, zero point | Output: scale, zero point | Q31 multiplier, shift |
|---|---|---|---|---|
| convolution 5 × 3 → 8 | 0.01891 | 0.008118, 0 | 0.01446, −128 | 1459333841, −6 |
| convolution 5 × 8 → 12 | 0.01446 | 0.01446, −128 | 0.06064, −128 | 1894880842, −8 |
| fully connected 12 → 5 | 0.02348 | 0.06064, −128 | 0.2671, −17 | 1465270345, −7 |
After ReLU the output is never negative, so the zero point is −128: all 256 levels go to the positive half. The input after removing the mean is symmetric, its zero point is 0; not one of the 192000 test numbers went outside int8. Max over 2 and the global maximum are computed directly in int8: rescaling is monotonic, and the largest integer is the same as the largest real value.
The sum of products accumulates in int32, the bias in the scale s_input · s_weight is added to it, and the sum is brought to the output scale by a multiplier and a shift. How to obtain the Q31 multiplier is in 119.7. The rescaling itself in C uses two roundings, as CMSIS-NN does by default:
int32_t v = (int32_t)(((int64_t)acc * m + (1 << 30)) >> 31); /* acc · m / 2³¹ с округлением */
int32_t mask = (1 << -sh) - 1, r = v >> -sh; /* затем / 2^(−sh), середина — от нуля */
return r + ((v & mask) > (mask >> 1) + (r < 0));
ReLU needs no separate instruction: the convolution output is clamped from below at its zero point, that is, at real zero:
acc += (v[i] - zx) * w[i];
y[t * f + o] = clamp8(requant(acc, m, sh) + zy, zy); /* ReLU: снизу — нулевая точка */
What was lost. On the 1000 test windows the float network is correct in 997 cases, the int8 one in 994; the answers matched in 997 windows out of 1000. All three disagreements are windows where float is right and int8 is wrong. On the training windows both are correct on 1000 of 1000. The integer pass in numpy and in C gave identical int8 outputs in all 1000 windows — a bit-for-bit comparison, not one by answers.
121м.6 On a Cortex-M4: instructions, flash and RAM
The same network in C (cnn121m.c, given in full at the end of the
section) in float and in int8; for comparison — int8 with the
arm_convolve_s8 convolutions from CMSIS-NN 7.0.0 and the fully
connected 192 → 32 → 5 in float. Instructions come from QEMU
netduinoplus2 with -icount, arm-none-eabi-gcc -O2 with the FPU,
averaged over 100 windows; accuracy is over 1000 windows in QEMU and
matched the computer:
| Network | Weights and biases, bytes | Activation buffers, bytes | Instructions per answer | At 168 MHz, no faster than | Correct of 1000 |
|---|---|---|---|---|---|
| convolutional, float | 2740 | 2880 | 150858 | 898.0 µs | 997 |
| convolutional, int8, own code | 760 | 720 | 156911 | 934.0 µs | 994 |
| convolutional, int8, CMSIS-NN convolutions | 760 | 720 + 160 | 117982 | 702.3 µs | 994 |
| fully connected 192 → 32 → 5, float | 25364 | — | 41758 | 248.6 µs | 796 |
Flash. int8 shrank the weights 3.6 times: 2740 bytes → 760. The fully connected network, with worse accuracy, takes 25364 bytes — 33 times more than the convolutional one in int8.
RAM for activations. The layers write in turn to two buffers: the
input and the outputs of max over 2 and of the global maximum go to
buffer A of 240 numbers, the outputs of the convolutions and of the last
layer go to buffer B of 480 (figure in 121м.1). In int8 that is 720
bytes, in float 2880. Buffer B is sized by the widest output, 60 × 8 —
the first convolution before pooling. CMSIS-NN asks for another 160
bytes to unroll the windows: arm_convolve_s8_get_buffer_size returned
160 for the 5 × 8 convolution.
Instructions. The convolutional network in float takes 150858
instructions, about 7.6 per multiplication. Our own int8 turned out 4.0 %
slower than float: the Cortex-M4 has an FPU, and a multiply-accumulate
in float is one instruction just as in integers, while int8 adds the
zero-point subtraction and the rescaling. On the M4 the gain of int8 is
in memory, not in speed, as long as the work proceeds one number at a
time. CMSIS-NN gets its speed from DSP instructions: two 16-bit
products in one instruction — and comes out 25 % below our own int8.
Its code is 3968 bytes of flash for arm_convolve_s8 and its three
helper functions. The convolution outputs of CMSIS-NN and of our own
code matched bit for bit in all 1000 windows: the scales, the weight
order [output][height][width][input] and the rounding are the same.
The fully connected network computes 3.6 times faster than the convolutional one: it has three times fewer multiplications. But the window is 0.64 s, and even 934 µs is less than 0.15 % of that time; on an accelerometer device it is flash and RAM that are saved, and the accuracy of 997 versus 796 makes the choice by itself.
121м.7 Pitfalls
Global mean instead of maximum. A short event is spread over all positions of the map: 850 correct of 1000 instead of 997. For "was it in the window" you need the maximum; the mean suits a feature spread over the whole window — a hum, a vibration.
Our own int8 is not faster than float on an M4. 156911 instructions versus 150858. One quantizes for flash and RAM, and speed comes from a library with DSP instructions or from a core with vector instructions (121в).
Weight order. CMSIS-NN expects the filter in the order [output][height][width][input], while numpy stores (height, width, input, output). The permutation is done in the script that writes the header; without it the network builds and answers garbage.
A different rounding — different bits. CMSIS-NN has a second
rescaling variant with a single rounding (the macro
CMSIS_NN_USE_SINGLE_ROUNDING). If the library is built with it while
your own code and the check use two roundings, outputs will differ by
one in some windows, and a bit-for-bit comparison shows it at once.
A gradient without a check. The network hides an error in the backward pass through convolution: it learns worse, but it learns. A finite difference on a small network — 47 parameters and a difference of 1.1·10⁻⁸ — catches it in seconds.
Scale from a small sample. The activation scales were taken from the largest values over 1000 training windows. A signal stronger than any of them will hit 127; in testing there was not one such input out of 192000, but on another device with a different sensor mounting this is checked again.
121м.8 Summary
- A 5 × 3 → 8 convolution versus a fully connected layer with the same 60 × 8 output: 128 parameters versus 92640 and 7200 multiplications versus 92160.
- The convolutional network has 685 parameters and 19740 multiplications, 997 of 1000; the fully connected 192 → 32 → 5 has 6341 parameters, 796 of 1000.
- Global maximum — 997, global mean — 850.
- Events only in the first half of the window during training: on the second half the convolutional network gets 986, the fully connected 436.
- Gradient check: 47 parameters, difference 1.1·10⁻⁸.
- int8 with a scale per layer: 994 versus 997, the answers matched in 997 windows; numpy and C — bit for bit, CMSIS-NN and our own code — bit for bit.
- Cortex-M4: float 150858 instructions, own int8 156911, CMSIS-NN 117982; weights 760 bytes in int8 versus 2740 in float, activations 720 bytes in two buffers.
Further reading: Michael Nielsen, Neural Networks and Deep Learning, neuralnetworksanddeeplearning.com.
Full sources
cnn121m.c — the convolutional network in C in float and in int8 with weights and scales from model121m.h.
/* Раздел 121м: свёрточная сеть на C — во float и в int8, без библиотек.
* Окно акселерометра 64 × 3 (mg) → свёртка 5 × 3 → 8 + ReLU → максимум по 2 → свёртка 5 × 8 → 12 + ReLU
* → глобальный максимум → полносвязный 12 → 5. Веса и масштабы — из model121m.h (train121m.py).
* prep — убрать постоянную составляющую по каждой оси в целых mg.
* cnn_f — сеть во float; cnn_q — та же сеть в int8: веса симметрично, активации со своей нулевой
* точкой, пересчёт суммы int32 — множитель Q31 и сдвиг (requant).
* Активации — в двух буферах по очереди (ping-pong): вход слоя в одном, выход в другом.
* На компьютере (-DML_HOST) main сверяет ответы с numpy на 1000 проверочных окнах.
* Проверка — _verify/nn121m_check.py. */
#include <math.h>
#include <stdint.h>
#include "model121m.h"
#define L0 64
#define C0 3
#define K 5
#define F1 8
#define L1 (L0 - K + 1) /* 60 */
#define P1 (L1 / 2) /* 30 */
#define F2 12
#define L2 (P1 - K + 1) /* 26 */
#define NC 5
static float fa[P1 * F1], fb[L1 * F1]; /* 240 и 480 чисел */
static int8_t qa[P1 * F1], qb[L1 * F1];
static void prep(const int16_t *mg, int32_t *x)
{
for (int c = 0; c < C0; c++) {
int32_t s = 0;
for (int t = 0; t < L0; t++)
s += mg[t * C0 + c];
int32_t m = (s + 32) >> 6;
for (int t = 0; t < L0; t++)
x[t * C0 + c] = mg[t * C0 + c] - m;
}
}
/* ── float ─────────────────────────────────────────────────────────── */
static void conv_f(const float *x, int n, int c, const float *W, const float *b, int f, float *y)
{
for (int t = 0; t + K <= n; t++)
for (int o = 0; o < f; o++) {
const float *w = W + o * K * c, *v = x + t * c; /* одни и те же K·c весов на каждом t */
float s = b[o];
for (int i = 0; i < K * c; i++)
s += w[i] * v[i];
y[t * f + o] = s > 0.0f ? s : 0.0f;
}
}
int cnn_f(const int16_t *mg, float *out)
{
int32_t x[L0 * C0];
prep(mg, x);
for (int i = 0; i < L0 * C0; i++)
fa[i] = (float)x[i] * 0.001f;
conv_f(fa, L0, C0, F_W1, F_B1, F1, fb);
for (int t = 0; t < P1; t++) /* максимум по 2 */
for (int o = 0; o < F1; o++)
fa[t * F1 + o] = fmaxf(fb[2 * t * F1 + o], fb[(2 * t + 1) * F1 + o]);
conv_f(fa, P1, F1, F_W2, F_B2, F2, fb);
for (int o = 0; o < F2; o++) { /* глобальный максимум */
float m = fb[o];
for (int t = 1; t < L2; t++)
m = fmaxf(m, fb[t * F2 + o]);
fa[o] = m;
}
int best = 0;
for (int j = 0; j < NC; j++) {
float s = F_B3[j];
for (int i = 0; i < F2; i++)
s += F_W3[j * F2 + i] * fa[i];
if (out)
out[j] = s;
fb[j] = s;
if (s > fb[best])
best = j;
}
return best;
}
/* ── int8 ──────────────────────────────────────────────────────────── */
static int32_t requant(int32_t acc, int32_t m, int sh)
{
int32_t v = (int32_t)(((int64_t)acc * m + (1 << 30)) >> 31); /* acc · m / 2³¹ с округлением */
int32_t mask = (1 << -sh) - 1, r = v >> -sh; /* затем / 2^(−sh), середина — от нуля */
return r + ((v & mask) > (mask >> 1) + (r < 0));
}
static int8_t clamp8(int32_t v, int32_t lo)
{
return (int8_t)(v < lo ? lo : v > 127 ? 127 : v);
}
static void conv_q(const int8_t *x, int n, int c, const int8_t *W, const int32_t *b, int f,
int zx, int zy, int32_t m, int sh, int8_t *y)
{
for (int t = 0; t + K <= n; t++)
for (int o = 0; o < f; o++) {
const int8_t *w = W + o * K * c, *v = x + t * c;
int32_t acc = b[o];
for (int i = 0; i < K * c; i++)
acc += (v[i] - zx) * w[i];
y[t * f + o] = clamp8(requant(acc, m, sh) + zy, zy); /* ReLU: снизу — нулевая точка */
}
}
static void pool_q(const int8_t *x, int8_t *y)
{
for (int t = 0; t < P1; t++)
for (int o = 0; o < F1; o++) {
int8_t a = x[2 * t * F1 + o], b = x[(2 * t + 1) * F1 + o];
y[t * F1 + o] = a > b ? a : b;
}
}
static int head_q(const int8_t *x, int8_t *out)
{
int8_t g[F2];
for (int o = 0; o < F2; o++) { /* глобальный максимум */
int8_t m = x[o];
for (int t = 1; t < L2; t++)
if (x[t * F2 + o] > m)
m = x[t * F2 + o];
g[o] = m;
}
int best = 0;
for (int j = 0; j < NC; j++) {
int32_t acc = Q_B3[j];
for (int i = 0; i < F2; i++)
acc += (g[i] - Q_ZX3) * Q_W3[j * F2 + i];
out[j] = clamp8(requant(acc, Q_M3, Q_SH3) + Q_ZY3, -128);
if (out[j] > out[best])
best = j;
}
return best;
}
static void quant_in(const int16_t *mg, int8_t *q)
{
int32_t x[L0 * C0];
prep(mg, x);
for (int i = 0; i < L0 * C0; i++)
q[i] = clamp8((int32_t)floorf((float)x[i] * Q_IN_K + 0.5f) + Q_IN_Z, -128);
}
int cnn_q(const int16_t *mg, int8_t *out)
{
quant_in(mg, qa);
conv_q(qa, L0, C0, Q_W1, Q_B1, F1, Q_ZX1, Q_ZY1, Q_M1, Q_SH1, qb);
pool_q(qb, qa);
conv_q(qa, P1, F1, Q_W2, Q_B2, F2, Q_ZX2, Q_ZY2, Q_M2, Q_SH2, qb);
return head_q(qb, out);
}
/* Полносвязная сеть 192 → 32 → 5 на том же входе — для сравнения. */
int mlp_f(const int16_t *mg)
{
int32_t x[L0 * C0];
float h[32], best = -1e30f;
int k = 0;
prep(mg, x);
for (int i = 0; i < L0 * C0; i++)
fa[i] = (float)x[i] * 0.001f;
for (int j = 0; j < 32; j++) {
float s = M_B1[j];
for (int i = 0; i < L0 * C0; i++)
s += M_W1[j * L0 * C0 + i] * fa[i];
h[j] = s > 0.0f ? s : 0.0f;
}
for (int j = 0; j < NC; j++) {
float s = M_B2[j];
for (int i = 0; i < 32; i++)
s += M_W2[j * 32 + i] * h[i];
if (s > best)
best = s, k = j;
}
return k;
}
#ifdef ML_HOST
#include <stdio.h>
int main(void)
{
int rf = 0, rq = 0, same_f = 0, same_q = 0, same_m = 0, agree = 0;
int8_t o[NC];
for (int k = 0; k < N_TEST; k++) {
const int16_t *w = TEST_MG + L0 * C0 * k;
int a = cnn_f(w, 0), b = cnn_q(w, o), eq = 1;
for (int j = 0; j < NC; j++)
eq &= o[j] == REF_Q[NC * k + j];
rf += a == TEST_Y[k], rq += b == TEST_Y[k], agree += a == b;
same_f += a == REF_F[k], same_q += eq, same_m += mlp_f(w) == REF_M[k];
}
printf("right_f=%d\nright_q=%d\nagree_fq=%d\nsame_f=%d\nsame_q=%d\nsame_m=%d\n", rf, rq, agree, same_f, same_q, same_m);
return 0;
}
#endif
Next: section 121н "Overfitting and regularization in depth: L2, L1, dropout, data augmentation, early stopping" — the series "Neural networks from the inside": what overfitting looks like on the curves and why the data needs three sets, where weight decay in L2 comes from and why small weights give a smooth function, how the zeros of L1 help flash memory, what to do with dropout at inference, and why shifting the accelerometer window gave more than all penalties together.