#!/usr/bin/env python3 import argparse import ctypes import os import signal import sys import time CUDA_SUCCESS = 0 def load_cudart(): candidates = [ "libcudart.so", "libcudart.so.11.0", "libcudart.so.12.0", "/usr/local/cuda/lib64/libcudart.so", "/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudart.so", "/lib/x86_64-linux-gnu/libcudart.so", ] last_error = None for name in candidates: try: return ctypes.CDLL(name) except OSError as exc: last_error = exc raise OSError(f"could not load libcudart: {last_error}") def cuda_check(code, api_name, cudart): if code == CUDA_SUCCESS: return try: name = cudart.cudaGetErrorName(code) msg = cudart.cudaGetErrorString(code) name = name.decode() if name else f"error_{code}" msg = msg.decode() if msg else "unknown CUDA error" except Exception: name = f"error_{code}" msg = "unknown CUDA error" raise RuntimeError(f"{api_name} failed: {name} ({msg})") def parse_gpus(raw_values): gpus = [] for item in raw_values: for part in item.split(","): part = part.strip() if not part: continue try: gpus.append(int(part)) except ValueError as exc: raise argparse.ArgumentTypeError(f"invalid GPU id: {part}") from exc if not gpus: raise argparse.ArgumentTypeError("at least one GPU id is required") return gpus def format_bytes(num_bytes): gib = num_bytes / (1024 ** 3) return f"{gib:.2f} GiB" def main(): parser = argparse.ArgumentParser( prog="currentest", description="Reserve a fixed amount of GPU memory on selected GPUs and keep it allocated.", ) parser.add_argument( "--gpus", nargs="+", required=True, help="GPU ids to reserve, for example: --gpus 0 1 or --gpus 0,1", ) parser.add_argument( "--gb", type=float, required=True, help="Amount of memory to reserve on each GPU, in GiB.", ) parser.add_argument( "--chunk-mb", type=int, default=256, help="Allocation chunk size in MiB. Default: 256", ) args = parser.parse_args() gpus = parse_gpus(args.gpus) if args.gb <= 0: raise SystemExit("--gb must be positive") if args.chunk_mb <= 0: raise SystemExit("--chunk-mb must be positive") total_bytes = int(args.gb * (1024 ** 3)) chunk_bytes = int(args.chunk_mb * (1024 ** 2)) if chunk_bytes > total_bytes: chunk_bytes = total_bytes cudart = load_cudart() cudart.cudaGetDeviceCount.argtypes = [ctypes.POINTER(ctypes.c_int)] cudart.cudaGetDeviceCount.restype = ctypes.c_int cudart.cudaSetDevice.argtypes = [ctypes.c_int] cudart.cudaSetDevice.restype = ctypes.c_int cudart.cudaMalloc.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t] cudart.cudaMalloc.restype = ctypes.c_int cudart.cudaFree.argtypes = [ctypes.c_void_p] cudart.cudaFree.restype = ctypes.c_int cudart.cudaMemGetInfo.argtypes = [ ctypes.POINTER(ctypes.c_size_t), ctypes.POINTER(ctypes.c_size_t), ] cudart.cudaMemGetInfo.restype = ctypes.c_int cudart.cudaGetErrorName.argtypes = [ctypes.c_int] cudart.cudaGetErrorName.restype = ctypes.c_char_p cudart.cudaGetErrorString.argtypes = [ctypes.c_int] cudart.cudaGetErrorString.restype = ctypes.c_char_p device_count = ctypes.c_int() cuda_check(cudart.cudaGetDeviceCount(ctypes.byref(device_count)), "cudaGetDeviceCount", cudart) max_gpu = max(gpus) if max_gpu >= device_count.value: raise SystemExit( f"requested GPU {max_gpu}, but this machine reports only {device_count.value} CUDA device(s)" ) allocations = {} stop = False def handle_signal(signum, frame): nonlocal stop stop = True signal.signal(signal.SIGINT, handle_signal) signal.signal(signal.SIGTERM, handle_signal) print(f"Detected {device_count.value} CUDA device(s).") print(f"Reserving {format_bytes(total_bytes)} on each GPU: {', '.join(map(str, gpus))}") print(f"Allocation chunk size: {format_bytes(chunk_bytes)}") sys.stdout.flush() for gpu in gpus: cuda_check(cudart.cudaSetDevice(gpu), f"cudaSetDevice({gpu})", cudart) free_before = ctypes.c_size_t() total_before = ctypes.c_size_t() cuda_check( cudart.cudaMemGetInfo(ctypes.byref(free_before), ctypes.byref(total_before)), f"cudaMemGetInfo(before, {gpu})", cudart, ) remaining = total_bytes ptrs = [] while remaining > 0 and not stop: size = min(chunk_bytes, remaining) ptr = ctypes.c_void_p() err = cudart.cudaMalloc(ctypes.byref(ptr), size) if err != CUDA_SUCCESS: if ptr.value: cudart.cudaFree(ptr) cuda_check(err, f"cudaMalloc({size}) on GPU {gpu}", cudart) ptrs.append(ptr) remaining -= size allocations[gpu] = ptrs free_after = ctypes.c_size_t() total_after = ctypes.c_size_t() cuda_check( cudart.cudaMemGetInfo(ctypes.byref(free_after), ctypes.byref(total_after)), f"cudaMemGetInfo(after, {gpu})", cudart, ) reserved = total_before.value - free_after.value print( f"GPU {gpu}: before {format_bytes(free_before.value)} free, after {format_bytes(free_after.value)} free, " f"reserved about {format_bytes(reserved)}" ) sys.stdout.flush() if stop: break if stop: print("Stopped before completing all allocations.") sys.stdout.flush() else: print("All requested allocations are active. Press Ctrl-C to release them and exit.") sys.stdout.flush() try: while not stop: time.sleep(60) finally: for gpu, ptrs in allocations.items(): try: cuda_check(cudart.cudaSetDevice(gpu), f"cudaSetDevice({gpu}) during cleanup", cudart) except Exception: pass for ptr in ptrs: if ptr and ptr.value: try: cuda_check(cudart.cudaFree(ptr), f"cudaFree({ptr.value}) on GPU {gpu}", cudart) except Exception: pass if __name__ == "__main__": main()