trainer
birdnet_stm32.training.trainer
¶
Training loop with cosine LR schedule, early stopping, and checkpointing.
WarmupCosineDecay
¶
Bases: LearningRateSchedule
Linear warmup followed by cosine decay to zero.
Also carries a step offset so a resumed run continues along the same schedule instead of jumping back to the peak learning rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_learning_rate
|
float
|
Peak learning rate reached at the end of warmup. |
required |
decay_steps
|
int
|
Total number of steps in the full run (warmup included). |
required |
warmup_steps
|
int
|
Number of steps spent ramping up linearly from ~0. |
0
|
offset_steps
|
int
|
Steps already completed by a previous run. |
0
|
Source code in birdnet_stm32/training/trainer.py
get_config()
¶
Return a serializable configuration dict.
Source code in birdnet_stm32/training/trainer.py
monitor_mode(monitor)
¶
Return "max" or "min" for a validation metric name.
train_model(model, train_dataset, val_dataset, epochs=50, learning_rate=0.001, batch_size=32, patience=10, checkpoint_path='checkpoints/best_model.keras', steps_per_epoch=None, val_steps=None, optimizer='adam', weight_decay=0.0, loss_fn=None, gradient_clip_norm=1.0, resume=False, extra_callbacks=None, checkpoint_model=None, checkpoint_sync=None, checkpoint_monitor=_MONITOR, checkpoint_mode=_MONITOR_MODE, checkpoint_start_epoch=0, checkpoint_managed=False)
¶
Train a model with cosine LR schedule, early stopping, and checkpointing.
The classifier head is always sigmoid + binary crossentropy (multi-label). Soundscape recordings are inherently multi-label even when the source label is a single species, so we always optimise per-class probabilities.
Checkpointing and early stopping track validation cmAP; the best model is saved as a full .keras file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
Model to train. |
required |
train_dataset
|
Dataset
|
Training dataset (infinite). |
required |
val_dataset
|
Dataset
|
Validation dataset (infinite). |
required |
epochs
|
int
|
Number of epochs. |
50
|
learning_rate
|
float
|
Initial learning rate for cosine schedule. |
0.001
|
batch_size
|
int
|
Unused; kept for API symmetry with data loader. |
32
|
patience
|
int
|
Early stopping patience (epochs). |
10
|
checkpoint_path
|
str
|
Path to save the best .keras model. |
'checkpoints/best_model.keras'
|
steps_per_epoch
|
int | None
|
Training steps per epoch (> 0 required). |
None
|
val_steps
|
int | None
|
Validation steps per epoch (defaults to 1 if <= 0). |
None
|
optimizer
|
str
|
Optimizer name ('adam', 'sgd', or 'adamw'). |
'adam'
|
weight_decay
|
float
|
Weight decay factor (only used by 'adamw'). |
0.0
|
loss_fn
|
str | Loss | None
|
Optional custom loss function. Defaults to |
None
|
gradient_clip_norm
|
float
|
Max gradient norm for clipping (0 = disabled). |
1.0
|
resume
|
bool
|
If True, reload the model from the checkpoint and continue from the recorded epoch (the learning-rate schedule is advanced to match). |
False
|
extra_callbacks
|
list[Callback] | None
|
Additional Keras callbacks (e.g. QAT callback). |
None
|
checkpoint_model
|
Model | None
|
Optional deployment model that shares weights with
|
None
|
checkpoint_sync
|
Callable[[], None] | None
|
Optional hook that copies separately cloned weights
into |
None
|
checkpoint_monitor
|
str
|
Validation metric used for checkpoint selection and early stopping. |
_MONITOR
|
checkpoint_mode
|
str
|
Whether a larger ( |
_MONITOR_MODE
|
checkpoint_managed
|
bool
|
An external callback owns checkpoint artifacts (INT8 selection). |
False
|
checkpoint_start_epoch
|
int
|
First epoch (0-based) eligible for checkpoint selection and early stopping. Compression schedules use this so a model that has not yet reached its target sparsity or quantization noise cannot win on the strength of the perturbation it is missing. |
0
|
Returns:
| Type | Description |
|---|---|
History
|
Keras training history. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in birdnet_stm32/training/trainer.py
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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | |
compute_hop_length(sample_rate, chunk_duration, spec_width)
¶
Compute hop length to produce spec_width frames from an input chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_rate
|
int
|
Sampling rate (Hz). |
required |
chunk_duration
|
float
|
Chunk duration (seconds). |
required |
spec_width
|
int
|
Desired number of frames. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Hop length in samples (floor(T / spec_width), at least 1). |