Transformers 文档

Swin2SR

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

Swin2SR

PyTorch

概述

Swin2SR 模型在 Swin2SR: SwinV2 Transformer for Compressed Image Super-Resolution and Restoration 中被提出,作者是 Marcos V. Conde, Ui-Jin Choi, Maxime Burchi, Radu Timofte。Swin2SR 通过整合 Swin Transformer v2 层改进了 SwinIR 模型,从而缓解了诸如训练不稳定、预训练和微调之间的分辨率差距以及数据饥渴等问题。

以下是论文的摘要

压缩在通过带宽受限系统(如流媒体服务、虚拟现实或视频游戏)高效传输和存储图像和视频方面发挥着重要作用。然而,压缩不可避免地会导致伪影和原始信息的丢失,这可能会严重降低视觉质量。由于这些原因,压缩图像的质量增强已成为一个热门的研究课题。虽然大多数最先进的图像恢复方法都基于卷积神经网络,但其他基于 Transformer 的方法(如 SwinIR)在这些任务上表现出令人印象深刻的性能。在本文中,我们探索了新颖的 Swin Transformer V2,以改进 SwinIR 在图像超分辨率方面的性能,特别是针对压缩输入场景。使用这种方法,我们可以解决 Transformer 视觉模型训练中的主要问题,例如训练不稳定、预训练和微调之间的分辨率差距以及数据饥渴。我们对三个代表性任务进行了实验:JPEG 压缩伪影去除、图像超分辨率(经典和轻量级)以及压缩图像超分辨率。实验结果表明,我们的方法 Swin2SR 可以提高 SwinIR 的训练收敛性和性能,并且是“AIM 2022 压缩图像和视频超分辨率挑战赛”的前 5 名解决方案。

drawing Swin2SR 架构。取自原始论文。

此模型由 nielsr 贡献。 原始代码可以在这里找到。

资源

Swin2SR 的演示 notebook 可以在这里找到。

使用 SwinSR 进行图像超分辨率的演示 Space 可以在这里找到。

Swin2SRImageProcessor

transformers.Swin2SRImageProcessor

< >

( do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_pad: bool = True pad_size: int = 8 **kwargs )

参数

  • do_rescale (bool, 可选,默认为 True) — 是否通过指定的比例 rescale_factor 重新缩放图像。可以被 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选,默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以被 preprocess 方法中的 rescale_factor 参数覆盖。

构建 Swin2SR 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_pad: typing.Optional[bool] = None pad_size: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • images (ImageInput) — 要预处理的图像。期望是像素值范围为 0 到 255 的单个或批量图像。如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • do_rescale (bool, 可选,默认为 self.do_rescale) — 是否重新缩放 [0 - 1] 之间的图像值。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 重缩放因子,用于在 do_rescale 设置为 True 时对图像进行重缩放。
  • do_pad (bool, 可选, 默认为 True) — 是否填充图像,以使高度和宽度可以被 window_size 整除。
  • pad_size (int, 可选, 默认为 32) — 局部注意力滑动窗口的大小。
  • return_tensors (strTensorType, 可选) — 返回张量的类型。可以是以下之一:
    • 未设置:返回 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回类型为 tf.Tensor 的批次。
    • TensorType.PYTORCH'pt':返回类型为 torch.Tensor 的批次。
    • TensorType.NUMPY'np':返回类型为 np.ndarray 的批次。
    • TensorType.JAX'jax':返回类型为 jax.numpy.ndarray 的批次。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。

预处理图像或图像批次。

Swin2SRConfig

class transformers.Swin2SRConfig

< >

( image_size = 64 patch_size = 1 num_channels = 3 num_channels_out = None embed_dim = 180 depths = [6, 6, 6, 6, 6, 6] num_heads = [6, 6, 6, 6, 6, 6] window_size = 8 mlp_ratio = 2.0 qkv_bias = True hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 drop_path_rate = 0.1 hidden_act = 'gelu' use_absolute_embeddings = False initializer_range = 0.02 layer_norm_eps = 1e-05 upscale = 2 img_range = 1.0 resi_connection = '1conv' upsampler = 'pixelshuffle' **kwargs )

参数

  • image_size (int, 可选, 默认为 64) — 每张图像的尺寸(分辨率)。
  • patch_size (int, 可选, 默认为 1) — 每个补丁的尺寸(分辨率)。
  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • num_channels_out (int, 可选, 默认为 num_channels) — 输出通道的数量。如果未设置,则将设置为 num_channels
  • embed_dim (int, 可选, 默认为 180) — 补丁嵌入的维度。
  • depths (list(int), 可选, 默认为 [6, 6, 6, 6, 6, 6]) — Transformer 编码器中每层的深度。
  • num_heads (list(int), 可选, 默认为 [6, 6, 6, 6, 6, 6]) — Transformer 编码器每层中的注意力头数。
  • window_size (int, 可选, 默认为 8) — 窗口大小。
  • mlp_ratio (float, 可选, 默认为 2.0) — MLP 隐藏层维度与嵌入维度的比率。
  • qkv_bias (bool, 可选, 默认为 True) — 是否应将可学习的偏置添加到 queries、keys 和 values 中。
  • hidden_dropout_prob (float, 可选, 默认为 0.0) — 嵌入层和编码器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。
  • drop_path_rate (float, 可选, 默认为 0.1) — 随机深度比率。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu""relu""selu""gelu_new"
  • use_absolute_embeddings (bool, 可选, 默认为 False) — 是否将绝对位置嵌入添加到补丁嵌入中。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-05) — 层归一化层使用的 epsilon 值。
  • upscale (int, 可选, 默认为 2) — 图像的放大倍数。图像超分辨率为 2/3/4/8,去噪和压缩伪影减少为 1
  • img_range (float, 可选, 默认为 1.0) — 输入图像的值的范围。
  • resi_connection (str, 可选, 默认为 "1conv") — 在每个阶段的残差连接之前使用的卷积块。
  • upsampler (str, 可选, 默认为 "pixelshuffle") — 重建模块。可以是 ‘pixelshuffle’/‘pixelshuffledirect’/‘nearest+conv’/None。

这是用于存储 Swin2SRModel 配置的配置类。它用于根据指定的参数实例化 Swin Transformer v2 模型,定义模型架构。使用默认值实例化配置将产生类似于 Swin Transformer v2 caidas/swin2sr-classicalsr-x2-64 架构的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。

示例

>>> from transformers import Swin2SRConfig, Swin2SRModel

>>> # Initializing a Swin2SR caidas/swin2sr-classicalsr-x2-64 style configuration
>>> configuration = Swin2SRConfig()

>>> # Initializing a model (with random weights) from the caidas/swin2sr-classicalsr-x2-64 style configuration
>>> model = Swin2SRModel(configuration)

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

Swin2SRModel

class transformers.Swin2SRModel

< >

( config )

参数

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

裸 Swin2SR 模型转换器输出原始隐藏状态,顶部没有任何特定的头部。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: FloatTensor head_mask: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 Swin2SRImageProcessor.call()
  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于使自注意力模块的选定头无效的掩码。在 [0, 1] 中选择的掩码值:

    • 1 表示头未被掩蔽
    • 0 表示头被掩蔽
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

transformers.modeling_outputs.BaseModelOutputtorch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),包括各种元素,具体取决于配置 (Swin2SRConfig) 和输入。

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

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(如果模型具有嵌入层,则为嵌入输出的元组,+ 每个层的输出的元组),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出端的隐藏状态,加上可选的初始嵌入输出。

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

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

Swin2SRModel forward 方法覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("caidas/swin2SR-classical-sr-x2-64")
>>> model = Swin2SRModel.from_pretrained("caidas/swin2SR-classical-sr-x2-64")

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

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

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 180, 488, 648]

Swin2SRForImageSuperResolution

class transformers.Swin2SRForImageSuperResolution

< >

( config )

参数

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

Swin2SR 模型转换器,顶部带有用于图像超分辨率和恢复的上采样器头。

此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageSuperResolutionOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 Swin2SRImageProcessor.call()
  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于使自注意力模块的选定头无效的掩码。在 [0, 1] 中选择的掩码值:

    • 1 表示头未被掩蔽
    • 0 表示头被掩蔽
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

transformers.modeling_outputs.ImageSuperResolutionOutputtuple(torch.FloatTensor)

transformers.modeling_outputs.ImageSuperResolutionOutputtorch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),包括各种元素,具体取决于配置 (Swin2SRConfig) 和输入。

  • loss (torch.FloatTensor,形状为 (1,), 可选, 当提供 labels 时返回) — 重建损失。

  • reconstruction (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 重建的图像,可能已放大。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(如果模型具有嵌入层,则为嵌入输出的元组,+ 每个阶段的输出的元组),形状为 (batch_size, sequence_length, hidden_size)。模型在每个阶段输出端的隐藏状态(也称为特征图)。

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

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

Swin2SRForImageSuperResolution forward 方法覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例

>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> import requests

>>> from transformers import AutoImageProcessor, Swin2SRForImageSuperResolution

>>> processor = AutoImageProcessor.from_pretrained("caidas/swin2SR-classical-sr-x2-64")
>>> model = Swin2SRForImageSuperResolution.from_pretrained("caidas/swin2SR-classical-sr-x2-64")

>>> url = "https://huggingface.co/spaces/jjourney1125/swin2sr/resolve/main/samples/butterfly.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> # prepare image for the model
>>> inputs = processor(image, return_tensors="pt")

>>> # forward pass
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> output = outputs.reconstruction.data.squeeze().float().cpu().clamp_(0, 1).numpy()
>>> output = np.moveaxis(output, source=0, destination=-1)
>>> output = (output * 255.0).round().astype(np.uint8)  # float32 to uint8
>>> # you can visualize `output` with `Image.fromarray`
< > 更新 在 GitHub 上