frontend
birdnet_stm32.models.frontend
¶
AudioFrontendLayer: in-model audio feature extraction for the STM32N6 NPU.
This Keras layer implements the three frontend modes that produce a fixed-size mel-like spectrogram [B, mel_bins, spec_width, 1] from different input representations:
- precomputed: Pass-through for offline mel spectrograms.
- hybrid: Linear STFT magnitude -> 1x1 Conv2D mel mixer.
- raw: Raw waveform -> learned Gabor quadrature filterbank -> magnitude.
Design constraints, in priority order:
- Cover the signal. The raw filterbank uses a kernel at least as long as its hop, so every input sample reaches at least one output frame, and the analysis window is long enough to resolve bird harmonics.
- Represent magnitude, not phase. A single real-valued bandpass filter
oscillates with the carrier; sampling it at the hop rate aliases. The raw
path therefore learns a quadrature (cosine/sine) pair and combines them as
max(|re|, |im|) + 0.4 * min(|re|, |im|)— within ~4% of the true modulus and, unlikesqrt(re^2 + im^2), INT8-friendly. - Stay on the NPU. No global reductions and no data-dependent scaling: every op here is a convolution, an elementwise op, or a layout change. Per-band calibration is learned (BatchNorm + trainable magnitude scaling) rather than computed per sample at inference time.
- Compute the same thing on the NPU. Compiling onto the NPU is not enough;
the arithmetic has to survive it. Two measured NPU defects shape the raw
path: the filterbank is split into channel-group convolutions (
RAW_SPLIT) and|x|is built from ReLU/SUB/ADD (AudioFrontendLayer._abs). Verify any change here withstedgeai validate --mode targeton trained weights.
The caller is expected to hand over a peak-normalized waveform (the training, evaluation, calibration and firmware paths all do this), which is what makes fixed learned gains valid in place of a per-sample normalization.
RawGeometry
¶
Bases: NamedTuple
Layout of the folded raw filterbank.
Attributes:
| Name | Type | Description |
|---|---|---|
hop |
int
|
Distance between output frames, in input samples. |
window |
int
|
Analysis window length, in input samples. |
fold |
int
|
Interleaved channels the waveform is reshaped into. |
kernel |
int
|
Convolution kernel width, in folded frames. |
stride |
int
|
Convolution stride, in folded frames (always 2). |
crop |
int
|
Input samples actually consumed (a whole number of folds). |
frames |
int
|
Frames the convolution emits before slicing to spec_width. |
Source code in birdnet_stm32/models/frontend.py
AudioFrontendLayer
¶
Bases: Layer
Audio frontend with interchangeable input modes and magnitude scaling.
Modes
precomputed: Mel spectrogram [B, mel_bins, T, 1] -> slice to spec_width. hybrid: Linear STFT bins [B, fft_bins, T, 1] -> 1x1 mel mixer. raw: Waveform [B, T, 1] -> Gabor quadrature filterbank -> L1 magnitude.
Magnitude scaling
'none': Pass-through. 'pwl': Piecewise-linear compression (DW 1x1 branches + ReLU + Add).
Notes
is_trainablecontrols the filterbank (raw) and mel mixer (hybrid). The per-band BatchNorm and the magnitude scaling are always trainable: they replace the per-sample normalization this layer used to apply, so they have to be learned from data to be calibrated.- The raw kernel length is at least the hop, so no input sample is skipped.
Source code in birdnet_stm32/models/frontend.py
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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 | |
build(input_shape)
¶
Build the frontend layer based on the selected mode.
Source code in birdnet_stm32/models/frontend.py
set_quantization_hook(hook)
¶
Install or remove a training-only internal quantization hook.
call(inputs, training=None)
¶
Run the selected frontend path and return a fixed-size spectrogram.
Shapes
precomputed: [B, mel_bins, T, 1] -> [B, mel_bins, spec_width, 1] hybrid: [B, fft_bins, T, 1] -> [B, mel_bins, spec_width, 1] raw: [B, T, 1] -> [B, mel_bins, spec_width, 1]
Source code in birdnet_stm32/models/frontend.py
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 | |
compute_output_shape(input_shape)
¶
Return static output shape: (batch, mel_bins, spec_width, 1).
from_config(config)
classmethod
¶
Build from a serialized config, ignoring retired arguments.
get_config()
¶
Return a serializable configuration for model saving/loading.
Source code in birdnet_stm32/models/frontend.py
normalize_frontend_name(name)
¶
Validate a frontend name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Frontend name. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The frontend name, unchanged. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If name is not a valid frontend. |
Source code in birdnet_stm32/models/frontend.py
hybrid_fft_bins(fft_length)
¶
Return the number of linear STFT bins the hybrid frontend consumes.
The Nyquist bin is dropped so the count is fft_length // 2 — a multiple
of 8 for every sane FFT size, which lets the mel mixer run at full NPU
channel utilization without a runtime zero-pad (a FILL + CONCATENATION pair
on every inference). The discarded bin carries no bird signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fft_length
|
int
|
FFT size. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of spectrogram rows expected as model input. |
Source code in birdnet_stm32/models/frontend.py
raw_filterbank_geometry(num_samples, spec_width, overlap=RAW_OVERLAP)
¶
Lay out the raw filterbank so its convolution runs on the NPU.
A learned STFT wants a long kernel and a hop of a few hundred samples. Fed to the N6 directly that is a large-stride convolution, which the compiler hands to the Cortex-M55 — measured, and the reason the previous frontend's filterbank never ran on the NPU at all.
The fix is a polyphase view: reinterpret the waveform as hop / 2
interleaved channels (free — NHWC memory is contiguous, so [T, 1] and
[T/fold, fold] are the same bytes) and convolve with stride 2. The
arithmetic is identical to the long strided kernel, but every convolution
now sits inside the NPU's supported stride range and sees a full channel
group instead of a single input channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_samples
|
int
|
Waveform length in samples. |
required |
spec_width
|
int
|
Required number of output frames. |
required |
overlap
|
int
|
Window length as a multiple of the hop. |
RAW_OVERLAP
|
Returns:
| Type | Description |
|---|---|
RawGeometry
|
The resolved :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no hop yields |
Source code in birdnet_stm32/models/frontend.py
gabor_filterbank(mel_bins, kernel, sample_rate, fmin, fmax)
¶
Build mel-spaced Gabor filters as a cosine/sine quadrature pair.
Each band is a Gaussian-windowed complex exponential centred on a mel frequency, with its time-domain width set from the spacing to its neighbours so the bank's frequency response approximates a mel filterbank. Starting from this initialization, an untrained frontend already produces a mel-like spectrogram; training only refines it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mel_bins
|
int
|
Number of filters (output channels). |
required |
kernel
|
int
|
Filter length in samples. |
required |
sample_rate
|
int
|
Sampling rate (Hz). |
required |
fmin
|
float
|
Lowest band centre (Hz). |
required |
fmax
|
float
|
Highest band centre (Hz). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Tuple of |
ndarray
|
normalized to unit energy per band. |