Below is an organized summary of the main issues and recommendations—along with code snippets—to help you resolve the memory problems.
1. Memory Allocation Mismatch
Even though your SBATCH script requests 64 GB using:
#SBATCH --mem=64G
your job report shows only ~16 GB allocated. This may happen if your cluster enforces limits per node, uses a different directive (e.g. --mem-per-cpu), or has a configuration override. Verify with your cluster admin that the requested 64 GB is truly being granted. For example, you might try:
#SBATCH --mem-per-cpu=8G
#SBATCH -c 8
to explicitly request 8 GB per CPU across eight cores.
2. Memory Leak from TensorFlow Graph Accumulation
Each trial builds a new model while old TensorFlow graphs (and corresponding ops) stick around if not properly cleared—even if you call:
del model, history
tf.keras.backend.clear_session()
gc.collect()
The gradual accumulation of graph operations can eventually lead to an “Out Of Memory” (OOM) error.
Recommended improvements:
- Clear the session immediately:
Start by calling
tf.keras.backend.clear_session() before getting rid of any objects.
- Call garbage collection multiple times:
Instead of one gc.collect(), loop through garbage collection a few times and bring in an additional trim on memory.
Here’s an example of a more aggressive cleanup function:
import gc
import time
import ctypes
import tensorflow as tf
def cleanup_trial():
"""Perform an extensive cleanup after each trial."""
# Clear any remnants from the Keras backend
tf.keras.backend.clear_session()
# Multiple rounds of garbage collection
for _ in range(3):
gc.collect()
# Clear GPU memory stats (if using GPU)
if tf.config.list_physical_devices('GPU'):
# Reset GPU memory stats
tf.config.experimental.reset_memory_stats('GPU:0')
# Trim the malloc heap (helpful on Linux systems)
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)
# Small pause to let cleanup complete
time.sleep(1)
Then, in your objective function (or trial loop), use a try-finally block to ensure cleanup always runs:
try:
# ... your model training / evaluation code ...
best_vals = ... # your trial result
return best_vals
finally:
# Delete explicitly to help garbage collection
del model, history, train_ds, val_ds, raw_train, raw_val
# Delete any additional objects that may hold references
cleanup_trial()
3. Dataset Creation and Cleanup
If you are recreating datasets within every trial without releasing the previous datasets, the memory may fill up over time. For example:
train_ds = raw_train.map(tfgnn.keras.layers.ParseExample(example_input_spec))
val_ds = raw_val.map(tfgnn.keras.layers.ParseExample(example_input_spec))
Recommendations:
- Avoid aggressive caching or prefetching that could retain too many batches in memory.
- Limit your dataset pipeline’s buffer sizes. For example:
raw_train = (tf.data.TFRecordDataset([train_path], compression_type="GZIP")
.shuffle(1000, reshuffle_each_iteration=True) # allow reshuffling
.batch(batch_size, drop_remainder=True)
.prefetch(2)) # use a modest prefetch buffer instead of tf.data.AUTOTUNE
Also, consistently delete your dataset variables after each trial:
del train_ds, val_ds, raw_train, raw_val
gc.collect()
4. Memory Monitoring
Adding logs can help pinpoint where your memory usage is climbing:
def rss_gb():
import psutil, os
process = psutil.Process(os.getpid())
return process.memory_info().rss / 1024**3
def log_memory(stage: str, trial_num: int):
"""Log memory usage at a given stage."""
current_rss = rss_gb()
print(f"[Trial {trial_num}] Memory usage after {stage}: {current_rss:.2f} GB")
# If using GPU, log the GPU memory usage as well (if available)
if tf.config.list_physical_devices('GPU'):
try:
gpu_stats = tf.config.experimental.get_memory_info('GPU:0')
current_gpu = gpu_stats.get('current', 0) / 1024**3
print(f" [Trial {trial_num}] GPU memory: {current_gpu:.2f} GB")
except Exception as e:
print("Could not retrieve GPU memory information:", e)
# Usage at various stages:
log_memory("start", trial.number)
# ... dataset creation, model building, training, etc.
log_memory("after training", trial.number)
This logging will give you insight into which parts of your pipeline are responsible for rising memory consumption.
5. Handling Optuna Storage
The SQLite database used by Optuna may grow as you save more trials. You can mitigate this by periodically cleaning or checkpointing the storage.
For instance, every 10 trials, you might trigger a major collection and let the study commit the progress:
if trial.number % 10 == 0:
# This forces a new trial and may help flush the storage
study.storage.create_new_trial(study._study_id)
gc.collect()
6. Optional: XLA Memory Optimization and Environment Settings
If you re-enable XLA or want to optimize GPU memory allocation, consider these environment settings:
export TF_GPU_ALLOCATOR=cuda_malloc_async
export TF_FORCE_GPU_ALLOW_GROWTH=true
They can help reduce fragmentation and improve memory management on GPU devices.
7. Consider Batching Your Trials
Running 1000 trials continuously without an explicit cleanup between batches may lead to accumulated memory artifacts. Instead, try processing trials in batches. For example:
from functools import partial
for batch_start in range(0, 1000, 50):
study.optimize(
partial(objective, model_name=model_name, pre_train=pre_train),
n_trials=50,
timeout=4000 # a reasonable timeout for each batch
)
# Call extensive cleanup between batches
cleanup_trial()
print(f"Completed trials {batch_start} to {batch_start + 50}")
Summary
- Confirm you are allocated the full 64 GB as expected.
- Clear TensorFlow sessions and explicitly delete objects vs. relying solely on
gc.collect().
- Limit prefetch and caching in data pipeline to avoid accumulating batches in memory.
- Integrate memory usage logging to help pinpoint the leak.
- Periodically run cleanup between trial batches to ensure resources are released.
Following these steps should help mitigate the OOM errors by ensuring that unused resources are properly freed between trials.