Transformers 文档

Swin Transformer V2

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2021 年 11 月 18 日在 HF papers 上发布,并于 2022 年 7 月 27 日贡献给 Hugging Face Transformers。

Swin Transformer V2

Swin Transformer V2 是一个拥有 30 亿参数的模型,专注于如何将视觉模型扩展到数十亿参数规模。它引入了诸如残差后归一化(residual-post-norm)结合余弦注意力机制(cosine attention)来提高训练稳定性,对数间距连续位置偏置(log-spaced continuous position bias)来更好地处理预训练和微调之间图像分辨率的变化,以及一种新的预训练方法(SimMIM)以减少对大量标记数据的需求。这些改进使得高效训练能够处理高分辨率图像的超大规模模型(高达 30 亿参数)成为可能。

你可以在 Microsoft 组织下找到官方的 Swin Transformer V2 检查点(checkpoints)。

点击右侧侧边栏中的 Swin Transformer V2 模型,查看更多关于如何将 Swin Transformer V2 应用于视觉任务的示例。

流水线
自动模型
from transformers import pipeline


pipeline = pipeline(
    task="image-classification",
    model="microsoft/swinv2-tiny-patch4-window8-256",
    device=0
)
pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")

注意事项

  • Swin Transformer V2 可以对任何高度和宽度均能被 32 整除的输入进行填充(pad)。
  • Swin Transformer V2 可以用作 骨干网络(backbone)。当 output_hidden_states = True 时,它会同时输出 hidden_statesreshaped_hidden_statesreshaped_hidden_states 的形状为 (batch, num_channels, height, width),而不是 (batch_size, sequence_length, num_channels)

Swinv2Config

class transformers.Swinv2Config

< >

( 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 image_size: int | list[int] | tuple[int, int] = 224 patch_size: int | list[int] | tuple[int, int] = 4 num_channels: int = 3 embed_dim: int = 96 depths: list[int] | tuple[int, ...] = (2, 2, 6, 2) num_heads: list[int] | tuple[int, ...] = (3, 6, 12, 24) window_size: int = 7 pretrained_window_sizes: list[int] | tuple[int, ...] = (0, 0, 0, 0) mlp_ratio: float = 4.0 qkv_bias: bool = True hidden_dropout_prob: float | int = 0.0 attention_probs_dropout_prob: float | int = 0.0 drop_path_rate: float | int = 0.1 hidden_act: str = 'gelu' use_absolute_embeddings: bool = False initializer_range: float = 0.02 layer_norm_eps: float = 1e-05 encoder_stride: int = 32 _out_features: list[str] | None = None _out_indices: list[int] | None = None )

参数

  • image_size (Union[int, list[int], tuple[int, int]], 可选, 默认为 224) — 每张图像的大小(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]], 可选, 默认为 4) — 每个补丁(patch)的大小(分辨率)。
  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • embed_dim (int, 可选, 默认为 96) — 嵌入和隐藏状态的维度。
  • depths (Union[list[int], tuple[int, ...]], 可选, 默认为 (2, 2, 6, 2)) — Transformer 中每一层的深度。
  • num_heads (Union[list[int], tuple[int, ...]], 可选, 默认为 (3, 6, 12, 24)) — Transformer 解码器中每个注意力层的注意力头数。
  • window_size (int, 可选, 默认为 7) — 窗口的大小。
  • pretrained_window_sizes (list(int), 可选, 默认为 [0, 0, 0, 0]) — 预训练期间窗口的大小。
  • mlp_ratio (float, 可选, 默认为 4.0) — MLP 隐藏维度与嵌入维度的比率。
  • qkv_bias (bool, 可选, 默认为 True) — 是否为查询(queries)、键(keys)和值(values)添加偏置。
  • hidden_dropout_prob (Union[float, int], 可选, 默认为 0.0) — 嵌入、编码器和池化层中所有全连接层的丢弃率(dropout probability)。
  • attention_probs_dropout_prob (Union[float, int], 可选, 默认为 0.0) — 注意力概率的丢弃率。
  • drop_path_rate (Union[float, int], 可选, 默认为 0.1) — 补丁融合(patch fusion)的随机深度率(drop path rate)。
  • hidden_act (str, 可选, 默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如:"gelu""relu""silu" 等。
  • use_absolute_embeddings (bool, 可选, 默认为 False) — 是否使用绝对位置嵌入。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器(truncated_normal_initializer)的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-05) — 层归一化层使用的 epsilon 值。
  • encoder_stride (int, 可选, 默认为 32) — 用于掩码图像建模(masked image modeling)的解码器头中增加空间分辨率的因子。

这是用于存储 Swinv2Model 配置的配置类。它根据指定的参数实例化一个 Swinv2 模型,定义模型架构。使用默认值实例化配置将产生与 microsoft/swinv2-tiny-patch4-window8-256 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。

示例

>>> from transformers import Swinv2Config, Swinv2Model

>>> # Initializing a Swinv2 microsoft/swinv2-tiny-patch4-window8-256 style configuration
>>> configuration = Swinv2Config()

>>> # Initializing a model (with random weights) from the microsoft/swinv2-tiny-patch4-window8-256 style configuration
>>> model = Swinv2Model(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

Swinv2Model

class transformers.Swinv2Model

< >

( config add_pooling_layer = True use_mask_token = False )

参数

  • config (Swinv2Model) — 包含模型所有参数的模型配置类。使用配置文件初始化模型不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法来加载模型权重。
  • add_pooling_layer (bool, 可选, 默认为 True) — 是否应用池化层。
  • use_mask_token (bool, 可选, 默认为 False) — 是否在嵌入层中创建并应用掩码令牌(mask tokens)。

原始的 Swinv2 模型,输出原始隐藏状态,顶部没有任何特定的预测头。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.FloatTensor | None = None bool_masked_pos: torch.BoolTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None interpolate_pos_encoding: bool = False return_dict: bool | None = None **kwargs ) Swinv2ModelOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)可选) — 对应于输入图像的张量。像素值可以使用 ViTImageProcessor 获取。详情请参阅 ViTImageProcessor.__call__()processor_class 使用 ViTImageProcessor 来处理图像)。
  • bool_masked_pos (torch.BoolTensor,形状为 (batch_size, num_patches)可选) — 布尔掩码位置。指示哪些分块(patch)被掩盖(1),哪些未被掩盖(0)。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量中的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states
  • interpolate_pos_encoding (bool可选,默认为 False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool可选) — 是否返回一个 ModelOutput 而不是普通的元组。

返回

Swinv2ModelOutputtuple(torch.FloatTensor)

一个 Swinv2ModelOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置(Swinv2Config)和输入包含各种元素。

Swinv2Model 的前向传播方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • last_hidden_state (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可选,默认为 None) — 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.FloatTensor,形状为 (batch_size, hidden_size)可选,当传递 add_pooling_layer=True 时返回) — 最后一层隐藏状态的平均池化。

  • hidden_states (tuple[torch.FloatTensor, ...]可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则第一个为嵌入输出,其余为每一层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor, ...]可选,当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

  • reshaped_hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入输出 + 每个阶段输出一个),形状为 (batch_size, hidden_size, height, width)

    模型在每层输出处的隐藏状态,以及重新调整以包含空间维度的初始嵌入输出。

示例

Swinv2ForMaskedImageModeling

class transformers.Swinv2ForMaskedImageModeling

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

  • config (Swinv2ForMaskedImageModeling) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。

Swinv2 模型,顶部带有用于掩码图像建模的解码器,如 SimMIM 中所提出。

请注意,我们在 examples directory 中提供了一个脚本,用于在自定义数据上预训练此模型。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.FloatTensor | None = None bool_masked_pos: torch.BoolTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None interpolate_pos_encoding: bool = False return_dict: bool | None = None **kwargs ) Swinv2MaskedImageModelingOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)可选) — 对应于输入图像的张量。像素值可以使用 ViTImageProcessor 获取。详情请参阅 ViTImageProcessor.__call__()processor_class 使用 ViTImageProcessor 来处理图像)。
  • bool_masked_pos (torch.BoolTensor,形状为 (batch_size, num_patches)) — 布尔掩码位置。指示哪些分块(patch)被掩盖(1),哪些未被掩盖(0)。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量中的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states
  • interpolate_pos_encoding (bool可选,默认为 False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool可选) — 是否返回一个 ModelOutput 而不是普通的元组。

返回

Swinv2MaskedImageModelingOutputtuple(torch.FloatTensor)

一个 Swinv2MaskedImageModelingOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置(Swinv2Config)和输入包含各种元素。

Swinv2ForMaskedImageModeling 的前向传播方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • loss (torch.FloatTensor,形状为 (1,)可选,当提供 bool_masked_pos 时返回) — 掩码图像建模 (MLM) 损失。

  • reconstruction (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 重构的像素值。

  • hidden_states (tuple[torch.FloatTensor, ...]可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则第一个为嵌入输出,其余为每一层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor, ...]可选,当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

  • reshaped_hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入输出 + 每个阶段输出一个),形状为 (batch_size, hidden_size, height, width)

    模型在每层输出处的隐藏状态,以及重新调整以包含空间维度的初始嵌入输出。

示例

>>> from transformers import AutoImageProcessor, Swinv2ForMaskedImageModeling
>>> import torch
>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
>>> model = Swinv2ForMaskedImageModeling.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")

>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()

>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
>>> list(reconstructed_pixel_values.shape)
[1, 3, 256, 256]

Swinv2ForImageClassification

class transformers.Swinv2ForImageClassification

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

  • config (Swinv2ForImageClassification) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。

Swinv2 模型变换器,顶部带有图像分类头(在 [CLS] 标记的最终隐藏状态之上的线性层),例如用于 ImageNet。

请注意,通过在模型的前向传播中将 interpolate_pos_encoding 设置为 True,可以在比训练时分辨率更高的图像上微调 SwinV2。这将把预训练的位置嵌入插值到更高的分辨率。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.FloatTensor | None = None labels: torch.LongTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None interpolate_pos_encoding: bool = False return_dict: bool | None = None **kwargs ) Swinv2ImageClassifierOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)可选) — 对应于输入图像的张量。像素值可以使用 ViTImageProcessor 获取。详情请参阅 ViTImageProcessor.__call__()processor_class 使用 ViTImageProcessor 来处理图像)。
  • labels (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方误差损失);如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量中的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states
  • interpolate_pos_encoding (bool可选,默认值为 False) — 是否插值预训练的位置编码。
  • return_dict (bool可选) — 是否返回一个 ModelOutput 对象,而不是普通的元组。

返回

Swinv2ImageClassifierOutputtuple(torch.FloatTensor)

一个 Swinv2ImageClassifierOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置 (Swinv2Config) 和输入包含不同的元素。

Swinv2ForImageClassification 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。

  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。

  • hidden_states (tuple[torch.FloatTensor, ...]可选,当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则第一个为嵌入输出,其余为每一层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor, ...]可选,当传递 output_attentions=Trueconfig.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

  • reshaped_hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入输出 + 每个阶段输出一个),形状为 (batch_size, hidden_size, height, width)

    模型在每层输出处的隐藏状态,以及重新调整以包含空间维度的初始嵌入输出。

示例

>>> from transformers import AutoImageProcessor, Swinv2ForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")
>>> model = Swinv2ForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256")

>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.