Transformers documentation

KOSMOS-2.5

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2023-09-20 在 HF papers 上发布,并于 2025-08-19 贡献至 Hugging Face Transformers。

FlashAttention SDPA

KOSMOS-2.5

Kosmos-2.5 模型由微软在 KOSMOS-2.5: A Multimodal Literate Model 中提出。

该论文的摘要如下:

我们提出了 Kosmos-2.5,一种用于机器阅读文本密集型图像的多模态识读模型。Kosmos-2.5 在大规模文本密集型图像上进行预训练,在两个不同但相互协作的转录任务中表现出色:(1) 生成具有空间感知能力的文本块,其中每个文本块都会被分配其在图像中的空间坐标;(2) 生成结构化的文本输出,将样式和结构捕获到 markdown 格式中。这种统一的多模态识读能力是通过共享的 Transformer 架构、特定于任务的提示词以及灵活的文本表示来实现的。我们在端到端的文档级文本识别和图像到 markdown 文本生成任务上对 Kosmos-2.5 进行了评估。此外,该模型可以通过监督微调,利用不同的提示词轻松适配任何文本密集型图像理解任务,使其成为处理富含文本的图像的实际应用的通用工具。这项工作也为未来多模态大语言模型的扩展奠定了基础。

drawing drawing Overview of tasks that KOSMOS-2.5 can handle. Taken from the original paper.

以下示例演示了如何使用 AutoModel 为 Markdown 和 OCR 任务生成内容。

AutoModel - Markdown 任务
AutoModel - OCR 任务
import requests
from PIL import Image

from transformers import AutoProcessor, Kosmos2_5ForConditionalGeneration


repo = "microsoft/kosmos-2.5"
model = Kosmos2_5ForConditionalGeneration.from_pretrained(repo, device_map="auto")
processor = AutoProcessor.from_pretrained(repo)

# sample image
url = "https://huggingface.co/microsoft/kosmos-2.5/resolve/main/receipt_00008.png"
image = Image.open(requests.get(url, stream=True).raw)

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

height, width = inputs.pop("height"), inputs.pop("width")
raw_width, raw_height = image.size
scale_height = raw_height / height
scale_width = raw_width / width

inputs = {k: v.to(model.device) if v is not None else None for k, v in inputs.items()}
inputs["flattened_patches"] = inputs["flattened_patches"].to(dtype)
generated_ids = model.generate(
    **inputs,
    max_new_tokens=1024,
)

generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
print(generated_text[0])

聊天版本

作者还发布了 Kosmos-2.5 Chat,这是一个针对文档理解进行优化的聊天版本。您可以这样使用它:

import requests
import torch
from PIL import Image

from transformers import AutoProcessor, Kosmos2_5ForConditionalGeneration


repo = "microsoft/kosmos-2.5-chat"
dtype = torch.bfloat16

model = Kosmos2_5ForConditionalGeneration.from_pretrained(repo,
                                                          device_map="auto",
                                                          attn_implementation="flash_attention_2")
processor = AutoProcessor.from_pretrained(repo)

# sample image
url = "https://huggingface.co/microsoft/kosmos-2.5/resolve/main/receipt_00008.png"

image = Image.open(requests.get(url, stream=True).raw)

question = "What is the sub total of the receipt?"
template = "<md>A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. USER: {} ASSISTANT:"
prompt = template.format(question)
inputs = processor(text=prompt, images=image, return_tensors="pt").to(model.device)

height, width = inputs.pop("height"), inputs.pop("width")
raw_width, raw_height = image.size
scale_height = raw_height / height
scale_width = raw_width / width

inputs = {k: v.to(model.device) if v is not None else None for k, v in inputs.items()}
inputs["flattened_patches"] = inputs["flattened_patches"].to(dtype)
generated_ids = model.generate(
    **inputs,
    max_new_tokens=1024,
)

generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
print(generated_text[0])

Kosmos2_5Config

class transformers.Kosmos2_5Config

< >

( 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 = Nonelatent_query_num: int = 2048tie_word_embeddings: bool = True )

参数

  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • latent_query_num (int,可选,默认为 2048) — 用于表示文本解码器组件中所用图像特征的潜在查询 token 数量。
  • tie_word_embeddings (bool,可选,默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 Kosmos2 5 模型配置的类。它根据指定的参数实例化 Kosmos2 5 模型,并定义模型架构。使用默认值实例化配置将得到与 microsoft/kosmos-2.5 类似的配置。

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

Kosmos2_5TextConfig

class transformers.Kosmos2_5TextConfig

< >

( 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 = 108481max_position_embeddings: int = 4096embed_dim: int = 1536layers: int = 24ffn_dim: int = 6144attention_heads: int = 16activation_function: str = 'gelu'dropout: float | int = 0.1attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0layerdrop: float | int = 0.0layer_norm_eps: float = 1e-05init_std: float = 0.02scale_embedding: bool = Trueuse_cache: bool = Truetie_word_embeddings: bool = Truepad_token_id: int | None = 1bos_token_id: int | None = 0eos_token_id: int | list[int] | None = 2 )

参数

  • vocab_size (int,可选,默认值为 108481) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • max_position_embeddings (int,可选,默认为 4096) — 该模型可能使用的最大序列长度。
  • embed_dim (int,可选,默认为 1536) — 嵌入和隐藏状态的维度。
  • layers (int,可选,默认为 24) — Transformer 解码器中的隐藏层数。
  • ffn_dim (int,可选,默认为 6144) — MLP 表示的维度。
  • attention_heads (int, 可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • activation_function (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu" 等。
  • dropout (Union[float, int],可选,默认为 0.1) — 所有 dropout 层的比率。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • activation_dropout (Union[float, int],可选,默认为 0.0) — 全连接层中激活值的 dropout 比率。
  • layerdrop (Union[float, int],可选,默认为 0.0) — LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](见 https://huggingface.co/papers/1909.11556)。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • init_std (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • scale_embedding (bool,可选,默认为 True) — 是否通过将嵌入除以 sqrt(d_model) 来对嵌入进行缩放。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • tie_word_embeddings (bool,可选,默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。
  • pad_token_id (int,可选,默认为 1) — 词表中用于填充的 token id。
  • bos_token_id (int,可选,默认为 0) — 词汇表中用于表示流起始的 Token id。
  • eos_token_id (Union[int, list[int]],可选,默认为 2) — 词汇表中用于表示流结束(end-of-stream)的 token id。

这是用于存储 Kosmos2 5 模型配置的类。它根据指定的参数实例化 Kosmos2 5 模型,并定义模型架构。使用默认值实例化配置将得到与 microsoft/kosmos-2.5 类似的配置。

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

Kosmos2_5VisionConfig

class transformers.Kosmos2_5VisionConfig

< >

( 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 = 1536patch_embed_hidden_size: int = 768intermediate_size: int = 3968head_dim: int = 64num_hidden_layers: int = 18num_attention_heads: int = 24dense_act_fn: str = 'gelu_new'layer_norm_eps: float = 1e-06dropout_rate: float | int = 0.0attention_dropout: float | int = 0.0max_num_patches: int = 4096initializer_factor: float = 1.0initializer_range: float = 0.02 )

参数

  • hidden_size (int,可选,默认为 1536) — 隐藏表示的维度。
  • patch_embed_hidden_size (int,可选,默认为 768) — Transformer 编码器中输入 patch_embedding 层的维度。
  • intermediate_size (int,可选,默认为 3968) — MLP 表示的维度。
  • head_dim (int,可选,默认为 64) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads
  • num_hidden_layers (int, 可选,默认为 18) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads(int,可选,默认值为 24)— Transformer 解码器中每个注意力层的注意力头数量。
  • dense_act_fn (str 或 function,可选,默认为 "gelu_new") — 编码器和池化器中使用的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu"、"relu"、"selu" 以及 "gelu_new" 或 "gelu"。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • dropout_rate (Union[float, int],可选,默认为 0.0) — 所有 dropout 层的比率。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • max_num_patches (int,可选,默认值为 4096) — 模型支持的最大序列长度(此处指 patch 数量)。
  • initializer_factor (float,可选,默认为 1.0) — 用于初始化所有权重矩阵的系数(应保持为 1,内部用于初始化测试)。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 Kosmos2 5 模型配置的类。它根据指定的参数实例化 Kosmos2 5 模型,并定义模型架构。使用默认值实例化配置将得到与 microsoft/kosmos-2.5 类似的配置。

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

示例:

>>> from transformers import Kosmos2_5VisionConfig, Kosmos2_5VisionModel

>>> # Initializing a Kosmos2_5VisionConfig with microsoft/kosmos-2.5 style configuration
>>> configuration = Kosmos2_5VisionConfig()

>>> # Initializing a Kosmos2_5VisionModel (with random weights) from the microsoft/kosmos-2.5 style configuration
>>> model = Kosmos2_5VisionModel(configuration)

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

Kosmos2_5ImageProcessor

class transformers.Kosmos2_5ImageProcessor

< >

( **kwargs: *<class 'transformers.models.kosmos2_5.image_processing_kosmos2_5.Kosmos2_5ImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • 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) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 None) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (Dict[str, *kwargs*, int],可选,默认为 {"height" -- 16, "width": 16}): 用于图像的 patch 大小。根据 Kosmos2_5 论文和代码,patch 大小为 16x16。
  • max_patches (int, kwargs, 可选,默认值为 4096) — 根据 KOSMOS 2.5 论文,从图像中提取的最大 patch 数量。

构建一个 image_processor_class 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.kosmos2_5.image_processing_kosmos2_5.Kosmos2_5ImageProcessorKwargs'> ) → ~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。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (Dict[str, *kwargs*, int],可选,默认为 {"height" -- 16, "width": 16}): 用于图像的 patch 大小。根据 Kosmos2_5 论文和代码,patch 大小为 16x16。
  • max_patches (int, kwargs, 可选,默认值为 4096) — 根据 KOSMOS 2.5 论文,从图像中提取的最大 patch 数量。

返回值

~image_processing_base.BatchFeature

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

Kosmos2_5ImageProcessorPil

class transformers.Kosmos2_5ImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.kosmos2_5.image_processing_pil_kosmos2_5.Kosmos2_5ImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • 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) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 None) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (Dict[str, *kwargs*, int],可选,默认为 {"height" -- 16, "width": 16}): 用于图像的 patch 大小。根据 Kosmos2_5 论文和代码,patch 大小为 16x16。
  • max_patches (int, kwargs, 可选,默认值为 4096) — 根据 KOSMOS 2.5 论文,从图像中提取的最大 patch 数量。

构建一个 image_processor_class 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.kosmos2_5.image_processing_pil_kosmos2_5.Kosmos2_5ImageProcessorKwargs'> ) → ~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。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • patch_size (Dict[str, *kwargs*, int],可选,默认为 {"height" -- 16, "width": 16}): 用于图像的 patch 大小。根据 Kosmos2_5 论文和代码,patch 大小为 16x16。
  • max_patches (int, kwargs, 可选,默认值为 4096) — 根据 KOSMOS 2.5 论文,从图像中提取的最大 patch 数量。

返回值

~image_processing_base.BatchFeature

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

Kosmos2_5Processor

class transformers.Kosmos2_5Processor

< >

( image_processortokenizernum_image_tokens: int = 2048 )

参数

  • image_processor (image_processor_class) — 图像处理器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。
  • num_image_tokens (int,可选,默认为 2048) — 用作占位符的图像 token 数量。

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

Kosmos2_5Processor 提供了 image_processor_class 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~image_processor_class 和 ~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] = Nonetext: str | list[str] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> ) → ~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。
  • text (Union[str, list[str]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • 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 类。

返回值

~image_processing_base.BatchFeature

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

Kosmos2_5Model

class transformers.Kosmos2_5Model

< >

( config: Kosmos2_5Config )

参数

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

用于生成文本和图像特征的 KOSMOS-2.5 模型。该模型由视觉编码器和语言模型组成。

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

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

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Noneflattened_patches: typing.Optional[torch.Tensor] = Nonewidth: typing.Optional[torch.Tensor] = Noneheight: typing.Optional[torch.Tensor] = Noneimage_embeds_position_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneimage_embeds: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → transformers.models.kosmos2_5.modeling_kosmos2_5.Kosmos2_5ModelOutput or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length)) — 输入序列中各 token 在词汇表中的索引。如果您提供了填充,默认情况下会被忽略。

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

    什么是输入 ID?

  • flattened_patches(形状为 (batch_size, max_patches, 2 + patch_height * patch_width * image_channels) 的 torch.Tensor) — 图像的展平补丁。flattened_patches 可以通过 AutoImageProcessor 获取。详情请参见 Kosmos2_5ImageProcessor.call()。
  • width (torch.Tensor,形状为 (batch_size,)) — 批次中每张图片在调整大小之前的原始宽度。可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 Kosmos2_5ImageProcessor.call()。
  • height (torch.Tensor,形状为 (batch_size,)) — 批次中每张图片在调整大小之前的原始高度。可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 Kosmos2_5ImageProcessor.call()。
  • image_embeds_position_mask (torch.Tensor 形状为 (batch_size, sequence_length), 可选) — 用于指示序列中插入图像特征位置的掩码。掩码值取自 [0, 1]:
    • 1 用于指定放置图像特征的位置,
    • 对于非图像特征的位置(即文本标记),值为 0。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • past_key_values (Cache 长度为 config.n_layers ,每个元组包含 4 个形状为 (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — 包含注意力块中预计算的键和值隐藏状态。可用于加速解码。

    如果使用了 past_key_values,用户可以选择仅输入最后一个 decoder_input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, 1),而不是输入所有形状为 (batch_size, sequence_length) 的 decoder_input_ids。

  • image_embeds — (torch.Tensor,形状为 (batch_size, latent_query_num, hidden_size),可选): Kosmos2ImageToTextProjection 输出的隐藏状态序列。
  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.max_position_embeddings - 1].

    什么是位置 ID?

  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。

返回值

transformers.models.kosmos2_5.modeling_kosmos2_5.Kosmos2_5ModelOutput 或 tuple(torch.Tensor)

transformers.models.kosmos2_5.modeling_kosmos2_5.Kosmos2_5ModelOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(<class 'transformers.models.kosmos2_5.configuration_kosmos2_5.Kosmos2_5Config'>)和输入。

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

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

  • width(形状为 (batch_size,) 的 torch.Tensor)— 批次中每张图片在调整大小之前的原始宽度。

  • height(形状为 (batch_size,) 的 torch.Tensor)— 批次中每张图片在调整大小之前的原始高度。

  • image_embeds(形状为 (batch_size, latent_query_num, hidden_size) 的 torch.Tensor,可选)— Kosmos2ImageToTextProjection 输出的隐藏状态序列。

  • projection_attentions (tuple(torch.Tensor),可选) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

  • vision_model_output(BaseModelOutputWithPooling, 可选) — Kosmos2VisionModel 的输出。

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

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

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

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

示例:

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

>>> model = Kosmos2_5Model.from_pretrained("microsoft/kosmos2.5")
>>> processor = AutoProcessor.from_pretrained("microsoft/kosmos2.5")

>>> url = "https://huggingface.co/microsoft/kosmos2.5/resolve/main/snowman.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> text = (
...     "<grounding> An image of<phrase> a snowman</phrase><object><patch_index_0044><patch_index_0863>"
...     "</object> warming himself by<phrase> a fire</phrase><object><patch_index_0005><patch_index_0911>"
...     "</object>"
... )

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

>>> last_hidden_state = model(
...     pixel_values=inputs["pixel_values"],
...     input_ids=inputs["input_ids"],
...     attention_mask=inputs["attention_mask"],
...     image_embeds_position_mask=inputs["image_embeds_position_mask"],
... ).last_hidden_state
>>> list(last_hidden_state.shape)
[1, 91, 2048]

Kosmos2_5ForConditionalGeneration

class transformers.Kosmos2_5ForConditionalGeneration

< >

( config: Kosmos2_5Config )

参数

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

KOSMOS-2.5 模型,用于根据图像生成文本和边界框。该模型由视觉编码器和语言模型组成。

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

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

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Noneflattened_patches: typing.Optional[torch.Tensor] = Nonewidth: typing.Optional[torch.Tensor] = Noneheight: typing.Optional[torch.Tensor] = Noneimage_embeds_position_mask: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneimage_embeds: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → transformers.models.kosmos2_5.modeling_kosmos2_5.Kosmos2_5ForConditionalGenerationModelOutput or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length)) — 输入序列中各 token 在词汇表中的索引。如果您提供了填充,默认情况下会被忽略。

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

    什么是输入 ID?

  • flattened_patches(形状为 (batch_size, max_patches, 2 + patch_height * patch_width * image_channels) 的 torch.Tensor) — 图像的展平补丁。flattened_patches 可以通过 AutoImageProcessor 获取。详情请参见 Kosmos2_5ImageProcessor.call()。
  • width (torch.Tensor,形状为 (batch_size,)) — 批次中每张图片在调整大小之前的原始宽度。可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 Kosmos2_5ImageProcessor.call()。
  • height (torch.Tensor,形状为 (batch_size,)) — 批次中每张图片在调整大小之前的原始高度。可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 Kosmos2_5ImageProcessor.call()。
  • image_embeds_position_mask (torch.Tensor 形状为 (batch_size, sequence_length), 可选) — 用于指示序列中插入图像特征位置的掩码。掩码值取自 [0, 1]:
    • 1 用于指定放置图像特征的位置,
    • 对于非图像特征的位置(即文本标记),值为 0。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • past_key_values (Cache 长度为 config.n_layers ,每个元组包含 4 个形状为 (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — 包含注意力块中预计算的键和值隐藏状态。可用于加速解码。

    如果使用了 past_key_values,用户可以选择仅输入最后一个 decoder_input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, 1),而不是输入所有形状为 (batch_size, sequence_length) 的 decoder_input_ids。

  • image_embeds — (torch.Tensor,形状为 (batch_size, latent_query_num, hidden_size),可选): Kosmos2ImageToTextProjection 输出的隐藏状态序列。
  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.max_position_embeddings - 1].

    什么是位置 ID?

  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算从左到右的语言建模损失(下一个词预测)的标签。索引应位于 [-100, 0, ..., config.vocab_size] 范围内(参见 input_ids 的文档字符串)。索引设置为 -100 的 token 将被 忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。

返回值

transformers.models.kosmos2_5.modeling_kosmos2_5.Kosmos2_5ForConditionalGenerationModelOutput 或 tuple(torch.Tensor)

transformers.models.kosmos2_5.modeling_kosmos2_5.Kosmos2_5ForConditionalGenerationModelOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(<class 'transformers.models.kosmos2_5.configuration_kosmos2_5.Kosmos2_5Config'>)和输入。

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

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

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

  • width(形状为 (batch_size,) 的 torch.Tensor)— 批次中每张图片在调整大小之前的原始宽度。

  • height(形状为 (batch_size,) 的 torch.Tensor)— 批次中每张图片在调整大小之前的原始高度。

  • image_embeds(形状为 (batch_size, latent_query_num, hidden_size) 的 torch.Tensor,可选)— Kosmos2ImageToTextProjection 输出的隐藏状态序列。

  • projection_attentions (tuple(torch.Tensor),可选) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

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

  • vision_model_output(BaseModelOutputWithPooling, 可选) — Kosmos2VisionModel 的输出。

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

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

Kosmos2_5ForConditionalGeneration 的 forward 方法会重写 __call__ 特殊方法。

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

示例:

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

>>> repo = "microsoft/kosmos-2.5"
>>> device = "cuda:0"
>>> dtype = torch.bfloat16 # torch.float16
>>> model = Kosmos2_5ForConditionalGeneration.from_pretrained(repo, device_map=device, dtype=dtype)
>>> processor = AutoProcessor.from_pretrained(repo)

>>> url = "https://huggingface.co/microsoft/kosmos-2.5/resolve/main/receipt_00008.png"

>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> prompt = "<ocr>" # <md>

>>> inputs = processor(text=prompt, images=image, return_tensors="pt")
>>> height, width = inputs.pop("height"), inputs.pop("width")
>>> inputs = {k: v.to(device) if v is not None else None for k, v in inputs.items()}
>>> inputs["flattened_patches"] = inputs["flattened_patches"].to(dtype)

>>> generated_ids = model.generate(**inputs,max_new_tokens=1024)
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
>>> generated_text
'<ocr><bbox><x_53><y_573><x_69><y_606></bbox>1\n<bbox><x_79><y_573><x_464><y_612></bbox>[REG] BLACK SAKURA\n<bbox><x_690><y_569><x_810><y_606></bbox>45,455\n<bbox><x_53><y_614><x_69><y_648></bbox>1\n<bbox><x_79><y_614><x_468><y_650></bbox>COOKIE DOH SAUCES\n<bbox><x_788><y_609><x_812><y_644></bbox>0\n<bbox><x_50><y_658><x_69><y_693></bbox>1\n<bbox><x_79><y_658><x_358><y_693></bbox>NATA DE COCO\n<bbox><x_790><y_652><x_814><y_687></bbox>0\n<bbox><x_31><y_742><x_820><y_781></bbox>Sub Total 45,455\n<bbox><x_27><y_781><x_822><y_827></bbox>PB1 (10%) 4,545\n<bbox><x_27><y_826><x_824><y_872></bbox>Rounding 0\n<bbox><x_24><y_872><x_827><y_921></bbox>Total 50,000\n<bbox><x_17><y_1056><x_836><y_1108></bbox>Card Payment 50,000\n'
Update on GitHub