Lunar Boom Learning

4.5 · Compute and Infrastructure

Section 4.5 of 4.6

Compute and Infrastructure

GPUs, memory, checkpoints, storage, and reproducible experiments

Learn what occupies GPU memory, how music representation and sequence length affect training cost, when memory-saving and distributed techniques help, and how to build a recoverable local, cloud, or hybrid workflow.

About 16 minutes

Guiding question

What actually occupies GPU memory during training?

By the end, you’ll be able to
  • Distinguish computational throughput, GPU memory capacity, system memory, and storage.
  • Identify the main sources of training memory use, including parameters, gradients, optimiser state, activations, and temporary buffers.
  • Explain how audio duration, token rate, sequence length, batch size, model width, and precision affect resource use.
  • Compare gradient accumulation, mixed precision, activation checkpointing, parameter freezing, and sharded training.
  • Distinguish data parallelism, fully sharded data parallelism, and model or tensor parallelism.
  • Design checkpoints that support inference, comparison, and exact or approximate training resumption.
  • Compare local, cloud, and hybrid experimentation workflows.
  • Create an experiment-tracking and reproducibility record containing configurations, data versions, code, metrics, samples, and environment information.

A model architecture can be mathematically valid and still be impossible to train with the available hardware.

Infrastructure determines which model sizes, sequence lengths, batch sizes, datasets, and experiments can be run in practice. It also determines whether a failed job can resume, whether two runs can be compared, and whether the result can be reproduced later.

The central question is therefore not simply Which GPU is fastest? It is:

Which combination of hardware, memory strategy, storage, software, and experiment controls can run this specific training plan reliably?

Four different resource constraints

Swipe sideways to view the full comparison

ResourceWhat it limitsTypical symptom
GPU computeHow quickly tensor operations are completedLow step throughput despite fitting in memory
GPU memoryHow many parameters, activations, gradients, and states fit at onceOut-of-memory error
CPU and data pipelineHow quickly examples are decoded, transformed, and transferredThe GPU waits between batches
Storage and networkHow quickly datasets and checkpoints can be read, written, or transferredSlow startup, checkpoint stalls, or repeated data downloads

What occupies training memory?

Loading model weights is only the beginning. A conventional training step may require memory for:

    1. Model parameters
    2. Parameter gradients
    3. Optimiser states
    4. Forward-pass activations saved for backpropagation
    5. Input batches, targets, masks, and conditions
    6. Temporary operation buffers
    7. Mixed-precision scaling or master values
    8. Distributed communication buffers
    9. Framework allocator reserves

The largest component depends on the model, optimiser, sequence length, batch size, precision, and implementation.

How memory changes during one training step

  1. Load parameters

    Model values occupy device memory before the batch begins.

  2. Load the batch

    Inputs, targets, conditions, lengths, and masks are transferred or created.

  3. Run the forward pass

    Activation memory grows as intermediate tensors are retained.

  4. Run the backward pass

    Activations are progressively released while gradients are created.

  5. Run the optimiser

    Optimiser states and temporary update tensors contribute to peak memory.

  6. Clear gradients

    Gradient storage can be released or reused before the next ordinary step.

Allocated and reserved memory

PyTorch uses a caching allocator for CUDA memory. Memory released by tensors may remain reserved by PyTorch so it can be reused quickly.

As a result, a system monitor can show memory as occupied even when that memory is not currently assigned to live tensors.

Useful measurements include:

    1. Memory allocated by tensors
    2. Memory reserved by the caching allocator
    3. Peak allocated memory
    4. Peak reserved memory

This distinction is important when debugging apparent memory leaks.

Audio duration becomes sequence length

A music model does not usually receive thirty seconds as an abstract unit. The representation converts those seconds into samples, frames, latent positions, or tokens.

Approximate sequence length depends on:

    1. Duration
    2. Sample or frame rate
    3. Codec token rate
    4. Number of codebooks or token streams
    5. Channel handling
    6. Interleaving pattern
    7. Padding and special tokens

Doubling duration usually increases the amount of represented data, but the exact memory and compute effect depends on the architecture.

In practice

Real-world example: MusicGen token sequences

MusicGen uses a 32 kHz EnCodec representation with four codebooks sampled at 50 frames per second. Its interleaving pattern determines how the four token streams become the sequence processed by the language model. Duration, codebook count, and interleaving therefore affect training sequence length and cost.

Why long sequences are expensive

Longer sequences increase the number of token representations and layer activations that must be processed.

For conventional dense self-attention, the attention relationship between sequence positions forms a square matrix. Materialising this matrix creates memory and computational costs that grow strongly as sequence length increases.

Efficient attention implementations such as FlashAttention reduce memory traffic and avoid storing some large intermediate matrices. They improve feasibility and throughput, but they do not make long-context training free.

What raises training cost?

Swipe sideways to view the full comparison

SettingPrimary effectImportant qualification
More parametersMore parameter, gradient, and optimiser stateFrozen parameters reduce some training state but still require model storage
Longer sequenceMore activations and more sequence operationsAttention implementation changes the memory profile
Larger microbatchMore examples and activations processed togetherCan improve throughput if memory remains available
More audio codebooksMore tokens or prediction streamsInterleaving and architecture determine the final sequence
Higher sample or frame rateMore representation positions per secondCompression can reduce the downstream sequence
Full fine-tuningGradients and optimiser state for the complete trainable modelLoRA or adapters can train substantially fewer values
More generated evaluationsAdditional decoding and audio storageEvaluation cost can become significant even without backpropagation

Batch size and microbatch size

A larger batch processes more examples together. This commonly increases activation and input memory because more examples pass through the network at once.

The microbatch size is the number of examples processed in one forward and backward pass on one worker. The effective batch size can be larger through gradient accumulation and multiple workers.

Reducing the microbatch is often the first response to an out-of-memory error, but very small microbatches can reduce hardware utilisation or change optimisation behaviour.

Gradient accumulation

Gradient accumulation divides a large effective batch into several smaller microbatches.

Each microbatch runs a forward and backward pass. Gradients are accumulated, and the optimiser updates the parameters only after the selected number of microbatches.

This lowers the activation memory required at one moment compared with processing the full effective batch together. It also adds more sequential computation and requires correct loss scaling and gradient clearing.

In practice

Effective batch size

A common approximation is: microbatch size multiplied by accumulation steps multiplied by the number of data-parallel workers. The actual optimisation behaviour can still depend on loss reduction, incomplete batches, masking, and distributed implementation.

Numerical precision

Numerical precision determines how tensor values are represented.

Common training formats include:

    1. FP32
    2. FP16
    3. BF16
    4. Mixed-precision combinations

Lower-precision operations can reduce tensor memory and improve throughput on compatible hardware. Some calculations remain in higher precision for numerical stability. FP16 training may use gradient scaling to reduce underflow risk.

Total memory does not necessarily fall in direct proportion to the bit width because optimiser states, master values, temporary tensors, and unsupported operations may remain in higher precision.

Activation checkpointing

Ordinary backpropagation keeps many forward activations in memory. Activation checkpointing saves only selected tensors and recomputes omitted forward operations during the backward pass.

This trades additional computation for lower activation memory. It is especially useful when activations, rather than parameters or optimiser state, are the main bottleneck.

This technique is unrelated to saving a model checkpoint to disk.

Two different meanings of checkpoint

Swipe sideways to view the full comparison

TermPurposeWhere it exists
Activation checkpointingReduce GPU memory through recomputationInside the forward and backward computation
Model checkpointSave model or training state for later useIn persistent storage
Choosing a memory-saving technique

Swipe sideways to view the full comparison

TechniqueReducesTrade-off
Smaller microbatchBatch-dependent activations and inputsLower parallel utilisation or different batch behaviour
Gradient accumulationPeak activation memory for a target effective batchMore sequential forward and backward passes
Mixed precisionMemory and time for supported tensor operationsNumerical-stability requirements
Activation checkpointingSaved activation memoryForward operations are recomputed
Freeze the base modelGradients and optimiser state for frozen parametersLower adaptation capacity
LoRA or adaptersTrainable gradient and optimiser stateMay not express every required model change
CPU offloadSelected GPU-resident stateTransfers can reduce speed
FSDP or ZeRO-style shardingReplicated parameters, gradients, or optimiser statesCommunication and distributed complexity

The GPU can be fast while training remains slow

Music data may require file reading, decompression, resampling, channel conversion, tokenisation, caption parsing, and random cropping before it reaches the model.

If this pipeline is slower than the GPU, the accelerator waits between batches.

Potential responses include:

    1. Additional data-loader workers
    2. Persistent workers
    3. Pinned host memory where appropriate
    4. Prefetching
    5. Cached or precomputed codec tokens
    6. Faster local dataset storage
    7. Sharding large datasets
    8. Moving expensive preprocessing outside the training loop

Each change should be measured because excessive workers or caching can create new CPU, memory, or storage bottlenecks.

From one GPU to distributed training

A single GPU is usually the simplest environment for debugging and small experiments. Distributed training becomes useful when:

    1. The model or training state does not fit on one device
    2. A larger global batch is required
    3. One-device throughput makes the experiment impractically slow
    4. Evaluation or generation needs to be parallelised

Adding GPUs introduces communication, synchronisation, process management, failure handling, and distributed checkpointing. More devices do not guarantee proportional speedup.

DDP and FSDP

Swipe sideways to view the full comparison

PropertyDDPFSDP
Model parametersNormally replicated per workerSharded outside relevant computation
GradientsNormally present for each replica before synchronisationSharded through reduce-scatter behaviour
Optimiser stateNormally replicated unless another technique is addedSharded across workers
Primary benefitRelatively direct multi-GPU data parallelismLower per-worker persistent model-state memory
Primary costFull replica must fit on each workerAdditional sharding, communication, and checkpoint complexity

Saving training progress

A checkpoint is a persistent record created at a particular training state.

Different checkpoints serve different purposes:

    1. Generation or inference
    2. Comparing earlier and later models
    3. Selecting the best validation checkpoint
    4. Resuming an interrupted training run
    5. Preserving milestones for an audit
    6. Rolling back after a software or data error

A weights-only checkpoint is smaller and simpler, but it generally does not contain everything needed to resume the exact optimiser trajectory.

Checkpoint types

Swipe sideways to view the full comparison

CheckpointTypical contentsPrimary use
Weights onlyModel state dictionaryInference or later initialisation
Resumable trainingModel, optimiser, scheduler, scaler, counters, and configurationContinue an interrupted run
Best validationState selected by a held-out metricModel comparison and final evaluation
Periodic milestoneState at fixed steps or epochsAudit learning progression or recover from later failure
Distributed checkpointSharded state stored across distributed workersResume large sharded training jobs

What a resumable checkpoint should preserve

  1. Model state

    Store the trainable and required non-trainable tensors.

  2. Optimiser state

    Preserve moments and other update history.

  3. Scheduler state

    Resume the correct learning-rate position.

  4. Precision scaler state

    Preserve mixed-precision gradient-scaling progress when used.

  5. Progress counters

    Record epoch, global step, tokens, examples, or audio hours processed.

  6. Model and data configuration

    Record architecture, tokenizer, codec, conditions, and dataset version.

  7. Randomness state

    Preserve relevant random-generator states when a closer continuation is required.

  8. Code and environment identifiers

    Record the commit, package versions, platform, and hardware.

How often should checkpoints be saved?

Frequent checkpoints reduce the amount of work lost after interruption. They also increase storage use and can pause training while large states are written.

The appropriate interval depends on:

    1. Cost per training step
    2. Failure or interruption risk
    3. Checkpoint size
    4. Storage bandwidth
    5. Validation frequency
    6. Whether asynchronous checkpointing is available
    7. How many historical states must be retained

Test checkpoint loading before depending on the recovery plan.

Storage can become a larger problem than the model

A music project may need to store:

    1. Original audio and MIDI
    2. Cleaned and resampled versions
    3. Captions and metadata
    4. Precomputed codec tokens or embeddings
    5. Dataset manifests and hashes
    6. Model checkpoints
    7. Optimiser states
    8. Generated evaluation samples
    9. Similarity indexes
    10. Logs, plots, and profiler traces

Keeping every artifact from every run can consume substantial space. Deleting everything except the final model removes evidence needed for debugging and reproducibility.

A practical storage plan

Swipe sideways to view the full comparison

ArtifactAccess patternSuggested treatment
Current training shardsRead repeatedly during the runKeep on fast storage close to the workers
Original source dataRead during preparation and auditsPreserve immutably with provenance records
Token or embedding cacheRead frequently but can be rebuiltVersion against the representation and preprocessing code
Latest resumable checkpointNeeded quickly after interruptionKeep in reliable persistent storage
Best validation checkpointNeeded for final evaluation and release decisionsProtect from automatic deletion
Old periodic checkpointsNeeded occasionally for analysisApply a documented retention policy
Generated samples and logsNeeded for comparison and auditStore representative outputs with run identifiers

Local, cloud, and hybrid workflows

A local workstation offers direct access to fixed hardware and data. It is well suited to pipeline development, small models, short runs, and repeated debugging.

Cloud or cluster infrastructure provides access to hardware that may not be available locally and can support larger or temporary experiments. It also introduces remote storage, job scheduling, environment setup, data transfer, access control, and interruption handling.

A hybrid workflow develops and validates the smallest version locally, then runs a versioned configuration on larger remote infrastructure.

Local and cloud training

Swipe sideways to view the full comparison

QuestionLocal hardwareCloud or managed cluster
CapacityLimited to owned hardwareCan access larger temporary configurations
SetupDirect but requires local drivers and maintenanceRequires remote environment and job configuration
Data accessFast when data already resides locallyMay require upload, replication, or remote storage
Cost behaviourHardware is paid for independently of each runResources and storage are commonly metered while allocated or used
InterruptionAffected by local crashes and power availabilityAffected by job limits, preemption, quota, or remote failures
ScalingConstrained by the physical machineCan support multi-GPU and multi-node experiments
ReproducibilityEnvironment may drift through local updatesImages and job specifications can standardise repeated launches

A reliable hybrid workflow

  1. Build locally

    Test parsing, tokenisation, one forward pass, one backward pass, and checkpoint loading.

  2. Run a tiny overfit test

    Confirm that the model can fit a deliberately small sample when debugging the pipeline.

  3. Run a short validation experiment

    Use the real split and evaluation code for a limited number of steps.

  4. Freeze the configuration

    Record code commit, environment, data manifest, model settings, and seed.

  5. Launch remotely

    Use the same versioned configuration on larger hardware.

  6. Track and checkpoint

    Stream metrics and save recoverable states to persistent storage.

  7. Reproduce locally

    Load selected outputs or checkpoints into the evaluation environment.

Experiment tracking

A model result is difficult to interpret without knowing how it was produced.

A useful run record includes:

    1. Run identifier
    2. Parent or comparison run
    3. Code commit
    4. Model configuration
    5. Dataset and split versions
    6. Tokenizer or codec version
    7. Optimiser and scheduler
    8. Batch and accumulation settings
    9. Precision and distributed strategy
    10. Hardware and worker count
    11. Seeds
    12. Training and validation metrics
    13. Gradient and memory diagnostics
    14. Checkpoint paths
    15. Generated samples
    16. Notes about failures or manual changes

The objective is not to collect every number. It is to preserve the information needed to explain and repeat the result.

Real-world example: AudioCraft training infrastructure

Meta's AudioCraft training pipelines are built on PyTorch, use Flashy for training-pipeline design, and use Dora as an experiment manager.

The framework supports named configurations, experiment grids, team-specific environment settings, cluster configuration, and model-specific solvers. This separates experiment definitions from the physical machine or cluster used to run them.

For MusicGen, AudioCraft combines the compression model, language model, conditions, optimiser, metrics, validation, and generation stages within the training system.

Reproducibility has several levels

Exact bit-for-bit repetition is not always available across PyTorch releases, devices, platforms, kernels, and distributed schedules.

A project can still aim for:

    1. Configuration reproducibility: the same settings can be reconstructed.
    2. Data reproducibility: the same dataset and splits can be identified.
    3. Procedural reproducibility: the same pipeline can be executed.
    4. Statistical reproducibility: repeated runs produce comparable distributions of results.
    5. Artifact reproducibility: the selected checkpoint and outputs can be recovered.

Record seeds, but do not treat one seed as a complete reproducibility system.

Minimum reproducibility record

  1. Identify the code

    Store the repository commit and note uncommitted changes.

  2. Identify the environment

    Record package, framework, driver, and platform versions.

  3. Identify the data

    Store manifests, split group IDs, preprocessing versions, and hashes.

  4. Identify the model

    Record architecture, parameter count, tokenizer, codec, and conditions.

  5. Identify the optimisation

    Record optimiser, scheduler, precision, batch, accumulation, and clipping.

  6. Identify the infrastructure

    Record GPU type, worker count, distributed strategy, and storage layout.

  7. Identify randomness

    Record seeds and relevant random-generator states.

  8. Preserve artifacts

    Retain selected checkpoints, logs, generated samples, and evaluation reports.

Plan infrastructure before the full run

  1. Define the model and representation

    Estimate parameters, token rate, codebooks, context, and trainable fraction.

  2. Measure one real step

    Run a representative batch and record peak memory, step time, and data wait.

  3. Locate the bottleneck

    Separate activation, gradient, optimiser, data, storage, and communication limits.

  4. Apply the smallest suitable technique

    Reduce the microbatch, change precision, checkpoint activations, freeze parameters, or shard state.

  5. Estimate the complete experiment

    Include training, validation, generation, repeated seeds, memorisation audits, and failed-run allowance.

  6. Test recovery

    Save, transfer, load, and resume a checkpoint before the long run.

  7. Freeze tracking requirements

    Ensure configuration, metrics, samples, and environment metadata are recorded automatically.

  8. Set resource limits

    Define maximum steps, wall time, storage, cloud spend, and checkpoint retention.

Interactive lesson

Estimate a Music Training Run

Try it: Begin with the small symbolic preset and inspect each memory category. Switch to codec-token music generation, increase duration and model size, then recover from an out-of-memory state using one technique at a time. Finish by selecting a checkpoint and tracking plan.

Training memory includes model parameters, gradients, optimiser states, activations, batches, temporary buffers, and allocator reserves. Duration affects sequence length through the representation. Mixed precision, smaller microbatches, accumulation, activation checkpointing, parameter-efficient tuning, and sharding solve different bottlenecks.

When the system still fails

A model that fits in memory can still produce NaN losses, silent data errors, stalled workers, broken checkpoints, invalid audio, or gradients that never reach part of the network.

The next section, Debugging Model Training, turns logs, gradients, memory traces, generated samples, and controlled tests into a systematic debugging process.

Check your understanding

Ready for a quick check?

Test whether you can identify memory components, choose infrastructure techniques, design checkpoints, and create a reproducible training workflow.

Ready to continue?

Save this section to your account and continue from any device.

Checking your account…
Sources for this lesson (33)
  1. CUDA Semantics — PyTorch contributors
  2. Understanding CUDA Memory Usage — PyTorch contributors
  3. Mosaic: Memory Profiling for PyTorch — PyTorch contributors
  4. How to Save Memory by Fusing the Optimizer Step into the Backward Pass — PyTorch contributors
  5. torch.autograd — PyTorch contributors
  6. Automatic Mixed Precision — PyTorch contributors
  7. Automatic Mixed Precision Examples — PyTorch contributors
  8. torch.utils.checkpoint — PyTorch contributors
  9. Performance Tuning Guide — PyTorch contributors
  10. torch.profiler — PyTorch contributors
  11. Data Loading Optimization in PyTorch — PyTorch contributors
  12. torch.utils.data — PyTorch contributors
  13. Getting Started with Distributed Data Parallel — PyTorch contributors
  14. DistributedDataParallel — PyTorch contributors
  15. Getting Started with Fully Sharded Data Parallel — PyTorch contributors
  16. Large Scale Transformer Model Training with Tensor Parallel — PyTorch contributors
  17. Getting Started with DeviceMesh — PyTorch contributors
  18. Saving and Loading Models — Matthew Inkawhich and PyTorch contributors
  19. Getting Started with Distributed Checkpoint — PyTorch contributors
  20. Asynchronous Saving with Distributed Checkpoint — PyTorch contributors
  21. Visualizing Models, Data, and Training with TensorBoard — PyTorch contributors
  22. Reproducibility — PyTorch contributors
  23. Mixed Precision Training — Paulius Micikevicius et al. (2018)
  24. ZeRO: Memory Optimizations Toward Training Trillion Parameter Models — Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, and Yuxiong He (2020)
  25. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, and Christopher Ré (2022)
  26. NVIDIA Deep Learning Performance Guide — NVIDIA
  27. GPU Performance Background User's Guide — NVIDIA
  28. Simple and Controllable Music Generation — Jade Copet et al. (2023)
  29. MusicGen Documentation — Meta AI
  30. EnCodec Documentation — Meta AI
  31. AudioCraft Training Pipelines — Meta AI
  32. MusicGenSolver API Documentation — Meta AI
  33. AudioCraft API Documentation — Meta AI
Browse all contextual sources →