AI Logic

Audio Features and Front-ends

LEAF

Updated:

Diagram of LEAF. The left side compares the pipeline of a mel filterbank (STFT, squaring, mel filters, log; all fixed) with LEAF (Gabor filter convolution, squaring, pooling with a Gaussian lowpass filter, sPCEN; all learned). The right side shows a single Gabor filter: on top, its Gaussian-shaped frequency response centered at η; below, its time-domain shape, a sinusoid multiplied by a Gaussian envelope

Background and Overview

LEAF (LEarnable Audio Frontend) is a frontend that splits the computation of features from an audio waveform into three stages (filtering, pooling, and compression with normalization) and makes all of them learnable layers. Zeghidour et al. at Google proposed it in 2021 as a drop-in replacement for the mel filterbank.

The mel filterbank is a long-standing feature: it takes the spectrum computed by an STFT, aggregates it with triangular filters spaced on the mel scale, and compresses it with a log. It is a good starting point that mimics human hearing, but the original paper points out the following limitations.

  • The mel scale itself has been revised many times, and the original listening experiments could not be reproduced later
  • For some tasks, a cube root or a 10th root has been reported to work better than the log
  • Matching human hearing can be a disadvantage for tasks where fine differences at high frequencies matter

Frontends that learn from the waveform, such as SincNet, existed before, but most of them learned only the filters or only the compression and kept the rest fixed. LEAF is new in that it learns all three stages with a small number of parameters, and it outperformed the mel filterbank on average across eight classification tasks covering speech, music, environmental sounds, and animal vocalizations.

The Three Stages

LEAF turns a waveform xx into a time-frequency representation in the following three stages (left side of the diagram at the top of the article). NN is the number of filters (channels); the default setting in the original paper is N=40N = 40.

  1. Split into bands with Gabor filters: convolve the waveform with complex Gabor filters φn\varphi_n of length WW and take the squared modulus (Eq. 2). The complex values can be computed with real arithmetic only, by treating two adjacent real filters as the real and imaginary parts.
  2. Pool with Gaussian lowpass filters: apply a separate Gaussian-shaped lowpass filter ϕn\phi_n to each channel (a depthwise convolution) and downsample at a fixed stride (Eq. 5).
  3. Compress and normalize with sPCEN: use PCEN to normalize and compress the magnitude per channel. Because the smoothing coefficient sns_n is also learned per channel, this variant is called sPCEN (Eq. 6).
fn=∣x∗φn∣2,φn(t)=ei2πηnt12π σne−t22σn2,t=−W2,…,W2f_n = |x * \varphi_n|^2, \qquad \varphi_n(t) = e^{i 2\pi \eta_n t} \frac{1}{\sqrt{2\pi}\, \sigma_n} e^{-\frac{t^2}{2\sigma_n^2}}, \qquad t = -\frac{W}{2}, \dots, \frac{W}{2} ϕn(t)=12π σne−t22σn2\phi_n(t) = \frac{1}{\sqrt{2\pi}\, \sigma_n} e^{-\frac{t^2}{2\sigma_n^2}} PCEN(F(t,n))=(F(t,n)(ϵ+M(t,n))αn+δn)rn−δnrn,M(t,n)=(1−sn) M(t−1,n)+snF(t,n)\mathrm{PCEN}(F(t, n)) = \left( \frac{F(t, n)}{(\epsilon + M(t, n))^{\alpha_n}} + \delta_n \right)^{r_n} - \delta_n^{r_n}, \qquad M(t, n) = (1 - s_n)\, M(t-1, n) + s_n F(t, n)

Here ηn\eta_n is the center frequency of the filter and σn\sigma_n is its temporal width (the frequency bandwidth is 1/σn1/\sigma_n); frequencies are expressed as values normalized by the sampling rate (−1/2-1/2 to 1/21/2). In the original paper's setting, the filter length is W=401W = 401 (about 25 ms at 16 kHz), the pooling window is also 401 samples, and an output is produced every 160 samples (10 ms). The output has exactly the same shape as a 40-channel mel filterbank with a 10 ms hop, so it can be swapped in without changing the downstream model.

The learnable parameters are the filters' ηn\eta_n and σn\sigma_n (2N2N), the pooling widths (NN), and sPCEN's αn\alpha_n, δn\delta_n, rnr_n, and sns_n (4N4N), for a total of 7N7N. That is only 280 for N=40N = 40 and 448 even for N=64N = 64.

If the mel filterbank is an "off-the-shelf measuring instrument with a fixed scale," LEAF is "an instrument of the same form whose scale positions, widths, and sensitivity can be tuned to the data." Its initial values are almost the same as the mel filterbank, so it performs on par with the off-the-shelf version from the start of training and then gradually adapts to the task.

Why This Design

Each of LEAF's three components is chosen to address a problem in prior work.

ComponentChoiceReason
FiltersGabor filters (only the center frequency and bandwidth are learned)The most compact shape in both time and frequency, and no window is needed even at a finite length (sinc filters need a window). The frequency response is also Gaussian and easy to interpret. Since there is almost no negative-frequency component, the squared modulus gives a per-band envelope that is robust to small shifts
PoolingPer-channel Gaussian lowpass filtersPrior work showed that downsampling with a lowpass filter works better than max pooling for speech recognition. Because each channel has a different bandwidth, the pooling filter is also learned per channel
Compression and normalizationsPCENThe log applies the same compression to every channel, and its shape is fixed. PCEN can learn the compression per channel and was known to outperform the log

Learning the filters as an unconstrained 1D convolution (W⋅NW \cdot N parameters) was also tried, but the learned filters spread widely across the frequency axis, responded to negative frequencies, and became spiky. Gabor filters cut the parameters by a factor of 200 (for W=401W = 401) and yield stable, interpretable filters.

To stabilize training, the center frequency ηn\eta_n is clipped to [0,1/2][0, 1/2], and σn\sigma_n is clipped so that the full width at half maximum of the frequency response stays between 1/W1/W and 1/21/2. The order of the filters' center frequencies (from low to high) was mostly preserved during training without any constraint, and enforcing the order did not change performance.

Experimental Results

The original paper used the same downstream model for every frontend (EfficientNet-B0, about 4 million parameters) and trained on 1-second crops of 16 kHz audio (Adam, learning rate 10−410^{-4}). The compared frontends were a 40-channel log mel filterbank, learnable filterbanks (TD-filterbanks), SincNet, and LEAF.

Test accuracy (%) when each of the eight tasks is trained separately is as follows (excerpted from Table 1 of the original paper).

TaskMelTD-filterbanksSincNetLEAF
Bird audio detection78.680.978.081.4
Emotion recognition49.157.144.257.8
Speaker identification (VoxCeleb)31.925.343.533.1
Pitch (NSynth)91.591.383.892.0
Keywords (Speech Commands)92.487.389.293.4
Language identification76.571.678.986.0
Average over 8 tasks73.972.973.176.9

The main takeaways are as follows.

  • It beat every baseline on average: task by task, LEAF was on par with or better than the others on almost every task. The exception was speaker identification, where SincNet, originally designed for speaker recognition, gave the best result.
  • One set of parameters works for many tasks: when a single model was trained on all eight tasks jointly, the average accuracy was 77.8% for mel and 79.3% for LEAF, with LEAF again the best.
  • Switching the compression to PCEN alone helps a lot: even for the mel filterbank, replacing the log with PCEN raised the average from 73.9% to 76.4%. The combination of LEAF's filters and sPCEN was the best at 76.9%.

On AudioSet (527 classes), a large-scale sound classification benchmark, the d-prime scores (higher is better) are as follows.

FrontendLearnable parametersd-prime (EfficientNet-B0)
Mel02.61
Mel + PCEN2562.60
Wavegram (9 convolutional layers)300K2.44
SincNet2562.48
SincNet+ (with LEAF's pooling and sPCEN)4482.58
LEAF4482.63

LEAF outperformed Wavegram with about 1/670 of its parameters. Also, simply adding LEAF's Gaussian pooling and sPCEN to SincNet (SincNet+) substantially improved SincNet's results.

The learned center frequencies did not move far from their mel-scale initialization, but they spread out at both ends: the lowest filter ended up at about 60 Hz, compared with about 100 Hz for mel. In an experiment with Gaussian noise added to the audio (Speech Commands), LEAF was also more robust to noise than the mel filterbank, and the combination of LEAF and PCEN gave the best result.

Practical Considerations

The filter length and the pooling stride are fixed. LEAF learns each filter's center frequency, bandwidth, pooling width, and compression parameters, but the filter length WW (about 25 ms) and the output stride (10 ms) are set by hand. The original paper also lists learning them from data as future work. For data with a sampling rate very different from 16 kHz, WW and the stride need to be retuned.

Keep the following points in mind as well.

  • Mel-scale initialization matters: the learned filters do not move far from their initial values, and the original paper describes the mel scale as a strong initialization. Random initialization loses this advantage.
  • It does not win on every task: SincNet is better for speaker identification, for example, so the best frontend depends on the task. For a new task, verify against the mel filterbank.
  • It costs more compute than a mel filterbank: although it has few parameters, convolving a length-401 filter over every sample of the waveform tends to be heavier than an FFT-based mel filterbank.
  • Combining it with operations that assume frequency order: operations such as 2D convolutions and SpecAugment assume that neighboring channels correspond to neighboring frequencies, so their meaning changes if the filter order breaks down. The order was mostly preserved in the original paper, but it is safer to check the learned center frequencies.

Comparison with Other Frontends

The frontends used for audio classification compare as follows.

FrontendFiltersPoolingCompressionLearnable parameters (40 channels)Best suited for
Mel filterbankMel-scale triangles (fixed)STFT window and hop (fixed)log (fixed)0The standard to try first. Many pretrained models available
Mel + PCENSame as aboveSame as abovePCEN (learnable)Compression onlyEnvironments with varying loudness or noise
SincNetRectangular bandpass (cutoff frequencies learned)Max pooling (fixed)Layer NormFilters onlySpeaker recognition
LEAFGabor (center frequency and bandwidth learned)Gaussian lowpass (learned)sPCEN (learned)280Broad audio classification: speech, music, environmental sounds, animal vocalizations
Stacked convolutional layers (e.g., Wavegram)UnconstrainedUnconstrainedNoneHundreds of thousandsVery large datasets

Rough guidelines for choosing:

  • Using existing models or pretrained weights: keep the mel filterbank.
  • Training a new audio classification model and wanting a bit more accuracy: plug in LEAF instead of the mel filterbank. Since the output shape is the same, it can be tried without changing the downstream model.
  • Wanting a quick boost in robustness first: just replacing the log with PCEN gives a large average improvement.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

'''
A small implementation of LEAF's three stages (Gabor filters -> squaring -> pooling with a Gaussian lowpass -> sPCEN).
The formulas follow Eqs. (2)(4)(5)(6) of the original paper. The initialization is one example for this implementation.
'''

def hz_to_mel(f):
  return 2595.0 * math.log10(1.0 + f / 700.0)

def mel_to_hz(m):
  return 700.0 * (10.0 ** (m / 2595.0) - 1.0)

class LEAF(nn.Module):
  def __init__(self, n_filters=40, sample_rate=16000, window=401, stride=160):
    super().__init__()
    self.window, self.stride = window, stride
    # 1. Gabor filters: learn the center frequency η (normalized by the sampling rate) and the temporal width σ (in samples)
    mels = torch.linspace(hz_to_mel(60.0), hz_to_mel(7800.0), n_filters)
    self.eta = nn.Parameter(torch.tensor([mel_to_hz(m) for m in mels.tolist()]) / sample_rate)
    self.sigma = nn.Parameter(torch.full((n_filters,), window / 8.0))
    # 2. Width of the pooling Gaussian (per channel, expressed on t normalized to -1..1)
    self.lowpass_width = nn.Parameter(torch.full((n_filters,), 0.4))
    # 3. sPCEN (this implementation initializes with the values from the PCEN paper and s = 0.04)
    self.log_alpha = nn.Parameter(torch.full((n_filters,), math.log(0.98)))
    self.log_delta = nn.Parameter(torch.full((n_filters,), math.log(2.0)))
    self.log_r = nn.Parameter(torch.full((n_filters,), math.log(0.5)))
    self.s = nn.Parameter(torch.full((n_filters,), 0.04))
    self.register_buffer('t', torch.arange(window, dtype=torch.float32) - (window - 1) / 2)

  def gabor_kernels(self):
    eta = self.eta.clamp(0.0, 0.5)  # keep the center frequency in the positive range
    sigma = self.sigma.clamp(4 * math.sqrt(2 * math.log(2)), 2 * self.window * math.sqrt(2 * math.log(2)))
    env = torch.exp(-self.t[None, :] ** 2 / (2 * sigma[:, None] ** 2)) / (math.sqrt(2 * math.pi) * sigma[:, None])
    phase = 2 * math.pi * eta[:, None] * self.t[None, :]
    # Lay out the real and imaginary parts as two adjacent real filters
    return torch.stack([env * torch.cos(phase), env * torch.sin(phase)], dim=1).reshape(-1, 1, self.window)

  def forward(self, x):
    # x: [batch, samples]
    n = self.eta.shape[0]
    y = F.conv1d(x.unsqueeze(1), self.gabor_kernels(), padding=self.window // 2)  # [B, 2N, T]
    y = y.reshape(y.shape[0], n, 2, -1).pow(2).sum(dim=2)                           # squared modulus [B, N, T]

    # Apply a Gaussian lowpass filter per channel and downsample (depthwise convolution)
    tn = self.t / ((self.window - 1) / 2)
    width = self.lowpass_width.clamp(2.0 / self.window, 0.5)
    lp = torch.exp(-0.5 * (tn[None, :] / width[:, None]) ** 2)
    lp = (lp / lp.sum(dim=1, keepdim=True)).unsqueeze(1)                            # [N, 1, W]
    y = F.conv1d(y, lp, stride=self.stride, padding=self.window // 2, groups=n)   # [B, N, frames]

    # sPCEN: the smoothing coefficient s is also learned per channel
    s = self.s.clamp(1e-3, 1.0)[None, :]
    m, ms = y[..., 0], []
    for t in range(y.shape[-1]):
      m = (1 - s) * m + s * y[..., t]
      ms.append(m)
    m = torch.stack(ms, dim=-1)
    alpha, delta, r = (p.exp()[None, :, None] for p in (self.log_alpha, self.log_delta, self.log_r))
    return (y / (1e-6 + m) ** alpha + delta) ** r - delta ** r


frontend = LEAF(n_filters=40)
wave = torch.randn(4, 16000)  # four 1-second clips
features = frontend(wave)
print(features.shape)  # torch.Size([4, 40, 100])  40 channels every 10 ms (same layout as a mel filterbank)
# Attach a classifier such as EfficientNet after this and train it together with the frontend

FAQ

Q. How does LEAF differ from SincNet?
A.

SincNet learns only the filters; its pooling (max pooling) and normalization (Layer Norm) are fixed. LEAF learns the filters, pooling, and compression. The filter shapes also differ: SincNet uses windowed rectangular bandpass filters, while LEAF uses Gabor filters that need no window. In the original paper's comparison, LEAF was better on average, and SincNet was better for speaker identification.

Q. How many parameters does it add?
A.

With NN filters it adds 7N7N parameters: 280 for 40 channels and 448 even for 64 channels. Compared with the downstream classifier (about 4 million for EfficientNet-B0), this is a negligible increase.

Q. Can data augmentation such as SpecAugment be applied to LEAF's output?
A.

Yes. The original paper also uses mixup and SpecAugment in its AudioSet experiments. However, SpecAugment assumes that neighboring channels correspond to neighboring frequencies, so it is safer to check that the learned center frequencies are still sorted from low to high (in the original paper, the order was mostly preserved).

References

  1. Zeghidour, N., Teboul, O., de Chaumont Quitry, F., & Tagliasacchi, M. (2021). LEAF: A learnable frontend for audio classification. International Conference on Learning Representations (ICLR 2021).
  2. Wang, Y., Getreuer, P., Hughes, T., Lyon, R. F., & Saurous, R. A. (2017). Trainable frontend for robust and far-field keyword spotting. ICASSP 2017, 5670–5674. (PCEN)
  3. Ravanelli, M., & Bengio, Y. (2018). Speaker recognition from raw waveform with SincNet. IEEE SLT 2018, 1021–1028.