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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#!/usr/bin/env python3
"""
速度测试脚本 - 对比 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  # vanilla or csa
    backend: str  # pytorch, onnx, tensorrt
    precision: str  # fp32, fp16, int8
    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()
        
        # Warmup
        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)  # ms
        
        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)
        
        # 分配 GPU 内存
        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)
        
        # 预分配 GPU 内存
        d_input = cuda.mem_alloc(input_np.nbytes)
        d_output = cuda.mem_alloc(output_np.nbytes)
        
        # Warmup
        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)  # ms
        
        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,  # TRT 内存统计需要额外处理
            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)
        
        # Warmup
        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}")
    
    # 按 backend 排序
    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)
    
    # 基准 (第一个 PyTorch 结果)
    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:
                # TensorRT benchmark
                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)
        
        # PyTorch benchmark
        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)
        
        # ONNX benchmark
        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)
        
        # TensorRT benchmark
        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()