File size: 8,866 Bytes
ddadeb4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | # coding: utf-8
__author__ = 'PyTorch Optimization Benchmark Tool'
import argparse
import time
import torch
import numpy as np
from utils import get_model_from_config
from pytorch_backend import (
PyTorchBackend,
PyTorchOptimizer,
benchmark_pytorch_optimizations,
get_model_info
)
import sys
def load_checkpoint(checkpoint_path: str, model, device: str):
"""Load model from checkpoint."""
print(f"Loading checkpoint from: {checkpoint_path}")
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
# Handle different checkpoint formats
if isinstance(checkpoint, dict):
if 'state_dict' in checkpoint:
state_dict = checkpoint['state_dict']
elif 'model' in checkpoint:
state_dict = checkpoint['model']
elif 'state' in checkpoint:
state_dict = checkpoint['state']
else:
state_dict = checkpoint
else:
state_dict = checkpoint
model.load_state_dict(state_dict, strict=False)
model = model.eval().to(device)
print("β Checkpoint loaded successfully")
return model
def benchmark_optimization_modes(args):
"""
Benchmark different PyTorch optimization modes.
"""
parser = argparse.ArgumentParser(description="Benchmark PyTorch Optimization Modes")
parser.add_argument("--model_type", type=str, required=True, help="Model type")
parser.add_argument("--config_path", type=str, required=True, help="Config path")
parser.add_argument("--start_check_point", type=str, required=True, help="Checkpoint path (.ckpt)")
parser.add_argument("--device", type=str, default='cuda:0', help="Device")
parser.add_argument("--num_iterations", type=int, default=100, help="Number of benchmark iterations")
parser.add_argument("--warmup_iterations", type=int, default=10, help="Number of warmup iterations")
parser.add_argument("--chunk_size", type=int, default=None, help="Override chunk size (optional)")
parser.add_argument("--batch_size", type=int, default=1, help="Batch size")
if args is None:
args = parser.parse_args()
else:
args = parser.parse_args(args)
# Check device
if args.device.startswith('cuda') and not torch.cuda.is_available():
print("β CUDA is not available!")
return
print("="*60)
print("PyTorch Optimization Benchmark Tool")
print("="*60)
print(f"Model Type: {args.model_type}")
print(f"Checkpoint: {args.start_check_point}")
print(f"Device: {args.device}")
print(f"Iterations: {args.num_iterations}")
print("="*60)
# Load model
print("\nπ¦ Loading model...")
model, config = get_model_from_config(args.model_type, args.config_path)
model = load_checkpoint(args.start_check_point, model, args.device)
# Get model info
model_info = get_model_info(model)
print(f"\nπ Model Information:")
print(f" Total Parameters: {model_info['total_parameters']:,}")
print(f" Trainable Parameters: {model_info['trainable_parameters']:,}")
print(f" Model Size: {model_info['model_size_mb']:.2f} MB")
print(f" Device: {model_info['device']}")
print(f" Dtype: {model_info['dtype']}")
# Get chunk size
if args.chunk_size:
chunk_size = args.chunk_size
else:
chunk_size = config.audio.chunk_size
num_channels = 2
input_shape = (args.batch_size, num_channels, chunk_size)
print(f"\nπ Test Configuration:")
print(f" Batch Size: {args.batch_size}")
print(f" Channels: {num_channels}")
print(f" Chunk Size: {chunk_size}")
print(f" Input Shape: {input_shape}")
# Benchmark different optimization modes
print("\n" + "="*60)
print("Benchmarking Optimization Modes")
print("="*60)
results = benchmark_pytorch_optimizations(
model=model,
input_shape=input_shape,
device=args.device,
num_iterations=args.num_iterations,
warmup_iterations=args.warmup_iterations
)
# Display results
print("\n" + "="*60)
print("π Benchmark Results")
print("="*60)
baseline = None
for mode, time_ms in results.items():
if time_ms is not None:
if baseline is None:
baseline = time_ms
speedup = baseline / time_ms if time_ms > 0 else 0
improvement = ((baseline - time_ms) / baseline) * 100 if baseline > 0 else 0
print(f"\n{mode.upper()}:")
print(f" Average Time: {time_ms:.2f} ms")
print(f" Speedup: {speedup:.2f}x")
print(f" Improvement: {improvement:.1f}%")
print("\n" + "="*60)
# Recommendations
print("\nπ‘ Recommendations:")
if results.get('compile') and results['compile'] < results['default']:
print(" β Use 'compile' mode for best performance (PyTorch 2.0+)")
elif results.get('channels_last') and results['channels_last'] < results['default']:
print(" β Use 'channels_last' mode for better performance")
else:
print(" β Default mode is optimal for your configuration")
if args.device.startswith('cuda'):
print(" β Enable TF32 for Ampere GPUs (RTX 30xx+)")
print(" β Enable cuDNN benchmark for consistent input sizes")
print("\nβ
Benchmark completed!")
def test_optimization_modes(args):
"""
Test different optimization modes with verification.
"""
parser = argparse.ArgumentParser(description="Test PyTorch Optimization Modes")
parser.add_argument("--model_type", type=str, required=True, help="Model type")
parser.add_argument("--config_path", type=str, required=True, help="Config path")
parser.add_argument("--start_check_point", type=str, required=True, help="Checkpoint path (.ckpt)")
parser.add_argument("--device", type=str, default='cuda:0', help="Device")
if args is None:
args = parser.parse_args()
else:
args = parser.parse_args(args)
print("="*60)
print("PyTorch Optimization Mode Test")
print("="*60)
# Load model
print("\nπ¦ Loading model...")
model, config = get_model_from_config(args.model_type, args.config_path)
model = load_checkpoint(args.start_check_point, model, args.device)
chunk_size = config.audio.chunk_size
input_shape = (1, 2, chunk_size)
dummy_input = torch.randn(*input_shape).to(args.device)
# Test each optimization mode
modes = ['default', 'compile', 'channels_last']
outputs = {}
for mode in modes:
print(f"\n{'='*60}")
print(f"Testing: {mode}")
print('='*60)
try:
backend = PyTorchBackend(device=args.device, optimize_mode=mode)
if mode == 'jit':
backend.optimize_model(model, example_input=dummy_input, use_amp=True)
else:
backend.optimize_model(
model,
use_amp=True,
use_channels_last=(mode == 'channels_last')
)
# Run inference
with torch.no_grad():
output = backend(dummy_input)
outputs[mode] = output
print(f"β {mode} successful")
print(f" Output shape: {output.shape}")
print(f" Output range: [{output.min().item():.6f}, {output.max().item():.6f}]")
except Exception as e:
print(f"β {mode} failed: {e}")
outputs[mode] = None
# Verify outputs match
print("\n" + "="*60)
print("π Output Verification")
print("="*60)
baseline_key = 'default'
if baseline_key in outputs and outputs[baseline_key] is not None:
baseline_output = outputs[baseline_key]
for mode, output in outputs.items():
if mode != baseline_key and output is not None:
diff = torch.abs(baseline_output - output)
max_diff = torch.max(diff).item()
mean_diff = torch.mean(diff).item()
print(f"\n{mode} vs {baseline_key}:")
print(f" Max difference: {max_diff:.6f}")
print(f" Mean difference: {mean_diff:.6f}")
if max_diff < 1e-3:
print(f" β Outputs match within tolerance")
else:
print(f" β Warning: Large difference detected!")
print("\nβ
Test completed!")
if __name__ == "__main__":
import sys
if len(sys.argv) > 1 and sys.argv[1] == 'test':
sys.argv.pop(1)
test_optimization_modes(None)
else:
benchmark_optimization_modes(None)
|