๐ก Real-World Context: High-Throughput Computer Vision Inference & Training Pipeline
Training modern neural networks on billions of parameters requires performing trillions of floating-point matrix multiplications per second. While a CPU optimizes for low-latency serial execution across a handful of complex cores, an NVIDIA GPU dedicates its silicon to thousands of parallel CUDA cores operating under a SIMT (Single Instruction, Multiple Threads) architecture.
To unlock this massive parallel throughput in PyTorch, tensors and model weights must be explicitly transferred from Host CPU system RAM across the PCIe bus into dedicated GPU high-bandwidth VRAMโminimizing host-device transfer bottlenecks and synchronizing asynchronous GPU kernels properly.
import torch
# 1. Check if CUDA is available and query device count
cuda_available = torch.cuda.is_available()
print("CUDA Available:", cuda_available)
if cuda_available:
device_count = torch.cuda.device_count()
current_idx = torch.cuda.current_device()
print(f"Detected {device_count} GPU(s) | Active Device Index: {current_idx}")
# 2. Inspect hardware properties of the active GPU
props = torch.cuda.get_device_properties(current_idx)
total_vram_gb = props.total_memory / (1024 ** 3)
print("GPU Model Name:", torch.cuda.get_device_name(current_idx))
print(f"Total Dedicated VRAM: {total_vram_gb:.2f} GB")
print(f"Streaming Multiprocessors (SMs): {props.multi_processor_count}")
print(f"CUDA Compute Capability: {props.major}.{props.minor}")
cpu) and Device VRAM (cuda) using .to(), .cuda(), .cpu(), and pinned host memory with non_blocking=True while avoiding cross-device operation errors.
import torch
import torch.nn as nn
# 1. Create a tensor directly in Host CPU memory
cpu_tensor = torch.randn(4, 128, dtype=torch.float32)
print("Initial Tensor Device:", cpu_tensor.device)
# 2. Transfer tensor to GPU VRAM (using .to('cuda') or .cuda())
gpu_tensor = cpu_tensor.to("cuda")
print("Transferred Tensor Device:", gpu_tensor.device)
# 3. High-throughput transfer using page-locked (pinned) host memory
pinned_batch = torch.randn(64, 3, 224, 224).pin_memory()
gpu_batch = pinned_batch.to("cuda", non_blocking=True)
print("Pinned Batch Pinned Status:", pinned_batch.is_pinned(), "| Target Device:", gpu_batch.device)
# 4. Move a neural network module's parameters to the GPU
linear_layer = nn.Linear(128, 10).to("cuda")
output = linear_layer(gpu_tensor) # Both model weights and input are on cuda:0
print("Output Tensor Device:", output.device, "| Shape:", output.shape)
# 5. Move results back to CPU before converting to NumPy
numpy_result = output.detach().cpu().numpy()
print("Converted Back to CPU NumPy Shape:", numpy_result.shape)
torch.device selector that prioritizes NVIDIA CUDA, falls back to Apple Silicon Metal Performance Shaders (MPS), and gracefully defaults to CPU when no accelerator is present.
import torch
import torch.nn as nn
def get_optimal_device() -> torch.device:
"""Automatically selects the fastest available compute backend."""
if torch.cuda.is_available():
return torch.device("cuda")
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
# 1. Resolve target device once at pipeline initialization
device = get_optimal_device()
print("Selected Production Backend:", device)
# 2. Allocate tensors directly on the target device (avoids extra CPU->GPU copies)
inputs = torch.randn(32, 512, device=device)
targets = torch.randint(0, 5, (32,), device=device)
# 3. Instantiate model and move all buffers/parameters to target device
classifier = nn.Sequential(
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 5)
).to(device)
logits = classifier(inputs)
loss = nn.CrossEntropyLoss()(logits, targets)
print(f"Forward Pass Complete on {logits.device} | Loss: {loss.item():.4f}")
torch.cuda.synchronize() or hardware torch.cuda.Event timers.
import time
import torch
N = 4096
cpu_a = torch.randn(N, N, device="cpu")
cpu_b = torch.randn(N, N, device="cpu")
# 1. Benchmark CPU Matrix Multiplication
start_cpu = time.perf_counter()
cpu_c = torch.matmul(cpu_a, cpu_b)
cpu_time_ms = (time.perf_counter() - start_cpu) * 1000.0
# 2. Prepare GPU tensors and run a warmup pass (initializes cuBLAS kernels)
gpu_a = cpu_a.to("cuda")
gpu_b = cpu_b.to("cuda")
_ = torch.matmul(gpu_a, gpu_b)
torch.cuda.synchronize()
# 3. Benchmark GPU Matrix Multiplication using accurate CUDA Hardware Events
start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
start_event.record()
gpu_c = torch.matmul(gpu_a, gpu_b)
end_event.record()
# Block host thread until all queued GPU stream operations complete
torch.cuda.synchronize()
gpu_time_ms = start_event.elapsed_time(end_event)
print(f"Matrix Size: {N}x{N} (FP32)")
print(f"CPU MatMul Time: {cpu_time_ms:.2f} ms")
print(f"GPU MatMul Time: {gpu_time_ms:.2f} ms")
print(f"Hardware Acceleration Speedup: {cpu_time_ms / gpu_time_ms:.1f}x faster")
memory_allocated() and empty_cache(), and leveraging Automatic Mixed Precision (torch.amp.autocast) to cut VRAM footprint in half while engaging NVIDIA Tensor Cores.
import torch
import torch.nn as nn
torch.cuda.reset_peak_memory_stats()
# Allocate a large FP32 activation tensor: 2048 x 4096 x 4 bytes = 32.00 MB
x_fp32 = torch.randn(2048, 4096, device="cuda", dtype=torch.float32)
w_fp32 = torch.randn(4096, 4096, device="cuda", dtype=torch.float32)
alloc_mb = torch.cuda.memory_allocated() / (1024 ** 2)
print(f"Active Allocated VRAM (FP32 Tensors): {alloc_mb:.2f} MB")
# Automatic Mixed Precision (AMP) casts eligible ops (matmul, linear, conv) to FP16
with torch.amp.autocast("cuda", dtype=torch.float16):
y_amp = torch.matmul(x_fp32, w_fp32)
print("AMP Output Tensor Dtype:", y_amp.dtype)
peak_mb = torch.cuda.max_memory_reserved() / (1024 ** 2)
print(f"Peak Cached VRAM Reserved by PyTorch Allocator: {peak_mb:.2f} MB")
# Delete references and release unused cached blocks back to the CUDA driver
del x_fp32, w_fp32, y_amp
torch.cuda.empty_cache()
print(f"VRAM Allocated After Cleanup: {torch.cuda.memory_allocated() / (1024 ** 2):.2f} MB")