Run a quantised dense layer
Compute an int8 fully connected layer with zero points, bias and requantisation. A hard embedded C problem (TinyML: machine learning on MCUs), run and graded…
hard · TinyML: machine learning on MCUs · tinyml · quantisation · fixed-point
TinyML models run in int8: each tensor stores q with real = scale × (q − zero_point). A fully connected (dense) layer computes, for each output neuron j:
- an int32 accumulator:
acc = bias[j] + Σ (x[i] − x_zp) × w[j][i](weights here have zero point 0; the bias is already in int32, scaled byx_scale × w_scale), - requantise:
y = round(acc × x_scale × w_scale / y_scale) + y_zp, - clamp to −128..127 (and apply ReLU if asked: clamp below at
y_zp, which is real 0).
Write dense_int8(x, n_in, w, bias, n_out, xq, w_scale, yq, relu, y), with w stored row by row (w[j * n_in + i]). Round half away from zero (lroundf, or add ±0.5 and truncate).
Starter code
void dense_int8(const int8_t *x, int n_in, const int8_t *w, const int32_t *bias, int n_out,
qparams_t xq, float w_scale, qparams_t yq, bool relu, int8_t *y) {
for (int j = 0; j < n_out; j++) {
int8_t acc = 0;
for (int i = 0; i < n_in; i++) acc += x[i] * w[j * n_in + i];
y[j] = acc;
}
(void)bias; (void)xq; (void)w_scale; (void)yq; (void)relu;
}Example tests
Two neurons
int8_t x[3] = { 10, -20, 30 };
int8_t w[6] = { 1, 2, 3, -1, 0, 4 };
int32_t b[2] = { 100, -50 };
qparams_t xq = { 0.05f, 0 }, yq = { 0.1f, 0 };
int8_t y[2];
dense_int8(x, 3, w, b, 2, xq, 0.02f, yq, false, y);
show(y, 2);Expected output:
2 1Zero points
int8_t x[2] = { -128, 127 };
int8_t w[2] = { 50, 50 };
int32_t b[1] = { 0 };
qparams_t xq = { 0.02f, -128 }, yq = { 0.05f, -10 };
int8_t y[1];
dense_int8(x, 2, w, b, 1, xq, 0.01f, yq, false, y);
show(y, 1);Expected output:
41Learn it first
- TinyML: machine learning on MCUs · Quantised models, TensorFlow Lite Micro and fitting the budget.