panns-inference developer on retainer: CNN14 pretrained at 32000 Hz — soundfile loads at 44100 Hz — panns_inference does not resample internally — mel filterbank bins misaligned — average precision 0.431 → 0.183 — 3 weeks — panns-inference developer on monthly retainer

panns_inference 0.1.1 • Python 3.10; PyTorch 1.13; CNN14 pretrained at 32000 Hz; soundfile.read() returns audio at native 44100 Hz; panns_inference does not resample internally; CNN14 mel filterbank bins calibrated for 32000 Hz applied to 44100 Hz data; every frequency component shifted down by factor ≈ 0.726; average precision 0.431 → 0.183; fix: librosa.resample(waveform, orig_sr=sr, target_sr=32000) before inference • Westfield Panns Ltd. (audio content moderation; 30,000 clips/month; 527 AudioSet sound event classes; 3 weeks; 2.0h retainer engagement)

Westfield Panns Ltd. built an audio content moderation service that classified 30,000 audio clips per month into 527 AudioSet sound event categories to flag objectionable content (gunshots, explosions, screaming) in user-uploaded videos. The pipeline used panns_inference (0.1.1) with the CNN14 pretrained model (AudioTagging(checkpoint_path=None, device=‘cpu’)) for sound event detection. All audio was extracted from MP4 video files using FFmpeg and loaded with soundfile.read(path, dtype=‘float32’). The developer had carefully implemented the correct audio shape — stereo downmix to mono with waveform.mean(axis=1), batch dimension with waveform = waveform[None, :], and shape assertion that clipwise_output.shape == (1, 527). All structural checks passed. What the developer had not checked was the sample rate returned by soundfile.read(): it was 44100 Hz, the native rate of the MP4 extraction pipeline. The CNN14 model inside panns_inference was pretrained at 32000 Hz and does not resample internally. The pipeline produced an average precision of 0.183 on the internal evaluation set, against the published CNN14 benchmark of 0.431 on AudioSet. The team spent three weeks adjusting the classification threshold, re-evaluating on different clip subsets, testing CPU versus GPU inference, and checking for PyTorch version incompatibilities.

The root cause was that CNN14’s internal mel filterbank is a fixed component of the pretrained model, calibrated to process audio sampled at 32000 Hz. The filterbank computes 64 mel bins spanning 50 Hz to 14000 Hz using an FFT window of 1024 samples and a hop length of 320 samples, all assuming a 32000 Hz sample rate. panns_inference passes the waveform directly to CNN14’s forward pass without any resampling step. When the developer passed 44100 Hz audio, the filterbank processed it as if it were 32000 Hz: the 1024-sample FFT window, intended to span 1024 / 32000 = 32 ms, spanned only 1024 / 44100 ≈ 23 ms; the hop of 320 samples covered 7.3 ms instead of 10 ms; and — most critically — every frequency in the actual audio was mapped to the wrong mel bin, shifted down by a factor of 32000 / 44100 ≈ 0.726. A dog bark with energy concentrated at 500–2000 Hz was interpreted as occupying the 363–1451 Hz frequency range, shifting it toward the region CNN14 associates with lower-pitched sounds. Frequencies in the actual audio above 14000 Hz × (44100 / 32000) ≈ 19250 Hz — frequencies that exist in 44100 Hz audio but were above the filterbank’s design ceiling — folded into the highest mel bins as spectral noise. The fix was a single line before inference: waveform = librosa.resample(waveform, orig_sr=sr, target_sr=32000). After resampling, average precision recovered from 0.183 to 0.428, within measurement error of the published CNN14 benchmark of 0.431.

The annotated buggy and fixed inference pipeline, with sample rate gate and shape validation:

# Westfield Panns Ltd. — panns_inference 0.1.1 sample rate fix
# panns_inference 0.1.1; Python 3.10; PyTorch 1.13; soundfile 0.12.1; librosa 0.10.1
# Audio content moderation; 30,000 clips/month; 527 AudioSet sound event classes
#
# Problem: CNN14 pretrained at 32000 Hz; soundfile loads at native 44100 Hz
#          panns_inference does NOT resample internally
#          mel filterbank bins misaligned: every frequency shifted down by 0.726×
#          dog bark (500–2000 Hz) → interpreted as 363–1451 Hz
#          average precision 0.431 (CNN14 benchmark) → 0.183 (measured)
#          3 weeks of threshold tuning and GPU/CPU benchmarking
# Fix:     librosa.resample(waveform, orig_sr=sr, target_sr=32000)

import numpy as np
import soundfile as sf
import librosa
from panns_inference import AudioTagging

TARGET_SR = 32000  # CNN14 pretrained sample rate — must resample to this

at = AudioTagging(checkpoint_path=None, device='cpu')


# ── BUGGY inference pipeline ──────────────────────────────────────────────────

def classify_audio_buggy(audio_path: str) -> np.ndarray:
    """BUGGY: loads at native 44100 Hz, skips resample — mel bins misaligned."""
    waveform, sr = sf.read(audio_path, dtype='float32')

    if waveform.ndim == 2:
        waveform = waveform.mean(axis=1)   # stereo → mono

    # BUG: sr is 44100 Hz; CNN14 mel filterbank expects 32000 Hz
    # panns_inference does not resample — processes 44100 Hz data at 32000 Hz scale
    # Every frequency shifted down by 32000/44100 ≈ 0.726
    # Dog bark at 500–2000 Hz processed as 363–1451 Hz; gunshot spectrum misaligned
    waveform = waveform[None, :]  # (n_samples,) → (1, n_samples)
    clipwise_output, _ = at.inference(waveform)
    return clipwise_output[0]  # (527,) class probabilities — WRONG due to sample rate


# ── FIXED inference pipeline ──────────────────────────────────────────────────

def classify_audio(audio_path: str) -> np.ndarray:
    """FIXED: resample to 32000 Hz before inference; validate shape and normalization."""
    waveform, sr = sf.read(audio_path, dtype='float32')

    # Validate normalization: soundfile float32 is [-1.0, 1.0]
    # scipy.io.wavfile returns int16; must divide by 32768.0 before this step
    assert waveform.max() <= 1.1 and waveform.min() >= -1.1, (
        f"[{audio_path}] Audio amplitude out of [-1,1] range: "
        f"min={waveform.min():.3f}, max={waveform.max():.3f}. "
        "If loaded with scipy.io.wavfile, divide int16 by 32768.0."
    )

    if waveform.ndim == 2:
        waveform = waveform.mean(axis=1)   # stereo → mono: (n_samples, 2) → (n_samples,)

    # FIX: resample to 32000 Hz before passing to CNN14
    # CNN14 mel filterbank calibrated for 32000 Hz — do not skip this step
    # even if source audio is reported as 32000 Hz: verify programmatically
    if sr != TARGET_SR:
        waveform = librosa.resample(waveform, orig_sr=sr, target_sr=TARGET_SR)

    waveform = waveform[None, :]  # (n_samples,) → (1, n_samples at 32000 Hz)

    clipwise_output, _ = at.inference(waveform)

    assert clipwise_output.shape == (1, 527), (
        f"Expected clipwise_output shape (1, 527), got {clipwise_output.shape}. "
        "Check panns_inference version and that audio is 2-D (batch, samples)."
    )

    return clipwise_output[0]  # (527,) class probabilities — CORRECT


# ── Startup validation ────────────────────────────────────────────────────────

def validate_sample_rate_sensitivity() -> None:
    """Assert that 32000 Hz and 44100 Hz inputs produce different top predictions."""
    # 1-second 1000 Hz sine wave
    t = np.linspace(0, 1.0, TARGET_SR, endpoint=False, dtype=np.float32)
    sine_32k = np.sin(2 * np.pi * 1000 * t)[None, :]  # (1, 32000)

    t_44k = np.linspace(0, 1.0, 44100, endpoint=False, dtype=np.float32)
    sine_44k = np.sin(2 * np.pi * 1000 * t_44k)[None, :]  # (1, 44100)

    out_32k, _ = at.inference(sine_32k)
    out_44k, _ = at.inference(sine_44k)  # wrong SR — should produce different top class

    top_32k = int(out_32k[0].argmax())
    top_44k = int(out_44k[0].argmax())

    assert top_32k != top_44k, (
        "SAMPLE RATE CHECK FAILED: 32000 Hz and 44100 Hz pure tones produced "
        f"the same top AudioSet class ({top_32k}). "
        "This indicates CNN14 may be resampling internally — verify panns_inference version."
    )

    # With resample, 44k input should match 32k behavior
    sine_44k_resampled = librosa.resample(sine_44k[0], orig_sr=44100, target_sr=TARGET_SR)[None, :]
    out_44k_fixed, _ = at.inference(sine_44k_resampled)
    top_44k_fixed = int(out_44k_fixed[0].argmax())
    assert top_44k_fixed == top_32k, (
        f"Resampled 44k input produces class {top_44k_fixed}, "
        f"but native 32k input produces class {top_32k}. "
        "Resampling should align predictions."
    )

How passing 44100 Hz audio to a CNN14 model pretrained at 32000 Hz produces systematically wrong mel filterbank bin assignments and halves the model’s average precision — and the correct resample-before-inference pattern for panns_inference pipelines

The core failure combines two independent factors. First, panns_inference’s CNN14 model processes audio at whatever sample rate it receives, without raising an error or warning for non-32000 Hz input. The mel filterbank layer is a fixed matrix that maps STFT frequency bins (computed from an FFT window of 1024 samples) to 64 mel bins spanning 50–14000 Hz. This mapping was calibrated during training under the assumption that one sample corresponds to 1/32000 of a second. When audio at 44100 Hz is passed in, one sample still corresponds to 1/44100 of a second, but the filterbank has no way to know this — it applies the same frequency-to-mel mapping regardless, causing every audio frequency to be assigned to the wrong mel bin by a constant factor of 32000/44100 ≈ 0.726. Second, the developer had verified every structurally verifiable aspect of the inference pipeline — the input shape (1, n_samples), the output shape (1, 527), the stereo downmix, and the float32 normalization — but had not verified the sample rate because it was not visible at the inference call site. The sr variable returned by soundfile.read() was used only once (to initialize the FFmpeg extraction parameters, correctly) and then discarded before the inference path. Adding a single assert sr == 32000 immediately before the at.inference() call was the fastest diagnostic step of the engagement: it raised an AssertionError for every clip. The fix was waveform = librosa.resample(waveform, orig_sr=sr, target_sr=32000) inserted between the mono downmix and the batch dimension addition. A startup validation function that tests 32000 Hz and 44100 Hz pure tones against CNN14 and asserts they produce different top predictions was added to the pipeline initialization, so any future configuration change that accidentally bypasses the resample step would immediately surface on startup. After applying the fix, average precision recovered from 0.183 to 0.428, flagging rate for gunshot and explosion classes recovered from near-zero to within 5% of the CNN14 benchmark. The retainer engagement was 2.0h: 0.5h triage (add assert sr == 32000 before inference; all clips fail; sr confirmed 44100 Hz); 0.5h root cause (CNN14 mel filterbank calibrated for 32000 Hz; panns_inference no internal resample; 44100 Hz data produces 0.726× frequency shift; average precision 0.431→0.183); 0.5h fix (add librosa.resample; startup validation function); 0.5h validation (average precision 0.183→0.428; 500-clip eval set; gunshot and explosion recall recovers; startup validation passes; 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 →