Finding failures in data, optimisation, conditioning, and generation
Learn how to reduce a failed training run to a reproducible test, verify each stage of the pipeline, interpret loss and gradient symptoms, diagnose conditioning failures, and separate model problems from generation or infrastructure problems.
About 16 minutes
Guiding question
What is the smallest test that still reproduces the failure?
By the end, you’ll be able to
Use a systematic debugging sequence that begins with data and targets before changing model complexity.
Create a small reproducible failure using a fixed batch, checkpoint, configuration, and random seed.
Explain why overfitting one tiny batch is a useful pipeline test but not evidence of generalisation.
Distinguish training failures from sampling, decoding, codec, and playback failures.
Diagnose ignored text, melody, or audio conditioning by tracing the complete conditioning pathway.
Use assertions, hooks, anomaly detection, profiling, checkpoint comparisons, and controlled ablations appropriately.
Document the evidence needed to reproduce and resolve a training bug.
A failed training run does not immediately reveal which part failed.
A flat loss might come from the optimiser, but it might also come from incorrect targets, an empty mask, frozen parameters, detached tensors, stale cached tokens, or a data loader that repeatedly returns the same example.
Repetitive audio might reflect overfitting, but it might instead come from low-diversity sampling settings. Silent output might come from the model, the codec decoder, amplitude scaling, file writing, or playback.
Debugging therefore means locating the earliest point where the observed values stop matching the expected values.
A reliable debugging order
1
Reproduce the failure
Freeze the code, configuration, data example, checkpoint, hardware context, and seed.
2
Verify the raw example
Listen to the audio and inspect its caption, metadata, duration, channels, and sample rate.
3
Verify preprocessing
Inspect crops, resampling, normalisation, symbolic conversion, codec tokens, and padding.
4
Verify model inputs
Check tensor shapes, data types, devices, masks, target alignment, and condition values.
5
Verify the forward pass
Inspect predictions, activation ranges, condition fusion, and the unreduced loss.
6
Verify the backward pass
Confirm that expected parameters receive finite, non-zero gradients.
7
Verify the update
Confirm that the optimiser changes the intended parameters by a plausible amount.
8
Overfit a tiny dataset
Test whether the complete pipeline can learn a deliberately small example set.
9
Restore scale gradually
Reintroduce mixed precision, workers, augmentation, distribution, caching, and full data one feature at a time.
10
Confirm the fix
Repeat the original failure case and an unaffected control case.
A golden batch is a small, saved set of examples whose expected intermediate values are understood.
For a text-conditioned music model, preserve:
Original audio
Caption and metadata
Resampled waveform
Crop boundaries
Codec or symbolic tokens
Padding mask
Tokenised condition
Condition embedding shape
Target alignment
Initial loss
The same batch can be run through new code versions to reveal where behaviour changed.
Inspect data before tuning the optimiser
The model learns only from the values that reach the loss function. A correct source file can become incorrect through cropping, resampling, channel conversion, caching, tokenisation, masking, or metadata pairing.
Before training, inspect examples after every important transformation. Listen to processed audio rather than only the original file. Decode model tokens back into audio or symbolic music where possible. Print captions beside the exact audio segment they condition.
Common data-pipeline failures
Swipe sideways to view the full comparison
Failure
Possible symptom
Direct check
Audio and caption are mispaired
The model appears to ignore text
Display and listen to paired examples after batching
Crop occurs after caption assignment
Caption describes content outside the crop
Inspect crop timestamps and caption relevance
Sample rate is interpreted incorrectly
Pitch, speed, or duration is wrong
Compare expected and decoded duration
Channel conversion is incorrect
Silence, cancellation, or distorted loudness
Listen to each channel and the converted waveform
Padding mask is reversed
Loss uses padding and ignores real tokens
Count valid targets per example and visualise the mask
Targets are shifted incorrectly
Loss remains high or learns an unintended identity task
Print input-target token pairs at several positions
Cached tokens are stale
Code changes have no effect or produce inconsistent examples
Re-encode selected files and compare cache metadata
One file is repeated by the sampler
Fast apparent fitting and low diversity
Log source IDs and frequency per epoch
Try to overfit one tiny batch
A sufficiently expressive model should usually be able to reduce loss sharply on a tiny fixed dataset when regularisation and augmentation are disabled.
This test asks whether the complete optimisation path is connected:
The targets contain learnable information
The loss depends on the predictions
Gradients reach trainable parameters
The optimiser updates those parameters
The model can represent the tiny task
Passing the test does not show that the model generalises. Failing it is strong evidence that the pipeline, objective, capacity, or optimisation settings need investigation.
Interpreting the tiny-batch test
Swipe sideways to view the full comparison
Result
Possible interpretation
Next check
Loss falls rapidly
The basic pipeline can learn the fixed examples
Restore validation, regularisation, and dataset scale
Loss is perfectly flat
No useful update reaches the prediction function
Check gradients, frozen parameters, targets, masks, and optimiser groups
Loss changes but remains high
Learning rate, target noise, representation, or capacity may be unsuitable
Inspect per-example and per-component losses
Loss becomes non-finite
Numerical or optimisation instability
Find the first non-finite tensor and lower the complexity of the run
Loss falls but generated output is wrong
Training and generation paths differ
Compare teacher-forced predictions with autoregressive sampling
One example fits and another does not
The difficult example may be malformed, masked, or out of range
Run each example independently
Loss does not decrease
A flat loss can have several causes:
Learning rate is too small
Parameters are frozen or absent from the optimiser
Gradients are zero, missing, or detached
The optimiser step is skipped
Targets are random, constant, or misaligned
The valid loss mask is empty or nearly empty
The model output does not influence the selected loss
The same stale predictions are reused
Integer or device conversions break the intended path
The model lacks enough capacity for the task
Check the parameter update itself before changing the architecture.
Verify that parameters actually change
1
Select representative parameters
Choose weights in the input, conditioning, middle, and output parts of the model.
2
Record values before the step
Store a copy or checksum of the selected tensors.
3
Run forward and backward
Confirm that the loss requires gradients and that backward completes.
4
Inspect gradients
Check whether each expected parameter has a finite gradient with a meaningful norm.
5
Run the optimiser
Confirm that the step is not skipped by mixed-precision overflow handling.
6
Measure the update
Compare parameter values before and after the optimiser step.
Learning rate problems
A learning rate that is too low can make the loss appear frozen. A learning rate that is too high can cause oscillation, sudden spikes, parameter explosion, or non-finite values.
Google's Deep Learning Tuning Playbook recommends examining loss behaviour around and above the best observed learning rate and logging the full gradient norm when investigating instability. Warm-up, clipping, optimiser changes, and architectural corrections can help in some cases, but they should follow a diagnosis rather than being added blindly.
NaN and infinite values
Non-finite values can arise from invalid arithmetic or from values exceeding the representable numerical range.
Possible causes include:
Division by zero
Logarithm of zero or a negative value
Invalid normalisation statistics
Exponential overflow
Very large gradients or updates
Unstable lower-precision operations
Non-finite input audio or cached features
Empty reductions
Invalid masks
Corrupted model or optimiser state
Find the first non-finite value rather than only the final non-finite loss.
Locate the first non-finite tensor
1
Save the failing batch and checkpoint
Ensure the failure can be replayed.
2
Disable unrelated complexity
Try full precision, one device, no compilation, no augmentation, and no extra workers.
3
Check inputs
Test waveforms, tokens, masks, lengths, and conditioning values.
4
Check forward boundaries
Insert finite assertions after the encoder, conditioner, model blocks, logits, and loss.
5
Check gradients
Inspect gradient hooks or enable anomaly detection for the short failing run.
6
Check the optimiser state
Compare the failure from a clean optimiser with the restored optimiser state.
7
Restore features individually
Re-enable mixed precision, compilation, workers, and distribution one at a time.
Mixed-precision failures
When FP16 mixed precision is used, gradient scaling enlarges small gradients before the backward pass. The scaler then unscales and checks the gradients before the optimiser step.
If non-finite gradients are detected, the optimiser step can be skipped and the scale adjusted. A run that repeatedly skips steps may appear to train slowly or not at all.
For diagnosis, compare the same batch in full precision and log the gradient scale, skipped steps, unscaled gradient norm, and first non-finite operation.
Repetitive generated music
Repetition can originate during training or generation.
Training-related causes include duplicated data, narrow adaptation data, excessive training, short contexts, weak structural supervision, and a model that mainly learns common local loops.
Generation-related causes include greedy decoding, low temperature, restrictive top-k or top-p settings, an overly dominant prefix, excessive guidance, or a stop condition that never activates.
Compare teacher-forced predictions, several sampling configurations, multiple checkpoints, and nearest training examples before attributing repetition to one source.
Diagnosing repetition
Swipe sideways to view the full comparison
Test
Result
Likely direction
Increase sampling temperature moderately
Repetition decreases but quality becomes unstable
Decoding concentration contributes to the loop
Use the same settings on an earlier checkpoint
Earlier checkpoint is more diverse
Later overfitting or narrowing may contribute
Change the prompt and seed
The same loop appears repeatedly
Strong model or dataset preference
Inspect nearest training examples
The loop matches duplicated material
Exposure imbalance or memorisation risk
Teacher-forced predictions remain good
Free generation still collapses
Autoregressive path dependence or sampling problem
Decoded real training tokens also sound repetitive
The representation or source segment contains the repetition
The generator may not be the original source
The model ignores captions or other controls
A condition can fail at several stages:
The metadata does not contain the intended condition.
The condition is paired with the wrong audio.
Tokenisation produces an empty or truncated input.
Condition dropout removes it more often than intended.
The condition encoder is frozen, detached, or incompatible.
The fusion module does not use the resulting tensor.
Gradients do not reach the conditioning path.
The training data does not contain a reliable relationship between condition and target.
Generation guidance or sampling settings are unsuitable.
The evaluation prompt asks for attributes the model was not trained to represent.
Trace the condition from source metadata to generated output.
Debug an ignored condition
1
Verify the source condition
Print the caption, melody, chord, or reference that belongs to each exact target segment.
2
Verify tokenisation
Check tokens, lengths, truncation, empty values, and vocabulary handling.
3
Verify dropout
Log whether classifier-free or attribute dropout removed the condition for each batch.
4
Verify embeddings
Inspect condition shapes, norms, finite values, and variation across contrasting inputs.
5
Verify fusion
Compare model logits with the condition present, replaced, and removed.
6
Verify gradients
Confirm that trainable conditioners and fusion layers receive gradients.
7
Build a contrast test
Use clearly different conditions such as solo piano and aggressive distorted drums.
8
Compare generation settings
Test reasonable guidance, temperature, top-k, and seed variations.
Real-world example: tracing MusicGen's training step
Meta's official AudioCraft solver exposes several useful debugging boundaries.
The solver:
Confirms that the audio batch size matches the metadata count
Converts metadata into conditioning attributes
Applies classifier-free and attribute dropout
Tokenises and encodes the conditions
Encodes audio into codec tokens
Constructs a padding mask from valid audio lengths
Produces logits for several codebooks
Checks that logits, targets, and masks have compatible shapes
Calculates cross-entropy only on valid positions
Runs backward propagation
Unscales mixed-precision gradients
Optionally records and clips gradient norm
Runs the optimiser and scheduler
Clears gradients
Raises an error when the loss is non-finite
Logs total and per-codebook cross-entropy and perplexity
This structure allows a failure to be located before the complete generation stage.
In practice
Inspect component losses separately
MusicGen logs cross-entropy and perplexity for each codec codebook. If the averaged loss looks normal while one codebook behaves abnormally, the per-codebook metrics reveal a failure hidden by the average.
Silent or nearly silent output
Silence can enter the system through several routes:
Source audio is silent or incorrectly normalised
Channel conversion cancels the waveform
The crop selects an empty or padded region
Codec tokens represent silence
Generated tokens are invalid or dominated by a silence token pattern
The decoder receives the wrong shape or codebook order
Amplitude values are scaled incorrectly before file writing
The output file uses the wrong sample rate or subtype
Playback software reads the file incorrectly
Test each stage by saving or listening to its output.
Locate silent audio
Swipe sideways to view the full comparison
Test
If it is silent
Likely area
Original source file
Yes
Dataset
Processed training waveform
Yes
Loading, crop, channel, resampling, or normalisation
Decoded tokens from real audio
Yes
Codec, token cache, or decoder
Decoded generated tokens
Yes, while real tokens decode correctly
Generative model or generation settings
In-memory generated waveform
No, but saved file is silent
File writing, scaling, subtype, or metadata
Saved file in one player only
Yes
Playback or format compatibility
Suspiciously good validation results
A broken split can imitate successful training.
Investigate when validation loss is unexpectedly low, generated validation pieces resemble training examples, or a small model performs implausibly well.
Check:
Source IDs across splits
Duplicate and near-duplicate clusters
Overlapping windows
Alternate arrangements or performances
Cached features created before splitting
Normalisation fitted on all data
Validation examples accidentally included in the sampler
Test results repeatedly used for model selection
Correct the split and rerun affected experiments.
Compare checkpoints and code versions
When a failure appears halfway through training, compare the last healthy checkpoint with the first unhealthy checkpoint using the same saved batch.
When a software change introduces a failure, run the golden batch across earlier and later commits. This form of bisection narrows the change interval before detailed tensor inspection begins.
Preserve optimiser state when the failure may depend on accumulated moments or learning-rate schedule.
Slow training and stalled pipelines
A run can appear frozen while it is waiting for data, synchronising devices, compiling operations, saving checkpoints, or performing an unexpectedly expensive calculation.
PyTorch Profiler can record operator time and memory. Data-loader logs can reveal slow workers or repeated restarts. Distributed debugging tools can help locate workers that reached different collective operations or stopped progressing.
Measure before assuming that the GPU or model is the bottleneck.
Confirm that the fix solved the right problem
A useful fix should pass three tests:
The original failure no longer occurs.
An unaffected control case still works.
The improvement persists across more than one batch, seed, or checkpoint when the failure was not inherently deterministic.
Record the before-and-after evidence. A run that merely restarts successfully has not necessarily resolved the underlying cause.
Record a resolved training failure
1
Symptom
Describe what was observed without claiming a cause.
2
First failing point
Identify the earliest tensor, operation, or pipeline stage known to be incorrect.
3
Reproduction
Record the batch, checkpoint, command, configuration, seed, and environment.
4
Competing hypotheses
List plausible causes and the tests used to separate them.
5
Root cause
State the mechanism supported by the evidence.
6
Fix
Describe the smallest relevant code, data, or configuration change.
7
Verification
Show that the original failure is gone and control cases remain correct.
8
Prevention
Add an assertion, regression test, monitor, or documentation change.
Interactive lesson
Debug a Failed Music Training Run
Try it: Choose a failure case, reproduce it using the fixed batch, and inspect the pipeline in order. Select tests that distinguish competing causes. The case is complete only after you identify the first incorrect stage and verify the proposed fix against the original failure and a control case.
Begin with a fixed failing batch. Verify raw data, preprocessing, targets, masks, conditions, predictions, gradients, and updates in order. Use tiny-batch fitting, finite-value assertions, hooks, anomaly detection, profiling, and controlled ablations only where they distinguish plausible causes.
From a working training run to a trustworthy model
A model can train without crashing and still be unsuitable for release. It may sound weak, ignore controls, reproduce training material, perform differently across groups, or fail under real product conditions.
Chapter 5, Evaluating, Releasing, and Governing the Model, moves beyond training correctness to musical quality, benchmarking, safety, provenance, disclosure, monitoring, and release decisions.
Check your understanding
Ready for a quick check?
Test whether you can locate failures systematically and distinguish data, optimisation, conditioning, generation, and infrastructure causes.
Ready to continue?
Save this section to your account and continue from any device.