Transformers 文档
Fuyu
并获得增强的文档体验
开始使用
该模型于 2023-10-17 发布,并于 2023-10-19 添加到 Hugging Face Transformers。
Fuyu
概述
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',这将由AutoModelAPI 用于将检查点从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)
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
< source >( 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 模型词汇表大小。定义传递给 FuyuForCausalLM 的inputs_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 (
strorfunction, 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 toTrue) — 模型是否应返回最后一个键/值注意力(并非所有模型都使用)。仅在config.is_decoder=True时相关。是否绑定权重嵌入。 - tie_word_embeddings (
bool, optional, defaults toFalse) — 是否绑定输入和输出嵌入。 - rope_parameters (
RopeParameters, optional) — 包含 RoPE 嵌入配置参数的字典。字典应包含rope_theta的值,以及如果您想将 RoPE 与更长的max_position_embeddings一起使用,可以选择性地包含用于缩放的参数。 - qk_layernorm (
bool, optional, defaults toTrue) — 在投影隐藏状态后是否对 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 的文档。
FuyuModel
class transformers.FuyuModel
< source >( 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
< source >( 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()。
- 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。
- position_ids (
torch.LongTensor, shape(batch_size, sequence_length), optional) — 每个输入序列 token 在位置嵌入中的索引。选择范围为[0, config.n_positions - 1]。 - past_key_values (
~cache_utils.Cache, optional) — 可以用于加速顺序解码的预计算隐藏状态(自 attention 块和交叉 attention 块中的 key 和 value)。这通常是在解码的先前阶段返回的past_key_values,当use_cache=True或config.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
< source >( 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
< source >( pixel_values: FloatTensor **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor, shape(batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(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
< source >( input_ids: LongTensor inputs_embeds: FloatTensor image_features: FloatTensor )
从 input_ids 或 inputs_embeds 获取多模态占位符掩码,并检查占位符 token 计数是否等于多模态特征的长度。如果长度不同,则会引发错误。
FuyuForCausalLM
class transformers.FuyuForCausalLM
< source >( 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.CausalLMOutputWithPast 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof 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.
- image_patches (
torch.FloatTensorof 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.LongTensorof shape(batch_size, sequence_length), optional) — Tensor of indices of the image patches in the input_ids tensor. - attention_mask (
torch.Tensorof 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.LongTensorof 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]. - 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 thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - labels (
torch.LongTensorof 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 (seeinput_idsdocstring). Tokens with indices set to-100are 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. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder 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 to0) — If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_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 atorch.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 toTrue) — Whether to resize the image tosize. - 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 toResampling.BILINEAR) —PILImageResamplingfilter to use when resizing the image e.g.PILImageResampling.BILINEAR. - do_pad (
bool, optional, defaults toTrue) — Whether to pad the image tosize. - 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 )
构造一个 FuyuProcessor,它将图像处理器和分词器包装到一个处理器中。
FuyuProcessor 提供了 FuyuImageProcessorFast 和 tokenizer_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 (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt': 返回 PyTorchtorch.Tensor对象。'np': 返回 NumPynp.ndarray对象。
返回
FuyuBatchEncoding
一个 FuyuBatchEncoding,具有以下字段
- input_ids — 要馈送到模型的 token ID 张量。在
text不为None时返回。 - image_patches — 图像块张量列表。在
images不为None时返回。 - image_patches_indices — 模型需要插入块嵌入的索引张量。
- attention_mask — 指定模型应关注哪些 token 的索引列表,当
return_attention_mask=True时返回。