nnAudio developer on retainer: CQT1992v2 output shape (batch, n_bins, time) — developer calls .T on 3-D tensor transposing to (time, n_bins, batch) — LSTM receives T examples each with 1 feature instead of 1 example with T steps and 84 features — chord recognition 23% not 76% — 30 000 clips per month — 3 weeks — nnAudio developer on monthly retainer

nnAudio 0.3.2 • Python 3.10 • PyTorch 1.13 • CUDA 11.7; CQT1992v2 returns (batch, 84, 130); cqt.T on 3-D tensor reverses all dims to (130, 84, 1) (not (1, 130, 84)); LSTM sees 130 examples per clip each with 1 feature; no RuntimeError raised; • Westfield Nnaudio Ltd. (chord recognition; 24 classes; 30,000 clips/month; accuracy 23% not 76%; 3 weeks; fix: cqt.permute(0, 2, 1); 2.0h retainer engagement)

Westfield Nnaudio Ltd. built a chord recognition API that classified guitar and piano audio clips into 24 chord classes (C major through B minor) for 150 music education platforms processing 30,000 clips per month. The original model had been trained using librosa for CQT feature extraction on CPU. To improve throughput, the developer migrated to nnAudio 0.3.2 for GPU-accelerated CQT computation. The original librosa code produced a 2-D array of shape (n_bins, time) and contained a transpose: cqt = librosa.cqt(...); cqt = cqt.T to convert from (84, 130) to (130, 84) before passing to the LSTM as (seq_len, features). After switching to nnAudio, the developer kept the .T call. nnAudio’s CQT1992v2 returns a 3-D tensor of shape (batch, n_bins, time). The pipeline ran without any exception. After three weeks of training on the nnAudio pipeline, chord recognition accuracy was 23% — near-random for 24 classes — compared to 76% from the librosa baseline.

nnAudio 0.3.2 Spectrogram.CQT1992v2(sr=22050, hop_length=512, fmin=32.70, n_bins=84, output_format=‘Magnitude’) returns a PyTorch tensor of shape (batch, n_bins, time). For a batch of 1 clip of 3 s at 22050 Hz: shape (1, 84, 130). In NumPy, .T on a 2-D array (84, 130) transposes to (130, 84). In PyTorch, .T on a 3-D tensor reverses all three dimensions: (1, 84, 130).T = (130, 84, 1). This is documented in PyTorch: “For a tensor with more than 2 dimensions, .T reverses the order of all axes.” The developer expected .T to swap only the last two axes (n_bins and time), producing (1, 130, 84) — the (batch, seq_len, features) format expected by nn.LSTM(input_size=84, hidden_size=256, batch_first=True). Instead, cqt.T produces (130, 84, 1). With batch_first=True, the LSTM interprets this as batch=130, seq_len=84, input_size=1: 130 independent examples each consisting of a 84-step sequence with a single feature value. The LSTM runs without raising a shape error because all dimensions are valid integers. The loss decreases during training because the LSTM learns to predict from single-feature 84-step sequences — an entirely wrong learning problem. No RuntimeError, no warning, no shape mismatch. The model converges to a local minimum that correctly memorises single-feature patterns from the training set but generalises at near-chance to unseen clips.

The annotated buggy and fixed nnAudio CQT preprocessing pipeline, with shape assertions and correct permute operation:

# Westfield Nnaudio Ltd. — nnAudio 0.3.2 cqt.T shape fix
# nnAudio 0.3.2; Python 3.10; PyTorch 1.13; CUDA 11.7
# Chord recognition; 24 classes; 30,000 clips/month; 3-second clips; sr=22050
#
# Problem: librosa cqt returned (n_bins, time) = (84, 130); cqt.T → (130, 84) OK
#          nnAudio CQT1992v2 returns (batch, n_bins, time) = (1, 84, 130)
#          cqt.T on 3-D tensor reverses ALL dims: (1, 84, 130).T = (130, 84, 1)
#          LSTM(batch_first=True) receives (130, 84, 1) = 130 examples, 1 feature
#          Should be (1, 130, 84) = 1 example, 130 steps, 84 features
#          No RuntimeError; loss decreases (wrong learning problem); accuracy 23%
# Fix:     cqt.permute(0, 2, 1) swaps dims 1 and 2, preserves batch dim 0
#          (1, 84, 130).permute(0, 2, 1) = (1, 130, 84) ✓

import torch
import torch.nn as nn
import nnAudio.Spectrogram as Spec

SR = 22050
HOP_LENGTH = 512
N_BINS = 84
FMIN = 32.70
BINS_PER_OCTAVE = 12
CLIP_SECONDS = 3.0
EXPECTED_T = int(CLIP_SECONDS * SR / HOP_LENGTH) + 1  # ~130 frames

cqt_layer = Spec.CQT1992v2(
    sr=SR,
    hop_length=HOP_LENGTH,
    fmin=FMIN,
    n_bins=N_BINS,
    bins_per_octave=BINS_PER_OCTAVE,
    output_format='Magnitude',
).cuda()


# ── BUGGY CQT preprocessing ──────────────────────────────────────────────────

def extract_cqt_buggy(audio_batch: torch.Tensor) -> torch.Tensor:
    """Extract CQT features — BUGGY: .T reverses all 3 dims."""
    # audio_batch shape: (batch, n_samples)
    cqt = cqt_layer(audio_batch)         # shape: (batch, 84, 130)
    # BUG: .T on a 3-D tensor reverses ALL dimensions
    # (batch, 84, 130).T = (130, 84, batch) — NOT (batch, 130, 84)
    # LSTM(batch_first=True) receives (130, 84, 1) for batch_size=1
    # Interprets as: batch=130, seq_len=84, input_size=1
    # Trains 130 single-feature examples per clip instead of 1 full-CQT example
    return cqt.T                          # shape: (130, 84, batch) — WRONG


# ── FIXED CQT preprocessing ──────────────────────────────────────────────────

def extract_cqt_fixed(audio_batch: torch.Tensor) -> torch.Tensor:
    """Extract CQT features — FIXED: permute(0, 2, 1) swaps only time and bins."""
    # audio_batch shape: (batch, n_samples)
    batch_size = audio_batch.shape[0]
    cqt = cqt_layer(audio_batch)         # shape: (batch, 84, T)

    # Validate output shape before permute
    assert cqt.shape[0] == batch_size, (
        f"CQT batch dim {cqt.shape[0]} != input batch {batch_size}"
    )
    assert cqt.shape[1] == N_BINS, (
        f"CQT n_bins={cqt.shape[1]}, expected {N_BINS}. "
        "Check CQT1992v2(n_bins=...) configuration."
    )
    assert cqt.ndim == 3, (
        f"nnAudio CQT output has {cqt.ndim} dims (expected 3: batch, n_bins, time). "
        "Do NOT call .T — use .permute(0, 2, 1) to swap time and feature axes."
    )

    # FIX: permute(0, 2, 1) swaps dims 1 and 2, preserving batch dim 0
    # (batch, 84, T).permute(0, 2, 1) = (batch, T, 84) ✓
    # LSTM(input_size=84, batch_first=True) expects (batch, seq_len, features)
    cqt_lstm = cqt.permute(0, 2, 1)     # shape: (batch, T, 84) ✓

    assert cqt_lstm.shape == (batch_size, cqt.shape[2], N_BINS), (
        f"After permute: {cqt_lstm.shape}, expected ({batch_size}, {cqt.shape[2]}, {N_BINS})"
    )
    return cqt_lstm


def startup_shape_check() -> None:
    """Verify nnAudio CQT output shape at service startup."""
    n_samples = int(CLIP_SECONDS * SR)
    dummy = torch.randn(1, n_samples).cuda()
    cqt = cqt_layer(dummy)
    expected_shape = (1, N_BINS, EXPECTED_T)
    if cqt.shape != expected_shape:
        raise RuntimeError(
            f"nnAudio CQT1992v2 output shape {tuple(cqt.shape)} != "
            f"expected {expected_shape}. "
            "If migrating from librosa: do NOT use .T — use .permute(0, 2, 1). "
            "librosa cqt returns (n_bins, time) for a single clip; "
            "nnAudio returns (batch, n_bins, time)."
        )
    # Verify permute correctness
    lstm_input = cqt.permute(0, 2, 1)
    assert lstm_input.shape == (1, EXPECTED_T, N_BINS), (
        f"LSTM input shape {tuple(lstm_input.shape)}, expected (1, {EXPECTED_T}, {N_BINS})"
    )

How PyTorch .T reversing all three dimensions, a loss curve that decreases on the wrong learning problem, and a NumPy transpose habit from the librosa migration combine to produce three weeks of incorrect training — and the correct nnAudio pattern for LSTM input preparation

The core failure combines three independent factors: PyTorch .T on an n-D tensor reverses all n dimensions (this is documented but non-obvious to developers who know .T as a 2-D transpose from NumPy and librosa); the LSTM accepts the wrong-shaped input (130, 84, 1) without raising an error because all dimension sizes are valid integers and input_size=1 matches the accidental last dimension; and the training loss decreases because the LSTM does learn a valid (but useless) function — predicting chord labels from individual CQT time-frame magnitude values — which creates the misleading appearance of a training process that is working correctly. The correct operation for swapping the time and feature axes while preserving the batch dimension is cqt.permute(0, 2, 1): this explicitly moves dimension 0 (batch) to position 0, dimension 2 (time) to position 1, and dimension 1 (n_bins) to position 2, producing (batch, time, n_bins) = (batch, T, 84) as required by nn.LSTM(input_size=84, batch_first=True). A startup shape check that creates a known dummy input, runs it through the CQT layer, asserts cqt.shape == (1, N_BINS, EXPECTED_T), then asserts cqt.permute(0, 2, 1).shape == (1, EXPECTED_T, N_BINS), would have caught the error before training started. The migration rule is: librosa returns (n_bins, time) for single clips (2-D); nnAudio returns (batch, n_bins, time) (3-D); the transition requires replacing cqt.T with cqt.permute(0, 2, 1), and any subsequent LSTM, Transformer, or Dense layer must receive the permuted (batch, time, n_bins) tensor. The recovery effort required retraining from scratch (3 weeks of training data was consumed on the wrong model); the retainer engagement was 2.0h: 0.5h triage (shape audit: cqt.shape = (1, 84, 130); cqt.T.shape = (130, 84, 1); LSTM processes 130 examples per clip); 0.5h root cause (PyTorch .T reverses all dims; NumPy .T transposes 2-D; librosa code ported incorrectly; permute(0, 2, 1) required); 0.5h fix (cqt.permute(0, 2, 1); shape assertion; startup check; migration checklist); 0.5h validation (1,000-clip test set; accuracy 76%; per-class confusion matrix correct; 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 →