openl3 developer on retainer: soundfile.read() returns int16 PCM by default — openl3.get_audio_embedding() receives amplitude values in [−32768, 32767] instead of [−1.0, 1.0] — mel spectrogram saturates — all 512-dimensional embeddings cluster together — cosine similarity returns 0.99 for unrelated audio — 3 weeks — openl3 developer on monthly retainer

openl3 0.4.2 • Python 3.9; openl3.get_audio_embedding(audio, sr) expects float32 in [−1.0, 1.0] • Eastfield Openl3 Ltd. (audio content similarity engine; 50,000 clips/month from 200 music libraries; soundfile.read(path) without dtype returns int16 for 16-bit WAV; openl3 receives [−32768, 32767]; mel spectrogram saturates at all frequencies; all 512-dimensional embeddings cluster together; cosine similarity between unrelated tracks returns 0.97–0.99; similarity search useless; fix: soundfile.read(path, dtype='float32'); 2.0h retainer engagement)

Eastfield Openl3 Ltd. built an audio content similarity engine for music libraries. Libraries uploaded audio clips; the pipeline computed 512-dimensional L3 embeddings using openl3, indexed them in a FAISS index, and exposed a similarity search API so music supervisors could find clips with similar acoustic content. The service processed 50,000 clips per month from 200 independent music libraries. Clips arrived in two formats: 44100 Hz MP3 files (loaded via librosa, which always returns float32 in [−1.0, 1.0]) and 44100 Hz 16-bit PCM WAV files (loaded via soundfile). The engineer who built the pipeline used soundfile.read(path) without specifying a dtype parameter, reasoning that soundfile would handle format detection automatically and return audio in the natural format. This was correct — soundfile did return the native format — but the native format for 16-bit PCM WAV is int16, with amplitude values in the range [−32768, 32767], not the float32 [−1.0, 1.0] that openl3’s L3 neural network model expects. The MP3 path (through librosa) returned correctly-normalized float32 audio and produced valid embeddings. The WAV path (through soundfile without dtype) returned int16 audio and produced saturated, nearly-identical embeddings. 60% of the catalog was 16-bit WAV.

openl3.get_audio_embedding(audio, sr) from openl3 0.4.2 does not validate the amplitude range of its input. It converts the input to float32 internally via audio.astype(np.float32) if the input is not already float32, then passes it to the internal mel spectrogram computation. For int16 input with values in [−32768, 32767], the conversion to float32 preserves the integer values as floating-point numbers: 32767 becomes 32767.0. The mel spectrogram layer calls librosa.feature.melspectrogram(y=audio_f32, sr=sr) where audio_f32 has values in [−32768.0, 32767.0]. librosa computes the Short-Time Fourier Transform of this signal; the STFT amplitudes are proportional to the input amplitudes. For audio 32,768× larger than the expected [−1.0, 1.0] range, the STFT power values are approximately 32768² ≈ 1.07 × 10&sup9; times larger than expected. After conversion to log scale (10 × log⊂10;(S + amin)), this 10&sup9; excess shifts all mel spectrogram values up by approximately 90 dB, compressing all frequency content into a narrow band near the maximum representable value. The L3 model receives a flat, saturated mel spectrogram with no tonal, spectral, or temporal variation — every clip looks acoustically identical to the neural network. The model outputs a 512-dimensional embedding vector, but because the input structure is nearly identical for every clip (all mel bins at maximum), the output vectors are nearly identical. The cosine similarity between any two of these saturated embeddings was 0.97–0.99 regardless of whether the actual audio was classical piano, electronic dance music, or ambient nature sounds. The FAISS index accepted these embeddings without error — they were valid float32 vectors of the correct shape. The similarity search returned every clip as “highly similar” to every query. The discovery service returned the same 10 tracks for every user query regardless of their listening history. The symptom appeared three weeks after the service launched, when enough 16-bit WAV clips had been ingested to make the saturation pattern visible in customer support tickets: “recommendations never change regardless of what I play.”

The annotated buggy and fixed openl3 audio embedding pipeline, with correct amplitude normalization and embedding quality monitoring:

# Eastfield Openl3 Ltd. — openl3 0.4.2 int16 amplitude normalization fix
# openl3 0.4.2; Python 3.9
# audio content similarity engine; 50,000 clips/month from 200 music libraries
# source: 44100 Hz 16-bit PCM WAV (60%) and 44100 Hz MP3 (40%)
# Problem: soundfile.read() returns int16 for 16-bit WAV (range [-32768, 32767])
#          openl3.get_audio_embedding() receives out-of-range amplitude values
#          mel spectrogram saturates at all frequencies
#          all 512-dimensional embeddings cluster together
#          cosine similarity between unrelated clips: 0.97-0.99
# Fix: soundfile.read(path, dtype='float32') — normalizes int16 to [-1.0, 1.0]

import numpy as np
import soundfile
import librosa
import openl3
import faiss

CONTENT_TYPE   = 'music'
EMBEDDING_SIZE = 512
HOP_SIZE       = 0.1   # seconds per frame


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

def embed_clip_buggy(path: str) -> np.ndarray:
    """
    BUG: soundfile.read() without dtype returns int16 for 16-bit WAV.
    int16 values in [-32768, 32767] passed to openl3.get_audio_embedding().
    Mel spectrogram saturates — L3 model produces near-identical embeddings.
    Cosine similarity between unrelated clips: 0.97-0.99.
    Similarity search returns entire catalog as 'highly similar'.
    """
    # BUG: no dtype — returns (int16_array, int) for 16-bit WAV
    audio, sr = soundfile.read(path)
    # audio.dtype = int16, audio.max() ≈ 32767 for typical audio
    # For MP3 (via librosa): float32, max ≈ 0.9 — works correctly
    # For 16-bit WAV: int16, max ≈ 32767 — will saturate mel spectrogram

    emb, ts = openl3.get_audio_embedding(
        audio, sr,
        hop_size=HOP_SIZE,
        content_type=CONTENT_TYPE,
        embedding_size=EMBEDDING_SIZE,
    )
    # emb.shape = (n_frames, 512)
    # For 16-bit WAV: all embeddings near-identical; cosine similarity ~0.99
    return emb.mean(axis=0)   # (512,) — but semantically meaningless for WAV


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

def load_audio_normalized(path: str) -> tuple:
    """
    Load audio as float32 normalized to [-1.0, 1.0] regardless of source format.
    soundfile with dtype='float32': normalizes int16/int24/int32 PCM to [-1.0, 1.0].
    Returns (audio: float32 1-D array, sr: int).
    """
    ext = path.rsplit('.', 1)[-1].lower()
    if ext in ('wav', 'flac', 'ogg', 'aiff', 'aif'):
        # soundfile normalizes int16/int24/int32 to [-1.0, 1.0] with dtype='float32'
        audio, sr = soundfile.read(path, dtype='float32', always_2d=False)
        if audio.ndim > 1:
            audio = audio.mean(axis=1)   # stereo → mono
    else:
        # librosa always returns float32 in [-1.0, 1.0] with internal resampling
        audio, sr = librosa.load(path, sr=None, mono=True, dtype=np.float32)
    return audio, sr


def validate_amplitude(audio: np.ndarray, path: str) -> None:
    """
    Raise ValueError if audio amplitude is outside the expected range.
    int16 PCM values would have max ~32767; float32 normalized max ~1.0.
    Threshold of 2.0 catches int16 input (even clipped) while allowing
    slight over-normalized float32 audio up to 2x full scale.
    """
    max_amp = np.abs(audio).max()
    if max_amp > 2.0:
        raise ValueError(
            f"Audio amplitude {max_amp:.1f} exceeds expected range [-1.0, 1.0] "
            f"for {path}. Expected float32 normalized audio (max ~1.0); got "
            f"values suggesting int16 PCM (max ~32767) or un-normalized input. "
            f"Use soundfile.read(path, dtype='float32') to normalize on load."
        )


def embed_clip_fixed(path: str) -> np.ndarray:
    """
    FIX: load as float32 normalized to [-1.0, 1.0] before openl3 embedding.
    Validate amplitude range before embedding.
    Resample to 22050 Hz if needed (openl3 resamples internally but
    pre-resampling avoids repeated internal resampling at scale).
    """
    audio, sr = load_audio_normalized(path)
    validate_amplitude(audio, path)   # raises ValueError for int16 input

    # Pre-resample to 22050 Hz (openl3's internal model sample rate)
    if sr != 22050:
        audio = librosa.resample(audio, orig_sr=sr, target_sr=22050)
        sr = 22050

    emb, ts = openl3.get_audio_embedding(
        audio, sr,
        hop_size=HOP_SIZE,
        content_type=CONTENT_TYPE,
        embedding_size=EMBEDDING_SIZE,
    )
    track_emb = emb.mean(axis=0).astype(np.float32)   # (512,)

    # Normalize for cosine similarity (FAISS IndexFlatIP with normalized vectors)
    norm = np.linalg.norm(track_emb)
    if norm < 1e-10:
        raise RuntimeError(
            f"Embedding norm near zero for {path}. "
            "Audio may be silent or corrupted."
        )
    return track_emb / norm   # unit vector in 512-D space


# ── Embedding quality monitor ─────────────────────────────────────────────────

def check_embedding_quality(index: faiss.IndexFlatIP, n_sample: int = 100) -> float:
    """
    Compute mean cosine similarity of n_sample random embedding pairs.
    For correctly-computed music embeddings: mean similarity ~0.15-0.45.
    For saturated mel spectrogram embeddings: mean similarity ~0.97-0.99.
    Raises RuntimeError if mean similarity exceeds alert threshold.
    """
    n_total = index.ntotal
    if n_total < 2:
        return 0.0
    idx_a = np.random.choice(n_total, n_sample, replace=False)
    idx_b = np.random.choice(n_total, n_sample, replace=False)
    vecs_a = index.reconstruct_batch(idx_a)   # (n_sample, 512)
    vecs_b = index.reconstruct_batch(idx_b)   # (n_sample, 512)
    similarities = (vecs_a * vecs_b).sum(axis=1)   # dot product of unit vectors = cosine
    mean_sim = float(similarities.mean())
    if mean_sim > 0.90:
        raise RuntimeError(
            f"Embedding quality alert: mean pairwise cosine similarity "
            f"{mean_sim:.3f} exceeds threshold 0.90. This suggests saturated "
            "mel spectrograms from out-of-range audio input (e.g., int16 PCM "
            "passed to openl3 without float32 normalization). "
            "Re-check audio loading with validate_amplitude()."
        )
    return mean_sim

How soundfile’s format-preserving default, openl3’s unvalidated amplitude input, and mel spectrogram saturation combine to make all 512-dimensional embeddings nearly identical — and the correct float32 normalization pattern for production openl3 deployments

The soundfile.read(path) format-preserving default is a correct design decision for a general-purpose audio I/O library: when you don’t specify dtype, soundfile returns the audio in the format in which it was stored, without silent data loss from premature conversion. For a 16-bit PCM WAV file, this means int16 — the natural integer representation of 16-bit PCM samples with 65536 possible values in the range [−32768, 32767]. This default is appropriate for audio editing tools, codec development, and bit-exact round-tripping. It is inappropriate for machine learning pipelines, where models are trained on float32 audio normalized to [−1.0, 1.0] and produce meaningless outputs for inputs at other scales. The collision between soundfile’s format-preserving default and openl3’s training-distribution assumption is the root cause of the bug. openl3 does not validate amplitude range because it assumes the caller has already normalized the audio — this assumption is documented (openl3’s README uses librosa.load() in its examples, which always returns float32 in [−1.0, 1.0]), but the library does not enforce it programmatically. The mel spectrogram saturation happens because log-scale compression is effective over its designed dynamic range (typically −80 dB to 0 dB for normalized audio) but collapses when the input exceeds that range: for int16 audio 32768× too large, the entire spectrogram is shifted ≈90 dB above the top of the designed range, compressing all tonal and temporal variation into a narrow band near the maximum representable value. The L3 model maps this information-free saturated spectrogram to a point near the center of the 512-dimensional embedding space, and all such points are nearly identical, so cosine similarity is near 1.0 for all pairs. The correct normalization is soundfile.read(path, dtype='float32') — soundfile scales int16, int24, and int32 PCM to [−1.0, 1.0] when dtype='float32' is specified, dividing by the maximum representable value for the original bit depth (32767 for int16, 8388607 for int24, 2147483647 for int32). The amplitude validation gate — raising ValueError when np.abs(audio).max() > 2.0 — catches any future loading path that returns un-normalized audio before the embedding is computed, preventing silent index corruption. The embedding quality monitor — checking that the mean pairwise cosine similarity of a random sample stays below 0.90 — detects the saturation pattern at the index level if any audio somehow passes the per-clip validation. The retainer engagement was 2.0h: 0.5h triage (cosine similarity heatmap: 0.97–0.99 for all pairs; sample 100 embedding vectors: all values in [0.09, 0.11] range; note that MP3-sourced clips have diverse embeddings but WAV-sourced clips do not); 0.5h root cause (compare soundfile.read(wav_path) vs soundfile.read(wav_path, dtype='float32'): first returns int16 max = 27891, second returns float32 max = 0.851; confirm openl3 does not validate amplitude range in source); 0.5h fix (dtype='float32' in soundfile.read(); amplitude validation; embedding quality monitor; rebuild WAV-sourced clips in FAISS index); 0.5h validation (1,000-clip test: cosine similarity distribution 0.12–0.42; discovery test: 20 queries return acoustically similar results; mean pairwise similarity drops from 0.98 to 0.26; 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 →