Skip to content

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

feat: optimize batch processing by implementing dynamic batch grouping and enhancing formula item handling

myhloli6eb91d3632b7
diff --git a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py b/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py
index 62613d87..57b516dc 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py
+++ b/mineru/model/mfr/pp_formulanet_plus_m/predict_formula.py
@@ -4,12 +4,12 @@ from pathlib import Path
import torch
import yaml
-from loguru import logger
from tqdm import tqdm
from mineru.model.utils.pytorchocr.base_ocr_v20 import BaseOCRV20
from mineru.model.utils.tools.infer import pytorchocr_utility
+from ..utils import build_mfr_batch_groups
from .processors import (
LatexImageFormat,
ToBatch,
@@ -43,7 +43,8 @@ class FormulaRecognizer(BaseOCRV20):
)
network_config = pytorchocr_utility.AnalysisConfig(
- self.weights_path, self.yaml_path
+ self.weights_path,
+ self.yaml_path,
)
weights = self.read_pytorch_weights(self.weights_path)
@@ -144,11 +145,13 @@ class FormulaRecognizer(BaseOCRV20):
images_formula_list = []
mf_image_list = []
backfill_list = []
- image_info = [] # Store (area, original_index, image) tuples
+ image_info = []
for mfd_res, image in zip(images_mfd_res, images):
formula_list, crop_targets = self._build_formula_items(
- mfd_res, image, interline_enable=interline_enable
+ mfd_res,
+ image,
+ interline_enable=interline_enable,
)
for formula_item, (xmin, ymin, xmax, ymax) in crop_targets:
@@ -166,14 +169,18 @@ class FormulaRecognizer(BaseOCRV20):
return images_formula_list
image_info.sort(key=lambda x: x[0])
+ sorted_areas = [x[0] for x in image_info]
sorted_indices = [x[1] for x in image_info]
sorted_images = [x[2] for x in image_info]
index_mapping = {
new_idx: old_idx for new_idx, old_idx in enumerate(sorted_indices)
}
- batch_size = min(batch_size, max(1, 2 ** (len(sorted_images).bit_length() - 1)))
- batch_size = max(1, int(0.5 * batch_size))
+ formula_requested_batch_size = max(1, batch_size // 2)
+ 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)
@@ -184,13 +191,13 @@ class FormulaRecognizer(BaseOCRV20):
rec_formula = []
with torch.no_grad():
with tqdm(total=len(inp), desc="MFR Predict") as pbar:
- for index in range(0, len(inp), batch_size):
- batch_data = inp[index : index + batch_size]
+ 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]
rec_formula += self.post_op(batch_preds)
- pbar.update(len(batch_data))
+ pbar.update(len(batch_group))
unsorted_results = [""] * len(rec_formula)
for new_idx, latex in enumerate(rec_formula):
diff --git a/mineru/model/mfr/unimernet/Unimernet.py b/mineru/model/mfr/unimernet/Unimernet.py
index b7fc9974..11151500 100644
--- a/mineru/model/mfr/unimernet/Unimernet.py
+++ b/mineru/model/mfr/unimernet/Unimernet.py
@@ -4,6 +4,8 @@ import torch
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
+from ..utils import build_mfr_batch_groups
+
class MathDataset(Dataset):
def __init__(self, image_paths, transform=None):
@@ -25,7 +27,10 @@ class UnimernetModel(object):
from .unimernet_hf import UnimernetModel
if _device_.startswith("mps") or _device_.startswith("npu") or _device_.startswith("musa"):
- self.model = UnimernetModel.from_pretrained(weight_dir, attn_implementation="eager")
+ self.model = UnimernetModel.from_pretrained(
+ weight_dir,
+ attn_implementation="eager",
+ )
else:
self.model = UnimernetModel.from_pretrained(weight_dir)
self.device = torch.device(_device_)
@@ -110,11 +115,13 @@ class UnimernetModel(object):
images_formula_list = []
mf_image_list = []
backfill_list = []
- image_info = [] # Store (area, original_index, image) tuples
+ image_info = []
for mfd_res, image in zip(images_mfd_res, images):
formula_list, crop_targets = self._build_formula_items(
- mfd_res, image, interline_enable=interline_enable
+ mfd_res,
+ image,
+ interline_enable=interline_enable,
)
for formula_item, (xmin, ymin, xmax, ymax) in crop_targets:
@@ -132,23 +139,30 @@ class UnimernetModel(object):
return images_formula_list
image_info.sort(key=lambda x: x[0])
+ sorted_areas = [x[0] for x in image_info]
sorted_indices = [x[1] for x in image_info]
sorted_images = [x[2] for x in image_info]
- index_mapping = {new_idx: old_idx for new_idx, old_idx in enumerate(sorted_indices)}
+ index_mapping = {
+ new_idx: old_idx for new_idx, old_idx in enumerate(sorted_indices)
+ }
+ batch_groups = build_mfr_batch_groups(sorted_areas, batch_size)
dataset = MathDataset(sorted_images, transform=self.model.transform)
- batch_size = min(batch_size, max(1, 2 ** (len(sorted_images).bit_length() - 1)))
- dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=0)
+ dataloader = DataLoader(dataset, batch_sampler=batch_groups, num_workers=0)
mfr_res = []
with tqdm(total=len(sorted_images), desc="MFR Predict") as pbar:
- for mf_img in dataloader:
+ for batch_group, mf_img in zip(batch_groups, dataloader):
+ current_batch_size = len(batch_group)
mf_img = mf_img.to(dtype=self.model.dtype)
mf_img = mf_img.to(self.device)
with torch.no_grad():
- output = self.model.generate({"image": mf_img}, batch_size=batch_size)
+ output = self.model.generate(
+ {"image": mf_img},
+ batch_size=current_batch_size,
+ )
mfr_res.extend(output["fixed_str"])
- pbar.update(len(mf_img))
+ pbar.update(current_batch_size)
unsorted_results = [""] * len(mfr_res)
for new_idx, latex in enumerate(mfr_res):
diff --git a/mineru/model/mfr/utils.py b/mineru/model/mfr/utils.py
index 8936d26c..aee712cd 100644
--- a/mineru/model/mfr/utils.py
+++ b/mineru/model/mfr/utils.py
@@ -336,4 +336,77 @@ def latex_rm_whitespace(s: str):
while s.endswith('\\'):
s = s[:-1]
- return s
\ No newline at end of file
+ return s
+
+
+def largest_power_of_two_leq(value: int) -> int:
+ if value < 1:
+ return 0
+ return 2 ** (value.bit_length() - 1)
+
+
+def get_mfr_effective_batch_size(num_items: int, requested_batch_size: int) -> int:
+ return min(
+ requested_batch_size,
+ largest_power_of_two_leq(max(1, num_items)),
+ )
+
+
+def get_mfr_min_dynamic_batch_size(requested_batch_size: int) -> int:
+ return max(1, requested_batch_size // 8)
+
+
+def build_mfr_batch_groups(sorted_areas: list[int], requested_batch_size: int) -> list[list[int]]:
+ if not sorted_areas:
+ return []
+
+ effective_batch_size = get_mfr_effective_batch_size(
+ len(sorted_areas),
+ requested_batch_size,
+ )
+ if effective_batch_size < 1:
+ return []
+
+ min_dynamic_batch_size = get_mfr_min_dynamic_batch_size(requested_batch_size)
+ total_count = len(sorted_areas)
+ if total_count < min_dynamic_batch_size:
+ return [list(range(total_count))]
+
+ base_mean_area = sum(sorted_areas[:effective_batch_size]) / effective_batch_size
+ batch_groups = []
+ cursor = 0
+
+ while cursor < total_count:
+ remaining_count = total_count - cursor
+ if remaining_count < min_dynamic_batch_size:
+ batch_groups.append(list(range(cursor, total_count)))
+ break
+
+ probe_size = min(effective_batch_size, remaining_count)
+ current_mean_area = sum(sorted_areas[cursor : cursor + probe_size]) / probe_size
+ ratio = 1 if base_mean_area <= 0 else current_mean_area / base_mean_area
+
+ candidate_batch_size = effective_batch_size
+ threshold = 4
+ while (
+ ratio >= threshold
+ and candidate_batch_size // 2 >= min_dynamic_batch_size
+ ):
+ candidate_batch_size //= 2
+ threshold *= 2
+
+ candidate_batch_size = min(
+ candidate_batch_size,
+ largest_power_of_two_leq(remaining_count),
+ )
+ batch_groups.append(list(range(cursor, cursor + candidate_batch_size)))
+ cursor += candidate_batch_size
+
+ if (
+ len(batch_groups) >= 2
+ and len(batch_groups[-1]) < min_dynamic_batch_size
+ ):
+ tail_group = batch_groups.pop()
+ batch_groups[-1].extend(tail_group)
+
+ return batch_groups