FantasticGNU/UniVAD项目中的Vision Transformer模型解析
2025-07-08 01:44:42作者:胡唯隽
概述
本文将深入解析FantasticGNU/UniVAD项目中使用的Vision Transformer(ViT)模型实现。ViT是一种将自然语言处理中成功的Transformer架构应用于计算机视觉任务的创新方法,它完全摒弃了传统CNN结构,直接处理图像块(patch)序列。
核心组件解析
1. DropPath机制
DropPath是一种正则化技术,也称为Stochastic Depth(随机深度)。它在训练过程中随机"丢弃"整个网络层,迫使网络学习更鲁棒的特征表示。
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
return drop_path(x, self.drop_prob, self.training)
2. 多层感知机(MLP)模块
MLP模块是Transformer中的标准组件,包含两个全连接层和GELU激活函数:
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
3. 自注意力机制(Attention)
自注意力机制是Transformer的核心,它允许模型关注输入序列的不同部分:
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
...
4. Transformer块(Block)
每个Transformer块包含自注意力层和前馈网络(MLP),并应用了残差连接和层归一化:
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, ...)
self.drop_path = DropPath(drop_path)
self.norm2 = norm_layer(dim)
self.mlp = Mlp(...)
图像到序列的转换
Vision Transformer需要将2D图像转换为1D序列,这是通过PatchEmbed模块实现的:
class PatchEmbed(nn.Module):
""" Image to Patch Embedding """
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
super().__init__()
num_patches = (img_size // patch_size) * (img_size // patch_size)
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
完整的Vision Transformer架构
VisionTransformer类整合了所有组件,构建完整的模型:
class VisionTransformer(nn.Module):
def __init__(self, img_size=[224], patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12,
num_heads=12, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
drop_path_rate=0., norm_layer=nn.LayerNorm, **kwargs):
super().__init__()
self.patch_embed = PatchEmbed(...)
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.pos_embed = nn.Parameter(...)
self.blocks = nn.ModuleList([Block(...) for _ in range(depth)])
self.norm = norm_layer(embed_dim)
模型变体
项目提供了三种不同规模的ViT模型变体:
- ViT-Tiny: 小型模型,适用于资源受限环境
- ViT-Small: 中等规模模型,平衡性能和计算成本
- ViT-Base: 基础规模模型,提供更好的性能
def vit_tiny(patch_size=16, **kwargs):
return VisionTransformer(patch_size=patch_size, embed_dim=192, depth=12, num_heads=3, ...)
def vit_small(patch_size=16, **kwargs):
return VisionTransformer(patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, ...)
def vit_base(patch_size=16, **kwargs):
return VisionTransformer(patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, ...)
DINO头部结构
DINOHead是一个特殊的投影头,用于自监督学习任务:
class DINOHead(nn.Module):
def __init__(self, in_dim, out_dim, use_bn=False, norm_last_layer=True, nlayers=3, hidden_dim=2048, bottleneck_dim=256):
super().__init__()
# 构建多层MLP
self.last_layer = nn.utils.weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))
技术亮点
- 位置编码插值: 允许模型处理不同分辨率的输入图像
- 随机深度衰减: 随着网络深度增加,DropPath的概率线性增加
- 层归一化: 在每个残差块前后应用层归一化
- 多头注意力: 并行计算多个注意力头,捕获不同特征
应用场景
在FantasticGNU/UniVAD项目中,这个Vision Transformer实现可能用于:
- 视频异常检测的特征提取
- 时空信息的建模
- 跨模态学习
- 自监督预训练
总结
本文详细解析了FantasticGNU/UniVAD项目中使用的Vision Transformer实现。通过模块化设计,该实现提供了灵活的配置选项,可以适应不同规模和需求的视觉任务。特别值得注意的是其对自监督学习的支持,通过DINOHead等组件实现了高效的特征学习。
登录后查看全文
热门项目推荐
ERNIE-4.5-VL-28B-A3B-ThinkingERNIE-4.5-VL-28B-A3B-Thinking 是 ERNIE-4.5-VL-28B-A3B 架构的重大升级,通过中期大规模视觉-语言推理数据训练,显著提升了模型的表征能力和模态对齐,实现了多模态推理能力的突破性飞跃Python00
unified-cache-managementUnified Cache Manager(推理记忆数据管理器),是一款以KV Cache为中心的推理加速套件,其融合了多类型缓存加速算法工具,分级管理并持久化推理过程中产生的KV Cache记忆数据,扩大推理上下文窗口,以实现高吞吐、低时延的推理体验,降低每Token推理成本。Python03
Kimi-K2-ThinkingKimi K2 Thinking 是最新、性能最强的开源思维模型。从 Kimi K2 开始,我们将其打造为能够逐步推理并动态调用工具的思维智能体。通过显著提升多步推理深度,并在 200–300 次连续调用中保持稳定的工具使用能力,它在 Humanity's Last Exam (HLE)、BrowseComp 等基准测试中树立了新的技术标杆。同时,K2 Thinking 是原生 INT4 量化模型,具备 256k 上下文窗口,实现了推理延迟和 GPU 内存占用的无损降低。Python00
Spark-Prover-X1-7BSpark-Prover-X1-7B is a 7B-parameter large language model developed by iFLYTEK for automated theorem proving in Lean4. It generates complete formal proofs for mathematical theorems using a three-stage training framework combining pre-training, supervised fine-tuning, and reinforcement learning. The model achieves strong formal reasoning performance and state-of-the-art results across multiple theorem-proving benchmarksPython00
MiniCPM-V-4_5MiniCPM-V 4.5 是 MiniCPM-V 系列中最新且功能最强的模型。该模型基于 Qwen3-8B 和 SigLIP2-400M 构建,总参数量为 80 亿。与之前的 MiniCPM-V 和 MiniCPM-o 模型相比,它在性能上有显著提升,并引入了新的实用功能Python00
Spark-Formalizer-X1-7BSpark-Formalizer-X1-7B is a 7B-parameter large language model by iFLYTEK for mathematical auto-formalization. It translates natural-language math problems into precise Lean4 formal statements, achieving high accuracy and logical consistency. The model is trained with a two-stage strategy combining large-scale pre-training and supervised fine-tuning for robust formal reasoning.Python00
GOT-OCR-2.0-hf阶跃星辰StepFun推出的GOT-OCR-2.0-hf是一款强大的多语言OCR开源模型,支持从普通文档到复杂场景的文字识别。它能精准处理表格、图表、数学公式、几何图形甚至乐谱等特殊内容,输出结果可通过第三方工具渲染成多种格式。模型支持1024×1024高分辨率输入,具备多页批量处理、动态分块识别和交互式区域选择等创新功能,用户可通过坐标或颜色指定识别区域。基于Apache 2.0协议开源,提供Hugging Face演示和完整代码,适用于学术研究到工业应用的广泛场景,为OCR领域带来突破性解决方案。00- HHowToCook程序员在家做饭方法指南。Programmer's guide about how to cook at home (Chinese only).Dockerfile015
Spark-Scilit-X1-13B科大讯飞Spark Scilit-X1-13B基于最新一代科大讯飞基础模型,并针对源自科学文献的多项核心任务进行了训练。作为一款专为学术研究场景打造的大型语言模型,它在论文辅助阅读、学术翻译、英语润色和评论生成等方面均表现出色,旨在为研究人员、教师和学生提供高效、精准的智能辅助。Python00- PpathwayPathway is an open framework for high-throughput and low-latency real-time data processing.Python00
项目优选
收起
deepin linux kernel
C
24
7
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
308
2.71 K
仓颉编译器源码及 cjdb 调试工具。
C++
123
803
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
9
1
暂无简介
Dart
598
132
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
1.03 K
461
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.07 K
616
Ascend Extension for PyTorch
Python
141
170
仓颉编程语言命令行工具,包括仓颉包管理工具、仓颉格式化工具、仓颉多语言桥接工具及仓颉语言服务。
C++
55
780
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
634
232