stempeg developer on retainer: read_stems() returns (n_stems, n_samples, n_channels) — developer expects (n_samples, n_channels) — stems[:, 0] extracts shape (5, 2) not (n_samples,) — librosa processes 2-sample signal silently — 8 000 STEM files produce zero feature vectors — 3 weeks — stempeg developer on monthly retainer

stempeg 0.3.0 • Python 3.9; stempeg.read_stems(path) returns ndarray shape (n_stems, n_samples, n_channels) • Eastfield Stempeg Ltd. (DJ music analysis platform; 8,000 STEM files/month from 400 DJs using NI Traktor; stems.shape = (5, 882000, 2) for 20-second 44100 Hz stereo 4-stem file; developer expects (n_samples, n_channels); writes mono = stems[:, 0]; stems[:, 0] = stems[:, 0, :] = shape (5, 2) — first sample of each stem, both channels; librosa.feature.mfcc(y=shape(5,2), sr=44100) processes 5-channel 2-sample signal; near-zero MFCCs for all files; 8,000 STEM files/month produce identical zero feature vectors; recommendation engine returns same 20 tracks for all DJs for 3 weeks; fix: audio = stems[0]; mono = audio.mean(axis=-1); 1.5h retainer engagement)

Eastfield Stempeg Ltd. built a DJ music analysis platform for a streaming service targeting professional DJs and producers. DJs uploaded STEM files in the Native Instruments Traktor format — .stem.mp4 files containing a full mix track plus four individual stem tracks (drums, bass, melody/lead, and other/effects) — and the platform extracted audio features to power a similarity-based recommendation engine. The pipeline processed 8,000 STEM files per month from 400 DJs. The feature extraction stage used stempeg 0.3.0 to read the STEM files and librosa for MFCC extraction. The engineer who built the extraction pipeline was familiar with soundfile.read(), which returns a numpy array of shape (n_samples, n_channels) for stereo audio. When switching to stempeg.read_stems(), they read the return value as stems, rate = stempeg.read_stems(path) and assumed stems had the same shape convention as soundfile.read(): (n_samples, n_channels). The actual shape returned by stempeg.read_stems() is (n_stems, n_samples, n_channels) — a 3D array with the number of audio streams as the leading dimension. For a typical 20-second 44100 Hz stereo Traktor 4-stem file: stems.shape = (5, 882000, 2) (5 streams: 1 full mix + 4 stems; 882,000 samples; 2 channels).

The extraction pipeline called mono = stems[:, 0] to extract what the engineer intended as the left channel of a (n_samples, n_channels) array — a 1D array of n_samples values. In numpy, for a 3D array with shape (5, 882000, 2), the expression stems[:, 0] is equivalent to stems[:, 0, :]: select all elements along axis 0 (the 5 stems), select index 0 along axis 1 (the 882,000 samples axis), and select all elements along axis 2 (the 2 channels). The result is an array of shape (5, 2) — the value of sample index 0 across all five stems and both channels: 10 floating-point numbers representing a single point in time, not 882,000 audio samples. When librosa.feature.mfcc(y=stems[:, 0], sr=44100, n_mfcc=20) was called with y having shape (5, 2), librosa interpreted the shape as (..., n_samples) where the last axis is the sample dimension: 5 channels, 2 samples each. With center=True (the librosa default), the input is zero-padded to n_fft // 2 on each side, allowing signals shorter than n_fft to be processed without raising ValueError. The resulting MFCC had shape (20, 5, 1): 20 coefficients, 5 channels, 1 time frame. The pipeline called mfccs.flatten()[:20] to produce a 20-element feature vector, which returned the first 20 values from the flattened (20, 5, 1) array: values computed from zero-padded input at the first sample of each of the 5 stems, all near zero. No exception was raised. The pipeline returned a 20-element near-zero vector for every STEM file processed. The recommendation engine computed cosine similarity between these near-zero vectors, producing NaN (0 ÷ 0 = undefined), which the system’s NaN guard replaced with 0.0 similarity. With all pairwise similarities at 0.0, the recommendation engine fell back to returning the globally top-20 most-played tracks for every DJ query. 400 DJs received identical recommendations regardless of their upload history. The issue was attributed to “model overfitting” for the first two weeks, then to “data quality issues in the DJs’ uploads,” before the third-week investigation printed stems.shape and found (5, 882000, 2) instead of the expected (882000, 2).

The annotated buggy and fixed stempeg feature extraction pipeline, with shape assertions:

# Eastfield Stempeg Ltd. — stempeg 0.3.0 read_stems() shape mismatch fix
# stempeg 0.3.0; Python 3.9; NI Traktor 4-stem STEM files
# 8,000 STEM files/month from 400 DJs; 44100 Hz stereo, n_stems=5
# stems.shape = (5, 882000, 2) for a 20-second 4-stem stereo file
# Problem: developer expects (n_samples, n_channels) based on soundfile.read()
#          stems[:, 0] = shape (5, 2) — first sample of each stem, not left channel
#          librosa.feature.mfcc(y=shape(5,2)) → near-zero (20,) vector
#          No exception raised — silent wrong output
#          8,000 files/month produce identical zero feature vectors
# Fix: audio = stems[0]; mono = audio.mean(axis=-1)

import numpy as np
import stempeg
import librosa


# STEM index constants for NI Traktor 4-stem format
STEM_FULL_MIX = 0   # Full stereo mix (all instruments combined)
STEM_DRUMS    = 1   # Drums + percussion stem
STEM_BASS     = 2   # Bass stem
STEM_MELODY   = 3   # Melody / lead stem
STEM_OTHER    = 4   # Other / effects stem


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

def extract_mfccs_buggy(path: str) -> np.ndarray:
    """
    BUG: stempeg.read_stems() returns (n_stems, n_samples, n_channels).
    Developer expects (n_samples, n_channels) like soundfile.read().

    stems.shape = (5, 882000, 2) for a 20-second 44100 Hz stereo 4-stem file.

    stems[:, 0]:
      - Developer intends: left channel of (n_samples, n_channels) → shape (882000,)
      - Actual result: index 0 along axis 1 (n_samples axis) = shape (5, 2)
        (the value of sample index 0 for all 5 stems and 2 channels — 10 numbers)

    librosa.feature.mfcc(y=shape(5,2), sr=44100, n_mfcc=20):
      - librosa interprets (5, 2) as 5 channels × 2 samples
      - center=True zero-pads → n_frames=1
      - output shape: (20, 5, 1) — near-zero values
      - No ValueError raised — silent wrong output

    mfccs.flatten()[:20]:
      - Returns [~0, ~0, ..., ~0] — 20 near-zero values
      - Identical for every STEM file
      - Cosine similarity between zero vectors = NaN → fallback = top-20 global tracks
      - 8,000 files/month: same 20 tracks recommended for all 400 DJs
    """
    stems, rate = stempeg.read_stems(path)
    # stems.shape: (5, 882000, 2) — NOT (882000, 2)
    mono = stems[:, 0]      # BUG: shape (5, 2), not (882000,)
    mfccs = librosa.feature.mfcc(y=mono, sr=rate, n_mfcc=20)
    # mfccs.shape: (20, 5, 1) — near-zero values computed on 2-sample signal
    return mfccs.flatten()[:20]   # returns [~0, ~0, ..., ~0] for every file


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

def extract_mfccs_fixed(path: str,
                         stem_index: int = STEM_FULL_MIX,
                         n_mfcc: int = 20) -> np.ndarray:
    """
    FIX: select a single stem first, then average channels to mono.

    stempeg.read_stems() shape: (n_stems, n_samples, n_channels)
      stems[0]: full mix — shape (n_samples, n_channels) = (882000, 2)
      stems[1]: drums     — shape (n_samples, n_channels) = (882000, 2)
      stems[2]: bass      — shape (n_samples, n_channels) = (882000, 2)
      stems[3]: melody    — shape (n_samples, n_channels) = (882000, 2)
      stems[4]: other     — shape (n_samples, n_channels) = (882000, 2)

    audio.mean(axis=-1): average last axis (n_channels=2) → shape (n_samples,)
    """
    stems, rate = stempeg.read_stems(path)

    # Validate shape before indexing
    assert stems.ndim == 3, (
        f"stempeg.read_stems() expected ndim=3 (n_stems, n_samples, n_channels), "
        f"got shape={stems.shape}. "
        f"If shape is 2D, the file may have a single stem or use a different encoding."
    )
    n_stems, n_samples, n_channels = stems.shape
    assert stem_index < n_stems, (
        f"stem_index={stem_index} out of range for file with n_stems={n_stems}. "
        f"Use STEM_FULL_MIX=0, STEM_DRUMS=1, STEM_BASS=2, STEM_MELODY=3, STEM_OTHER=4."
    )

    audio = stems[stem_index]           # shape: (n_samples, n_channels) = (882000, 2)
    mono = audio.mean(axis=-1)          # average stereo → mono: shape (n_samples,) = (882000,)

    assert mono.ndim == 1 and mono.shape[0] == n_samples, (
        f"Expected mono shape ({n_samples},), got {mono.shape}. "
        f"Check stem_index={stem_index} and stems.shape={stems.shape}."
    )

    mfccs = librosa.feature.mfcc(y=mono, sr=rate, n_mfcc=n_mfcc)
    # mfccs.shape: (n_mfcc, n_frames) = (20, ~1721) for 20-second file at hop_length=512
    return mfccs.mean(axis=-1)   # aggregate over time: shape (n_mfcc,) = (20,)


# ── Shape reference ───────────────────────────────────────────────────────────
#
# stempeg.read_stems(path) → (stems_array, rate)
#   stems_array.shape: (n_stems, n_samples, n_channels)
#   n_stems:    5 for NI Traktor 4-stem (mix + drums + bass + melody + other)
#               2 for 2-stem (mix + single stem track)
#   n_samples:  duration_seconds × rate
#   n_channels: 2 (stereo) or 1 (mono)
#
# Common indexing mistakes vs correct usage:
#   stems[:, 0]        → shape (n_stems, n_channels) at sample 0  — WRONG
#   stems[0, :, 0]     → shape (n_samples,) — full mix left channel — CORRECT
#   stems[0]           → shape (n_samples, n_channels) — full mix stereo — CORRECT
#   stems[0].mean(-1)  → shape (n_samples,) — full mix mono — CORRECT
#
# stempeg vs soundfile shape comparison:
#   soundfile.read(path)       → (n_samples, n_channels)  2D
#   librosa.load(path, mono=0) → (n_channels, n_samples)  2D, channels-first
#   stempeg.read_stems(path)   → (n_stems, n_samples, n_channels)  3D, stems-first

How stempeg’s stems-first array layout, numpy’s multi-axis indexing, and librosa’s center-padding produce a silent wrong-output failure when the shape convention is mistaken for soundfile’s convention — and the correct indexing pattern for per-stem feature extraction

The stempeg shape (n_stems, n_samples, n_channels) is the natural layout for STEM files because a STEM file’s fundamental structure is a collection of independent audio streams: the leading dimension identifies which stream, and the remaining two dimensions describe the audio within that stream. This hierarchy is different from the soundfile convention — (n_samples, n_channels) — and from the librosa/PyTorch convention — (n_channels, n_samples) — because stempeg has an extra outer dimension that neither soundfile nor librosa has. The analogy that misleads engineers is treating stempeg.read_stems() like soundfile.read(): both return (array, rate), but the array has a different number of dimensions. The stems[:, 0] expression is the natural translation of “give me column 0 (the left channel) of a (n_samples, n_channels) array,” and it fails silently for two reasons. First, in numpy, a[:, 0] for a 3D array selects index 0 from the second axis, not the last axis — there is no error, just a different result than intended. Second, librosa’s center-padding allows the resulting 2-sample signal to pass through MFCC computation without raising ValueError, producing a near-zero output of the wrong shape rather than failing loudly. The shape assertion assert mono.ndim == 1 immediately after the channel-averaging step costs negligible runtime and catches the error at the point of incorrect indexing rather than at the point of incorrect output, making the diagnostic unambiguous: the assertion prints the actual shape (5, 2), directly identifying the wrong axis. The fix — audio = stems[0]; mono = audio.mean(axis=-1) — is two operations that together enforce the correct access pattern: first select a specific stem by its leading-dimension index, reducing the 3D array to a 2D (n_samples, n_channels) array; then average the trailing channel dimension to mono. This is the pattern that generalizes correctly across all five stems and both mono and stereo STEM files. The retainer engagement was 1.5h: 0.5h triage (all 8,000 feature vectors near-zero; print stems.shape: (5, 882000, 2); print stems[:, 0].shape: (5, 2) — wrong; trace the indexing path: [:, 0] for a 3D array selects axis 1 index 0, not axis 2 index 0); 0.5h root cause (stempeg (n_stems, n_samples, n_channels) shape confirmed in stempeg documentation; stems[:, 0] numpy behavior confirmed by interactive array inspection; librosa center-padding confirmed to prevent ValueError for 2-sample input); 0.25h fix (audio = stems[0]; mono = audio.mean(axis=-1); add shape assertions); 0.25h validation (20-file test: mfccs.shape = (20, 1721) for 20-second files; feature vectors diverse — cosine similarity varies from 0.12 to 0.89 across file pairs; recommendation engine returns diverse results; 1.5h 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 →