| |
| """ |
| TensorRT 量化脚本 for EVA-CLIP CSA模式 |
| 支持 FP16、FP8、INT8 精度 |
| |
| 量化策略: |
| - FP16: 无量化,只设置 TensorRT BuilderFlag.FP16 |
| - FP8: 使用 TensorRT 原生 FP8 支持(需要 H100/Ada 架构) |
| - INT8: 使用 pytorch-quantization PTQ 或 TensorRT 内置校准器 |
| |
| 校准数据集:COCO Panoptic val2017 |
| |
| Usage: |
| # FP16 (无量化) |
| python trt_quantize.py --mode csa --precision fp16 |
| |
| # FP8 (TensorRT 原生支持,H100 优化) |
| python trt_quantize.py --mode csa --precision fp8 |
| |
| # INT8 (PTQ,使用 pytorch-quantization) |
| python trt_quantize.py --mode csa --precision int8 --calib-size 512 |
| """ |
|
|
| import os |
| import sys |
| import argparse |
| import json |
| import numpy as np |
| from pathlib import Path |
| from typing import List, Optional |
| import logging |
| from contextlib import nullcontext |
|
|
| import torch |
| import torch.nn as nn |
| from torch.utils.data import DataLoader, Dataset |
| from PIL import Image |
| from torchvision import transforms |
| from tqdm import tqdm |
|
|
| |
| PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| sys.path.insert(0, str(PROJECT_ROOT / "src")) |
|
|
| |
| |
| |
|
|
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') |
| logger = logging.getLogger(__name__) |
|
|
|
|
| |
| OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) |
| OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711) |
|
|
|
|
| |
| def check_modelopt_available(): |
| """检查 nvidia-modelopt 是否可用""" |
| try: |
| import modelopt.torch.quantization as mtq |
| logger.info("nvidia-modelopt is available") |
| return True |
| except ImportError as e: |
| logger.warning(f"nvidia-modelopt not installed: {e}") |
| return False |
| except Exception as e: |
| logger.warning(f"nvidia-modelopt import failed: {type(e).__name__}: {e}") |
| return False |
|
|
|
|
| |
| |
| |
| FP8_DEFAULT_CONFIG = { |
| "quant_cfg": { |
| "*weight_quantizer": {"num_bits": (4, 3), "axis": None, "trt_high_precision_dtype": "Half"}, |
| "*input_quantizer": {"num_bits": (4, 3), "axis": None, "trt_high_precision_dtype": "Half"}, |
| "*output_quantizer": {"enable": False}, |
| "default": {"enable": False}, |
| }, |
| "algorithm": "max", |
| } |
|
|
|
|
| def disable_conv2d_quantizers(model: nn.Module): |
| """ |
| 禁用模型中所有 Conv2d 层的量化器 |
| |
| 这是解决 ONNX 导出时 "unknown kernel shape" 错误的必要步骤。 |
| PyTorch ONNX 导出器无法正确处理 TRT_FP8DequantizeLinear 操作后的卷积。 |
| |
| 参考:TensorRT/demo/Diffusion/demo_diffusion/utils_modelopt.py 中的 quantize_lvl 函数 |
| """ |
| disabled_count = 0 |
| for name, module in model.named_modules(): |
| if isinstance(module, nn.Conv2d): |
| |
| if hasattr(module, 'input_quantizer') and module.input_quantizer is not None: |
| module.input_quantizer.disable() |
| disabled_count += 1 |
| if hasattr(module, 'weight_quantizer') and module.weight_quantizer is not None: |
| module.weight_quantizer.disable() |
| |
| if disabled_count > 0: |
| logger.info(f"Disabled FP8 quantizers for {disabled_count} Conv2d layers to enable ONNX export") |
|
|
|
|
| def quantize_model_fp8(model: nn.Module, calib_dataloader, device): |
| """ |
| 使用 nvidia-modelopt 对模型进行 FP8 量化 |
| |
| Args: |
| model: PyTorch 模型 |
| calib_dataloader: 校准数据加载器 |
| device: 设备 |
| |
| Returns: |
| 量化后的模型(FP16 精度) |
| """ |
| import modelopt.torch.quantization as mtq |
| |
| model.eval() |
| |
| |
| |
| logger.info("Converting model to FP16 for FP8 quantization...") |
| model = model.half() |
| |
| |
| def forward_loop(model): |
| with torch.no_grad(): |
| for i, batch in enumerate(calib_dataloader): |
| if i >= 32: |
| break |
| |
| batch = batch.to(device).half() |
| _ = model(batch) |
| |
| logger.info("Quantizing model with FP8 (nvidia-modelopt)...") |
| logger.info(f"Using {min(32, len(calib_dataloader))} batches for calibration") |
| |
| |
| mtq.quantize(model, FP8_DEFAULT_CONFIG, forward_loop) |
| |
| |
| disable_conv2d_quantizers(model) |
| |
| logger.info("FP8 quantization completed") |
| return model |
|
|
|
|
| def export_onnx_fp8(model: nn.Module, onnx_path: str, image_size: int, batch_size: int = 1): |
| """ |
| 导出 FP8 量化模型为 ONNX(包含 Q/DQ 节点) |
| |
| Args: |
| model: FP8 量化后的模型(应该是 FP16 精度) |
| onnx_path: ONNX 输出路径 |
| image_size: 输入图像尺寸 |
| batch_size: batch size |
| """ |
| model.eval() |
| device = next(model.parameters()).device |
| |
| |
| |
| dummy_input = torch.randn(batch_size, 3, image_size, image_size, device=device).half() |
| |
| logger.info(f"Exporting FP8 quantized model to ONNX: {onnx_path}") |
| logger.info(f"Model dtype: {next(model.parameters()).dtype}, Input dtype: {dummy_input.dtype}") |
| |
| |
| with torch.no_grad(): |
| torch.onnx.export( |
| model, |
| dummy_input, |
| onnx_path, |
| input_names=["input"], |
| output_names=["output"], |
| dynamic_axes={ |
| "input": {0: "batch_size"}, |
| "output": {0: "batch_size"}, |
| }, |
| opset_version=17, |
| do_constant_folding=True, |
| ) |
| |
| logger.info(f"FP8 ONNX export completed: {onnx_path}") |
|
|
|
|
| |
| def check_ptq_available(): |
| """检查 pytorch-quantization 是否可用""" |
| try: |
| from pytorch_quantization import quant_modules |
| from pytorch_quantization.tensor_quant import QuantDescriptor |
| logger.info("pytorch-quantization is available") |
| return True |
| except ImportError as e: |
| logger.warning(f"pytorch-quantization not installed: {e}") |
| return False |
| except Exception as e: |
| logger.warning(f"pytorch-quantization import failed: {type(e).__name__}: {e}") |
| return False |
|
|
|
|
| def initialize_ptq(precision: str): |
| """ |
| 初始化 PTQ 量化模块 |
| |
| 注意:pytorch-quantization 只支持 INT8 量化 |
| FP8 需要使用 TensorRT 的原生支持(BuilderFlag.FP8) |
| |
| Args: |
| precision: "int8"(FP8 不支持 PTQ) |
| |
| Returns: |
| 是否成功初始化 |
| """ |
| if precision == "fp8": |
| |
| |
| logger.info("FP8 uses TensorRT native support, no PTQ needed") |
| return False |
| |
| try: |
| from pytorch_quantization import quant_modules |
| from pytorch_quantization.tensor_quant import QuantDescriptor |
| from pytorch_quantization import nn as quant_nn |
| |
| |
| |
| |
| quant_desc_input = QuantDescriptor(num_bits=8, calib_method="histogram") |
| quant_desc_weight = QuantDescriptor(num_bits=8, axis=(0,)) |
| logger.info("Configured INT8 quantization (histogram calibration, per-channel weights)") |
| |
| |
| quant_nn.TensorQuantizer.set_default_quant_desc_input(quant_desc_input) |
| quant_nn.TensorQuantizer.set_default_quant_desc_weight(quant_desc_weight) |
| |
| |
| quant_modules.initialize() |
| |
| logger.info("PTQ modules initialized successfully") |
| return True |
| |
| except ImportError as e: |
| logger.warning(f"pytorch-quantization not available: {e}") |
| logger.warning("Install with: pip install pytorch-quantization --extra-index-url https://pypi.nvidia.com") |
| return False |
| except Exception as e: |
| logger.warning(f"PTQ initialization failed: {type(e).__name__}: {e}") |
| return False |
|
|
|
|
| def deactivate_ptq(): |
| """恢复原始模块""" |
| try: |
| from pytorch_quantization import quant_modules |
| quant_modules.deactivate() |
| except ImportError: |
| pass |
|
|
|
|
| def calibrate_model(model: nn.Module, dataloader: DataLoader, device: torch.device, num_batches: int = None): |
| """ |
| 使用校准数据收集量化统计信息 |
| |
| 基于 pytorch-quantization 官方示例实现 |
| |
| Args: |
| model: 量化模型 |
| dataloader: 校准数据加载器 |
| device: 设备 |
| num_batches: 校准批次数(None 表示使用全部数据) |
| """ |
| from pytorch_quantization import nn as quant_nn |
| from pytorch_quantization import calib |
| |
| model.eval() |
| |
| |
| logger.info("Enabling calibration mode...") |
| for name, module in model.named_modules(): |
| if isinstance(module, quant_nn.TensorQuantizer): |
| if module._calibrator is not None: |
| module.disable_quant() |
| module.enable_calib() |
| else: |
| module.disable() |
| |
| |
| logger.info("Collecting calibration statistics...") |
| total_batches = num_batches or len(dataloader) |
| |
| with torch.no_grad(): |
| for i, batch in enumerate(tqdm(dataloader, total=total_batches, desc="Calibrating")): |
| batch = batch.to(device) |
| _ = model(batch) |
| if num_batches and i >= num_batches: |
| break |
| |
| |
| logger.info("Disabling calibration mode...") |
| for name, module in model.named_modules(): |
| if isinstance(module, quant_nn.TensorQuantizer): |
| if module._calibrator is not None: |
| module.enable_quant() |
| module.disable_calib() |
| else: |
| module.enable() |
| |
| |
| logger.info("Computing amax from calibration statistics...") |
| for name, module in model.named_modules(): |
| if isinstance(module, quant_nn.TensorQuantizer): |
| if module._calibrator is not None: |
| if isinstance(module._calibrator, calib.MaxCalibrator): |
| module.load_calib_amax() |
| else: |
| module.load_calib_amax(method="max") |
| |
| |
| model.to(device) |
| |
| logger.info("Calibration completed") |
|
|
|
|
| def export_onnx_with_ptq( |
| model: nn.Module, |
| output_path: str, |
| image_size: int = 560, |
| batch_size: int = 1, |
| opset_version: int = 17, |
| dynamic_batch: bool = True, |
| ): |
| """导出带 Q/DQ 节点的 ONNX 模型(用于 FP8/INT8)""" |
| from pytorch_quantization import quant_modules |
| from pytorch_quantization import nn as quant_nn |
| |
| model.eval() |
| device = next(model.parameters()).device |
| |
| dummy_input = torch.randn(batch_size, 3, image_size, image_size, device=device) |
| |
| dynamic_axes = None |
| if dynamic_batch: |
| dynamic_axes = { |
| 'input': {0: 'batch_size'}, |
| 'output': {0: 'batch_size'}, |
| } |
| |
| logger.info(f"Exporting quantized ONNX to {output_path}") |
| |
| |
| with torch.no_grad(), quant_modules.enable_onnx_export(): |
| torch.onnx.export( |
| model, |
| dummy_input, |
| output_path, |
| input_names=['input'], |
| output_names=['output'], |
| dynamic_axes=dynamic_axes, |
| opset_version=opset_version, |
| do_constant_folding=True, |
| ) |
| |
| logger.info(f"Quantized ONNX export completed: {output_path}") |
| |
| |
| import onnx |
| onnx_model = onnx.load(output_path) |
| onnx.checker.check_model(onnx_model) |
| logger.info("ONNX model validation passed") |
|
|
|
|
| |
| class COCOCalibrationDataset(Dataset): |
| """COCO Panoptic 校准数据集""" |
|
|
| def __init__( |
| self, |
| image_root: str, |
| annotation_file: str, |
| image_size: int = 560, |
| max_samples: int = 512, |
| ): |
| self.image_root = Path(image_root) |
| self.image_size = image_size |
|
|
| |
| with open(annotation_file, 'r') as f: |
| data = json.load(f) |
|
|
| self.images = data.get('images', [])[:max_samples] |
| logger.info(f"Loaded {len(self.images)} images for calibration") |
|
|
| |
| self.transform = transforms.Compose([ |
| transforms.Resize((image_size, image_size), interpolation=transforms.InterpolationMode.BICUBIC), |
| transforms.ToTensor(), |
| transforms.Normalize(mean=OPENAI_DATASET_MEAN, std=OPENAI_DATASET_STD), |
| ]) |
|
|
| def __len__(self): |
| return len(self.images) |
|
|
| def __getitem__(self, idx): |
| img_info = self.images[idx] |
| img_path = self.image_root / img_info['file_name'] |
|
|
| image = Image.open(img_path).convert('RGB') |
| image = self.transform(image) |
|
|
| return image |
|
|
|
|
| |
| def disable_xformers(model): |
| """ |
| 递归禁用模型中所有 Attention 模块的 xformers |
| xformers 的 memory_efficient_attention 不支持 ONNX 导出 |
| """ |
| for name, module in model.named_modules(): |
| if hasattr(module, 'xattn'): |
| module.xattn = False |
| logger.info(f"Disabled xformers for module: {name}") |
| return model |
|
|
|
|
| |
| class EVAVisualCSAWrapper(nn.Module): |
| """ |
| 包装 EVA-CLIP Visual Encoder 用于 ONNX 导出 |
| 仅导出 visual encoder 的 CSA 推理路径 |
| """ |
|
|
| def __init__(self, model, mode: str = "csa"): |
| super().__init__() |
| |
| self.visual = disable_xformers(model.visual) |
| self.mode = mode |
|
|
| def forward(self, x: torch.Tensor) -> torch.Tensor: |
| """ |
| Args: |
| x: [B, 3, H, W] 输入图像 |
| Returns: |
| features: [B, C, H', W'] dense features |
| """ |
| return self.visual.encode_dense(x, keep_shape=True, mode=self.mode) |
|
|
|
|
| |
| |
| def create_int8_calibrator_class(): |
| """动态创建 INT8 校准器类,继承自 trt.IInt8EntropyCalibrator2""" |
| import tensorrt as trt |
|
|
| class Int8EntropyCalibrator2(trt.IInt8EntropyCalibrator2): |
| """TensorRT INT8 熵校准器 - 继承自 trt.IInt8EntropyCalibrator2""" |
|
|
| def __init__( |
| self, |
| dataloader: DataLoader, |
| cache_file: str = "calibration.cache", |
| input_shape: tuple = (3, 560, 560), |
| ): |
| super().__init__() |
| self.dataloader = dataloader |
| self.cache_file = cache_file |
| self.batch_iter = iter(dataloader) |
| self.device = torch.device("cuda") |
| self.input_shape = input_shape |
|
|
| |
| self.batch_size = dataloader.batch_size |
| self.d_input = torch.empty( |
| (self.batch_size, *input_shape), |
| dtype=torch.float32, |
| device=self.device |
| ) |
|
|
| def get_batch_size(self): |
| return self.batch_size |
|
|
| def get_batch(self, names: List[str]): |
| try: |
| batch = next(self.batch_iter) |
| if isinstance(batch, torch.Tensor): |
| batch = batch.to(self.device) |
| |
| self.d_input.copy_(batch) |
| return [int(self.d_input.data_ptr())] |
| except StopIteration: |
| return None |
|
|
| def read_calibration_cache(self): |
| if os.path.exists(self.cache_file): |
| with open(self.cache_file, "rb") as f: |
| return f.read() |
| return None |
|
|
| def write_calibration_cache(self, cache): |
| with open(self.cache_file, "wb") as f: |
| f.write(cache) |
|
|
| return Int8EntropyCalibrator2 |
|
|
|
|
| |
| def export_onnx( |
| model: nn.Module, |
| output_path: str, |
| image_size: int = 560, |
| batch_size: int = 1, |
| opset_version: int = 17, |
| dynamic_batch: bool = False, |
| ): |
| """导出模型为 ONNX 格式 |
| |
| 注意:EVA-CLIP 的 RoPE 实现与动态 batch 不兼容, |
| 因此默认使用固定 batch size 导出。 |
| """ |
|
|
| model.eval() |
| device = next(model.parameters()).device |
|
|
| dummy_input = torch.randn(batch_size, 3, image_size, image_size, device=device) |
|
|
| dynamic_axes = None |
| if dynamic_batch: |
| dynamic_axes = { |
| 'input': {0: 'batch_size'}, |
| 'output': {0: 'batch_size'}, |
| } |
|
|
| logger.info(f"Exporting ONNX to {output_path} (batch_size={batch_size}, dynamic={dynamic_batch})") |
|
|
| with torch.no_grad(): |
| torch.onnx.export( |
| model, |
| dummy_input, |
| output_path, |
| input_names=['input'], |
| output_names=['output'], |
| dynamic_axes=dynamic_axes, |
| opset_version=opset_version, |
| do_constant_folding=True, |
| ) |
|
|
| logger.info(f"ONNX export completed: {output_path}") |
|
|
| |
| try: |
| import onnxsim |
| logger.info("Simplifying ONNX model with onnx-simplifier...") |
| import onnx |
| onnx_model = onnx.load(output_path) |
| onnx_model_simplified, check = onnxsim.simplify(onnx_model) |
| if check: |
| onnx.save(onnx_model_simplified, output_path) |
| logger.info("ONNX model simplified successfully") |
| else: |
| logger.warning("ONNX simplification failed, using original model") |
| except ImportError: |
| logger.info("onnx-simplifier not installed, skipping simplification") |
| except Exception as e: |
| logger.warning(f"ONNX simplification failed: {e}, using original model") |
|
|
| |
| import onnx |
| onnx_model = onnx.load(output_path) |
| onnx.checker.check_model(onnx_model) |
| logger.info("ONNX model validation passed") |
|
|
|
|
| |
| def build_trt_engine( |
| onnx_path: str, |
| engine_path: str, |
| precision: str = "int8", |
| calib_dataloader: Optional[DataLoader] = None, |
| calib_cache: str = "calibration.cache", |
| workspace_size: int = 8, |
| min_batch: int = 1, |
| opt_batch: int = 1, |
| max_batch: int = 1, |
| image_size: int = 560, |
| use_fixed_batch: bool = True, |
| ): |
| """构建 TensorRT 引擎 |
| |
| 注意:EVA-CLIP 的 RoPE 与动态 batch 不兼容, |
| 默认使用固定 batch size 构建引擎。 |
| """ |
|
|
| import tensorrt as trt |
|
|
| TRT_LOGGER = trt.Logger(trt.Logger.INFO) |
|
|
| builder = trt.Builder(TRT_LOGGER) |
| network_flags = 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) |
| network = builder.create_network(network_flags) |
| parser = trt.OnnxParser(network, TRT_LOGGER) |
|
|
| |
| logger.info(f"Parsing ONNX file: {onnx_path}") |
| with open(onnx_path, 'rb') as f: |
| if not parser.parse(f.read()): |
| for error in range(parser.num_errors): |
| logger.error(f"ONNX parse error: {parser.get_error(error)}") |
| raise RuntimeError("Failed to parse ONNX file") |
|
|
| |
| config = builder.create_builder_config() |
| config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace_size * (1 << 30)) |
|
|
| |
| if precision == "fp16": |
| if builder.platform_has_fast_fp16: |
| config.set_flag(trt.BuilderFlag.FP16) |
| logger.info("Enabled FP16 precision") |
| else: |
| logger.warning("FP16 not supported on this platform") |
|
|
| elif precision == "fp8": |
| |
| |
| |
| config.set_flag(trt.BuilderFlag.FP16) |
| if hasattr(trt.BuilderFlag, 'FP8'): |
| config.set_flag(trt.BuilderFlag.FP8) |
| logger.info("Enabled FP8 precision (with FP16 fallback)") |
| else: |
| logger.info("FP8 flag not available, using FP16") |
|
|
| elif precision == "int8": |
| if builder.platform_has_fast_int8: |
| config.set_flag(trt.BuilderFlag.INT8) |
|
|
| |
| if calib_dataloader is not None: |
| logger.info("Setting up INT8 calibrator") |
| |
| Int8EntropyCalibrator2 = create_int8_calibrator_class() |
| calibrator = Int8EntropyCalibrator2( |
| calib_dataloader, |
| calib_cache, |
| input_shape=(3, image_size, image_size), |
| ) |
| config.int8_calibrator = calibrator |
| else: |
| logger.warning("No calibration data provided for INT8") |
|
|
| logger.info("Enabled INT8 precision") |
| else: |
| logger.warning("INT8 not supported on this platform, falling back to FP16") |
| config.set_flag(trt.BuilderFlag.FP16) |
|
|
| |
| profile = builder.create_optimization_profile() |
| input_name = network.get_input(0).name |
|
|
| if use_fixed_batch: |
| |
| fixed_batch = opt_batch |
| logger.info(f"Using fixed batch size: {fixed_batch}") |
| profile.set_shape( |
| input_name, |
| min=(fixed_batch, 3, image_size, image_size), |
| opt=(fixed_batch, 3, image_size, image_size), |
| max=(fixed_batch, 3, image_size, image_size), |
| ) |
| else: |
| |
| logger.info(f"Using dynamic batch size: min={min_batch}, opt={opt_batch}, max={max_batch}") |
| profile.set_shape( |
| input_name, |
| min=(min_batch, 3, image_size, image_size), |
| opt=(opt_batch, 3, image_size, image_size), |
| max=(max_batch, 3, image_size, image_size), |
| ) |
| config.add_optimization_profile(profile) |
|
|
| |
| logger.info("Building TensorRT engine (this may take a while)...") |
| serialized_engine = builder.build_serialized_network(network, config) |
|
|
| if serialized_engine is None: |
| raise RuntimeError("Failed to build TensorRT engine") |
|
|
| |
| with open(engine_path, 'wb') as f: |
| f.write(serialized_engine) |
|
|
| logger.info(f"TensorRT engine saved: {engine_path}") |
|
|
| return engine_path |
|
|
|
|
| class Int8EntropyCalibrator2: |
| """TensorRT INT8 熵校准器(使用 IInt8EntropyCalibrator2)""" |
|
|
| def __init__( |
| self, |
| dataloader: DataLoader, |
| cache_file: str, |
| input_shape: tuple, |
| ): |
| import tensorrt as trt |
|
|
| self.dataloader = dataloader |
| self.cache_file = cache_file |
| self.input_shape = input_shape |
| self.batch_iter = iter(dataloader) |
| self.device = torch.device("cuda") |
|
|
| |
| self.batch_size = dataloader.batch_size |
| self.d_input = torch.empty( |
| (self.batch_size,) + input_shape, |
| dtype=torch.float32, |
| device=self.device |
| ) |
|
|
| def get_batch_size(self): |
| return self.batch_size |
|
|
| def get_batch(self, names): |
| try: |
| batch = next(self.batch_iter) |
| if isinstance(batch, torch.Tensor): |
| batch = batch.to(self.device, dtype=torch.float32) |
| self.d_input.copy_(batch) |
| return [int(self.d_input.data_ptr())] |
| except StopIteration: |
| return None |
|
|
| def read_calibration_cache(self): |
| if os.path.exists(self.cache_file): |
| with open(self.cache_file, "rb") as f: |
| return f.read() |
| return None |
|
|
| def write_calibration_cache(self, cache): |
| with open(self.cache_file, "wb") as f: |
| f.write(cache) |
|
|
|
|
| |
| def convert_with_trtexec( |
| onnx_path: str, |
| engine_path: str, |
| precision: str = "int8", |
| calib_cache: Optional[str] = None, |
| workspace_size: int = 4096, |
| min_batch: int = 1, |
| opt_batch: int = 1, |
| max_batch: int = 8, |
| image_size: int = 560, |
| ): |
| """使用 trtexec 命令行工具进行转换""" |
| import subprocess |
|
|
| cmd = [ |
| "trtexec", |
| f"--onnx={onnx_path}", |
| f"--saveEngine={engine_path}", |
| f"--workspace={workspace_size}", |
| f"--minShapes=input:{min_batch}x3x{image_size}x{image_size}", |
| f"--optShapes=input:{opt_batch}x3x{image_size}x{image_size}", |
| f"--maxShapes=input:{max_batch}x3x{image_size}x{image_size}", |
| ] |
|
|
| if precision == "fp16": |
| cmd.append("--fp16") |
| elif precision == "int8": |
| cmd.append("--int8") |
| if calib_cache and os.path.exists(calib_cache): |
| cmd.append(f"--calib={calib_cache}") |
|
|
| cmd_str = " ".join(cmd) |
| logger.info(f"Running: {cmd_str}") |
|
|
| result = subprocess.run(cmd, capture_output=True, text=True) |
|
|
| if result.returncode != 0: |
| logger.error(f"trtexec failed:\n{result.stderr}") |
| raise RuntimeError("trtexec conversion failed") |
|
|
| logger.info(f"Engine saved: {engine_path}") |
|
|
|
|
| |
| def main(): |
| parser = argparse.ArgumentParser(description="TensorRT quantization for EVA-CLIP CSA") |
|
|
| |
| parser.add_argument("--model-name", type=str, default="EVA02-CLIP-B-16") |
| parser.add_argument("--cache-dir", type=str, |
| default="/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt", |
| 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", "qq", "kk", "vv", "all", "vanilla", "dummy_csa", "qq_xformer"]) |
| parser.add_argument("--image-size", type=int, default=560) |
|
|
| |
| parser.add_argument("--data-root", type=str, |
| default="/opt/tiger/xiaomoguhzz/standard_coco") |
| parser.add_argument("--calib-size", type=int, default=512, |
| help="Number of calibration samples") |
| parser.add_argument("--batch-size", type=int, default=8) |
|
|
| |
| parser.add_argument("--output-dir", type=str, default="./trt_engines") |
| parser.add_argument("--precision", type=str, default="int8", |
| choices=["fp32", "fp16", "fp8", "int8"]) |
|
|
| |
| parser.add_argument("--workspace", type=int, default=4, |
| help="Workspace size in GB") |
| parser.add_argument("--min-batch", type=int, default=1) |
| parser.add_argument("--opt-batch", type=int, default=1) |
| parser.add_argument("--max-batch", type=int, default=8) |
| parser.add_argument("--use-trtexec", action="store_true", |
| help="Use trtexec command instead of Python API") |
| parser.add_argument("--model-tag", type=str, default="", |
| help="Model tag for output naming (e.g., 'clip' or 'declip')") |
| parser.add_argument("--use-ptq", action="store_true", |
| help="Use pytorch-quantization for PTQ (recommended for FP8/INT8)") |
| parser.add_argument("--force-ptq", action="store_true", |
| help="Force PTQ mode for FP8/INT8 (auto-enabled if pytorch-quantization available)") |
|
|
| args = parser.parse_args() |
| |
| |
| use_modelopt_fp8 = False |
| if args.precision == "fp8": |
| if check_modelopt_available(): |
| logger.info("FP8 will use nvidia-modelopt quantization") |
| use_modelopt_fp8 = True |
| else: |
| logger.warning("nvidia-modelopt not available. FP8 will fall back to FP16.") |
| logger.warning("Install with: pip install nvidia-modelopt --extra-index-url https://pypi.nvidia.com") |
| elif args.precision == "int8" and not args.use_ptq: |
| if check_ptq_available(): |
| logger.info("Auto-enabling PTQ mode for INT8 quantization") |
| args.use_ptq = True |
| else: |
| logger.warning("PTQ not available for INT8. Will use TensorRT's built-in calibrator.") |
|
|
| |
| output_dir = Path(args.output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| logger.info(f"Using device: {device}") |
|
|
| |
| |
| |
| use_ptq = args.use_ptq and args.precision == "int8" |
| |
| if use_ptq: |
| if not initialize_ptq(args.precision): |
| logger.warning("Failed to initialize PTQ. Will use TensorRT's built-in INT8 calibrator.") |
| use_ptq = False |
| |
| |
| logger.info("Loading EVA-CLIP model...") |
|
|
| from open_clip.eva_clip import create_model |
|
|
| |
| |
| |
| |
| model = create_model( |
| args.model_name, |
| pretrained=args.cache_dir, |
| precision="fp32", |
| device=device, |
| force_custom_clip=True, |
| ) |
| model.eval() |
|
|
| |
| wrapped_model = EVAVisualCSAWrapper(model, mode=args.mode) |
| wrapped_model.eval() |
|
|
| logger.info(f"Model loaded, mode: {args.mode}") |
| if use_ptq: |
| logger.info(f"PTQ mode enabled for {args.precision.upper()}") |
|
|
| |
| calib_dataloader = None |
| calib_cache = output_dir / f"{args.model_tag + '_' if args.model_tag else ''}calibration_{args.precision}.cache" |
| name_prefix = f"{args.model_tag}_" if args.model_tag else "" |
|
|
| if use_modelopt_fp8 or use_ptq or args.precision == "int8": |
| logger.info("Preparing calibration dataset...") |
|
|
| calib_dataset = COCOCalibrationDataset( |
| image_root=f"{args.data_root}/val2017", |
| annotation_file=f"{args.data_root}/annotations/panoptic_val2017.json", |
| image_size=args.image_size, |
| max_samples=args.calib_size, |
| ) |
|
|
| calib_dataloader = DataLoader( |
| calib_dataset, |
| batch_size=args.batch_size, |
| shuffle=False, |
| num_workers=4, |
| pin_memory=True, |
| ) |
|
|
| |
| if use_modelopt_fp8: |
| |
| logger.info("Running FP8 quantization with nvidia-modelopt...") |
| wrapped_model = quantize_model_fp8(wrapped_model, calib_dataloader, device) |
| elif use_ptq: |
| logger.info(f"Running PTQ calibration for {args.precision.upper()}...") |
| calibrate_model(wrapped_model, calib_dataloader, device) |
| elif args.precision == "int8": |
| |
| logger.info("Running calibration data through model...") |
| with torch.no_grad(): |
| for batch in tqdm(calib_dataloader, desc="Calibration"): |
| batch = batch.to(device) |
| _ = wrapped_model(batch) |
|
|
| |
| |
| bs_suffix = f"_bs{args.opt_batch}" if args.opt_batch != 1 else "" |
| onnx_path = output_dir / f"{name_prefix}eva_clip_b16_{args.mode}_{args.image_size}{bs_suffix}.onnx" |
| |
| if use_modelopt_fp8: |
| |
| onnx_path = output_dir / f"{name_prefix}eva_clip_b16_{args.mode}_{args.image_size}{bs_suffix}_fp8_modelopt.onnx" |
| export_onnx_fp8( |
| wrapped_model, |
| str(onnx_path), |
| image_size=args.image_size, |
| batch_size=args.opt_batch, |
| ) |
| elif use_ptq: |
| |
| onnx_path = output_dir / f"{name_prefix}eva_clip_b16_{args.mode}_{args.image_size}{bs_suffix}_{args.precision}_ptq.onnx" |
| export_onnx_with_ptq( |
| wrapped_model, |
| str(onnx_path), |
| image_size=args.image_size, |
| batch_size=args.opt_batch, |
| dynamic_batch=True, |
| ) |
| else: |
| |
| export_onnx( |
| wrapped_model, |
| str(onnx_path), |
| image_size=args.image_size, |
| batch_size=args.opt_batch, |
| dynamic_batch=False, |
| ) |
|
|
| |
| if use_ptq: |
| deactivate_ptq() |
|
|
| |
| engine_path = output_dir / f"{name_prefix}eva_clip_b16_{args.mode}_{args.image_size}_{args.precision}{bs_suffix}.trt" |
|
|
| if args.use_trtexec: |
| convert_with_trtexec( |
| str(onnx_path), |
| str(engine_path), |
| precision=args.precision, |
| calib_cache=str(calib_cache) if calib_cache.exists() else None, |
| workspace_size=args.workspace * 1024, |
| min_batch=args.min_batch, |
| opt_batch=args.opt_batch, |
| max_batch=args.max_batch, |
| image_size=args.image_size, |
| ) |
| else: |
| |
| |
| trt_calib_dataloader = None if use_ptq else calib_dataloader |
|
|
| |
| build_trt_engine( |
| str(onnx_path), |
| str(engine_path), |
| precision=args.precision, |
| calib_dataloader=trt_calib_dataloader, |
| calib_cache=str(calib_cache), |
| workspace_size=args.workspace, |
| min_batch=args.min_batch, |
| opt_batch=args.opt_batch, |
| max_batch=args.max_batch, |
| image_size=args.image_size, |
| use_fixed_batch=True, |
| ) |
|
|
| logger.info("=" * 50) |
| logger.info("Quantization completed!") |
| logger.info(f"ONNX model: {onnx_path}") |
| logger.info(f"TRT engine: {engine_path}") |
| logger.info("=" * 50) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|