| |
| """ |
| 速度测试脚本 - 对比 CLIP 与 DeCLIP 在不同精度和 batch size 下的性能 |
| |
| 测试矩阵: |
| - 精度:FP32 PyTorch, FP16 PyTorch, FP16 TensorRT, FP8 TensorRT |
| - Batch sizes: 1, 16, 64, 128 |
| - 模型:CLIP (vanilla), DeCLIP (csa) |
| |
| 指标: |
| - 延迟 (ms) |
| - 吞吐量 (FPS) |
| - 显存使用 (MB) |
| |
| Usage: |
| # 测试单个模型和 batch size |
| python benchmark.py --model-tag clip --batch-size 32 --cache-dir /path/to/clip.pt |
| |
| # 测试所有 batch sizes |
| python benchmark.py --model-tag declip --batch-sizes 1,16,64,128 --cache-dir /path/to/declip.pt |
| |
| # 仅测试 TRT |
| python benchmark.py --model-tag declip --skip-pytorch --batch-sizes 1,16,64,128 |
| """ |
|
|
| import os |
| import sys |
| import argparse |
| import json |
| import time |
| import numpy as np |
| from pathlib import Path |
| from typing import Optional, Dict, Any, List |
| from datetime import datetime |
| import logging |
|
|
| import torch |
| import torch.nn as nn |
|
|
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') |
| logger = logging.getLogger(__name__) |
|
|
| PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| sys.path.insert(0, str(PROJECT_ROOT / "src")) |
|
|
| |
| DEFAULT_BATCH_SIZES = [1, 16, 64, 128] |
|
|
|
|
| |
| class TRTInference: |
| """TensorRT 推理引擎封装""" |
|
|
| def __init__(self, engine_path: str): |
| import tensorrt as trt |
|
|
| self.logger = trt.Logger(trt.Logger.WARNING) |
| self.engine_path = engine_path |
|
|
| logger.info(f"Loading TensorRT engine: {engine_path}") |
| with open(engine_path, 'rb') as f: |
| engine_data = f.read() |
|
|
| runtime = trt.Runtime(self.logger) |
| self.engine = runtime.deserialize_cuda_engine(engine_data) |
| self.context = self.engine.create_execution_context() |
|
|
| self.input_name = self.engine.get_tensor_name(0) |
| self.output_name = self.engine.get_tensor_name(1) |
| self.engine_device_memory_bytes = self._get_device_memory_size(self.engine) |
| self.context_device_memory_bytes = self._get_device_memory_size(self.context) |
|
|
| @staticmethod |
| def _get_device_memory_size(obj) -> Optional[int]: |
| if hasattr(obj, "device_memory_size"): |
| value = getattr(obj, "device_memory_size") |
| return value() if callable(value) else value |
| if hasattr(obj, "get_device_memory_size"): |
| try: |
| return obj.get_device_memory_size() |
| except Exception: |
| return None |
| return None |
|
|
| def infer(self, input_tensor: torch.Tensor) -> torch.Tensor: |
| """执行推理""" |
| self.context.set_input_shape(self.input_name, tuple(input_tensor.shape)) |
| if self.context_device_memory_bytes is None: |
| self.context_device_memory_bytes = self._get_device_memory_size(self.context) |
|
|
| output_shape = self.context.get_tensor_shape(self.output_name) |
| output_tensor = torch.empty(tuple(output_shape), dtype=torch.float32, device=input_tensor.device) |
|
|
| self.context.set_tensor_address(self.input_name, input_tensor.data_ptr()) |
| self.context.set_tensor_address(self.output_name, output_tensor.data_ptr()) |
|
|
| stream = torch.cuda.current_stream().cuda_stream |
| self.context.execute_async_v3(stream) |
| torch.cuda.synchronize() |
|
|
| return output_tensor |
|
|
|
|
| |
| class PyTorchModel: |
| """PyTorch 模型封装""" |
|
|
| def __init__( |
| self, |
| model_name: str = "EVA02-CLIP-B-16", |
| cache_dir: str = None, |
| mode: str = "csa", |
| precision: str = "fp32", |
| device: str = "cuda", |
| ): |
| from open_clip.eva_clip import create_model |
|
|
| self.device = torch.device(device) |
| self.precision = precision |
| self.mode = mode |
|
|
| logger.info(f"Loading PyTorch model ({precision}), mode={mode}, cache_dir={cache_dir}...") |
| |
| |
| |
| self.model = create_model( |
| model_name, |
| pretrained=cache_dir, |
| precision="fp32", |
| device=self.device, |
| force_custom_clip=True, |
| ) |
| self.model.eval() |
|
|
| if precision == "fp16": |
| self.model = self.model.half() |
|
|
| @torch.no_grad() |
| def infer(self, input_tensor: torch.Tensor) -> torch.Tensor: |
| return self.model.visual.encode_dense(input_tensor, keep_shape=True, mode=self.mode) |
|
|
|
|
| |
| def _parse_visible_devices(visible: str): |
| parts = [p.strip() for p in visible.split(",") if p.strip()] |
| if not parts: |
| return None |
| if all(p.isdigit() for p in parts): |
| return [int(p) for p in parts] |
| return parts |
|
|
|
|
| def _get_nvml_handle(pynvml): |
| device_index = torch.cuda.current_device() |
| visible = os.environ.get("CUDA_VISIBLE_DEVICES") |
|
|
| if visible: |
| parts = _parse_visible_devices(visible) |
| if parts: |
| if isinstance(parts[0], int): |
| if device_index < len(parts): |
| device_index = parts[device_index] |
| return pynvml.nvmlDeviceGetHandleByIndex(device_index) |
| if device_index < len(parts): |
| try: |
| return pynvml.nvmlDeviceGetHandleByUUID(parts[device_index]) |
| except Exception: |
| pass |
|
|
| return pynvml.nvmlDeviceGetHandleByIndex(device_index) |
|
|
|
|
| class NVMLMemoryTracker: |
| """使用 NVML 统计进程级 GPU 显存""" |
|
|
| def __init__(self): |
| self.available = False |
| self._pynvml = None |
| self._handle = None |
| self._pid = os.getpid() |
| self._error = None |
|
|
| try: |
| import pynvml |
|
|
| self._pynvml = pynvml |
| pynvml.nvmlInit() |
| self._handle = _get_nvml_handle(pynvml) |
| self.available = True |
| except Exception as e: |
| self._error = e |
|
|
| def get_process_used_mb(self) -> Optional[float]: |
| if not self.available: |
| return None |
|
|
| try: |
| processes = self._pynvml.nvmlDeviceGetComputeRunningProcesses(self._handle) |
| except Exception: |
| try: |
| processes = self._pynvml.nvmlDeviceGetGraphicsRunningProcesses(self._handle) |
| except Exception: |
| return None |
|
|
| for proc in processes: |
| if proc.pid == self._pid: |
| used = getattr(proc, "usedGpuMemory", None) |
| if used is None or used < 0: |
| return None |
| return used / (1024 ** 2) |
|
|
| return 0.0 |
|
|
| def get_device_used_mb(self) -> Optional[float]: |
| if not self.available: |
| return None |
| try: |
| info = self._pynvml.nvmlDeviceGetMemoryInfo(self._handle) |
| return info.used / (1024 ** 2) |
| except Exception: |
| return None |
|
|
| def shutdown(self): |
| if not self.available: |
| return |
| try: |
| self._pynvml.nvmlShutdown() |
| except Exception: |
| pass |
|
|
|
|
|
|
|
|
| def get_gpu_memory_mb() -> float: |
| return torch.cuda.memory_allocated() / (1024 ** 2) |
|
|
|
|
| def get_gpu_memory_peak_mb() -> float: |
| return torch.cuda.max_memory_allocated() / (1024 ** 2) |
|
|
|
|
| def reset_gpu_memory_stats(): |
| torch.cuda.reset_peak_memory_stats() |
| torch.cuda.empty_cache() |
|
|
|
|
| def benchmark_latency( |
| model, |
| input_shape: tuple, |
| warmup_iterations: int = 50, |
| benchmark_iterations: int = 200, |
| device: str = "cuda", |
| input_dtype: torch.dtype = torch.float32, |
| ) -> Dict[str, float]: |
| """测试推理延迟""" |
| device = torch.device(device) |
| reset_gpu_memory_stats() |
| model_memory_mb = get_gpu_memory_mb() |
|
|
| dummy_input = torch.randn(input_shape, device=device, dtype=input_dtype) |
| nvml_tracker = NVMLMemoryTracker() |
| nvml_base_mb = None |
| nvml_peak_mb = None |
| nvml_device_base_mb = None |
| nvml_device_peak_mb = None |
| if nvml_tracker.available: |
| nvml_base_mb = nvml_tracker.get_process_used_mb() |
| nvml_peak_mb = nvml_base_mb if nvml_base_mb is not None else 0.0 |
| nvml_device_base_mb = nvml_tracker.get_device_used_mb() |
| nvml_device_peak_mb = nvml_device_base_mb if nvml_device_base_mb is not None else 0.0 |
|
|
| |
| for _ in range(warmup_iterations): |
| _ = model.infer(dummy_input) |
| if nvml_tracker.available: |
| used_mb = nvml_tracker.get_process_used_mb() |
| if used_mb is not None: |
| if nvml_peak_mb is None: |
| nvml_peak_mb = used_mb |
| else: |
| nvml_peak_mb = max(nvml_peak_mb, used_mb) |
| device_used_mb = nvml_tracker.get_device_used_mb() |
| if device_used_mb is not None: |
| if nvml_device_peak_mb is None: |
| nvml_device_peak_mb = device_used_mb |
| else: |
| nvml_device_peak_mb = max(nvml_device_peak_mb, device_used_mb) |
| torch.cuda.synchronize() |
|
|
| |
| latencies = [] |
| for _ in range(benchmark_iterations): |
| torch.cuda.synchronize() |
| start = time.perf_counter() |
| _ = model.infer(dummy_input) |
| torch.cuda.synchronize() |
| end = time.perf_counter() |
| latencies.append((end - start) * 1000) |
| if nvml_tracker.available: |
| used_mb = nvml_tracker.get_process_used_mb() |
| if used_mb is not None: |
| if nvml_peak_mb is None: |
| nvml_peak_mb = used_mb |
| else: |
| nvml_peak_mb = max(nvml_peak_mb, used_mb) |
| device_used_mb = nvml_tracker.get_device_used_mb() |
| if device_used_mb is not None: |
| if nvml_device_peak_mb is None: |
| nvml_device_peak_mb = device_used_mb |
| else: |
| nvml_device_peak_mb = max(nvml_device_peak_mb, device_used_mb) |
|
|
| latencies = np.array(latencies) |
| torch_peak_memory_mb = get_gpu_memory_peak_mb() |
| nvml_peak_total_mb = None |
| nvml_peak_delta_mb = None |
| if nvml_peak_mb is not None and nvml_base_mb is not None: |
| nvml_peak_total_mb = nvml_peak_mb |
| nvml_peak_delta_mb = max(nvml_peak_mb - nvml_base_mb, 0.0) |
|
|
| if nvml_peak_delta_mb is not None and nvml_peak_delta_mb > 0: |
| peak_memory_mb = nvml_peak_delta_mb |
| peak_memory_source = "nvml-delta" |
| elif nvml_peak_total_mb is not None and nvml_peak_total_mb > 0: |
| peak_memory_mb = nvml_peak_total_mb |
| peak_memory_source = "nvml-total" |
| else: |
| peak_memory_mb = torch_peak_memory_mb |
| peak_memory_source = "torch" |
|
|
| nvml_tracker.shutdown() |
|
|
| return { |
| "mean_ms": float(np.mean(latencies)), |
| "std_ms": float(np.std(latencies)), |
| "min_ms": float(np.min(latencies)), |
| "max_ms": float(np.max(latencies)), |
| "p50_ms": float(np.percentile(latencies, 50)), |
| "p95_ms": float(np.percentile(latencies, 95)), |
| "p99_ms": float(np.percentile(latencies, 99)), |
| "throughput_fps": float(1000 / np.mean(latencies) * input_shape[0]), |
| "model_memory_mb": float(model_memory_mb), |
| "peak_memory_mb": float(peak_memory_mb), |
| "base_memory_mb": float(nvml_base_mb) if nvml_base_mb is not None else None, |
| "peak_memory_total_mb": float(nvml_peak_total_mb) if nvml_peak_total_mb is not None else None, |
| "torch_peak_memory_mb": float(torch_peak_memory_mb), |
| "peak_memory_source": peak_memory_source, |
| "nvml_device_base_mb": float(nvml_device_base_mb) if nvml_device_base_mb is not None else None, |
| "nvml_device_peak_mb": float(nvml_device_peak_mb) if nvml_device_peak_mb is not None else None, |
| "batch_size": input_shape[0], |
| } |
|
|
|
|
| def find_trt_engine(engine_dir: Path, model_tag: str, mode: str, image_size: int, precision: str, batch_size: int) -> Optional[Path]: |
| """查找 TRT 引擎文件""" |
| |
| engine_name = f"{model_tag}_eva_clip_b16_{mode}_{image_size}_{precision}_bs{batch_size}.trt" |
| engine_path = engine_dir / engine_name |
| if engine_path.exists(): |
| return engine_path |
|
|
| |
| old_name = f"{model_tag}_eva_clip_b16_{mode}_{image_size}_{precision}.trt" |
| old_path = engine_dir / old_name |
| if old_path.exists() and batch_size == 1: |
| return old_path |
|
|
| return None |
|
|
|
|
| def run_single_benchmark( |
| model_tag: str, |
| checkpoint: str, |
| mode: str, |
| precision: str, |
| batch_size: int, |
| image_size: int, |
| engine_dir: Path, |
| warmup: int = 50, |
| iterations: int = 200, |
| ) -> Optional[Dict[str, Any]]: |
| """运行单个基准测试""" |
| device = "cuda" |
| input_shape = (batch_size, 3, image_size, image_size) |
|
|
| result = None |
|
|
| if precision in ["fp32", "fp16"]: |
| |
| try: |
| model = PyTorchModel( |
| cache_dir=checkpoint, |
| mode=mode, |
| precision=precision, |
| device=device, |
| ) |
| input_dtype = torch.float16 if precision == "fp16" else torch.float32 |
| result = benchmark_latency( |
| model, |
| input_shape, |
| warmup, |
| iterations, |
| device, |
| input_dtype=input_dtype, |
| ) |
| result["precision"] = precision |
| result["backend"] = "pytorch" |
| del model |
| torch.cuda.empty_cache() |
| except Exception as e: |
| logger.error(f"PyTorch {precision} failed: {e}") |
|
|
| elif precision.startswith("trt-"): |
| |
| trt_precision = precision.replace("trt-", "") |
| engine_path = find_trt_engine(engine_dir, model_tag, mode, image_size, trt_precision, batch_size) |
|
|
| if engine_path is None: |
| logger.warning(f"TRT engine not found for {model_tag}, {trt_precision}, bs={batch_size}") |
| return None |
|
|
| try: |
| model = TRTInference(str(engine_path)) |
| result = benchmark_latency(model, input_shape, warmup, iterations, device) |
| result["precision"] = trt_precision |
| result["backend"] = "tensorrt" |
| result["engine_path"] = str(engine_path) |
| if model.engine_device_memory_bytes is not None: |
| result["trt_engine_device_memory_mb"] = model.engine_device_memory_bytes / (1024 ** 2) |
| if model.context_device_memory_bytes is not None: |
| result["trt_context_device_memory_mb"] = model.context_device_memory_bytes / (1024 ** 2) |
| del model |
| torch.cuda.empty_cache() |
| except Exception as e: |
| logger.error(f"TensorRT {trt_precision} failed: {e}") |
|
|
| if result: |
| result["model_tag"] = model_tag |
| result["mode"] = mode |
|
|
| return result |
|
|
|
|
| def print_results_table(results: List[Dict[str, Any]], title: str = "Benchmark Results"): |
| """打印结果表格""" |
| if not results: |
| logger.warning("No results to print") |
| return |
|
|
| print("\n" + "=" * 110) |
| print(f" {title}") |
| print("=" * 110) |
|
|
| headers = ["Model", "Backend", "Precision", "Batch", "Mean (ms)", "Std (ms)", "P95 (ms)", "FPS", "Peak Mem (MB)"] |
| col_widths = [10, 10, 10, 6, 12, 10, 10, 12, 14] |
|
|
| header_row = " | ".join(h.center(w) for h, w in zip(headers, col_widths)) |
| print(header_row) |
| print("-" * len(header_row)) |
|
|
| for r in results: |
| row = [ |
| r.get("model_tag", "")[:10], |
| r.get("backend", "")[:10], |
| r.get("precision", "")[:10], |
| str(r.get("batch_size", "")), |
| f"{r['mean_ms']:.2f}", |
| f"{r['std_ms']:.2f}", |
| f"{r['p95_ms']:.2f}", |
| f"{r['throughput_fps']:.1f}", |
| f"{r['peak_memory_mb']:.1f}", |
| ] |
| print(" | ".join(str(v).center(w) for v, w in zip(row, col_widths))) |
|
|
| print("=" * 110) |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Benchmark EVA-CLIP inference") |
|
|
| |
| parser.add_argument("--model-name", type=str, default="EVA02-CLIP-B-16") |
| parser.add_argument("--cache-dir", type=str, default=None, |
| help="Path to model checkpoint, e.g. EVA02_CLIP_B_psz16_s8B.pt or declip epoch_6.pt") |
| parser.add_argument("--mode", type=str, default="csa", |
| choices=["csa", "vanilla", "dummy_csa", "qq_xformer"]) |
| parser.add_argument("--image-size", type=int, default=560) |
|
|
| |
| parser.add_argument("--engine-dir", type=str, default="./trt_engines") |
| parser.add_argument("--model-tag", type=str, default="", |
| help="Model tag for engine naming") |
|
|
| |
| parser.add_argument("--batch-size", type=int, default=None, |
| help="Single batch size (deprecated, use --batch-sizes)") |
| parser.add_argument("--batch-sizes", type=str, default="1,16,64,128", |
| help="Comma-separated batch sizes") |
| parser.add_argument("--precisions", type=str, default="fp32,fp16,trt-fp16,trt-fp8", |
| help="Comma-separated precisions to test") |
| parser.add_argument("--warmup", type=int, default=50) |
| parser.add_argument("--iterations", type=int, default=200) |
|
|
| |
| parser.add_argument("--output-dir", type=str, default="./results") |
| parser.add_argument("--output-json", type=str, default=None, |
| help="Output JSON file (auto-generated if not specified)") |
|
|
| |
| parser.add_argument("--skip-pytorch", action="store_true") |
| parser.add_argument("--skip-trt", action="store_true") |
|
|
| args = parser.parse_args() |
|
|
| |
| if args.batch_size: |
| batch_sizes = [args.batch_size] |
| else: |
| batch_sizes = [int(x.strip()) for x in args.batch_sizes.split(",")] |
|
|
| precisions = [x.strip() for x in args.precisions.split(",")] |
|
|
| if args.skip_pytorch: |
| precisions = [p for p in precisions if not p in ["fp32", "fp16"]] |
| if args.skip_trt: |
| precisions = [p for p in precisions if not p.startswith("trt-")] |
|
|
| engine_dir = Path(args.engine_dir) |
| output_dir = Path(args.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| logger.info(f"Batch sizes: {batch_sizes}") |
| logger.info(f"Precisions: {precisions}") |
| logger.info(f"Device: {torch.cuda.get_device_name(0)}") |
|
|
| |
| if not args.skip_pytorch and args.cache_dir is None: |
| parser.error("--cache-dir is required for PyTorch tests (or use --skip-pytorch)") |
|
|
| |
| all_results = [] |
|
|
| for precision in precisions: |
| for batch_size in batch_sizes: |
| logger.info(f"\n--- {precision.upper()}, Batch {batch_size} ---") |
|
|
| result = run_single_benchmark( |
| model_tag=args.model_tag, |
| checkpoint=args.cache_dir, |
| mode=args.mode, |
| precision=precision, |
| batch_size=batch_size, |
| image_size=args.image_size, |
| engine_dir=engine_dir, |
| warmup=args.warmup, |
| iterations=args.iterations, |
| ) |
|
|
| if result: |
| all_results.append(result) |
|
|
| |
| print_results_table(all_results, f"Benchmark Results - {args.model_tag}") |
|
|
| |
| if args.output_json: |
| output_file = Path(args.output_json) |
| else: |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| output_file = output_dir / f"{args.model_tag}_benchmark_{timestamp}.json" |
|
|
| output_data = { |
| "config": { |
| "model_tag": args.model_tag, |
| "mode": args.mode, |
| "image_size": args.image_size, |
| "batch_sizes": batch_sizes, |
| "precisions": precisions, |
| "device": torch.cuda.get_device_name(0), |
| "timestamp": datetime.now().isoformat(), |
| }, |
| "results": all_results, |
| } |
|
|
| with open(output_file, 'w') as f: |
| json.dump(output_data, f, indent=2) |
|
|
| logger.info(f"Results saved: {output_file}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|