Skip to content

Lab 6 — KWS Kernel: From Model to C

Goal

Get familiar with the hand-written int8 inference kernel you will run on your platform and accelerate in Project 3. This lab is a reading and running exercise — no hardware needed yet (that requires the UART and timer from Project 2, which you have, but the kernel can be built and tested on your PC first).

When to do this

This lab is released alongside the M04 classes on TinyML. Complete it before Lab 7 (profiling), which builds directly on the code you explore here. You already estimated the MAC count in Lab 1 — now you will see exactly how those MACs are computed.

The big picture

In Lab 1 you ran TFLite Micro's reference implementation on your PC. That implementation is ~100,000 lines of C++. The course's kernel does the same computation in ~150 lines of C, with no dependencies beyond <stdint.h>. This is what runs on your CPU.

The trade-off: TFLite Micro handles arbitrary models; the course kernel is hand-written for tiny_conv only. But it is small enough to read completely, which is the point.

Same weights for everyone

The kernel ships with the weights of the course's reference model, not the model you trained in Lab 1. That way every group computes the same thing, and results and cycle counts can be compared. Your own model.tflite stays in ml/.

Getting the files

The kernel is already in your repository, in kws/: run git pull if you do not see it. The folder is separate from your own work: nothing outside it was changed, and it has its own Makefile, so your Project 1 and 2 files are untouched. Its README.md explains how to build it for the PC and for your core.

File layout

kws/
  weights.h       — int8 weight/bias arrays + per-channel quantization params
  kws_model.h     — layer shapes as constants (kernel sizes, strides, channels)
  kws_kernel.c    — the inference kernel (conv_int8, fully_connected_int8, kws_infer)
  kws_kernel.h    — public interface
  test_vectors.h  — 8 precomputed 49×40 int8 MFCC inputs + expected labels
  main.c          — PC test: run the 8 vectors, print the result
  platform.h      — read_cycle() and the UART, for the board programs
  main_board.c    — board firmware: vector in over the UART, result out
  selftest.c      — board test with no UART (for simulation)

Step 1 — Read the public interface

Activity 1

Open kws_kernel.h. The top-level function is:

1
2
3
4
// input: KWS_INPUT_FRAMES * KWS_INPUT_BINS int8 MFCC values (row-major)
// returns: predicted class index 0..3
//          (silence=0, unknown=1, yes=2, no=3)
int kws_infer(const int8_t *input);

And the layer primitive (static, inside kws_kernel.c):

static void conv_int8(
    const int8_t  *input,   int in_h,  int in_w,  int in_c,
    const int8_t  *weights,
    const int32_t *bias,
    int8_t        *output,  int out_c,
    const int32_t *mult,    // per-output-channel multiplier
    const int32_t *shift,   // per-output-channel shift (negative = right shift)
    int32_t input_zero_point,
    int32_t output_zero_point
);

Answer the following (check kws_model.h for the shapes):

  • What are in_h, in_w, in_c for the Conv2D call?
  • What is out_c?
  • Why are mult and shift arrays, while the two zero points are scalars?
Hint

mult and shift are arrays indexed by output channel because TFLite uses per-channel quantization of the weights: each output channel has its own scale factor, chosen to minimise quantization error for that channel's weight distribution. A single scale for the whole tensor (per-tensor quantization) would be less accurate. The activations (input and output of the layer) are quantized per tensor, so each needs just one zero point.

Step 2 — Trace a single output element

Activity 2

Open kws_kernel.c and find the innermost loop of conv_int8. The computation for one output element output[oh][ow][oc] is:

int32_t acc = bias[co];
for (int ky = 0; ky < CONV1_KH; ky++) {
  int iy = oy * CONV1_STRIDE_H - CONV1_PAD_TOP + ky;
  if (iy < 0 || iy >= in_h) continue;             // SAME padding: skip
  for (int kx = 0; kx < CONV1_KW; kx++) {
    int ix = ox * CONV1_STRIDE_W - CONV1_PAD_LEFT + kx;
    if (ix < 0 || ix >= in_w) continue;
    for (int ci = 0; ci < in_c; ci++)
      acc += (input[(iy * in_w + ix) * in_c + ci] - input_zero_point)
           * weights[((co * CONV1_KH + ky) * CONV1_KW + kx) * in_c + ci];
  }
}
// Requantize acc → int8, then the fused ReLU clamp
output[(oy * CONV1_OUT_W + ox) * out_c + co] = ...;

Trace this on paper for co=0, oy=0, ox=0 using the actual values from weights.h. For these coordinates, which kernel positions (ky, kx) fall inside the input and which are skipped by the padding? You don't need to compute the full result — just verify you understand the index arithmetic. What is conv1_weights[0], and which (co, ky, kx, ci) does it belong to?

Step 3 — Count the MACs

Activity 3

You estimated the total MAC count in Lab 1. Now compute it precisely from kws_model.h:

Layer Formula MACs
Conv2D KH × KW × in_c × out_h × out_w × out_c ?
FC in_features × out_classes ?
Total ?

Fill in the table. Does it match your Lab 1 estimate?

Hint

Conv2D: KH=10, KW=8, in_c=1, out_h=25, out_w=20, out_c=8 → 10×8×1×25×20×8 = 320,000
FC: 4000 × 4 = 16,000
Total: 336,000 MACs

(The kernel skips the positions that fall in the padding, so it executes slightly fewer multiplies than this count at the borders; the count is the right figure for sizing hardware.)

Step 4 — Build and run on your PC

Activity 4

The kernel is designed to compile natively (no hardware, no UART):

cd kws
make test            # same as: gcc -O2 -o kws_test kws_kernel.c main.c && ./kws_test

Expected output: all 8 test vectors classified correctly (matching the labels in test_vectors.h), ending in ~~~ALL TESTS PASSED~~~. The kernel is given to you and already passes; if a label ever mismatches after you edit it, check the requantization functions first.

Use -O2 for the PC build

The native build uses -O2 so the PC reference runs fast. When you later compile for your RISC-V CPU, you will compare -O0 vs -O2 results — both must produce the same classification outputs (optimisation must not change correctness).

Step 5 — The requantization

Activity 5

The accumulator of a layer is an int32 that must be turned back into an int8. Find multiply_by_quantized_multiplier() in kws_kernel.c and the two lines that call it, one in conv_int8 and one in fully_connected_int8:

1
2
3
4
5
6
7
// Conv2D: requantize, add the zero point, fused ReLU
int32_t q = multiply_by_quantized_multiplier(acc, mult[co], shift[co]) + output_zero_point;
output[...] = clamp_int8(q, output_zero_point, 127);

// FC: same requantization, but no activation
int32_t q = multiply_by_quantized_multiplier(acc, mult[co], shift[co]) + output_zero_point;
output[co] = clamp_int8(q, -128, 127);

multiply_by_quantized_multiplier multiplies acc by mult / 2^31 (a fixed-point number in [0.5, 1)) and then shifts right by -shift, rounding to nearest. It is TFLite's own arithmetic, ported line by line. Answer:

  1. saturating_rounding_doubling_high_mul computes acc * mult in 64 bits. Why? What would happen with a 32-bit product?
  2. The Conv2D layer clamps to [output_zero_point, 127], not to [-128, 127]. Why? (Hint: fused ReLU.) What is CONV1_OUTPUT_ZERO_POINT in weights.h, and what does that make the clamp range in practice?
  3. The FC layer clamps to [-128, 127]. Why the difference?
Hint
  1. acc is a sum of 80 products of (input - zero_point) (up to 255 in magnitude) and weights (up to 127), so |acc| is around a few million for the Conv2D layer and up to ~10^8 for the FC layer. mult is up to ~2^31. Their product needs up to ~58 bits and overflows int32, so the multiplication is done in int64_t and then brought back to 32 bits by the / 2^31.
  2. A real value of 0 is represented by output_zero_point in quantized space, so ReLU ("never below real 0") becomes "never below output_zero_point". In this model that zero point is -128, so the clamp range happens to equal the full int8 range: the ReLU is already "built into" the quantization.
  3. The FC layer produces the class scores (logits), which can be negative: no activation function is fused, so the full range is kept.

Step 6 — Sketch the accelerator interface

Activity 6

Project 3 asks you to accelerate conv_int8. Before writing any hardware, sketch on paper:

  1. Which loop level would you accelerate? (Output element? Row? Full layer?)
  2. What data needs to travel from CPU to accelerator per invocation?
  3. How would you use the memory-mapped register interface from Project 2?

No exact answer expected — this is your first design sketch. You will revisit it in Project 3 kickoff.

Checklist

  • kws_infer interface understood; layer shapes identified from kws_model.h.
  • MAC count computed precisely and matches Lab 1 estimate.
  • Kernel builds and runs natively; all 8 test vectors pass.
  • Requantization understood (64-bit product, zero points, fused ReLU, clamping range).
  • Accelerator interface sketch done (rough, on paper).

Summary

You read a complete, dependency-free int8 inference kernel and traced the computation from input through quantized output. The conv_int8 function — with its per-channel mult/shift/zero_point arrays — is the inner loop of the whole model and the target of Lab 7 and Project 3. The requantization step is where floating-point scale factors are emulated in integer arithmetic: understanding it is prerequisite for designing a correct accelerator.