The Memory Wall on Edge Microcontrollers
Standard neural networks store weights and compute activations using single-precision floating point (32-bit float). On hardware with limited SRAM, storing thousands of 32-bit parameters causes memory overflow.
INT8 quantization converts 32-bit floating-point values into 8-bit signed integers. This delivers three practical advantages:
- Reduces parameter storage (Flash) by up to 75%.
- Cuts intermediate activation buffer requirements (SRAM) significantly.
- Allows microcontrollers lacking hardware floating-point units (FPUs) to execute inference through single-cycle integer arithmetic.
Using MATLAB's Deep Learning Quantizer
MATLAB provides the dlquantizer tool to calibrate, validate, and convert neural networks without retraining from scratch.
Step 1: Set Up Calibration and Validation Data
Quantization requires a representative dataset to measure the dynamic range of activations across every layer. This prevents numerical saturation and clipping.
% Load floating point network
net = load('audio_keyword_net.mat').net;
% Prepare a small calibration datastore (e.g., 50-100 sample inputs)
calData = imageDatastore('data/calibration', 'IncludeSubfolders', true);
valData = imageDatastore('data/validation', 'IncludeSubfolders', true);
Step 2: Quantize with dlquantizer
Run the quantization workflow via the command-line API:
% Create the quantizer object
dq = dlquantizer(net, 'ExecutionEnvironment', 'arm-cortex');
% Run calibration to determine scaling factors and dynamic ranges
calResults = calibrate(dq, calData);
% Evaluate validation accuracy before finalizing
valResults = validate(dq, valData);
disp(valResults.MetricComparison);
Step 3: Save the Quantized Network
Inspect the accuracy difference between the original floating-point model and the INT8 quantized model. In most feedforward networks, the accuracy drop is below 1%.
% Export the INT8 quantized model
quantizedNet = quantize(dq);
save('quantized_keyword_net.mat', 'quantizedNet');
Step 4: Generate INT8 C Code
Once quantized, feed the new network directly into Embedded Coder. The generated C code uses int8_t arrays and CMSIS-NN integer SIMD instructions, drastically reducing execution time per inference cycle.
Executable MATLAB Script & Model Setup
% =========================================================================
% Script: int8_deep_learning_quantization.m
% Description: Measure dynamic range, calibrate activations, and quantize
% a 32-bit floating point network to 8-bit signed integers.
% =========================================================================
clc; clear; close all;
%% 1. Load Floating-Point Baseline Model
% Creating a compact 2D CNN baseline
layers = [
imageInputLayer([32 32 1], 'Normalization', 'none', 'Name', 'in')
convolution2dLayer(3, 8, 'Padding', 'same', 'Name', 'conv')
reluLayer('Name', 'relu')
fullyConnectedLayer(2, 'Name', 'fc')
softmaxLayer('Name', 'sm')
classificationLayer('Name', 'out')
];
dummyData = rand(32, 32, 1, 60, 'single');
dummyLabels = categorical(randi([1 2], [60 1]));
floatNet = trainNetwork(dummyData, dummyLabels, layers, trainingOptions('sgdm', 'MaxEpochs', 2, 'Verbose', false));
%% 2. Prepare Representative Calibration Datastore
% Representative inputs prevent clipping and scaling distortion
calibImages = rand(32, 32, 1, 30, 'single');
%% 3. Instantiate dlquantizer Object
fprintf('Starting INT8 Quantization Workflow...\n');
dq = dlquantizer(floatNet, 'ExecutionEnvironment', 'arm-cortex');
%% 4. Calibrate Dynamic Ranges Across Layers
% Computes scale factors and zero points for weights and bias arrays
calResults = calibrate(dq, calibImages);
disp('Layer Calibration Statistics:');
disp(calResults);
%% 5. Export Quantized Network
% Generates final int8 network ready for Embedded Coder deployment
quantizedNet = quantize(dq);
save('quantizedNet_int8.mat', 'quantizedNet');
% Calculate parameter footprint reduction
originalSize = numel(floatNet.Layers(2).Weights) * 4; % float32 = 4 bytes
quantizedSize = numel(floatNet.Layers(2).Weights) * 1; % int8 = 1 byte
fprintf('Layer Conv1 Weights: Float32 = %d Bytes | INT8 = %d Bytes (75%% reduction)\n', ...
originalSize, quantizedSize);
Related Verified MATLAB & Simulink Projects
Need pre-built, debugged Simulink models with complete parameter initialization scripts and documentation? Explore top related solutions:
Common Engineering Troubleshooting & Q&A
Frequently encountered bugs, solver convergence issues, and implementation questions answered by our engineering mentors:
Recommended Engineering Articles
Need Custom MATLAB / Simulink Implementation?
Our team of PhD engineers build custom simulation plants, train machine learning agents, tune PID/MPC controllers, and deliver complete, executable code with Turnitin reports.