Unit 3 of 9 · about 5 hours · derive, measure

GPU memory: allocated, reserved, peak and memory models

OOM errors name a requested size but never the cause. The fix differs completely between live tensors, cached reserve and fragmentation, and only the counters tell them apart.

You'll be able to

  • Derive persistent training memory from parameter, gradient, optimizer-state and activation terms at stated precision.
  • Read allocated, reserved and peak counters and explain each discrepancy between them.
  • Separate live tensors, allocator reserve and outside-allocator memory when an OOM makes no sense.

Covers

Allocated, reserved and peak memoryParameter, gradient, optimizer and activation memory modelsTemporary workspace, input and allocator reserve
1

Read

In this order, only the parts listed

0 of 4 done

  1. Caching-allocator memory managementPyTorch - checkpointing, numerical accuracy and CUDA semantics

    Memory management: memory_allocated and max_memory_allocated for tensors, memory_reserved and max_memory_reserved for the allocator, empty_cache releasing only unused segments

  2. Snapshot-based memory debuggingPyTorch - checkpointing, numerical accuracy and CUDA semantics

    Generating a Snapshot with _record_memory_history and _dump_snapshot; Allocator State History: segments, blocks and active_allocated versus inactive states; Identifying Non-PyTorch allocations

    Skip pinned host-memory capture. Use device-only snapshots for this unit.

  3. Profiler memory analysisPyTorch - reliability and performance recipes

    Step 4, Using profiler to analyze memory consumption: profile_memory with self versus total memory and the aten::empty example

  4. Mixed-Precision Training Memory AccountantTensorTonic - mixed-precision memory and transformer FLOPs

    Compute exact storage for parameters, gradients, saved activations, and optimizer state from tensor shapes and byte widths

2

Focus on

  • fp32 Adam training holds about 16 bytes per parameter before activations: 4 for the weight, 4 for the gradient, 8 for the two moment buffers. Precision and optimizer choice change the constants, not the method.
  • Allocated sums live tensors; reserved sums allocator segments. A 4 MiB tensor can sit inside 20 MiB of reserve, and nvidia-smi reports closer to reserve.
  • Peak counters are sticky. Reset them immediately before the measured region or the peak belongs to an earlier phase.
  • empty_cache returns unused segments to the driver. It never frees live tensors and never defragments them, so it cannot make a too-large tensor fit.
Common mistakes · 3
  • Reading nvidia-smi as live usage. It sees everything the driver gave the process: the CUDA context, cached segments and non-PyTorch allocations such as NCCL.
  • Counting the cuBLAS workspace as model memory. The CUDA notes say each handle and stream keeps its workspace until explicitly cleared, so take the baseline after a warm-up matmul, not before.
  • Comparing a derived model against current allocated only. Peak across forward, backward and optimizer phases is the number that must fit, and it needs a reset counter.
3

Try it yourself

Closed-book, before checking anything

Derive fp32 Adam memory for a 10M-parameter model as 160 MB (152.6 MiB) before activations. Then, in a fresh process on a CUDA GPU, allocate one fp32 tensor and read memory_allocated as 4.00 MiB and memory_reserved as 20.00 MiB. Run one matmul and read allocated again: it stays higher by the cuBLAS workspace (about 8 MiB on an RTX 3050 with PyTorch 2.14). State which number nvidia-smi tracks.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A 10M-parameter model trains in fp32 with Adam and no AMP. How many bytes do parameters, gradients and optimizer states hold?Answer

    40 MB, 40 MB and 80 MB: 160 MB total before activations, workspace, inputs and reserve.

  2. 2.After allocating one fp32 tensor, allocated reads 4.00 MiB and reserved reads 20.00 MiB. What is the extra 16 MiB?Answer

    The unused rest of the 20 MiB segment the allocator reserved for this request, held for reuse, not live tensors. nvidia-smi tracks closer to reserved than to allocated.

  3. 3.Peak grows every loop iteration while current stays flat. What was forgotten?Answer

    reset_peak_memory_stats before the measured region. Max counters never decrease on their own.

  4. 4.Will empty_cache let a run allocate one bigger tensor than the OOM size?Answer

    No. It returns unused cached segments to the driver for other processes, but it frees no live tensors, so the docs say it cannot increase the memory available to PyTorch.

5

Practice

You're done when

Your hand-derived parameter, gradient and optimizer bytes match the profiler within stated exclusions, and you can attribute any allocated-versus-reserved gap to segments, peak staleness or outside-allocator memory.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 6 more in the section
  • PyTorch - reliability and performance recipesPyTorch · primary

    Use the Profiler, Automatic Mixed Precision, model loading and Benchmark recipes, then the Performance Tuning Guide. Apply each to one compact model from an earlier section and keep a CPU fallback when CUDA is unavailable.

  • PyTorch - checkpointing, numerical accuracy and CUDA semanticsPyTorch · required

    Use the official user-guide entries for torch.utils.checkpoint, numerical accuracy, CUDA semantics, reproducibility and serialization. Predict memory categories before measuring and define resume equivalence before running.

  • TensorTonic - mixed-precision memory and transformer FLOPsTensorTonic · support

    Solve only Mixed-Precision Training Memory Accountant and Transformer Training FLOP Estimator. Reconcile both with the compact model's profiler and document every included and excluded term.

Also in this section

  • PyTorch - compiler troubleshootingPyTorch · required

    Read graph breaks, guards, recompilations and logging. Compile one stable fragment, intentionally trigger a graph break or recompilation, inspect it, and compare eager and compiled outputs and gradients.

  • Deep Learning Training DebuggerRoadmap-Final · reference

    Use the failure-injection, measurement and evidence rules as the deeper standard. The full Tier 2 project is a later route and is not added to this stage milestone.

  • Learn PyTorch - profiler walkthroughDaniel Bourke · optional

    Use notebook 10 only if the official profiler route remains unclear. Transfer the relevant annotations into the compact model instead of keeping the tutorial code.

  • TrenTorch - precision, checkpointing and resumeTrenTorch · support

    Solve Loss Scaling, FP16/BF16 Representable Range, Gradient Checkpointing and Resume-from-checkpoint in NumPy, then reproduce each behavior with the PyTorch API in the compact model.

  • Python os - `os.replace`Python Software Foundation · reference

    Read os.replace for the atomic-rename step of checkpoint writes: save to a temp file in the same directory, flush and fsync, then replace the final name.

  • Hands-On Machine Learning with Scikit-Learn and PyTorchAurelien Geron (O'Reilly, 2025) · support

    Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why float16 training underflows and what fp32 primary weights and loss scaling fix.