Bash Script to Wait for GPU Memory to Free Up Before Running PyTorch Training Script

Abstract: Resolve PyTorch Out of Memory errors by automatically waiting for sufficient GPU VRAM to become available before launching training jobs.

Created: 2026-08-17 by

Use nvidia-smi with the --query-gpu=memory.used,memory.total,index flags and parse the output to check if available memory exceeds a threshold. A bash loop retries every few seconds until the condition is met, ensuring your PyTorch script starts only when sufficient GPU resources are free.

Understanding GPU Memory Constraints

When running deep learning workloads, multiple processes often compete for limited Video RAM (VRAM). If you attempt to launch a new training job while another process holds significant memory, PyTorch will fail with an Out of Memory (OOM) error. This is particularly common in shared server environments or when debugging residual memory leaks from previous runs. To automate this process, you need a script that actively monitors the Graphics Processing Unit (GPU) state. The standard tool for this on Linux systems is nvidia-smi. However, parsing its output correctly is critical because the format can vary depending on whether you query specific metrics or use default table views. Many existing scripts fail because they assume a static column layout or ignore the specific GPU index being targeted. For more context on how to inspect these resources manually, see our guide on viewing processes using GPU memory in Linux. Understanding which processes consume VRAM helps in diagnosing why memory might not be freeing up as expected.

Constructing the Monitoring Script

The core logic involves querying the current memory usage, calculating the available portion, and comparing it against a desired minimum. Below is a robust implementation that addresses common pitfalls such as variable scoping and output parsing. Create a file named wait_for_gpu.sh and insert the following code:
#!/bin/bash

# Configuration
GPU_ID=${1:-0}          # Default to GPU 0 if not specified
MIN_FREE_GB=${2:-8}     # Minimum free GB required (default 8GB)
CHECK_INTERVAL=5        # Seconds between checks
MAX_RETRIES=100         # Safety limit to prevent infinite loops

echo "Waiting for GPU $GPU_ID to have at least ${MIN_FREE_GB}GB free..."

retries=0

while [ $retries -lt $MAX_RETRIES ]; do
    # Query specific metrics: used memory, total memory, and index
    # Using comma-separated query ensures predictable output order
    output=$(nvidia-smi --query-gpu=memory.used,memory.total,index --format=csv,noheader,nounits -i $GPU_ID)

    # Check if nvidia-smi returned valid data
    if [ -z "$output" ]; then
        echo "Error: Could not retrieve GPU info. Is the driver loaded?"
        exit 1
    fi

    # Parse the CSV output
    # Format: used,total,index
    # Example: 1024,8192,0
    used_mem=$(echo "$output" | cut -d',' -f1)
    total_mem=$(echo "$output" | cut -d',' -f2)

    # Calculate free memory in MB
    free_mem_mb=$((total_mem - used_mem))
    free_mem_gb=$(echo "scale=2; $free_mem_mb / 1024" | bc)

    echo "Current Free Memory: ${free_mem_gb} GB"

    # Check if free memory meets threshold
    # Using bc for floating point comparison
    if (( $(echo "$free_mem_gb >= $MIN_FREE_GB" | bc -l) )); then
        echo "GPU $GPU_ID is ready! Starting training..."
        break
    fi

    retries=$((retries + 1))
    echo "Waiting ${CHECK_INTERVAL}s... (Attempt $retries/$MAX_RETRIES)"
    sleep $CHECK_INTERVAL
done

if [ $retries -eq $MAX_RETRIES ]; then
    echo "Timeout: GPU did not free up enough memory."
    exit 1
fi

# Execute the target command passed as arguments
if [ $# -gt 2 ]; then
    shift 2
    exec "$@"
else
    echo "No command provided to execute after wait."
    exit 1
fi

Key Implementation Details

This script avoids several common bugs found in simpler implementations. First, it uses the -i $GPU_ID flag to explicitly target the correct GPU. Older scripts often rely on line numbers in multi-GPU outputs, which breaks if GPUs are indexed differently or if the query returns unexpected rows. By specifying the index, we ensure cut -d',' -f1 always refers to the memory of the intended device. Second, the script uses bc for arithmetic. Bash does not support floating-point math natively. Calculating gigabytes from megabytes requires division, which bc handles precisely. Without bc, integer division would truncate values incorrectly, leading to false positives where low memory appears sufficient. Third, the script accepts the training command as arguments. The shift 2 command removes the first two positional parameters (GPU ID and Memory Threshold), leaving the remaining arguments to be executed via exec. This allows you to pass environment variables or complex PyTorch commands directly without subshell overhead. If you encounter issues with script execution permissions or path resolution, review our article on Linux RHEL 7 shell script execution issues for troubleshooting steps.

Usage Examples

Make the script executable:
chmod +x wait_for_gpu.sh
Run a PyTorch training script, requiring at least 10GB of free memory on GPU 1:
./wait_for_gpu.sh 1 10 python train.py --epochs 100
The script will poll every 5 seconds. Once GPU 1 has more than 10GB free, it immediately launches train.py.

Cleaning Up Residual Memory

Sometimes memory does not free up automatically due to zombie processes or kernel-level allocations. Before relying on this waiting script, ensure no stale Python processes are holding locks. You can identify them using tools mentioned in freeing GPU memory in Linux. Killing these processes manually before running your batch script reduces the likelihood of timeouts.

Frequently Asked Questions

What happens if nvidia-smi fails to return data?

The script checks for empty output and exits with an error code 1 if no data is retrieved. This usually indicates that the NVIDIA driver is not installed or the user lacks permission to read GPU stats. Ensure you are running the script with appropriate privileges or as the root user if necessary.

Can I monitor multiple GPUs simultaneously?

This script is designed for a single GPU instance per invocation. To monitor multiple GPUs, you would need to wrap the logic in a function that iterates over an array of GPU IDs. Each GPU would require its own threshold check within the loop before proceeding to the main command.

Why use bc instead of bash arithmetic?

Bash arithmetic expansion ($((...))) only supports integers. Since GPU memory totals and usage are often large numbers that result in fractional gigabytes, integer truncation would make comparisons inaccurate. bc provides arbitrary precision calculator capabilities needed for reliable floating-point evaluation.

Is there a risk of the script hanging indefinitely?

Yes, if the GPU never frees up memory, the script could run forever. The implementation includes a MAX_RETRIES counter to prevent this. If the limit is reached, the script terminates with a timeout message, allowing your higher-level workflow to handle the failure gracefully.

How does this differ from using CUDA_VISIBLE_DEVICES?

CUDA_VISIBLE_DEVICES restricts which GPUs a process can see but does not manage memory availability. It is useful for isolation but does not solve OOM errors caused by insufficient VRAM. Combining both strategies—using this script to ensure space and CUDA_VISIBLE_DEVICES to isolate devices—is the most robust approach.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More