|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""GPU benchmark script for testing PyTorch CUDA capabilities. |
| 3 | +
|
| 4 | +Used by ``demo-gpu-dbg.yml``. |
| 5 | +""" |
| 6 | + |
| 7 | +import sys |
| 8 | +import time |
| 9 | +import torch |
| 10 | + |
| 11 | + |
| 12 | +def main(): |
| 13 | + print(f'PyTorch version: {torch.__version__}') |
| 14 | + print(f'CUDA available: {torch.cuda.is_available()}') |
| 15 | + |
| 16 | + if not torch.cuda.is_available(): |
| 17 | + print('ERROR: CUDA not available!') |
| 18 | + sys.exit(1) |
| 19 | + |
| 20 | + # Get GPU information |
| 21 | + device = torch.cuda.get_device_properties(0) |
| 22 | + print(f'GPU: {device.name}') |
| 23 | + print(f'Memory: {device.total_memory / 1e9:.1f} GB') |
| 24 | + print(f'CUDA version: {torch.version.cuda}') |
| 25 | + |
| 26 | + # Matrix multiplication benchmark |
| 27 | + print('\nRunning matrix multiplication benchmark...') |
| 28 | + size = 8192 |
| 29 | + x = torch.randn(size, size, dtype=torch.float32).cuda() |
| 30 | + torch.cuda.synchronize() |
| 31 | + |
| 32 | + # Warmup |
| 33 | + print(' Warming up...') |
| 34 | + for _ in range(3): |
| 35 | + _ = torch.matmul(x, x.T) |
| 36 | + torch.cuda.synchronize() |
| 37 | + |
| 38 | + # Benchmark |
| 39 | + print(' Running benchmark...') |
| 40 | + start = time.time() |
| 41 | + y = torch.matmul(x, x.T) |
| 42 | + torch.cuda.synchronize() |
| 43 | + elapsed = time.time() - start |
| 44 | + |
| 45 | + gflops = (2 * size**3) / (elapsed * 1e9) |
| 46 | + print(f' Matrix size: {size}x{size}') |
| 47 | + print(f' Time: {elapsed:.3f} seconds') |
| 48 | + print(f' Performance: {gflops:.1f} GFLOPS') |
| 49 | + print(f' Memory used: {torch.cuda.max_memory_allocated()/1e9:.2f} GB') |
| 50 | + |
| 51 | + # Quick training simulation |
| 52 | + print('\nSimulating model training...') |
| 53 | + model = torch.nn.Sequential( |
| 54 | + torch.nn.Linear(1024, 512), |
| 55 | + torch.nn.ReLU(), |
| 56 | + torch.nn.Linear(512, 256), |
| 57 | + torch.nn.ReLU(), |
| 58 | + torch.nn.Linear(256, 10) |
| 59 | + ).cuda() |
| 60 | + |
| 61 | + optimizer = torch.optim.Adam(model.parameters()) |
| 62 | + data = torch.randn(32, 1024).cuda() |
| 63 | + |
| 64 | + for i in range(10): |
| 65 | + output = model(data) |
| 66 | + loss = output.sum() |
| 67 | + loss.backward() |
| 68 | + optimizer.step() |
| 69 | + optimizer.zero_grad() |
| 70 | + if i == 0 or i == 9: |
| 71 | + print(f' Iteration {i+1}: loss = {loss.item():.4f}') |
| 72 | + |
| 73 | + print('\nGPU workload completed successfully!') |
| 74 | + return 0 |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == '__main__': |
| 78 | + sys.exit(main()) |
0 commit comments