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
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 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 | |
filterbank_convs()
¶
Every convolution the raw filterbank is emitted as, in graph order.
scale_filterbank_bands(gains)
¶
Multiply band c's filters by gains[c], both components.
Equalization's only handle on the filterbank, written once here because
a fused bank carries the two components in one kernel (and, with a
second exposure, both exposures of each: they scale together, so the
high copy stays exactly raw_exposure_gain times the low one).
Source code in birdnet_stm32/models/frontend.py
build(input_shape)
¶
Build the frontend layer based on the selected mode.
Source code in birdnet_stm32/models/frontend.py
partial_kernel(full, i)
¶
Partial i's share of a full folded kernel [1, kernel, fold, M].
Source code in birdnet_stm32/models/frontend.py
full_filterbank()
¶
Reassemble the full folded kernels [1, kernel, fold, M] (real, imag).
With a second exposure this is the low copy; the high copy is always it
times raw_exposure_gain.
Source code in birdnet_stm32/models/frontend.py
set_full_filterbank(re_kernel, im_kernel)
¶
Load full folded kernels [1, kernel, fold, M] into the partial convolutions.
With a second exposure they are the low copy; the high copy is set to
them times raw_exposure_gain.
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
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 | |
compute_output_shape(input_shape)
¶
Return static output shape: (batch, mel_bins, spec_width, out_channels).
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
raw_filterbank_split(geom)
¶
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. |