audiomentations developer on retainer: TimeStretch(leave_length_unchanged=False) produces variable-length clips — DataLoader collate_fn RuntimeError on 15% of batches — broad except silently skips batches — model trains on 85% of data — accuracy 0.76 instead of 0.89 — 3 weeks — audiomentations developer on monthly retainer

audiomentations 0.33.0 • Python 3.9 • PyTorch 1.12; TimeStretch(min_rate=0.8, max_rate=1.25, leave_length_unchanged=False, p=1.0); rate=0.8 stretches 88 200-sample clip to 110 250 samples; rate=1.25 compresses to 70 560 samples; • Westfield Audiomentations Ltd. (keyword spotting training pipeline; 500,000 clips/day; torch.stack() raises RuntimeError on variable-length tensors; broad except RuntimeError: continue skips 15% of batches; model accuracy 0.76 vs expected 0.89; 3 weeks of hyperparameter tuning; fix: leave_length_unchanged=True; 2.0h retainer engagement)

Westfield Audiomentations Ltd. built a keyword spotting model for a smart speaker product, training on 500,000 labelled audio clips per day using an in-house PyTorch training pipeline. The model was a CNN-LSTM architecture designed to detect a 2-second wake-word utterance from 2-second (88 200-sample at 44 100 Hz) audio windows. Data augmentation was implemented using audiomentations 0.33.0, with a Compose pipeline containing TimeStretch, AddGaussianNoise, and PitchShift transforms applied in the PyTorch Dataset.__getitem__ method. The developer configured TimeStretch(min_rate=0.8, max_rate=1.25, leave_length_unchanged=False, p=1.0), intending the model to “hear the full stretched audio” rather than a version cropped or padded to the original 2-second length. At the same session the developer added a broad except RuntimeError: continue clause around the training loop’s batch step, noting there had been occasional DataLoader worker crashes during development. The model was trained for 20 epochs and achieved validation accuracy 0.76 — 13 percentage points below the 0.89 baseline established by an earlier run without augmentation.

audiomentations.TimeStretch applies pitch-preserving time stretching by calling pyrubberband under the hood. With leave_length_unchanged=False, the output length is proportional to the input length divided by the stretch rate: a 88 200-sample clip stretched at rate=0.8 becomes 88 200 / 0.8 = 110 250 samples (2.5 seconds); the same clip compressed at rate=1.25 becomes 88 200 / 1.25 = 70 560 samples (1.6 seconds). With p=1.0 (always apply), every clip in the dataset received a randomly-drawn rate from [0.8, 1.25] producing a unique length. The PyTorch DataLoader with batch_size=32 assembled 32 clips per batch by calling the default collate_fn, which uses torch.stack() to combine a list of 1-D tensors into a 2-D tensor of shape (32, N). torch.stack() requires all input tensors to have identical shapes: when the 32 clips included a mix of lengths — some 70 560, some 88 200, some 95 000, some 110 250 — the call raised RuntimeError: stack expects each tensor to be equal size, but got [88200] at entry 0 and [70560] at entry 2. This RuntimeError was caught by the broad except RuntimeError: continue clause, which silently skipped the entire batch without logging any warning. The probability that all 32 clips drawn from a batch had identical lengths (all rates drawn within the same rounding bucket) was approximately 85%; batches with any length mix raised RuntimeError and were skipped. The model therefore trained on only 85% of batches — 425,000 clips per day instead of 500,000 — equivalent to removing 2 of every 13 training examples. Validation was run on un-augmented clips (correctly, without TimeStretch), so validation batches always had uniform length and the RuntimeError never appeared in the validation loop, masking the problem for 3 weeks. The accuracy degradation of 13 percentage points was attributed to insufficient augmentation intensity, insufficient learning rate, or model capacity, and the team spent 3 weeks adjusting these hyperparameters. The issue was identified when a developer added per-epoch batch count logging: logger.info(f'Epoch {epoch}: batches processed: {batches_processed}') printed 85 instead of the expected 100 on the first run, revealing that 15% of batches were silently dropped each epoch.

The annotated buggy and fixed audiomentations TimeStretch pipeline, with batch count validation:

# Westfield Audiomentations Ltd. — audiomentations 0.33.0 leave_length_unchanged fix
# audiomentations 0.33.0; Python 3.9; PyTorch 1.12
# Keyword spotting training pipeline; 500,000 clips/day; 2-second clips at 44100 Hz
#
# Problem: TimeStretch(leave_length_unchanged=False) produces variable-length output
#          rate=0.8 → 110250 samples (2.5s); rate=1.25 → 70560 samples (1.6s)
#          DataLoader collate_fn: torch.stack() raises RuntimeError on shape mismatch
#          broad except RuntimeError: continue silently skips 15% of batches
#          model trains on 85% of data; accuracy 0.76 vs expected 0.89
# Fix:     TimeStretch(leave_length_unchanged=True) trims/pads to input length

import logging
import numpy as np
import torch
from torch.utils.data import Dataset
from audiomentations import Compose, TimeStretch, AddGaussianNoise, PitchShift

logger = logging.getLogger(__name__)

SAMPLE_RATE = 44100
CLIP_LENGTH = 88200  # 2 seconds at 44100 Hz


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

augment_buggy = Compose([
    TimeStretch(
        min_rate=0.8,
        max_rate=1.25,
        leave_length_unchanged=False,  # BUG: variable-length output
        p=1.0,
    ),
    AddGaussianNoise(min_amplitude=0.001, max_amplitude=0.015, p=0.5),
])


class KeywordDatasetBuggy(Dataset):
    def __init__(self, clips: list, labels: list):
        self.clips = clips
        self.labels = labels

    def __getitem__(self, idx: int):
        audio = self.clips[idx]  # np.float32, shape (88200,)
        augmented = augment_buggy(samples=audio, sample_rate=SAMPLE_RATE)
        # BUG: augmented.shape may be (70560,), (88200,), or (110250,)
        # torch.stack() on a batch will raise RuntimeError on shape mismatch
        return torch.from_numpy(augmented), self.labels[idx]

    def __len__(self):
        return len(self.clips)


def train_epoch_buggy(loader, model, optimiser, loss_fn) -> float:
    batches_processed = 0
    for audio, labels in loader:  # collate_fn raises RuntimeError on mismatch
        try:
            logits = model(audio)
            loss = loss_fn(logits, labels)
            loss.backward()
            optimiser.step()
            batches_processed += 1
        except RuntimeError:
            continue   # BUG: silently skips 15% of batches — shape-mismatch error
            # masked as "DataLoader worker crash" — actual cause never investigated

    # NOTE: no logging of batches_processed — silent data loss invisible
    return batches_processed


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

augment_fixed = Compose([
    TimeStretch(
        min_rate=0.8,
        max_rate=1.25,
        leave_length_unchanged=True,   # FIX: output trimmed/padded to input length
        p=1.0,
    ),
    AddGaussianNoise(min_amplitude=0.001, max_amplitude=0.015, p=0.5),
])


class KeywordDatasetFixed(Dataset):
    def __init__(self, clips: list, labels: list, augment: bool = True):
        self.clips = clips
        self.labels = labels
        self.augment = augment  # False for validation/test datasets

    def __getitem__(self, idx: int):
        audio = self.clips[idx]  # np.float32, shape (88200,)
        if self.augment:
            audio = augment_fixed(samples=audio, sample_rate=SAMPLE_RATE)
        # audio.shape is always (88200,) — leave_length_unchanged=True guarantees this
        assert audio.shape == (CLIP_LENGTH,), (
            f"Unexpected clip length {audio.shape[0]} != {CLIP_LENGTH}. "
            "Augmentation must not change clip length for fixed-batch training. "
            "Check leave_length_unchanged=True in all TimeStretch transforms."
        )
        return torch.from_numpy(audio), self.labels[idx]

    def __len__(self):
        return len(self.clips)


def train_epoch_fixed(loader, model, optimiser, loss_fn,
                      expected_batches: int) -> float:
    batches_processed = 0
    for audio, labels in loader:
        # No try/except — shape errors must surface immediately, not be swallowed
        logits = model(audio)
        loss = loss_fn(logits, labels)
        loss.backward()
        optimiser.step()
        batches_processed += 1

    if batches_processed < expected_batches * 0.99:
        logger.error(
            f"Only {batches_processed}/{expected_batches} batches processed. "
            "Missing batches indicate dropped data. "
            "Check for RuntimeError handlers in training loop or DataLoader workers."
        )
        raise RuntimeError(
            f"Batch count mismatch: {batches_processed} processed, "
            f"{expected_batches} expected. Investigate DataLoader or augmentation pipeline."
        )

    logger.info(f"Epoch complete: {batches_processed}/{expected_batches} batches.")
    return batches_processed

How leave_length_unchanged=False, the default torch.stack() collate, a broad except RuntimeError, and no batch-count logging combine to silently train on 85% of data for 3 weeks — and the correct TimeStretch configuration for fixed-batch training pipelines

The core issue is a chain of four independent design decisions that each seemed reasonable in isolation but combined to produce silent data loss. First: leave_length_unchanged=False was set intentionally, with the rationale that the model should hear the full stretched audio — a reasonable goal. Second: PyTorch’s default collate_fn uses torch.stack(), which is the correct tool for fixed-length input but raises immediately on variable-length input — correct behavior that surface a problem clearly. Third: a broad except RuntimeError: continue was added to suppress unrelated DataLoader worker crashes during development — a common and often harmless pattern that silenced the shape-mismatch error. Fourth: no per-epoch batch count logging was present, so the 15% batch drop rate was invisible in training logs. Each choice was individually defensible; together they formed a failure mode that evaded detection for 3 weeks of active model development. The 15% skip rate arises from probability: with batch_size=32 and each clip independently drawing a rate from [0.8, 1.25], the probability that all 32 clips happen to have the exact same quantised output length is approximately 85% (rates cluster near 1.0 since librosa.effects.time_stretch returns integer-quantised output lengths for most inputs). The accuracy impact of 0.76 vs 0.89 (13 percentage points, 15% less data) is consistent with published learning-curve research on keyword spotting models, where removing 15% of training data degrades accuracy by 8–15 percentage points depending on data diversity. The fix is a one-parameter change: leave_length_unchanged=True causes audiomentations to call librosa.effects.time_stretch and then trim the output to exactly the input length using output[:input_length] for compressed audio and zero-pad with np.pad for stretched audio. The resulting clip always has exactly 88 200 samples regardless of the stretch rate, making torch.stack() always succeed. The secondary fix is removing the broad except RuntimeError: continue from the training loop and adding per-epoch batch count assertions. The first training run with the fix processed all 100 batches per epoch and reached validation accuracy 0.88 after 5 epochs — confirming the model architecture and augmentation strategy were correct; only the variable-length batching had been the obstacle. The retainer engagement was 2.0h: 0.5h triage (per-epoch logging: 85/100 batches; isolate RuntimeError to collation step); 0.5h root cause (TimeStretch leave_length_unchanged=False; rate=0.8 → 110250 samples; torch.stack shape mismatch; broad except silently skips 15%); 0.5h fix (leave_length_unchanged=True; remove broad except; add batch count assertion); 0.5h validation (5-epoch retrain; accuracy 0.88; all 100 batches/epoch; 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 →