| |
| """ |
| GPU内存占用程序 |
| 占用指定CUDA设备的显存 |
| """ |
|
|
| import torch |
| import time |
| import gc |
| import argparse |
| import signal |
| import sys |
| import random |
| import math |
| from typing import List |
|
|
|
|
| class GPUMemoryOccupier: |
| def __init__(self, device_ids: List[int] = [2], memory_gb: float = 18.0): |
| """ |
| 初始化GPU内存占用器 |
| |
| Args: |
| device_ids: CUDA设备ID列表,默认为[2] |
| memory_gb: 每个设备要占用的显存大小(GB),默认为18GB |
| """ |
| self.device_ids = device_ids if isinstance(device_ids, list) else [device_ids] |
| self.memory_gb = memory_gb |
| self.allocated_tensors: dict = {device_id: [] for device_id in self.device_ids} |
| self.computation_tensors: dict = {device_id: [] for device_id in self.device_ids} |
| self.running = True |
| |
| |
| if not torch.cuda.is_available(): |
| raise RuntimeError("CUDA不可用,请检查CUDA环境配置") |
| |
| |
| available_devices = torch.cuda.device_count() |
| for device_id in self.device_ids: |
| if device_id >= available_devices: |
| raise RuntimeError(f"CUDA设备{device_id}不存在,当前可用设备数量: {available_devices}") |
| |
| print(f"目标设备: {self.device_ids}") |
| for device_id in self.device_ids: |
| print(f"设备{device_id}: {torch.cuda.get_device_name(device_id)}") |
| |
| def get_available_memory(self, device_id: int) -> float: |
| """获取指定设备的可用显存(GB)""" |
| torch.cuda.set_device(device_id) |
| total_memory = torch.cuda.get_device_properties(device_id).total_memory |
| allocated_memory = torch.cuda.memory_allocated(device_id) |
| available_memory = total_memory - allocated_memory |
| return available_memory / (1024**3) |
| |
| def get_total_memory(self, device_id: int) -> float: |
| """获取指定设备的总显存(GB)""" |
| torch.cuda.set_device(device_id) |
| total_memory = torch.cuda.get_device_properties(device_id).total_memory |
| return total_memory / (1024**3) |
| |
| def get_allocated_memory(self, device_id: int) -> float: |
| """获取指定设备已分配的显存(GB)""" |
| torch.cuda.set_device(device_id) |
| allocated_memory = torch.cuda.memory_allocated(device_id) |
| return allocated_memory / (1024**3) |
| |
| def get_all_memory_info(self) -> dict: |
| """获取所有设备的显存信息""" |
| memory_info = {} |
| for device_id in self.device_ids: |
| memory_info[device_id] = { |
| 'total': self.get_total_memory(device_id), |
| 'allocated': self.get_allocated_memory(device_id), |
| 'available': self.get_available_memory(device_id) |
| } |
| return memory_info |
| |
| def create_computation_tensors(self, device_id: int): |
| """为计算创建专门的张量""" |
| torch.cuda.set_device(device_id) |
| |
| |
| sizes = [ |
| (1024, 1024), |
| (2048, 2048), |
| (4096, 4096), |
| (8192, 8192), |
| ] |
| |
| for size in sizes: |
| try: |
| |
| tensor = torch.randn(size, dtype=torch.float32, device=f"cuda:{device_id}") |
| self.computation_tensors[device_id].append(tensor) |
| except Exception: |
| |
| continue |
| |
| def perform_gpu_computation(self, device_id: int): |
| """执行真正的GPU计算来产生使用率""" |
| torch.cuda.set_device(device_id) |
| |
| if not self.computation_tensors[device_id]: |
| return |
| |
| try: |
| |
| computation_type = random.choice([ |
| 'matrix_multiply', 'convolution', 'reduction', |
| 'element_wise', 'transpose_ops', 'mixed_operations' |
| ]) |
| |
| if computation_type == 'matrix_multiply': |
| |
| a = random.choice(self.computation_tensors[device_id]) |
| b = random.choice(self.computation_tensors[device_id]) |
| if a.size(1) == b.size(0): |
| for _ in range(10): |
| result = torch.matmul(a, b) |
| |
| result = result * 0.99 + 0.01 |
| torch.cuda.synchronize(device_id) |
| |
| elif computation_type == 'convolution': |
| |
| tensor = random.choice(self.computation_tensors[device_id]) |
| if tensor.dim() == 2: |
| |
| tensor_4d = tensor.unsqueeze(0).unsqueeze(0) |
| |
| kernel = torch.randn(3, 3, 3, 3, device=f'cuda:{device_id}') * 0.1 |
| for _ in range(5): |
| result = torch.nn.functional.conv2d(tensor_4d, kernel, padding=1) |
| result = torch.relu(result) |
| torch.cuda.synchronize(device_id) |
| |
| elif computation_type == 'reduction': |
| |
| tensor = random.choice(self.computation_tensors[device_id]) |
| for _ in range(20): |
| result = tensor.sum() + tensor.mean() + tensor.std() + tensor.max() + tensor.min() |
| |
| result = result * 0.0001 |
| torch.cuda.synchronize(device_id) |
| |
| elif computation_type == 'element_wise': |
| |
| tensor = random.choice(self.computation_tensors[device_id]) |
| for _ in range(15): |
| result = torch.sigmoid(tensor) * torch.tanh(tensor) + torch.relu(tensor * 0.5) |
| result = torch.log(torch.abs(result) + 1.0) |
| torch.cuda.synchronize(device_id) |
| |
| elif computation_type == 'transpose_ops': |
| |
| tensor = random.choice(self.computation_tensors[device_id]) |
| for _ in range(8): |
| result = tensor.T |
| result = result.contiguous() |
| result = torch.matmul(result, tensor) |
| torch.cuda.synchronize(device_id) |
| |
| elif computation_type == 'mixed_operations': |
| |
| a = random.choice(self.computation_tensors[device_id]) |
| b = random.choice(self.computation_tensors[device_id]) |
| for _ in range(12): |
| result1 = torch.matmul(a, b) |
| result2 = torch.sigmoid(a) * torch.tanh(b) |
| result3 = result1 + result2 |
| result3 = torch.relu(result3) |
| torch.cuda.synchronize(device_id) |
| |
| except Exception as e: |
| |
| pass |
| |
| def allocate_memory_single_device(self, device_id: int): |
| """为单个设备分配指定大小的显存""" |
| torch.cuda.set_device(device_id) |
| |
| total_memory = self.get_total_memory(device_id) |
| available_memory = self.get_available_memory(device_id) |
| |
| print(f"\n设备 {device_id}:") |
| print(f" 总显存: {total_memory:.2f} GB") |
| print(f" 可用显存: {available_memory:.2f} GB") |
| print(f" 目标占用显存: {self.memory_gb:.2f} GB") |
| |
| if self.memory_gb > available_memory: |
| print(f" 警告: 目标占用显存 ({self.memory_gb:.2f} GB) 大于可用显存 ({available_memory:.2f} GB)") |
| print(f" 将尝试占用最大可用显存: {available_memory * 0.95:.2f} GB") |
| target_memory = available_memory * 0.95 |
| else: |
| target_memory = self.memory_gb |
| |
| |
| bytes_to_allocate = int(target_memory * 1024**3) |
| |
| |
| elements_needed = bytes_to_allocate // 4 |
| |
| try: |
| print(f" 正在分配 {target_memory:.2f} GB 显存...") |
| |
| |
| chunk_size = min(elements_needed, 500_000_000) |
| |
| while elements_needed > 0: |
| current_chunk = min(chunk_size, elements_needed) |
| tensor = torch.randn(current_chunk, dtype=torch.float32, device=f"cuda:{device_id}") |
| self.allocated_tensors[device_id].append(tensor) |
| elements_needed -= current_chunk |
| |
| |
| current_allocated = self.get_allocated_memory(device_id) |
| print(f" 已分配显存: {current_allocated:.2f} GB", end='\r') |
| |
| print(f"\n 成功分配显存: {self.get_allocated_memory(device_id):.2f} GB") |
| |
| |
| print(" 创建计算张量...") |
| self.create_computation_tensors(device_id) |
| |
| except torch.cuda.OutOfMemoryError as e: |
| print(f"\n 显存不足错误: {e}") |
| print(f" 当前已分配: {self.get_allocated_memory(device_id):.2f} GB") |
| raise |
| except Exception as e: |
| print(f"\n 分配过程中发生错误: {e}") |
| raise |
| |
| def allocate_memory(self): |
| """为所有指定设备分配显存""" |
| print("开始为所有设备分配显存...") |
| |
| for device_id in self.device_ids: |
| try: |
| self.allocate_memory_single_device(device_id) |
| except Exception as e: |
| print(f"设备 {device_id} 分配失败: {e}") |
| |
| continue |
| |
| print(f"\n所有设备显存分配完成!") |
| self._print_summary() |
| |
| def _print_summary(self): |
| """打印显存使用摘要""" |
| print("\n=== 显存使用摘要 ===") |
| total_allocated = 0 |
| for device_id in self.device_ids: |
| allocated = self.get_allocated_memory(device_id) |
| total = self.get_total_memory(device_id) |
| usage_percent = (allocated / total) * 100 |
| print(f"设备 {device_id}: {allocated:.2f}GB / {total:.2f}GB ({usage_percent:.1f}%)") |
| total_allocated += allocated |
| print(f"总占用显存: {total_allocated:.2f} GB") |
| print("=" * 20) |
| |
| def free_memory(self): |
| """释放所有分配的显存""" |
| print("正在释放所有设备的显存...") |
| self.running = False |
| for device_id in self.device_ids: |
| self.allocated_tensors[device_id].clear() |
| self.computation_tensors[device_id].clear() |
| torch.cuda.set_device(device_id) |
| torch.cuda.empty_cache() |
| print(f"设备 {device_id} 显存已释放") |
| |
| gc.collect() |
| print("所有显存释放完成") |
| self._print_summary() |
| |
| def start_computation_loop(self, device_id: int): |
| """启动计算循环来持续产生GPU使用率""" |
| def computation_worker(): |
| torch.cuda.set_device(device_id) |
| while self.running: |
| if random.random() < 0.8: |
| self.perform_gpu_computation(device_id) |
| time.sleep(0.1) |
| |
| import threading |
| thread = threading.Thread(target=computation_worker, daemon=True) |
| thread.start() |
| return thread |
| |
| def monitor_memory(self, interval: int = 5): |
| """监控所有设备的显存使用情况""" |
| print(f"\n开始监控所有设备显存使用情况 (每{interval}秒更新一次)") |
| print("启动计算线程来产生GPU使用率...") |
| print("按 Ctrl+C 停止监控并释放显存") |
| |
| |
| computation_threads = [] |
| for device_id in self.device_ids: |
| thread = self.start_computation_loop(device_id) |
| computation_threads.append(thread) |
| print(f"设备 {device_id} 计算线程已启动") |
| |
| try: |
| while True: |
| print(f"\n[{time.strftime('%H:%M:%S')}] 显存状态:") |
| total_allocated = 0 |
| total_memory = 0 |
| |
| for device_id in self.device_ids: |
| allocated = self.get_allocated_memory(device_id) |
| available = self.get_available_memory(device_id) |
| total = self.get_total_memory(device_id) |
| usage_percent = (allocated / total) * 100 |
| |
| print(f" GPU {device_id}: {allocated:.2f}GB / {total:.2f}GB " |
| f"({usage_percent:.1f}%) | 可用: {available:.2f}GB") |
| |
| total_allocated += allocated |
| total_memory += total |
| |
| overall_usage = (total_allocated / total_memory) * 100 if total_memory > 0 else 0 |
| print(f" 总计: {total_allocated:.2f}GB / {total_memory:.2f}GB ({overall_usage:.1f}%)") |
| print(" GPU计算线程正在运行中...") |
| |
| time.sleep(interval) |
| |
| except KeyboardInterrupt: |
| print("\n接收到停止信号,正在清理...") |
| self.free_memory() |
| sys.exit(0) |
|
|
|
|
| def signal_handler(signum, frame): |
| """信号处理函数""" |
| print(f"\n接收到信号 {signum},正在清理...") |
| sys.exit(0) |
|
|
|
|
| def parse_device_list(device_str: str) -> List[int]: |
| """解析设备列表字符串,支持格式: "1", "1,2,3", "1-3"等""" |
| devices = [] |
| parts = device_str.split(',') |
| |
| for part in parts: |
| part = part.strip() |
| if '-' in part: |
| |
| start, end = map(int, part.split('-')) |
| devices.extend(range(start, end + 1)) |
| else: |
| |
| devices.append(int(part)) |
| |
| return sorted(list(set(devices))) |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="GPU显存占用工具") |
| parser.add_argument("--devices", "-d", type=str, default="0", |
| help="CUDA设备ID,支持多种格式: 单个设备(2),多个设备(1,2,3),范围(1-3) (默认: 2)") |
| parser.add_argument("--memory", "-m", type=float, default=8.0, |
| help="每个设备要占用的显存大小(GB) (默认: 18.0)") |
| parser.add_argument("--monitor", action="store_true", |
| help="持续监控显存使用情况") |
| parser.add_argument("--interval", "-i", type=int, default=5, |
| help="监控间隔时间(秒) (默认: 5)") |
| |
| args = parser.parse_args() |
| |
| |
| try: |
| device_ids = parse_device_list(args.devices) |
| except ValueError as e: |
| print(f"设备ID解析错误: {e}") |
| print("请使用正确的格式,例如: 2 或 1,2,3 或 1-3") |
| sys.exit(1) |
| |
| print(f"将要占用的设备: {device_ids}") |
| print(f"每个设备占用显存: {args.memory} GB") |
| |
| |
| signal.signal(signal.SIGINT, signal_handler) |
| signal.signal(signal.SIGTERM, signal_handler) |
| |
| try: |
| |
| occupier = GPUMemoryOccupier(device_ids=device_ids, memory_gb=args.memory) |
| |
| |
| occupier.allocate_memory() |
| |
| if args.monitor: |
| |
| occupier.monitor_memory(interval=args.interval) |
| else: |
| print("\n显存分配完成!") |
| print("启动计算线程来产生GPU使用率...") |
| print("按 Ctrl+C 停止程序并释放显存。") |
| |
| |
| computation_threads = [] |
| for device_id in device_ids: |
| thread = occupier.start_computation_loop(device_id) |
| computation_threads.append(thread) |
| print(f"设备 {device_id} 计算线程已启动") |
| |
| try: |
| while True: |
| time.sleep(1) |
| except KeyboardInterrupt: |
| print("\n正在释放显存...") |
| occupier.free_memory() |
| print("程序结束。") |
| |
| except Exception as e: |
| print(f"程序执行出错: {e}") |
| sys.exit(1) |
|
|
|
|
| if __name__ == "__main__": |
| main() |