Transformers documentation

ALIGN

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2021-02-11 在 HF papers 上发表,并于 2023-03-01 贡献至 Hugging Face Transformers。

Transformers

ALIGN

ALIGN 在一个包含 18 亿个带噪声的替代文本与图像对的预训练数据集上进行训练,以证明规模可以弥补噪声的影响。它采用双编码器架构,图像部分使用 EfficientNet,文本部分使用 BERT,并通过对比损失将相似的图像-文本嵌入拉近,同时将不同的嵌入推远。训练完成后,ALIGN 可以将任意图像和候选说明编码到共享的向量空间中,从而无需额外标签即可实现零样本检索或分类。这种规模优先的方法降低了数据集整理成本,并推动了最先进的图像-文本检索和零样本 ImageNet 分类性能。

您可以在 Kakao Brain 组织下找到所有原始的 ALIGN 检查点。

点击右侧边栏中的 ALIGN 模型,以查看将 ALIGN 应用于不同视觉和文本相关任务的更多示例。

以下示例演示了如何使用 Pipeline 或 AutoModel 类进行零样本图像分类。

Pipeline
AutoModel
from transformers import pipeline


pipeline = pipeline(
    task="zero-shot-image-classification",
    model="kakaobrain/align-base",
    device=0,
)

candidate_labels = [
    "a photo of a dog",
    "a photo of a cat",
    "a photo of a person"
]

pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", candidate_labels=candidate_labels)

备注

  • ALIGN 将文本和视觉特征投影到潜在空间,并使用投影后的图像特征与文本特征之间的点积作为相似度分数。下面的示例演示了如何使用 AlignProcessor 和 AlignModel 计算图文相似度分数。

    # Example of using ALIGN for image-text similarity
    from transformers import AlignProcessor, AlignModel
    import torch
    from PIL import Image
    import requests
    from io import BytesIO
    
    # Load processor and model
    processor = AlignProcessor.from_pretrained("kakaobrain/align-base")
    model = AlignModel.from_pretrained("kakaobrain/align-base", device_map="auto")
    
    # Download image from URL
    url = "https://huggingface.co/roschmid/dog-races/resolve/main/images/Golden_Retriever.jpg"
    response = requests.get(url)
    image = Image.open(BytesIO(response.content))  # Convert the downloaded bytes to a PIL Image
    
    texts = ["a photo of a cat", "a photo of a dog"]
    
    # Process image and text inputs
    inputs = processor(images=image, text=texts, return_tensors="pt").to(model.device)
    
    # Get the embeddings
    with torch.no_grad():
        outputs = model(**inputs)
    
    image_embeds = outputs.image_embeds
    text_embeds = outputs.text_embeds
    
    # Normalize embeddings for cosine similarity
    image_embeds = image_embeds / image_embeds.norm(dim=1, keepdim=True)
    text_embeds = text_embeds / text_embeds.norm(dim=1, keepdim=True)
    
    # Calculate similarity scores
    similarity_scores = torch.matmul(text_embeds, image_embeds.T)
    
    # Print raw scores
    print("Similarity scores:", similarity_scores)
    
    # Convert to probabilities
    probs = torch.nn.functional.softmax(similarity_scores, dim=0)
    print("Probabilities:", probs)
    
    # Get the most similar text
    most_similar_idx = similarity_scores.argmax().item()
    print(f"Most similar text: '{texts[most_similar_idx]}'")

资源

AlignConfig

class transformers.AlignConfig

< >

( 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.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprojection_dim: int = 640temperature_init_value: float = 1.0initializer_range: float = 0.02 )

参数

  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • projection_dim (int,可选,默认为 640) — 文本和视觉投影层的维度。
  • temperature_init_value (float,可选,默认为 1.0) — temperature 参数的初始值。默认值遵循原始 ALIGN 实现。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 AlignModel 配置的类。它根据指定的参数实例化 Align 模型,并定义模型架构。使用默认值实例化配置将得到与 kakaobrain/align-base 类似的配置。

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

示例:

>>> from transformers import AlignConfig, AlignModel

>>> # Initializing a AlignConfig with kakaobrain/align-base style configuration
>>> configuration = AlignConfig()

>>> # Initializing a AlignModel (with random weights) from the kakaobrain/align-base style configuration
>>> model = AlignModel(configuration)

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

>>> # We can also initialize a AlignConfig from a AlignTextConfig and a AlignVisionConfig
>>> from transformers import AlignTextConfig, AlignVisionConfig

>>> # Initializing ALIGN Text and Vision configurations
>>> config_text = AlignTextConfig()
>>> config_vision = AlignVisionConfig()

>>> config = AlignConfig(text_config=config_text, vision_config=config_vision)

AlignTextConfig

class transformers.AlignTextConfig

< >

( 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 = 30522hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.1attention_probs_dropout_prob: float | int = 0.1max_position_embeddings: int = 512type_vocab_size: int = 2initializer_range: float = 0.02layer_norm_eps: float = 1e-12pad_token_id: int | None = 0bos_token_id: int | None = Noneeos_token_id: int | list[int] | None = None )

参数

  • vocab_size (int,可选,默认为 30522) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_dropout_prob (Union[float, int],可选,默认为 0.1) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (Union[float, int],可选,默认为 0.1) — 注意力概率的 dropout 比率。
  • max_position_embeddings (int,可选,默认为 512) — 该模型可能使用的最大序列长度。
  • type_vocab_size (int,可选,默认为 2) — token_type_ids 的词汇表大小。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-12) — 层归一化层所使用的 epsilon 值。
  • 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。

这是用于存储 AlignModel 配置的类。它根据指定的参数实例化 Align 模型,并定义模型架构。使用默认值实例化配置将得到与 kakaobrain/align-base 类似的配置。

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

示例:

>>> from transformers import AlignTextConfig, AlignTextModel

>>> # Initializing a AlignTextConfig with kakaobrain/align-base style configuration
>>> configuration = AlignTextConfig()

>>> # Initializing a AlignTextModel (with random weights) from the kakaobrain/align-base style configuration
>>> model = AlignTextModel(configuration)

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

AlignVisionConfig

class transformers.AlignVisionConfig

< >

( 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 = Nonenum_channels: int = 3image_size: int | list[int] | tuple[int, int] = 600width_coefficient: float = 2.0depth_coefficient: float = 3.1depth_divisor: int = 8kernel_sizes: list[int] | tuple[int, ...] = (3, 3, 5, 3, 5, 5, 3)in_channels: list[int] | tuple[int, ...] = (32, 16, 24, 40, 80, 112, 192)out_channels: list[int] | tuple[int, ...] = (16, 24, 40, 80, 112, 192, 320)depthwise_padding: list | tuple[int, ...] = ()strides: list[int] | tuple[int, ...] = (1, 2, 2, 2, 1, 2, 1)num_block_repeats: list[int] | tuple[int, ...] = (1, 2, 2, 3, 3, 4, 1)expand_ratios: list[int] | tuple[int, ...] = (1, 6, 6, 6, 6, 6, 6)squeeze_expansion_ratio: float = 0.25hidden_act: str = 'swish'hidden_dim: int = 2560pooling_type: str = 'mean'initializer_range: float = 0.02batch_norm_eps: float = 0.001batch_norm_momentum: float = 0.99drop_connect_rate: float | int = 0.2 )

参数

  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 600) — 每张图片的尺寸(分辨率)。
  • width_coefficient (float,可选,默认为 2.0) — 每个阶段网络宽度的缩放系数。
  • depth_coefficient (float,可选,默认为 3.1) — 每个阶段网络深度的缩放系数。
  • depth_divisor (int,可选,默认为 8) — 网络宽度的单位。
  • kernel_sizes (list[int],可选,默认为 [3, 3, 5, 3, 5, 5, 3]) — 用于每个块的核大小列表。
  • in_channels (list[int],可选,默认为 [32, 16, 24, 40, 80, 112, 192]) — 用于每个块中卷积层的输入通道大小列表。
  • out_channels (list[int],可选,默认为 [16, 24, 40, 80, 112, 192, 320]) — 用于每个块中卷积层的输出通道大小列表。
  • depthwise_padding (list[int],可选,默认为 []) — 具有方形填充的块索引列表。
  • strides (list[int],可选,默认为 [1, 2, 2, 2, 1, 2, 1]) — 用于卷积层中每个块的步长大小列表。
  • num_block_repeats (list[int],可选,默认为 [1, 2, 2, 3, 3, 4, 1]) — 每个 block 需要重复的次数列表。
  • expand_ratios (list[int],可选,默认为 [1, 6, 6, 6, 6, 6, 6]) — 每个块的缩放系数列表。
  • squeeze_expansion_ratio (float,可选,默认值为 0.25) — Squeeze 扩展比率。
  • hidden_act (str,可选,默认为 swish) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_dim (int,可选,默认为 1280) — 分类头之前层的隐藏维度。
  • pooling_type (str 或 function,可选,默认为 "mean") — 在稠密分类头之前应用的最终池化类型。可用选项为 ["mean"、"max"]
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • batch_norm_eps (float,可选,默认为 0.001) — 批归一化层所使用的 epsilon 值。
  • batch_norm_momentum (float,可选,默认值为 0.99) — 批归一化层所使用的动量。
  • drop_connect_rate (float,可选,默认值为 0.2) — 跳跃连接的丢弃率。

这是用于存储 AlignModel 配置的类。它根据指定的参数实例化 Align 模型,并定义模型架构。使用默认值实例化配置将得到与 kakaobrain/align-base 类似的配置。

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

示例:

>>> from transformers import AlignVisionConfig, AlignVisionModel

>>> # Initializing a AlignVisionConfig with kakaobrain/align-base style configuration
>>> configuration = AlignVisionConfig()

>>> # Initializing a AlignVisionModel (with random weights) from the kakaobrain/align-base style configuration
>>> model = AlignVisionModel(configuration)

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

AlignProcessor

class transformers.AlignProcessor

< >

( image_processortokenizer )

参数

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

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

AlignProcessor 提供了 EfficientNetImageProcessor 和 BertTokenizer 的所有功能。有关更多信息,请参阅 ~EfficientNetImageProcessor 和 ~BertTokenizer。

__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_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

AlignModel

类 transformers.AlignModel

< >

( config: AlignConfig )

参数

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

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

该模型继承自 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] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonereturn_loss: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → AlignOutput 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),可选) — 与输入图像对应的张量。可以使用 EfficientNetImageProcessor 获取像素值。有关详细信息,请参阅 EfficientNetImageProcessor.call()(AlignProcessor 使用 EfficientNetImageProcessor 处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • token_type_ids (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取自 [0, 1]:
    • 0 对应 sentence A 标记,
    • 1 对应于 sentence B 标记。

    什么是 token type ID?

  • position_ids (torch.Tensor 形状为 (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 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • return_loss (bool, 可选) — 是否返回对比损失。

返回值

AlignOutput 或 tuple(torch.Tensor)

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

AlignModel 的 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 (torch.Tensor,形状为 (batch_size, output_dim) — 通过对 AlignTextModel 的池化输出应用投影层得到的文本嵌入。
  • image_embeds (torch.Tensor,形状为 (batch_size, output_dim) — AlignVisionModel 的输出。
  • text_model_output (~modeling_outputs.BaseModelOutputWithPooling,可选) — AlignTextModel 的输出。
  • vision_model_output(~modeling_outputs.BaseModelOutputWithPoolingAndNoAttention,可选)— AlignVisionModel 的输出。

示例:

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

>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
>>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)

>>> inputs = processor(
...     images=image, text=["a photo of a cat", "a photo of a dog"], return_tensors="pt", padding=True
... )

>>> with torch.inference_mode():
...     outputs = model(**inputs)
>>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
>>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities

get_text_features

< >

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

参数

  • input_ids (torch.Tensor 形状为 (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。

    什么是注意力掩码?

  • token_type_ids (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取自 [0, 1]:
    • 0 对应 sentence A 标记,
    • 1 对应于 sentence B 标记。

    什么是 token type ID?

  • position_ids (torch.Tensor 形状为 (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),其包含的元素取决于配置(AlignConfig)和输入。

  • 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 AutoTokenizer, AlignModel

>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
>>> tokenizer = AutoTokenizer.from_pretrained("kakaobrain/align-base")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> with torch.inference_mode():
...     text_features = model.get_text_features(**inputs)

get_image_features

< >

( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

  • 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 AutoProcessor, AlignModel
>>> from transformers.image_utils import load_image

>>> model = AlignModel.from_pretrained("kakaobrain/align-base")
>>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = load_image(url)

>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
...     image_features = model.get_image_features(**inputs)

AlignTextModel

class transformers.AlignTextModel

< >

( config: AlignTextConfigadd_pooling_layer: bool = True )

参数

  • config (AlignTextConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
  • add_pooling_layer (bool,可选,默认为 True) — 是否添加池化层

ALIGN 的文本模型,顶部未添加任何分类头或投影层。

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

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

forward

< >

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

参数

  • input_ids (torch.Tensor 形状为 (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。

    什么是注意力掩码?

  • token_type_ids (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取自 [0, 1]:
    • 0 对应 sentence A 标记,
    • 1 对应于 sentence B 标记。

    什么是 token type ID?

  • position_ids (torch.Tensor 形状为 (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),其包含的元素取决于配置(AlignConfig)和输入。

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

示例:

>>> from transformers import AutoTokenizer, AlignTextModel

>>> model = AlignTextModel.from_pretrained("kakaobrain/align-base")
>>> tokenizer = AutoTokenizer.from_pretrained("kakaobrain/align-base")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states

AlignVisionModel

class transformers.AlignVisionModel

< >

( config: AlignVisionConfig )

参数

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

ALIGN 的视觉模型,顶部未添加任何分类头或投影层。

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

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

forward

< >

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

参数

返回值

BaseModelOutputWithPoolingAndNoAttention 或 tuple(torch.Tensor)

BaseModelOutputWithPoolingAndNoAttention 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(AlignConfig)和输入而定的各种元素。

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

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

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

  • pooler_output(形状为 (batch_size, hidden_size) 的 torch.Tensor)— 在空间维度上执行池化操作后的最后一层隐藏状态。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, num_channels, height, width)。

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

示例:

>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import AutoProcessor, AlignVisionModel

>>> model = AlignVisionModel.from_pretrained("kakaobrain/align-base")
>>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base")

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

>>> inputs = processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled CLS states
Update on GitHub