torchlibrosa developer on retainer: LogmelFilterBank output is (batch, 1, time, n_mels) — ResNet expects (batch, 1, n_mels, time) — time and frequency axes transposed — model trains on swapped spectrogram — bird species accuracy 0.52 not 0.86 — 4 weeks — torchlibrosa developer on monthly retainer

torchlibrosa 0.1.0 • Python 3.9; PyTorch 1.11; LogmelFilterBank returns (batch, 1, time_steps, n_mels) = (batch, 1, 130, 128) for 3-second clips; ResNet-50 classifier expects (batch, 1, n_mels, time_steps) = (batch, 1, 128, 130); shape difference is 2 (130 vs 128); no RuntimeError; model trains on transposed spectrograms; bird call temporal patterns unrecognizable when time and frequency axes are swapped; accuracy 0.52 not 0.86; fix: logmel.transpose(2, 3) • Westfield Torchlibrosa Ltd. (ornithology research platform; 15,000 recordings/month; 400 bird species; 4 weeks; 2.0h retainer engagement)

Westfield Torchlibrosa Ltd. built a bird species identification platform classifying 15,000 field recordings per month from 400 species monitored at 80 nature reserves. The pipeline used torchlibrosa (0.1.0) with Spectrogram + LogmelFilterBank as a differentiable feature extraction frontend feeding a ResNet-50 image classifier. LogmelFilterBank(sr=22050, n_fft=1024, n_mels=128, fmin=50, fmax=11025, top_db=80.0) returns a log-mel spectrogram of shape (batch, 1, time_steps, n_mels). The ResNet-50 classifier, adapted from image classification, expected input of shape (batch, channels, height, width) = (batch, 1, n_mels, time_steps) — frequency bins as the height dimension, time steps as width. The developer fed LogmelFilterBank’s output directly to the ResNet without transposing. For 3-second clips at 22050 Hz with hop_length=512: time_steps ≈ 130 and n_mels=128 — a shape difference of only 2. PyTorch’s nn.Conv2d processed (batch, 1, 130, 128) without raising any error. The model trained for 50 epochs with continuously decreasing loss and appeared to converge. Validation accuracy was 0.52 — barely above the most-frequent-class baseline for a 400-class dataset with imbalanced species counts. The expected benchmark for ResNet-50 on this architecture was 0.86.

The root cause was that torchlibrosa’s LogmelFilterBank output orientation follows the PANN (Pretrained Audio Neural Networks) convention: time is the height dimension (dimension 2) and mel frequency bins are the width dimension (dimension 3). Image classifiers adapted from ImageNet typically follow the opposite convention for spectrograms: frequency bins as height, time as width. When the ResNet received (batch, 1, 130, 128) instead of (batch, 1, 128, 130), it processed the time axis as if it were the frequency axis and vice versa. Bird calls are defined by their temporal structure: a rising frequency sweep, a rhythmic drumming pattern, or a tonal phrase with a characteristic duration. With time and frequency transposed, a robin’s ascending frequency sweep — a rising diagonal in a correctly oriented spectrogram — became a falling diagonal in the transposed version, indistinguishable from a descending call of a different species. The model could not learn species-discriminative temporal patterns from transposed features, achieving chance-level accuracy despite valid training mechanics. The diagnostic was printing logmel.shape (yielding torch.Size([16, 1, 130, 128])) and comparing with the documented ResNet input expectation ((batch, 1, 128, 130)). The fix was a single call: logmel = logmel_extractor(spec).transpose(2, 3). After transposing and retraining from scratch, accuracy reached 0.85 at epoch 20.

The annotated buggy and fixed pipeline, with shape assertion gate and startup validation:

# Westfield Torchlibrosa Ltd. — torchlibrosa 0.1.0 axis transposition fix
# torchlibrosa 0.1.0; Python 3.9; PyTorch 1.11
# Bird species identification; 15,000 recordings/month; 400 species
#
# Problem: LogmelFilterBank outputs (batch, 1, time_steps, n_mels)
#          ResNet-50 expects (batch, 1, n_mels, time_steps) — freq as height, time as width
#          3-second clips: time_steps=130, n_mels=128 — shape diff of 2 → no RuntimeError
#          Model trains on transposed spectrograms; temporal patterns unrecognizable
#          Validation accuracy 0.52 not 0.86; 4 weeks of hyperparam experiments
# Fix:     logmel.transpose(2, 3) — swap time and frequency dimensions

import torch
import torch.nn as nn
from torchlibrosa.stft import Spectrogram, LogmelFilterBank

SR = 22050
N_FFT = 1024
HOP_LENGTH = 512
WIN_LENGTH = 1024
N_MELS = 128
FMIN = 50
FMAX = 11025
TOP_DB = 80.0

# Shared feature extractors — freeze_parameters=True for fixed feature extraction
spectrogram_extractor = Spectrogram(
    n_fft=N_FFT,
    hop_length=HOP_LENGTH,
    win_length=WIN_LENGTH,
    window='hann',
    center=True,
    pad_mode='reflect',
    freeze_parameters=True,
)

logmel_extractor = LogmelFilterBank(
    sr=SR,
    n_fft=N_FFT,
    n_mels=N_MELS,
    fmin=FMIN,
    fmax=FMAX,
    ref=1.0,
    amin=1e-10,
    top_db=TOP_DB,       # 80.0 dB floor prevents -inf for near-silent recordings
    freeze_parameters=True,
)


# ── BUGGY feature extraction (no axis transposition) ──────────────────────────

def extract_features_buggy(audio: torch.Tensor) -> torch.Tensor:
    """BUGGY: feeds LogmelFilterBank output directly to ResNet without transposing.
    LogmelFilterBank returns (batch, 1, time_steps, n_mels) = (batch, 1, 130, 128)
    ResNet expects (batch, 1, n_mels, time_steps) = (batch, 1, 128, 130)
    Shape diff is 2 — no RuntimeError; conv2d runs on transposed features.
    """
    spec = spectrogram_extractor(audio)  # (batch, 1, time, n_fft//2+1)
    logmel = logmel_extractor(spec)      # (batch, 1, time_steps=130, n_mels=128)
    # BUG: return logmel directly — time and frequency axes transposed relative
    # to ResNet's expected (batch, 1, n_mels=128, time_steps=130)
    return logmel  # (batch, 1, 130, 128) — WRONG orientation for ResNet


# ── FIXED feature extraction ──────────────────────────────────────────────────

def extract_features(audio: torch.Tensor) -> torch.Tensor:
    """FIXED: transpose time and frequency axes after LogmelFilterBank.
    torchlibrosa PANN convention: (batch, 1, time, n_mels)
    ResNet image convention: (batch, 1, freq=n_mels, time)
    """
    spec = spectrogram_extractor(audio)  # (batch, 1, time, n_fft//2+1)
    logmel = logmel_extractor(spec)      # (batch, 1, time_steps, n_mels)

    # FIX: transpose dimensions 2 and 3 — swap time and frequency
    # (batch, 1, time_steps, n_mels) → (batch, 1, n_mels, time_steps)
    logmel = logmel.transpose(2, 3)  # (batch, 1, 128, 130) ✓

    return logmel  # (batch, 1, n_mels=128, time_steps=130) — correct for ResNet


# ── Startup shape assertion ───────────────────────────────────────────────────

def validate_feature_shape(audio_duration_s: float = 3.0,
                            batch_size: int = 1) -> None:
    """
    Assert LogmelFilterBank output shape after transposition matches ResNet input.
    Call once at model initialization — catches axis transposition bugs immediately.
    """
    n_samples = int(SR * audio_duration_s)
    dummy = torch.zeros(batch_size, 1, n_samples)  # (batch, 1, samples)

    spec = spectrogram_extractor(dummy)
    logmel_raw = logmel_extractor(spec)
    logmel_transposed = logmel_raw.transpose(2, 3)

    batch, channels, freq_bins, time_steps = logmel_transposed.shape

    # torchlibrosa PANN convention: raw output is (batch, 1, time, n_mels)
    # After transpose: (batch, 1, n_mels, time) — frequency first
    assert freq_bins == N_MELS, (
        f"After transpose, dim 2 should be n_mels={N_MELS}, got {freq_bins}. "
        "Check that you called logmel.transpose(2, 3) — not logmel.transpose(1, 2). "
        f"Raw LogmelFilterBank output shape: {logmel_raw.shape}"
    )

    # Warn if time and frequency dims are nearly equal (easy to miss swap)
    if abs(freq_bins - time_steps) <= 5:
        import warnings
        warnings.warn(
            f"n_mels={freq_bins} and time_steps={time_steps} differ by only "
            f"{abs(freq_bins - time_steps)} — transposition errors may not raise "
            "RuntimeError. Always assert shape after transpose.",
            UserWarning,
            stacklevel=2,
        )

    print(
        f"[torchlibrosa startup OK] "
        f"Raw LogmelFilterBank: {tuple(logmel_raw.shape)} (batch, 1, time, n_mels). "
        f"After .transpose(2, 3): {tuple(logmel_transposed.shape)} "
        f"(batch, 1, n_mels={freq_bins}, time={time_steps}). Shape verified."
    )

How torchlibrosa’s (batch, 1, time, n_mels) output orientation causes a ResNet to train on transposed spectrograms — why the near-identical shape (130 vs 128) makes the bug invisible — and the one-line fix

The failure combines two design choices from different conventions. torchlibrosa was built to support the PANN (Pretrained Audio Neural Networks) architecture family (Kong et al., 2020), which processes log-mel spectrograms in (batch, channels, time, frequency) orientation — time along the height dimension and mel frequency bins along the width dimension. This matches the natural reading direction of a spectrogram: time left-to-right, frequency bottom-to-top. ResNet, VGG, and EfficientNet classifiers adapted from image recognition for audio typically use the opposite orientation — (batch, channels, frequency, time) — because audio spectrograms are conventionally displayed with frequency on the vertical axis and time on the horizontal axis, and because frequency bins are the spatially meaningful “height” dimension that early conv layers should detect patterns along (harmonic stacks, formants, bird call frequency trajectories). The bug is invisible for several reasons: torch.nn.Conv2d does not check whether the spatial dimensions correspond to time or frequency; it processes any 2D spatial tensor. The near-identical sizes — 130 time steps and 128 mel bins for 3-second clips at 22050 Hz with hop_length=512 — mean the conv kernel sizes, stride, and padding produce nearly the same output tensor dimensions regardless of which axis is treated as height. The loss function (cross-entropy on class logits) has no spatial interpretation: it only cares about the final output class probabilities, not the intermediate spatial representations. Training loss decreases because the model overfits to dataset-level class imbalance and common spectral signatures (mean energy, presence of high-frequency components) that survive transposition; it cannot learn the temporal patterns (frequency sweep direction, rhythmic periodicity, duration) that actually discriminate species. The diagnostic is straightforward: print(logmel.shape) reveals torch.Size([16, 1, 130, 128]) where the last two dimensions should be [16, 1, 128, 130]. The fix is logmel.transpose(2, 3). The startup validation — a forward pass on a dummy tensor followed by an assert that dimension 2 equals N_MELS (not time_steps) — catches the missing transpose before training begins. Westfield Torchlibrosa Ltd. retrained from scratch after the fix; validation accuracy reached 0.85 at epoch 20 and 0.87 at epoch 50, matching the expected benchmark for ResNet-50 on the ornithology dataset. The retainer engagement was 2.0h: 0.5h triage (print logmel.shape = (batch, 1, 130, 128); compare to model input expectation (batch, 1, 128, 130); transposition confirmed); 0.5h root cause (torchlibrosa PANN convention: time-first; ResNet image convention: frequency-first; shape diff 2 → no RuntimeError; temporal features unrecognizable when transposed); 0.5h fix (logmel.transpose(2, 3); startup shape assertion; validate that dim 2 = n_mels after transpose); 0.5h validation (retrain from scratch; accuracy 0.52→0.85 at epoch 20; startup assertion added; 2.0h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →