Transformers documentation
MiniCPM-OCR
该模型于 2025-09-16 在 HF papers 上发布,并于 2026-10-26 贡献至 Hugging Face Transformers。
MiniCPM-OCR
MiniCPM-OCR 是由 OpenBMB 开发的 MiniCPM-V 系列中的文档理解模型。它沿用了 MiniCPM-V 4.6 的架构——在 Qwen3.5 语言模型之前,采用带有窗口注意力合并器的 SigLIP 视觉编码器——并针对阅读文本密集型图像(如扫描页面、截图、收据和表格)进行了专门优化。
使用示例
from transformers import pipeline
messages = [
{
"role": "user",
"content": [
{
"type": "image",
"image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_receipt.jpeg",
},
{"type": "text", "text": "Transcribe all the text in this document."},
],
},
]
pipe = pipeline("image-text-to-text", model="openbmb/MiniCPM-OCR-1.0")
outputs = pipe(text=messages, max_new_tokens=256, return_full_text=False)
print(outputs[0]["generated_text"])
#
#
# Document No : TD01167104
# Date : 25/12/2018 8:13:39 PM
# Cashier : MANIS
# Member :
# CASH BILL
# CODE/DESC PRICE Disc AMOUNT
# QTY RM RM
# 9556939040118 KF MODELLING CLAY KIDDY FISH
# 1 PC * 9.00 0.00 9.00
# Total : 9.00
# Rounding Adjustment : 0.00
# Round-d Total (RM) : 9.00from transformers import AutoModelForImageTextToText, AutoProcessor
model_id = "openbmb/MiniCPM-OCR-1.0"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(model_id, device_map="auto")
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg"},
{"type": "text", "text": "Convert this page to markdown."},
],
}
]
inputs = processor.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True,
return_dict=True, return_tensors="pt",
).to(model.device, dtype=model.dtype)
output = model.generate(**inputs, max_new_tokens=512)
decoded_output = processor.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
print(decoded_output)
# ```markdown
# R&D QUALITY IMPROVEMENT
# SUGGESTION/SOLUTION FORM
#
# Name/Phone Ext.: M. Hamann, P. Harper, P. Martinez Date: 9/3/92
#
# Supervisor/Manager: J. S. Wigand R&D Group: Licensee
# ...
# ```已发布的检查点的聊天模板默认禁用思考功能。向 apply_chat_template 传入 enable_thinking=True 即可显式启用该功能。
MiniCPM-OCR 支持 MiniCPM-V 系列的两种视觉下采样模式:
- 4x(默认值):下采样程度更低,视觉 token 更多,适用于文档和截图转录场景。
- 16x:更激进的降采样,更少的视觉 token,在自然图像上推理速度更快。
必须将 mode 同时传递给 processor 和 model.generate,因为 processor 需要计算视觉塔预期生成的视觉占位符数量:
from transformers import AutoModelForImageTextToText, AutoProcessor
model_id = "openbmb/MiniCPM-OCR-1.0"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(model_id, device_map="auto")
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg"},
{"type": "text", "text": "Convert this page to markdown."},
],
}
]
inputs = processor.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True,
return_dict=True, return_tensors="pt",
processor_kwargs={"downsample_mode": "4x"},
).to(model.device, dtype=model.dtype)
output = model.generate(**inputs, max_new_tokens=512, downsample_mode="4x")
print((inputs["input_ids"] == model.config.image_token_id).sum().item())
# 1260 visual tokens; the same page in `"16x"` mode is 315 instead针对单次调用的 downsample_mode 仅对该次调用生效,不会修改处理器本身,因此同一个处理器可以并发地服务于两种模式。如果直接调用处理器而不是通过 apply_chat_template,请将其作为普通的关键字参数传入:
inputs = processor(images=[image], text=[text], return_tensors="pt", downsample_mode="4x")若要将其设为默认模式,请在加载处理器时进行设置:
processor = AutoProcessor.from_pretrained("openbmb/MiniCPM-OCR-1.0", downsample_mode="4x")尺寸过小、无法进行切片的图像默认会被放大至 scale_resolution,即发布检查点所使用的训练设置。对于截图和裁剪图像,通常建议保留其原始分辨率,因为放大只会使字形变得模糊,因此 small_image_upsize 用于在这两种处理方式之间进行选择:
"always"(默认值):将它们放大至scale_resolution。"never":保持其原始分辨率,仅对齐到 patch 网格。"adaptive":根据字形大小和密度,逐张图像、逐切片进行决策。
from transformers import AutoProcessor
from transformers.image_utils import load_image
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_receipt.jpeg"
image = load_image(url).resize((224, 224))
processor = AutoProcessor.from_pretrained("openbmb/MiniCPM-OCR-1.0")
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Read the text."}]}]
text = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
print(processor(images=[image], text=[text], return_tensors="pt")["target_sizes"].tolist())
# [[32, 32]] -- upscaled to `scale_resolution`
processor = AutoProcessor.from_pretrained("openbmb/MiniCPM-OCR-1.0", small_image_upsize="never")
print(processor(images=[image], text=[text], return_tensors="pt")["target_sizes"].tolist())
# [[16, 16]] -- 224 / 14 patches per side, no upscaling"adaptive" 模式会将小尺寸密集文本放大至 scale_resolution,将低于 6272 像素的图像放大至 84,其余图像保持原始分辨率;在切片处理中,其消耗的 token 数绝不会超过基线瓦片。字形的高度和密度通过 Otsu 阈值法结合连通域分析进行测量,因此该模式依赖 OpenCV,若未安装则会直接抛出异常,而不是静默回退到其他规则。
processor = AutoProcessor.from_pretrained("openbmb/MiniCPM-OCR-1.0", small_image_upsize="adaptive")
print(processor(images=[image], text=[text], return_tensors="pt")["target_sizes"].tolist())
# [[32, 32]] -- dense text detected, so this one is upscaled anyway与 downsample_mode 类似,它也可以在每次调用时进行覆盖,从而在不重新加载处理器的情况下,将 224x224 的收据保持在其原始分辨率:
inputs = processor(images=[image], text=[text], return_tensors="pt", small_image_upsize="never")
print(inputs["target_sizes"].tolist())
# [[16, 16]] -- 224 / 14 patches per side, no upscalingfrom transformers import AutoModelForImageTextToText, AutoProcessor
model_id = "openbmb/MiniCPM-OCR-1.0"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(model_id, device_map="auto")
messages = [
[
{
"role": "user",
"content": [
{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_receipt.jpeg"},
{"type": "text", "text": "Transcribe all the text in this document."},
],
}
],
[
{
"role": "user",
"content": [
{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/ocr_suggestion_form.jpg"},
{"type": "text", "text": "Transcribe all the text in this document."},
],
}
],
]
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, dtype=model.dtype)
output = model.generate(**inputs, max_new_tokens=256)
decoded_outputs = processor.batch_decode(output[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
print(decoded_outputs[0])
# Document No : TD01167104
# Date : 25/12/2018 8:13:39 PM
# Cashier : MANIS
# ...
print(decoded_outputs[1])
# R&D QUALITY IMPROVEMENT
# SUGGESTION/SOLUTION FORM
#
# Name/Phone Ext.: M. Hamann P. Harper P. Martinez Date: 9/3/92
# Supervisor/Manager: J. S. Wigand R&D Group: Licensee
# ...这两个页面是独立调整大小的,因此它们的提示词长度不同。必须通过 processor_kwargs 请求 padding,以便 apply_chat_template 将其转发给处理器,并且处理器会在左侧填充,从而确保 generate 始终从每个提示词的末尾开始生成。
MiniCPMOcrConfig
class transformers.MiniCPMOcrConfig
< 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 = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneinsert_layer_id: int = 6image_token_id: int | None = Nonevideo_token_id: int | None = Nonetie_word_embeddings: bool = Truedownsample_mode: str = '4x'merge_kernel_size: tuple[int, int] | list[int] = (2, 2)merger_times: int = 1 )
参数
- text_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。 - vision_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。 - insert_layer_id (
int,可选,默认为 6) — 应用窗口注意力合并器的视觉编码器层索引。 - image_token_id (
int, 可选) — 用作输入图像占位符的图像 token 索引。 - video_token_id (
int, 可选) — 用作输入视频占位符的视频 token 索引。 - tie_word_embeddings (
bool,可选,默认为True) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。 - downsample_mode (
str,可选,默认为"4x") — 视觉 token 的下采样比例。"4x"保留的 token 数量是"16x"的 4 倍,后者用于读取文本密集型的文档图像。 - merge_kernel_size (
tuple[int, int],可选,默认为(2, 2)) — 用于在 Merger 中合并相邻视觉 patch 的卷积核大小(h, w)。 - merger_times (
int,可选,默认为 1) — Merger 中迭代合并轮次的数量。
这是用于存储 MiniCPMOcrModel 配置的类。它根据指定的参数实例化 Minicpm Ocr 模型,并定义模型架构。使用默认值实例化配置,将得到与 openbmb/MiniCPM-OCR-1.0 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
MiniCPMOcrVisionConfig
class transformers.MiniCPMOcrVisionConfig
< 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 = 768intermediate_size: int = 3072num_hidden_layers: int = 12num_attention_heads: int = 12num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'gelu_pytorch_tanh'layer_norm_eps: float = 1e-06attention_dropout: float | int = 0.0insert_layer_id: int = 6window_kernel_size: tuple[int, int] | list[int] = (2, 2) )
参数
- 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]],可选,默认为224) — 每张图片的尺寸(分辨率)。 - 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 比率。 - insert_layer_id (
int,可选,默认为 6) — 应用窗口注意力合并器的视觉编码器层索引。 - window_kernel_size (
tuple[int, int],可选,默认为(2, 2)) — 中间窗口注意力合并器的窗口大小(h, w)。
这是用于存储 MiniCPMOcrModel 配置的类。它根据指定的参数实例化 Minicpm Ocr 模型,并定义模型架构。使用默认值实例化配置,将得到与 openbmb/MiniCPM-OCR-1.0 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
MiniCPMOcrVisionPreTrainedModel
class transformers.MiniCPMOcrVisionPreTrainedModel
< source >( config: PreTrainedConfig*inputs**kwargs )
MiniCPMOcrVisionModel
forward
< source >( pixel_valuestarget_sizes: typing.Optional[torch.IntTensor] = Noneuse_vit_merger: bool = True**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values (`
of shape(batch_size, num_channels, image_size, image_size)`) — 与输入图像对应的张量。可以使用 MiniCPMOcrImageProcessor 获取像素值。有关详细信息,请参阅 MiniCPMOcrImageProcessor.call()(MiniCPMOcrProcessor 使用 MiniCPMOcrImageProcessor 来处理图像)。 - target_sizes (
torch.IntTensor,形状为(batch_size, 2),可选) — 用于计算位置嵌入的补丁网格大小(h, w)。 - use_vit_merger (
bool,可选,默认为True) — 是否在编码器之后应用 ViT 窗口注意力合并器。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MiniCPMOcrConfig)和输入。
MiniCPMOcrVisionModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
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 之后的权重,用于在自注意力头中计算加权平均值。
MiniCPMOcrModel
class transformers.MiniCPMOcrModel
< source >( config: MiniCPMOcrConfig )
参数
- config (MiniCPMOcrConfig) — 模型配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
MiniCPMOcr 模型由视觉主干网络和语言模型组成,不包含语言建模头。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonetarget_sizes: typing.Optional[torch.IntTensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Nonetarget_sizes_videos: typing.Optional[torch.IntTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: list[torch.Tensor] | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneuse_cache: bool | None = Nonedownsample_mode: str | None = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | 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()。
- pixel_values (
torch.Tensor, 可选) — 图像的像素值补丁,采用 NaViT 打包格式。 - target_sizes (
torch.IntTensor,可选) — 每张图片的高度和宽度(以 patch 为单位)。 - pixel_values_videos (
torch.Tensor, 可选) — 视频帧的像素值补丁,采用 NaViT 打包格式。 - target_sizes_videos (
torch.IntTensor, 可选) — 每个视频帧的高度和宽度(以 patch 为单位)。 - 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 (
list[torch.Tensor], 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由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)。 - downsample_mode (
str,可选) —"4x"保留 4 倍数量的视觉 token;默认值"16x"应用完全合并。 - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions)pooler_output,形状为(batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。
返回值
BaseModelOutputWithPast 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MiniCPMOcrConfig)和输入。
MiniCPMOcrModel 的 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 指南。包含预计算的隐藏状态(自注意力块中的键和值,以及如果
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 之后的权重,用于在自注意力头中计算加权平均值。
get_image_features
< source >( pixel_values: Tensortarget_sizes: IntTensordownsample_mode: str | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 MiniCPMOcrImageProcessor 获取像素值。有关详细信息,请参阅 MiniCPMOcrImageProcessor.call()(MiniCPMOcrProcessor 使用 MiniCPMOcrImageProcessor 来处理图像)。 - target_sizes(形状为
(num_images, 2)的torch.IntTensor)— 每张图片的高度和宽度(以 patch 为单位)。 - downsample_mode (
str, 可选) — 当设置为"4x"时,会跳过中间的vit_merger,从而使每张图像保留4×倍的视觉 token。默认的"16x"模式会应用完整的合并流程。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MiniCPMOcrConfig)和输入。
提取图像特征:视觉编码器,插入合并器,然后是 MLP 合并器。
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 之后的权重,用于在自注意力头中计算加权平均值。
get_video_features
< source >( pixel_values_videos: Tensortarget_sizes_videos: IntTensordownsample_mode: str | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- pixel_values_videos (
torch.Tensor,形状为(1, channels, patch_size, seq_len)) — 所有视频帧的 NaViT 打包像素块。视频处理器将每一帧的块沿最后一个维度拼接为一个序列,其中 dim-0 = 1,与图像打包格式完全相同。 - target_sizes_videos(形状为
(num_patches, 2)的torch.IntTensor)— 每个视觉单元的高度和宽度(以 patch 为单位)。 - downsample_mode (
str, 可选) — 当设置为"4x"时,会跳过中间的vit_merger,使每帧保留4×倍的视觉 token。默认的"16x"模式会应用完整的合并流程。
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MiniCPMOcrConfig)和输入。
提取视频特征:将帧重新打包为 NaViT 格式,然后使用视觉编码器 + 合并器。
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 之后的权重,用于在自注意力头中计算加权平均值。
MiniCPMOcrForConditionalGeneration
类 transformers.MiniCPMOcrForConditionalGeneration
< source >( config: MiniCPMOcrConfig )
参数
- config (MiniCPMOcrConfig) — 模型配置类,包含模型的所有参数。通过配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
用于在其他模态(例如图像-文本到文本生成)条件下进行 token 生成的 Minicpm Ocr 模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Nonetarget_sizes: typing.Optional[torch.IntTensor] = Nonepixel_values_videos: typing.Optional[torch.Tensor] = Nonetarget_sizes_videos: typing.Optional[torch.IntTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: list[torch.Tensor] | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonedownsample_mode: str | None = Nonemm_encoder_outputs: dict[str, transformers.modeling_outputs.BaseModelOutputWithPooling] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → CausalLMOutputWithPast or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- pixel_values (
torch.Tensor, 可选) — 图像的像素值补丁,采用 NaViT 打包格式。 - target_sizes (
torch.IntTensor,可选) — 每张图片的高度和宽度(以 patch 为单位)。 - pixel_values_videos (
torch.Tensor, 可选) — 视频帧的像素值补丁,采用 NaViT 打包格式。 - target_sizes_videos (
torch.IntTensor, 可选) — 每个视频帧的高度和宽度(以 patch 为单位)。 - 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 (
list[torch.Tensor], 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由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)。 - downsample_mode (
str,可选) —"4x"保留 4 倍数量的视觉 token;默认值"16x"应用完全合并。 - mm_encoder_outputs (
dict[str, ~modeling_outputs.BaseModelOutputWithPooling], 可选) — 一个字典,其中键为支持的模态,值为该模态的编码输出。每个编码输出是一个元组,由 (pooler_output、可选:last_hidden_states、可选:hidden_states、可选:attentions)pooler_output,形状为(batch_size, sequence_length, hidden_size),可选) 组成,它是编码器融合到文本嵌入中的多模态特征序列。
返回值
CausalLMOutputWithPast 或 tuple(torch.Tensor)
一个 CausalLMOutputWithPast 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MiniCPMOcrConfig)和输入。
MiniCPMOcrForConditionalGeneration 的 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 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from PIL import Image
>>> from transformers import AutoProcessor, MiniCPMOcrForConditionalGeneration
>>> model = MiniCPMOcrForConditionalGeneration.from_pretrained("openbmb/MiniCPM-OCR-1.0")
>>> processor = AutoProcessor.from_pretrained("openbmb/MiniCPM-OCR-1.0")
>>> 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]get_image_features
< source >( *args**kwargs ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MiniCPMOcrConfig)和输入。
提取图像特征:视觉编码器,插入合并器,然后是 MLP 合并器。
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, MiniCPMOcrForConditionalGeneration
>>> model = MiniCPMOcrForConditionalGeneration.from_pretrained("openbmb/MiniCPM-OCR-1.0")
>>> processor = AutoProcessor.from_pretrained("openbmb/MiniCPM-OCR-1.0")
>>> 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]get_video_features
< source >( *args**kwargs ) → BaseModelOutputWithPooling or tuple(torch.Tensor)
返回值
BaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MiniCPMOcrConfig)和输入。
提取视频特征:将帧重新打包为 NaViT 格式,然后使用视觉编码器 + 合并器。
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, MiniCPMOcrForConditionalGeneration
>>> model = MiniCPMOcrForConditionalGeneration.from_pretrained("openbmb/MiniCPM-OCR-1.0")
>>> processor = AutoProcessor.from_pretrained("openbmb/MiniCPM-OCR-1.0")
>>> 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]MiniCPMOcrProcessor
class transformers.MiniCPMOcrProcessor
< source >( image_processor = Nonevideo_processor = Nonetokenizer = Nonechat_template = None**kwargs )
构建一个 MiniCPMOcrProcessor,它将图像处理器、视频处理器和分词器封装为单一处理器。
MiniCPMOcrProcessor 提供了 MiniCPMOcrImageProcessor、MiniCPMOcrVideoProcessor 和 TokenizersBackend 的全部功能。有关更多信息,请参阅 ~MiniCPMOcrImageProcessor、~MiniCPMOcrVideoProcessor 和 ~TokenizersBackend。
__call__
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] | None = Nonevideos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None**kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'> )
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], 可选) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - text (
Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置is_split_into_words=True,以避免与批量输入产生歧义。 - videos (
Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]], 可选) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置do_rescale=False。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:'pt':返回 PyTorchtorch.Tensor对象。'np':返回 NumPynp.ndarray对象。
- **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
MiniCPMOcrImageProcessor
class transformers.MiniCPMOcrImageProcessor
< source >( **kwargs: *<class 'transformers.models.minicpm_ocr.image_processing_minicpm_ocr.MiniCPMOcrImageProcessorKwargs'> )
参数
- 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) — 描述模型的最大输入维度。
- default_to_square (bool,kwargs,可选,默认为 True) — 当 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,默认为 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, optional) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
- 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, optional) —
输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
- “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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
- max_slice_nums (int,kwargs,可选,默认值为 9) — 分割高分辨率图像时的最大切片数量。
- scale_resolution (int,kwargs,可选,默认值为 448) — 单个切片的分辨率。
- patch_size (int, kwargs, 可选,默认为 14) — 视觉编码器的空间块大小。
- slice_mode (bool,kwargs,可选,默认为 True) — 是否将图像分割为多个切片以提高分辨率。
- downsample_mode (str,kwargs,可选,默认为 “4x”) — 视觉 token 的下采样模式。“4x” 保留的 token 数量是 “16x” 的 4 倍,后者会应用完整的合并。支持在每次调用时覆盖该设置。
- use_image_id (bool,kwargs,可选,默认为 True) —
是否在每个图像占位符之前添加图像 ID 标签(
<image_id>N</image_id>)。该参数由 Processor 用于生成占位符,而非由图像处理流水线本身使用。 - small_image_upsize (str, kwargs, 可选,默认为 “always”) — 指定边长不超过 scale_resolution 的图像和切片如何调整大小。“always” 会将它们放大至 scale_resolution,“never” 保持其原始分辨率并对齐到 patch 网格,而 “adaptive” 则根据字形大小和密度为每张图像和每个切片单独选择(需要 OpenCV,参见 [adaptive_upsize_resolution])。
构建一个 MiniCPMOcrImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.minicpm_ocr.image_processing_minicpm_ocr.MiniCPMOcrImageProcessorKwargs'> ) → ~feature_extraction_utils.BatchFeature
参数
- images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False。
- do_convert_rgb (bool, kwargs, 可选) — 是否将图像转换为 RGB。
- do_resize (bool,kwargs,可选) — 是否调整图像大小。
- size (Annotated[int | list[int] | tuple[int, …] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
- default_to_square (bool,kwargs,可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
- crop_size (Annotated[int | list[int] | tuple[int, …] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
- resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
- do_rescale (bool, kwargs, 可选) — 是否对图像进行重新缩放。
- rescale_factor (float, kwargs, optional) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
- do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
- image_mean (Union[float, list[float], tuple[float, …]], kwargs, optional) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
- image_std (Union[float, list[float], tuple[float, …]], kwargs, optional) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
- do_pad (bool, kwargs, optional) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
- 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, optional) —
输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
- “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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
- max_slice_nums (int,kwargs,可选,默认值为 9) — 分割高分辨率图像时的最大切片数量。
- scale_resolution (int,kwargs,可选,默认值为 448) — 单个切片的分辨率。
- patch_size (int, kwargs, 可选,默认为 14) — 视觉编码器的空间块大小。
- slice_mode (bool,kwargs,可选,默认为 True) — 是否将图像分割为多个切片以提高分辨率。
- downsample_mode (str,kwargs,可选,默认为 “4x”) — 视觉 token 的下采样模式。“4x” 保留的 token 数量是 “16x” 的 4 倍,后者会应用完整的合并。支持在每次调用时覆盖该设置。
- use_image_id (bool,kwargs,可选,默认为 True) —
是否在每个图像占位符之前添加图像 ID 标签(
<image_id>N</image_id>)。该参数由 Processor 用于生成占位符,而非由图像处理流水线本身使用。 - small_image_upsize (str, kwargs, 可选,默认为 “always”) — 指定边长不超过 scale_resolution 的图像和切片如何调整大小。“always” 会将它们放大至 scale_resolution,“never” 保持其原始分辨率并对齐到 patch 网格,而 “adaptive” 则根据字形大小和密度为每张图像和每个切片单独选择(需要 OpenCV,参见 [adaptive_upsize_resolution])。
返回值
~feature_extraction_utils.BatchFeature
- data (dict,可选) — 由 call/pad 方法返回的列表/数组/张量字典(如 ‘input_values’、‘attention_mask’ 等)。
- tensor_type (Union[None, str, TensorType],可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
- skip_tensor_conversion(list[str] 或 set[str],可选)—— 即使指定了 tensor_type,也不应转换为张量的键的列表或集合。
MiniCPMOcrVideoProcessor
class transformers.MiniCPMOcrVideoProcessor
< source >( **kwargs: *<class 'transformers.models.minicpm_ocr.video_processing_minicpm_ocr.MiniCPMOcrVideoProcessorKwargs'> )
参数
- 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) — 描述模型的最大输入维度。
- default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
- 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_center_crop (bool, kwargs, 可选) — 是否对图像进行中心裁剪。
- do_pad (bool, kwargs, optional) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
- crop_size (Annotated[int | list[int] | tuple[int, …] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
- data_format (Union[str, ~image_utils.ChannelDimension],kwargs,可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
- input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, optional) —
输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
- “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) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
- do_sample_frames (bool,kwargs,可选,默认为 True) — 是否在处理前从视频中采样帧,还是处理整个视频。
- video_metadata (Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 视频的元数据,包含总时长、帧率(fps)和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频,否则请勿传入任何元数据。
- fps (Annotated[int | float | None, None], kwargs) — 当 do_sample_frames=True 时,每秒要采样的目标帧数。
- num_frames (Annotated[int | None, None], kwargs) — 当 do_sample_frames=True 时,要采样的最大帧数。
- return_metadata (bool,kwargs,可选,默认为 False) — 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。
- return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) —
如果设置,将返回特定框架的张量。可接受的值为:
- ‘pt’:返回 PyTorch torch.Tensor 对象。
- ‘np’:返回 NumPy np.ndarray 对象。
- max_num_frames (int, kwargs, 可选,默认为 128) — 每个视频要采样的主帧最大数量。
- stack_frames (int, kwargs, 可选,默认为 1) —
每秒堆叠的子帧数。
1表示禁用堆叠。 - max_slice_nums (int,kwargs,可选,默认值为 9) — 分割高分辨率图像时的最大切片数量。
- scale_resolution (int,kwargs,可选,默认值为 448) — 单个切片的分辨率。
- patch_size (int, kwargs, 可选,默认为 14) — 视觉编码器的空间块大小。
- slice_mode (bool,kwargs,可选,默认为 True) — 是否将图像分割为多个切片以提高分辨率。
- downsample_mode (str, kwargs, 可选,默认为 “4x”) — 视觉 token 的下采样模式。“4x” 保留的 token 数量是 “16x” 的 4 倍,后者会应用完整的合并。
- use_image_id (bool,kwargs,可选,默认为 True) —
是否在每个图像占位符之前添加图像 ID 标签(
<image_id>N</image_id>)。该参数由 Processor 用于生成占位符,而非由图像处理流水线本身使用。 - **kwargs ([ProcessingKwargs], 可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。
构建一个 MiniCPMOcrVideoProcessor 视频处理器。
预处理
< source >( videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]]]**kwargs: *<class 'transformers.processing_utils.VideosKwargs'> ) → ~feature_extraction_utils.BatchFeature
参数
- videos (
Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]) — 要预处理的视频。期望输入单个视频或一批视频,其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间,请设置do_rescale=False。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - 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_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - 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) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - do_sample_frames (
bool, kwargs, 可选) — 是否在处理前对视频进行帧采样,还是处理整个视频。 - video_metadata (
Annotated[~video_utils.VideoMetadata | dict | list[dict | ~video_utils.VideoMetadata] | list[list[dict | ~video_utils.VideoMetadata]] | None, None], kwargs) — 视频的元数据,包含总时长、帧率(fps)和总帧数等信息。该元数据将用于从视频中采样帧或计算时间戳。除非您打算在预处理之前手动解码视频,否则请勿传入任何元数据。 - fps (
Annotated[int | float | None, None], kwargs) — 当do_sample_frames=True时,每秒要采样的目标帧数。 - num_frames (
Annotated[int | None, None], kwargs) — 当do_sample_frames=True时,要采样的最大帧数。 - return_metadata (
bool, kwargs, 可选) — 是否返回视频元数据。视频元数据是一个包含视频时长、帧率、解码后端等信息的对象。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。
返回值
~feature_extraction_utils.BatchFeature
- data (
dict,可选) — 由 call/pad 方法返回的列表/数组/张量字典(例如 ‘input_values’、‘attention_mask’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。 - skip_tensor_conversion(
list[str]或set[str],可选)——即使指定了tensor_type,也不应转换为张量的键的列表或集合。