Transformers documentation

UnlimitedOcr

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2026-06-23 在 HF papers 上发布,并于 2026-10-14 贡献至 Hugging Face Transformers。

UnlimitedOcr

概述

UnlimitedOcr 模型由百度公司的 Youyang Yin、Huanhuan Liu、Qunyi Xie、Chaorun Liu、Shiqi Yang、Shaohua Wang、Zhanlong Liu、Hao Zou、Jinyue Chen、Shu Wei、Jingjing Wu、Mingxin Huang、Zhen Wu、Guibin Wang、Tengyu Du 和 Lei Jia 在 Unlimited OCR Works 中提出。

它是一个具有 30 亿参数的单一模型,标准上下文长度为 32,768 个 token。

该论文的摘要如下:

近期,以 DeepSeek OCR 为代表的端到端 OCR 模型再次将 OCR 推至聚光灯下。一种普遍的观点认为,将大语言模型(LLM)用作解码器,能够利用语言的先验分布,从而提升 OCR 性能。然而,其弊端同样明显:随着输出序列变长,累积的 KV cache 会导致内存消耗增加,并使生成速度逐渐变慢。这与人类的表现形成鲜明对比——人类在执行长时程的抄写任务时,效率并不会出现此类下降。在本技术报告中,我们提出了 Unlimited OCR,一个旨在模拟人类解析工作记忆的模型。以 DeepSeek OCR 为基线,我们将解码器中的所有注意力层替换为我们提出的 Reference Sliding Window Attention(R-SWA),在保持整个解码过程中 KV cache 恒定的同时,降低了注意力计算成本。通过将 DeepSeek OCR 编码器的高压缩率与我们恒定的 KV cache 设计相结合,Unlimited OCR 能够在标准最大长度 32K 下,通过单次前向传播转录数十页文档。更重要的是,R-SWA 是一种通用的解析注意力机制——除了 OCR 之外,它同样适用于 ASR、翻译等任务。代码和模型权重已公开于 http://github.com/baidu/Unlimited-OCR

Unlimited-OCR 支持两种推理配置:默认的 “gundam” 模式使用 640x640 的图块,并结合动态裁剪来处理高分辨率文档;“base” 模式则使用单个 1024x1024 的全局视图来处理标准分辨率的输入。要启用 base 模式,请在 processor 中设置 crop_to_patches=False,或者在使用 apply_chat_template() 时通过 processor_kwargs 传入该参数。

视觉塔采用了 DeepSeek-OCR-2 中的两阶段方法:SAM ViT-B 编码器作为输入,接入 CLIP ViT 编码器。与 DeepSeek-OCR-2 不同,CLIP 特征还会与 SAM 特征进行拼接,以生成最终的图像 token。Unlimited-OCR 还省略了 DeepSeek-OCR-2 中的可学习 patch 查询。

文本模型与 DeepSeek-OCR-2 相同,额外增加了 Reference Sliding Window Attention (R-SWA)。R-SWA 仅应用于生成的 token。所有图像和提示 token 在整个解码过程中均保持完全可见,因此长文档不会因早期页面而丢失上下文。

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

原始实现使用 torch.autocast 以 bfloat16 运行模型。请将 forward 和 generate 调用包裹在 autocast 上下文中,以复现其输出。

with torch.autocast(device_type=model.device.type, dtype=torch.bfloat16):
    output = model.generate(**inputs)
单页 OCR
多页 OCR
from transformers import AutoProcessor, AutoModelForImageTextToText

model = AutoModelForImageTextToText.from_pretrained("baidu/Unlimited-OCR", device_map="auto")
processor = AutoProcessor.from_pretrained("baidu/Unlimited-OCR")

image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg"
messages = [
    {
        "role": "user",
        "content": [{"type": "image", "url": image}, {"type": "text", "text": "document parsing."}],
    }
]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device, model.dtype)

output = model.generate(**inputs, max_new_tokens=512)
processor.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
# image [383, 87, 497, 171]\ntext [333, 201, 558, 230]R&D QUALITY IMPROVEMENT\nSUGGESTION/SOLUTION FORM...

# All bounding boxes are in (x1, y1, x2, y2) format with coordinates normalized to [0, 999]

批处理

对于批量处理,请传入一个消息列表。如果图像尺寸不同,请将处理器的 padding=True 设置为 True。

from transformers import AutoProcessor, AutoModelForImageTextToText

model = AutoModelForImageTextToText.from_pretrained("baidu/Unlimited-OCR", device_map="auto")
processor = AutoProcessor.from_pretrained("baidu/Unlimited-OCR")

image1 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg"
image2 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_receipt.jpeg"
messages = [
    [
        {
            "role": "user",
            "content": [{"type": "image", "url": image}, {"type": "text", "text": "document parsing."}],
        }
    ]
    for image in [image1, image2]
]
inputs = processor.apply_chat_template(
    messages,
    add_generation_prompt=True,
    tokenize=True,
    return_dict=True,
    return_tensors="pt",
    processor_kwargs={"padding": True},
).to(model.device, model.dtype)

output = model.generate(**inputs)
processor.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
# image [383, 87, 497, 171]\ntext [333, 201, 558, 230]R&D QUALITY IMPROVEMENT\nSUGGESTION/SOLUTION FORM...

# All bounding boxes are in (x1, y1, x2, y2) format with coordinates normalized to [0, 999]

区域检测

将 skip_special_tokens=False 设置为 <|det|>...<|/det|> 标记,以包裹所有检测结果和区域类型。这对于输出的进一步后处理非常有用,例如在图像上绘制检测到的边界框。每个检测结果的格式为 <|det|>region_type [x1, y1, x2, y2]<|/det|>text...,其中坐标已归一化到 [0, 999] 范围内。将 return_detections=True 设置为 {"region_type": region_type, "box": [x1, y1, x2, y2], "text": "..."} 以获取一个额外的字典列表,其中包含所有解析后的检测结果。

from transformers import AutoProcessor, AutoModelForImageTextToText

model = AutoModelForImageTextToText.from_pretrained("baidu/Unlimited-OCR", device_map="auto")
processor = AutoProcessor.from_pretrained("baidu/Unlimited-OCR")

image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg"
messages = [
    {
        "role": "user",
        "content": [{"type": "image", "url": image}, {"type": "text", "text": "document parsing."}],
    }
]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device, model.dtype)

output = model.generate(**inputs)
decoded, detections = processor.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=False, return_detections=True)
# <|det|>image [383, 87, 497, 171]<|/det|>\n<|det|>text [333, 201, 558, 230]<|/det|>R&D QUALITY IMPROVEMENT\nSUGGESTION/SOLUTION FORM...

# Visualization
import random
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from transformers.image_utils import load_image

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg")
width, height = image.size

figure, axis = plt.subplots(figsize=(10, 12))
axis.imshow(image)
for detection in detections:
    region_type = detection["region_type"]
    x1, y1, x2, y2 = detection["box"]
    x1, y1, x2, y2 = int(x1) / 999 * width, int(y1) / 999 * height, int(x2) / 999 * width, int(y2) / 999 * height
    color = (random.random(), random.random(), random.random())
    rectangle = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=1.5, edgecolor=color, facecolor="none")
    axis.add_patch(rectangle)
    axis.text(x1, y1, region_type, color="white", fontsize=8, backgroundcolor=color, verticalalignment="top")
axis.axis("off")
plt.show()

UnlimitedOcrConfig

class transformers.UnlimitedOcrConfig

< >

( 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 = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneimage_token_id: int = 128815tie_word_embeddings: bool = False )

参数

  • vision_config (dict 或 UnlimitedOcrVisionConfig,可选) — 视觉编码器的配置。默认为 UnlimitedOcrVisionConfig()。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • image_token_id (int,可选,默认为 128815) — 用作输入图像占位符的图像 token 索引。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。

这是用于存储 UnlimitedOcrModel 配置的类。它根据指定的参数实例化 Unlimited Ocr 模型,并定义模型架构。使用默认值实例化配置将生成与 baidu/Unlimited-OCR 类似的配置。

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

示例:

>>> from transformers import UnlimitedOcrConfig, UnlimitedOcrModel

>>> configuration = UnlimitedOcrConfig()
>>> model = UnlimitedOcrModel(configuration)
>>> configuration = model.config

UnlimitedOcrTextConfig

class transformers.UnlimitedOcrTextConfig

< >

( 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 = 129280hidden_size: int = 1280intermediate_size: int = 6848num_hidden_layers: int = 12num_attention_heads: int = 10num_key_value_heads: int | None = 10hidden_act: str = 'silu'max_position_embeddings: int = 32768initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truepad_token_id: int | None = Nonebos_token_id: int | None = 0eos_token_id: int | list[int] | None = 1pretraining_tp: int | None = 1tie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Noneattention_bias: bool = Falseattention_dropout: float | None = 0.0mlp_bias: bool = Falsehead_dim: int | None = Nonen_group: int | None = 1n_routed_experts: int = 64output_router_logits: bool = Falsen_shared_experts: int = 2routed_scaling_factor: float = 1.0topk_group: int | None = 1topk_method: str | None = 'greedy'num_experts_per_tok: int | None = 6moe_intermediate_size: int = 896mlp_layer_types: list[str] | None = Nonelayer_types: list[str] | None = Nonesliding_window: int | None = 128 )

参数

  • vocab_size (int,可选,默认为 129280) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 1280) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 6848) — MLP 表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 10) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选,默认为 10) — 这是用于实现 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 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 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-06) — RMS 归一化层使用的 epsilon 值。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • pad_token_id (int, 可选) — 词表中用于填充的 token id。
  • bos_token_id (int,可选,默认为 0) — 词汇表中用于表示流起始的 Token id。
  • eos_token_id (Union[int, list[int]],可选,默认为 1) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • pretraining_tp (int,可选,默认为 1) — 实验性功能。预训练期间使用的张量并行 rank。请参阅此文档以了解更多相关信息。此值对于确保预训练结果的精确可复现性是必需的。请参阅此 issue。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 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 (float,可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • mlp_bias (bool,可选,默认为 False) — 是否在 MLP 层的 up_proj、down_proj 和 gate_proj 层中使用偏置。
  • head_dim (int,可选) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads
  • n_group (int, 可选) — 用于分组 top-k 专家路由的组数。
  • n_routed_experts (int,可选,默认为 64) — 路由专家的数量。
  • output_router_logits (bool,可选,默认为 False) — 是否由模型返回路由器 logits。启用此选项后,模型还将输出辅助损失,包括负载均衡损失和路由器 z-loss。
  • n_shared_experts (int,可选,默认为 2) — 共享专家的数量。
  • routed_scaling_factor (float,可选,默认为 1.0) — 路由专家的缩放因子。
  • topk_group (int,可选,默认为 1) — 每个 token 所选的组数(对于每个 token,确保所选专家仅位于 topk_group 个组内)。
  • topk_method (str,可选,默认为 "greedy") — 用于在 MoE 层中选择 top-k 专家的方法。
  • num_experts_per_tok (int,可选,默认为 6) — 每个 token 路由到的专家数量。这是 token-choice 路由的 top-k 值。
  • moe_intermediate_size (int,可选,默认为 896) — 路由专家 MLP 的中间层大小。
  • mlp_layer_types (list[str], 可选) — 每个解码器层的 MLP 类型("dense" 或 "sparse"),例如 ["dense", "sparse", "sparse", ...]。
  • layer_types (list[str], 可选) — 每个解码器层的注意力类型。默认情况下,每一层均为 "reference_sliding_attention"。
  • sliding_window (int, 可选,默认为 128) — 用于参考滑动窗口注意力的滑动窗口大小。如果设置,每个 token 将关注最近的 sliding_window 个 token 以及所有图像和提示 token。

这是用于存储 UnlimitedOcrModel 配置的类。它根据指定的参数实例化 Unlimited Ocr 模型,并定义模型架构。使用默认值实例化配置将生成与 baidu/Unlimited-OCR 类似的配置。

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

示例:

>>> from transformers import UnlimitedOcrTextConfig, UnlimitedOcrTextModel

>>> configuration = UnlimitedOcrTextConfig()
>>> model = UnlimitedOcrTextModel(configuration)
>>> configuration = model.config

UnlimitedOcrVisionConfig

class transformers.UnlimitedOcrVisionConfig

< >

( 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 = Nonesam_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneencoder_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None )

参数

  • sam_config (dict 或 UnlimitedOcrSamVisionConfig,可选) — SAM 视觉编码器的配置。默认为 UnlimitedOcrSamVisionConfig()。
  • encoder_config (dict 或 UnlimitedOcrVisionEncoderConfig,可选) — 视觉编码器的配置。默认为 UnlimitedOcrVisionEncoderConfig()。

这是用于存储 UnlimitedOcrModel 配置的类。它根据指定的参数实例化 Unlimited Ocr 模型,并定义模型架构。使用默认值实例化配置将生成与 baidu/Unlimited-OCR 类似的配置。

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

示例:

>>> from transformers import UnlimitedOcrVisionConfig, UnlimitedOcrVisionModel

>>> configuration = UnlimitedOcrVisionConfig()
>>> model = UnlimitedOcrVisionModel(configuration)
>>> configuration = model.config

UnlimitedOcrVisionEncoderConfig

class transformers.UnlimitedOcrVisionEncoderConfig

< >

( 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 = 1024intermediate_size: int = 4096num_hidden_layers: int = 24num_attention_heads: int = 16num_channels: int = 3image_size: int | list[int] | tuple[int, int] | None = 224patch_size: int | list[int] | tuple[int, int] | None = 14hidden_act: str = 'quick_gelu'layer_norm_eps: float = 1e-05attention_dropout: int | float | None = 0.0initializer_range: float = 0.02initializer_factor: float = 1.0 )

参数

  • hidden_size (int,可选,默认为 1024) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 4096) — MLP 表示的维度。
  • num_hidden_layers (int,可选,默认为 24) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 16) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 224) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 14) — 每个 patch 的大小(分辨率)。
  • hidden_act (str,可选,默认为 quick_gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[int, float],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • initializer_factor (float,可选,默认为 1.0) — 用于初始化所有权重矩阵的系数(应保持为 1,内部用于初始化测试)。

这是用于存储 UnlimitedOcrModel 配置的类。它根据指定的参数实例化 Unlimited Ocr 模型,并定义模型架构。使用默认值实例化配置将生成与 baidu/Unlimited-OCR 类似的配置。

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

示例:

>>> from transformers import UnlimitedOcrVisionEncoderConfig, UnlimitedOcrVisionEncoder

>>> configuration = UnlimitedOcrVisionEncoderConfig()
>>> model = UnlimitedOcrVisionEncoder(configuration)
>>> configuration = model.config

UnlimitedOcrSamVisionConfig

class transformers.UnlimitedOcrSamVisionConfig

< >

( 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 = 768output_channels: int = 256num_hidden_layers: int = 12num_attention_heads: int = 12num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 1024patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'gelu'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0initializer_range: float = 1e-10qkv_bias: bool = Trueuse_abs_pos: bool = Trueuse_rel_pos: bool = Truewindow_size: int = 14global_attn_indexes: list[int] | tuple[int, ...] = (2, 5, 8, 11)mlp_dim: int = 3072downsample_channels: list[int] | tuple[int, ...] = (512, 1024) )

参数

  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • output_channels (int, 可选,默认为 256) — Patch Encoder 中输出通道的维度。
  • 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]],可选,默认为 1024) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-06) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 1e-10) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • use_abs_pos (bool,可选,默认为 True) — 是否使用绝对位置嵌入。
  • use_rel_pos (bool,可选,默认为 True) — 是否使用相对位置嵌入。
  • window_size (int,可选,默认为 14) — 相对位置的窗口大小。
  • global_attn_indexes (list[int],可选,默认为 [2, 5, 8, 11]) — 全局注意力层的索引。
  • mlp_dim (int,可选,默认值为 3072) — Transformer 编码器中 MLP 层的维度。
  • downsample_channels (list[int],可选,默认为 (512, 1024)) — 多尺度下采样颈部层的通道维度。

这是用于存储 UnlimitedOcrModel 配置的类。它根据指定的参数实例化 Unlimited Ocr 模型,并定义模型架构。使用默认值实例化配置将生成与 baidu/Unlimited-OCR 类似的配置。

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

UnlimitedOcrImageProcessor

class transformers.UnlimitedOcrImageProcessor

< >

( **kwargs: *<class 'transformers.models.unlimited_ocr.image_processing_unlimited_ocr.UnlimitedOcrImageProcessorKwargs'> )

参数

  • 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' -- 1024, 'width': 1024}): 描述输入到模型的最大尺寸。
  • 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.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当 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) — 是否将图像裁剪为 patches。可被 preprocess 方法中的 crop_to_patches 参数覆盖。
  • min_patches (int,kwargs,可选,默认为 2) — 从图像中提取的最小 patch 数量。仅当 crop_to_patches 设置为 True 时生效。可通过 preprocess 方法中的 min_patches 参数进行覆盖。
  • max_patches (int, kwargs, 可选,默认为 32) — 从图像中提取的最大 patch 数量。仅当 crop_to_patches 设置为 True 时生效。可通过 preprocess 方法中的 max_patches 参数进行覆盖。
  • tile_size (int,kwargs,可选,默认值为 640) — 每个局部 tile 的大小。必须与模型的 query embedding 大小相匹配。
  • background_color (list[int],kwargs,可选,默认为 [127, 127, 127]) — 用于填充的背景颜色。
  • maximum_pad_value (int,kwargs,可选,默认值为 640) — 如果 crop_to_patches 为 False,且 max(size.height, size.width) 小于或等于该值,则图像将直接调整为 max(size.height, size.width) 大小的正方形,且不保持宽高比。否则,图像将在保持宽高比的情况下进行缩放,然后使用 background_color 填充为正方形。

构建一个 UnlimitedOcrImageProcessor 图像处理器。

crop_image_to_patches

< >

( images: torch.Tensormin_patches: intmax_patches: inttile_size: intresample: PIL.Image.Resampling | None = None ) → tuple[torch.Tensor, int]

参数

  • images (torch.Tensor) — 要裁剪的图像,形状为 (batch, channels, height, width)。
  • min_patches (int) — 最小 patch 数量。
  • max_patches (int) — 最大 patch 数量。
  • tile_size (int) — 每个 tile 的大小。
  • resample (PILImageResampling, 可选) — 用于调整大小的重采样滤波器。

返回值

tuple[torch.Tensor, int]

堆叠的图像块 (batch, num_patches, channels, tile_size, tile_size) 以及每张图像的图像块数量。

根据最佳平铺方式,将批量图像裁剪为图像块。

get_number_of_image_patches

< >

( height: intwidth: intimages_kwargs: dict | None = None )

返回给定图像大小的图像块数量(1 个全局块 + 局部块)。

pad_to_square

< >

( images: torch.Tensorbackground_color: int | tuple[int, int, int] = 0 ) → torch.Tensor

参数

  • images (torch.Tensor) — 要填充的图像。形状:(batch_size, num_channels, height, width) 或 (num_channels, height, width)。
  • background_color (int 或 tuple[int, int, int],可选,默认为 0) — 用于填充的颜色。可以是表示单通道的整数,也可以是表示多通道图像的整数元组。如果在多通道模式下传入整数,则后续通道将默认为 0。

返回值

torch.Tensor

填充后的图像。

根据最长边将图像填充为正方形。

UnlimitedOcrProcessor

class transformers.UnlimitedOcrProcessor

< >

( image_processor = Nonetokenizer = Nonechat_template = Nonepatch_size = 16downsample_ratio = 4**kwargs )

参数

  • image_processor (UnlimitedOcrImageProcessor) — 图像处理器是必需的输入。
  • tokenizer (tokenizer_class) — 分词器是必需的输入。
  • chat_template (str) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可分词的字符串。
  • patch_size (int,可选,默认为 16) — 视觉编码器使用的 patch 大小(SAM ViT 的 patch 嵌入大小)。
  • downsample_ratio (int,可选,默认为 4) — 在视觉编码器之后应用的降采样比率。

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

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

batch_decode

< >

( *argsreturn_detections: bool = False**kwargs ) → list[str] or tuple[list[str], list[list[dict]]]

参数

  • return_detections (bool,可选,默认为 False) — 是否同时返回从解码文本中解析出的布局检测结果。

返回值

list[str] 或 tuple[list[str], list[list[dict]]]

解码后的文本。如果 return_detections 为 True,则返回一个元组,包含解码后的文本以及每个序列的检测信息,其中每个检测信息都是一个字典,包含键 region_type、box 和 text。框的格式为 [x1, y1, x2, y2],坐标已归一化到 [0, 999] 范围内。

此方法会将其所有参数转发给 PreTrainedTokenizer 的 batch_decode()。有关更多信息,请参阅该方法的文档字符串。

decode

< >

( *argsreturn_detections: bool = False**kwargs ) → str or tuple[str, list[dict]]

参数

  • return_detections (bool,可选,默认为 False) — 是否同时返回从解码文本中解析出的布局检测结果。

返回值

str 或 tuple[str, list[dict]]

解码后的文本。如果 return_detections 为 True,则返回一个元组,包含解码后的文本和一个检测列表,其中每个检测都是一个字典,包含键 region_type、box 和 text。框的格式为 [x1, y1, x2, y2],坐标已归一化到 [0, 999]。

此方法会将其所有参数转发给 PreTrainedTokenizer 的 decode()。有关更多信息,请参阅该方法的文档字符串。

UnlimitedOcrPreTrainedModel

class transformers.UnlimitedOcrPreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

参数

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

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

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

UnlimitedOcrTextPreTrainedModel

class transformers.UnlimitedOcrTextPreTrainedModel

< >

( config: PreTrainedConfig*inputs**kwargs )

参数

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

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

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

UnlimitedOcrTextModel

class transformers.UnlimitedOcrTextModel

< >

( config: UnlimitedOcrTextConfig )

参数

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

未附加任何特定头部的裸 Unlimited Ocr Text Model,直接输出原始 hidden-states。

该模型继承自 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] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeModelOutputWithPast 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?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。

返回值

MoeModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

  • router_logits (tuple(torch.Tensor),可选,当传入 output_router_probs=True 且 config.add_router_probs=True,或当 config.output_router_probs=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, sequence_length, num_experts)。

    由 MoE 路由器计算的原始路由器 logits(softmax 之后),这些术语用于计算混合专家模型的辅助损失。

UnlimitedOcrVisionModel

class transformers.UnlimitedOcrVisionModel

< >

( config: UnlimitedOcrVisionConfig )

参数

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

视觉模型首先使用 SAM 对图像进行编码,随后再使用一个额外的(CLIP)模型。

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

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

forward

< >

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

参数

返回值

BaseModelOutput 或 tuple(torch.Tensor)

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

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

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

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

示例:

>>> import torch
>>> from transformers import AutoConfig, AutoImageProcessor, AutoModel
>>> from transformers.image_utils import load_image

>>> model_id = "baidu/Unlimited-OCR"
>>> config = AutoConfig.from_pretrained(model_id)
>>> model = AutoModel.from_pretrained(model_id, config=config.vision_config, device_map="auto")
>>> image_processor = AutoImageProcessor.from_pretrained(model_id)

>>> image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg")
>>> inputs = image_processor(images=image, return_tensors="pt").to(model.device, model.dtype)

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # Patch tokens without class tokens (batch_size, height * width, vision_hidden_size + sam_hidden_size)
>>> patch_tokens = outputs.last_hidden_state

UnlimitedOcrModel

class transformers.UnlimitedOcrModel

< >

( config: UnlimitedOcrConfig )

参数

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

由视觉骨干网络和语言模型组成的 UnlimitedOcr 模型。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_local: typing.Optional[torch.Tensor] = Nonenum_local_patches: list[int] | None = Nonepatches_grid: list[list[int]] | None = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → UnlimitedOcrModelOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 UnlimitedOcrImageProcessor 获取像素值。有关详细信息,请参阅 UnlimitedOcrImageProcessor.call()(UnlimitedOcrProcessor 使用 UnlimitedOcrImageProcessor 来处理图像)。
  • pixel_values_local (torch.Tensor, 可选) — 形状为 (total_patches, 3, H, W) 的局部图像块像素值。
  • num_local_patches (list[int], 可选) — 批次中每张图片的局部 patch 数量。
  • patches_grid (list[list[int]],可选) — 每张图片的 patches 网格 (num_columns, num_rows)。
  • 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?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

UnlimitedOcrModelOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

  • image_hidden_states (torch.Tensor,可选) — 一个尺寸为 (batch_size, num_images, sequence_length, hidden_size) 的 torch.Tensor。 由视觉编码器生成的模型 image_hidden_states,并在投影最后一个隐藏状态之后得到。

  • router_logits (tuple[torch.Tensor],可选,在传入 output_router_logits=True 或 config.add_router_probs=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, sequence_length, num_experts)。

    模型的 Router logits,可用于计算混合专家(Mixture of Experts)模型的辅助损失。

UnlimitedOcrForConditionalGeneration

class transformers.UnlimitedOcrForConditionalGeneration

< >

( config: UnlimitedOcrConfig )

参数

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

用于基于其他模态(例如图像-文本到文本生成)进行 token 生成的 Unlimited Ocr Model。

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

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

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonepixel_values_local: typing.Optional[torch.Tensor] = Nonenum_local_patches: list[int] | None = Nonepatches_grid: list[list[int]] | None = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0mm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → UnlimitedOcrCausalLMOutputWithPast or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 UnlimitedOcrImageProcessor 获取像素值。有关详细信息,请参阅 UnlimitedOcrImageProcessor.call()(UnlimitedOcrProcessor 使用 UnlimitedOcrImageProcessor 来处理图像)。
  • pixel_values_local (torch.Tensor, 可选) — 形状为 (total_patches, 3, H, W) 的局部图像块像素值。
  • num_local_patches (list[int], 可选) — 批次中每张图片的局部 patch 数量。
  • patches_grid (list[list[int]],可选) — 每张图片的 patches 网格 (num_columns, num_rows)。
  • 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?

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

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

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

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

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。
  • use_cache (bool,可选) — 如果设置为 True,则会返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。
  • mm_encoder_outputs (dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions) pooler_output,形状为 (batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。

返回值

UnlimitedOcrCausalLMOutputWithPast 或 tuple(torch.Tensor)

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

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

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

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

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

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

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

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

  • image_hidden_states (torch.Tensor,可选) — 大小为 (batch_size * num_patches, num_images, sequence_length, hidden_size)` 的 torch.Tensor。 由视觉编码器生成的模型 image_hidden_states,并在投影最后一个隐藏状态之后得到。

  • router_logits (tuple[torch.Tensor],可选,在传入 output_router_logits=True 或 config.add_router_probs=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, sequence_length, num_experts)。

    模型的 Router logits,可用于计算混合专家(Mixture of Experts)模型的辅助损失。

单页 OCR 示例:

>>> from transformers import AutoProcessor, AutoModelForImageTextToText

>>> model = AutoModelForImageTextToText.from_pretrained("baidu/Unlimited-OCR", device_map="auto")
>>> processor = AutoProcessor.from_pretrained("baidu/Unlimited-OCR")

>>> image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg"
>>> messages = [
...     {
...         "role": "user",
...         "content": [{"type": "image", "url": image}, {"type": "text", "text": "document parsing."}],
...     }
... ]
>>> inputs = processor.apply_chat_template(
...     messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
... ).to(model.device, model.dtype)

>>> output = model.generate(**inputs)
>>> processor.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
>>> # image [383, 87, 497, 171]\ntext [333, 201, 558, 230]R&D QUALITY IMPROVEMENT\nSUGGESTION/SOLUTION FORM...

多页 OCR 示例:

>>> from transformers import AutoProcessor, AutoModelForImageTextToText

>>> model = AutoModelForImageTextToText.from_pretrained("baidu/Unlimited-OCR", device_map="auto")
>>> processor = AutoProcessor.from_pretrained("baidu/Unlimited-OCR")

>>> page1 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg"
>>> page2 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_receipt.jpeg"

>>> messages = [
...     {
...         "role": "user",
...         "content": [{"type": "image", "url": page} for page in [page1, page2]]
...         + [{"type": "text", "text": "Multi page parsing."}],
...     }
... ]
>>> inputs = processor.apply_chat_template(
...     messages,
...     add_generation_prompt=True,
...     tokenize=True,
...     return_dict=True,
...     return_tensors="pt",
...     processor_kwargs={"crop_to_patches": False},
... ).to(model.device, model.dtype)

>>> output = model.generate(
...     **inputs,
...     no_repeat_ngram_window_size=1024,
... )
>>> processor.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
>>> # <PAGE>image [382, 87, 489, 174]\ntitle [333, 201, 556, 230]R&D QUALITY IMPROVEMENT\nSUGGESTION/SCLUTION FORM...
Update on GitHub