Transformers 文档

Big Transfer (BiT)

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2019-12-24 在 HF 论文中发表,并于 2022-12-07 贡献给 Hugging Face Transformers。

Big Transfer (BiT)

概述

BiT 模型由 Alexander Kolesnikov、Lucas Beyer、Xiaohua Zhai、Joan Puigcerver、Jessica Yung、Sylvain Gelly 和 Neil Houlsby 在 Big Transfer (BiT): General Visual Representation Learning 一文中提出。BiT 是一种用于扩展 ResNet 类架构(特别是 ResNetv2)预训练的简单方案。该方法显著提升了迁移学习的效果。

论文摘要如下:

在训练深度视觉神经网络时,预训练表征的迁移能够提高样本效率并简化超参数调优。我们重访了在大型监督数据集上进行预训练并在目标任务上进行微调的范式。我们扩展了预训练规模,并提出了一种称为“大迁移”(Big Transfer, BiT)的简单方案。通过结合几个精心挑选的组件,并使用简单的启发式方法进行迁移,我们在超过 20 个数据集上取得了强劲的性能。BiT 在极其广泛的数据规模范围内表现良好——从每个类别仅 1 个样本到总共 100 万个样本。BiT 在 ILSVRC-2012 上达到了 87.5% 的 Top-1 准确率,在 CIFAR-10 上达到了 99.4%,在 19 项任务的视觉任务适应基准(VTAB)上达到了 76.3%。在小型数据集上,BiT 在每个类别 10 个样本的 ILSVRC-2012 上达到了 76.8% 的准确率,在每个类别 10 个样本的 CIFAR-10 上达到了 97.0%。我们对导致高迁移性能的主要组件进行了详细分析。

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

使用技巧

2) 卷积层使用了权重标准化(Weight Standardization)。作者证明,两者的结合对于在大批量(Large Batch)环境下进行训练非常有效,并且对迁移学习具有显著影响。

资源

以下是官方 Hugging Face 和社区(以 🌎 标记)资源列表,旨在帮助您上手 BiT。

图像分类

如果您有兴趣在此处提交资源,请随时开启 Pull Request,我们将对其进行审查!该资源最好能展示一些新内容,而不是重复现有资源。

BitConfig

class transformers.BitConfig

< >

( 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 num_channels: int = 3 embedding_size: int = 64 hidden_sizes: list[int] | tuple[int, ...] = (256, 512, 1024, 2048) depths: list[int] | tuple[int, ...] = (3, 4, 6, 3) layer_type: str = 'preactivation' hidden_act: str = 'relu' global_padding: str | None = None num_groups: int = 32 drop_path_rate: float | int = 0.0 embedding_dynamic_padding: bool = False output_stride: int = 32 width_factor: int = 1 _out_features: list[str] | None = None _out_indices: list[int] | None = None )

参数

  • num_channels (int, optional, defaults to 3) — 输入通道的数量。
  • embedding_size (int, optional, defaults to 64) — 嵌入层和隐藏状态的维度。
  • hidden_sizes (Union[list[int], tuple[int, ...]], optional, defaults to (256, 512, 1024, 2048)) — 模型每个阶段的维度(隐藏层大小)。
  • depths (Union[list[int], tuple[int, ...]], optional, defaults to (3, 4, 6, 3)) — Transformer 中每一层的深度。
  • layer_type (str, optional, defaults to "preactivation") — 使用的层类型,可以是 "preactivation""bottleneck"
  • hidden_act (str, optional, defaults to relu) — 解码器中的非线性激活函数(函数或字符串)。例如 "gelu", "relu", "silu" 等。
  • global_padding (str, optional) — 用于卷积层的填充策略。可以是 "valid", "same"None
  • num_groups (int, optional, defaults to 32) — 用于 BitGroupNormActivation 层的组数。
  • drop_path_rate (Union[float, int], optional, defaults to 0.0) — Patch fusion 的随机深度失活率(Drop path rate)。
  • embedding_dynamic_padding (bool, optional, defaults to False) — 是否为嵌入层使用动态填充。
  • output_stride (int, optional, defaults to 32) — 输入特征图与输出特征图空间分辨率之间的比率。
  • width_factor (int, optional, defaults to 1) — 模型的宽度因子。

这是用于存储 BitModel 配置的类。它用于根据指定的参数实例化 Bit 模型,从而定义模型架构。使用默认值实例化配置将产生与 google/bit-50 相似的配置。

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

示例

>>> from transformers import BitConfig, BitModel

>>> # Initializing a BiT bit-50 style configuration
>>> configuration = BitConfig()

>>> # Initializing a model (with random weights) from the bit-50 style configuration
>>> model = BitModel(configuration)

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

BitImageProcessor

class transformers.BitImageProcessor

< >

( **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] )

参数

  • **kwargs (ImagesKwargs, optional) — 附加的图像预处理选项。模型特定的 kwargs 列在上面;有关支持参数的完整列表,请参阅 TypedDict 类。

构建一个 BitImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] ) ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望单个图像或一批图像,像素值范围在 0 到 255 之间。如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • return_tensors (strTensorType, optional) — 如果设置为 'pt',则返回堆叠后的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

BitImageProcessorPil

class transformers.BitImageProcessorPil

< >

( **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] )

参数

  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。

构建一个 BitImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] ) ~image_processing_base.BatchFeature

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单个图像或一批图像,像素值范围为 0 到 255。如果输入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠后的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

BitModel

class transformers.BitModel

< >

( 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 (BitModel) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载模型相关的权重,仅加载配置。请查看 from_pretrained() 方法来加载模型权重。

不带任何特定顶层头的裸 Bit 模型,输出原始隐藏状态。

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

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

forward

< >

( pixel_values: Tensor output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。像素值可以使用 BitImageProcessor 获得。详细信息请参阅 BitImageProcessor.__call__()processor_class 使用 BitImageProcessor 来处理图像)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回

BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一个 BaseModelOutputWithPoolingAndNoAttention 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),根据配置 (BitConfig) 和输入包含各种元素。

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

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

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

  • pooler_output (torch.FloatTensor, 形状为 (batch_size, hidden_size)) — 经过空间维度池化操作后的最后一层隐藏状态。

  • hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每层的一个输出),形状为 (batch_size, num_channels, height, width)

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

示例

BitForImageClassification

class transformers.BitForImageClassification

< >

( 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 (BitForImageClassification) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载模型相关的权重,仅加载配置。请查看 from_pretrained() 方法来加载模型权重。

带有图像分类头(在池化特征之上的线性层)的 BiT 模型,例如用于 ImageNet。

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

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

forward

< >

( pixel_values: torch.FloatTensor | None = None labels: torch.LongTensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)可选) — 对应于输入图像的张量。像素值可以使用 BitImageProcessor 获得。详细信息请参阅 BitImageProcessor.__call__()processor_class 使用 BitImageProcessor 来处理图像)。
  • labels (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 中。如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回

ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

一个 ImageClassifierOutputWithNoAttention 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),根据配置 (BitConfig) 和输入包含各种元素。

BitForImageClassification 的前向传播方法,覆盖了 __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), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每阶段的一个输出),形状为 (batch_size, num_channels, height, width)。模型在每个阶段输出的隐藏状态(也称为特征图)。

示例

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/bit-50")
>>> model = BitForImageClassification.from_pretrained("google/bit-50")

>>> 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.