Audio Classification with BEST-RQ-2


Audio Classification with BEST-RQ-2

Audio classification models are the silent gates in a lot of edge and handheld devices nowadays. Starting from wake word recognition in smartphones to predictive maintenance of machines by recognizing sounds that might lead to faults, audio classification models are more prominent than we think. In this article, we will try to tackle such a simple use case of audio classification with the BEST-RQ-2 model. Along with that, we will also cover the paper and model architecture briefly.

BEST-RQ-2 training pipeline and results.
Figure 1. BEST-RQ-2 training pipeline and results.

Primarily, a lot of audio processing deep learning models are based on 2D CNN architectures. However, with the emergence of Vision Transformers, models like BEST-RQ-2 are catching up. The latest model in the series, BEST-RQ-2, uses a JEPA-like self-supervised training approach to learn audio features. We will cover the model and a simple downstream audio classification task using it in this article.

What will we cover in this article?

  • Introduction to BEST-RQ-2
    • Brief walkthrough of the paper, the model architecture, and training regime
  • Using BEST-RQ-2 for audio classification on the ESC-50 dataset
    • Setting up the local training environment
    • Walkthrough of the dataset preparation and training logic
    • Inference using the trained model

BEST-RQ-2: Paper Discussion

The BEST-RQ-2 model was released by Ludovic Tuncay, Étienne Labbé, and Thomas Pellegrini from IRIT, Université de Toulouse, in the paper titled BEST-RQ-2: Contextualize-Then-Predict, a Two-Step Approach for Self-Supervised Audio Representations.

It also has its own GitHub codebase and Hugging Face model checkpoints.

Most audio deep learning models today lean on encoders trained on speech. While speech constitutes a majority of real-world scenarios, there is a much larger ecosystem waiting to be unlocked by training audio encoders on environmental sound as well. Recent self-supervised models such as wav2vec 2.0, data2vec, and JEPA-like architectures have been trying to move in the same direction. BEST-RQ-2 is one of the latest entries in the space that we will cover in detail in this article.

A Quick Recap of BEST-RQ and Audio-JEPA

To understand BEST-RQ-2 better, let’s have a quick look at BEST-RQ and Audio-JEPA.

BEST-RQ 2 primarily builds on the works of BEST-RQ and Audio-JEPA.

BEST-RQ stands for BERT-based Speech pre-Training with Random-projection Quantizer. It is masked prediction method for self-supervised audio learning. The input audio is masked in a few places, and the encoder has to predict a discrete target for each masked region. This model used a Conformer encoder and was mostly trained for speech optimization.

Audio-JEPA, which was the previous paper from the BEST-RQ-2 authors, applies the JEPA methodology to the audio domain. Instead of predicting discrete targets, the model predicts latent representations of masked audio patches in an embedding space.

Contributions of the BEST-RQ-2 Paper

There are four major contributions from the paper:

  • The original Conformer encoder is replaced with ViT (Vision Transformer).
  • The masked prediction is decomposed into two steps: contextualization and prediction.
  • Benchmarks on X-ARES and XARES-LLM show that the main gains come from this decomposition and not just shifting from Conformer to ViT.
  • The code and checkpoints are open-source.

The BEST-RQ-2 Pretraining Pipeline

The following diagram shows the entire pipeline for pretraining BEST-RQ-2.

BEST-RQ-2 pretraining pipeline.
Figure 2. BEST-RQ-2 pretraining pipeline.

Here is a step-by-step breakdown of the entire process:

  • The audio clip gets converted to a 128-bin log-mel spectrogram. A 10-second audio clip at 16 kHz produces a 128×256 spectrogram with a 128 ms analysis window and a 39.0625 ms hop.
  • The spectrogram is partitioned into 16×16 non-overlapping patches, producing a total of 128 tokens.
  • Masking is done by sampling a ratio between 0.4 and 0.6.
  • Next, a ViT context encoder processes the unmasked patches. This is the contextualization step.
  • The ViT predictor receives the contextualized representations along with the learnable mask embeddings at the masked positions. A linear classifier then outputs a distribution over 8192 codes for each masked patch. This is the prediction step.
  • Cross-entropy loss is used for computing the loss on the masked positions. This is done against the frozen random-projection targets.

The entire pipeline uses the predictor only during the pretraining phase. We discard it during inference, and only the context encoder remains. This also leads to a reduction in parameters during the inference phase.

The Frozen Random-Projection Quantizer

Generating the targets is also one of the interesting parts of the entire pipeline. As in BEST-RQ, each 16×16 patch is multiplied by a frozen random projection matrix R of shape 16×256. The matrix is sampled using a Xavier/Glorot uniform initialization. The authors then assign the nearest code from a random codebook of 8192 codes on a 16-dimensional hypersphere. The index of that code acts as the target for the patch.

The projection matrix and the codebook are sampled once and kept frozen.

Ablation Study

The authors also train a BEST-RQ (ViT) model without the encoder-predictor contextualization pipeline. The training regime is similar to BEST-RQ, with the backbone swapped with ViT.

BEST-RQ-2 Benchmarks

The authors evaluate the model on two benchmarks: X-ARES and XARES-LLM. While the former measures the general representation quality across speech, environmental sound, and music using a linear probe and kNN, the later measures how well the trained encoder works for downstream large audio language models.

The following table shows the X-ARES linear probe benchmarks averaged by domain.

BEST-RQ-2 linear probe benchmarks on the X-ARES dataset.
Figure 3. BEST-RQ-2 linear probe benchmarks on the X-ARES dataset.

Here, BEST-RQ-2 shows consistent gain in all domains except for speech. In speech, Whisper leads, which is specifically trained for the domain.

The following are X-ARES kNN results.

BEST-RQ-2 kNN benchmarks on the X-ARES dataset.
Figure 4. BEST-RQ-2 kNN benchmarks on the X-ARES dataset.

Here, although BEST-RQ-2 beats the other BEST-RQ variants, however, it lags behind Audio JEPA.

Finally, the X-ARES LLM benchmarks.

BEST-RQ-2 XARES-LLM benchmarks.
Figure 5. BEST-RQ-2 XARES-LLM benchmarks.

Although BEST-RQ-2 shows some gains, Whisper pretty much leads here. This is due to the fact that models like Whisper are trained with objectives which are more aligned to text-conditioned tasks.

We will halt the paper discussion here and move on to the more hands-on, training of a linear classifier for audio classification using the BEST-RQ-2 frozen encoder. However, I would recommend going through the paper to gain an in-depth understanding.

Training an Audio Classifier on Top of BEST-RQ-2

From this section onward, we will train a simple linear audio classifier on top of the BEST-RQ-2 backbone. For this, we will use the ESC-50 dataset.

We will use the BEST-RQ-2 model checkpoints from Hugging Face ltuncay/BEST-RQ-2.2-base

The ESC-50 Dataset

ESC-50 dataset contains 2000 environmental audio recordings spanning over 50 classes. We can find the dataset on Hugging Face, TigreGotico/ESC-50.

The classes are divided into 5 high-level categories and 50 granular ones. The following image shows all the classes present in the dataset.

Classes in the ESC-50 dataset.
Figure 6. Classes in the ESC-50 dataset.

Each file contains 5 seconds of audio and belongs to one of 5 folds. We will use 4 folds for training and hold out one for validation and inference after training.

The file naming follows the following format: {fold}-{source_id}-{take}-{target}. For example, if the file belongs to fold 1 and class 0, it might be, 1-100032-A-0.wav.

Code Download and Local Setup

A zip file is available for download along with this article. It is complete with all the code, the trained model, and the requirements file for getting started right away.

Download Code

We see the following directory structure after downloading the codebase and extracting it.

├── best-rq-esc50-classifier
│   ├── feature_extraction_audio.py
│   ├── model.pt
│   └── preprocessor_config.json
├── input
│   └── inference_data
├── engine.py
├── inference.py
├── main.py
├── predictions.json
├── prepare_datasets.py
└── requirements.txt
  • The Python files contain the dataset preparation, training, and inference logic.
  • The input/inference_data directory contains the audio files that we use in the evaluation loop during training. We do this so that we can easily use these files for inference after training as well.
  • And the best-rq-esc50-classifier directory contains the trained model.

Installing Requirements

We can use the requirements.txt file to install all the necessary packages.

pip install -r requirements.txt

Codebase Walkthrough for Training Audio Classifier using BEST-RQ-2

Here, we will cover the important parts of the codebase before we start the training process.

Dataset Preparation

Let’s start with the dataset preparation script that we have.

All the code for the same is present in the prepare_datasets.py file. The following code blocks shows the entire logic that we use for dataset preparation.

"""Dataset preparation for ESC-50."""

from pathlib import Path

import torch
import torchaudio
from datasets import Audio, load_dataset

DATASET_ID = "TigreGotico/ESC-50"


def _parse_esc50_filename(path):
    """Extract the fold and target class from an ESC-50 file name."""
    parts = Path(path).stem.split("-")
    return int(parts[0]), int(parts[-1])

def _load_waveform(audio, target_sampling_rate):
    """Load one encoded audio row as a mono float waveform at the target 
    sample rate.
    """
    waveform, sample_rate = torchaudio.load(audio["path"])

    if waveform.shape[0] > 1:
        waveform = waveform.mean(dim=0, keepdim=True)

    if sample_rate != target_sampling_rate:
        waveform = torchaudio.functional.resample(
            waveform,
            orig_freq=sample_rate,
            new_freq=target_sampling_rate,
        )

    return waveform.squeeze(0)


def add_labels(example):
    """Add fold and label fields to each dataset row."""
    fold, label = _parse_esc50_filename(example["audio"]["path"])
    example["fold"] = fold
    example["label"] = label
    return example


def get_esc50_splits(processor, test_fold=1):
    """Load ESC-50, add labels, and split it into train and validation by fold."""
    dataset = load_dataset(DATASET_ID, split="train")
    dataset = dataset.cast_column("audio", Audio(decode=False))
    dataset = dataset.map(add_labels)

    train_dataset = dataset.filter(
        lambda example: int(example["fold"]) != int(test_fold)
    )
    valid_dataset = dataset.filter(
        lambda example: int(example["fold"]) == int(test_fold)
    )

    num_labels = max(dataset["label"]) + 1
    return train_dataset, valid_dataset, num_labels


def export_validation_audio(valid_dataset, output_dir, sampling_rate):
    """Save the validation split's audio clips to disk for later inference."""
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    saved_paths = []

    for example in valid_dataset:
        audio = example["audio"]
        output_path = output_dir / Path(audio["path"]).name
        saved_paths.append(output_path)

        if output_path.exists():
            continue

        waveform = _load_waveform(audio, sampling_rate)
        torchaudio.save(output_path, waveform.unsqueeze(0), int(sampling_rate))

    return saved_paths


def make_collate_fn(processor):
    """Create a collate function that turns raw audio rows into model inputs."""
    sampling_rate = processor.sampling_rate

    def collate_fn(batch):
        waveforms = []
        labels = []

        for example in batch:
            waveform = _load_waveform(example["audio"], sampling_rate)
            waveforms.append(waveform.numpy())
            labels.append(int(example["label"]))

        inputs = processor(
            waveforms,
            sampling_rate=sampling_rate,
            return_tensors="pt",
            padding=True,
        )
        inputs["labels"] = torch.tensor(labels, dtype=torch.long)
        return inputs

    return collate_fn

Here are some of the important points about the above file.

  • The _parse_esc50_filename() function returns the audio file’s fold and class by splitting the file name appropriately.
  • _load_waveform() loads an audio file using torchaudio, resamples it to 16 kHz as that’s what the BEST-RQ-2 feature extractor expects.
  • The add_labels() function parses each fold and class index from every file name and adds them as columns.
  • The make_collate_fn() function bundles all of the above into a collation function that a PyTorch DataLoader can use.

We also have a export_validation_audio() function that exports the validation split’s audio clips into the local directory that we can use for inference later.

The Core Training Logic

The training logic lives in the engine.py file.

"""Training and evaluation loops for the audio classifier."""

import torch
from torch.nn import functional as F


def _move_batch_to_device(batch, device):
    """Move model inputs and labels to the target device."""
    labels = batch.pop("labels").to(device)
    inputs = {
        name: value.to(device) if torch.is_tensor(value) else value
        for name, value in batch.items()
    }
    return inputs, labels


def train_one_epoch(model, data_loader, optimizer, device):
    """Train for one epoch and return average loss and accuracy."""
    model.train()
    total_loss = 0.0
    total_correct = 0
    total_examples = 0

    for batch in data_loader:
        inputs, labels = _move_batch_to_device(batch, device)
        logits = model(**inputs)
        loss = F.cross_entropy(logits, labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_loss += loss.item() * labels.size(0)
        total_correct += logits.argmax(dim=-1).eq(labels).sum().item()
        total_examples += labels.size(0)

    if total_examples == 0:
        return 0.0, 0.0

    return total_loss / total_examples, total_correct / total_examples


@torch.inference_mode()
def evaluate(model, data_loader, device):
    """Evaluate the model and return average loss and accuracy."""
    model.eval()
    total_loss = 0.0
    total_correct = 0
    total_examples = 0

    for batch in data_loader:
        inputs, labels = _move_batch_to_device(batch, device)
        logits = model(**inputs)
        loss = F.cross_entropy(logits, labels)

        total_loss += loss.item() * labels.size(0)
        total_correct += logits.argmax(dim=-1).eq(labels).sum().item()
        total_examples += labels.size(0)

    if total_examples == 0:
        return 0.0, 0.0

    return total_loss / total_examples, total_correct / total_examples

The above are straightforward training and validation functions in PyTorch for training the audio classifier.

The Main Training File

We have the executable logic in the main.py file. The file also contains the preparation of the Audio Classifier model. Let’s take a look at the code block.

class AudioClassifier(torch.nn.Module):
    """A pretrained audio encoder with a linear classification head."""

    def __init__(self, encoder, num_labels, freeze_encoder=True):
        super().__init__()
        self.encoder = encoder
        self.freeze_encoder = freeze_encoder
        self.head = torch.nn.Linear(self._embedding_dim(), num_labels)

        if freeze_encoder:
            for parameter in self.encoder.parameters():
                parameter.requires_grad = False

We use the pretrained encoder of BEST-RQ-2 and simply add a Linear Classifier on top of it. We keep the encoder frozen by default so that only the linear head gets trained.

The other parts of the Python file contains the DataLoader preparation, running the loops through the training & validation epochs, and saving the model at the end.

Executing the Training

Let’s execute a training run and check out the results.

python main.py --batch-size 128 --epochs 40

We are using a batch size of 128 and training for 40 epochs. As the entire encoder is frozen, even with a higher batch size, the VRAM usage is only slightly above 1 GB.

The following are some of the truncated results from training.

Train dataset size: 1600
Validation dataset size: 400
Saved 400 validation clips to input/inference_data
Epoch 01 | train loss 3.5649 acc 0.2188 | valid loss 3.1408 acc 0.4250
Epoch 02 | train loss 2.7684 acc 0.6325 | valid loss 2.5586 acc 0.6150
Epoch 03 | train loss 2.1820 acc 0.7350 | valid loss 2.1282 acc 0.6825
Epoch 04 | train loss 1.7540 acc 0.7831 | valid loss 1.8196 acc 0.7200
Epoch 05 | train loss 1.4469 acc 0.8150 | valid loss 1.6013 acc 0.7475
Epoch 06 | train loss 1.2265 acc 0.8438 | valid loss 1.4417 acc 0.7600
Epoch 07 | train loss 1.0628 acc 0.8731 | valid loss 1.3199 acc 0.7875
.
.
.
Epoch 38 | train loss 0.1890 acc 0.9894 | valid loss 0.6344 acc 0.8525
Epoch 39 | train loss 0.1828 acc 0.9881 | valid loss 0.6314 acc 0.8525
Epoch 40 | train loss 0.1777 acc 0.9894 | valid loss 0.6314 acc 0.8525

By the end of training, we have a validation accuracy of 85.25%, and this is the model that we will use for inference.

Inference Using the Trained BEST-RQ-2 Audio Classifier

The inference.py file contains the entire inference logic. We will not do a thorough walkthrough of the script here. It is quite a straightforward one that loads the trained model, prepares the labels, iterates through each of the audio files from the input/inference_data directory, and runs prediction on each one.

Let’s execute the script.

python inference.py

We are using the entirety of fold 1 for inference. Here are some of the results from the terminal output.

1-94231-B-32.wav: keyboard_typing (0.341) | true keyboard_typing
1-95563-A-31.wav: mouse_click (0.938) | true mouse_click
1-96890-A-37.wav: clock_alarm (0.612) | true clock_alarm
1-96950-A-9.wav: siren (0.102) | true crow
1-96950-B-9.wav: crow (0.129) | true crow
1-97392-A-0.wav: dog (0.365) | true dog
1-977-A-39.wav: can_opening (0.042) | true glass_breaking
1-97793-A-31.wav: mouse_click (0.062) | true mouse_click
1-9841-A-13.wav: helicopter (0.944) | true crickets
1-9886-A-49.wav: breathing (0.985) | true hand_saw
1-9887-A-49.wav: breathing (0.894) | true hand_saw
1-9887-B-49.wav: breathing (0.261) | true hand_saw
1-99958-A-31.wav: wind (0.264) | true mouse_click

We show the predictions with the probability score and the true label so that we can know where the model makes mistakes. We are also saving a predictions.json file in the same working directory to take a look at the results later.

[
  {
    "file": "input/inference_data/1-100032-A-0.wav",
    "predicted_label": "can_opening",
    "probability": 0.048582982271909714,
    "true_label": "dog"
  },
  {
    "file": "input/inference_data/1-100038-A-14.wav",
    "predicted_label": "chirping_birds",
    "probability": 0.9394031167030334,
    "true_label": "chirping_birds"
  },
.
.
.
  {
    "file": "input/inference_data/1-99958-A-31.wav",
    "predicted_label": "wind",
    "probability": 0.26445290446281433,
    "true_label": "mouse_click"
  }
]

You can check with different learning rates, unfreezing the encoder, and training for longer on how the model is working.

Summary and Conclusion

In this article, we covered the BEST-RQ-2 model, which was trained for masked audio recognition. After a brief walkthrough of the paper, we used the encoder for audio classification and checked how it works out on real-world audio. In the future, we will cover more such experiments that align more with real-world scenarios. I hope that this article was worth your time.

If you have any questions, thoughts, or suggestions, please leave them in the comment section. I will surely address them.

You can contact me using the Contact section. You can also find me on LinkedIn, and X.

Liked it? Take a second to support Sovit Ranjan Rath on Patreon!
Become a patron at Patreon!

Leave a Reply

Your email address will not be published. Required fields are marked *