quantize
birdnet_stm32.conversion.quantize
¶
Post-training quantization (PTQ) conversion from Keras to TFLite.
Provides representative dataset generation and TFLite conversion with float32 I/O and INT8 internal ops for STM32N6 NPU deployment.
stratified_sample_paths(file_paths, num_samples, *, seed, exclude=None)
¶
Select an exact, deterministic, class-balanced audio manifest.
Source code in birdnet_stm32/conversion/quantize.py
representative_data_gen(file_paths, cfg, num_samples=100, snr_threshold=0.0)
¶
Build a representative dataset generator for TFLite PTQ calibration.
Yields one input tensor per iteration in the exact shape expected by the model. Includes quiet and nuisance recordings by default because they are part of the deployed input distribution and every requested calibration path must contribute deterministically. Callers may opt into energy filtering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_paths
|
list[str]
|
Audio file paths to sample from. |
required |
cfg
|
dict
|
Training config dict (sample_rate, num_mels, spec_width, chunk_duration, fft_length, audio_frontend, mag_scale). |
required |
num_samples
|
int
|
Maximum number of samples to draw. |
100
|
snr_threshold
|
float
|
Minimum RMS energy for a chunk to be included (0 to disable). |
0.0
|
Yields:
| Type | Description |
|---|---|
list[ndarray]
|
Single-element list containing the input tensor with batch dimension. |
Source code in birdnet_stm32/conversion/quantize.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
convert_to_tflite(model, rep_data_gen, output_path, quantization='ptq', per_tensor=False)
¶
Convert a Keras model to quantized TFLite with float32 I/O and INT8 internals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
Loaded Keras model. |
required |
rep_data_gen
|
Callable[[], Iterable[list[ndarray]]]
|
Callable returning an iterable of [input_tensor] for calibration. Not used when quantization='dynamic'. |
required |
output_path
|
str
|
Path to save the .tflite model. |
required |
quantization
|
str
|
'ptq' (full INT8 with calibration) or 'dynamic' (dynamic range). |
'ptq'
|
per_tensor
|
bool
|
If True, use per-tensor instead of per-channel quantization. |
False
|
Returns:
| Type | Description |
|---|---|
bytes
|
Raw TFLite model bytes. |