Transformers documentation

TIPSv2

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2026-04-13 在 HF papers 上发布,并于 2026-07-06 贡献至 Hugging Face Transformers。

TIPSv2

FlashAttention SDPA

概述

TIPSv2(Text-Image Pre-training with Spatial awareness,具有空间感知能力的文本-图像预训练)是一组对比式视觉-语言编码器,由 Bingyi Cao、Koert Chen、Kevis-Kokitsi Maninis、Kaifeng Chen、Arjun Karpur、Ye Xia、Sahil Dua、Tanmaya Dabral、Guangxing Han、Bohyung Han、Joshua Ainslie、Alex Bewley、Mithun Jacob、René Wagner、Washington Ramos、Krzysztof Choromanski、Mojtaba Seyedhosseini 和 Howard Zhou 在 TIPSv2: Advancing Vision-Language Pretraining with Enhanced Patch-Text Alignment 中提出。

该论文的摘要如下:

视觉-语言预训练领域的最新进展显著提升了众多下游计算机视觉应用的性能,例如分类、检索、分割和深度预测。然而,这些模型仍然面临一个根本性的挑战:将密集的 patch 表示与对应概念的文本嵌入进行对齐。在本工作中,我们深入研究了这一关键问题,并提出了新颖的技术来增强基础视觉-语言模型在该方面的能力。首先,我们发现 patch 级别的蒸馏过程能够显著提升密集的 patch-文本对齐效果——令人惊讶的是,蒸馏后学生模型的 patch-文本对齐效果远远超过了教师模型。这一观察启发我们重新审视预训练方案,从而提出了 iBOT++,这是对常用 iBOT 掩码图像目标的升级,其中未掩码的 token 也直接参与损失计算。这极大地增强了预训练模型的 patch-文本对齐能力。此外,为了提高视觉-语言预训练的效率与效果,我们修改了学习方案中的指数移动平均设置,并引入了一种 caption 采样策略,以利用不同粒度下的合成 caption。结合这些组件,我们开发了 TIPSv2,这是一个适用于广泛下游应用的新图像-文本编码器模型系列。通过在 9 项任务和 20 个数据集上的全面实验,我们展示了强劲的性能,通常与近期视觉编码器模型相当或更优。代码和模型已通过我们的项目页面 https://gdm-tipsv2.github.io/ 发布。

tipsv2 architecture overview

该模型由 Ternuraz 和 guarin 贡献。 原始代码可在此处找到。

您可以在 TIPSv2 集合中找到所有原始的 TIPSv2 检查点。

有关在 TIPSv2 视觉骨干网络之上进行深度估计、法线估计和语义分割,请参阅 TIPSv2 DPT。

Pipeline
AutoModel
get_image_features 和 get_text_features
用于视觉特征图的 AutoBackbone
Tipsv2VisionModel
from transformers import pipeline


image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
candidate_labels = ["a photo of a cat", "a photo of a dog", "a photo of a car"]

classifier = pipeline(task="zero-shot-image-classification", model="google/tipsv2-b14", device_map="auto")
out = classifier(image, candidate_labels=candidate_labels)
print(out)
# [{'score': 0.999, 'label': 'a photo of a cat'}, {'score': 0.001, 'label': 'a photo of a dog'}, {'score': 0.0, 'label': 'a photo of a car'}]

备注

Tipsv2Config

class transformers.Tipsv2Config

< >

( 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 = Nonetext_config: dict | transformers.models.tipsv2.configuration_tipsv2.Tipsv2TextConfig | None = Nonevision_config: dict | transformers.models.tipsv2.configuration_tipsv2.Tipsv2VisionConfig | None = Nonetemperature_init_value: float = 0.005065968260169029 )

参数

  • text_config (dict, 可选) — 用于初始化 Tipsv2TextConfig 的配置选项字典。
  • vision_config (dict, 可选) — 用于初始化 Tipsv2VisionConfig 的配置选项字典。
  • temperature_init_value (float,可选,默认为 0.005065968260169029) — Tipsv2Model 中用于缩放余弦相似度 logits 的可学习温度参数的初始值。

这是用于存储 Tipsv2Model 配置的类。它根据指定的参数实例化 Tipsv2 模型,并定义模型架构。使用默认值实例化配置将得到与 google/tipsv2-b14 类似的配置。

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

示例:

>>> from transformers import Tipsv2Config, Tipsv2Model

>>> configuration = Tipsv2Config()
>>> model = Tipsv2Model(configuration)
>>> configuration = model.config

>>> from transformers import Tipsv2TextConfig, Tipsv2VisionConfig

>>> text_config = Tipsv2TextConfig()
>>> vision_config = Tipsv2VisionConfig()
>>> config = Tipsv2Config(text_config=text_config, vision_config=vision_config)

Tipsv2TextConfig

class transformers.Tipsv2TextConfig

< >

( 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 = Nonevocab_size: int = 32000hidden_size: int = 768intermediate_size: int = 3072num_hidden_layers: int = 12num_attention_heads: int = 12max_position_embeddings: int = 64hidden_act: str = 'relu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0pad_token_id: int | None = 0bos_token_id: int | None = Noneeos_token_id: int | list[int] | None = Noneinitializer_range: float = 0.02scale_sqrt_depth: bool = Truepooling_epsilon: float = 1e-08 )

参数

  • vocab_size (int,可选,默认为 32000) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • max_position_embeddings (int,可选,默认为 64) — 该模型可能使用的最大序列长度。
  • hidden_act (str,可选,默认为 relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • pad_token_id (int, 可选,默认为 0) — 词表中用于填充的 token id。
  • bos_token_id (int, 可选) — 词汇表中用于表示流起始的 Token id。
  • eos_token_id (Union[int, list[int]], 可选) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • scale_sqrt_depth (bool,可选,默认为 True) — 是否在添加正弦位置嵌入之前,将 token 嵌入乘以 sqrt(hidden_size)。
  • pooling_epsilon (float, 可选,默认为 1e-8) — 在计算掩码平均池化时,添加到有效 token 数量上的 epsilon 值。

这是用于存储 Tipsv2Model 配置的类。它根据指定的参数实例化 Tipsv2 模型,并定义模型架构。使用默认值实例化配置将得到与 google/tipsv2-b14 类似的配置。

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

示例:

>>> from transformers import Tipsv2TextConfig, Tipsv2TextModel

>>> configuration = Tipsv2TextConfig()
>>> model = Tipsv2TextModel(configuration)
>>> configuration = model.config

Tipsv2VisionConfig

class transformers.Tipsv2VisionConfig

< >

( 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 = Nonehidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12mlp_ratio: int | float = 4hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06image_size: int | list[int] | tuple[int, int] = 448patch_size: int | list[int] | tuple[int, int] = 14num_channels: int = 3qkv_bias: bool = Truelayerscale_value: float = 1.0drop_path_rate: float | int = 0.0use_swiglu_ffn: bool = Falsenum_register_tokens: int = 1_out_features: list[str] | None = None_out_indices: list[int] | None = Noneapply_layernorm: bool = Truereshape_hidden_states: bool = True )

参数

  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • mlp_ratio (Union[int, float],可选,默认为 4) — MLP 隐藏层维度与嵌入维度的比值。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_dropout_prob (Union[float, int],可选,默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_probs_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]],可选,默认为 448) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 14) — 每个 patch 的大小(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • layerscale_value (float,可选,默认为 1.0) — 用于 layer scale 的初始值。
  • drop_path_rate (Union[float, int],可选,默认为 0.0) — 用于 patch fusion 的 drop path 比率。
  • use_swiglu_ffn (bool,可选,默认为 False) — 是否使用 SwiGLU 前馈神经网络。否则,将使用以 hidden_act 作为激活函数的标准 MLP。
  • num_register_tokens (int,可选,默认为 1) — 要使用的 register token 数量。
  • apply_layernorm (bool,可选,默认为 True) — 当模型用作 backbone 时,是否对特征图应用层归一化。
  • reshape_hidden_states (bool,可选,默认为 True) — 当模型用作骨干网络时,是否将特征图重塑为形状为 (batch_size, hidden_size, height, width) 的 4D 张量。如果为 False,则特征图将是形状为 (batch_size, seq_len, hidden_size) 的 3D 张量。

这是用于存储 Tipsv2Model 配置的类。它根据指定的参数实例化 Tipsv2 模型,并定义模型架构。使用默认值实例化配置将得到与 google/tipsv2-b14 类似的配置。

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

示例:

>>> from transformers import Tipsv2VisionConfig, Tipsv2VisionModel

>>> configuration = Tipsv2VisionConfig()
>>> model = Tipsv2VisionModel(configuration)
>>> configuration = model.config

Tipsv2Tokenizer

class transformers.Tipsv2Tokenizer

< >

( vocab: dict[str, int] | None = Nonemerges: list[tuple[str, str]] | None = Noneunk_token: str | None = '<unk>'pad_token: str | None = '<pad>'bos_token: str | None = Noneeos_token: str | None = Nonemodel_max_length: int = 64do_lower_case: bool = Truetoken_type_ids_pattern: str = 'all_zeros'_spm_precompiled_charsmap = None**kwargs )

基于 HuggingFace 的 tokenizers 库,采用 BPE (SentencePiece) 模型的 Tipsv2 分词器。

__call__

< >

( text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = Nonetext_pair: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = Nonetext_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = Nonetext_pair_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = Noneadd_special_tokens: bool = Truepadding: bool | str | PaddingStrategy = Falsetruncation: bool | str | TruncationStrategy | None = Nonemax_length: int | None = Nonestride: int = 0is_split_into_words: bool = Falsepad_to_multiple_of: int | None = Nonepadding_side: str | None = Nonereturn_tensors: str | TensorType | None = Nonereturn_token_type_ids: bool | None = Nonereturn_attention_mask: bool | None = Nonereturn_overflowing_tokens: bool = Falsereturn_special_tokens_mask: bool = Falsereturn_offsets_mapping: bool = Falsereturn_length: bool = Falseverbose: bool = Truetokenizer_kwargs: dict[str, Any] | None = None**kwargs ) → BatchEncoding

参数

  • text (str、list[str]、list[list[str]]、可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果以字符串列表(预分词)形式提供序列,则必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair (str、list[str]、list[list[str]]、可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果以字符串列表(预分词)形式提供序列,则必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_target (str、list[str]、list[list[str]]、可选) — 要编码为目标文本的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果以字符串列表(预分词)的形式提供序列,则必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • text_pair_target (str、list[str]、list[list[str]]、可选) — 要编码为目标文本的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果序列以字符串列表(预分词)的形式提供,则必须设置 is_split_into_words=True(以消除与序列批次的歧义)。
  • tokenizer_kwargs (dict[str, Any], 可选) — 传递给 tokenizer 的额外 kwargs。这些 kwargs 将与显式参数及其他 kwargs 合并,其中显式参数具有更高的优先级。
  • add_special_tokens (bool,可选,默认为 True) — 在编码序列时是否添加特殊标记。此操作将使用底层的 PretrainedTokenizerBase.build_inputs_with_special_tokens 函数,该函数定义了哪些标记会自动添加到输入 ID 中。如果您希望自动添加 bos 或 eos 标记,此功能非常有用。
  • padding (bool, str 或 PaddingStrategy, ,可选, ,默认为 False) — 启用并控制填充。接受以下值:
    • True 或 'longest':填充至批次中最长的序列(如果仅提供单个序列,则不进行填充)。
    • 'max_length':填充至由参数 max_length 指定的最大长度;若未提供该参数,则填充至模型可接受的最大输入长度。
    • False 或 'do_not_pad'(默认值):不进行填充(即可以输出包含不同长度序列的批次)。
  • truncation (bool, str 或 TruncationStrategy, ,可选, ,默认为 False) — 启用并控制截断。接受以下值:
    • True 或 'longest_first':截断至由参数 max_length 指定的最大长度,或者如果未提供该参数,则截断至模型可接受的最大输入长度。这将逐个 token 进行截断,如果提供了一对序列(或一批序列对),则会从该对中最长的序列中移除一个 token。
    • 'only_first':截断至由参数 max_length 指定的最大长度,或者在未提供该参数时,截断至模型可接受的最大输入长度。如果提供了一对序列(或一批序列对),则仅截断其中的第一个序列。
    • 'only_second':截断至由参数 max_length 指定的最大长度,或者如果未提供该参数,则截断至模型可接受的最大输入长度。仅当提供了一对序列(或一批序列对)时,才会截断其中的第二个序列。
    • False 或 'do_not_truncate'(默认值):不进行截断(即,可以输出序列长度大于模型最大可接受输入大小的批次)。
  • max_length (int, 可选) — 控制截断/填充参数之一所使用的最大长度。如果未设置或设置为 None,则当截断/填充参数需要最大长度时,将使用预定义的最大模型长度。如果模型没有特定的最大输入长度(如 XLNet),则禁用截断/填充到最大长度的功能。

    如果未设置或设置为 None,当截断/填充参数需要最大长度时,将使用预定义的最大模型长度。如果模型没有特定的最大输入长度(例如 XLNet),则禁用截断/填充至最大长度的功能。

  • stride (int,可选,默认为 0) — 如果与 max_length 一起设置为某个数值,则当 return_overflowing_tokens=True 时,返回的溢出 token 将包含截断序列末尾的若干 token,以在截断序列和溢出序列之间提供一定的重叠。此参数的值定义了重叠 token 的数量。
  • is_split_into_words (bool,可选,默认为 False) — 输入是否已经预先分词(例如,已拆分为单词)。如果设置为 True,分词器将假设输入已经拆分为单词(例如,通过按空白字符拆分),然后对其进行分词。这对于命名实体识别(NER)或 token 分类非常有用。
  • pad_to_multiple_of (int, 可选) — 如果设置,则将序列填充为所提供值的倍数。需要启用 padding。 这对于在计算能力为 >= 7.5(Volta)的 NVIDIA 硬件上启用 Tensor Cores 的使用特别有用。
  • padding_side (str, 可选) — 模型应应用填充的一侧。应在 [‘right’, ‘left’] 之间进行选择。 默认值取自同名的类属性。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回张量而不是 Python 整数列表。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 Numpy np.ndarray 对象。
  • return_token_type_ids (bool, 可选) — 是否返回 token type ID。如果保持默认值,将根据特定分词器的默认设置返回 token type ID,该设置由 return_outputs 属性定义。

    什么是 token type ID?

  • return_attention_mask (bool, 可选) — 是否返回注意力掩码。如果保持默认值,将根据特定分词器的默认设置返回注意力掩码,该设置由 return_outputs 属性定义。

    什么是注意力掩码?

  • return_overflowing_tokens (bool,可选,默认为 False) — 是否返回溢出的 token 序列。如果提供了输入 id 的序列对(或序列对批次),且 truncation_strategy = longest_first 或 True,则会抛出错误,而不是返回溢出的 token。
  • return_special_tokens_mask (bool,可选,默认为 False) — 是否返回特殊 token 掩码信息。
  • return_offsets_mapping (bool, 可选, 默认为 False) — 是否返回 (char_start, char_end) 每个 token 的。

    此功能仅在继承自 PreTrainedTokenizerFast 的快速分词器上可用。如果使用 Python 分词器,此方法将抛出 NotImplementedError。

  • return_length (bool,可选,默认为 False) — 是否返回编码后输入的长度。
  • verbose (bool,可选,默认为 True) — 是否打印更多信息和警告。
  • **kwargs — 传递给 self.tokenize() 方法

返回值

BatchEncoding

一个包含以下字段的 BatchEncoding:

  • input_ids — 要输入模型的 token id 列表。

    什么是输入 ID?

  • token_type_ids — 要输入模型的 token 类型 ID 列表(当 return_token_type_ids=True 或 self.model_input_names 中包含 “token_type_ids” 时)。

    什么是 token type ID?

  • attention_mask — 索引列表,指定模型应关注哪些 token(当 return_attention_mask=True 或 “attention_mask” 位于 self.model_input_names 中时)。

    什么是注意力掩码?

  • overflowing_tokens — 溢出 token 序列的列表(当指定了 max_length 且 return_overflowing_tokens=True 时)。

  • num_truncated_tokens — 被截断的 token 数量(当指定了 max_length 且 return_overflowing_tokens=True 时)。

  • special_tokens_mask — 由 0 和 1 组成的列表,其中 1 表示添加的特殊标记,0 表示常规序列标记(当 add_special_tokens=True 且 return_special_tokens_mask=True 时)。

  • length — 输入的长度(当 return_length=True 时)

用于对一条或多条序列,或一对或多对序列进行分词并准备输入模型的主要方法。

Tipsv2ImageProcessor

class transformers.Tipsv2ImageProcessor

< >

( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 448, 'width': 448}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 False) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • Returns 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。 —

构建一个 Tipsv2ImageProcessor 图像处理器。

disable_grouping (bool, kwargs, 可选): 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详情见此处:https://github.com/huggingface/transformers/pull/38157 image_seq_length (int, kwargs, 可选): 输入中每张图像所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中应将其设置为处理器属性。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class '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。
  • image_like_kwargs (dict[str, Any], 可选) — 用于额外图像类输入的开发者标志,这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如,preprocess(images, masks=masks) 是首选方式,但对于某些模型会导致参数优先级问题。在这种情况下,可以改用 preprocess(images, image_like_inputs={"masks": masks})。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

Tipsv2Processor

类 transformers.Tipsv2Processor

< >

( image_processor = Nonetokenizer = None )

参数

  • image_processor (Tipsv2ImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (Tipsv2Tokenizer) — 分词器是必需的输入。

构建一个 Tipsv2Processor,它将图像处理器和分词器封装为单一处理器。

Tipsv2Processor 提供了 Tipsv2ImageProcessor 和 Tipsv2Tokenizer 的所有功能。有关更多信息,请参阅 ~Tipsv2ImageProcessor 和 ~Tipsv2Tokenizer。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = Noneaudio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )

参数

  • 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。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • videos (Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置 do_rescale=False。
  • audio (Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]], 可选) — 要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。 如果为 NumPy 数组/PyTorch 张量,每个音频的形状应为 (C, T),其中 C 为通道数,T 为音频的采样长度。
  • return_mm_token_type_ids (bool, kwargs) — 是否返回多模态 token 类型 id,用于指示多模态占位符 token 的位置。
  • return_text_replacement_offsets (bool, kwargs) — 是否返回每个多模态占位符及其替换内容的字符偏移量。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

Tipsv2Model

class transformers.Tipsv2Model

< >

( config: Tipsv2Config )

参数

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

未添加任何特定头部的裸 Tipsv2 模型,直接输出原始隐藏状态。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonebool_masked_pos: typing.Optional[torch.Tensor] = Nonereturn_loss: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Tipsv2Output or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Tipsv2ImageProcessor 获取像素值。有关详细信息,请参阅 Tipsv2ImageProcessor.call()(Tipsv2Processor 使用 Tipsv2ImageProcessor 处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • bool_masked_pos (torch.BoolTensor,形状为 (batch_size, sequence_length),可选) — 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。仅与预训练相关。
  • return_loss (bool, 可选) — 当同时提供图像和文本输入时,是否返回对比损失。

返回值

Tipsv2Output 或 tuple(torch.Tensor)

Tipsv2Output 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Tipsv2Config)和输入。

Tipsv2Model 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选,当 return_loss 为 True 时返回) — 用于图像-文本相似度的对比损失。
  • logits_per_image(形状为 (image_batch_size, text_batch_size) 的 torch.Tensor)— image_embeds 与 text_embeds 之间的缩放点积分数。这表示图像-文本相似度分数。
  • logits_per_text(形状为 (text_batch_size, image_batch_size) 的 torch.Tensor)— text_embeds 与 image_embeds 之间的缩放点积分数。这表示文本-图像相似度分数。
  • text_embeds(形状为 (batch_size, output_dim 的 torch.Tensor)—— 通过对 Tipsv2TextModel 的池化输出应用投影层获得的文本嵌入。
  • image_embeds (torch.Tensor,形状为 (batch_size, output_dim) — 通过对 Tipsv2VisionModel 的池化输出应用投影层得到的图像嵌入。
  • text_model_output (~modeling_outputs.BaseModelOutputWithPooling,可选) — Tipsv2TextModel 的输出。
  • vision_model_output(~modeling_outputs.BaseModelOutputWithPooling,可选)— Tipsv2VisionModel 的输出。

示例:

>>> import torch
>>> from transformers import AutoModel, AutoProcessor
>>> from transformers.image_utils import load_image

>>> model_id = "google/tipsv2-b14"
>>> model = AutoModel.from_pretrained(model_id, device_map="auto")
>>> processor = AutoProcessor.from_pretrained(model_id)

>>> image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")
>>> candidate_labels = ["a photo of a cat", "a photo of a dog", "a photo of a car"]

>>> inputs = processor(text=candidate_labels, images=image, return_tensors="pt").to(model.device)

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

>>> probs = outputs.logits_per_image.softmax(dim=1)
>>> most_likely_idx = probs.argmax(dim=1).item()
>>> most_likely_label = candidate_labels[most_likely_idx]
>>> print(f"Most likely label: '{most_likely_label}' with probability: {probs[0][most_likely_idx].item():.3f}")
Most likely label: 'a photo of a cat' with probability: 0.975

get_text_features

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Tipsv2Config)和输入。

  • 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

get_image_features

< >

( pixel_values: Tensorbool_masked_pos: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。可以使用 Tipsv2ImageProcessor 获取像素值。有关详细信息,请参阅 Tipsv2ImageProcessor.call()(Tipsv2Processor 使用 Tipsv2ImageProcessor 处理图像)。
  • bool_masked_pos (torch.BoolTensor,形状为 (batch_size, sequence_length),可选) — 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。仅与预训练相关。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Tipsv2Config)和输入。

  • 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

Tipsv2TextModel

class transformers.Tipsv2TextModel

< >

( config: Tipsv2TextConfig )

参数

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

未添加任何投影头的 TIPSv2 文本塔。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Tipsv2Config)和输入。

Tipsv2TextModel 的 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> import torch
>>> from transformers import AutoConfig, Tipsv2TextModel, AutoProcessor

>>> model_id = "google/tipsv2-b14"
>>> config = AutoConfig.from_pretrained(model_id)
>>> model = Tipsv2TextModel.from_pretrained(model_id, config=config.text_config, device_map="auto")
>>> processor = AutoProcessor.from_pretrained(model_id)

>>> candidate_labels = ["a photo of a cat", "a photo of a dog", "a photo of a car"]
>>> inputs = processor(text=candidate_labels, return_tensors="pt").to(model.device)

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

>>> text_embeds = outputs.pooler_output  # (batch_size, hidden_size)

Tipsv2VisionModel

class transformers.Tipsv2VisionModel

< >

( config: Tipsv2VisionConfig )

参数

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

未添加任何特定头部的裸 Tipsv2 模型,直接输出原始隐藏状态。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonebool_masked_pos: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Tipsv2ImageProcessor 获取像素值。有关详细信息,请参阅 Tipsv2ImageProcessor.call()(Tipsv2Processor 使用 Tipsv2ImageProcessor 处理图像)。
  • bool_masked_pos(形状为 (batch_size, sequence_length) 的 torch.BoolTensor)— 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。仅与预训练相关。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Tipsv2Config)和输入。

Tipsv2VisionModel 的 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 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> import torch
>>> from transformers import AutoConfig, AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image

>>> model_id = "google/tipsv2-b14"
>>> config = AutoConfig.from_pretrained(model_id)
>>> model = AutoModel.from_pretrained(model_id, config=config.vision_config, device_map="auto")
>>> image_processor = AutoImageProcessor.from_pretrained(model_id)

>>> image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")
>>> inputs = image_processor(images=image, return_tensors="pt").to(model.device)

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

>>> # Tipsv2 repurposes the register token from DINOv2-with-registers as a secondary class token
>>> sequence = outputs.last_hidden_state  # (batch_size, 1 + num_register_tokens + num_patches, hidden_size)
>>> cls_token_1 = sequence[:, 0]  # supervised by web alt-text captions
>>> cls_token_2 = sequence[:, 1 : 1 + model.config.num_register_tokens]  # supervised by synthetic captions

Tipsv2VisionBackbone

class transformers.Tipsv2VisionBackbone

< >

( config: Tipsv2Config | Tipsv2VisionConfig )

参数

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

Tipsv2Vision 骨干网络,用于与 DETR 和 MaskFormer 等框架配合使用。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensorattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BackboneOutput or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。可以使用 Tipsv2ImageProcessor 获取像素值。有关详细信息,请参阅 Tipsv2ImageProcessor.call()(Tipsv2Processor 使用 Tipsv2ImageProcessor 处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

返回值

BackboneOutput 或 tuple(torch.Tensor)

BackboneOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Tipsv2Config)和输入。

Tipsv2VisionBackbone 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • feature_maps(形状为 (batch_size, num_channels, height, width) 的 tuple(torch.Tensor))— 各阶段的特征图。

  • hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(包含嵌入层的输出以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size) 或 (batch_size, num_channels, height, width),具体取决于骨干网络。

    模型在每个阶段输出处的隐藏状态,以及初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力机制时适用。

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

示例:

>>> import torch
>>> from transformers import AutoBackbone, Tipsv2VisionConfig

>>> config = Tipsv2VisionConfig(out_features=["stage3", "stage6", "stage9", "stage12"])
>>> model = AutoBackbone.from_config(config)

>>> pixel_values = torch.randn(1, 3, 448, 448)

>>> outputs = model(pixel_values)
>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 768, 32, 32]
Update on GitHub