Transformers 文档
ViTDet
并获得增强的文档体验
开始使用
该模型于 2022-03-30 发布在 HF papers 上,并于 2023-08-29 贡献给 Hugging Face Transformers。
ViTDet
概述
ViTDet 模型由 Yanghao Li, Hanzi Mao, Ross Girshick, Kaiming He 在 Exploring Plain Vision Transformer Backbones for Object Detection 中提出。VitDet 利用简单的 Vision Transformer 来执行目标检测任务。
论文摘要如下:
我们探索了将简单的、非分层的 Vision Transformer (ViT) 作为目标检测的主干网络。这种设计使得原始 ViT 架构无需为预训练重新设计分层主干,即可微调用于目标检测。通过极少的微调适配,我们的纯主干检测器可以达到具有竞争力的结果。令人惊讶的是,我们观察到:(i) 从单尺度特征图构建简单的特征金字塔(无需常见的 FPN 设计)就已足够;(ii) 使用窗口注意力(无需移动)辅以极少的跨窗口传播块就已足够。借助以掩码自动编码器 (MAE) 预训练的纯 ViT 主干,我们的检测器(名为 ViTDet)可以与之前所有基于分层主干的领先方法相媲美,仅使用 ImageNet-1K 预训练,在 COCO 数据集上达到了 61.3 AP_box。我们希望我们的研究能引起人们对纯主干检测器研究的关注。
技巧
- 目前仅提供了主干网络。
VitDetConfig
class transformers.VitDetConfig
< 源代码 >( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None hidden_size: int = 768 num_hidden_layers: int = 12 num_attention_heads: int = 12 mlp_ratio: int = 4 hidden_act: str = 'gelu' dropout_prob: float | int = 0.0 initializer_range: float = 0.02 layer_norm_eps: float = 1e-06 image_size: int | list[int] | tuple[int, int] = 224 pretrain_image_size: int | list[int] | tuple[int, int] = 224 patch_size: int | list[int] | tuple[int, int] = 16 num_channels: int = 3 qkv_bias: bool = True drop_path_rate: float | int = 0.0 window_block_indices: list[int] | tuple[int, ...] = () residual_block_indices: list[int] | tuple[int, ...] = () use_absolute_position_embeddings: bool = True use_relative_position_embeddings: bool = False window_size: int = 0 _out_features: list[str] | None = None _out_indices: list[int] | None = None )
参数
- hidden_size (
int, 可选, 默认为768) — 隐藏层表示的维度。 - num_hidden_layers (
int, 可选, 默认为12) — Transformer 解码器中的隐藏层数。 - num_attention_heads (
int, 可选, 默认为12) — Transformer 解码器中每个注意力层的注意力头数。 - mlp_ratio (
int, 可选, 默认为4) — MLP 隐藏维度与嵌入维度的比率。 - hidden_act (
str, 可选, 默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu","relu","silu"等。 - dropout_prob (
Union[float, int], 可选, 默认为0.0) — 所有 dropout 层的比率。 - initializer_range (
float, 可选, 默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float, 可选, 默认为1e-06) — 层归一化层使用的 epsilon 值。 - image_size (
Union[int, list[int], tuple[int, int]], 可选, 默认为224) — 每张图像的大小(分辨率)。 - pretrain_image_size (
int, 可选, 默认为 224) — 预训练期间每张图像的大小(分辨率)。 - patch_size (
Union[int, list[int], tuple[int, int]], 可选, 默认为16) — 每个补丁(patch)的大小(分辨率)。 - num_channels (
int, 可选, 默认为3) — 输入通道的数量。 - qkv_bias (
bool, 可选, 默认为True) — 是否为查询、键和值添加偏置。 - drop_path_rate (
Union[float, int], 可选, 默认为0.0) — 补丁融合(patch fusion)的 drop path 比率。 - window_block_indices (
list[int], 可选, 默认为[]) — 应该使用窗口注意力而不是常规全局自注意力的块索引列表。 - residual_block_indices (
list[int], 可选, 默认为[]) — 应该在 MLP 之后包含额外残差块的块索引列表。 - use_absolute_position_embeddings (
bool, 可选, 默认为True) — 是否使用绝对位置嵌入。 - use_relative_position_embeddings (
bool, 可选, 默认为False) — 是否将相对位置嵌入添加到注意力图中。 - window_size (
int, 可选, 默认为 0) — 注意力窗口的大小。
这是用于存储 VitDetModel 配置的配置类。它根据指定的参数实例化 VitDet 模型,定义模型架构。使用默认值实例化配置将产生与 google/vitdet-base-patch16-224 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。
示例
>>> from transformers import VitDetConfig, VitDetModel
>>> # Initializing a VitDet configuration
>>> configuration = VitDetConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = VitDetModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configVitDetModel
class transformers.VitDetModel
< 源代码 >( config: VitDetConfig )
参数
- config (VitDetConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法以加载模型权重。
裸的 VitDet 模型,输出原始隐藏状态,顶部没有任何特定的头部(head)。
该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< 源码 >( pixel_values: torch.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) → BaseModelOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 对应于输入图像的张量。像素值可以使用image_processor_class获取。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - output_attentions (
bool,可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool,可选) — 是否返回一个 ModelOutput 而不是普通元组。
返回
BaseModelOutput 或 tuple(torch.FloatTensor)
一个 BaseModelOutput 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(VitDetConfig)和输入而定的各种元素。
VitDetModel 的 forward 方法,覆盖了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
last_hidden_state (
torch.FloatTensor, 形状为(batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。hidden_states (
tuple(torch.FloatTensor), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
示例
>>> from transformers import VitDetConfig, VitDetModel
>>> import torch
>>> config = VitDetConfig()
>>> model = VitDetModel(config)
>>> pixel_values = torch.randn(1, 3, 224, 224)
>>> with torch.no_grad():
... outputs = model(pixel_values)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 768, 14, 14]