auraloss developer on retainer: STFTLoss(fft_size=2048) requires signal length ≥ 2048 — 15 clips of 2,000 samples crash torch.stft() — DataLoader(shuffle=True) makes crash timing non-deterministic — training fails after random number of batches — 4 weeks — auraloss developer on monthly retainer
auraloss 0.2.1 • Python 3.10; PyTorch 2.0; audio super-resolution GAN training; STFTLoss(fft_size=2048, win_length=1024, hop_size=256); torch.stft() requires signal_length ≥ fft_size=2048; 15 clips of 2,000 samples (45 ms) in 1,200-clip dataset; each batch has ≈20 % chance of containing a short clip; RuntimeError at unpredictable step; fix: filter dataset to remove clips shorter than fft_size samples • Northfield Auraloss Ltd. (music AI startup; GAN super-resolution training; 1,200 piano clips; 4 weeks; 2.0h retainer engagement)
Northfield Auraloss Ltd. built a GAN-based audio super-resolution model to convert 22050 Hz piano recordings to 44100 Hz, training on 1,200 clips from 50 music schools. The loss function combined auraloss.freq.STFTLoss(fft_size=2048, win_length=1024, hop_size=256) with an L1 reconstruction term. The dataset had been assembled from two sources: 1,185 clips of normal length (1–30 seconds) and 15 brief test recordings (exactly 2,000 samples, 45 ms at 44100 Hz) that had been generated by an earlier encoder evaluation tool and accidentally left in the training data directory. auraloss.freq.STFTLoss.forward() internally calls torch.stft(x, n_fft=self.fft_size, ...) on both the input and target tensors. PyTorch’s torch.stft() enforces a hard precondition: the signal must have at least n_fft samples. For a 2,000-sample signal with n_fft=2048, torch.stft() raises RuntimeError: “Expected signal length at least 2048 to compute STFT, but got signal length 2000”. With DataLoader(shuffle=True), the 15 short clips were distributed randomly across all epochs. With batch_size=16, each batch had a 15/1200 × 16 ≈ 20% probability of drawing a short clip. Training crashed at step 47 on the first run, step 312 on the second, and step 8 on the third — always with the same RuntimeError, always after hours of valid training steps.
The root cause was invisible at training startup because all 1,200 clips loaded correctly from disk and all passed the DataLoader’s collate function without error. The shape check that would have caught the problem — asserting that every clip has at least fft_size samples — was absent. The team investigated gradient explosion (the crash appeared similar to a sudden divergence), mixed-precision fp16 loss scale overflow, discriminator architecture instability, and batch normalization in the GAN discriminator. None of these could produce a RuntimeError at an arbitrary step N with valid training for steps 1 through N−1. The diagnostic was wrapping the loss call in a try/except RuntimeError block that logged the batch file paths on exception: every crash batch contained a file from /data/train/eval_outputs/. All 15 problematic clips were identified immediately. The fix was adding a startup dataset validation that asserts all(len(audio) ≥ 2048 for audio, _ in dataset) before the first training step, raising a ValueError that lists the offending file paths. After removing the 15 short clips, training completed 100 epochs without crashing.
The annotated buggy and fixed training loop, with startup dataset validation and loss guard:
# Northfield Auraloss Ltd. — auraloss 0.2.1 clip length fix
# auraloss 0.2.1; Python 3.10; PyTorch 2.0; torchaudio 2.0
# Audio super-resolution GAN training; 1,200 piano clips at 44100 Hz
#
# Problem: STFTLoss(fft_size=2048) → torch.stft() requires signal_length >= 2048
# 15 clips in dataset are exactly 2000 samples (45ms at 44100 Hz)
# DataLoader(shuffle=True) → short clips appear in random batches
# RuntimeError at unpredictable step (step 47, 312, 8 across runs)
# 4 weeks of gradient clipping, fp16, batch norm, arch experiments
# Fix: startup assert all clips >= fft_size samples; remove short clips
import math
import torch
import auraloss.freq
import soundfile as sf
FFT_SIZE = 2048
WIN_LENGTH = 1024
HOP_SIZE = 256
stft_loss = auraloss.freq.STFTLoss(
fft_size=FFT_SIZE,
win_length=WIN_LENGTH,
hop_size=HOP_SIZE,
w_sc=1.0,
w_log_mag=1.0,
w_lin_mag=0.0,
)
# ── BUGGY training step (no clip length guard) ────────────────────────────────
def train_step_buggy(batch_audio: torch.Tensor, batch_target: torch.Tensor) -> torch.Tensor:
"""BUGGY: STFTLoss called without checking signal length.
For clips of 2000 samples with fft_size=2048:
RuntimeError: Expected signal length at least 2048 to compute STFT
Crash is non-deterministic (depends on shuffle order).
"""
# batch_audio: (batch, 1, time) — may contain 2000-sample clips
loss = stft_loss(batch_audio, batch_target) # CRASHES if any clip < 2048 samples
return loss
# ── FIXED training step ───────────────────────────────────────────────────────
def train_step(batch_audio: torch.Tensor, batch_target: torch.Tensor,
batch_paths: list[str]) -> torch.Tensor:
"""FIXED: guard against short clips; validate loss before backward."""
min_len = batch_audio.shape[-1]
# Defensive check: catch short clips that passed dataset validation
if min_len < FFT_SIZE:
raise RuntimeError(
f"Batch contains signal of length {min_len} shorter than "
f"fft_size={FFT_SIZE}. Files: {batch_paths}. "
"These should have been filtered by validate_dataset_clip_lengths()."
)
loss = stft_loss(batch_audio, batch_target)
# Guard against NaN/Inf loss before backward (log-magnitude STFT instability)
loss_val = loss.item()
if math.isnan(loss_val) or math.isinf(loss_val) or loss_val > 1000.0:
raise RuntimeError(
f"Loss value {loss_val:.4f} is NaN/Inf/diverged. "
"Check for near-silent clips with log-magnitude STFT instability."
)
return loss
# ── Startup dataset validation ────────────────────────────────────────────────
def validate_dataset_clip_lengths(file_paths: list[str], fft_size: int = FFT_SIZE) -> None:
"""
Assert every clip has at least fft_size samples before first training batch.
Call once at training startup — catches the non-deterministic crash immediately.
"""
too_short = []
for path in file_paths:
info = sf.info(path)
n_samples = info.frames # number of audio frames (samples per channel)
if n_samples < fft_size:
too_short.append((path, n_samples))
if too_short:
lines = [f" {p}: {n} samples ({n/44100*1000:.1f}ms at 44100 Hz)" for p, n in too_short]
raise ValueError(
f"Dataset contains {len(too_short)} clip(s) shorter than "
f"fft_size={fft_size} samples ({fft_size/44100*1000:.1f}ms at 44100 Hz).\n"
"These will crash torch.stft() at a random training step when "
"DataLoader(shuffle=True) includes them in a batch.\n"
"Remove or pad these clips before training:\n" + "\n".join(lines)
)
print(
f"[auraloss startup OK] All {len(file_paths)} clips have "
f">= {fft_size} samples. STFTLoss(fft_size={fft_size}) is safe."
)
# ── Usage ─────────────────────────────────────────────────────────────────────
# Call before creating DataLoader — catches short clips immediately
# validate_dataset_clip_lengths(dataset.file_paths, fft_size=FFT_SIZE)
#
# For MultiResolutionSTFTLoss: validate against max fft_size
# mr_loss = auraloss.freq.MultiResolutionSTFTLoss(fft_sizes=[2048, 1024, 512])
# validate_dataset_clip_lengths(dataset.file_paths, fft_size=max([2048, 1024, 512]))
How 15 short clips in a 1,200-clip dataset cause non-deterministic torch.stft() crashes after hours of valid training — and the startup validation pattern that surfaces the problem before the first batch
The failure combines the minimum-length precondition of torch.stft(), the random ordering introduced by DataLoader(shuffle=True), and the absence of a startup clip length validation. torch.stft(x, n_fft) computes the Short-Time Fourier Transform using an FFT window of n_fft samples. Without center padding (which auraloss does not apply by default), the first STFT frame requires the full n_fft samples from the start of the signal. Any signal shorter than n_fft samples cannot produce even one STFT frame and raises a RuntimeError immediately. This is not a numerical edge case or a gradient issue: it is a shape precondition enforced by PyTorch before any computation begins. When the error occurs mid-training after valid steps, it destroys the training checkpoint: the optimizer state from the last valid step was not saved, the model weights from the failing batch are not saved (the backward never ran), and the run must restart from the previous checkpoint epoch. With a dataset of 1,200 clips where 15 are short and batch_size=16, the probability that at least one of the first 10 batches contains a short clip is approximately 1 − (1185/1200)^160 ≈ 87%. In practice, Northfield Auraloss Ltd.’s team restarted training eight times over four weeks, each time reaching a different step before the same RuntimeError, and each time investigating a different hypothesis for why training “suddenly diverged.” The diagnostic that broke the loop was adding a bare except RuntimeError as e: print(batch_paths); raise wrapper around the loss call, which immediately revealed the file path of a 2,000-sample clip. The startup validation — iterating the dataset once with soundfile.info() and asserting every clip’s frame count is at least fft_size — adds less than 2 seconds for a 1,200-clip dataset and permanently prevents this class of non-deterministic crash. For MultiResolutionSTFTLoss, the validation must use max(fft_sizes) as the minimum length. The retainer engagement was 2.0h: 0.5h triage (wrap STFTLoss in try/except; log batch paths; identify 15 short clips in /data/train/eval_outputs/); 0.5h root cause (torch.stft() minimum length = n_fft; no center padding in auraloss default; 2000 < 2048; shuffle causes random batch inclusion); 0.5h fix (startup validate_dataset_clip_lengths() using soundfile.info(); remove 15 clips; add per-step loss guard); 0.5h validation (100-epoch training completes; loss converges; mel cepstral distortion 2.1 dB; startup validation added to dataset preparation script; 2.0h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- torchaudio developer on retainer — torchaudio 0.13.1; Python 3.10;
MelSpectrogramdefaultn_fft=400not 1024; feature mismatch with librosa defaultn_fft=2048; model accuracy 0.61 not 0.82; fix: match n_fft, win_length, hop_length to training config; 1.5h - kapre developer on retainer — kapre 0.3.7; Python 3.9;
Melspectrogramlayer input shape(batch, samples, 1)but developer passes(batch, 1, samples)channels-first; Keras silently reshapes; mel filterbank applied to wrong axis; model F1 0.52 not 0.81; 3 weeks — 2.0h - librosa developer on retainer — librosa 0.10.1; Python 3.10;
librosa.load()defaultsr=22050resamples audio silently; model trained at 44100 Hz receives 22050 Hz features at inference; classification accuracy 0.61 not 0.84; 3 weeks — 2.0h
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 →