| |
| """ |
| 速度测试脚本 - 对比 PyTorch vs TensorRT 推理性能 |
| 测试 DeCLIP (csa模式) 和 CLIP (vanilla模式) 的延迟和吞吐量 |
| |
| Usage: |
| python benchmark_speed.py --pytorch-model <path> --trt-engine <path> |
| python benchmark_speed.py --all # 运行所有配置的测试 |
| """ |
|
|
| import os |
| import sys |
| import argparse |
| import time |
| import json |
| from pathlib import Path |
| from dataclasses import dataclass, asdict |
| from typing import Optional, List, Dict, Any |
| from datetime import datetime |
|
|
| import torch |
| import torch.cuda |
| import numpy as np |
|
|
| |
| SCRIPT_DIR = Path(__file__).parent |
| DECLIP_ROOT = SCRIPT_DIR.parent |
| sys.path.insert(0, str(DECLIP_ROOT)) |
| sys.path.insert(0, str(DECLIP_ROOT / 'src')) |
|
|
|
|
| @dataclass |
| class BenchmarkResult: |
| """Benchmark 结果""" |
| model_name: str |
| mode: str |
| backend: str |
| precision: str |
| image_size: tuple |
| batch_size: int |
| warmup_rounds: int |
| test_rounds: int |
| latency_mean_ms: float |
| latency_std_ms: float |
| latency_min_ms: float |
| latency_max_ms: float |
| throughput_fps: float |
| memory_mb: float |
| timestamp: str |
|
|
|
|
| class PyTorchBenchmark: |
| """PyTorch 模型 benchmark""" |
| |
| def __init__(self, model, device='cuda:0', mode='csa'): |
| self.model = model |
| self.device = torch.device(device) |
| self.mode = mode |
| self.model.to(self.device) |
| self.model.eval() |
| |
| @torch.no_grad() |
| def run(self, input_tensor: torch.Tensor) -> torch.Tensor: |
| """运行单次推理""" |
| if hasattr(self.model, 'visual'): |
| return self.model.visual.encode_dense( |
| input_tensor, keep_shape=True, mode=self.mode |
| ) |
| else: |
| return self.model.encode_dense( |
| input_tensor, keep_shape=True, mode=self.mode |
| ) |
| |
| def benchmark( |
| self, |
| image_size: tuple = (560, 560), |
| batch_size: int = 1, |
| warmup: int = 10, |
| iterations: int = 100, |
| fp16: bool = False |
| ) -> BenchmarkResult: |
| """运行 benchmark""" |
| H, W = image_size |
| dtype = torch.float16 if fp16 else torch.float32 |
| |
| |
| input_tensor = torch.randn( |
| batch_size, 3, H, W, |
| device=self.device, |
| dtype=dtype |
| ) |
| |
| if fp16: |
| self.model.half() |
| |
| |
| for _ in range(warmup): |
| _ = self.run(input_tensor) |
| torch.cuda.synchronize() |
| |
| |
| latencies = [] |
| torch.cuda.reset_peak_memory_stats() |
| |
| for _ in range(iterations): |
| torch.cuda.synchronize() |
| start = time.perf_counter() |
| |
| _ = self.run(input_tensor) |
| |
| torch.cuda.synchronize() |
| end = time.perf_counter() |
| |
| latencies.append((end - start) * 1000) |
| |
| memory_mb = torch.cuda.max_memory_allocated() / (1024 * 1024) |
| |
| latencies = np.array(latencies) |
| |
| return BenchmarkResult( |
| model_name=type(self.model).__name__, |
| mode=self.mode, |
| backend='pytorch', |
| precision='fp16' if fp16 else 'fp32', |
| image_size=image_size, |
| batch_size=batch_size, |
| warmup_rounds=warmup, |
| test_rounds=iterations, |
| latency_mean_ms=float(latencies.mean()), |
| latency_std_ms=float(latencies.std()), |
| latency_min_ms=float(latencies.min()), |
| latency_max_ms=float(latencies.max()), |
| throughput_fps=float(batch_size * 1000 / latencies.mean()), |
| memory_mb=float(memory_mb), |
| timestamp=datetime.now().isoformat() |
| ) |
|
|
|
|
| class TensorRTBenchmark: |
| """TensorRT 引擎 benchmark""" |
| |
| def __init__(self, engine_path: str, device='cuda:0'): |
| self.engine_path = engine_path |
| self.device = device |
| self.engine = None |
| self.context = None |
| self.stream = None |
| |
| self._load_engine() |
| |
| def _load_engine(self): |
| """加载 TRT 引擎""" |
| try: |
| import tensorrt as trt |
| import pycuda.driver as cuda |
| import pycuda.autoinit |
| |
| self.cuda = cuda |
| self.trt = trt |
| |
| logger = trt.Logger(trt.Logger.WARNING) |
| runtime = trt.Runtime(logger) |
| |
| with open(self.engine_path, 'rb') as f: |
| self.engine = runtime.deserialize_cuda_engine(f.read()) |
| |
| self.context = self.engine.create_execution_context() |
| self.stream = cuda.Stream() |
| |
| |
| self.input_name = self.engine.get_tensor_name(0) |
| self.output_name = self.engine.get_tensor_name(1) |
| |
| except ImportError as e: |
| raise ImportError(f"TensorRT/PyCUDA not installed: {e}") |
| |
| def run(self, input_np: np.ndarray) -> np.ndarray: |
| """运行单次推理""" |
| cuda = self.cuda |
| |
| |
| self.context.set_input_shape(self.input_name, input_np.shape) |
| |
| |
| output_shape = self.context.get_tensor_shape(self.output_name) |
| output_np = np.empty(output_shape, dtype=np.float32) |
| |
| |
| d_input = cuda.mem_alloc(input_np.nbytes) |
| d_output = cuda.mem_alloc(output_np.nbytes) |
| |
| |
| cuda.memcpy_htod_async(d_input, input_np.astype(np.float32), self.stream) |
| |
| |
| self.context.set_tensor_address(self.input_name, int(d_input)) |
| self.context.set_tensor_address(self.output_name, int(d_output)) |
| |
| |
| self.context.execute_async_v3(self.stream.handle) |
| |
| |
| cuda.memcpy_dtoh_async(output_np, d_output, self.stream) |
| self.stream.synchronize() |
| |
| return output_np |
| |
| def benchmark( |
| self, |
| image_size: tuple = (560, 560), |
| batch_size: int = 1, |
| warmup: int = 10, |
| iterations: int = 100 |
| ) -> BenchmarkResult: |
| """运行 benchmark""" |
| cuda = self.cuda |
| H, W = image_size |
| |
| |
| input_np = np.random.randn(batch_size, 3, H, W).astype(np.float32) |
| |
| |
| self.context.set_input_shape(self.input_name, input_np.shape) |
| output_shape = self.context.get_tensor_shape(self.output_name) |
| output_np = np.empty(output_shape, dtype=np.float32) |
| |
| |
| d_input = cuda.mem_alloc(input_np.nbytes) |
| d_output = cuda.mem_alloc(output_np.nbytes) |
| |
| |
| for _ in range(warmup): |
| cuda.memcpy_htod(d_input, input_np) |
| self.context.set_tensor_address(self.input_name, int(d_input)) |
| self.context.set_tensor_address(self.output_name, int(d_output)) |
| self.context.execute_async_v3(self.stream.handle) |
| self.stream.synchronize() |
| |
| |
| latencies = [] |
| |
| for _ in range(iterations): |
| cuda.memcpy_htod(d_input, input_np) |
| |
| start = time.perf_counter() |
| |
| self.context.set_tensor_address(self.input_name, int(d_input)) |
| self.context.set_tensor_address(self.output_name, int(d_output)) |
| self.context.execute_async_v3(self.stream.handle) |
| self.stream.synchronize() |
| |
| end = time.perf_counter() |
| |
| latencies.append((end - start) * 1000) |
| |
| latencies = np.array(latencies) |
| |
| |
| precision = 'fp16' if 'fp16' in self.engine_path else 'fp32' |
| if 'int8' in self.engine_path: |
| precision = 'int8' |
| |
| return BenchmarkResult( |
| model_name=Path(self.engine_path).stem, |
| mode='unknown', |
| backend='tensorrt', |
| precision=precision, |
| image_size=image_size, |
| batch_size=batch_size, |
| warmup_rounds=warmup, |
| test_rounds=iterations, |
| latency_mean_ms=float(latencies.mean()), |
| latency_std_ms=float(latencies.std()), |
| latency_min_ms=float(latencies.min()), |
| latency_max_ms=float(latencies.max()), |
| throughput_fps=float(batch_size * 1000 / latencies.mean()), |
| memory_mb=0.0, |
| timestamp=datetime.now().isoformat() |
| ) |
|
|
|
|
| class ONNXBenchmark: |
| """ONNX Runtime benchmark""" |
| |
| def __init__(self, onnx_path: str, device='cuda'): |
| self.onnx_path = onnx_path |
| self.device = device |
| |
| import onnxruntime as ort |
| |
| providers = ['CUDAExecutionProvider'] if device == 'cuda' else ['CPUExecutionProvider'] |
| self.session = ort.InferenceSession(onnx_path, providers=providers) |
| self.input_name = self.session.get_inputs()[0].name |
| |
| def run(self, input_np: np.ndarray) -> np.ndarray: |
| """运行单次推理""" |
| return self.session.run(None, {self.input_name: input_np})[0] |
| |
| def benchmark( |
| self, |
| image_size: tuple = (560, 560), |
| batch_size: int = 1, |
| warmup: int = 10, |
| iterations: int = 100 |
| ) -> BenchmarkResult: |
| """运行 benchmark""" |
| H, W = image_size |
| input_np = np.random.randn(batch_size, 3, H, W).astype(np.float32) |
| |
| |
| for _ in range(warmup): |
| _ = self.run(input_np) |
| |
| |
| latencies = [] |
| |
| for _ in range(iterations): |
| start = time.perf_counter() |
| _ = self.run(input_np) |
| end = time.perf_counter() |
| latencies.append((end - start) * 1000) |
| |
| latencies = np.array(latencies) |
| |
| return BenchmarkResult( |
| model_name=Path(self.onnx_path).stem, |
| mode='unknown', |
| backend='onnxruntime', |
| precision='fp32', |
| image_size=image_size, |
| batch_size=batch_size, |
| warmup_rounds=warmup, |
| test_rounds=iterations, |
| latency_mean_ms=float(latencies.mean()), |
| latency_std_ms=float(latencies.std()), |
| latency_min_ms=float(latencies.min()), |
| latency_max_ms=float(latencies.max()), |
| throughput_fps=float(batch_size * 1000 / latencies.mean()), |
| memory_mb=0.0, |
| timestamp=datetime.now().isoformat() |
| ) |
|
|
|
|
| def print_result(result: BenchmarkResult): |
| """打印 benchmark 结果""" |
| print(f"\n{'='*60}") |
| print(f"Benchmark Results: {result.model_name}") |
| print(f"{'='*60}") |
| print(f"Backend: {result.backend}") |
| print(f"Mode: {result.mode}") |
| print(f"Precision: {result.precision}") |
| print(f"Image Size: {result.image_size}") |
| print(f"Batch Size: {result.batch_size}") |
| print(f"Warmup: {result.warmup_rounds} rounds") |
| print(f"Test: {result.test_rounds} rounds") |
| print(f"-" * 40) |
| print(f"Latency Mean: {result.latency_mean_ms:.2f} ms") |
| print(f"Latency Std: {result.latency_std_ms:.2f} ms") |
| print(f"Latency Min: {result.latency_min_ms:.2f} ms") |
| print(f"Latency Max: {result.latency_max_ms:.2f} ms") |
| print(f"Throughput: {result.throughput_fps:.1f} FPS") |
| if result.memory_mb > 0: |
| print(f"GPU Memory: {result.memory_mb:.1f} MB") |
| print(f"{'='*60}") |
|
|
|
|
| def compare_results(results: List[BenchmarkResult]): |
| """对比多个结果""" |
| if len(results) < 2: |
| return |
| |
| print(f"\n{'='*60}") |
| print("Comparison Summary") |
| print(f"{'='*60}") |
| |
| |
| results = sorted(results, key=lambda x: (x.mode, x.backend)) |
| |
| |
| headers = ["Model", "Mode", "Backend", "Precision", "Latency (ms)", "FPS", "Speedup"] |
| row_format = "{:<20} {:<8} {:<12} {:<10} {:>12} {:>8} {:>8}" |
| print(row_format.format(*headers)) |
| print("-" * 80) |
| |
| |
| baseline = next((r for r in results if r.backend == 'pytorch'), results[0]) |
| |
| for result in results: |
| speedup = baseline.latency_mean_ms / result.latency_mean_ms |
| speedup_str = f"{speedup:.2f}x" if speedup != 1.0 else "-" |
| |
| print(row_format.format( |
| result.model_name[:20], |
| result.mode, |
| result.backend, |
| result.precision, |
| f"{result.latency_mean_ms:.2f}", |
| f"{result.throughput_fps:.1f}", |
| speedup_str |
| )) |
|
|
|
|
| def save_results(results: List[BenchmarkResult], output_path: str): |
| """保存结果到 JSON""" |
| data = [asdict(r) for r in results] |
| |
| with open(output_path, 'w') as f: |
| json.dump(data, f, indent=2) |
| |
| print(f"\nResults saved to: {output_path}") |
|
|
|
|
| def parse_args(): |
| parser = argparse.ArgumentParser(description='速度测试') |
| |
| parser.add_argument('--pytorch-model', type=str, |
| help='PyTorch 模型检查点路径') |
| parser.add_argument('--trt-engine', type=str, |
| help='TensorRT 引擎路径') |
| parser.add_argument('--onnx-model', type=str, |
| help='ONNX 模型路径') |
| |
| parser.add_argument('--model-name', type=str, default='EVA02-CLIP-B-16', |
| help='模型名称') |
| parser.add_argument('--mode', type=str, default='csa', |
| choices=['vanilla', 'csa'], |
| help='特征模式') |
| |
| parser.add_argument('--image-size', type=int, nargs=2, default=[560, 560], |
| help='图像尺寸 [H, W]') |
| parser.add_argument('--batch-size', type=int, default=1, |
| help='批处理大小') |
| parser.add_argument('--warmup', type=int, default=10, |
| help='预热轮数') |
| parser.add_argument('--iterations', type=int, default=100, |
| help='测试轮数') |
| |
| parser.add_argument('--fp16', action='store_true', |
| help='使用 FP16 (仅 PyTorch)') |
| |
| parser.add_argument('--all', action='store_true', |
| help='运行所有配置的测试') |
| parser.add_argument('--output', type=str, default='results/benchmark_results.json', |
| help='输出文件路径') |
| |
| parser.add_argument('--device', type=str, default='cuda:0', |
| help='设备') |
| |
| return parser.parse_args() |
|
|
|
|
| def run_all_benchmarks(args): |
| """运行所有配置的测试""" |
| from configs.fvit_tensorrt_fp16 import model_paths, benchmark_config |
| |
| results = [] |
| |
| |
| modes = ['vanilla', 'csa'] |
| image_sizes = benchmark_config['input_sizes'] |
| batch_sizes = benchmark_config['batch_sizes'] |
| |
| |
| engine_dir = SCRIPT_DIR / 'engines' |
| |
| for mode in modes: |
| model_type = 'clip' if mode == 'vanilla' else 'declip' |
| |
| |
| engine_pattern = f"{model_type}_{mode}_*_fp16.engine" |
| engines = list(engine_dir.glob(engine_pattern)) |
| |
| if not engines: |
| print(f"Warning: No TRT engine found for {model_type} {mode}") |
| continue |
| |
| engine_path = engines[0] |
| |
| for image_size in image_sizes: |
| for batch_size in batch_sizes: |
| |
| try: |
| benchmark = TensorRTBenchmark(str(engine_path), args.device) |
| result = benchmark.benchmark( |
| image_size=image_size, |
| batch_size=batch_size, |
| warmup=args.warmup, |
| iterations=args.iterations |
| ) |
| result.mode = mode |
| results.append(result) |
| print_result(result) |
| except Exception as e: |
| print(f"Error benchmarking TRT {mode}: {e}") |
| |
| return results |
|
|
|
|
| def main(): |
| args = parse_args() |
| |
| results = [] |
| |
| print(f"\n{'='*60}") |
| print("DeCLIP/CLIP Speed Benchmark") |
| print(f"{'='*60}") |
| print(f"Device: {args.device}") |
| print(f"Image Size: {args.image_size}") |
| print(f"Batch Size: {args.batch_size}") |
| print(f"Warmup: {args.warmup}") |
| print(f"Iterations: {args.iterations}") |
| |
| if args.all: |
| results = run_all_benchmarks(args) |
| else: |
| image_size = tuple(args.image_size) |
| |
| |
| if args.pytorch_model: |
| from open_clip import create_model |
| |
| print(f"\nLoading PyTorch model: {args.pytorch_model}") |
| model = create_model( |
| args.model_name, |
| pretrained='eva', |
| device=args.device, |
| precision='fp32', |
| output_dict=True, |
| cache_dir=args.pytorch_model |
| ) |
| |
| benchmark = PyTorchBenchmark(model, args.device, args.mode) |
| result = benchmark.benchmark( |
| image_size=image_size, |
| batch_size=args.batch_size, |
| warmup=args.warmup, |
| iterations=args.iterations, |
| fp16=args.fp16 |
| ) |
| results.append(result) |
| print_result(result) |
| |
| |
| if args.onnx_model: |
| print(f"\nLoading ONNX model: {args.onnx_model}") |
| benchmark = ONNXBenchmark(args.onnx_model, 'cuda') |
| result = benchmark.benchmark( |
| image_size=image_size, |
| batch_size=args.batch_size, |
| warmup=args.warmup, |
| iterations=args.iterations |
| ) |
| result.mode = args.mode |
| results.append(result) |
| print_result(result) |
| |
| |
| if args.trt_engine: |
| print(f"\nLoading TensorRT engine: {args.trt_engine}") |
| benchmark = TensorRTBenchmark(args.trt_engine, args.device) |
| result = benchmark.benchmark( |
| image_size=image_size, |
| batch_size=args.batch_size, |
| warmup=args.warmup, |
| iterations=args.iterations |
| ) |
| result.mode = args.mode |
| results.append(result) |
| print_result(result) |
| |
| |
| if len(results) > 1: |
| compare_results(results) |
| |
| |
| if results: |
| output_path = Path(args.output) |
| output_path.parent.mkdir(parents=True, exist_ok=True) |
| save_results(results, str(output_path)) |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|