iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Reducing GPU memory use and avoiding out-of-memory (OOM) errors starts with measurement, not with blindly emptying the CUDA cache. First determine whether live tensors, cached allocator blocks, model weights, activations, optimizer state, sequence length, or runtime overhead is consuming memory. Then apply the remedy that matches the cause: smaller per-device batches, shorter sequences, gradient accumulation, mixed precision, activation checkpointing, leaner optimizer state, offloading, or a more careful multi-device placement. If the optimized workload still exceeds the card’s physical capacity, additional VRAM may be necessary.
What actually causes a GPU OOM in an AI workload?
A GPU OOM means the framework could not satisfy an allocation, but the reason is not always that every byte of VRAM is occupied by useful tensors. Training commonly combines model parameters, gradients, optimizer state, and saved intermediate activations. Inference generally needs model weights plus attention or key-value caches, temporary working buffers, CUDA initialization, framework kernels, and any other processes sharing the device.
Two workloads with the same model can therefore have very different peaks. A long context, large padded batch, generation cache, or optimizer can push a previously successful run over the limit. Conversely, a high total in nvidia-smi may include memory that PyTorch has reserved for reuse rather than memory currently held by live tensors.
How do I tell whether tensors or the caching allocator use the memory?
Compare PyTorch’s allocated and reserved counters before changing settings. memory_allocated() and its peak counterpart describe live tensor occupancy. memory_reserved() and max_memory_reserved() describe memory managed by PyTorch’s CUDA caching allocator, including unused blocks kept for future allocations. The distinction is documented in PyTorch’s CUDA semantics guide.
Popular on Amazon
- 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
- 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
- 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
- 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
- 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.
import torch
torch.cuda.reset_peak_memory_stats()
# run one representative training step or inference request here
print('allocated now:', torch.cuda.memory_allocated())
print('reserved now: ', torch.cuda.memory_reserved())
print('peak allocated:', torch.cuda.max_memory_allocated())
print('peak reserved: ', torch.cuda.max_memory_reserved())
print(torch.cuda.memory_summary())
Run the measurement on a representative batch, not only during model loading. Record the peak after warm-up and during the operation that fails, such as backward propagation or token generation. At the same time, use nvidia-smi to see total device use and which processes own it:
nvidia-smi --query-gpu=index,name,memory.total,memory.used,memory.free --format=csv
nvidia-smi
A large reserved-minus-allocated gap suggests cached blocks or fragmentation may matter; a high allocated value indicates that the workload itself needs more live tensor storage. Neither command alone identifies the exact tensor, so inspect the operation and retain a memory summary around it.
Does torch.cuda.empty_cache() fix an OOM?
Usually, no. torch.cuda.empty_cache() releases unused cached blocks so another application can use them, but it does not release memory held by live tensors and does not increase the capacity available to those tensors. Treat it as cache management, not as a general memory-reduction technique. PyTorch explains this behavior in its CUDA documentation.
torch.cuda.empty_cache()
It can help after a genuinely unused block has been returned to the allocator, particularly when another process needs the device. It cannot make an oversized model, batch, activation graph, or generation cache fit. If calling it appears to help, continue measuring: the underlying issue may be allocation churn or fragmentation rather than insufficient model capacity.
How can I find a memory leak or retained computation graph?
If memory rises every iteration instead of reaching a repeatable peak, look for Python references that keep tensors and their autograd graphs alive. Common examples are appending a loss tensor to a list, storing outputs for logging without detaching them, closures that capture batch tensors, and metrics that retain the graph.
When a value is needed only for reporting, store a detached scalar or a CPU copy rather than the graph-connected tensor:
Also popular on Amazon
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
running_loss += loss.detach().item()
logged_logits.append(logits.detach().cpu())
Do not keep an entire output list merely to calculate a statistic that can be updated incrementally. Check the references in callbacks, logging code, exception handlers, and notebook variables. The PyTorch FAQ specifically warns that tensors connected to a computation graph can retain memory and points to checkpointing as another way to control peaks.
What should I change first when training runs out of memory?
Start with the least disruptive change that targets the largest category. The following order generally provides a clear diagnostic signal while preserving model quality.
- Lower the per-device batch size. Fewer examples means fewer sets of activations must remain live for backpropagation. Change one device’s batch, rerun the same step, and record peak allocated memory.
- Recover effective batch size with gradient accumulation. Process several micro-batches, accumulate gradients, and update the optimizer after the desired number of steps. This preserves a larger effective batch without materializing it on one GPU, although it increases the number of forward and backward passes per optimizer update.
- Reduce sequence length and padding. Long sequences create larger attention and intermediate tensors. Bucket examples by length, cap the maximum context when acceptable, and avoid padding every sample to an unnecessarily large global maximum.
- Enable mixed precision when the hardware and operations support it. Lower-precision storage for eligible intermediates can reduce memory and may allow a larger batch. Validate numerical behavior and verify that the layers consuming most memory actually run in the selected precision.
- Use activation checkpointing when activations dominate. Checkpointing stores selected activations and recomputes others during backward propagation. It lowers peak memory at the cost of extra compute, so it is most useful when model weights and optimizer state already fit.
- Reduce optimizer-state memory. Optimizers can require additional copies of parameters and moment estimates. Hugging Face’s model-memory guide discusses quantized optimizer variants as an option. Confirm that the chosen optimizer supports your model and evaluate convergence and stability rather than assuming all quantized variants behave identically.
- Offload selected activations when host RAM and transfer time are acceptable. The TRL memory-reduction documentation describes moving activations to CPU memory and bringing them back for backward computation. This lowers GPU peaks but adds host-to-device traffic and can substantially increase training time.
How do gradient accumulation and checkpointing differ?
Gradient accumulation reduces the number of samples present in one device batch; checkpointing reduces how many intermediate activations are retained for each sample. They solve different pressure points and can be combined. Accumulation increases the number of micro-steps per update, while checkpointing increases backward compute through recomputation.
How do sequence length and padding create avoidable peaks?
Token count is often a more useful control than nominal example count. A batch of a few very long sequences can require more memory than a larger batch of short sequences. Dynamic padding or length-based bucketing keeps each batch closer to its actual token count.
Some TRL trainer paths support padding-free batching, which concatenates sequences to avoid padding waste. The TRL documentation notes that this option is not currently available in DPOTrainer and may fall back to standard padding. Check the exact trainer and installed version before relying on the setting; an unsupported option will not reduce memory.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →When does mixed precision help, and what can go wrong?
Mixed precision uses lower-precision arithmetic for eligible operations while retaining higher precision where needed. It can reduce the storage of activations and temporary tensors, but savings depend on the model, hardware, kernels, and framework path. NVIDIA’s mixed-precision training guide recommends checking whether the workload’s slow or memory-heavy portions actually use the selected precision and whether the resulting capacity permits a larger batch.
Also popular on Amazon
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Enable the mode supported by your framework and accelerator, then validate loss behavior, convergence, and any numerically sensitive layers. A setting that changes a few small operators will not materially reduce the peak if attention, convolution, or large embeddings remain in a higher-precision representation. Do not infer support solely from a GPU’s marketing label; verify the runtime’s documented path.
How should I reduce memory during inference and model loading?
Inference usually has no gradients or optimizer state, but it still needs room for weights, temporary activations, attention or key-value caches, CUDA initialization, kernels, and concurrent processes. Use the smallest model representation and precision that meets your quality requirement and is supported by the runtime.
When loading a large model across GPUs or between GPU and CPU, leave headroom below advertised VRAM. Hugging Face Accelerate warns that initial CUDA allocation loads kernels and that a device’s full nominal capacity is not available for model data. Its big-model inference guide recommends adjusting max_memory to account for actual device use.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteA placement budget should reserve space for:
- CUDA context and framework kernels;
- temporary tensors created during a forward pass;
- the generation or attention cache, which grows with context and output length;
- other processes and monitoring tools; and
- short-lived peaks during layer transfers or model initialization.
A model that loads successfully can still OOM on the first long request if the cache and runtime working memory were not included. Test representative prompt and generation lengths, inspect each device’s allocation, and keep placement decisions explicit. If a layer split places a large cache on one GPU, rebalance the placement rather than setting every device budget to its advertised maximum.
Can distributed training or serving create a one-GPU spike?
Yes. Sharding normally spreads weights, but generation or checkpoint operations can temporarily gather them. TRL documents an option to disable ZeRO-3 gathering for generation so sharded weights are not assembled on one GPU; the trade-off is slower generation. Use that option only when the installed trainer and distributed configuration support it.
For online multi-GPU serving, TRL also documents a vLLM sleep mode that offloads parameters and cache between phases. Waking the model requires transferring them back, adding latency. Measure the phase that matters to your service and confirm that your versions implement the option before adding it to a production configuration.
Also popular on Amazon
- Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
- Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
- 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
- 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
- Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.
When is allocator fragmentation the real problem?
Fragmentation is plausible when reserved memory is much larger than allocated memory and an allocation fails despite apparently available total space. Inspect memory_summary() and inactive split blocks first; do not change allocator settings merely because an OOM occurred.
Recommended Free Tools
PyTorch exposes allocator configuration through PYTORCH_ALLOC_CONF. For allocation patterns involving changing tensor sizes, expandable_segments can reduce unusable split regions in supported configurations:
export PYTORCH_ALLOC_CONF=expandable_segments:True
max_split_size_mb is a last-resort option for the native allocator backend when inactive split blocks are large. It is not a universal speed or memory setting, and the useful value depends on the allocation pattern. Apply one change at a time, restart the process, and compare peak allocated, peak reserved, and runtime behavior.
TRL documents expandable_segments:True for long runs where fragmentation can accumulate. Since PyTorch 2.10, PYTORCH_ALLOC_CONF is the canonical name; a documented compatibility caveat remains for some vLLM sleep-mode configurations that use PYTORCH_CUDA_ALLOC_CONF. Match the variable name to the installed PyTorch, backend, and serving stack.
What is a practical diagnosis workflow?
Use a repeatable sequence so each change has an observable result:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
- Capture the failure context. Record GPU model, total VRAM, framework and library versions, batch or token count, sequence and generation lengths, precision, and concurrent processes.
- Reproduce one representative step or request. Warm up the model, reset peak statistics, then measure the operation that reaches the maximum.
- Compare allocated with reserved. A high allocated peak points to workload capacity; a large reserved gap points toward cache behavior or fragmentation.
- Classify the consumer. For training, estimate weights, gradients, optimizer state, and activations. For inference, include weights, caches, temporary buffers, initialization, and placement overhead.
- Apply one targeted change. Lower batch or sequence length first, then use accumulation, precision, checkpointing, optimizer reduction, offloading, or placement changes as indicated.
- Repeat the same workload. Record peak allocated and reserved memory, throughput or step time, numerical behavior, and whether the failure moved to a later operation.
- Escalate only after software fixes. If the optimized, correctly placed workload still exceeds physical VRAM, evaluate a larger-memory GPU or a smaller model.
Should I buy a GPU with more VRAM?
More VRAM is a capacity escalation, not a substitute for diagnosing avoidable allocations. A larger card helps when weights, activations, cache, and runtime overhead genuinely exceed the current device after sensible reductions. It does not fix a retained graph, an accidental all-gather, an unbounded generation cache, or a second process occupying the card.
Also popular on Amazon
- 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
- 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
- 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
- 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
- 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.
As a concrete reference, NVIDIA lists the RTX 5090 with 32 GB of GDDR7, 575 W total graphics power, and 1,000 W required system power for its stated reference configuration. The NVIDIA product page cautions that add-in-card specifications can vary. Those figures are product specifications, not a guarantee that a particular model or workload will fit.
Before upgrading, check case dimensions, power-supply capacity and connectors, cooling, driver and framework compatibility, availability, and total cost. Estimate the required headroom for your longest context, largest batch, cache, and other processes rather than matching the model’s weight size alone.
Which remedy should I choose?
| Observed symptom | Most likely pressure | First action | Trade-off |
|---|---|---|---|
| Peak allocated rises with batch size | Activations and per-step tensors | Lower per-device batch; use gradient accumulation | More micro-steps per update |
| Long prompts fail while short prompts fit | Sequence or cache length | Cap context, reduce padding, shorten generation | Less context or output |
| Training fails during backward, weights fit | Saved activations | Activation checkpointing or activation offload | Recomputation or transfer time |
| Optimizer initialization causes the failure | Optimizer state | Use a supported memory-efficient or quantized optimizer | Compatibility and possible convergence changes |
| Reserved greatly exceeds allocated | Cache or fragmentation | Inspect allocator statistics; then consider allocator configuration | Version- and backend-dependent behavior |
| Model loads but first request fails | Runtime overhead or cache | Lower placement ceilings and reserve headroom | More CPU placement or lower concurrency |
What should I remember before changing settings?
There is no universal batch size, dtype, allocator value, or expected memory saving without the model, GPU, framework version, sequence shape, and performance target. Validate changes on the real workload, monitor both allocated and reserved peaks, and keep a record of throughput and numerical behavior. The reliable path is to identify the dominant consumer, reduce that consumer, and reserve explicit headroom for transient runtime use.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Frequently Asked Questions
Why does GPU memory remain high after a Python tensor is deleted?
PyTorch may keep the freed block in its caching allocator for reuse, so the total shown by the driver can stay high even though live tensor allocation fell. Check allocated and reserved counters separately; release genuinely unused cached blocks only when another process needs the memory.
Can CPU RAM completely replace GPU VRAM for a large model?
CPU offload can make a model load when it cannot fit entirely on the GPU, but transfers add latency and runtime working memory still needs GPU space. The model may load successfully yet fail on a long request if cache and temporary buffers were not budgeted.
How much VRAM headroom should I leave when setting a device budget?
There is no fixed percentage that applies to every model or runtime. Reserve space for CUDA initialization, kernels, temporary tensors, caches, and other processes, then validate the longest realistic prompt or batch rather than stopping at the card’s advertised total.
Will switching everything to a lower precision always prevent OOM?
No. Only eligible operations use the lower precision, and large caches, optimizer state, padding, or retained graphs can remain the dominant consumers. Verify actual operator dtypes and monitor peak memory after the change.

