Transformers documentation
UnlimitedOcr
该模型于 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 在整个解码过程中均保持完全可见,因此长文档不会因早期页面而丢失上下文。
原始实现使用 torch.autocast 以 bfloat16 运行模型。请将 forward 和 generate 调用包裹在 autocast 上下文中,以复现其输出。
with torch.autocast(device_type=model.device.type, dtype=torch.bfloat16): output = model.generate(**inputs)
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()
多页文档可以通过一次性传入所有页面图像,在单次前向传播中联合解析。在消息中为每一页添加一个图像块,以便模型将所有页面作为连续文档进行处理。
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, # default: 128, larger window size recommended for long documents
)
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...
# All bounding boxes are in (x1, y1, x2, y2) format with coordinates normalized to [0, 999]UnlimitedOcrConfig
class transformers.UnlimitedOcrConfig
< source >( 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 的文档。
UnlimitedOcrTextConfig
class transformers.UnlimitedOcrTextConfig
< source >( 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 的文档。
UnlimitedOcrVisionConfig
class transformers.UnlimitedOcrVisionConfig
< source >( 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 )
这是用于存储 UnlimitedOcrModel 配置的类。它根据指定的参数实例化 Unlimited Ocr 模型,并定义模型架构。使用默认值实例化配置将生成与 baidu/Unlimited-OCR 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
UnlimitedOcrVisionEncoderConfig
class transformers.UnlimitedOcrVisionEncoderConfig
< source >( 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 的文档。
UnlimitedOcrSamVisionConfig
class transformers.UnlimitedOcrSamVisionConfig
< source >( 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
< source >( **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
< source >( 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)
以及每张图像的图像块数量。
根据最佳平铺方式,将批量图像裁剪为图像块。
返回给定图像大小的图像块数量(1 个全局块 + 局部块)。
pad_to_square
< source >( images: torch.Tensorbackground_color: int | tuple[int, int, int] = 0 ) → torch.Tensor
根据最长边将图像填充为正方形。
UnlimitedOcrProcessor
class transformers.UnlimitedOcrProcessor
< source >( image_processor = Nonetokenizer = Nonechat_template = Nonepatch_size = 16downsample_ratio = 4**kwargs )
构建一个 UnlimitedOcrProcessor,它将图像处理器和分词器封装为单一处理器。
UnlimitedOcrProcessor 提供了 UnlimitedOcrImageProcessor 和 tokenizer_class 的所有功能。有关更多信息,请参阅 ~UnlimitedOcrImageProcessor 和 ~tokenizer_class。
batch_decode
< source >( *argsreturn_detections: bool = False**kwargs ) → list[str] or tuple[list[str], list[list[dict]]]
此方法会将其所有参数转发给 PreTrainedTokenizer 的 batch_decode()。有关更多信息,请参阅该方法的文档字符串。
decode
< source >( *argsreturn_detections: bool = False**kwargs ) → str or tuple[str, list[dict]]
此方法会将其所有参数转发给 PreTrainedTokenizer 的 decode()。有关更多信息,请参阅该方法的文档字符串。
UnlimitedOcrPreTrainedModel
class transformers.UnlimitedOcrPreTrainedModel
< source >( config: PreTrainedConfig*inputs**kwargs )
参数
- config (PreTrainedConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
UnlimitedOcrTextPreTrainedModel
class transformers.UnlimitedOcrTextPreTrainedModel
< source >( config: PreTrainedConfig*inputs**kwargs )
参数
- config (PreTrainedConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
UnlimitedOcrTextModel
class transformers.UnlimitedOcrTextModel
< source >( config: UnlimitedOcrTextConfig )
参数
- config (UnlimitedOcrTextConfig) — 模型的配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未附加任何特定头部的裸 Unlimited Ocr Text Model,直接输出原始 hidden-states。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( 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.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeModelOutputWithPast or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- 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]. - 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 (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - use_cache (
bool,可选) — 如果设置为True,则会返回past_key_values键值状态,可用于加速解码(参见past_key_values)。
返回值
MoeModelOutputWithPast 或 tuple(torch.FloatTensor)
MoeModelOutputWithPast 或 torch.FloatTensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(UnlimitedOcrConfig)和输入。
UnlimitedOcrTextModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor)— 模型最后一层输出的隐藏状态序列。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.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.FloatTensor),可选,当传入output_router_probs=True且config.add_router_probs=True,或当config.output_router_probs=True时返回) — 一个torch.FloatTensor元组(每层一个),形状为(batch_size, sequence_length, num_experts)。由 MoE 路由器计算的原始路由器 logits(softmax 之后),这些术语用于计算混合专家模型的辅助损失。
UnlimitedOcrVisionModel
class transformers.UnlimitedOcrVisionModel
< source >( config: UnlimitedOcrVisionConfig )
参数
- config (UnlimitedOcrVisionConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
视觉模型首先使用 SAM 对图像进行编码,随后再使用一个额外的(CLIP)模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutput or tuple(torch.FloatTensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 与输入图像对应的张量。可以使用 UnlimitedOcrImageProcessor 获取像素值。有关详细信息,请参阅 UnlimitedOcrImageProcessor.call()(UnlimitedOcrProcessor 使用 UnlimitedOcrImageProcessor 来处理图像)。
返回值
BaseModelOutput 或 tuple(torch.FloatTensor)
一个 BaseModelOutput 或 torch.FloatTensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(UnlimitedOcrConfig)和输入。
UnlimitedOcrVisionModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor)— 模型最后一层输出的隐藏状态序列。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 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> 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_stateUnlimitedOcrModel
class transformers.UnlimitedOcrModel
< source >( config: UnlimitedOcrConfig )
参数
- config (UnlimitedOcrConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
由视觉骨干网络和语言模型组成的 UnlimitedOcr 模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Nonepixel_values_local: typing.Optional[torch.FloatTensor] = 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.FloatTensor] = 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.FloatTensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values (
torch.FloatTensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 对应输入图像的张量。可以使用 UnlimitedOcrImageProcessor 获取像素值。有关详细信息,请参阅 UnlimitedOcrImageProcessor.call()(UnlimitedOcrProcessor 使用 UnlimitedOcrImageProcessor 来处理图像)。 - pixel_values_local (
torch.FloatTensor,可选) — 形状为(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]. - 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 (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入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.FloatTensor)
UnlimitedOcrModelOutputWithPast 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(UnlimitedOcrConfig)和输入。
UnlimitedOcrModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor)— 模型最后一层输出的隐藏状态序列。如果使用了
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.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 之后的权重,用于在自注意力头中计算加权平均值。
image_hidden_states (
torch.FloatTensor,可选) — 大小为(batch_size, num_images, sequence_length, hidden_size)的torch.FloatTensor。 由视觉编码器生成的模型 image_hidden_states,并在投影最后一个隐藏状态之后得到。router_logits (
tuple[torch.FloatTensor],可选,在传入output_router_logits=True或config.add_router_probs=True时返回) — 一个torch.FloatTensor元组(每层一个),形状为(batch_size, sequence_length, num_experts)。模型的 Router logits,可用于计算混合专家(Mixture of Experts)模型的辅助损失。
UnlimitedOcrForConditionalGeneration
class transformers.UnlimitedOcrForConditionalGeneration
< source >( config: UnlimitedOcrConfig )
参数
- config (UnlimitedOcrConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
用于基于其他模态(例如图像-文本到文本生成)进行 token 生成的 Unlimited Ocr Model。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Nonepixel_values_local: typing.Optional[torch.FloatTensor] = 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.FloatTensor] = 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.FloatTensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values (
torch.FloatTensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。像素值可通过 UnlimitedOcrImageProcessor 获取。有关详细信息,请参阅 UnlimitedOcrImageProcessor.call()(UnlimitedOcrProcessor 使用 UnlimitedOcrImageProcessor 处理图像)。 - pixel_values_local (
torch.FloatTensor,可选) — 形状为(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]. - 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 (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入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.FloatTensor)
UnlimitedOcrCausalLMOutputWithPast 或 torch.FloatTensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(UnlimitedOcrConfig)和输入。
UnlimitedOcrForConditionalGeneration 的 forward 方法会重写 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.FloatTensor,形状为(1,),可选,在提供labels时返回) — 语言建模损失(用于下一个 token 预测)。logits(形状为
(batch_size, sequence_length, config.vocab_size)的torch.FloatTensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。past_key_values(
Cache,可选,在传入use_cache=True或config.use_cache=True时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见
past_key_values输入)加速顺序解码。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 之后的权重,用于在自注意力头中计算加权平均值。
image_hidden_states (
torch.FloatTensor,可选) — 一个形状为 (batch_size * num_patches, num_images, sequence_length, hidden_size)` 的torch.FloatTensor。 由视觉编码器生成的模型 image_hidden_states,并在投影最后一个隐藏状态之后得到。router_logits (
tuple[torch.FloatTensor],可选,在传入output_router_logits=True或config.add_router_probs=True时返回) — 一个torch.FloatTensor元组(每层一个),形状为(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...