DeCLIP-TPAMI / code /detection_trt /configs /custom_modules.py
xiaomoguhzz's picture
Upload code/detection_trt/configs/custom_modules.py with huggingface_hub
822454a verified
"""
自定义模块注册 - 用于 MMDeploy ONNX 导出
处理 EVA-CLIP ViT 的特殊操作:
1. 禁用 xformers (不支持 ONNX)
2. 处理 RoPE 位置编码的动态形状
3. 不同 feature_mode (vanilla/csa) 的处理
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple, List, Optional
def register_custom_rewriters():
"""注册自定义重写器到 MMDeploy"""
try:
from mmdeploy.core import FUNCTION_REWRITER, MODULE_REWRITER
except ImportError:
print("Warning: MMDeploy not installed. Skipping rewriter registration.")
return
# ============================================================
# EVAVisionTransformer 相关重写器
# ============================================================
@FUNCTION_REWRITER.register_rewriter(
func_name='src.open_clip.eva_clip.eva_vit_model.Attention.forward',
backend='tensorrt'
)
def attention__forward__tensorrt(self, x, rel_pos_bias=None, attn_mask=None):
"""
重写 Attention.forward 以禁用 xformers,使用标准 attention
"""
B, N, C = x.shape
if self.subln:
q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
else:
qkv_bias = None
if self.q_bias is not None:
qkv_bias = torch.cat((
self.q_bias,
torch.zeros_like(self.v_bias, requires_grad=False),
self.v_bias
))
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
# RoPE 位置编码 (如果启用)
if self.rope is not None:
q_t = q[:, :, 1:, :]
ro_q_t = self.rope(q_t)
q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
k_t = k[:, :, 1:, :]
ro_k_t = self.rope(k_t)
k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
# 强制使用标准 attention (不使用 xformers)
q = q * self.scale
attn = (q @ k.transpose(-2, -1))
if self.relative_position_bias_table is not None:
relative_position_bias = \
self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
self.window_size[0] * self.window_size[1] + 1,
self.window_size[0] * self.window_size[1] + 1, -1)
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
attn = attn + relative_position_bias.unsqueeze(0).type_as(attn)
if rel_pos_bias is not None:
attn = attn + rel_pos_bias.type_as(attn)
if attn_mask is not None:
attn_mask = attn_mask.bool()
attn = attn.masked_fill(~attn_mask[:, None, None, :], float("-inf"))
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
x = self.inner_attn_ln(x)
x = self.proj(x)
x = self.proj_drop(x)
return x
@FUNCTION_REWRITER.register_rewriter(
func_name='src.open_clip.eva_clip.eva_vit_model.Attention.ss_attn',
backend='tensorrt'
)
def attention__ss_attn__tensorrt(self, x, mode, attn_mask=None):
"""
重写 ss_attn (self-supervised attention) 用于 DeCLIP 的 csa 模式
"""
B, N, C = x.shape
if self.subln:
q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
else:
qkv_bias = None
if self.q_bias is not None:
qkv_bias = torch.cat((
self.q_bias,
torch.zeros_like(self.v_bias, requires_grad=False),
self.v_bias
))
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
# RoPE 位置编码
if self.rope is not None:
q_t = q[:, :, 1:, :]
ro_q_t = self.rope(q_t)
q = torch.cat((q[:, :, :1, :], ro_q_t), -2).type_as(v)
k_t = k[:, :, 1:, :]
ro_k_t = self.rope(k_t)
k = torch.cat((k[:, :, :1, :], ro_k_t), -2).type_as(v)
q = q.contiguous().view(B * self.num_heads, N, -1)
k = k.contiguous().view(B * self.num_heads, N, -1)
v = v.contiguous().view(B * self.num_heads, N, -1)
# CSA (Combined Self-Attention) 模式
if 'csa' in mode:
q_attn = torch.bmm(q, q.transpose(1, 2))
k_attn = torch.bmm(k, k.transpose(1, 2))
attn_weights = F.softmax(q_attn, dim=-1) + F.softmax(k_attn, dim=-1)
elif 'qq' in mode:
q_attn = torch.bmm(q, q.transpose(1, 2))
attn_weights = F.softmax(q_attn, dim=-1)
elif 'kk' in mode:
k_attn = torch.bmm(k, k.transpose(1, 2))
attn_weights = F.softmax(k_attn, dim=-1)
elif 'vv' in mode:
v_attn = torch.bmm(v, v.transpose(1, 2))
attn_weights = F.softmax(v_attn, dim=-1)
else: # vanilla
q_scaled = q * (q.shape[-1] ** -0.5)
attn_weights = F.softmax(torch.bmm(q_scaled, k.transpose(1, 2)), dim=-1)
attn_output = torch.bmm(attn_weights, v)
attn_output = attn_output.transpose(0, 1).contiguous().view(N, B, C).transpose(0, 1)
attn_output = self.inner_attn_ln(attn_output)
attn_output = self.proj(attn_output)
attn_output = self.proj_drop(attn_output)
return attn_output
@FUNCTION_REWRITER.register_rewriter(
func_name='src.open_clip.eva_clip.eva_vit_model.EVAVisionTransformer.encode_dense',
backend='tensorrt'
)
def eva_vit__encode_dense__tensorrt(
self, x, keep_shape=True, mode="csa", get_intermediate_layer=None
):
"""
重写 encode_dense 用于 ONNX 导出
简化逻辑,移除不兼容 ONNX 的操作
"""
if get_intermediate_layer is None:
get_intermediate_layer = []
get_intermediate_layer = set(get_intermediate_layer)
bs, _, h, w = x.shape
h = h // self.patch_embed.patch_size[0]
w = w // self.patch_embed.patch_size[1]
x = self.patch_embed(x)
batch_size, seq_len, _ = x.size()
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
x = torch.cat((cls_tokens, x), dim=1)
if self.pos_embed is not None:
x = x + self.rescale_positional_embedding(out_size=(h, w))
x = self.pos_drop(x)
# 跳过 patch_dropout (推理时不需要)
rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
for blk in self.blocks[:-1]:
x = blk(x, rel_pos_bias=rel_pos_bias)
# 最后一个 block 根据 mode 处理
if mode == "vanilla":
x = self.blocks[-1](x, rel_pos_bias=rel_pos_bias)
else:
x = self.blocks[-1].forward_without_rcffn(x, mode)
x = x[:, 1:] # 移除 CLS token
x = self.norm(x)
x = self.head(x)
if keep_shape:
x = x.view(bs, h, w, -1).permute(0, 3, 1, 2)
return x
print("Custom rewriters registered successfully.")
class EVACLIPWrapper(nn.Module):
"""
EVA-CLIP 模型包装器,用于 ONNX 导出
将复杂的模型接口简化为单一的 forward 方法
"""
def __init__(self, model, mode='csa'):
"""
Args:
model: EVA-CLIP 模型实例
mode: 特征提取模式 ('vanilla' 或 'csa')
"""
super().__init__()
self.model = model
self.mode = mode
self.visual = model.visual if hasattr(model, 'visual') else model
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
简化的 forward 方法
Args:
x: 输入图像 [B, C, H, W]
Returns:
dense_features: 密集特征图 [B, D, H', W']
"""
return self.visual.encode_dense(x, keep_shape=True, mode=self.mode)
def extract_roi_features(
self,
x: torch.Tensor,
boxes: List[torch.Tensor]
) -> torch.Tensor:
"""
提取 RoI 特征
Args:
x: 输入图像 [B, C, H, W]
boxes: 归一化边界框列表,每个元素 [N, 4]
Returns:
roi_features: RoI 特征 [total_boxes, D]
"""
return self.visual.extract_roi_features(
x, boxes, mode=self.mode
)
class TRTInferenceWrapper:
"""
TensorRT 推理包装器
处理 TRT Engine 的加载和推理
"""
def __init__(self, engine_path: str, device: str = 'cuda:0'):
"""
Args:
engine_path: TRT 引擎文件路径
device: 设备
"""
self.engine_path = engine_path
self.device = torch.device(device)
self.engine = None
self.context = None
def load(self):
"""加载 TRT 引擎"""
try:
import tensorrt as trt
logger = trt.Logger(trt.Logger.WARNING)
runtime = trt.Runtime(logger)
with open(self.engine_path, 'rb') as f:
engine_data = f.read()
self.engine = runtime.deserialize_cuda_engine(engine_data)
self.context = self.engine.create_execution_context()
print(f"Loaded TRT engine from {self.engine_path}")
except ImportError:
raise ImportError("TensorRT is not installed")
def __call__(self, input_tensor: torch.Tensor) -> torch.Tensor:
"""
运行推理
Args:
input_tensor: 输入张量 [B, C, H, W]
Returns:
output_tensor: 输出特征
"""
if self.engine is None:
self.load()
# 实际推理逻辑需要根据具体引擎绑定实现
# 这里只是一个框架
raise NotImplementedError("TRT inference not fully implemented")
def disable_xformers_for_export(model):
"""
禁用模型中的 xformers 以支持 ONNX 导出
Args:
model: EVA-CLIP 模型
"""
def _disable_xattn(module):
if hasattr(module, 'xattn'):
module.xattn = False
model.apply(_disable_xattn)
print("Disabled xformers for ONNX export")
return model
def prepare_model_for_export(model, mode='csa'):
"""
准备模型用于 ONNX 导出
Args:
model: 原始模型
mode: 特征模式
Returns:
wrapped_model: 包装后的模型
"""
# 禁用 xformers
model = disable_xformers_for_export(model)
# 设置为评估模式
model.eval()
# 包装模型
wrapped = EVACLIPWrapper(model, mode=mode)
return wrapped
if __name__ == '__main__':
# 测试注册
register_custom_rewriters()