| |
| """ |
| 模型转换脚本 - PyTorch -> ONNX -> TensorRT |
| 支持 DeCLIP (csa模式) 和 CLIP (vanilla模式) 的转换 |
| |
| Usage: |
| python convert_model.py --model-type declip --mode csa --checkpoint <path> |
| python convert_model.py --model-type clip --mode vanilla --checkpoint <path> |
| """ |
|
|
| import os |
| import sys |
| import argparse |
| import time |
| from pathlib import Path |
|
|
| import torch |
| import torch.onnx |
| 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')) |
|
|
| from configs.custom_modules import ( |
| prepare_model_for_export, |
| register_custom_rewriters, |
| disable_xformers_for_export |
| ) |
|
|
|
|
| def parse_args(): |
| parser = argparse.ArgumentParser(description='DeCLIP/CLIP TensorRT 转换') |
| |
| |
| parser.add_argument('--model-type', type=str, default='declip', |
| choices=['declip', 'clip'], |
| help='模型类型: declip (DeCLIP) 或 clip (原始CLIP)') |
| parser.add_argument('--model-name', type=str, default='EVA02-CLIP-B-16', |
| help='模型名称') |
| parser.add_argument('--checkpoint', type=str, required=True, |
| help='模型检查点路径') |
| parser.add_argument('--mode', type=str, default='csa', |
| choices=['vanilla', 'csa', 'qq', 'kk'], |
| help='特征模式: vanilla (原始) 或 csa (DeCLIP)') |
| |
| |
| parser.add_argument('--image-size', type=int, default=560, |
| help='输入图像尺寸') |
| parser.add_argument('--batch-size', type=int, default=1, |
| help='批处理大小') |
| |
| |
| parser.add_argument('--output-dir', type=str, default='engines', |
| help='输出目录') |
| parser.add_argument('--output-name', type=str, default=None, |
| help='输出文件名 (不含扩展名)') |
| |
| |
| parser.add_argument('--fp16', action='store_true', default=True, |
| help='使用 FP16 精度') |
| parser.add_argument('--int8', action='store_true', |
| help='使用 INT8 精度 (需要校准数据)') |
| parser.add_argument('--workspace', type=int, default=4, |
| help='TRT workspace 大小 (GB)') |
| |
| |
| parser.add_argument('--dynamic', action='store_true', |
| help='启用动态输入形状') |
| parser.add_argument('--min-shape', type=int, nargs=2, default=[560, 560], |
| help='最小输入尺寸 [H, W]') |
| parser.add_argument('--max-shape', type=int, nargs=2, default=[800, 1333], |
| help='最大输入尺寸 [H, W]') |
| |
| |
| parser.add_argument('--device', type=str, default='cuda:0', |
| help='设备') |
| parser.add_argument('--verify', action='store_true', default=True, |
| help='验证转换后的模型精度') |
| parser.add_argument('--verbose', action='store_true', |
| help='详细输出') |
| |
| return parser.parse_args() |
|
|
|
|
| def load_model(args): |
| """加载 EVA-CLIP 模型""" |
| print(f"Loading model: {args.model_name}") |
| print(f"Checkpoint: {args.checkpoint}") |
| |
| from open_clip import create_model |
| |
| |
| model = create_model( |
| args.model_name, |
| pretrained='eva', |
| device=args.device, |
| precision='fp32', |
| output_dict=True, |
| cache_dir=args.checkpoint |
| ) |
| |
| |
| if os.path.isfile(args.checkpoint): |
| print(f"Loading checkpoint from {args.checkpoint}") |
| checkpoint = torch.load(args.checkpoint, map_location=args.device) |
| if 'state_dict' in checkpoint: |
| model.load_state_dict(checkpoint['state_dict'], strict=False) |
| elif 'model' in checkpoint: |
| model.load_state_dict(checkpoint['model'], strict=False) |
| else: |
| model.load_state_dict(checkpoint, strict=False) |
| |
| model.eval() |
| return model |
|
|
|
|
| def export_to_onnx(model, args): |
| """导出模型到 ONNX 格式""" |
| output_dir = Path(args.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
| |
| |
| if args.output_name: |
| output_name = args.output_name |
| else: |
| output_name = f"{args.model_type}_{args.mode}_{args.image_size}" |
| |
| onnx_path = output_dir / f"{output_name}.onnx" |
| |
| print(f"\n{'='*60}") |
| print(f"Exporting to ONNX: {onnx_path}") |
| print(f"{'='*60}") |
| |
| |
| model = prepare_model_for_export(model, mode=args.mode) |
| model = model.to(args.device) |
| |
| |
| dummy_input = torch.randn( |
| args.batch_size, 3, args.image_size, args.image_size, |
| device=args.device, |
| dtype=torch.float32 |
| ) |
| |
| |
| if args.dynamic: |
| dynamic_axes = { |
| 'input': {0: 'batch', 2: 'height', 3: 'width'}, |
| 'output': {0: 'batch', 2: 'feat_height', 3: 'feat_width'} |
| } |
| else: |
| dynamic_axes = None |
| |
| |
| torch.onnx.export( |
| model, |
| dummy_input, |
| str(onnx_path), |
| input_names=['input'], |
| output_names=['output'], |
| dynamic_axes=dynamic_axes, |
| opset_version=17, |
| do_constant_folding=True, |
| verbose=args.verbose |
| ) |
| |
| print(f"ONNX model saved to: {onnx_path}") |
| |
| |
| try: |
| import onnx |
| from onnxsim import simplify |
| |
| print("Simplifying ONNX model...") |
| onnx_model = onnx.load(str(onnx_path)) |
| simplified_model, check = simplify(onnx_model) |
| |
| if check: |
| simplified_path = output_dir / f"{output_name}_simplified.onnx" |
| onnx.save(simplified_model, str(simplified_path)) |
| print(f"Simplified ONNX model saved to: {simplified_path}") |
| return str(simplified_path) |
| else: |
| print("Warning: ONNX simplification failed, using original model") |
| except ImportError: |
| print("onnxsim not installed, skipping simplification") |
| |
| return str(onnx_path) |
|
|
|
|
| def convert_to_tensorrt(onnx_path, args): |
| """转换 ONNX 到 TensorRT 引擎""" |
| try: |
| import tensorrt as trt |
| except ImportError: |
| print("Error: TensorRT not installed") |
| return None |
| |
| output_dir = Path(args.output_dir) |
| engine_name = Path(onnx_path).stem.replace('_simplified', '') |
| |
| if args.fp16: |
| engine_name += '_fp16' |
| if args.int8: |
| engine_name += '_int8' |
| |
| engine_path = output_dir / f"{engine_name}.engine" |
| |
| print(f"\n{'='*60}") |
| print(f"Converting to TensorRT: {engine_path}") |
| print(f"{'='*60}") |
| |
| |
| logger = trt.Logger(trt.Logger.VERBOSE if args.verbose else trt.Logger.WARNING) |
| builder = trt.Builder(logger) |
| network = builder.create_network( |
| 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) |
| ) |
| parser = trt.OnnxParser(network, logger) |
| |
| |
| print("Parsing ONNX model...") |
| with open(onnx_path, 'rb') as f: |
| if not parser.parse(f.read()): |
| for error in range(parser.num_errors): |
| print(f"ONNX Parse Error: {parser.get_error(error)}") |
| return None |
| |
| |
| config = builder.create_builder_config() |
| config.set_memory_pool_limit( |
| trt.MemoryPoolType.WORKSPACE, |
| args.workspace * (1 << 30) |
| ) |
| |
| |
| if args.fp16: |
| if builder.platform_has_fast_fp16: |
| config.set_flag(trt.BuilderFlag.FP16) |
| print("FP16 mode enabled") |
| else: |
| print("Warning: FP16 not supported on this platform") |
| |
| if args.int8: |
| if builder.platform_has_fast_int8: |
| config.set_flag(trt.BuilderFlag.INT8) |
| print("INT8 mode enabled (requires calibration)") |
| else: |
| print("Warning: INT8 not supported on this platform") |
| |
| |
| if args.dynamic: |
| profile = builder.create_optimization_profile() |
| input_tensor = network.get_input(0) |
| |
| min_shape = (args.batch_size, 3, args.min_shape[0], args.min_shape[1]) |
| opt_shape = (args.batch_size, 3, args.image_size, args.image_size) |
| max_shape = (args.batch_size, 3, args.max_shape[0], args.max_shape[1]) |
| |
| profile.set_shape(input_tensor.name, min_shape, opt_shape, max_shape) |
| config.add_optimization_profile(profile) |
| print(f"Dynamic shapes: min={min_shape}, opt={opt_shape}, max={max_shape}") |
| |
| |
| print("Building TensorRT engine (this may take a while)...") |
| start_time = time.time() |
| |
| serialized_engine = builder.build_serialized_network(network, config) |
| |
| if serialized_engine is None: |
| print("Error: Failed to build TensorRT engine") |
| return None |
| |
| build_time = time.time() - start_time |
| print(f"Engine built in {build_time:.1f} seconds") |
| |
| |
| with open(engine_path, 'wb') as f: |
| f.write(serialized_engine) |
| |
| print(f"TensorRT engine saved to: {engine_path}") |
| |
| |
| runtime = trt.Runtime(logger) |
| engine = runtime.deserialize_cuda_engine(serialized_engine) |
| |
| print(f"\nEngine Info:") |
| print(f" - Number of layers: {engine.num_layers}") |
| print(f" - Number of IO tensors: {engine.num_io_tensors}") |
| |
| for i in range(engine.num_io_tensors): |
| name = engine.get_tensor_name(i) |
| shape = engine.get_tensor_shape(name) |
| dtype = engine.get_tensor_dtype(name) |
| mode = engine.get_tensor_mode(name) |
| print(f" - {name}: shape={shape}, dtype={dtype}, mode={mode}") |
| |
| return str(engine_path) |
|
|
|
|
| def verify_model(pytorch_model, onnx_path, engine_path, args): |
| """验证转换后的模型精度""" |
| print(f"\n{'='*60}") |
| print("Verifying model accuracy") |
| print(f"{'='*60}") |
| |
| |
| dummy_input = torch.randn( |
| 1, 3, args.image_size, args.image_size, |
| device=args.device, |
| dtype=torch.float32 |
| ) |
| |
| |
| pytorch_model = prepare_model_for_export(pytorch_model, mode=args.mode) |
| pytorch_model = pytorch_model.to(args.device).eval() |
| |
| with torch.no_grad(): |
| pytorch_output = pytorch_model(dummy_input) |
| |
| pytorch_output = pytorch_output.cpu().numpy() |
| print(f"PyTorch output shape: {pytorch_output.shape}") |
| |
| |
| try: |
| import onnxruntime as ort |
| |
| ort_session = ort.InferenceSession( |
| onnx_path, |
| providers=['CUDAExecutionProvider', 'CPUExecutionProvider'] |
| ) |
| |
| onnx_output = ort_session.run( |
| None, |
| {'input': dummy_input.cpu().numpy()} |
| )[0] |
| |
| |
| onnx_diff = np.abs(pytorch_output - onnx_output).max() |
| print(f"ONNX max difference: {onnx_diff:.6f}") |
| |
| if onnx_diff < 1e-3: |
| print("✓ ONNX verification passed") |
| else: |
| print("✗ ONNX verification failed (diff > 1e-3)") |
| |
| except ImportError: |
| print("ONNX Runtime not installed, skipping ONNX verification") |
| |
| |
| if engine_path and os.path.exists(engine_path): |
| try: |
| import tensorrt as trt |
| import pycuda.driver as cuda |
| import pycuda.autoinit |
| |
| |
| logger = trt.Logger(trt.Logger.WARNING) |
| runtime = trt.Runtime(logger) |
| |
| with open(engine_path, 'rb') as f: |
| engine = runtime.deserialize_cuda_engine(f.read()) |
| |
| context = engine.create_execution_context() |
| |
| |
| input_name = engine.get_tensor_name(0) |
| output_name = engine.get_tensor_name(1) |
| |
| input_shape = list(dummy_input.shape) |
| context.set_input_shape(input_name, input_shape) |
| |
| output_shape = context.get_tensor_shape(output_name) |
| output_size = int(np.prod(output_shape)) |
| |
| |
| d_input = cuda.mem_alloc(dummy_input.numpy().nbytes) |
| d_output = cuda.mem_alloc(output_size * np.float32().nbytes) |
| |
| |
| cuda.memcpy_htod(d_input, dummy_input.cpu().numpy()) |
| |
| |
| context.set_tensor_address(input_name, int(d_input)) |
| context.set_tensor_address(output_name, int(d_output)) |
| |
| |
| stream = cuda.Stream() |
| context.execute_async_v3(stream.handle) |
| stream.synchronize() |
| |
| |
| trt_output = np.empty(output_shape, dtype=np.float32) |
| cuda.memcpy_dtoh(trt_output, d_output) |
| |
| |
| trt_diff = np.abs(pytorch_output - trt_output).max() |
| print(f"TensorRT max difference: {trt_diff:.6f}") |
| |
| if trt_diff < 1e-2: |
| print("✓ TensorRT verification passed") |
| else: |
| print("✗ TensorRT verification failed (diff > 1e-2)") |
| |
| except ImportError as e: |
| print(f"TensorRT/PyCUDA not installed, skipping TRT verification: {e}") |
| except Exception as e: |
| print(f"TensorRT verification error: {e}") |
|
|
|
|
| def main(): |
| args = parse_args() |
| |
| print(f"\n{'='*60}") |
| print("DeCLIP/CLIP TensorRT Conversion") |
| print(f"{'='*60}") |
| print(f"Model Type: {args.model_type}") |
| print(f"Mode: {args.mode}") |
| print(f"Image Size: {args.image_size}") |
| print(f"FP16: {args.fp16}") |
| print(f"Dynamic Shapes: {args.dynamic}") |
| print(f"{'='*60}\n") |
| |
| |
| register_custom_rewriters() |
| |
| |
| model = load_model(args) |
| |
| |
| onnx_path = export_to_onnx(model, args) |
| |
| |
| engine_path = convert_to_tensorrt(onnx_path, args) |
| |
| |
| if args.verify and engine_path: |
| verify_model(model, onnx_path, engine_path, args) |
| |
| print(f"\n{'='*60}") |
| print("Conversion complete!") |
| print(f"{'='*60}") |
| print(f"ONNX: {onnx_path}") |
| if engine_path: |
| print(f"TensorRT: {engine_path}") |
| print() |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|