How to fix ResourceExhaustedError OOM when allocating tensor
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
ResourceExhaustedError: OOM when allocating tensor means TensorFlow tried to create a tensor that did not fit into available device memory. The fix is rarely a single magic flag. You usually need to identify whether the pressure comes from batch size, model size, input size, or memory allocation behavior.
Start with the Biggest Lever: Batch Size
The fastest practical fix is often to reduce batch size:
If you were training with batch_size=64, moving to 16 or 8 can dramatically reduce activation memory. This matters because training stores intermediate tensors for backpropagation, not just the inputs and outputs.
A large batch is the most common cause of this error on GPUs.
Check Input Resolution and Tensor Shapes
Sometimes the model is not unusually large, but the inputs are. Images, long sequences, and large attention tensors can explode memory usage.
For example, resizing images before training can help:
Reducing width, height, sequence length, or embedding dimensions often saves more memory than small optimizer tweaks.
Enable GPU Memory Growth
By default, TensorFlow may reserve GPU memory aggressively. Allowing growth can make debugging easier and can reduce wasted preallocation:
This does not create more memory, but it can prevent TensorFlow from grabbing all GPU memory up front and interacting badly with other processes.
Reduce Model Memory Pressure
If batch size alone is not enough, shrink the model:
- fewer layers
- narrower dense layers
- fewer filters in convolution blocks
- shorter sequence lengths
- smaller hidden state sizes
For example, this difference matters:
versus an oversized version with several huge dense layers. Large dense layers are especially memory-hungry because both weights and activations grow quickly.
Mixed Precision Can Help
If your hardware supports it, mixed precision can reduce memory usage by using lower-precision tensors where appropriate:
This can both speed up training and reduce memory consumption on supported GPUs. It is not always the first fix, but it is a strong option when the model is close to fitting already.
Watch the Input Pipeline Too
Memory problems are not always inside the model. Bad dataset handling can cause extra pressure:
- loading the full dataset into RAM
- caching enormous tensors unexpectedly
- creating giant batches before mapping
- duplicating arrays in Python generators
Using tf.data carefully helps:
Be cautious with .cache() on very large datasets. It is useful, but only when the dataset actually fits.
Distinguish Training from Inference
Training uses more memory than inference because gradients and intermediate activations must be kept around. So if inference works and training fails, that does not mean TensorFlow is inconsistent. It usually means the model only fits without backpropagation overhead.
That is also why validation may succeed on a model size that training cannot handle.
Inspect the Actual Allocation Site
The stack trace often tells you which operation triggered the failure:
- a convolution
- a matrix multiply
- an embedding lookup
- a reshape into a giant tensor
That clue matters. If the error comes from one attention layer or one concatenation, the solution is often architectural rather than global. Read the failing tensor shape carefully before applying generic fixes blindly.
Common Pitfalls
- Lowering batch size once by a tiny amount and assuming memory is no longer the problem.
- Forgetting that training needs more memory than inference.
- Using
.cache()on datasets that do not fit in memory. - Assuming
set_memory_growthcreates extra memory instead of only changing allocation behavior. - Ignoring the tensor shape in the error trace, which often points directly at the real culprit.
Summary
- The first practical fix for TensorFlow OOM errors is usually reducing batch size.
- Input resolution, sequence length, and hidden dimensions can matter as much as model depth.
- GPU memory growth can improve allocation behavior, but it does not increase capacity.
- Mixed precision and smaller architectures help when the model is close to fitting.
- Read the failing tensor shape and operation in the traceback before guessing.
Related reading
- How to fix ResourceExhaustedError OOM when allocating tensor
- How to fix 'RuntimeError get_session is not available when using TensorFlow 2.0.
- How to fix RuntimeError Missing implementation that supports loader when calling hub.text_embedding_column method?
- How to fix ‘RuntimeError The Session graph is empty. Add operations to the graph before calling run.”
- How to fix ROC curve with points below diagonal?
- how to fix slow kmeans of opencv
- How to force browsers to reload cached CSS and JS files?
- How to force garbage collection in Java?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.