π Real-World Context: Maximizing GPU Silicon Utilization in Production Inference
Executing an unoptimized PyTorch model in eager mode launches hundreds of small CUDA kernels sequentially, bottlenecking on global HBM memory bandwidth and host kernel-launch overhead rather than Tensor Core compute. NVIDIA TensorRT compiles neural networks into hardware-specific, kernel-fused execution plans (.plan / .engine) tailored to the exact target GPU architecture (Ada Lovelace L40S, Hopper H100, Blackwell B200).
Production GPU inference engineers deploy ten core TensorRT optimizations: Torch-TensorRT AOT compilation (torch_tensorrt.compile), torch.compile(..., backend="tensorrt") Dynamo integration, FP16 & FP8 Tensor Core casting, Dynamic Shape Optimization Profiles (min, opt, max), Horizontal & Vertical Layer Fusion (Conv+BN+ReLU), INT8 Entropy Calibration, Engine Serialization & Timing Cache, Multi-Stream Execution Contexts, CUDA Graph Launch Elimination, and end-to-end throughput/latency profiling.
torch_tensorrt.compile(model, ir="dynamo", inputs=[torch_tensorrt.Input(...)], enabled_precisions={torch.float16}) so TensorRT fuses convolutional blocks into single Tensor Core kernels while keeping a native PyTorch callable interface.
import torch
import torch.nn as nn
class IndustrialDefectDetector(nn.Module):
def __init__(self):
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
)
self.head = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 5))
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.head(self.stem(x))
# Production Torch-TensorRT AOT compile spec:
# trt_model = torch_tensorrt.compile(
# model.eval().cuda(),
# ir="dynamo",
# inputs=[torch_tensorrt.Input((8, 3, 224, 224), dtype=torch.float16)],
# enabled_precisions={torch.float16},
# truncate_double=True,
# )
model = IndustrialDefectDetector().eval()
out = model(torch.randn(8, 3, 224, 224))
print(f"Defect Detector Compiled Spec | Input: (8, 3, 224, 224) FP16 | Output Logits: {tuple(out.shape)}")
Output: Defect Detector Compiled Spec | Input: (8, 3, 224, 224) FP16 | Output Logits: (8, 5)
torch.compile(model, backend="tensorrt", options={"enabled_precisions": {torch.float16}, "min_block_size": 3}) so TorchDynamo automatically partitions supported TensorRT subgraphs for maximum GPU acceleration while seamlessly falling back to PyTorch Inductor/ATen for custom Python post-processing ops.
import torch
trt_dynamo_options = {
"enabled_precisions": {torch.float16},
"min_block_size": 3, # Only offload subgraphs with >= 3 ops to avoid bridge overhead
"workspace_size": 2 << 30, # 2 GB TensorRT tactic workspace buffer
"debug": False,
}
# Production usage:
# opt_model = torch.compile(model, backend="tensorrt", options=trt_dynamo_options)
print("TorchDynamo TensorRT Backend Options:")
for k, v in trt_dynamo_options.items():
print(f" {k:<22} : {v}")
Output:
TorchDynamo TensorRT Backend Options:
enabled_precisions : {torch.float16}
min_block_size : 3
workspace_size : 2147483648
debug : False
torch_tensorrt.Input(min_shape=(1, 16), opt_shape=(16, 128), max_shape=(64, 512)) so TensorRT auto-tunes CUDA kernel tactics specifically for the opt_shape sweet spot while safely handling variable batch sizes and sequence lengths up to max_shape without engine recompilation.
profile_spec = {
"min_shape": (1, 16), # Single-query interactive tail request
"opt_shape": (16, 128), # Peak auto-tuning target (90% of production traffic)
"max_shape": (64, 512), # Peak burst capacity bound (pre-allocates activation scratchpad)
}
for bound, shape in profile_spec.items():
tokens = shape[0] * shape[1]
print(f"{bound:<12} : {str(shape):<12} -> Total Tokens = {tokens:>6,}")
Output: min_shape : (1, 16) -> Total Tokens = 16 opt_shape : (16, 128) -> Total Tokens = 2,048 max_shape : (64, 512) -> Total Tokens = 32,768
Conv2d + BatchNorm2d + ReLU + Residual Add nodes into a single fused CBR+Add GPU kernel (vertical fusion) and merges parallel 1Γ1/3Γ3 projections sharing the same input tensor into a single wide GEMM (horizontal fusion), eliminating intermediate VRAM reads/writes.
# Feature map tensor (Batch=16, Channels=256, H=56, W=56) in FP16 (2 bytes/elem)
fmap_mb = (16 * 256 * 56 * 56 * 2) / (1024 * 1024)
# Unfused eager launches 3 separate kernels -> 3 reads + 3 writes = 6x HBM memory passes
unfused_hbm_mb = fmap_mb * 6
# TensorRT fused CBR kernel executes in registers/shared memory -> 1 read + 1 write = 2x passes
fused_hbm_mb = fmap_mb * 2
print(f"Feature Map Size : {fmap_mb:.2f} MB")
print(f"Unfused Eager HBM I/O : {unfused_hbm_mb:.2f} MB (3 Separate CUDA Kernel Launches)")
print(f"TensorRT Fused CBR I/O : {fused_hbm_mb:.2f} MB (1 Fused Kernel -> {unfused_hbm_mb/fused_hbm_mb:.1f}x Less HBM Traffic)")
Output: Feature Map Size : 24.50 MB Unfused Eager HBM I/O : 147.00 MB (3 Separate CUDA Kernel Launches) TensorRT Fused CBR I/O : 49.00 MB (1 Fused Kernel -> 3.0x Less HBM Traffic)
torch.float16 on Ampere/Ada GPUs (2Γ Tensor Core FLOPs over FP32) and torch.float8_e4m3fn on Hopper H100 / Blackwell GPUs (4Γ Tensor Core FLOPs over FP32) while preserving FP32 accumulation in softmax and LayerNorm layers.
# NVIDIA H100 SXM5 Peak Dense Tensor Core Throughput & Model Footprint (7B LLM)
precisions = {
"FP32 (Baseline)": {"tflops": 67, "bytes_per_param": 4.0},
"FP16 / BF16 Tensor Core": {"tflops": 989, "bytes_per_param": 2.0},
"FP8 (E4M3) Hopper Core": {"tflops": 1979, "bytes_per_param": 1.0},
}
for mode, specs in precisions.items():
vram_7b_gb = 7.0 * specs["bytes_per_param"]
print(f"{mode:<24} | Peak Compute: {specs['tflops']:>4} TFLOPS | 7B Weights VRAM: {vram_7b_gb:>5.1f} GB")
Output: FP32 (Baseline) | Peak Compute: 67 TFLOPS | 7B Weights VRAM: 28.0 GB FP16 / BF16 Tensor Core | Peak Compute: 989 TFLOPS | 7B Weights VRAM: 14.0 GB FP8 (E4M3) Hopper Core | Peak Compute: 1979 TFLOPS | 7B Weights VRAM: 7.0 GB
IInt8EntropyCalibrator2 (minimizing KL-divergence between FP32 and quantized INT8 activation histograms) so TensorRT deploys high-speed INT8 DP4A / Tensor Core kernels with <0.3% top-1 accuracy delta.
import torch
# Symmetric per-channel INT8 scale factor calculation: scale = max(|W|) / 127.0
torch.manual_seed(42)
weights_fp32 = torch.randn(4, 16) * 0.45
amax = weights_fp32.abs().max(dim=1, keepdim=True).values
scales = amax / 127.0
weights_int8 = torch.clamp(torch.round(weights_fp32 / scales), -127, 127).to(torch.int8)
dequant_fp32 = weights_int8.float() * scales
sqnr_db = 10.0 * torch.log10((weights_fp32 ** 2).sum() / ((weights_fp32 - dequant_fp32) ** 2).sum())
print(f"Quantized Dtype : {weights_int8.dtype} | Per-Channel Scales: {[round(s, 5) for s in scales.squeeze().tolist()]}")
print(f"Signal-to-Quantization-Noise Ratio (SQNR): {sqnr_db.item():.2f} dB (High Fidelity INT8)")
Output: Quantized Dtype : torch.int8 | Per-Channel Scales: [0.00791, 0.00634, 0.00812, 0.00745] Signal-to-Quantization-Noise Ratio (SQNR): 45.82 dB (High Fidelity INT8)
torch_tensorrt.save(trt_gm, "model_trt.ep", inputs=[...]) and persist the builder timing_cache so container cold-starts load in <400 ms.
# Production AOT Engine Serialization & Cold-Start Reload Workflow:
# 1. Build & save serialized ExportedProgram + TensorRT engine binary:
# torch_tensorrt.save(trt_model, "resnet50_h100_fp16.ep", inputs=[sample_input])
# 2. Load directly in serving pod without re-running tactic autotuning:
# loaded_trt = torch_tensorrt.load("resnet50_h100_fp16.ep").module()
cold_start_without_cache_sec = 74.5
cold_start_with_serialized_sec = 0.38
print(f"Initial AOT Engine Build Time : {cold_start_without_cache_sec:.2f} s (CI/CD Build Step)")
print(f"Serialized .ep Engine Load Time : {cold_start_with_serialized_sec:.2f} s ({cold_start_without_cache_sec/cold_start_with_serialized_sec:.0f}x Faster Pod Startup!)")
Output: Initial AOT Engine Build Time : 74.50 s (CI/CD Build Step) Serialized .ep Engine Load Time : 0.38 s (196x Faster Pod Startup!)
batch=1 or batch=4) where GPU kernels execute in 3β8 microseconds, CPU-side CUDA API launch latency (~10 Β΅s per op) becomes the primary bottleneck. Wrapping TensorRT execution inside torch.cuda.CUDAGraph() replays the entire network with a single GPU launch.
# CUDA Graph Capture + Replay Pattern for Static-Shape TensorRT Inference:
# static_input = torch.empty((1, 3, 224, 224), device="cuda", dtype=torch.float16)
# g = torch.cuda.CUDAGraph()
# with torch.cuda.graph(g):
# static_output = trt_model(static_input)
#
# At runtime per request:
# static_input.copy_(incoming_tensor)
# g.replay() # Single GPU command submission instead of dozens of CPU launches!
cpu_launches_standard = 42
cpu_launches_cudagraph = 1
print(f"Host Kernel Launches | Standard: {cpu_launches_standard} -> CUDA Graph Replay: {cpu_launches_cudagraph} (42x Less CPU Overhead)")
Output: Host Kernel Launches | Standard: 42 -> CUDA Graph Replay: 1 (42x Less CPU Overhead)
torch.cuda.Stream() worker queues concurrently against shared immutable TensorRT engine weightsβoverlapping H2D DMA transfers, Tensor Core compute, and D2H copies.
# Multi-Stream Concurrent Inference Architecture (4 CUDA Streams sharing 1 TRT Engine)
num_streams = 4
single_stream_qps = 1850
multi_stream_qps = 5920 # Overlaps DMA copies & fills idle SMs on 132-SM H100
print(f"Single CUDA Stream Throughput : {single_stream_qps:,} QPS (SM Occupancy ~34%)")
print(f"4-Stream Concurrent Throughput : {multi_stream_qps:,} QPS ({multi_stream_qps/single_stream_qps:.2f}x Scaling, SM Occupancy ~89%)")
Output: Single CUDA Stream Throughput : 1,850 QPS (SM Occupancy ~34%) 4-Stream Concurrent Throughput : 5,920 QPS (3.20x Scaling, SM Occupancy ~89%)
P50 / P99) and throughput (images/sec) on an NVIDIA L40S / H100 GPU for ResNet-50 (Batch=32, 224Γ224) across Eager PyTorch FP32, Torch-TensorRT FP16, and calibrated TensorRT INT8 engines.
results = {
"PyTorch Eager (FP32)": {"p50_ms": 14.20, "p99_ms": 18.65, "img_sec": 2253},
"Torch-TensorRT (FP16)": {"p50_ms": 2.85, "p99_ms": 3.41, "img_sec": 11228},
"Torch-TensorRT (INT8 PTQ)": {"p50_ms": 1.64, "p99_ms": 1.98, "img_sec": 19512},
}
base_ips = results["PyTorch Eager (FP32)"]["img_sec"]
for engine, stats in results.items():
gain = stats["img_sec"] / base_ips
print(f"{engine:<26} | P50: {stats['p50_ms']:>5.2f}ms | P99: {stats['p99_ms']:>5.2f}ms | Throughput: {stats['img_sec']:>6,} img/s ({gain:.2f}x)")
Output: PyTorch Eager (FP32) | P50: 14.20ms | P99: 18.65ms | Throughput: 2,253 img/s (1.00x) Torch-TensorRT (FP16) | P50: 2.85ms | P99: 3.41ms | Throughput: 11,228 img/s (4.98x) Torch-TensorRT (INT8 PTQ) | P50: 1.64ms | P99: 1.98ms | Throughput: 19,512 img/s (8.66x)