Building an int8 inference engine from DSP slices
A tutorial built on the MCLP inference engine: fix the integer arithmetic first, describe layers as data, turn the loops into counters, pipeline one DSP multiply-accumulate, and test the RTL bit for bit against a reference.
There are two common ways to run a neural network on an AMD FPGA. One is a vendor accelerator such as the DPU. The other is a tool such as hls4ml or FINN, which generates hardware for one specific model. Neither fit MCLP, the load-cell core from this series.
The DPU is far larger than the models in part 5, and current Vitis AI releases no longer support it on Zynq-7000. hls4ml and FINN build the network into the hardware, so every model change needs a new bitstream. MCLP is an IP core, and its users train and load their own models.
So I built mclp_nn, a small programmable engine. The model lives in block RAM as a list of layers, biases and weights. The engine works through the list with one int8 multiply-accumulate per clock. Software loads a new model over AXI4-Lite.
These steps build an engine like it. The RTL is rtl/mclp_nn.sv in the MCLP repository. The test and its integer reference are in tb/mclp_nn. The method suits any small one-dimensional model on sensor data.
The engine. Everything runs in the 50 MHz processing clock.
What you need
- A trained model, quantized to int8, with a scale per layer. Any quantization-aware training flow works. Mine is in PyTorch, and part 5 describes it.
- Python 3 with numpy, for the integer reference.
- cocotb 2.x and Icarus Verilog 12, for the bit-exact test.
- Vivado, for synthesis and timing. MCLP targets a Zynq-7000 (xc7z020). Its DSP48E1 slices have a 25 × 18 multiplier and a 48-bit accumulator.
Step 1: fix the integer arithmetic first
The engine and the training flow must agree on every bit. So write the arithmetic down before any RTL. For MCLP, the arithmetic is:
- Weights and activations are int8, and biases are int32.
- Each output starts from its bias and adds products of weights and activations. The accumulator is 48 bits, the width of the DSP48 accumulator. The model export checks that no layer goes past it.
- Between layers, a fixed-point multiply and a rounding shift scale the accumulator back to int8: y = sat8((acc × M + 2^(s−1)) >> s). For a layer with ReLU, the result is clipped at 0. M is a 15-bit integer, and s is a shift from 1 to 47.
- The last layer uses the same scaling into a 32-bit correction in Q0.20.
Each layer has a float scale: the weight scale times the input scale, divided by the output scale. This scale becomes an M and an s. The test computes them like this:
def scale_ms(scale):
s = clamp(14 - math.floor(math.log2(scale)), 1, 47)
return clamp(round(scale * 2**s), 1, 0x7FFF), s
M lands between 2^14 and 2^15, so it keeps 15 bits of precision for any scale.
Then write a plain integer reference of the whole network. This reference, from the cocotb test, reads the same packed memories as the engine. Thus it also checks the packing:
for o in range(oo):
for t in range(tt):
acc = signed(bias[bb + o], 32) + sum(w8(wb + (o * cc + c) * kk + j) * a[c * ll + t * st + j]
for c in range(cc) for j in range(kk))
out.append((acc * m + (1 << (s - 1))) >> s)
That loop is the specification. Everything after this step must reproduce it exactly.
Step 2: normalize the input in integers
The input of the model is a window of 256 weights. Each weight is written as its deviation from the weigh-in-motion result of the core, ref, in steps of 1/1024: q = (x / ref − 1) × 1024, saturated to int8. A division of every sample by ref would need a divider in the sample path. Instead, the engine divides once per inference:
- k is the bit length of ref, and R = 2^(k+21) / ref.
- For each sample, d = x − ref, clamped to ±2^k.
- q = sat8((d × R + 2^(k+10)) >> (k+11)).
One shift-and-subtract divider, at 64 cycles per division, computes ref from WIM_SUM / WIM_COUNT and then R. After that, each sample costs one multiplication and a shift, 4 clocks in the input stage. The general rule is: divide once per inference, and multiply per sample.
Step 3: describe the layers as data
To make the engine programmable, every layer has the same shape: a one-dimensional convolution over the valid positions. A dense layer also fits, as a convolution whose kernel covers its whole input (K = L, one output position). Each layer is four 32-bit words in the layer list:
| Word | Fields |
|---|---|
| 0 | [31] last, [30] ReLU, [29:26] stride, [25:16] kernel K, [15:8] input channels C, [7:0] output channels O |
| 1 | [25:16] input length L, [9:0] output length T |
| 2 | [21:16] shift s, [14:0] multiplier M |
| 3 | [31:16] first bias, [15:0] first weight byte |
The weights are int8 in (O, C, K) order, four to a 32-bit word. The three model memories are dual-port block RAMs. The AXI4-Lite side writes them on one port, and the engine reads them on the other port. In MCLP, the memories hold 64 layer words, 256 biases and 4096 weight words (16 KB). So a model has at most 16 layers. The activation buffers hold 1024 values per half, so the C × L and O × T of each layer must fit in 1024.
In this format, the default MCLP model has three convolutions and two dense layers, with 5328 weight bytes and 57 biases.
Step 4: turn the loops into counters
The reference in step 1 has four nested loops: output channel o, output position t, input channel c and kernel tap k. In hardware, these loops become four counters that advance once per clock. The activation address is c × L + t × stride + k. The weight pointer steps through the (O, C, K) array:
ST_RUN: begin
if (!k_end) begin
k <= k + 1'b1;
wptr <= wptr + 1'b1;
end else begin
k <= 10'd0;
if (!c_end) begin
c <= c + 1'b1;
arow <= arow + l_l;
wptr <= wptr + 1'b1;
end else begin
c <= 8'd0;
if (!t_end) begin
t <= t + 1'b1;
ts <= ts + l_s;
arow <= ts + l_s;
wptr <= wob; // same output channel, same weights
end else begin
... // next channel, or the layer is done
end
end
end
end
When t advances, the weight pointer goes back to the start of the weights of the current output channel, because every output position uses the same kernel. When o advances, the pointer moves to the weights of the next channel.
The activations sit in two halves of one buffer. Layer 0 reads half A and writes half B. Layer 1 reads B and writes A, and so on. The lowest bit of the layer number selects the half. No activation ever leaves the engine.
Step 5: pipeline one multiply-accumulate
On each clock, the counters issue one weight address and one activation address. The pipeline behind them has two stages. In the first stage, the memories return a weight word and an activation byte, and the engine selects the correct byte of the word. In the second stage, the 8 × 8 product goes into the 48-bit accumulator. The first product of each output starts from the bias instead of the old accumulator value:
wire signed [7:0] w8 = wt_q[8*bs1 +: 8];
// sign-extended; a concatenation would make the sum unsigned
wire signed [47:0] b2e = b2;
wire signed [47:0] acc_n = (f2 ? b2e : acc) + pr2;
When an output is complete, two more pipeline stages requantize it with the M and s of the layer. A hidden layer clips the result to int8 (or to 0 to 127 with ReLU). It writes the result into the other half of the activation buffer. The last layer saturates the result to 32 bits as the correction. The output stage then computes the corrected estimate, ref + ((ref × correction + 2^19) >> 20).
With one multiply-accumulate per clock, the model sets the cycle count. The default model needs 43216 multiply-accumulates and takes 44439 clock cycles, 0.89 ms at 50 MHz. The other 1223 cycles go to the two divisions, the input stage, the pipeline fill and drain of each layer, and the output stage.
Step 6: test it bit for bit
The cocotb test runs the engine and the integer reference side by side:
- the default model on 10 windows shaped like real loads
- edge cases: ref clamped to 1, ref at 2^31 − 1, and a quotient that must be clamped
- eight random models with three windows each, with random layer counts, sizes, strides and scales, chosen so that values saturate
- no run while the engine is disabled, and no run for a weigh-in-motion result that arrives during a run
Every output matches the reference exactly. The test found two bugs:
- At first, an
always @(*)block computed the ring and activation read addresses. Icarus doesn't evaluate such a block until one of its inputs changes, so the first window read X. The addresses are now continuous assignments. - The bias went into the accumulator through a concatenation. In Verilog, a concatenation is unsigned. This made the whole sum unsigned and zero-extended the negative products. The bias now goes through an explicitly signed 48-bit wire, the
b2eline in step 5.
The system test showed a third problem. In simulation, a load in the first 1.7 s after reset read X from the ring buffer, because the ring started empty. Block RAM powers up as zeros after configuration. So the ring now also starts at zero in simulation.
Step 7: connect it to software
In MCLP, the registers of the engine sit at 0x1000 in the 64 KB AXI4-Lite window of the core. The layer list is at 0x2000, the biases at 0x3000 and the weights at 0x4000 to 0x7FFF. To load a model, do these steps:
- Clear NN_CTRL.enable.
- Write the layer list, biases and weights.
- Set NN_CTRL.enable.
The nn load command of the console does this from three memory files. It reads every word back and prints a CRC-32 of the model, so that you can identify the loaded model. After each weigh-in-motion load, the engine sets IRQ_STATUS[7]. Software then reads the correction from NN_CORR and the corrected estimate from NN_EST. The network service publishes each result on its MQTT inference topic.
Size and timing
In the ZC702 reference design, the placed mclp_nn uses 1641 LUTs, 758 registers, one RAMB36, one RAMB18 and 10 DSP48E1 slices. Besides the multiply-accumulate, the RTL has wide multiplications in the input stage, the requantizer and the output stage. With the model memories and registers, the engine adds 1964 LUTs, 1266 registers, 7.5 block RAM tiles and 10 DSP48E1 slices to the core.
The whole reference design meets all timing constraints. The worst setup slack is +0.737 ns, and the worst hold slack is +0.021 ns. A parameter, USE_NN, builds the core without the engine.
Limits
One multiply-accumulate per clock is plenty for 43216 operations at 50 MHz. Larger models, or a separate model per load cell on 64 channels, would need several multiply-accumulates in parallel.
The engine supports convolution, dense layers and ReLU. It has no pooling, because the default model doesn't use it.
The activation buffers limit the input and output of each layer to 1024 values.
The model doesn't learn on the device. It is trained offline and loaded as fixed parameters.
Building your own
- Write the integer arithmetic down first: data types, accumulator width, requantization and saturation.
- Write a plain integer reference that reads the same packed memories as the hardware.
- Express every layer as one operation with parameters, and describe the model as data in RAM.
- Turn the loops of the reference into counters, with one multiply-accumulate per clock.
- Pipeline the memory reads, the product, the accumulation and the requantization.
- Test against the reference with your real model, with edge cases and with random models that saturate.
- Load models over the bus, read them back, and identify them with a CRC.
In MCLP, the whole engine is one SystemVerilog file of 380 lines.