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
Step 1 — Read the public interface
Activity 1
Open kws_kernel.h. The top-level function is:
And the layer primitive (static, inside kws_kernel.c):
Answer the following (check kws_model.h for the shapes):
- What are
in_h,in_w,in_cfor the Conv2D call? - What is
out_c? - Why are
multandshiftarrays, 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:
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):
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:
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:
saturating_rounding_doubling_high_mulcomputesacc * multin 64 bits. Why? What would happen with a 32-bit product?- The Conv2D layer clamps to
[output_zero_point, 127], not to[-128, 127]. Why? (Hint: fused ReLU.) What isCONV1_OUTPUT_ZERO_POINTinweights.h, and what does that make the clamp range in practice? - The FC layer clamps to
[-128, 127]. Why the difference?
Hint
accis 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.multis up to ~2^31. Their product needs up to ~58 bits and overflows int32, so the multiplication is done inint64_tand then brought back to 32 bits by the/ 2^31.- A real value of 0 is represented by
output_zero_pointin quantized space, so ReLU ("never below real 0") becomes "never belowoutput_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. - 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:
- Which loop level would you accelerate? (Output element? Row? Full layer?)
- What data needs to travel from CPU to accelerator per invocation?
- 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_inferinterface understood; layer shapes identified fromkws_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.