Transformers 文档

Fuyu

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2023-10-17 发布,并于 2023-10-19 添加到 Hugging Face Transformers。

Fuyu

PyTorch

概述

Fuyu 模型由 ADEPT 创建,作者包括 Rohan Bavishi、Erich Elsen、Curtis Hawthorne、Maxwell Nye、Augustus Odena、Arushi Somani、Sağnak Taşırlar。

作者介绍了 Fuyu-8B,这是一款基于经典 Transformer 架构的仅解码器多模态模型,具有查询和键的归一化。增加了一个线性编码器,用于从图像输入创建多模态嵌入。

通过将图像 token 视为文本 token 并使用特殊的图像换行符,模型可以知道图像行的结束位置。移除了图像位置嵌入。这避免了针对不同图像分辨率需要不同训练阶段的需求。Fuyu-8B 拥有 80 亿参数,并获得 CC-BY-NC 许可,其显著特点是能够同时处理文本和图像、令人印象深刻的 16K 上下文大小以及整体性能。

Fuyu 模型使用 bfloat16 进行训练,但原始推理使用 float16。Hub 上上传的检查点使用 dtype = 'float16',这将由 AutoModel API 用于将检查点从 torch.float32 转换为 torch.float16

在线权重的 dtype 大部分是无关紧要的,除非您在使用 model = AutoModelForCausalLM.from_pretrained("path", dtype = "auto") 初始化模型时使用 dtype="auto"。原因是模型将首先下载(使用在线检查点的 dtype),然后将其转换为 torch 的默认 dtype(变为 torch.float32)。用户应指定所需的 dtype,如果未指定,则为 torch.float32

不建议在 float16 中微调模型,已知这会产生 nan,因此应在 bfloat16 中进行微调。

技巧

  • 要转换模型,您需要克隆原始仓库:git clone https://github.com/persimmon-ai-labs/adept-inference,然后获取检查点。
git clone https://github.com/persimmon-ai-labs/adept-inference
wget path/to/fuyu-8b-model-weights.tar
tar -xvf fuyu-8b-model-weights.tar
python src/transformers/models/fuyu/convert_fuyu_weights_to_hf.py  --input_dir /path/to/downloaded/fuyu/weights/ --output_dir /output/path \
    --pt_model_path /path/to/fuyu_8b_release/iter_0001251/mp_rank_00/model_optim_rng.pt
    --ada_lib_path /path/to/adept-inference

对于聊天模型

wget https://axtkn4xl5cip.objectstorage.us-phoenix-1.oci.customer-oci.com/n/axtkn4xl5cip/b/adept-public-data/o/8b_chat_model_release.tar
tar -xvf 8b_base_model_release.tar

然后,模型可以通过以下方式加载:

from transformers import FuyuConfig, FuyuForCausalLM
model_config = FuyuConfig()
model = FuyuForCausalLM(model_config).from_pretrained('/output/path')

输入需要通过特定的 Processor 进行处理,以获得正确的格式。Processor 需要一个 image_processor 和一个 tokenizer。因此,输入可以通过以下方式加载:

from PIL import Image
from transformers import AutoTokenizer
from transformers.models.fuyu.processing_fuyu import FuyuProcessor
from transformers.models.fuyu.image_processing_fuyu_fast import FuyuImageProcessorFast


tokenizer = AutoTokenizer.from_pretrained('adept-hf-collab/fuyu-8b')
image_processor = FuyuImageProcessorFast()


processor = FuyuProcessor(image_processor=image_processor, tokenizer=tokenizer)
text_prompt = "Generate a coco-style caption.\\n"

bus_image_url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bus.png"
bus_image_pil = Image.open(io.BytesIO(requests.get(bus_image_url).content))
inputs_to_model = processor(images=bus_image_pil, text=text_prompt)

此模型由 Molbap 贡献。原始代码可以在 此处找到。

  • Fuyu 使用基于 sentencepiece 的 tokenizer,模型为 Unigram。它支持 bytefallback,这对于 fast tokenizer 仅在 tokenizers==0.14.0 中可用。LlamaTokenizer 被用作 sentencepiece 的标准包装器。

  • 作者建议使用以下 prompt 进行图像字幕生成:f"Generate a coco-style caption.\\n"

FuyuConfig

class transformers.FuyuConfig

< >

( vocab_size: int | None = 262144 hidden_size: int | None = 4096 intermediate_size: int | None = 16384 num_hidden_layers: int | None = 36 num_attention_heads: int | None = 64 hidden_act: str | None = 'relu2' max_position_embeddings: int | None = 16384 image_size: int | None = 300 patch_size: int | None = 30 num_channels: int | None = 3 initializer_range: float | None = 0.02 layer_norm_eps: int | None = 1e-05 use_cache: bool | None = True tie_word_embeddings: bool | None = False rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict[str, transformers.modeling_rope_utils.RopeParameters] | None = None qk_layernorm: bool | None = True hidden_dropout: float | None = 0.0 attention_dropout: float | None = 0.0 pad_token_id: int | None = None bos_token_id: int | None = 1 eos_token_id: int | None = 2 image_token_id: int | None = 71011 text_config: dict | None = None **kwargs )

参数

  • vocab_size (int, optional, defaults to 262144) — Fuyu 模型词汇表大小。定义传递给 FuyuForCausalLMinputs_ids 可以表示的不同 token 的数量。
  • hidden_size (int, optional, defaults to 4096) — 隐藏表示的维度。
  • intermediate_size (int, optional, defaults to 16384) — MLP 表示的维度。
  • num_hidden_layers (int, optional, defaults to 36) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 64) — Transformer 编码器中每个注意力层的注意力头数量。
  • hidden_act (str or function, optional, defaults to "relu2") — 解码器中的非线性激活函数(函数或字符串)。
  • max_position_embeddings (int, optional, defaults to 16384) — 此模型可能使用的最大序列长度。
  • image_size (int, optional, defaults to 300) — 输入图像的大小。
  • patch_size (int, optional, defaults to 30) — 输入 Vision Transformer 编码的 patch 大小。
  • num_channels (int, optional, defaults to 3) — 输入图像的通道数。
  • initializer_range (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的截断正态分布初始化器的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-05) — rms 归一化层使用的 epsilon。
  • use_cache (bool, optional, defaults to True) — 模型是否应返回最后一个键/值注意力(并非所有模型都使用)。仅在 config.is_decoder=True 时相关。是否绑定权重嵌入。
  • tie_word_embeddings (bool, optional, defaults to False) — 是否绑定输入和输出嵌入。
  • rope_parameters (RopeParameters, optional) — 包含 RoPE 嵌入配置参数的字典。字典应包含 rope_theta 的值,以及如果您想将 RoPE 与更长的 max_position_embeddings 一起使用,可以选择性地包含用于缩放的参数。
  • qk_layernorm (bool, optional, defaults to True) — 在投影隐藏状态后是否对 Queries 和 Keys 进行归一化。
  • hidden_dropout (float, optional, defaults to 0.0) — 应用 MLP 到隐藏状态后的 dropout 比率。
  • attention_dropout (float, optional, defaults to 0.0) — 计算注意力分数后的 dropout 比率。
  • pad_token_id (int, optional) — 填充 token 的 ID。
  • bos_token_id (int, optional, defaults to 1) — 序列开始 token 的 ID。
  • eos_token_id (Union[int, list[int]], optional, defaults to 2) — 序列结束 token 的 ID。可选地,可以使用列表设置多个序列结束 token。
  • image_token_id (int, optional, defaults to 71011) — 图像占位符 token 的 ID。
  • text_config (dict, optional) — 用于初始化 language```Aut 的配置选项字典。

这是用于存储 FuyuForCausalLM 配置的类。它用于根据指定的参数实例化 Fuyu 模型,定义模型的架构。使用默认值实例化配置将产生与 adept/fuyu-8b 相似的配置。

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

>>> from transformers import FuyuConfig

>>> # Initializing a Fuyu fuyu-7b style configuration
>>> configuration = FuyuConfig()

FuyuModel

class transformers.FuyuModel

< >

( config: FuyuConfig )

参数

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

The Fuyu model which consists of a vision backbone and a language model, without a language modeling head.

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

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

forward

< >

( input_ids: torch.LongTensor | None = None image_patches: torch.Tensor | None = None image_patches_indices: torch.Tensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor, shape (batch_size, sequence_length), optional) — Input sequence tokens 的索引。默认情况下会忽略 padding。

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

    什么是 input IDs?

  • image_patches (torch.FloatTensor, shape (batch_size, num_total_patches, patch_size_ x patch_size x num_channels), optional) — 要用作连续嵌入的图像块。这些块将被展平然后投影到模型的隐藏大小。
  • image_patches_indices (torch.LongTensor, shape (batch_size, sequence_length), optional) — 图像块在 input_ids 张量中的索引张量。
  • attention_mask (torch.Tensor, shape (batch_size, sequence_length), optional) — 用于避免对 padding token 索引执行 attention 的掩码。掩码值选择在 [0, 1] 之间:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

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

    什么是 position IDs?

  • past_key_values (~cache_utils.Cache, optional) — 可以用于加速顺序解码的预计算隐藏状态(自 attention 块和交叉 attention 块中的 key 和 value)。这通常是在解码的先前阶段返回的 past_key_values,当 use_cache=Trueconfig.use_cache=True 时。

    仅允许使用 Cache 实例,请参阅我们的 kv cache 指南。如果未传递 past_key_values,则默认会初始化 DynamicCache

    模型将输出与输入相同的 cache 格式。

    如果使用 past_key_values,用户应只输入未处理的 input_ids(即其 past key value 状态未提供给此模型的那些),其形状为 (batch_size, unprocessed_length),而不是所有 input_ids 的形状 (batch_size, sequence_length)

  • inputs_embeds (torch.FloatTensor, shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以直接传入嵌入表示,而不是传入 input_ids。如果您希望对如何将 input_ids 索引转换为关联向量的控制程度超过模型的内部嵌入查找矩阵,这将非常有用。
  • use_cache (bool, optional) — 如果设置为 True,则会返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attention 张量。有关详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)

A transformers.modeling_outputs.CausalLMOutputWithPast or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (FuyuConfig) and inputs.

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits (形状为 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

The FuyuModel forward method, overrides the __call__ special method.

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

gather_continuous_embeddings

< >

( word_embeddings: Tensor continuous_embeddings: list image_patch_input_indices: Tensor )

参数

  • word_embeddings (torch.FloatTensor, shape (batch_size, sequence_length, hidden_size)) — 词嵌入张量。
  • continuous_embeddings (torch.FloatTensor, shape (batch_size, num_patches, hidden_size)) — 连续嵌入张量。列表的长度是批处理大小。每个条目的形状是 [num_image_embeddings, hidden],并且 num_image_embeddings 需要与该批次元素在 image_patch_input_indices 中的非负索引数量相匹配。
  • image_patch_input_indices (torch.LongTensor, shape (batch_size, sequence_length)) — 图像块在 input_ids 张量中的索引张量。

This function places the continuous_embeddings into the word_embeddings at the locations indicated by image_patch_input_indices. Different batch elements can have different numbers of continuous embeddings.

get_image_features

< >

( pixel_values: FloatTensor **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor, shape (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (FuyuConfig) and inputs.

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

  • pooler_output (torch.FloatTensor,形状为 (batch_size, hidden_size)) — 序列第一个 token(分类 token)在进一步通过用于辅助预训练任务的层后的最后一个隐藏状态。例如,对于 BERT 系列模型,这会返回经过线性层和 tanh 激活函数处理后的分类 token。线性层的权重是通过预训练期间的下一句预测(分类)目标来训练的。

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

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

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

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

get_placeholder_mask

< >

( input_ids: LongTensor inputs_embeds: FloatTensor image_features: FloatTensor )

input_idsinputs_embeds 获取多模态占位符掩码,并检查占位符 token 计数是否等于多模态特征的长度。如果长度不同,则会引发错误。

FuyuForCausalLM

class transformers.FuyuForCausalLM

< >

( config: FuyuConfig )

参数

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

Fuyu Model with a language modeling head on top for causal language model conditioned on image patches and text.

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

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

forward

< >

( input_ids: torch.LongTensor | None = None image_patches: torch.Tensor | None = None image_patches_indices: torch.Tensor | None = None attention_mask: torch.Tensor | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None use_cache: bool | None = None labels: torch.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None logits_to_keep: int | None = 0 **kwargs ) transformers.modeling_outputs.CausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    输入 ID 是什么?

  • image_patches (torch.FloatTensor of shape (batch_size, num_total_patches, patch_size_ x patch_size x num_channels), optional) — Image patches to be used as continuous embeddings. The patches are flattened and then projected to the hidden size of the model.
  • image_patches_indices (torch.LongTensor of shape (batch_size, sequence_length), optional) — Tensor of indices of the image patches in the input_ids tensor.
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    注意力掩码是什么?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1].

    位置 ID 是什么?

  • past_key_values (~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.text_config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.text_config.vocab_size].
  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
  • logits_to_keep (int, optional, defaults to 0) — If an int, compute logits for the last logits_to_keep tokens. If 0, calculate logits for all input_ids (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If a torch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).

返回

transformers.modeling_outputs.CausalLMOutputWithPast or tuple(torch.FloatTensor)

A transformers.modeling_outputs.CausalLMOutputWithPast or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (FuyuConfig) and inputs.

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits (形状为 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

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

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

The FuyuForCausalLM forward method, overrides the __call__ special method.

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

示例

>>> from transformers import FuyuProcessor, FuyuForCausalLM
>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO

>>> processor = FuyuProcessor.from_pretrained("adept/fuyu-8b")
>>> model = FuyuForCausalLM.from_pretrained("adept/fuyu-8b")

>>> url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bus.png"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> prompt = "Generate a coco-style caption.\n"

>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
>>> outputs = model(**inputs)

>>> generated_ids = model.generate(**inputs, max_new_tokens=7)
>>> generation_text = processor.batch_decode(generated_ids[:, -7:], skip_special_tokens=True)
>>> print(generation_text[0])
A blue bus parked on the side of a road.

FuyuImageProcessor

class transformers.FuyuImageProcessor

< >

( do_resize: bool = True size: dict[str, int] | None = None resample: Resampling = <Resampling.BILINEAR: 2> do_pad: bool = True padding_value: float = 1.0 padding_mode: str = 'constant' do_normalize: bool = True image_mean: float | list[float] = 0.5 image_std: float | list[float] = 0.5 do_rescale: bool = True rescale_factor: float = 0.00392156862745098 patch_size: dict[str, int] | None = None **kwargs )

参数

  • do_resize (bool, optional, defaults to True) — Whether to resize the image to size.
  • size (dict[str, int], optional, defaults to {"height" -- 1080, "width": 1920}): Dictionary in the format {"height": int, "width": int} specifying the size of the output image.
  • resample (PILImageResampling, optional, defaults to Resampling.BILINEAR) — PILImageResampling filter to use when resizing the image e.g. PILImageResampling.BILINEAR.
  • do_pad (bool, optional, defaults to True) — Whether to pad the image to size.
  • padding_value (float, optional, defaults to 1.0) — The value to pad the image with.
  • padding_mode (str, 可选, 默认值 "constant") — 填充图像时使用的填充模式。
  • do_normalize (bool, 可选, 默认值 True) — 是否对图像进行归一化。
  • image_mean (float, 可选, 默认值 0.5) — 归一化图像时使用的均值。
  • image_std (float, 可选, 默认值 0.5) — 归一化图像时使用的标准差。
  • do_rescale (bool, 可选, 默认值 True) — 是否对图像进行缩放。
  • rescale_factor (float, 可选, 默认值 1 / 255) — 缩放图像时使用的因子。
  • patch_size (dict[str, int], 可选, 默认值 {"height" -- 30, "width": 30}): 格式为 {"height": int, "width": int} 的字典,指定块的大小。

此类应处理 FuyuForCausalLM 主模型之前的图像处理部分。具体来说,它应该处理

  • 处理图像:输入一批图像。如果图像大小可变,则根据所需的块尺寸调整它们。图像输出始终是 img_h, img_w,尺寸为 (1080, 1920)

    然后,它使用 patchify_image 函数对这些图像进行分块。

  • 创建图像输入 ID:对于每个块,会给出一个占位符 ID,以识别这些块在 token 序列中的位置。对于可变大小的图像,每个块行都以换行符 ID 结束。

  • 图像块索引:对于每个图像块,代码会维护一个索引,以指示这些块应插入到 token 流中的位置。

__call__

< >

( 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] )

预处理单张或批量图像。

FuyuImageProcessor

class transformers.FuyuImageProcessorFast

< >

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

构造一个快速 Fuyu 图像处理器。

__call__

< >

( 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] )

预处理单张或批量图像。

FuyuProcessor

class transformers.FuyuProcessor

< >

( image_processor tokenizer **kwargs )

参数

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

构造一个 FuyuProcessor,它将图像处理器和分词器包装到一个处理器中。

FuyuProcessor 提供了 FuyuImageProcessorFasttokenizer_class 的所有功能。有关更多信息,请参阅 ~FuyuImageProcessorFast~tokenizer_class

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None text: str | list[str] | None = None **kwargs: typing_extensions.Unpack[transformers.models.fuyu.processing_fuyu.FuyuProcessorKwargs] ) FuyuBatchEncoding

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list, list, list], 可选) — 要预处理的图像。期望单个或一批图像,像素值范围为 0 到 255。如果传入像素值介于 0 和 1 之间的图像,请将 do_rescale 设置为 False
  • text (Union[str, list], 可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果您传递预分词输入,请将 is_split_into_words 设置为 True 以避免与批次输入混淆。
  • return_tensors (strTensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:

    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 NumPy np.ndarray 对象。

返回

FuyuBatchEncoding

一个 FuyuBatchEncoding,具有以下字段

  • input_ids — 要馈送到模型的 token ID 张量。在 text 不为 None 时返回。
  • image_patches — 图像块张量列表。在 images 不为 None 时返回。
  • image_patches_indices — 模型需要插入块嵌入的索引张量。
  • attention_mask — 指定模型应关注哪些 token 的索引列表,当 return_attention_mask=True 时返回。

在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.