Looking at your code and the error message, you're experiencing an Out-Of-Memory (OOM) error. The job was killed after using 15.86GB out of 16GB reserved memory, despite requesting 64GB in your SBATCH script.
Key Issues Identified:
1. Memory Allocation Discrepancy
You requested 64GB but only got 16GB. This could be due to:
- Cluster limits on your account
- The partition's per-node memory limits
- A typo or misconfiguration
2. Memory Leak in Trial Loop
The gradual memory increase (reaching OOM after ~32 trials) indicates memory isn't being properly released between trials.
Recommended Fixes:
1. Fix Memory Allocation
# Try these alternatives in your SBATCH script:
#SBATCH --mem=64G
# OR if that doesn't work:
#SBATCH --mem-per-cpu=16G # with --cpus-per-task=4
# OR specify a high-memory partition if available:
#SBATCH --partition=highmem
2. Enhanced Memory Cleanup
Replace your current cleanup with more aggressive memory management:
def cleanup_trial():
"""Comprehensive cleanup after each trial."""
import ctypes
import time
# Clear TensorFlow session
tf.keras.backend.clear_session()
# Force garbage collection multiple times
for _ in range(3):
gc.collect()
# Clear Python's internal memory caches
if hasattr(ctypes, 'CDLL'):
try:
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)
except:
pass
time.sleep(0.5) # Brief pause for cleanup
def objective(trial, model_name, pre_train):
try:
# Your existing code...
# ... model training ...
return best_vals
finally:
# Ensure cleanup happens even if trial fails
# Delete all large objects explicitly
for var_name in ['model', 'history', 'train_ds', 'val_ds',
'raw_train', 'raw_val', 'preproc_model',
'exported_model']:
if var_name in locals():
del locals()[var_name]
cleanup_trial()
3. Limit TensorFlow Memory Growth
Add this at the start of your script:
# Configure TensorFlow to release memory
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# Limit TensorFlow's memory allocation
import tensorflow as tf
tf.config.threading.set_inter_op_parallelism_threads(2)
tf.config.threading.set_intra_op_parallelism_threads(2)
4. Dataset Memory Optimization
Modify dataset creation to reduce memory usage:
# Use smaller buffer sizes and avoid excessive caching
raw_train = (tf.data.TFRecordDataset([train_path], compression_type="GZIP")
.shuffle(1000, reshuffle_each_iteration=True)
.batch(batch_size, drop_remainder=True)
.prefetch(2)) # Use fixed small buffer instead of AUTOTUNE
raw_val = (tf.data.TFRecordDataset([val_path], compression_type="GZIP")
.batch(batch_size, drop_remainder=True)
.prefetch(2)) # Same here
# Don't cache parsed datasets
train_ds = raw_train.map(
tfgnn.keras.layers.ParseExample(example_input_spec),
num_parallel_calls=2 # Limit parallelism
)
5. Monitor and Debug Memory Usage
Add memory monitoring to identify the leak source:
def log_memory_usage(stage, trial_num):
rss = rss_gb()
print(f"[Trial {trial_num:3d}] {stage:30s}: RSS = {rss:6.2f} GB",
flush=True)
# Trigger cleanup if memory is getting high
if rss > 12.0: # If using more than 12GB
print(f"WARNING: High memory usage detected. Forcing cleanup.")
cleanup_trial()
return rss
# In your objective function:
def objective(trial, model_name, pre_train):
log_memory_usage("Start", trial.number)
# ... create datasets ...
log_memory_usage("After dataset creation", trial.number)
# ... create model ...
log_memory_usage("After model creation", trial.number)
# ... train model ...
log_memory_usage("After training", trial.number)
# ... cleanup ...
log_memory_usage("After cleanup", trial.number)
6. Run Trials in Batches
Instead of running all 1000 trials at once, batch them:
def run_optimization_in_batches(study_name, model_name, pre_train,
total_trials=1000, batch_size=25):
"""Run optimization in batches to prevent memory buildup."""
for batch_start in range(0, total_trials, batch_size):
print(f"\n{'='*50}")
print(f"Starting batch: trials {batch_start} to {batch_start + batch_size}")
print(f"{'='*50}\n")
# Load or create study
study = optuna.create_study(
study_name=study_name,
storage=f"sqlite:///{data_dir}/{study_name}.db",
load_if_exists=True,
direction="maximize",
pruner=pruner,
sampler=sampler
)
# Run batch of trials
study.optimize(
partial(objective, model_name=model_name, pre_train=pre_train),
n_trials=batch_size,
timeout=300 # 5 minutes per batch
)
# Force complete cleanup between batches
cleanup_trial()
print(f"Batch complete. Current memory: {rss_gb():.2f} GB")
# Optional: restart Python interpreter between batches
# if batch_start % 100 == 0 and batch_start > 0:
# print("Major cleanup checkpoint...")
# time.sleep(5)
# Use it instead of study.optimize():
run_optimization_in_batches(study_name, model_name, pre_train)
7. Quick Fix - Restart Job Periodically
If the above doesn't work, use a wrapper script to restart the job:
#!/bin/bash
#SBATCH --array=0-39 # 40 jobs of 25 trials each = 1000 trials
# Each array job handles 25 trials
python script.py --start-trial=$((SLURM_ARRAY_TASK_ID * 25)) --n-trials=25
The most important fixes are:
- Ensure you actually get 64GB RAM allocation
- Implement aggressive cleanup between trials
- Monitor memory usage to identify where the leak occurs
- Consider batching trials with restarts between batches
With these changes, you should be able to complete your optimization without running out of memory.