Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Refactor FormulaRecognizer to support multiple model variants and enhance caching mechanism

myhloli9d5ff639db5a
diff --git a/mineru/model/_internal/pytorchocr/modeling/backbones/__init__.py b/mineru/model/_internal/pytorchocr/modeling/backbones/__init__.py
index 1c884044..78bdcea1 100644
--- a/mineru/model/_internal/pytorchocr/modeling/backbones/__init__.py
+++ b/mineru/model/_internal/pytorchocr/modeling/backbones/__init__.py
@@ -37,7 +37,7 @@ def build_backbone(config, model_type):
from .rec_mobilenet_v3 import MobileNetV3
from .rec_svtrnet import SVTRNet
from .rec_mv1_enhance import MobileNetV1Enhance
- from .rec_pphgnetv2 import PPHGNetV2_B4, PPHGNetV2_B6_Formula
+ from .rec_pphgnetv2 import PPHGNetV2_B4, PPHGNetV2_B4_Formula, PPHGNetV2_B6_Formula
support_dict = {
"MobileNetV1Enhance": MobileNetV1Enhance,
"MobileNetV3": MobileNetV3,
@@ -47,6 +47,7 @@ def build_backbone(config, model_type):
"PPHGNet_small": PPHGNet_small,
"PPHGNetV2_B4": PPHGNetV2_B4,
"PPHGNetV2_B6_Formula": PPHGNetV2_B6_Formula,
+ "PPHGNetV2_B4_Formula": PPHGNetV2_B4_Formula,
}
else:
raise NotImplementedError
diff --git a/mineru/model/_internal/pytorchocr/modeling/backbones/rec_pphgnetv2.py b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_pphgnetv2.py
index 3114fdf1..be24d4d7 100644
--- a/mineru/model/_internal/pytorchocr/modeling/backbones/rec_pphgnetv2.py
+++ b/mineru/model/_internal/pytorchocr/modeling/backbones/rec_pphgnetv2.py
@@ -1550,7 +1550,7 @@ class PPHGNetV2_B4_Formula(nn.Module):
pixel_values = torch.repeat_interleave(pixel_values, repeats=3, dim=1)
pphgnet_b4_output = self.pphgnet_b4(pixel_values)
b, c, h, w = pphgnet_b4_output.shape
- pphgnet_b4_output = pphgnet_b4_output.reshape([b, c, h * w]).transpose(
+ pphgnet_b4_output = pphgnet_b4_output.reshape([b, c, h * w]).permute(
[0, 2, 1]
)
pphgnet_b4_output = DonutSwinModelOutput(
diff --git a/mineru/model/_internal/pytorchocr/modeling/heads/generation_cache.py b/mineru/model/_internal/pytorchocr/modeling/heads/generation_cache.py
new file mode 100644
index 00000000..5823abcf
--- /dev/null
+++ b/mineru/model/_internal/pytorchocr/modeling/heads/generation_cache.py
@@ -0,0 +1,37 @@
+"""公式增量生成专用缓存;缓存仅由当前调用持有,不写入模型权重。"""
+
+import torch
+
+
+class GrowingLayerCache(tuple):
+ """兼容四项层缓存协议,按几何增长容量保存 self-attention K/V。"""
+
+ def __new__(cls, states, buffers=None):
+ """保留普通元组索引协议,并携带当前调用独享的底层缓冲区。"""
+ instance = super().__new__(cls, states)
+ instance.buffers = buffers
+ return instance
+
+ def append(self, key, value):
+ """仅写入新增 token,容量不足时扩容,避免逐轮复制完整历史。"""
+ if torch.is_grad_enabled():
+ raise RuntimeError("GrowingLayerCache is only valid during inference")
+ length = self[0].shape[2]
+ needed = length + key.shape[2]
+ buffers = self.buffers
+ if buffers is None or needed > buffers[0].shape[2]:
+ capacity = max(64, 1 << (needed - 1).bit_length())
+ shape = (*key.shape[:2], capacity, key.shape[3])
+ buffers = (key.new_empty(shape), value.new_empty(shape))
+ if length:
+ buffers[0][:, :, :length].copy_(self[0])
+ buffers[1][:, :, :length].copy_(self[1])
+ buffers[0][:, :, length:needed].copy_(key)
+ buffers[1][:, :, length:needed].copy_(value)
+ return type(self)(
+ (buffers[0][:, :, :needed], buffers[1][:, :, :needed]), buffers
+ )
+
+ def __add__(self, cross_states):
+ """拼接 cross-attention 状态时保留 self-attention 缓冲区所有权。"""
+ return type(self)(tuple(self) + tuple(cross_states), self.buffers)
diff --git a/mineru/model/_internal/pytorchocr/modeling/heads/rec_ppformulanet_head.py b/mineru/model/_internal/pytorchocr/modeling/heads/rec_ppformulanet_head.py
index 6ba09d25..4785f346 100644
--- a/mineru/model/_internal/pytorchocr/modeling/heads/rec_ppformulanet_head.py
+++ b/mineru/model/_internal/pytorchocr/modeling/heads/rec_ppformulanet_head.py
@@ -23,8 +23,8 @@ from typing import Optional, Tuple, Union, List, Dict, Any
from dataclasses import dataclass, fields, is_dataclass
from sympy import totient
+from .generation_cache import GrowingLayerCache
-from .....runtime.device import get_device
from .rec_unimernet_head import (
MBartForCausalLM,
MBartDecoder,
@@ -81,14 +81,14 @@ class AttentionMaskConverter:
bsz, tgt_len = input_ids_shape
if is_export:
mask = torch.full(
- (tgt_len, tgt_len), torch.finfo(dtype).min, dtype=torch.float64
+ (tgt_len, tgt_len), torch.finfo(dtype).min, dtype=dtype
)
mask_cond = torch.arange(mask.shape[-1])
mask.masked_fill_(
mask_cond < (mask_cond + 1).reshape([mask.shape[-1], 1]), 0
)
else:
- mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min)
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, dtype=dtype)
mask_cond = torch.arange(mask.shape[-1])
mask.masked_fill_(
mask_cond < (mask_cond + 1).reshape([mask.shape[-1], 1]), 0
@@ -127,7 +127,7 @@ class AttentionMaskConverter:
Make causal mask used for bi-directional self-attention.
"""
bsz, tgt_len = input_ids_shape
- mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min)
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, dtype=dtype)
mask_cond = torch.arange(mask.shape[-1])
mask_cond_parallel = torch.arange(mask.shape[-1])
@@ -220,7 +220,7 @@ class AttentionMaskConverter:
)
if causal_4d_mask is not None:
- expanded_attn_mask = causal_4d_mask.masked_fill_(
+ expanded_attn_mask = causal_4d_mask.to(expanded_attn_mask.device).masked_fill_(
expanded_attn_mask.to(torch.bool), torch.finfo(dtype).min
)
@@ -469,7 +469,11 @@ class CustomMBartDecoder(MBartDecoder):
)
else:
# 4d mask is passed through the layers
- if self.is_export:
+ # 增量推理每次只处理一个并行组;历史与本组均可见,无需构造全零 mask。
+ group_size = self.config_decoder.parallel_step if self.config_decoder.use_parallel else 1
+ if self.is_export and attention_mask is None and input_shape[-1] <= group_size:
+ attention_mask = None
+ elif self.is_export:
attention_mask = _prepare_4d_causal_attention_mask_export(
attention_mask,
input_shape,
@@ -799,7 +803,19 @@ class PPFormulaNet_Head(UniMERNetHead):
generation_config["forced_eos_token_id"],
)
)
- self.device = torch.device(get_device())
+
+
+ def set_fast_attention(self, enabled=True):
+ """为本模型实例启用增量缓存和 SDPA,保留关闭开关用于数值回归。"""
+ self.use_growing_cache = enabled
+ for layer in self.decoder.model.decoder.layers:
+ layer.self_attn.use_sdpa = enabled
+ layer.encoder_attn.use_sdpa = enabled
+
+ @property
+ def device(self):
+ """跟随参数的实际设备,支持显式 CPU 与模型迁移。"""
+ return self.decoder.model.decoder.embed_tokens.weight.device
def prepare_inputs_for_generation(
self,
@@ -893,27 +909,12 @@ class PPFormulaNet_Head(UniMERNetHead):
return model_kwargs
def stopping_criteria(self, input_ids):
- if self.is_export:
- return input_ids[:, -1].cpu() == torch.Tensor([self.eos_token_id])
- is_done = torch.isin(input_ids[:, -1].cpu(), torch.Tensor([self.eos_token_id]))
- return is_done
+ """在输入设备上判断单 token 生成是否遇到 EOS。"""
+ return input_ids[:, -1].eq(self.eos_token_id)
def stopping_criteria_parallel(self, input_ids):
- parallel_step = self.config_decoder.parallel_step
-
- if self.is_export:
- is_done_list = []
- for i in range(parallel_step, 0, -1):
- cur_is_done = input_ids[:, -i] == torch.Tensor([self.eos_token_id])
- is_done_list.append(cur_is_done)
- is_done_list = torch.Tensor(is_done_list).permute([1, 0])
- return is_done_list
- else:
- is_done = torch.isin(
- input_ids[:, -parallel_step:],
- torch.Tensor([self.eos_token_id]).reshape([1, 1]),
- )
- return torch.Tensor(is_done)
+ """分别判断并行组各位置的 EOS,保持批维度及布尔类型。"""
+ return input_ids[:, -self.config_decoder.parallel_step:].eq(self.eos_token_id)
def generate_single_iter(
self,
@@ -927,12 +928,16 @@ class PPFormulaNet_Head(UniMERNetHead):
output_attentions=None,
output_hidden_states=None,
return_dict=None,
+ projected_encoder_hidden_states=None,
**kwargs,
):
- encoder_hidden_states = encoder_outputs[0]
- if self.config_decoder.hidden_size != self.encoder_hidden_size:
- encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states)
+ # 加速路径传入本批次缓存的投影,其他调用保持原来的逐次计算行为。
+ encoder_hidden_states = projected_encoder_hidden_states
+ if encoder_hidden_states is None:
+ encoder_hidden_states = encoder_outputs[0]
+ if self.config_decoder.hidden_size != self.encoder_hidden_size:
+ encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states)
kwargs_decoder = {}
decoder_outputs = self.decoder(
input_ids=decoder_input_ids,
@@ -989,7 +994,7 @@ class PPFormulaNet_Head(UniMERNetHead):
)
decoder_input_ids_start = torch.Tensor(
decoder_start_token_id
- ).to(torch.int64)
+ ).to(device=self.device, dtype=torch.int64)
decoder_input_ids_start = decoder_input_ids_start.view(-1, 1)
else:
use_parallel = self.config_decoder.use_parallel
@@ -1050,11 +1055,84 @@ class PPFormulaNet_Head(UniMERNetHead):
return decoder_input_ids, model_kwargs
@torch.no_grad()
- def generate_export(
+ def generate_export(self, encoder_outputs, model_kwargs):
+ """标准生成复用增量缓存,CPU 逐轮检查结束;自定义提示保留参考路径。"""
+ # 自定义提示词仍走参考实现,加速路径仅处理模型标准起始组。
+ custom_prompt = any(key in model_kwargs for key in ("decoder_input_ids", "input_ids", "inputs_embeds"))
+ if custom_prompt or (self.device.type == "cpu" and not getattr(self, "use_growing_cache", False)):
+ return self._generate_export_eager(encoder_outputs, model_kwargs)
+ return self._generate_export_accelerated(encoder_outputs, model_kwargs)
+
+ @torch.no_grad()
+ def _generate_export_accelerated(self, encoder_outputs, model_kwargs):
+ """预分配输出并增量维护完成状态,CPU 每轮检查,设备端按段检查。"""
+ parallel = self.config_decoder.use_parallel
+ step = self.config_decoder.parallel_step if parallel else 1
+ rounds = self.max_seq_len // step
+ encoder_states = encoder_outputs["last_hidden_state"]
+ batch_size = encoder_states.shape[0]
+ input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
+ batch_size=batch_size,
+ model_kwargs=model_kwargs,
+ decoder_start_token_id=0,
+ bos_token_id=0,
+ )
+ initial_length = input_ids.shape[1]
+ # 输出只增长到配置允许的整组边界,位置嵌入上限不因延后检查而扩大。
+ tokens = input_ids.new_full((batch_size, initial_length + rounds * step), self.pad_token_id)
+ tokens[:, :initial_length] = input_ids
+ decoder_ids = input_ids
+ projected = encoder_states
+ if self.config_decoder.hidden_size != self.encoder_hidden_size:
+ projected = self.enc_to_dec_proj(projected)
+ heads = self.config_decoder.decoder_attention_heads
+ empty = encoder_states.new_empty((batch_size, heads, 0, self.config_decoder.d_model // heads))
+ cache = [(empty, empty, empty, empty) for _ in range(self.config_decoder.decoder_layers)]
+ if getattr(self, "use_growing_cache", False):
+ cache = [GrowingLayerCache(states) for states in cache]
+ unfinished = torch.ones((batch_size, step), dtype=torch.bool, device=encoder_states.device)
+ # 每行只记录首次 EOS 所在轮次;单次 max().item() 同时判断完成和确定裁剪长度。
+ first_eos_round = input_ids.new_full((batch_size,), rounds + 1)
+ written = initial_length
+ for index in range(rounds):
+ outputs = self.generate_single_iter(
+ decoder_input_ids=decoder_ids,
+ decoder_attention_mask=None,
+ encoder_outputs=encoder_outputs,
+ projected_encoder_hidden_states=projected,
+ past_key_values=cache,
+ return_dict=True,
+ output_attentions=False,
+ output_hidden_states=False,
+ )
+ logits = outputs.logits[:, -step:, :] if parallel else outputs.logits[:, -1, :]
+ scores = self.logits_processor(tokens[:, :written], logits)
+ next_ids = torch.argmax(scores, dim=-1).reshape(batch_size, step)
+ next_ids = torch.where(unfinished, next_ids, self.pad_token_id)
+ tokens[:, written:written + step] = next_ids
+ written += step
+ decoder_ids = next_ids
+ cache = outputs.past_key_values
+ eos = next_ids.eq(self.eos_token_id)
+ unfinished = unfinished & ~eos
+ first_eos_round = torch.where(
+ (first_eos_round == rounds + 1) & eos.any(dim=-1), index + 1, first_eos_round
+ )
+ completed_rounds = index + 1
+ # CPU 每轮检查;设备端最多多算七轮,返回时裁回首次完整结束组。
+ if self.device.type == "cpu" or completed_rounds in (1, 2, 4) or completed_rounds % 8 == 0 or completed_rounds == rounds:
+ last_eos_round = int(first_eos_round.max().item())
+ if last_eos_round <= completed_rounds:
+ return tokens[:, :initial_length + last_eos_round * step].contiguous()
+ return tokens[:, :written].contiguous()
+
+ @torch.no_grad()
+ def _generate_export_eager(
self,
encoder_outputs,
model_kwargs,
):
+ """保留逐轮检查的参考实现,供 CPU 推理及加速路径回归对照。"""
use_parallel = self.config_decoder.use_parallel
parallel_step = self.config_decoder.parallel_step
batch_size = encoder_outputs["last_hidden_state"].shape[0]
@@ -1077,17 +1155,17 @@ class PPFormulaNet_Head(UniMERNetHead):
if "inputs_embeds" in model_kwargs:
cur_len = model_kwargs["inputs_embeds"].shape[1]
- cache_position = torch.arange(cur_len)
+ cache_position = torch.arange(cur_len, device=self.device)
pad_token_id = self.pad_token_id
eos_token_id = [self.eos_token_id]
eos_token = self.eos_token_id
if use_parallel:
unfinished_sequences = torch.ones(
- [batch_size, parallel_step], dtype=torch.int64, device=self.device
+ [batch_size, parallel_step], dtype=torch.bool, device=self.device
)
parallel_length = math.ceil(self.max_seq_len // parallel_step)
else:
- unfinished_sequences = torch.ones(batch_size, dtype=torch.int64, device=self.device)
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.bool, device=self.device)
parallel_length = self.max_seq_len
i_idx = 0
@@ -1098,22 +1176,30 @@ class PPFormulaNet_Head(UniMERNetHead):
)
for i in range(self.config_decoder.decoder_layers):
init_arr = torch.zeros(
- [batch_size, decoder_attention_heads, 0, decoder_attention_heads_dim]
+ [batch_size, decoder_attention_heads, 0, decoder_attention_heads_dim],
+ device=encoder_outputs["last_hidden_state"].device,
+ dtype=encoder_outputs["last_hidden_state"].dtype,
)
cache = (init_arr, init_arr, init_arr, init_arr)
past_key_values.append(cache)
+ # CPU 参考循环也只投影视觉特征一次;线性层输入整批保持不变,无需逐 token 重算。
+ projected = encoder_outputs["last_hidden_state"]
+ if self.config_decoder.hidden_size != self.encoder_hidden_size:
+ projected = self.enc_to_dec_proj(projected)
+
while i_idx < parallel_length:
model_inputs = self.prepare_inputs_for_generation_export(
past_key_values=past_key_values, **model_kwargs
)
- decoder_attention_mask = torch.ones(input_ids.shape, device=self.device)
+ decoder_attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
outputs = self.generate_single_iter(
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
encoder_outputs=encoder_outputs,
+ projected_encoder_hidden_states=projected,
past_key_values=past_key_values,
return_dict=True,
output_attentions=False,
@@ -1133,9 +1219,8 @@ class PPFormulaNet_Head(UniMERNetHead):
raise ValueError(
"If `eos_token_id` is defined, make sure that `pad_token_id` is defined."
)
- next_tokens = next_tokens * unfinished_sequences + pad_token_id * (
- 1 - unfinished_sequences
- )
+ # 完成状态保持 bool,生成 token 和 PAD 保持 int64。
+ next_tokens = torch.where(unfinished_sequences, next_tokens, pad_token_id)
if use_parallel:
input_ids = torch.concat([input_ids, next_tokens], dim=-1)
decoder_input_ids = next_tokens
@@ -1152,12 +1237,12 @@ class PPFormulaNet_Head(UniMERNetHead):
if use_parallel:
unfinished_sequences = (
unfinished_sequences
- & ~self.stopping_criteria_parallel(input_ids).to(torch.int64).to(self.device)
+ & ~self.stopping_criteria_parallel(input_ids)
)
else:
unfinished_sequences = unfinished_sequences & ~self.stopping_criteria(
input_ids
- ).to(torch.int64).to(self.device)
+ )
if (
eos_token is not None
@@ -1219,11 +1304,11 @@ class PPFormulaNet_Head(UniMERNetHead):
eos_token = self.eos_token_id
if use_parallel:
unfinished_sequences = torch.ones(
- [batch_size, parallel_step], dtype=torch.int64
+ [batch_size, parallel_step], dtype=torch.bool, device=self.device
)
parallel_length = math.ceil(self.max_seq_len // parallel_step)
else:
- unfinished_sequences = torch.ones(batch_size, dtype=torch.int64)
+ unfinished_sequences = torch.ones(batch_size, dtype=torch.bool, device=self.device)
parallel_length = self.max_seq_len
past_key_values = []
@@ -1251,9 +1336,8 @@ class PPFormulaNet_Head(UniMERNetHead):
raise ValueError(
"If `eos_token_id` is defined, make sure that `pad_token_id` is defined."
)
- next_tokens = next_tokens * unfinished_sequences + pad_token_id * (
- 1 - unfinished_sequences
- )
+ # 完成状态保持 bool,生成 token 和 PAD 保持 int64。
+ next_tokens = torch.where(unfinished_sequences, next_tokens, pad_token_id)
if use_parallel:
input_ids = torch.concat([input_ids, next_tokens], dim=-1)
else:
@@ -1267,12 +1351,12 @@ class PPFormulaNet_Head(UniMERNetHead):
if use_parallel:
unfinished_sequences = (
unfinished_sequences
- & ~self.stopping_criteria_parallel(input_ids).to(torch.int64)
+ & ~self.stopping_criteria_parallel(input_ids)
)
else:
unfinished_sequences = unfinished_sequences & ~self.stopping_criteria(
input_ids
- ).to(torch.int64)
+ )
if (
eos_token is not None
diff --git a/mineru/model/_internal/pytorchocr/modeling/heads/rec_unimernet_head.py b/mineru/model/_internal/pytorchocr/modeling/heads/rec_unimernet_head.py
index f36be7f8..e94b4928 100644
--- a/mineru/model/_internal/pytorchocr/modeling/heads/rec_unimernet_head.py
+++ b/mineru/model/_internal/pytorchocr/modeling/heads/rec_unimernet_head.py
@@ -14,8 +14,8 @@ import torch.nn as nn
from torch import Tensor
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
+from .generation_cache import GrowingLayerCache
-from .....runtime.device import get_device
class ModelOutput(OrderedDict):
@@ -271,10 +271,10 @@ class AttentionMaskConverter:
bsz, tgt_len = input_ids_shape
if is_export:
mask = torch.full(
- [tgt_len, tgt_len], fill_value=torch.finfo(dtype).min, dtype=torch.float64
+ [tgt_len, tgt_len], fill_value=torch.finfo(dtype).min, dtype=dtype
)
else:
- mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min)
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, dtype=dtype)
mask_cond = torch.arange(mask.shape[-1])
mask = mask.masked_fill_(
mask_cond < (mask_cond + 1).reshape([mask.shape[-1], 1]), 0
@@ -444,14 +444,13 @@ class MBartLearnedPositionalEmbedding(nn.Embedding):
def __init__(self, num_embeddings, embedding_dim):
self.offset = 2
super().__init__(num_embeddings + self.offset, embedding_dim)
- self.device = torch.device(get_device())
def forward(self, input_ids, past_key_values_length=0):
"""`input_ids' shape is expected to be [bsz x seqlen]."""
bsz, seq_len = input_ids.shape[:2]
positions = torch.arange(
- past_key_values_length, past_key_values_length + seq_len, dtype=torch.int64
- ).expand([bsz, -1]).to(self.device)
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.int64, device=self.weight.device
+ ).expand([bsz, -1])
return nn.Embedding.forward(self, positions + self.offset)
@@ -564,15 +563,33 @@ class MBartAttention(nn.Module):
elif past_key_value is not None:
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
- key_states = torch.concat([past_key_value[0], key_states], dim=2)
- value_states = torch.concat([past_key_value[1], value_states], dim=2)
+ if isinstance(past_key_value, GrowingLayerCache):
+ past_key_value = past_key_value.append(key_states, value_states)
+ key_states, value_states = past_key_value
+ else:
+ key_states = torch.concat([past_key_value[0], key_states], dim=2)
+ value_states = torch.concat([past_key_value[1], value_states], dim=2)
else:
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
- if self.is_decoder:
+ if self.is_decoder and not isinstance(past_key_value, GrowingLayerCache):
past_key_value = (key_states, value_states)
+ if getattr(self, "use_sdpa", False) and not output_attentions and layer_head_mask is None:
+ # Q 已按原路径缩放;scale=1 避免重复缩放。增量缓存全部可见,不能额外加因果掩码。
+ attn_output = F.scaled_dot_product_attention(
+ self._shape(query_states, tgt_len, bsz),
+ key_states,
+ value_states,
+ attn_mask=attention_mask,
+ dropout_p=self.dropout if self.training else 0.0,
+ is_causal=False,
+ scale=1.0,
+ )
+ attn_output = attn_output.transpose(1, 2).reshape(bsz, tgt_len, self.embed_dim)
+ return self.out_proj(attn_output), None, past_key_value
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
query_states = self._shape(query_states, tgt_len, bsz).reshape(proj_shape)
key_states = key_states.reshape(proj_shape)
@@ -590,7 +607,8 @@ class MBartAttention(nn.Module):
[bsz * self.num_heads, tgt_len, src_len]
)
- attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+ # FP16 下用 FP32 计算 softmax,再还原 dtype 以匹配后续 value 矩阵。
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
if layer_head_mask is not None:
if tuple(layer_head_mask.shape) != (self.num_heads,):
raise ValueError(
@@ -660,7 +678,6 @@ class MBartDecoderLayer(nn.Module):
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
- self.device = torch.device(get_device())
def forward(
self,
@@ -679,9 +696,11 @@ class MBartDecoderLayer(nn.Module):
hidden_states = self.self_attn_layer_norm(hidden_states)
self_attn_past_key_value = None
- if past_key_value is not None:
+ if isinstance(past_key_value, GrowingLayerCache):
+ self_attn_past_key_value = past_key_value
+ elif past_key_value is not None:
self_attn_past_key_value = tuple(
- t.to(self.device) if isinstance(t, torch.Tensor) else t for t in past_key_value[:2]
+ t.to(device=hidden_states.device, dtype=hidden_states.dtype) if isinstance(t, torch.Tensor) else t for t in past_key_value[:2]
)
hidden_states, self_attn_weights, present_key_value = self.self_attn(
diff --git a/mineru/model/_internal/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml b/mineru/model/_internal/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml
index f04e01d4..ca9a72e7 100644
--- a/mineru/model/_internal/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml
+++ b/mineru/model/_internal/pytorchocr/utils/resources/pp_formulanet_arch_config.yaml
@@ -1,24 +1,48 @@
-Architecture:
- model_type: rec
- algorithm: PP-FormulaNet_plus-M
- in_channels: 3
- Transform:
- Backbone:
- name: PPHGNetV2_B6_Formula
- class_num: 1024
+PP-FormulaNet_plus-M:
+ Architecture:
+ model_type: rec
+ algorithm: PP-FormulaNet_plus-M
+ in_channels: 3
+ Transform:
+ Backbone:
+ name: PPHGNetV2_B6_Formula
+ class_num: 1024
+ Head:
+ name: PPFormulaNet_Head
+ max_new_tokens: 2560
+ decoder_start_token_id: 0
+ decoder_ffn_dim: 2048
+ decoder_hidden_size: 512
+ decoder_layers: 6
+ temperature: 0.2
+ do_sample: False
+ top_p: 0.95
+ encoder_hidden_size: 2048
+ is_export: False
+ length_aware: False
+ use_parallel: False
+ parallel_step: 0
- Head:
- name: PPFormulaNet_Head
- max_new_tokens: 2560
- decoder_start_token_id: 0
- decoder_ffn_dim: 2048
- decoder_hidden_size: 512
- decoder_layers: 6
- temperature: 0.2
- do_sample: False
- top_p: 0.95
- encoder_hidden_size: 2048
- is_export: False
- length_aware: False
- use_parallel: False
- parallel_step: 0
\ No newline at end of file
+PP-FormulaNet_plus-S:
+ Architecture:
+ model_type: rec
+ algorithm: PP-FormulaNet_plus-S
+ in_channels: 3
+ Backbone:
+ name: PPHGNetV2_B4_Formula
+ class_num: 1024
+ Head:
+ name: PPFormulaNet_Head
+ max_new_tokens: 1024
+ decoder_start_token_id: 0
+ decoder_ffn_dim: 1536
+ decoder_hidden_size: 384
+ decoder_layers: 2
+ temperature: 0.2
+ do_sample: false
+ top_p: 0.95
+ encoder_hidden_size: 2048
+ is_export: false
+ length_aware: true
+ use_parallel: true
+ parallel_step: 3
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/__init__.py b/mineru/model/mfr/pp_formulanet/__init__.py
similarity index 100%
rename from mineru/model/mfr/pp_formulanet_plus_m/__init__.py
rename to mineru/model/mfr/pp_formulanet/__init__.py
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py b/mineru/model/mfr/pp_formulanet/predict_formula.py
similarity index 54%
rename from mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py
rename to mineru/model/mfr/pp_formulanet/predict_formula.py
index 91c7f568..46f8000a 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py
+++ b/mineru/model/mfr/pp_formulanet/predict_formula.py
@@ -1,14 +1,15 @@
# Copyright (c) Opendatalab. All rights reserved.
import math
import os
+import zipfile
from pathlib import Path
import torch
import yaml
from tqdm import tqdm
+from loguru import logger
from ..._internal.pytorchocr.base_ocr_v20 import BaseOCRV20
-from ..._internal.pytorchocr.infer import pytorchocr_utility
from ..utils import build_mfr_batch_groups
from .processors import (
@@ -20,15 +21,26 @@ from .processors import (
)
+# MFR 独立精度策略:auto 为 CPU fp32、非 CPU fp16;可改为 fp32 做精度对照。
+MFR_INFERENCE_PRECISION = "auto"
+
+
class FormulaRecognizer(BaseOCRV20):
def __init__(
self,
weight_dir,
device="cpu",
+ *,
+ model_name="PP-FormulaNet_plus-M",
):
+ """按明确的模型变体加载权重和配置,默认保持 plus-M 兼容。"""
+ variants = {"PP-FormulaNet_plus-M", "PP-FormulaNet_plus-S"}
+ if model_name not in variants:
+ raise ValueError(f"Unsupported formula model: {model_name}")
+ self.model_name = model_name
self.weights_path = os.path.join(
weight_dir,
- "PP-FormulaNet_plus-M.pth",
+ f"{model_name}.pth",
)
self.yaml_path = str(
Path(__file__).resolve().parents[2]
@@ -40,28 +52,49 @@ class FormulaRecognizer(BaseOCRV20):
)
self.infer_yaml_path = os.path.join(
weight_dir,
- "PP-FormulaNet_plus-M_inference.yml",
+ f"{model_name}_inference.yml",
)
- network_config = pytorchocr_utility.AnalysisConfig(
- self.weights_path,
- self.yaml_path,
+ # 同一配置文件按模型名选择完整架构,避免 S/M 参数混用。
+ with open(self.yaml_path, encoding="utf-8") as config_file:
+ network_config = yaml.safe_load(config_file)[model_name]["Architecture"]
+ # 新版 ZIP 权重使用 mmap;旧版 pickle 权重仍支持普通读取。
+ weights = torch.load(
+ self.weights_path, map_location="cpu", weights_only=True,
+ mmap=zipfile.is_zipfile(self.weights_path),
)
- weights = self.read_pytorch_weights(self.weights_path)
-
- super(FormulaRecognizer, self).__init__(network_config)
-
- self.load_state_dict(weights)
+ # 只创建结构,避免父类临时解码器及随机初始化占用实际内存。
+ with torch.device("meta"):
+ super(FormulaRecognizer, self).__init__(network_config)
+ self.net.load_state_dict(weights, strict=True, assign=True)
+ del weights
self.device = torch.device(device) if isinstance(device, str) else device
- self.net.to(self.device)
+ self.ocr_inference_dtype = self._resolve_inference_dtype(
+ self.device, precision_override=MFR_INFERENCE_PRECISION
+ )
+ self.net.to(device=self.device, dtype=self.ocr_inference_dtype)
self.net.eval()
+ if model_name == "PP-FormulaNet_plus-M" and self.device.type == "cpu":
+ # CPU 仅使用增量缓存,attention 仍保持原有 eager 算子。
+ self.net.head.use_growing_cache = True
+ if model_name == "PP-FormulaNet_plus-M" and self.device.type in {"mps", "cuda"}:
+ # 仅为经过适配的公式解码器启用快速 attention;CPU 和其他模型保持原路径。
+ self.net.head.set_fast_attention()
+ logger.info(
+ "MFR loaded: model={}, device={}, dtype={}, attention={}, cache={}",
+ model_name, self.device, self.ocr_inference_dtype,
+ "sdpa" if getattr(self.net.head.decoder.model.decoder.layers[0].self_attn, "use_sdpa", False) else "eager",
+ "growing" if getattr(self.net.head, "use_growing_cache", False) else "concat",
+ )
with open(self.infer_yaml_path, "r", encoding="utf-8") as yaml_file:
data = yaml.load(yaml_file, Loader=yaml.FullLoader)
self.pre_tfs = {
"UniMERNetImgDecode": UniMERNetImgDecode(input_size=(384, 384)),
- "UniMERNetTestTransform": UniMERNetTestTransform(),
+ "UniMERNetTestTransform": UniMERNetTestTransform(
+ paddle_compatible=model_name == "PP-FormulaNet_plus-S"
+ ),
"LatexImageFormat": LatexImageFormat(),
"ToBatch": ToBatch(),
}
@@ -137,6 +170,7 @@ class FormulaRecognizer(BaseOCRV20):
batch_size: int = 64,
interline_enable: bool = True,
) -> list:
+ """按原有面积分组逐批预处理和识别,并保持原页序与检测字段回填。"""
if not images_mfd_res:
return []
@@ -177,27 +211,46 @@ class FormulaRecognizer(BaseOCRV20):
new_idx: old_idx for new_idx, old_idx in enumerate(sorted_indices)
}
- formula_requested_batch_size = max(1, batch_size // 2)
+ # Plus-S/M 统一直接使用请求上限,后续按面积动态缩小批次。
+ formula_requested_batch_size = max(1, batch_size)
batch_groups = build_mfr_batch_groups(
sorted_areas,
formula_requested_batch_size,
)
-
- batch_imgs = self.pre_tfs["UniMERNetImgDecode"](imgs=sorted_images)
- batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)
- batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)
- inp = self.pre_tfs["ToBatch"](imgs=batch_imgs)
- inp = torch.from_numpy(inp[0]).to(self.device)
+ # 公共分组器可能将不足 16 张的尾部整体收下;公式网络严格遵守实际 batch 上限。
+ batch_groups = [
+ group[start:start + formula_requested_batch_size]
+ for group in batch_groups
+ for start in range(0, len(group), formula_requested_batch_size)
+ ]
+ # 参照公共分组器合并较小尾批,Plus-S/M 均允许合并到请求上限。
+ # 保留至少两组,避免样本不足请求 batch 时破坏公共分组器的拆分语义。
+ while (
+ len(batch_groups) >= 3
+ and len(batch_groups[-1]) < len(batch_groups[-2])
+ and len(batch_groups[-2]) + len(batch_groups[-1]) <= formula_requested_batch_size
+ ):
+ tail_group = batch_groups.pop()
+ batch_groups[-1].extend(tail_group)
rec_formula = []
- with torch.no_grad():
- with tqdm(total=len(inp), desc="MFR Predict") as pbar:
+ with torch.inference_mode():
+ with tqdm(total=len(sorted_images), desc="MFR Predict") as pbar:
for batch_group in batch_groups:
- batch_data = inp[batch_group]
- batch_preds = [self.net(batch_data)]
- batch_preds = [p.reshape([-1]) for p in batch_preds[0]]
- batch_preds = [bp.cpu().numpy() for bp in batch_preds]
+ # CPU 和设备端均只保留当前批次的归一化输入。
+ batch_imgs = self.pre_tfs["UniMERNetImgDecode"](
+ imgs=sorted_images[batch_group[0]:batch_group[-1] + 1]
+ )
+ batch_imgs = self.pre_tfs["UniMERNetTestTransform"](imgs=batch_imgs)
+ batch_imgs = self.pre_tfs["LatexImageFormat"](imgs=batch_imgs)
+ inp = self.pre_tfs["ToBatch"](imgs=batch_imgs)[0]
+ del batch_imgs
+ batch_data = torch.from_numpy(inp).to(
+ device=self.device, dtype=self.ocr_inference_dtype
+ )
+ batch_preds = self.net(batch_data).cpu().numpy()
rec_formula += self.post_op(batch_preds)
+ del inp, batch_data, batch_preds
pbar.update(len(batch_group))
unsorted_results = [""] * len(rec_formula)
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/processors.py b/mineru/model/mfr/pp_formulanet/processors.py
similarity index 97%
rename from mineru/model/mfr/pp_formulanet_plus_m/processors.py
rename to mineru/model/mfr/pp_formulanet/processors.py
index a53524cc..c31dad6b 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m/processors.py
+++ b/mineru/model/mfr/pp_formulanet/processors.py
@@ -162,12 +162,13 @@ class UniMERNetTestTransform:
A class for transforming images according to UniMERNet test specifications.
"""
- def __init__(self, **kwargs) -> None:
+ def __init__(self, paddle_compatible: bool = False, **kwargs) -> None:
"""
Initializes the UniMERNetTestTransform class.
"""
super().__init__()
self.num_output_channels = 3
+ self.paddle_compatible = paddle_compatible
def transform(self, img: np.ndarray) -> np.ndarray:
"""
@@ -185,6 +186,11 @@ class UniMERNetTestTransform:
shape = (1, 1, 3)
mean = np.array(mean).reshape(shape).astype("float32")
std = np.array(std).reshape(shape).astype("float32")
+ if self.paddle_compatible:
+ # plus-S 对齐 Paddle:先对 RGB uint8 图像灰度化,再归一化;保留 plus-M 原行为。
+ gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
+ img = cv2.merge([gray] * self.num_output_channels).astype("float32")
+ return (img - mean * 255.0) * (1.0 / (std * 255.0))
img = (img.astype("float32") * scale - mean) / std
grayscale_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
squeezed = np.squeeze(grayscale_image)
@@ -248,7 +254,7 @@ class ToBatch(object):
super(ToBatch, self).__init__()
def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
- """Concatenates a list of images into a single batch.
+ """拼接为独立连续批次;concatenate 已分配新数组,无需再次复制。
Args:
imgs (list): A list of image arrays to be concatenated.
@@ -257,7 +263,6 @@ class ToBatch(object):
list: A list containing the concatenated batch of images wrapped in another list (to comply with common batch processing formats).
"""
batch_imgs = np.concatenate(imgs)
- batch_imgs = batch_imgs.copy()
x = [batch_imgs]
return x
diff --git a/mineru/model/registry.py b/mineru/model/registry.py
index bd35b9db..126ce75d 100644
--- a/mineru/model/registry.py
+++ b/mineru/model/registry.py
@@ -18,7 +18,10 @@ PDF_EXTRACT_KIT = ModelRepo(
},
paths={
"pp_doclayout_v2": "models/Layout/PP-DocLayoutV2",
- "unimernet_small": "models/MFR/unimernet_hf_small_2503",
+ "pp_formulanet_plus_m_weights": "models/MFR/pp_formulanet_plus_m/PP-FormulaNet_plus-M.pth",
+ "pp_formulanet_plus_m_config": "models/MFR/pp_formulanet_plus_m/PP-FormulaNet_plus-M_inference.yml",
+ "pp_formulanet_plus_s_weights": "models/MFR/pp_formulanet_plus_s/PP-FormulaNet_plus-S.pth",
+ "pp_formulanet_plus_s_config": "models/MFR/pp_formulanet_plus_s/PP-FormulaNet_plus-S_inference.yml",
"pytorch_paddle": "models/OCR/paddleocr_torch",
"slanet_plus": "models/TabRec/SlanetPlus/slanet-plus.onnx",
"unet_structure": "models/TabRec/UnetStructure/unet.onnx",
diff --git a/mineru/model/runtime/hybrid.py b/mineru/model/runtime/hybrid.py
index 80cdda9b..7d021bba 100644
--- a/mineru/model/runtime/hybrid.py
+++ b/mineru/model/runtime/hybrid.py
@@ -20,8 +20,7 @@ from .contracts import AtomicModelName
if TYPE_CHECKING:
from ..layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
- from ..mfr.pp_formulanet_plus_m.predict_formula import FormulaRecognizer
- from ..mfr.unimernet.Unimernet import UnimernetModel
+ from ..mfr.pp_formulanet.predict_formula import FormulaRecognizer
from ..ocr.pytorch_paddle import PytorchPaddleOCR
from .device import get_device, get_model_stack
@@ -124,10 +123,11 @@ def wireless_table_model_init(lang: str | None = None) -> PaddleTableModel:
return table_model
-def mfr_model_init(weight_dir: str, device: str = "cpu") -> "UnimernetModel":
- from ..mfr.unimernet.Unimernet import UnimernetModel
+def mfr_model_init(weight_dir: str, device: str = "cpu") -> "FormulaRecognizer":
+ """初始化默认 Torch 公式模型 plus-M,精度由设备策略决定。"""
+ from ..mfr.pp_formulanet.predict_formula import FormulaRecognizer
- return UnimernetModel(weight_dir, device)
+ return FormulaRecognizer(weight_dir, device, model_name="PP-FormulaNet_plus-M")
def pp_doclayout_v2_model_init(weight: str, device: str = "cpu") -> "PPDocLayoutV2LayoutModel":
@@ -238,8 +238,11 @@ def atom_model_init(model_name: str, **kwargs: Any) -> Any:
else:
from ..registry import PDF_EXTRACT_KIT
+ # 按文件检查手工放置的资源,不要求模型目录存在下载完成标记。
+ weights_path = PDF_EXTRACT_KIT.pp_formulanet_plus_m_weights.ensure()
+ PDF_EXTRACT_KIT.pp_formulanet_plus_m_config.ensure()
atom_model = mfr_model_init(
- str(PDF_EXTRACT_KIT.unimernet_small.ensure()),
+ str(weights_path.parent),
kwargs.get("device"),
)
elif model_name == AtomicModelName.OCR:
@@ -366,7 +369,7 @@ class HybridLocalModelContext:
self.layout_model = self.get_layout_model()
@cached_property
- def mfr_model(self) -> UnimernetModel | FormulaRecognizer:
+ def mfr_model(self) -> FormulaRecognizer:
"""首次访问时加载公式识别模型,并在当前 Context 内复用。"""
return self.get_mfr_model()
@@ -417,7 +420,7 @@ class HybridLocalModelContext:
device=self.device,
)
- def get_mfr_model(self) -> "UnimernetModel":
+ def get_mfr_model(self) -> "FormulaRecognizer":
"""获取公式识别原子模型,统一复用当前公式模型配置和设备。"""
return self.atom_model_manager.get_atom_model(
atom_model_name=AtomicModelName.MFR,
diff --git a/tests/unittest/test_mfr_latex_utils.py b/tests/unittest/test_mfr_latex_utils.py
index 43778094..4192d7ab 100644
--- a/tests/unittest/test_mfr_latex_utils.py
+++ b/tests/unittest/test_mfr_latex_utils.py
@@ -6,7 +6,7 @@ import numpy as np
from types import SimpleNamespace
from mineru.model.mfr import utils as mfr_utils
-from mineru.model.mfr.pp_formulanet_plus_m.processors import UniMERNetDecode
+from mineru.model.mfr.pp_formulanet.processors import UniMERNetDecode
from mineru.model.mfr.unimernet.unimernet_hf.modeling_unimernet import UnimernetModel