Transformers documentation

GraniteDocling

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

and get access to the augmented documentation experience

to get started

该模型于 2026-11-12 贡献至 Hugging Face Transformers。

FlashAttention SDPA

GraniteDocling

GraniteDocling 是一个用于文档转换的视觉语言模型。给定一张页面图像,它会生成 DocLang(<doclang>):按阅读顺序排列的布局元素及其边界框,以及其中包含的文本、表格、公式和代码。DocLang 是标记语言;Docling(docling-core)会将预测结果解析为文档,并可导出为 Markdown、HTML、JSON 及其他格式。

该页面被分割为 512x512 像素的图块,这些图块按照最匹配其宽高比的网格进行排列;当存在多个图块时,还会附带一个整页的缩略图。视觉编码器对每个图块进行嵌入,像素混洗连接器将视觉块映射为图像标记。视觉编码器的中间状态也会被投影,并在第一个解码器层之后添加到图像标记中。随后,一个稠密的 Granite 风格文本解码器生成 DocLang。

GraniteDocling 以两个模型发布。500M 模型每个图块使用 64 个图像 token,并且可以将密集页面切换为 256 个;路由器会针对每个页面进行选择。2B 模型使用 2 的像素混洗比率,即每个图块 256 个图像 token,与 500M 模型的细粒度路径具有相同的密度。

Docling 项目创建了 GraniteDocling。这两个模型均发布在 IBM Granite 组织下。

GraniteDocling 与 granite-docling-258M 采用不同的架构,后者仍通过 Idefics3 进行加载。

该模型由Docling 团队贡献。

点击右侧边栏中的 GraniteDocling 模型,以查看将 GraniteDocling 应用于不同文档转换任务的更多示例。

使用技巧

  • 通过聊天模板向模型发出提示。<doclang> 会转换整个页面。在末尾添加一个括号列表以请求部分元素,例如 <doclang> [<ocr>] 或 <doclang> [<ocr>, <layout>, <picture>]。
  • 如果要将字符串解析为 DocLang,请使用 skip_special_tokens=False 进行解码。否则,专用标记令牌将被移除。
  • 在 500M 模型上,对于密集页面(小字号、长表格、多栏文本),请传入 fine_route=True。该路径使用的图像 token 数量是原来的四倍,因此提示词更长,推理速度也更慢。2B 模型本身已采用该 token 密度,且没有第二条路径,因此对它传入 fine_route=True 会引发错误。
  • 500M 模型包含一个密度路由器,它会为您做出决定:predict_fine_route() 返回批次中哪些页面需要走精细路径。

以下示例将 Docling Technical Report(arXiv:2408.09869)的第 1 页进行转换。只需更改文本提示即可切换任务;模型会返回经过 DocLang 过滤、仅包含所请求元素的输出。

任务提示
完整页面<doclang>
OCR<doclang> [<ocr>]
布局<doclang> [<layout>]
表格<doclang> [<table>]
公式<doclang> [<formula>]
代码<doclang> [<code>]
图表<doclang> [<chart>]
图片<doclang> [<picture>]
组合<doclang> [<ocr>, <layout>, <picture>]

完整页面

<doclang> 会转换整个页面:布局、文本、表格、公式、代码、图表和图片。

Pipeline
AutoModel
from transformers import pipeline

pipe = pipeline(
    task="image-text-to-text",
    model="ibm-granite/granite-for-docling-500m",
)
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png"},
            {"type": "text", "text": "<doclang>"},
        ],
    }
]
pipe(text=messages, max_new_tokens=4096, return_full_text=False, skip_special_tokens=False)

若要仅转换部分元素,请将文本提示词更改为上表中的某一项,例如 <doclang> [<ocr>, <layout>, <picture>]。其余部分保持不变。

密集页面:精细路径

细粒度连接路径每个图块消耗的图像 token 数量是普通路径的四倍,这有助于处理小字号文本、长表格和多栏文本。在每次调用时通过 fine_route=True 选择该路径:

inputs = processor.apply_chat_template(
    conversation,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"fine_route": True},
).to(model.device)
output = model.generate(**inputs, max_new_tokens=4096)

500M 模型(已设置 config.density_router_hidden_size)会根据其默认图像 token 预测哪些页面需要走精细路径:

needs_fine = model.model.predict_fine_route(inputs["pixel_values"], inputs["pixel_attention_mask"])  # (batch_size,) bool
if needs_fine[0]:
    inputs = processor.apply_chat_template(
        conversation,
        add_generation_prompt=True,
        tokenize=True,
        return_dict=True,
        return_tensors="pt",
        processor_kwargs={"fine_route": True},
    ).to(model.device)
output = model.generate(**inputs, max_new_tokens=4096)

批量推理

由于不同页面具有不同的图块网格,pixel_values 会被填充至批次中最大的图块数量。pixel_attention_mask 用于标记真实的图块,模型会丢弃填充部分。

pages = [
    "https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png",
    "https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png",
]
conversations = [
    [{"role": "user", "content": [{"type": "image", "url": url}, {"type": "text", "text": "<doclang>"}]}]
    for url in pages
]
inputs = processor.apply_chat_template(
    conversations,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"padding": True},
).to(model.device)

output = model.generate(**inputs, max_new_tokens=4096)
for row in output:
    doclang = processor.decode(row[inputs["input_ids"].shape[1] :], skip_special_tokens=False)
    print(doclang.removesuffix(processor.tokenizer.eos_token).strip())

在 processor_kwargs 中添加 "fine_route": True,可将整个批次路由至精细路径;此时处理器会返回 tile_fine_mask。由于一个批次只能走一条路径,因此应将路由器发送至精细路径的页面作为独立的批次运行。

使用 Docling 导出 DocLang

docling-core 将 AutoModel 示例中的 doclang 字符串解析为 DoclingDocument,您可以将其序列化为所需的任何格式。

from pathlib import Path
from docling_core.transforms.deserializer.doclang import DocLangDocDeserializer

document = DocLangDocDeserializer().deserialize_str(doclang)

print(document.export_to_markdown())
print(document.export_to_html())
print(document.export_to_dict())

document.save_as_markdown(Path("page.md"))
document.save_as_html(Path("page.html"))
document.save_as_json(Path("page.json"))

DocLang 规范和 doclang 工具包(validate / pack)位于 doclang-project/doclang。反序列化器和 DoclingDocument 导出器位于 docling-core 中。

备注

  • 完整页面通常较长:请将max_new_tokens的预算设置为数千,否则 DocLang 会被静默截断。
  • Tiles 为 512x512,按照最匹配页面宽高比的网格进行布局,并受 max_patches(默认值为 32)和每侧 16 个 tile 的限制。如果页面可以容纳在一个 tile 中,则不会生成缩略图。
  • 检查点可以在其图像处理器配置中携带一条分布规则:对于宽幅横向页面(dense_min_aspect < 宽/高 <= dense_max_aspect),使用 dense_max_patches 个图块,而不是 max_patches,以避免 max_patches 网格将其缩小到低于 dense_max_scale。报纸跨页是典型场景。该规则默认关闭(dense_max_patches=0),且必须与检查点训练时使用的设置一致。
  • 在 500M 模型上,细粒度路径将每个图块的图像 token 数量增加四倍,从 64 增至 256。请仅对密集页面使用该路径,或通过 predict_fine_route() 让路由器自行决定。2B 模型始终使用每个图块 256 个图像 token(像素重排比例为 2)。

GraniteDoclingConfig

类 transformers.GraniteDoclingConfig

< >

( 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 = Noneimage_token_id: int = 100337tie_word_embeddings: bool = Trueuse_cache: bool = Truepad_token_id: int | None = 100256density_router_hidden_size: int | None = Nonedensity_router_threshold: float = 0.4density_router_loss_weight: float = 0.1 )

参数

  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • image_token_id (int,可选,默认为 100337) — 用作输入图像占位符的图像标记索引。
  • tie_word_embeddings (bool,可选,默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • pad_token_id (int,可选,默认为 100256) — 词汇表中用于填充的 Token id。
  • density_router_hidden_size (int, 可选) — 密度路由器的隐藏层大小,用于根据视觉编码器特征预测页面是否需要细粒度连接器路径。当值为 None 时,不会构建路由器。
  • density_router_threshold (float,可选,默认值为 0.4) — 密度路由器选择细粒度连接路径的概率阈值。
  • density_router_loss_weight (float, 可选, 默认值为 0.1) — 当提供 router_labels 时,密度路由器损失的权重。

这是用于存储 GraniteDoclingModel 配置的类。它根据指定的参数实例化 Granite Docling 模型,并定义模型架构。使用默认值实例化配置将生成与 ibm-granite/granite-for-docling-500m 类似的配置。

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

GraniteDoclingTextConfig

类 transformers.GraniteDoclingTextConfig

< >

( 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 = 133800hidden_size: int = 1024intermediate_size: int = 2048num_hidden_layers: int = 28num_attention_heads: int = 16num_key_value_heads: int | None = 4hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int | None = 100256bos_token_id: int | None = 100257eos_token_id: int | list[int] | None = 100257tie_word_embeddings: bool = Truerope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falseattention_dropout: float | int = 0.0mlp_bias: bool = Falseembedding_multiplier: float | int = 12.0logits_scaling: float | int = 4.0residual_multiplier: float | int = 0.263attention_multiplier: float | int = 0.015625 )

参数

  • vocab_size (int, 可选, 默认为 133800) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 的数量。
  • hidden_size (int,可选,默认为 1024) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 2048) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 28) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选,默认为 4) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果 num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则将使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 num_attention_heads。
  • hidden_act (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 32768) — 该模型可能使用的最大序列长度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rms_norm_eps (float,可选,默认为 1e-05) — RMS 归一化层使用的 epsilon 值。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • pad_token_id (int,可选,默认为 100256) — 词汇表中用于填充的 Token id。
  • bos_token_id (int,可选,默认为 100257) — 词汇表中用于表示流起始的 Token id。
  • eos_token_id (Union[int, list[int]],可选,默认为 100257) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • tie_word_embeddings (bool,可选,默认为 True) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • mlp_bias (bool,可选,默认为 False) — 是否在 MLP 层的 up_proj、down_proj 和 gate_proj 层中使用偏置。
  • embedding_multiplier (Union[float, int],可选,默认为 12.0) — 应用于词嵌入的缩放因子。用于根据隐藏层大小对嵌入进行缩放。
  • logits_scaling (Union[float, int],可选,默认为 4.0) — 在计算概率分布之前应用于输出 logits 的缩放因子。
  • residual_multiplier (Union[float, int],可选,默认为 0.263) — 应用于残差连接的缩放因子。
  • attention_multiplier (Union[float, int],可选,默认为 0.015625) — 应用于注意力权重的缩放因子。

这是用于存储 GraniteDoclingModel 配置的类。它根据指定的参数实例化 Granite Docling 模型,并定义模型架构。使用默认值实例化配置将生成与 ibm-granite/granite-for-docling-500m 类似的配置。

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

>>> from transformers import GraniteDoclingTextModel, GraniteDoclingTextConfig

>>> # Initializing a GraniteDoclingText granite_docling_text-3b style configuration
>>> configuration = GraniteDoclingTextConfig()

>>> # Initializing a model from the granite_docling_text-7b style configuration
>>> model = GraniteDoclingTextModel(configuration)

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

GraniteDoclingVisionConfig

类 transformers.GraniteDoclingVisionConfig

< >

( 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 = 768intermediate_size: int = 3072num_hidden_layers: int = 12num_attention_heads: int = 12num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 512patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'gelu_pytorch_tanh'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0initializer_range: float = 0.02out_hidden_size: int = 1024scale_factor: int = 4deepstack_visual_indexes: list[int] | None = Noneuse_fine_route: bool = True )

参数

  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 512) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • hidden_act (str,可选,默认为 gelu_pytorch_tanh) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • out_hidden_size (int,可选,默认为 1024) — 连接器所投影到的文本解码器的隐藏层大小。
  • scale_factor (int, 可选,默认为 4) — 连接器的像素混洗因子。每个由 (image_size // patch_size) ** 2 个视觉标记组成的图块会按 scale_factor ** 2 进行缩减。
  • deepstack_visual_indexes (list[int],可选,默认为 [3, 7, 10]) — 视觉编码器层的索引,这些层的输出将由 DeepStack 合并器进行投影。索引 0 对应第一层的输出。
  • use_fine_route (bool,可选,默认为 True) — 是否构建细粒度连接路径。该路径会以 scale_factor 的一半对像素进行洗牌,从而使每个 tile 产生的图像 token 数量增加四倍。500M 检查点包含此路径,而 2B 检查点不包含。

SigLIP 风格视觉编码器的配置,该编码器对页面的每个 512x512 图块进行嵌入,以及将编码器输出转换为图像标记的连接器。

示例:

>>> from transformers import GraniteDoclingVisionConfig, GraniteDoclingVisionModel

>>> # Initializing a GraniteDoclingVisionConfig with ibm-granite/granite-for-docling-500m style configuration
>>> configuration = GraniteDoclingVisionConfig()

>>> # Initializing a GraniteDoclingVisionModel (with random weights) from the ibm-granite/granite-for-docling-500m style configuration
>>> model = GraniteDoclingVisionModel(configuration)

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

GraniteDoclingImageProcessor

class transformers.GraniteDoclingImageProcessor

< >

( **kwargs: *<class 'transformers.models.granite_docling.image_processing_granite_docling.GraniteDoclingImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 512, 'width': 512}): 描述输入到模型的最大尺寸。
  • 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,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为 [0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • crop_to_patches (bool, kwargs, 可选,默认为 True) — 是否将页面分割为 512x512 的图块,并按最匹配其宽高比的网格进行排列(每侧最多 16 个图块)。可通过 preprocess 方法中的 crop_to_patches 参数进行覆盖。
  • min_patches (int,kwargs,可选,默认为 1) — 每页的最小瓦片数量。仅当 crop_to_patches 设置为 True 时生效。可通过 preprocess 方法中的 min_patches 参数进行覆盖。
  • max_patches (int, kwargs, 可选,默认为 32) — 每页的最大瓦片数量。仅当 crop_to_patches 设置为 True 时生效。可通过 preprocess 方法中的 max_patches 参数进行覆盖。
  • fine_route (bool,kwargs,可选,默认为 False) — 页面是否采用细粒度连接器路径,该路径会为每个图块生成四倍数量的图像标记。
  • dense_max_patches (int, kwargs, 可选, 默认为 0) — 展开规则所选页面的最大瓦片数(0 表示禁用该规则)。当 max_patches 网格将页面缩小至低于 dense_max_scale,且其宽高比高于 dense_min_aspect(若设置了 dense_max_aspect,则宽高比至多为 dense_max_aspect)时,页面将使用最多 dense_max_patches 个瓦片进行平铺,而不是 max_patches。检查点必须使用相同的规则进行训练。
  • dense_max_scale (float,kwargs,可选,默认值为 0.0) — 在 max_patches 下,分块画布宽度与页面宽度的比值低于该阈值时,该页面被视为分辨率不足。设为 0 则跳过此测试。
  • dense_min_aspect (float,kwargs,可选,默认值为 0.0) — 页面宽高比必须超过该值才能获得 dense_max_patches。设为 0 则跳过此测试。
  • dense_max_aspect (float, kwargs, optional, 默认值为 0.0) — 页面宽高比的上限,超过该值则无法获得 dense_max_patches,从而将单行公式等条状内容保持在 max_patches 以内。0 表示无上限。

将页面分割为 512x512 的图块,网格选择最匹配其宽高比的方案(crop_to_patches,最多 max_patches 个图块,每侧 16 个),当存在多个图块时添加整个页面的缩略图,并将批次中的样本填充至相同的图块数量。pixel_attention_mask 用于标记真实的图块。fine_route=True 标记用于精细连接器路径的样本(tile_fine_mask,每个样本一个值)。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~image_processing_base.BatchFeature

参数

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

返回值

~image_processing_base.BatchFeature

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

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

GraniteDoclingImageProcessorPil

class transformers.GraniteDoclingImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.granite_docling.image_processing_pil_granite_docling.GraniteDoclingImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 512, 'width': 512}): 描述输入到模型的最大尺寸。
  • 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,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为 [0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • crop_to_patches (bool, kwargs, 可选,默认为 True) — 是否将页面分割为 512x512 的图块,并按最匹配其宽高比的网格进行排列(每侧最多 16 个图块)。可通过 preprocess 方法中的 crop_to_patches 参数进行覆盖。
  • min_patches (int,kwargs,可选,默认为 1) — 每页的最小瓦片数量。仅当 crop_to_patches 设置为 True 时生效。可通过 preprocess 方法中的 min_patches 参数进行覆盖。
  • max_patches (int, kwargs, 可选,默认为 32) — 每页的最大瓦片数量。仅当 crop_to_patches 设置为 True 时生效。可通过 preprocess 方法中的 max_patches 参数进行覆盖。
  • fine_route (bool,kwargs,可选,默认为 False) — 页面是否采用细粒度连接器路径,该路径会为每个图块生成四倍数量的图像标记。
  • dense_max_patches (int, kwargs, 可选, 默认为 0) — 展开规则所选页面的最大瓦片数(0 表示禁用该规则)。当 max_patches 网格将页面缩小至低于 dense_max_scale,且其宽高比高于 dense_min_aspect(若设置了 dense_max_aspect,则宽高比至多为 dense_max_aspect)时,页面将使用最多 dense_max_patches 个瓦片进行平铺,而不是 max_patches。检查点必须使用相同的规则进行训练。
  • dense_max_scale (float,kwargs,可选,默认值为 0.0) — 在 max_patches 下,分块画布宽度与页面宽度的比值低于该阈值时,该页面被视为分辨率不足。设为 0 则跳过此测试。
  • dense_min_aspect (float,kwargs,可选,默认值为 0.0) — 页面宽高比必须超过该值才能获得 dense_max_patches。设为 0 则跳过此测试。
  • dense_max_aspect (float, kwargs, optional, 默认值为 0.0) — 页面宽高比的上限,超过该值则无法获得 dense_max_patches,从而将单行公式等条状内容保持在 max_patches 以内。0 表示无上限。

GraniteDoclingImageProcessor 的 PIL 后端:相同的 512x512 分块、缩略图以及分块填充。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~image_processing_base.BatchFeature

参数

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

返回值

~image_processing_base.BatchFeature

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

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

GraniteDoclingProcessor

类 transformers.GraniteDoclingProcessor

< >

( image_processortokenizer = Noneimage_seq_len: int = 64chat_template: str | None = None**kwargs )

参数

  • image_processor (GraniteDoclingImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。
  • image_seq_len (int, 可选, 默认为 64) — 粗粒度路径中每个 tile 的 <image> token 数量。其计算方式为 image_seq_len = int(((image_size // patch_size) ** 2) / (scale_factor**2))。
  • chat_template (str, 可选) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。

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

GraniteDoclingProcessor 提供了 GraniteDoclingImageProcessor 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~GraniteDoclingImageProcessor 和 ~tokenizer_class。

__call__

< >

( images = Nonetext = None**kwargs ) → BatchEncoding

参数

  • images (`) -- Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False`.
  • text (`) -- The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, set is_split_into_words=True` to avoid ambiguity with batched inputs.
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。

返回值

BatchEncoding

带有 pixel_values 和 pixel_attention_mask 的标记化提示,以及当 fine_route=True 时的 tile_fine_mask。瓦片网格仅用于构建提示,不会被返回。

GraniteDoclingVisionModel

类 transformers.GraniteDoclingVisionModel

< >

( config: GraniteDoclingVisionConfig )

参数

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

GraniteDocling 的视觉编码器及其顶部的连接器:嵌入页面的各个图块,并返回每个图块的图像标记以及投影后的 DeepStack 特征。

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

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

forward

< >

( pixel_values: FloatTensorfine: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> )

参数

  • pixel_values(形状为 (num_tiles, num_channels, image_size, image_size) 的 torch.FloatTensor)— 跨批次展平的图块,不包含填充图块。
  • fine (bool,可选,默认为 False) — 是否让 tile 走 fine 连接路径,该路径会为每个 tile 生成四倍数量的图像 token。

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

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

GraniteDoclingModel

类 transformers.GraniteDoclingModel

< >

( config: GraniteDoclingConfig )

参数

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

GraniteDocling 模型由视觉编码器、连接器和文本解码器组成,输出原始隐藏状态,顶部不附加任何特定的输出头。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Nonetile_fine_mask: typing.Optional[torch.BoolTensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Nonemm_encoder_outputs: dict | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → GraniteDoclingBaseModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

  • cache (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 cache 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 cache,则默认会初始化 DynamicCache。

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

    如果使用 cache,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的所有 input_ids。

  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • tile_fine_mask (torch.BoolTensor,形状为 (batch_size,),可选) — 当处理器以 fine_route=True 调用时,所有值均为 True:该批次将走细粒度连接器路径,每个 tile 产生的图像 token 数量是原来的四倍。
  • pixel_attention_mask (torch.BoolTensor,形状为 (batch_size, num_tiles),可选) — 处理器返回的真实 tile。填充 tile 为 false。使用 pixel_values 时必填。
  • mm_encoder_outputs (dict, 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output, 可选: last_hidden_states, 可选: hidden_states, 可选: attentions) pooler_output 形状为 (batch_size, sequence_length, hidden_size), 可选) 组成,它是编码器生成的多模态特征序列,已合并到文本嵌入中。

返回值

GraniteDoclingBaseModelOutputWithPast 或 tuple(torch.Tensor)

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

输入到模型的图像数量可以是任意的。为此,输入模型的 pixel_values 会进行图像填充,其形状为 (batch_size, max_num_tiles, 3, image_size, image_size),其中 max_num_tiles 是 batch_size 个样本中最大的图像块数量。填充的图像块在 pixel_attention_mask 中为 false,并会在进入视觉编码器之前被丢弃。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.FloatTensor)— 语言模型主干最后一层输出的隐藏状态序列。 如果使用 cache,则仅输出形状为 (batch_size, 1, hidden_size) 的序列最后一个隐藏状态。
  • cache (Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回) — 它是一个 Cache 实例。有关更多详细信息,请参阅我们的 kv cache 指南。 包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 cache 输入)加速顺序解码。
  • hidden_states (tuple(torch.FloatTensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.FloatTensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。 语言模型主干在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
  • attentions (tuple(torch.FloatTensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.FloatTensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。语言模型主干的注意力权重,位于注意力 softmax 之后。
  • router_logits (tuple(torch.Tensor),可选,在传入 output_router_logits=True 或 config.output_router_logits=True 时返回) — 一个 torch.Tensor 元组(每个稀疏层对应一个),形状为 (batch_size * sequence_length, num_experts)。 由 MoE 路由器计算的原始路由 logits。可用于计算负载均衡损失,或检查 token 如何被分发到各个专家。
  • image_outputs(BaseModelOutputWithPooling,可选)— 图像编码器的输出:last_hidden_state、pooler_output、hidden_states 和 attentions。如果未处理任何图像,则为 None。
  • video_outputs(BaseModelOutputWithPooling,可选)— 视频编码器的输出:last_hidden_state、pooler_output、hidden_states 和 attentions。如果未处理任何视频,则为 None。
  • audio_outputs(BaseModelOutputWithPooling,可选)— 音频编码器的输出:last_hidden_state、pooler_output、hidden_states 和 attentions。如果未处理任何音频,则为 None。

get_image_features

< >

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

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_tiles, num_channels, image_size, image_size)) — 与输入图像块对应的张量。
  • pixel_attention_mask (torch.BoolTensor,形状为 (batch_size, num_tiles)) — 由处理器返回的真实图块。填充图块为 false。
  • tile_fine_mask (torch.BoolTensor,形状为 (batch_size,),可选) — 要求处理器以 fine_route=True 调用:该批次将采用细粒度连接器路径,每个 tile 生成的图像 token 数量是原来的四倍。

返回值

GraniteDoclingImageFeaturesOutput 或 tuple(torch.Tensor)

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

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

  • pooler_output(长度为 batch_size 的 tuple[torch.FloatTensor])— 每个样本的图像 token,按 tile 顺序投影到文本隐藏层维度。每个张量的形状为 (num_image_tokens, hidden_size)。在粗粒度连接器路径上,一个 tile 产生 image_seq_len 个 token;在细粒度路径上,产生的 token 数量是其四倍。生成过程中,这些按样本划分的张量会在各个 beam 中重复使用。

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

  • deepstack_features (list[tuple[torch.FloatTensor]], 可选) — config.deepstack_visual_indexes 中每个条目对应一个投影后的视觉编码器中间隐藏状态。每个条目按样本拆分,布局与 pooler_output 相同。

  • router_logits (torch.FloatTensor,形状为 (batch_size,),可选) — 密度路由器的 logits,每个样本一个。当模型包含路由器时返回。

predict_fine_route

< >

( pixel_values: FloatTensorpixel_attention_mask: BoolTensor ) → torch.BoolTensor of shape (batch_size,)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_tiles, num_channels, image_size, image_size)) — 与输入图像块对应的张量。
  • pixel_attention_mask (torch.BoolTensor,形状为 (batch_size, num_tiles)) — 由处理器返回的真实图块。

返回值

形状为 (batch_size,) 的 torch.BoolTensor

对于需要细粒度连接器路径的样本,值为True。

使用密度路由器预测哪些样本需要细粒度连接路径。通过再次调用处理器并设置 fine_route=True 来路由这些样本。

GraniteDoclingTextModel

类 transformers.GraniteDoclingTextModel

< >

( config: GraniteDoclingTextConfig )

参数

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

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

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: bool | None = Nonevisual_pos_masks: typing.Optional[torch.BoolTensor] = Nonedeepstack_visual_embeds: list[torch.Tensor] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

  • cache (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 cache 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 cache,则默认会初始化 DynamicCache。

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

    如果使用 cache,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的所有 input_ids。

  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 True,则会返回 cache 键值状态,可用于加速解码(参见 cache)。
  • visual_pos_masks(形状为 (batch_size, sequence_length) 的 torch.BoolTensor,可选) — 接收 DeepStack 特征的图像标记的位置。
  • deepstack_visual_embeds (list[torch.Tensor], 可选) — DeepStack 特征,每个的形状为 (num_image_tokens, hidden_size)。第 i 个条目会在解码器层 i 之后,被添加到 visual_pos_masks 处的隐藏状态中。

返回值

BaseModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

    如果使用了cache,则仅输出形状为(batch_size, 1, hidden_size)的序列的最后一个隐藏状态。

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

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

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

GraniteDoclingForConditionalGeneration

类 transformers.GraniteDoclingForConditionalGeneration

< >

( config: GraniteDoclingConfig )

参数

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

带有语言建模头的 GraniteDocling 模型。它由视觉编码器、连接器和文本解码器组成,并在顶部添加了一个语言建模头。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Nonetile_fine_mask: typing.Optional[torch.BoolTensor] = Nonepixel_attention_mask: typing.Optional[torch.BoolTensor] = Nonemm_encoder_outputs: dict | None = Nonelabels: typing.Optional[torch.LongTensor] = Nonerouter_labels: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → GraniteDoclingCausalLMOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

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

    什么是注意力掩码?

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

    什么是位置 ID?

  • cache (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 cache 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 cache,则默认会初始化 DynamicCache。

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

    如果使用 cache,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的所有 input_ids。

  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • tile_fine_mask (torch.BoolTensor,形状为 (batch_size,),可选) — 当处理器以 fine_route=True 调用时,所有值均为 True:该批次将走细粒度连接器路径,每个 tile 产生的图像 token 数量是原来的四倍。
  • pixel_attention_mask (torch.BoolTensor,形状为 (batch_size, num_tiles),可选) — 处理器返回的真实 tile。填充 tile 为 false。使用 pixel_values 时必填。
  • mm_encoder_outputs (dict, 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output, 可选: last_hidden_states, 可选: hidden_states, 可选: attentions) pooler_output 形状为 (batch_size, sequence_length, hidden_size), 可选) 组成,它是编码器生成的多模态特征序列,已合并到文本嵌入中。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引应位于 [0, ..., config.vocab_size] 或 model.image_token_id(其中 model 是 GraniteDoclingForConditionalGeneration 的实例)。 索引设置为 model.image_token_id 的 token 将被忽略(掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 中的 token 进行计算。
  • router_labels (torch.Tensor,形状为 (batch_size,),可选) — 密度路由器的目标值,对于需要精细连接器路径的样本为 1(或 True),否则为 0。以 float、bool 或 int 形式给出;路由器损失是对 logits 的二元交叉熵。
  • use_cache (bool, 可选) — 如果设置为 True,则会返回 cache 键值状态,可用于加速解码(参见 cache)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。

返回值

GraniteDoclingCausalLMOutputWithPast 或 tuple(torch.Tensor)

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

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

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

  • loss (torch.FloatTensor,形状为 (1,),可选,在提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。
  • aux_loss (torch.Tensor,可选,当传入 output_router_logits=True 或 config.output_router_logits=True,且模型使用负载均衡损失训练其路由器时返回) — 稀疏模块的负载均衡辅助损失。那些改用路由器偏差来平衡其专家(DeepSeek-V3 及由其衍生的架构)的模型,此处返回 None,但仍会返回 router_logits。
  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.FloatTensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。
  • cache (Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回) — 它是一个 Cache 实例。有关更多详细信息,请参阅我们的 kv cache 指南。 包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 cache 输入)加速顺序解码。
  • hidden_states (tuple(torch.FloatTensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.FloatTensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。 语言模型主干在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
  • attentions (tuple(torch.FloatTensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.FloatTensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。语言模型主干的注意力权重,位于注意力 softmax 之后。
  • router_logits (tuple(torch.Tensor),可选,在传入 output_router_logits=True 或 config.output_router_logits=True 时返回) — 一个 torch.Tensor 元组(每个稀疏层对应一个),形状为 (batch_size * sequence_length, num_experts)。 由 MoE 路由器计算的原始路由 logits。可用于计算负载均衡损失,或检查 token 如何被分发到各个专家。
  • image_outputs(BaseModelOutputWithPooling,可选)— 图像编码器的输出:last_hidden_state、pooler_output、hidden_states 和 attentions。如果未处理任何图像,则为 None。
  • video_outputs(BaseModelOutputWithPooling,可选)— 视频编码器的输出:last_hidden_state、pooler_output、hidden_states 和 attentions。如果未处理任何视频,则为 None。
  • audio_outputs(BaseModelOutputWithPooling,可选)— 音频编码器的输出:last_hidden_state、pooler_output、hidden_states 和 attentions。如果未处理任何音频,则为 None。

示例:

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> from transformers.image_utils import load_image

>>> image = load_image("https://huggingface.co/ibm-granite/granite-for-docling-500m/resolve/main/docling_technical_report_p1.png")

>>> processor = AutoProcessor.from_pretrained("ibm-granite/granite-for-docling-500m")
>>> model = AutoModelForImageTextToText.from_pretrained("ibm-granite/granite-for-docling-500m", device_map="auto")

>>> messages = [
...     {
...         "role": "user",
...         "content": [
...             {"type": "image"},
...             {"type": "text", "text": "<doclang>"},
...         ],
...     }
... ]
>>> prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
>>> inputs = processor(text=prompt, images=image, return_tensors="pt").to(model.device)

>>> generated_ids = model.generate(**inputs, max_new_tokens=4096)
>>> print(processor.decode(generated_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=False))

get_image_features

< >

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

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 与输入图像对应的张量。
  • pixel_attention_mask (torch.LongTensor, 可选) — 指示图像中填充区域的注意力掩码。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

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

  • 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 PIL import Image
>>> from transformers import AutoProcessor, GraniteDoclingForConditionalGeneration

>>> model = GraniteDoclingForConditionalGeneration.from_pretrained("ibm-granite/granite-for-docling-500m")
>>> processor = AutoProcessor.from_pretrained("ibm-granite/granite-for-docling-500m")

>>> messages = [
...     {
...         "role": "user", "content": [
...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
...             {"type": "text", "text": "Where is the cat standing?"},
...         ]
...     },
... ]

>>> inputs = processor.apply_chat_template(
...     messages,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
Update on GitHub