Transformers documentation
Hiera
该模型于 2023-06-01 在 HF papers 上发布,并于 2024-07-12 贡献至 Hugging Face Transformers。
Hiera
概述
Hiera 由 Chaitanya Ryali、Yuan-Ting Hu、Daniel Bolya、Chen Wei、Haoqi Fan、Po-Yao Huang、Vaibhav Aggarwal、Arkabandhu Chowdhury、Omid Poursaeed、Judy Hoffman、Jitendra Malik、Yanghao Li 和 Christoph Feichtenhofer 在 Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles 中提出。
该论文提出了“Hiera”,一种分层视觉 Transformer。它通过移除不必要的组件,在不牺牲精度或效率的前提下,简化了现代分层视觉 Transformer 的架构。与那些为了提升有监督分类性能而添加复杂视觉专用组件的传统 Transformer 不同,Hiera 表明,这些通常被称为“花哨功能”的附加组件对于实现高精度并非必不可少。通过利用强大的视觉预训练任务(MAE)进行预训练,Hiera 保持了架构的简洁性,并在多种图像和视频识别任务中,于推理和训练阶段均实现了更优的精度和速度。该方法表明,视觉任务所需的空间偏置可以通过适当的预训练有效习得,从而无需增加架构的复杂性。
该论文的摘要如下:
现代分层视觉 Transformer 为了追求有监督分类性能,引入了若干视觉专用组件。虽然这些组件带来了较高的有效准确率和较低的 FLOP 数,但增加的复杂度实际上使这些 Transformer 比标准 ViT 更慢。本文认为这些额外的冗余是不必要的。通过采用强大的视觉预训练任务(MAE),我们可以在不损失准确率的情况下,从最先进的多阶段视觉 Transformer 中移除所有花哨的组件。在此过程中,我们构建了 Hiera,一个极其简单的分层视觉 Transformer,其准确率高于此前的模型,同时在推理和训练阶段都显著更快。我们在多种图像和视频识别任务上评估了 Hiera。我们的代码和模型可在 https://github.com/facebookresearch/hiera 获取。
Hiera architecture. Taken from the original paper. 该模型由 EduardoPacheco 和 namangarg110 共同贡献。原始代码可在[此处] (https://github.com/facebookresearch/hiera) 找到。
资源
以下是 Hugging Face 官方和社区(以 🌎 标识)提供的资源列表,可帮助您快速上手 Hiera。如果您希望提交资源以收录于此,欢迎随时发起 Pull Request,我们将进行审核!理想情况下,该资源应展示一些新内容,而非重复现有资源。
- HieraForImageClassification 受此 notebook 支持。
- 另请参阅:图像分类任务指南
HieraConfig
class transformers.HieraConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneembed_dim: int = 96image_size: list[int] | tuple[int, ...] = (224, 224)patch_size: list[int] | tuple[int, ...] = (7, 7)patch_stride: list[int] | tuple[int, ...] = (4, 4)patch_padding: list[int] | tuple[int, ...] = (3, 3)mlp_ratio: float = 4.0depths: list[int] | tuple[int, ...] = (2, 3, 16, 3)num_heads: list[int] | tuple[int, ...] = (1, 2, 4, 8)embed_dim_multiplier: float | int = 2.0num_query_pool: int = 3query_stride: list[int] | tuple[int, ...] = (2, 2)masked_unit_size: list[int] | tuple[int, ...] = (8, 8)masked_unit_attention: list[bool] | tuple[bool, ...] = (True, True, False, False)drop_path_rate: float | int = 0.0num_channels: int = 3hidden_act: str = 'gelu'initializer_range: float = 0.02layer_norm_init: float = 1.0layer_norm_eps: float = 1e-06decoder_hidden_size: int | None = Nonedecoder_depth: int | None = Nonedecoder_num_heads: int | None = Nonenormalize_pixel_loss: bool | None = Truemask_ratio: float = 0.6_out_features: list[str] | None = None_out_indices: list[int] | None = None )
参数
- embed_dim (
int,可选,默认为96) — 嵌入和隐藏状态的维度。 - image_size (
Union[list[int], tuple[int, ...]],可选,默认为(224, 224)) — 每张图片的尺寸(分辨率)。 - patch_size (
Union[list[int], tuple[int, ...]],可选,默认为(7, 7)) — 每个 patch 的大小(分辨率)。 - patch_stride (
list(int),可选,默认为[4, 4]) — patch 的步长。 - patch_padding (
list(int),可选,默认为[3, 3]) — 补丁的填充。 - mlp_ratio (
float,可选,默认为4.0) — MLP 隐藏层维度与嵌入维度的比值。 - depths (
Union[list[int], tuple[int, ...]],可选,默认为(2, 3, 16, 3)) — Transformer 中每一层的深度。 - num_heads (
list(int),可选,默认为[1, 2, 4, 8]) — Transformer 编码器每一层中的注意力头数量。 - embed_dim_multiplier (
float,可选,默认为 2.0) — Transformer 编码器中每一层 patch embedding 维度的乘数。 - num_query_pool (
int,可选,默认为 3) — 查询池化阶段的数量。 - query_stride (
list(int),可选,默认为[2, 2]) — 查询池化的步长。 - masked_unit_size (
list(int),可选,默认为[8, 8]) — 掩码单元的大小。 - masked_unit_attention (
list(bool),可选,默认为[True, True, False, False]) — 是否在 Transformer 编码器的每一层中使用带掩码的单元注意力。 - drop_path_rate (
Union[float, int],可选,默认为0.0) — 用于 patch fusion 的 drop path 比率。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_init (
float, 可选,默认为 1.0) — 层归一化层的初始权重值。 - layer_norm_eps (
float,可选,默认为1e-06) — 层归一化层所使用的 epsilon 值。 - decoder_hidden_size (
int, 可选) — 隐藏表示的维度。 - decoder_depth (
int, 可选) — 用于 MAE 预训练的解码器深度。 - decoder_num_heads (
int, 可选) — Transformer 解码器中每个注意力层的注意力头数量。 - normalize_pixel_loss (
bool,可选,默认为True) — 是否根据像素数量对像素损失进行归一化。 - mask_ratio (
float,可选,默认值为 0.6) — 输入中被掩码标记的比例。
这是用于存储 HieraModel 配置的类。它根据指定的参数实例化 Hiera 模型,并定义模型架构。使用默认值实例化配置将生成与 facebook/hiera-base-224 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import HieraConfig, HieraModel
>>> # Initializing a Hiera hiera-base-patch16-224 style configuration
>>> configuration = HieraConfig()
>>> # Initializing a model (with random weights) from the hiera-base-patch16-224 style configuration
>>> model = HieraModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configHieraModel
class transformers.HieraModel
< source >( config: HieraConfigadd_pooling_layer: bool = Trueis_mae: bool = False )
参数
- config (HieraConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
- add_pooling_layer (
bool,可选,默认为True) — 是否应用池化层。 - is_mae (
bool,可选,默认为False) — 是否以 MAE 模式运行模型。
未添加任何特定头部的裸 Hiera 模型,直接输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonenoise: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneinterpolate_pos_encoding: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 BitImageProcessor 获取像素值。有关详细信息,请参阅 BitImageProcessor.call()(processor_class使用 BitImageProcessor 处理图像)。 - noise (
torch.Tensor,形状为(batch_size, num_mask_units),可选) — 主要用于测试目的,以控制随机性并保持可复现性 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - interpolate_pos_encoding (
bool, 可选) — 是否对预训练的位置编码进行插值。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(HieraConfig)和输入。
HieraModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
HieraForPreTraining
class transformers.HieraForPreTraining
< source >( config: HieraConfig )
参数
- config (HieraConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
用于自监督预训练的 Hiera 模型 Transformer,其顶部带有解码器。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonenoise: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneinterpolate_pos_encoding: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → HieraForPreTrainingOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 BitImageProcessor 获取像素值。有关详细信息,请参阅 BitImageProcessor.call()(processor_class使用 BitImageProcessor 处理图像)。 - noise (
torch.Tensor,形状为(batch_size, num_mask_units),可选) — 主要用于测试目的,以控制随机性并保持可复现性 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - interpolate_pos_encoding (
bool, 可选) — 是否对预训练的位置编码进行插值。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
HieraForPreTrainingOutput 或 tuple(torch.Tensor)
HieraForPreTrainingOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(HieraConfig)和输入而定的各种元素。
HieraForPreTraining 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss(形状为
(1,)的torch.Tensor)— 像素重建损失。logits(形状为
(batch_size, sequence_length, patch_size ** 2 * num_channels)的torch.Tensor)— 像素重建 logits。bool_masked_pos(形状为
(batch_size, sequence_length)的torch.BoolTensor)— 指示哪些 patch 被掩码(0)、哪些未被掩码(1)的张量。ids_restore(形状为
(batch_size, sequence_length)的torch.LongTensor)— 包含(打乱后的)掩码补丁原始索引的张量。hidden_states (
tuple[torch.Tensor],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple[torch.Tensor],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
reshaped_hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层输出以及每一层的输出),形状为(batch_size, height, width, hidden_size)。模型在每一层输出处的隐藏状态,以及重塑为包含空间维度的初始嵌入输出。
示例:
>>> from transformers import AutoImageProcessor, HieraForPreTraining
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils 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("facebook/hiera-tiny-224-mae-hf")
>>> model = HieraForPreTraining.from_pretrained("facebook/hiera-tiny-224-mae-hf")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> loss = outputs.loss
>>> print(list(logits.shape))
[1, 196, 768]HieraForImageClassification
class transformers.HieraForImageClassification
< source >( config: HieraConfig )
参数
- config (HieraConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Hiera 模型,顶部带有图像分类头(在最终隐藏状态之上进行平均池化,然后接一个线性层),例如用于 ImageNet。
请注意,通过在模型的前向传播中将
interpolate_pos_encoding设置为True,可以对 Hiera 进行微调,使其处理比训练时更高分辨率的图像。这会将预训练的位置嵌入插值到更高分辨率。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_valueslabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneinterpolate_pos_encoding: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → HieraForImageClassificationOutput or tuple(torch.Tensor)
参数
- pixel_values (`
of shape(batch_size, num_channels, image_size, image_size)) -- The tensors corresponding to the input images. Pixel values can be obtained using [BitImageProcessor](/docs/transformers/main/en/model_doc/bit#transformers.BitImageProcessor). See [BitImageProcessor.__call__()](/docs/transformers/main/en/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) for details (processor_class` uses BitImageProcessor for processing images). - labels(形状为
(batch_size,)的torch.LongTensor,可选)— 用于计算图像分类/回归损失的标签。索引应在[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, 可选) — 是否对预训练的位置编码进行插值。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
HieraForImageClassificationOutput 或 tuple(torch.Tensor)
HieraForImageClassificationOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(HieraConfig)和输入而定的各种元素。
HieraForImageClassification 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。logits(形状为
(batch_size, config.num_labels)的torch.Tensor)— 分类(或当 config.num_labels==1 时为回归)得分(SoftMax 之前)。hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个阶段输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每个阶段输出处的隐藏状态(也称为特征图)。attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, patch_size, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
reshaped_hidden_states (
tuple(torch.Tensor),optional) — 一个torch.Tensor元组(包含一个嵌入层输出的张量以及每个阶段输出的张量),形状为(batch_size, height, width, hidden_size)。这些是模型经过重塑和重新卷起的隐藏状态。模型在每一层输出处的隐藏状态,以及重塑为包含空间维度的初始嵌入输出。
示例:
>>> from transformers import AutoImageProcessor, HieraForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/hiera-base-224")
>>> model = HieraForImageClassification.from_pretrained("facebook/hiera-base-224")
>>> 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])
...