Lunar Boom Learning

4.6 · Debugging Model Training

Section 4.6 of 4.6

Debugging Model Training

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.
  • Verify audio, tokens, metadata, masks, conditions, predictions, gradients, and parameter updates separately.
  • Diagnose stagnant loss, unstable loss, non-finite values, missing gradients, and unexpected parameter behaviour.
  • 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.

Create a golden batch

A golden batch is a small, saved set of examples whose expected intermediate values are understood.

For a text-conditioned music model, preserve:

    1. Original audio
    2. Caption and metadata
    3. Resampled waveform
    4. Crop boundaries
    5. Codec or symbolic tokens
    6. Padding mask
    7. Tokenised condition
    8. Condition embedding shape
    9. Target alignment
    10. 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

FailurePossible symptomDirect check
Audio and caption are mispairedThe model appears to ignore textDisplay and listen to paired examples after batching
Crop occurs after caption assignmentCaption describes content outside the cropInspect crop timestamps and caption relevance
Sample rate is interpreted incorrectlyPitch, speed, or duration is wrongCompare expected and decoded duration
Channel conversion is incorrectSilence, cancellation, or distorted loudnessListen to each channel and the converted waveform
Padding mask is reversedLoss uses padding and ignores real tokensCount valid targets per example and visualise the mask
Targets are shifted incorrectlyLoss remains high or learns an unintended identity taskPrint input-target token pairs at several positions
Cached tokens are staleCode changes have no effect or produce inconsistent examplesRe-encode selected files and compare cache metadata
One file is repeated by the samplerFast apparent fitting and low diversityLog 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:

    1. The targets contain learnable information
    2. The loss depends on the predictions
    3. Gradients reach trainable parameters
    4. The optimiser updates those parameters
    5. 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

ResultPossible interpretationNext check
Loss falls rapidlyThe basic pipeline can learn the fixed examplesRestore validation, regularisation, and dataset scale
Loss is perfectly flatNo useful update reaches the prediction functionCheck gradients, frozen parameters, targets, masks, and optimiser groups
Loss changes but remains highLearning rate, target noise, representation, or capacity may be unsuitableInspect per-example and per-component losses
Loss becomes non-finiteNumerical or optimisation instabilityFind the first non-finite tensor and lower the complexity of the run
Loss falls but generated output is wrongTraining and generation paths differCompare teacher-forced predictions with autoregressive sampling
One example fits and another does notThe difficult example may be malformed, masked, or out of rangeRun each example independently

Loss does not decrease

A flat loss can have several causes:

    1. Learning rate is too small
    2. Parameters are frozen or absent from the optimiser
    3. Gradients are zero, missing, or detached
    4. The optimiser step is skipped
    5. Targets are random, constant, or misaligned
    6. The valid loss mask is empty or nearly empty
    7. The model output does not influence the selected loss
    8. The same stale predictions are reused
    9. Integer or device conversions break the intended path
    10. 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:

    1. Division by zero
    2. Logarithm of zero or a negative value
    3. Invalid normalisation statistics
    4. Exponential overflow
    5. Very large gradients or updates
    6. Unstable lower-precision operations
    7. Non-finite input audio or cached features
    8. Empty reductions
    9. Invalid masks
    10. 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

TestResultLikely direction
Increase sampling temperature moderatelyRepetition decreases but quality becomes unstableDecoding concentration contributes to the loop
Use the same settings on an earlier checkpointEarlier checkpoint is more diverseLater overfitting or narrowing may contribute
Change the prompt and seedThe same loop appears repeatedlyStrong model or dataset preference
Inspect nearest training examplesThe loop matches duplicated materialExposure imbalance or memorisation risk
Teacher-forced predictions remain goodFree generation still collapsesAutoregressive path dependence or sampling problem
Decoded real training tokens also sound repetitiveThe representation or source segment contains the repetitionThe generator may not be the original source

The model ignores captions or other controls

A condition can fail at several stages:

  1. The metadata does not contain the intended condition.
  2. The condition is paired with the wrong audio.
  3. Tokenisation produces an empty or truncated input.
  4. Condition dropout removes it more often than intended.
  5. The condition encoder is frozen, detached, or incompatible.
  6. The fusion module does not use the resulting tensor.
  7. Gradients do not reach the conditioning path.
  8. The training data does not contain a reliable relationship between condition and target.
  9. Generation guidance or sampling settings are unsuitable.
  10. 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:

    1. Confirms that the audio batch size matches the metadata count
    2. Converts metadata into conditioning attributes
    3. Applies classifier-free and attribute dropout
    4. Tokenises and encodes the conditions
    5. Encodes audio into codec tokens
    6. Constructs a padding mask from valid audio lengths
    7. Produces logits for several codebooks
    8. Checks that logits, targets, and masks have compatible shapes
    9. Calculates cross-entropy only on valid positions
    10. Runs backward propagation
    11. Unscales mixed-precision gradients
    12. Optionally records and clips gradient norm
    13. Runs the optimiser and scheduler
    14. Clears gradients
    15. Raises an error when the loss is non-finite
    16. 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:

    1. Source audio is silent or incorrectly normalised
    2. Channel conversion cancels the waveform
    3. The crop selects an empty or padded region
    4. Codec tokens represent silence
    5. Generated tokens are invalid or dominated by a silence token pattern
    6. The decoder receives the wrong shape or codebook order
    7. Amplitude values are scaled incorrectly before file writing
    8. The output file uses the wrong sample rate or subtype
    9. 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

TestIf it is silentLikely area
Original source fileYesDataset
Processed training waveformYesLoading, crop, channel, resampling, or normalisation
Decoded tokens from real audioYesCodec, token cache, or decoder
Decoded generated tokensYes, while real tokens decode correctlyGenerative model or generation settings
In-memory generated waveformNo, but saved file is silentFile writing, scaling, subtype, or metadata
Saved file in one player onlyYesPlayback 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:

    1. Source IDs across splits
    2. Duplicate and near-duplicate clusters
    3. Overlapping windows
    4. Alternate arrangements or performances
    5. Cached features created before splitting
    6. Normalisation fitted on all data
    7. Validation examples accidentally included in the sampler
    8. 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:

  1. The original failure no longer occurs.
  2. An unaffected control case still works.
  3. 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.

Checking your account…
Sources for this lesson (23)
  1. Deep Learning Tuning Playbook — Google researchers and engineers
  2. Additional Guidance for the Training Pipeline — Google researchers and engineers
  3. Deep Learning Tuning Playbook FAQ — Google researchers and engineers
  4. torch.autograd — PyTorch contributors
  5. torch.Tensor.register_hook — PyTorch contributors
  6. torch.nn.Module — PyTorch contributors
  7. torch.nn.utils.clip_grad_norm_ — PyTorch contributors
  8. torch.isfinite — PyTorch contributors
  9. Automatic Mixed Precision — PyTorch contributors
  10. Automatic Mixed Precision Examples — PyTorch contributors
  11. torch.profiler — PyTorch contributors
  12. torch.utils.data — PyTorch contributors
  13. Saving and Loading Models — PyTorch contributors
  14. Reproducibility — PyTorch contributors
  15. Performance Tuning Guide — PyTorch contributors
  16. Debugging Hangs with Flight Recorder — PyTorch contributors
  17. Common Pitfalls and Recommended Practices — scikit-learn contributors
  18. Cross-Validation: Evaluating Estimator Performance — scikit-learn contributors
  19. Simple and Controllable Music Generation — Jade Copet et al. (2023)
  20. MusicGen Documentation — Meta AI
  21. AudioCraft Language Model API — Meta AI
  22. AudioCraft Conditioning Documentation — Meta AI
  23. MusicGenSolver API Documentation — Meta AI
Browse all contextual sources →