Pollo Neuronal: Embedded Neural Inference on Zynq

A 2020 master's research project on dielectric sensing, compact neural regression and ARM/FPGA architecture on PYNQ-Z1.

From a laboratory model to embedded inference

Pollo Neuronal investigated how to estimate chicken meat post-mortem time from dielectric measurements using a neural regressor suitable for an embedded platform. The engineering challenge joined three concerns: preserve useful predictive accuracy, reduce the network’s computational structure, and adapt inference to a heterogeneous ARM/FPGA system.

The work was completed as a 2020 master’s thesis at Universitat Politècnica de València, dated December 2020 in the original document. The official degree is Máster Universitario en Ingeniería de Sistemas Electrónicos. Supervision: Rafael Gadea Gironés, with co-supervisors Ricardo José Colom Palero and Pedro José Fito Suñer.

My thesis contribution covered data analysis, neural-network selection and training, structural reduction, evaluation, and adaptation of the inference approach to PYNQ-Z1. The sensing instrumentation and underlying food-characterization research came from the I3M/IIAD collaboration; they are credited as prior collaborative work. “Pollo Neuronal” is the portfolio project name; the citation preserves the original academic title.

Research problem and approach

Post-mortem biochemical changes affect meat’s electrical properties. The project explored a supervised mapping from measured dielectric features to elapsed post-mortem time, used as a maturation-related variable under the studied conditions.

The objectives were to replace a more elaborate predictive processing stage with neural inference, select and train a regression topology, reduce its size, evaluate its error, and adapt the model to an embedded platform. The development followed three stages:

  1. Understand the measurements. Inspect missing values, feature scales and correlations; study raw spectral features and a derived-feature representation.
  2. Select an efficient model. Compare optimizers, train dense regressors, then remove neurons/layers and retrain to examine the size–error tradeoff.
  3. Adapt inference. Separate workstation training from embedded execution and export the learned model parameters for a Python/NumPy inference approach on PYNQ-Z1.
Original project-stage figure from the thesis
Original 2020 thesis figure with three stages: investigate the existing system and measurements, develop and optimize neural networks, then adapt inference to an embedded platform.
Original standalone figure from thesis chapter 3, reproduced at the author's request. Spanish labels are retained: stage 1 reviews the existing system and data; stage 2 develops, trains and optimizes the neural model; stage 3 adapts inference to the embedded target. The original PDF remains private.

Acquisition instrument architecture

The original diagram makes the signal boundary explicit. A generator excites the existing sensor through conditioning circuitry; measurement electrodes feed a second conditioning path, followed by signal processing, communication and data analysis. The neural-regression work studies the analysis of the resulting measurements.

Original acquisition-device diagram from the 2020 thesis: an injection electrode and two measurement electrodes connect to C1/C2 conditioning circuits and G1 excitation generation, then PS1 signal processing, TX1 communication and UAD data analysis.
Original diagram from thesis chapter 2, reproduced at the author's request with its Spanish labels preserved. It describes the prior I3M/IIAD sensing system. The source PDF and its metadata are not distributed.
Original label Engineering role
C1 / C2 Injection-path and measurement-path signal conditioning.
G1 Electrical excitation-signal generator.
PS1 Instrument signal-processing block.
TX1 Communication unit.
UAD Data-analysis unit.

PS1 in this instrument diagram denotes signal processing. The Zynq PS discussed below denotes the ARM processing system. The source figure does not specify a Zynq/FPGA implementation of those instrument blocks. This separation matters when defining the interface between acquisition, preprocessing and a proposed neural accelerator: feature layout, calibration state and transfer framing must be established before timing the complete chain.

Documented workflow: existing dielectric acquisition supplies features; workstation training and structural reduction produce weights for software inference on the ARM processing system of PYNQ-Z1.
Reconstructed high-level architecture from thesis chapters 2–4. The sensing system is prior collaborative work. The documented deployment path uses the ARM side of Zynq; custom FPGA acceleration remained future work.

Mathematical and computational foundations

The sensing background uses complex impedance and permittivity:

Z(f)=R(f)+jX(f),ε∗(f)=ε′(f)−jε′′(f).Z(f)=R(f)+jX(f), \qquad \varepsilon^*(f)=\varepsilon'(f)-j\varepsilon''(f).

These quantities motivate the input features; the public overview omits detailed electrode geometry, calibration parameters and the original measurement records. With a normalized feature vector x\mathbf{x}, the dense hidden layers apply

a(ℓ)=ReLU⁡ ⁣(W(ℓ)a(ℓ−1)+b(ℓ)),a(0)=x.\mathbf{a}^{(\ell)}=\operatorname{ReLU}\!\left(W^{(\ell)}\mathbf{a}^{(\ell-1)}+\mathbf{b}^{(\ell)}\right), \qquad \mathbf{a}^{(0)}=\mathbf{x}.

A scalar linear readout predicts post-mortem time, following the Keras listing. The documented sklearn.preprocessing.normalize path normalizes each sample vector; it must be distinguished from feature-wise standardization. Training and evaluation use squared-error loss, MAE and MSE:

MAE⁡=1n∑i=1n∣yi−y^i∣,MSE⁡=1n∑i=1n(yi−y^i)2.\operatorname{MAE}=\frac{1}{n}\sum_{i=1}^{n}|y_i-\hat y_i|, \qquad \operatorname{MSE}=\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat y_i)^2.

Because the target is expressed in hours, MAE is in hours and MSE in hours squared. These equations restate standard mathematical foundations with consistent notation.

Zynq architecture and embedded implementation

The inference target was PYNQ-Z1, based on Zynq XC7Z020. Its processing system (PS) contains dual Cortex-A9 ARM cores; its programmable logic (PL) provides an FPGA fabric. The board has 512 MB DDR3 and 220 DSP slices. Those are platform capacities, not resource-utilization results for this project. The Digilent reference manual, §§1–2, describes the PS/PL split.

The thesis documents Ubuntu, Python/Jupyter, TensorFlow/Keras, NumPy and scikit-learn. Its training workstation is identified as an Intel Core i7-7820HK system with an NVIDIA GeForce GTX 1070. Notebook snapshots identify TensorFlow 2.2.0.

The embedded work examined how to move a trained network beyond its training framework. Following deployment difficulties recorded at the time, the described approach exports weights and expresses forward propagation with NumPy on the ARM/Linux environment. The archived inference listing is incomplete, so this page does not present it as a reproducible board implementation.

FPGA acceleration: partitioning, memory and dataflow

Retrospective architecture proposal. The following design discussion develops the FPGA acceleration direction identified as future work in the thesis. It is an engineering extension for this portfolio, not a synthesized or measured 2020 accelerator.

The natural partition leaves measurement orchestration, preprocessing and control on the ARM PS, while a custom PL engine performs dense matrix–vector products and hidden-layer activations. A reusable MAC datapath can trade parallelism against DSP usage. Weights and intermediate activations should remain in on-chip buffers where capacity permits; DDR transfers and buffer ownership are part of the design, rather than incidental overhead.

Proposed accelerator: ARM controls DMA and preprocessing; DDR exchanges feature and output buffers through AXI DMA with programmable logic containing weight BRAM, MAC/reduction compute and activation buffers. Dashed boundaries mark the unimplemented extension.
Conceptual PS/PL acceleration partition. The proposed DMA, BRAM and MAC blocks are not a reconstruction of an implemented bitstream. The generic transfer pattern follows the public PYNQ DMA documentation.
Analytical cost model and accelerator design decisions

Let DD be the number of input features and d1,…,dLd_1,\ldots,d_L the dense layer widths, including the output. A dense forward pass has

NMAC=∑ℓ=1Ldℓ−1dℓ,Nparam=∑ℓ=1L(dℓ−1+1)dℓ,d0=D.N_{\mathrm{MAC}}=\sum_{\ell=1}^{L}d_{\ell-1}d_\ell, \qquad N_{\mathrm{param}}=\sum_{\ell=1}^{L}(d_{\ell-1}+1)d_\ell, \qquad d_0=D.

For the documented 128–64–32–16–1 baseline this gives 128D+10,768128D+10{,}768 MACs and 128D+11,009128D+11{,}009 parameters. For the compact 8–8–1 network it gives 8D+728D+72 MACs and 8D+898D+89 parameters. These are analytical counts with biases, not benchmark results. Keeping DD explicit avoids conflating raw and derived-feature inputs. The reduction in neuron count alone is not a measured latency or memory reduction.

As a consistency check, the raw-input appendix’s 8–8–1 network uses D=2706D=2706 and reports 21,737 parameters. The analytical model gives 21,720 MACs per inference and 86,948 bytes if all weights and biases were stored as FP32. Actual BRAM allocation would also depend on banking, buffering, alignment and the accelerator architecture. This appendix run has different training settings and scores from the final results table below.

An accelerator evaluation would need to establish:

  • Parallelism and reuse. Select the MAC lane count, pipeline initiation interval and BRAM banking; amortize weight reads without assuming all 220 DSP slices map one-to-one to useful arithmetic lanes.
  • Numerical representation. Compare a floating-point reference with candidate fixed-point formats, accumulation widths, saturation and rounding. No quantized accuracy is established by the thesis.
  • Transport and ownership. Define contiguous buffers, cache maintenance, AXI stream framing and DMA completion before consuming output. Overlap requires separate buffers and explicit ownership.
  • Complete-system latency. Measure preprocessing, transfers, compute and synchronization, then compare against the ARM software baseline using the same inputs and numerical tolerance.

A useful non-overlapped accounting is

Tend-to-end=Tpre+Ttransfer in+Tcompute+Ttransfer out+Tsync.T_{\mathrm{end\text{-}to\text{-}end}}=T_{\mathrm{pre}}+T_{\mathrm{transfer\ in}}+T_{\mathrm{compute}}+T_{\mathrm{transfer\ out}}+T_{\mathrm{sync}}.

This breakdown explains why a smaller network or a faster MAC array does not, by itself, prove an application speedup. Hardware validation would report achieved clock frequency and initiation interval, LUT/DSP utilization, power and complete-system speedup alongside numerical correctness.

Quantization as a hardware design decision

Engineering extension to the FPGA proposal. Quantization chooses the numerical contract of the datapath: representation, scale, rounding, accumulator width and overflow behavior. The archive establishes no quantized-network accuracy or synthesized accelerator. The following calculations and interactive examples are analytical illustrations.

For the appendix’s 2706–8–8–1 network, there are 21,720 weights and 17 biases. The parameter payload alone changes as follows:

Analytical storage for 21,720 weights and 17 biases. Reduced formats retain 32-bit stored biases. Scales, zero-points, buffers, alignment and BRAM banking are excluded.
Weight storageBias storageParameter payload (bytes)
FP32FP3286948
16-bit fixed pointINT3243508
INT8INT3221788

The INT8 candidate reduces this payload from 86,948 to 21,788 bytes, about 3.99× while retaining 32-bit stored biases. Actual BRAM savings depend on port widths, banking, packing and replication. Accumulator precision is a separate decision from parameter storage.

Scaling, accumulator bounds, DSP mapping and a numerical laboratory

Representation and scale alignment

An affine integer representation uses a positive scale ss and integer zero-point zz:

q=clip⁡qmin⁡,qmax⁡ ⁣(round⁡(x/s)+z),x^=s(q−z).q=\operatorname{clip}_{q_{\min},q_{\max}}\!\left(\operatorname{round}(x/s)+z\right),\qquad \hat{x}=s(q-z).

For dense output ii, input scale sxs_x and per-output weight scale sw,is_{w,i} give the accumulator scale sxsw,is_xs_{w,i}. The bias must use that same scale:

qb,i=round⁡ ⁣(bisxsw,i),ai=∑j=1n(qx,j−zx)(qw,ij−zw,i)+qb,i.q_{b,i}=\operatorname{round}\!\left(\frac{b_i}{s_xs_{w,i}}\right),\qquad a_i=\sum_{j=1}^{n}(q_{x,j}-z_x)(q_{w,ij}-z_{w,i})+q_{b,i}.

Requantization to output scale sys_y uses an integer multiplier and shift approximating the scale ratio:

qy,i=clip⁡ ⁣(round⁡ ⁣(Miai2ri)+zy),Mi2ri≈sxsw,isy.q_{y,i}=\operatorname{clip}\!\left(\operatorname{round}\!\left(\frac{M_i a_i}{2^{r_i}}\right)+z_y\right),\qquad \frac{M_i}{2^{r_i}}\approx\frac{s_xs_{w,i}}{s_y}.

The multiplier product also needs a sufficiently wide intermediate. Hidden ReLU and the final linear readout must preserve their distinct semantics. The affine integer framework follows Jacob et al.; per-output weight scales are an architectural choice for this proposal.

Binary fixed point is a particular representation with step Δ=2−F\Delta=2^{-F}. In ap_fixed<16,6,AP_RND_CONV,AP_SAT>, the six integer bits include the sign, leaving ten fractional bits: range [−32, 31.9990234375], step 0.0009765625. The named modes select convergent rounding and saturation. Intermediate products and sums still require explicit width planning; final saturation cannot repair an earlier overflow. See Vivado HLS UG902, arbitrary-precision fixed-point types.

Accumulator growth and DSP48E1 mapping

Let $$A_x=\max q_x-z_x andandA_w=\max q_w-z_w $$. A sufficient signed-accumulator condition is
nAxAw+∣qb∣≤2Bacc−1−1.nA_xA_w+|q_b|\le 2^{B_{\mathrm{acc}}-1}-1.

For symmetric signed INT8 operands with zero-points equal to zero, n=2706n=2706 and no bias, the magnitude bound is 44,335,104. A convenient conservative product-sum budget is

Bacc=bx+bw+⌈log⁡2n⌉=8+8+12=28.B_{\mathrm{acc}}=b_x+b_w+\lceil\log_2 n\rceil=8+8+12=28.

INT32 is a candidate with headroom relative to that conservative budget; actual bias ranges and requantization intermediates still need checking. Changing both operands to 16 bits raises the same budget to 44 bits. An 8-bit output does not imply that its dot product should accumulate in eight bits.

Zynq-7020’s DSP48E1 contains a 25×18 signed multiplier and a 48-bit arithmetic path. Its SIMD modes concern the add/subtract/accumulate unit; they do not provide several independent INT8 multipliers automatically. Operand widths, pipelining, DSP binding and memory ports must be verified in synthesis and implementation reports. AMD/Xilinx UG479, chapters 1–2.

Proposed symmetric INT8 datapath: zero-centered signed operands enter an 8-by-8 multiplier, feed a wider accumulator with aligned bias, and are requantized with a multiplier and shift, rounding and saturation; hidden activations and the linear output remain distinct.
Engineering illustration for the symmetric zero-point-zero candidate. General affine zero-points can change correction arithmetic and operand-width requirements. This diagram is separate from the original acquisition instrument.

Explore a fixed-point format

Synthetic scalar illustration with rounding to nearest, ties to even, and saturation. It does not run the trained network or measure FPGA performance.

The calculator requires JavaScript. The equations and worked numerical example remain available in the technical discussion.

Worked MAC example and validation plan

Use synthetic vectors x=(0.5,−0.25,0.125)x=(0.5,-0.25,0.125), w=(0.25,0.5,−0.25)w=(0.25,0.5,-0.25) and bias b=0.0625b=0.0625, with sx=sw=2−7s_x=s_w=2^{-7} and zero-points zero. They give integer vectors (64, −32, 16) and (32, 64, −32); the aligned bias is 1024. The accumulator is 512, reconstructing 0.03125. With sy=2−7s_y=2^{-7}, output code 4 reconstructs the same value. Exact agreement in this deliberately representable example is not an accuracy result for the thesis network.

A hardware evaluation should freeze the floating-point reference and preprocessing, calibrate ranges on a separate calibration subset, and reserve held-out evaluation data. Compare per-layer saturation counts, numerical error and the task change ΔMAE⁡=MAE⁡q−MAE⁡float\Delta\operatorname{MAE}=\operatorname{MAE}_{q}-\operatorname{MAE}_{\mathrm{float}}. Quantization-aware training is a follow-on option if post-training quantization exceeds the defined error budget. C simulation, RTL co-simulation and board results should then agree on bit patterns, rounding, saturation and stream framing before throughput or energy claims are made.

Reference implementation: a quantized neural accelerator

RTL simulation and C++ verification. This separate implementation turns the architectural discussion into a concrete dense-layer engine: signed INT8 inputs and weights, INT32 biases, a 48-bit accumulator, configurable requantization and an AXI4-Lite control interface. It extends the portfolio study; it is not an archived 2020 bitstream. All verification uses synthetic parameters.

The module boundary is a dense layer rather than a framework runtime. A small sequential datapath makes signed arithmetic, memory latency, register semantics and software ownership inspectable before adding parallel MAC lanes. The code below is the tested implementation, not pseudocode.

Zynq: selecting the interface before the datapath

Zynq is a heterogeneous system with an ARM processing system and programmable logic. The reference connects PS M_AXI_GP0 through an AXI interconnect to the PL register peripheral. Zynq’s PS-facing interface is AXI3; the integration must provide the AXI4-Lite adaptation. The port directions and PS–PL interfaces are defined in UG585.

Zynq integration of the reference: Cortex-A9 runs C++ control; M_AXI_GP0 reaches an AXI interconnect and the AXI4-Lite wrapper, dense engine, local memories and requantizer. One fabric clock and synchronized reset serve the design. A separate dashed DDR, HP port and DMA path is a proposed extension.
The solid path corresponds to the register-based RTL reference. DMA and streaming are a separate scale-out option; the drawing is an integration plan, not a Vivado block-design export.
System decision Reference integration
ARM responsibility Prepare quantized inputs and aligned biases, load parameters, start a layer and validate outputs against the C++ integer reference.
PL responsibility Read local operands, perform dense dot products, apply the selected activation and expose results, cycle count and clipping count.
Clock/reset Use one PL clock domain. Connect FCLK_CLK0 and a processor-system-reset circuit with synchronized reset release. No unsynchronized clock-domain crossing is hidden inside the RTL.
Addressing Allocate a peripheral window in Vivado Address Editor. The wrapper decodes eight address bits; the BSP base address must come from the exported hardware description. No fixed address is assumed by the driver.
Memory ownership Software owns the loading phase; START transfers ownership to the engine. Configuration writes are rejected while busy. All operands must be loaded after reset. DONE releases the results.

For larger transfers, S_AXI_HP provides a PL-master path toward PS memory. S_AXI_ACP offers an optional cache-coherent path with its own integration requirements; ordinary HP traffic is not made coherent simply by using an AXI interface. These are different system choices. PS–PL interface table, ACP description.

This reference moves each operand through registers and does not access DDR from PL. A DMA variant would add AXI4-Stream framing, TLAST, receive-buffer sizing and explicit buffer ownership. Linux DMA mappings/cache synchronization belong to a kernel driver or the platform’s supported buffer API; a bare-metal cache-maintenance call is not a Linux userspace strategy. Compare register-transfer overhead before investing in that extension.

Numerical contract and microarchitecture

The implementation selects symmetric zero-points equal to zero and a power-of-two scale ratio:

ao=qb,o+∑i=0Nin−1qx,iqw,oi,qy,o=sat⁡[−128,127] ⁣(RNE⁡(ao/2r)),0≤r≤31.a_o=q_{b,o}+\sum_{i=0}^{N_{\mathrm{in}}-1}q_{x,i}q_{w,oi},\qquad q_{y,o}=\operatorname{sat}_{[-128,127]}\!\left(\operatorname{RNE}(a_o/2^r)\right),\quad 0\le r\le31.

Here sxsw/sy=2−rs_xs_w/s_y=2^{-r}. RNE rounds to the nearest integer, choosing an even integer at a tie. ReLU, when enabled, clamps negative rounded values before INT8 saturation. The general multiplier/per-output-scale formulation above is broader; this baseline uses one common shift per layer and no arbitrary requantization multiplier.

  • Widths. Multiplication produces a signed 16-bit value that is explicitly sign-extended into the 48-bit sum. Biases are sign-extended from 32 bits. With the supported shape limits, this avoids intermediate accumulator overflow even for extreme INT8 operands and INT32 biases.
  • Memory. Weights are output-major: W[o * N_IN + i]. Inputs, weights and biases have distinct local arrays. The FSM allocates an explicit synchronous read cycle; it does not assume a combinational BRAM read. Memory mapping to BRAM, distributed RAM or registers remains a synthesis decision to inspect.
  • Schedule. For each output: read bias, initialize the accumulator, alternate operand reads and MAC updates, then store the requantized result. The explicit states are BIAS_READ → INIT → (READ → MAC) × N_IN → STORE.
  • Activation and observability. A layer can use ReLU or signed linear output. CLIPS counts numerical output saturation after activation; it does not count ReLU clamps. CYCLES counts compute cycles, excluding CPU transfers and polling.

The implemented schedule gives an exact RTL compute count:

Clayer=Nout(2Nin+3).C_{\mathrm{layer}}=N_{\mathrm{out}}(2N_{\mathrm{in}}+3).

The synthetic 3 × 2 layer takes 18 cycles, verified in simulation. The same schedule gives 43,320 cycles for a 2706 × 8 layer. These are cycle counts, not measured latency or a speedup. A timing-constrained implementation must establish its achievable clock and memory/DSP mapping first.

Dimensions are fixed at elaboration: 1 ≤ N_IN ≤ 65535, 1 ≤ N_OUT ≤ 256; defaults are 8 × 8. The worked example elaborates 3 × 2. A complete 2706–8–8–1 regressor would need layer sequencing and activation buffers, with matching scales between layers. This reference verifies the layer primitive and does not import the thesis’s trained network.

Register map and AXI behavior

The wrapper accepts write addresses and data independently, then commits a paired transaction once. It holds read data and response status stable until the corresponding handshake. This is tested with skewed channels and response stalls. AXI4-Lite has separate address, data and response channels and single-beat transfers. Vivado AXI Reference Guide UG1037.

Offset Register Contract
0x00 ID Read-only 0x504E5131 (PNQ1).
0x04 CONTROL Write 1 to start, 2 to acknowledge completion. 3 is invalid. A new start clears stale DONE.
0x08 STATUS Bit 0: busy; bit 1: sticky done.
0x0C SHAPE Input count in bits 15:0; output count in bits 31:16.
0x10 CONFIG Right shift in bits 4:0; ReLU in bit 8; other bits reserved zero.
0x14 INDEX Shared index used by subsequent input, weight, bias or output accesses.
0x18 / 0x1C XDATA / WDATA Write signed INT8 in the low byte. Only byte strobe 0 updates the operand.
0x20 BDATA Write a full INT32 bias; partial nonzero byte masks are rejected.
0x24 YDATA Read the indexed result, sign-extended to 32 bits, after completion.
0x28 / 0x2C CYCLES / CLIPS Read compute-cycle and clipped-output counts.

Misaligned/unknown addresses, invalid operand indices and active configuration writes return SLVERR. A zero write-strobe mask is a no-op. The shared index requires serialized software access. Memories are not cleared by reset; the caller must reload every input, weight and bias before starting. There is no initialization-completeness bitmap, DMA engine or interrupt controller in this baseline.

Verilog modules and C++ control

These listings are generated from the same files used in the local RTL and C++ tests. Each module can be expanded and copied. The inputs and weights are synthetic; the original thesis implementation and trained parameters remain private.

Registered signed multiplier–accumulator · INT8 to 48-bitpn_mac_int8.v
// Portfolio reference, separate from the historical 2020 implementation.
// Signed INT8 operands; bias and partial sum share the accumulator scale.
module pn_mac_int8 (
    input wire clk,
    input wire resetn,
    input wire load_bias,
    input wire enable,
    input wire signed [31:0] bias,
    input wire signed [7:0] x,
    input wire signed [7:0] w,
    output reg signed [47:0] accumulator
);
    wire signed [15:0] product = x * w;
    wire signed [47:0] extended_product = {{32{product[15]}}, product};

    always @(posedge clk) begin
        if (!resetn)
            accumulator <= 48'sd0;
        else if (load_bias)
            accumulator <= {{16{bias[31]}}, bias};
        else if (enable)
            accumulator <= accumulator + extended_product;
    end
endmodule
Requantization · nearest rounding, ties to even, saturation and ReLUpn_requantize.v
// Symmetric zero point = 0; sx * sw / sy = 2^(-shift), shift in [0,31].
// Magnitude arithmetic defines negative ties explicitly and handles -2^47.
module pn_requantize (
    input wire signed [47:0] accumulator,
    input wire [4:0] shift,
    input wire relu,
    output reg signed [7:0] value,
    output reg clipped
);
    reg [48:0] magnitude, quotient, remainder, half;
    reg signed [49:0] rounded;

    always @* begin
        magnitude = accumulator[47] ? {1'b0, (~accumulator + 48'd1)}
                                    : {1'b0, accumulator};
        quotient = magnitude >> shift;
        remainder = magnitude - (quotient << shift);
        half = 49'd0;
        if (shift != 0) begin
            half = 49'd1 << (shift - 1'b1);
            if ((remainder > half) ||
                ((remainder == half) && quotient[0]))
                quotient = quotient + 1'b1; // nearest, ties to even
        end
        rounded = $signed({1'b0, quotient});
        if (accumulator[47]) rounded = -rounded;
        // ReLU is an activation; it is not counted as numerical clipping.
        if (relu && (rounded < 0)) rounded = 50'sd0;
        clipped = 1'b0;
        if (rounded > 127) begin value = 8'sd127; clipped = 1'b1; end
        else if (rounded < -128) begin value = -8'sd128; clipped = 1'b1; end
        else value = rounded[7:0];
    end
endmodule
Dense-layer engine · synchronous reads and sequential controlpn_dense_int8.v
// One serial MAC, output-major weights W[o * N_IN + i].
// Contract: load every input, weight and bias after reset before START.
// Memories have no reset loop. Host configuration is blocked while busy.
module pn_dense_int8 #(
    parameter integer N_IN = 8,
    parameter integer N_OUT = 8
) (
    input wire clk, resetn, start,
    input wire [4:0] shift,
    input wire relu,
    input wire cfg_we,
    input wire [1:0] cfg_target, // 0: input, 1: weight, 2: bias
    input wire [31:0] cfg_index, cfg_data,
    input wire [31:0] output_index,
    output wire signed [7:0] output_data,
    output reg busy, done,
    output reg [31:0] cycles, clip_count
);
    localparam IDLE=0, BIAS_READ=1, INIT=2, READ=3, MAC=4, STORE=5;
    reg [2:0] state;
    reg signed [7:0] inputs [0:N_IN-1];
    reg signed [7:0] weights [0:N_IN*N_OUT-1];
    reg signed [31:0] biases [0:N_OUT-1];
    reg signed [7:0] outputs [0:N_OUT-1];
    reg signed [7:0] x_q, w_q;
    reg signed [31:0] bias_q;
    reg [31:0] i, o;
    reg [4:0] shift_q;
    reg relu_q;
    wire signed [47:0] accumulator;
    wire signed [7:0] quantized;
    wire clipped;
    assign output_data = output_index < N_OUT ? outputs[output_index] : 8'sd0;

    pn_mac_int8 mac(clk, resetn, state == INIT, state == MAC,
                    bias_q, x_q, w_q, accumulator);
    pn_requantize quant(accumulator, shift_q, relu_q, quantized, clipped);

    always @(posedge clk) begin
        if (resetn && cfg_we && !busy) begin
            case (cfg_target)
                0: if (cfg_index < N_IN) inputs[cfg_index] <= cfg_data[7:0];
                1: if (cfg_index < N_IN*N_OUT) weights[cfg_index] <= cfg_data[7:0];
                2: if (cfg_index < N_OUT) biases[cfg_index] <= cfg_data;
            endcase
        end
    end

    always @(posedge clk) begin
        if (!resetn) begin
            state <= IDLE; busy <= 0; done <= 0;
            cycles <= 0; clip_count <= 0; i <= 0; o <= 0;
            shift_q <= 0; relu_q <= 0; x_q <= 0; w_q <= 0; bias_q <= 0;
        end else begin
            done <= 0;
            if (busy) cycles <= cycles + 1'b1;
            case (state)
                IDLE: if (start) begin
                    busy <= 1; cycles <= 0; clip_count <= 0;
                    shift_q <= shift; relu_q <= relu; i <= 0; o <= 0;
                    state <= BIAS_READ;
                end
                BIAS_READ: begin bias_q <= biases[o]; state <= INIT; end
                INIT: state <= READ;
                READ: begin
                    // Explicit read cycle: no assumption of asynchronous BRAM.
                    x_q <= inputs[i]; w_q <= weights[o*N_IN+i];
                    state <= MAC;
                end
                MAC: if (i == N_IN-1) state <= STORE;
                     else begin i <= i + 1'b1; state <= READ; end
                STORE: begin
                    outputs[o] <= quantized;
                    if (clipped) clip_count <= clip_count + 1'b1;
                    if (o == N_OUT-1) begin busy <= 0; done <= 1; state <= IDLE; end
                    else begin o <= o + 1'b1; i <= 0; state <= BIAS_READ; end
                end
                default: begin state <= IDLE; busy <= 0; end
            endcase
        end
    end
endmodule
AXI4-Lite wrapper · independent channels and stable responsespn_axi_lite.v
// 32-bit AXI4-Lite register interface, one outstanding response per direction.
// AW and W are captured independently. Responses remain stable under stalls.
// N_IN: 1..65535, N_OUT: 1..256 (fixed at elaboration, reported in SHAPE).
module pn_axi_lite #(
    parameter integer N_IN = 8,
    parameter integer N_OUT = 8
) (
    input wire aclk, aresetn,
    input wire [7:0] s_axi_awaddr,
    input wire s_axi_awvalid, output wire s_axi_awready,
    input wire [31:0] s_axi_wdata, input wire [3:0] s_axi_wstrb,
    input wire s_axi_wvalid, output wire s_axi_wready,
    output reg [1:0] s_axi_bresp, output reg s_axi_bvalid,
    input wire s_axi_bready,
    input wire [7:0] s_axi_araddr,
    input wire s_axi_arvalid, output wire s_axi_arready,
    output reg [31:0] s_axi_rdata, output reg [1:0] s_axi_rresp,
    output reg s_axi_rvalid, input wire s_axi_rready
);
    localparam ID=8'h00, CONTROL=8'h04, STATUS=8'h08, SHAPE=8'h0c,
               CONFIG=8'h10, INDEX=8'h14, XDATA=8'h18, WDATA=8'h1c,
               BDATA=8'h20, YDATA=8'h24, CYCLES=8'h28, CLIPS=8'h2c;
    reg aw_full, w_full;
    reg [7:0] awaddr;
    reg [31:0] wdata;
    reg [3:0] wstrb;
    reg [31:0] config_reg, index_reg;
    reg core_start, cfg_we, done_sticky;
    reg [1:0] cfg_target;
    reg [31:0] cfg_index, cfg_data;
    wire core_busy, core_done;
    wire busy = core_busy | core_start;
    wire signed [7:0] y;
    wire [31:0] cycles, clips;
    wire [31:0] byte_mask = {{8{wstrb[3]}}, {8{wstrb[2]}},
                                   {8{wstrb[1]}}, {8{wstrb[0]}}};
    wire [31:0] merged_config = (config_reg & ~byte_mask) | (wdata & byte_mask);
    assign s_axi_awready = aresetn && !aw_full && !s_axi_bvalid;
    assign s_axi_wready = aresetn && !w_full && !s_axi_bvalid;
    assign s_axi_arready = aresetn && !s_axi_rvalid;

    pn_dense_int8 #(.N_IN(N_IN), .N_OUT(N_OUT)) core (
        .clk(aclk), .resetn(aresetn), .start(core_start),
        .shift(config_reg[4:0]), .relu(config_reg[8]),
        .cfg_we(cfg_we), .cfg_target(cfg_target),
        .cfg_index(cfg_index), .cfg_data(cfg_data),
        .output_index(index_reg), .output_data(y),
        .busy(core_busy), .done(core_done), .cycles(cycles), .clip_count(clips)
    );

    always @(posedge aclk) begin
        if (!aresetn) begin
            aw_full <= 0; w_full <= 0; awaddr <= 0; wdata <= 0; wstrb <= 0;
            s_axi_bvalid <= 0; s_axi_bresp <= 0;
            s_axi_rvalid <= 0; s_axi_rresp <= 0; s_axi_rdata <= 0;
            config_reg <= 0; index_reg <= 0; core_start <= 0; cfg_we <= 0;
            cfg_target <= 0; cfg_index <= 0; cfg_data <= 0; done_sticky <= 0;
        end else begin
            core_start <= 0; cfg_we <= 0;
            if (core_done) done_sticky <= 1;
            if (s_axi_awvalid && s_axi_awready) begin aw_full <= 1; awaddr <= s_axi_awaddr; end
            if (s_axi_wvalid && s_axi_wready) begin w_full <= 1; wdata <= s_axi_wdata; wstrb <= s_axi_wstrb; end
            if (s_axi_bvalid && s_axi_bready) s_axi_bvalid <= 0;
            if (aw_full && w_full && !s_axi_bvalid) begin
                aw_full <= 0; w_full <= 0; s_axi_bvalid <= 1; s_axi_bresp <= 0;
                if (awaddr[1:0] != 0) s_axi_bresp <= 2'b10;
                else if (wstrb == 0) begin end // AXI write with no enabled bytes
                else if (busy) s_axi_bresp <= 2'b10;
                else case (awaddr)
                    CONTROL: if (wstrb[0]) begin
                        if ((wdata & 32'hfffffffc) != 0 || wdata[1:0] == 3)
                            s_axi_bresp <= 2'b10;
                        else if (wdata[0]) begin core_start <= 1; done_sticky <= 0; end
                        else if (wdata[1]) done_sticky <= 0;
                    end
                    CONFIG: if ((merged_config & 32'hfffffee0) != 0) s_axi_bresp <= 2'b10;
                            else config_reg <= merged_config;
                    INDEX: index_reg <= (index_reg & ~byte_mask) | (wdata & byte_mask);
                    XDATA, WDATA, BDATA: begin
                        cfg_index <= index_reg; cfg_data <= wdata;
                        if (awaddr == XDATA && index_reg < N_IN) begin
                            cfg_target <= 0; cfg_we <= wstrb[0];
                        end else if (awaddr == WDATA && index_reg < N_IN*N_OUT) begin
                            cfg_target <= 1; cfg_we <= wstrb[0];
                        end else if (awaddr == BDATA && index_reg < N_OUT && wstrb == 4'hf) begin
                            cfg_target <= 2; cfg_we <= 1;
                        end else s_axi_bresp <= 2'b10;
                    end
                    default: s_axi_bresp <= 2'b10;
                endcase
            end
            if (s_axi_rvalid && s_axi_rready) s_axi_rvalid <= 0;
            if (s_axi_arvalid && s_axi_arready) begin
                s_axi_rvalid <= 1; s_axi_rresp <= 0; s_axi_rdata <= 0;
                if (s_axi_araddr[1:0] != 0) s_axi_rresp <= 2'b10;
                else case (s_axi_araddr)
                    ID: s_axi_rdata <= 32'h504e5131;
                    CONTROL: s_axi_rdata <= 0;
                    STATUS: s_axi_rdata <= {30'd0, done_sticky, busy};
                    SHAPE: s_axi_rdata <= (N_OUT << 16) | N_IN;
                    CONFIG: s_axi_rdata <= config_reg;
                    INDEX: s_axi_rdata <= index_reg;
                    YDATA: if (!busy && done_sticky && index_reg < N_OUT)
                               s_axi_rdata <= {{24{y[7]}}, y};
                           else s_axi_rresp <= 2'b10;
                    CYCLES: s_axi_rdata <= cycles;
                    CLIPS: s_axi_rdata <= clips;
                    default: s_axi_rresp <= 2'b10;
                endcase
            end
        end
    end
endmodule
C++17 integer reference · the numerical contractpn_quant.hpp
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <vector>

namespace pn {
// Independent software oracle: division/remainder, no signed right shift.
inline std::int8_t requantize(std::int64_t accumulator, unsigned shift,
                              bool relu, bool* clipped = nullptr) {
    if (shift > 31 || accumulator < -(INT64_C(1) << 47) ||
        accumulator > (INT64_C(1) << 47) - 1)
        throw std::invalid_argument("requantization domain");
    const auto divisor = INT64_C(1) << shift;
    auto rounded = accumulator / divisor; // C++ truncates toward zero
    const auto remainder = accumulator % divisor;
    const auto magnitude = remainder < 0 ? -remainder : remainder;
    if (magnitude * 2 > divisor ||
        (magnitude * 2 == divisor && rounded % 2 != 0))
        rounded += accumulator < 0 ? -1 : 1;
    if (relu && rounded < 0) rounded = 0;
    if (clipped) *clipped = rounded < -128 || rounded > 127;
    return static_cast<std::int8_t>(std::clamp<std::int64_t>(rounded, -128, 127));
}

inline std::vector<std::int8_t> dense_reference(
    const std::vector<std::int8_t>& x,
    const std::vector<std::int8_t>& weights,
    const std::vector<std::int32_t>& bias, unsigned shift, bool relu) {
    if (x.empty() || x.size() > 65535 || bias.empty() || bias.size() > 256 ||
        weights.size() != x.size() * bias.size() || shift > 31)
        throw std::invalid_argument("dense shape or scale");
    std::vector<std::int8_t> output(bias.size());
    for (std::size_t o = 0; o < bias.size(); ++o) {
        std::int64_t accumulator = bias[o];
        for (std::size_t i = 0; i < x.size(); ++i)
            accumulator += static_cast<std::int32_t>(x[i]) * weights[o*x.size()+i];
        output[o] = requantize(accumulator, shift, relu);
    }
    return output;
}
} // namespace pn
C++17 driver · shape checks, loading and bounded pollingpn_driver.hpp
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>

namespace pn {
enum Register : std::uint32_t {
    ID=0x00, CONTROL=0x04, STATUS=0x08, SHAPE=0x0c, CONFIG=0x10,
    INDEX=0x14, XDATA=0x18, WDATA=0x1c, BDATA=0x20,
    YDATA=0x24, CYCLES=0x28, CLIPS=0x2c
};
enum class Result { ok, incompatible_ip, invalid_argument, busy, timeout, verification_failed };

// Io supplies read32(offset) and write32(offset,value), ordered Device accesses.
// Single caller: serialize access to the shared INDEX register externally.
template<class Io> class DenseDriver {
    Io& io;
public:
    explicit DenseDriver(Io& registers) : io(registers) {}
    Result run(const std::vector<std::int8_t>& x,
               const std::vector<std::int8_t>& weights,
               const std::vector<std::int32_t>& biases,
               unsigned shift, bool relu, std::uint32_t max_polls,
               std::vector<std::int8_t>& output) {
        if (io.read32(ID) != 0x504e5131u) return Result::incompatible_ip;
        const auto shape = io.read32(SHAPE);
        const std::size_t inputs = shape & 0xffffu, outputs = shape >> 16;
        if (inputs == 0 || outputs == 0 || outputs > 256 || shift > 31 ||
            max_polls == 0 || x.size() != inputs || biases.size() != outputs ||
            weights.size() != inputs * outputs) return Result::invalid_argument;
        if (io.read32(STATUS) & 1u) return Result::busy;

        io.write32(CONFIG, shift | (relu ? 0x100u : 0u));
        for (std::size_t i = 0; i < inputs; ++i) {
            io.write32(INDEX, static_cast<std::uint32_t>(i));
            io.write32(XDATA, static_cast<std::uint8_t>(x[i]));
        }
        for (std::size_t i = 0; i < weights.size(); ++i) {
            io.write32(INDEX, static_cast<std::uint32_t>(i));
            io.write32(WDATA, static_cast<std::uint8_t>(weights[i]));
        }
        for (std::size_t o = 0; o < outputs; ++o) {
            io.write32(INDEX, static_cast<std::uint32_t>(o));
            io.write32(BDATA, static_cast<std::uint32_t>(biases[o]));
        }
        io.write32(CONTROL, 1u); // START also clears stale DONE
        for (std::uint32_t poll = 0; poll < max_polls; ++poll) {
            const auto status = io.read32(STATUS);
            if ((status & 3u) == 2u) {
                std::vector<std::int8_t> completed(outputs);
                for (std::size_t o = 0; o < outputs; ++o) {
                    io.write32(INDEX, static_cast<std::uint32_t>(o));
                    const auto byte = io.read32(YDATA) & 0xffu;
                    const auto signed_value = byte < 128 ? static_cast<int>(byte)
                                                        : static_cast<int>(byte) - 256;
                    completed[o] = static_cast<std::int8_t>(signed_value);
                }
                output.swap(completed); // publish only a completed inference
                return Result::ok;
            }
        }
        // A poll budget is not a wall-clock deadline. Do not overwrite a busy IP.
        // The caller must recover/reset and reload the IP after a timeout.
        return Result::timeout;
    }
};
} // namespace pn
Zynq standalone BSP adapter · hardware integration boundarypn_xilinx_io.hpp
#pragma once
#include <cstdint>
#include "xil_io.h" // AMD/Xilinx standalone BSP; not a Linux userspace header.

namespace pn {
struct XilinxBspIo {
    UINTPTR base; // Generated hardware address from xparameters.h, never guessed.
    std::uint32_t read32(std::uint32_t offset) const {
        const auto value = Xil_In32(base + offset);
        dmb();
        return value;
    }
    void write32(std::uint32_t offset, std::uint32_t value) const {
        dmb();
        Xil_Out32(base + offset, value);
        dmb();
    }
};
} // namespace pn
Synthetic end-to-end call · expected integer outputs {4, −4}synthetic_demo.cpp
#include "pn_driver.hpp"
#include "pn_quant.hpp"

// This function accepts either a tested register model or a board BSP adapter.
// Hardware shape for this example: N_IN=3, N_OUT=2, symmetric Q1.7 operands.
template<class Io> pn::Result synthetic_demo(Io& io) {
    const std::vector<std::int8_t> x{64, -32, 16};
    const std::vector<std::int8_t> w{32, 64, -32, -32, -64, 32};
    const std::vector<std::int32_t> bias{1024, -1024};
    const auto reference = pn::dense_reference(x, w, bias, 7, false);
    std::vector<std::int8_t> actual;
    pn::DenseDriver<Io> engine(io);
    const auto result = engine.run(x, w, bias, 7, false, 10000, actual);
    if (result != pn::Result::ok) return result;
    // Expected integer outputs: {4,-4}; reconstructed values: {0.03125,-0.03125}.
    return actual == reference ? pn::Result::ok : pn::Result::verification_failed;
}

C++ libraries and the board boundary

pn_quant.hpp implements the numerical reference with standard C++17 containers, fixed-width integers and checked dimensions. pn_driver.hpp is independent of an operating system and accepts an ordered read32/write32 adapter. It checks IP identity and shape, loads the complete layer, clears stale completion through START, polls with a finite budget and publishes output only after completion. A poll budget is not a wall-clock deadline; timeout recovery must reset/reinitialize the peripheral before reuse.

pn_xilinx_io.hpp shows the AMD/Xilinx standalone BSP adapter using xil_io.h, Xil_In32, Xil_Out32 and ARM data-memory barriers. The target must map registers as Device memory and use its generated hardware base address. This adapter has not been compiled with a board BSP or exercised on Zynq; the host tests use a register model. Official BSP I/O API source.

On PYNQ Linux, use the platform MMIO API or an appropriately mapped kernel/UIO interface with correct device attributes and ordering. The standalone BSP header is not a Linux userspace dependency. TensorFlow/Keras belongs to the documented training workflow; this integer PL engine does not execute TensorFlow or require its runtime.

Verification evidence and implementation next steps

The local checks compare 3,514 independent exact-rational rounding vectors against RTL and C++, exercise 84 dense layers over AXI4-Lite, and test 2,706-input accumulation with extreme INT32 biases. They cover positive/negative ties, both saturation limits, ReLU, shifts 0–31, repeated execution, byte masks, invalid accesses, channel skew, response backpressure, busy-write rejection, reset and driver timeout handling. The C++ tests run with AddressSanitizer and UndefinedBehaviorSanitizer. The RTL also compiles as Verilog-2005.

A board implementation still needs IP packaging, clock/reset/address integration, synthesis and place-and-route, timing closure, resource reports and bit-exact board comparison. An ILA capture should check the start/completion sequence and AXI responses before benchmarking. System evaluation should separate parameter loading, inference compute and transfer/synchronization costs, and compare with the ARM reference on identical inputs. No bitstream, Fmax, board throughput, power result or quantized thesis accuracy is claimed here.

Experimental method and selected findings

The thesis studies labeled measurements spanning 5–146 post-mortem hours. Chapter 4 describes an 80/20 train/test split, a further 20% validation fraction within training, up to 5,000 epochs, and RMSprop, Adam and SGD comparisons. Appendix notebooks preserve other configurations and intermediate results; those settings cannot be treated as complete provenance for every final-table entry.

The final topology table reports the following selected results:

Selected results reported in the thesis, Chapter 5. These values were not reproduced for this portfolio. Input features are excluded from the dense-unit count.
ModelDense layer widthsDense unitsMAE (h)MSE (h²)
R1128 → 64 → 32 → 16 → 12411.848.97
R264 → 32 → 16 → 11131.697.1
R78 → 8 → 1172.6215.42
Three selected thesis results: R1 has 241 dense units and MAE 1.84 hours; R2 has 113 units and MAE 1.69 hours; R7 has 17 units and MAE 2.62 hours.
Reconstructed plot of three aggregate rows from the thesis's final topology table. It contains no sample-level data, fitted trend or uncertainty estimate.

The documented contribution is the exploration of a network-size versus predictive-error tradeoff. R2 has the lowest MAE in the reported final table. R7 retains two eight-unit dense layers and a scalar output, while accepting a higher MAE than R1. The result concerns model structure and regression error; it is not evidence of FPGA throughput or energy efficiency.

Selected academic references

  • M. V. Traffano-Schiffo, M. Castro-Giraldez, R. J. Colom and P. J. Fito. Innovative photonic system in radiofrequency and microwave range to determine chicken meat quality. Journal of Food Engineering, 239, 1–7, 2018. DOI: 10.1016/j.jfoodeng.2018.06.029. Prior sensing research, not a paper authored by the thesis student.
  • D. Blalock, J. J. Gonzalez Ortiz, J. Frankle and J. Guttag. What is the State of Neural Network Pruning? MLSys, 2020. Conference record.

Data and Research Materials

Selected technical information and two author-selected original figures are presented for academic and professional reference. The complete thesis, source PDFs, original LaTeX, notebooks, datasets, trained weights and original implementation files are not included. The separate Verilog/C++ reference is shown inline; it and the quantization laboratory use synthetic values. No source archive or access arrangement is offered. No new open-source or Creative Commons license is implied. The original research and third-party materials retain their respective attribution and rights.

Citation and Academic Reference

Cite the original thesis for the academic research. This portfolio page is a selected technical overview, not the original thesis.

APA 7

Ramírez Betancourth, C. (2020). Sistema embebido para la determinación de la maduración de carne basado en un sensor de impedancias y procesado neuronal [Trabajo Fin de Máster, Universitat Politècnica de València].

IEEE

C. Ramírez Betancourth, “Sistema embebido para la determinación de la maduración de carne basado en un sensor de impedancias y procesado neuronal,” Trabajo Fin de Máster, Departamento de Ingeniería Electrónica, Universitat Politècnica de València, Valencia, 2020.

BibTeX

@mastersthesis{ramirez2020polloneuronal,
  author = {Ramírez Betancourth, Cristian},
  title = {Sistema embebido para la determinación de la maduración de carne basado en un sensor de impedancias y procesado neuronal},
  school = {Universitat Politècnica de València},
  year = {2020},
  month = dec,
  type = {Trabajo Fin de Máster},
  note = {Máster Universitario en Ingeniería de Sistemas Electrónicos}
}

The bibliographic record is provided for reference. No full-text thesis link or research download is included.

Back to projects