Skip to content

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

fix(layout): restore PP-DocLayoutV2 model class thresholds

myhlolib479e42d901a
diff --git a/mineru/model/layout/pp_doclayout_v2_base.py b/mineru/model/layout/pp_doclayout_v2_base.py
index 0f22a0c0..88d58a31 100644
--- a/mineru/model/layout/pp_doclayout_v2_base.py
+++ b/mineru/model/layout/pp_doclayout_v2_base.py
@@ -132,7 +132,7 @@ class PPDocLayoutV2PostProcessor:
"""PP-DocLayoutV2 检测结果的后处理逻辑。
所有方法都是纯 numpy/Python 实现,不依赖 torch/transformers。
- 子类只需提供 ``conf`` / ``use_paddlex_filter_boxes`` 等实例属性,
+ 子类只需提供 ``use_paddlex_filter_boxes`` 等实例属性,
并实现 ``predict`` / ``batch_predict`` 即可。
"""
diff --git a/mineru/model/layout/pp_doclayout_v2_onnx.py b/mineru/model/layout/pp_doclayout_v2_onnx.py
index 34fa97bd..0169ed5f 100644
--- a/mineru/model/layout/pp_doclayout_v2_onnx.py
+++ b/mineru/model/layout/pp_doclayout_v2_onnx.py
@@ -9,21 +9,20 @@
"""
from __future__ import annotations
-from docvortex.image import resize_image
-
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
import yaml
+from docvortex.image import resize_image
from loguru import logger
from PIL import Image
from tqdm import tqdm
from ..ocr.image import rgb_to_bgr
from ..runtime.onnx import ort_session
-from .pp_doclayout_v2_base import PP_DOCLAYOUT_V2_LABELS, PPDocLayoutV2PostProcessor
+from .pp_doclayout_v2_base import DEFAULT_CLASS_THRESHOLDS, PP_DOCLAYOUT_V2_LABELS, PPDocLayoutV2PostProcessor
__all__ = ["PPDocLayoutV2LayoutModelONNX"]
@@ -49,14 +48,12 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):
weight: str,
device: Optional[str] = None,
imgsz: Tuple[int, int] = _INPUT_SIZE,
- conf: float = 0.45,
use_paddlex_filter_boxes: bool = True,
intra_op_num_threads: int = 0,
config_path: str | None = None,
) -> None:
- """加载 CPU 检测图及官方预处理配置。"""
+ """加载 CPU 检测图及官方预处理配置,检测筛选使用官方分类阈值。"""
self.device = "cpu"
- self.conf = conf
self.use_paddlex_filter_boxes = use_paddlex_filter_boxes
self.model_path = str(weight)
self.imgsz = imgsz
@@ -94,11 +91,36 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):
else:
raise TypeError(f"Unsupported image type for PP-DocLayoutV2 ONNX: {type(image)}")
- resized = resize_image(arr, (self.imgsz[1], self.imgsz[0]), interpolation={0: 'nearest', 1: 'linear', 2: 'cubic', 3: 'area', 4: 'lanczos4'}[self.interpolation])
+ resized = resize_image(
+ arr,
+ (self.imgsz[1], self.imgsz[0]),
+ interpolation={0: "nearest", 1: "linear", 2: "cubic", 3: "area", 4: "lanczos4"}[self.interpolation],
+ )
norm = resized.astype(np.float32) * self.rescale_factor
chw = norm.transpose(2, 0, 1)
return chw, target_size
+ @staticmethod
+ def _filter_by_class_thresholds(sample: np.ndarray) -> np.ndarray:
+ """按最高分类分数确定候选有效性,再对其各个标签应用官方分类阈值。"""
+ if len(sample) == 0:
+ return sample
+
+ labels = sample[:, 0].astype(np.int64)
+ scores = sample[:, 1]
+ thresholds = np.asarray(DEFAULT_CLASS_THRESHOLDS, dtype=scores.dtype)[labels]
+ # 同一检测候选的多标签行共享原始坐标和阅读顺序键,须在逐页范围内分组。
+ _, query_ids = np.unique(sample[:, 2:8], axis=0, return_inverse=True)
+ # 与 argmax 的同分规则一致:最高分相同时,较小类别编号作为候选主类别。
+ primary_order = np.lexsort((labels, -scores, query_ids))
+ sorted_query_ids = query_ids[primary_order]
+ first_in_query = np.concatenate(([True], sorted_query_ids[1:] != sorted_query_ids[:-1]))
+ primary_indices = primary_order[first_in_query]
+ valid_queries = np.empty(len(primary_indices), dtype=bool)
+ valid_queries[query_ids[primary_indices]] = scores[primary_indices] >= thresholds[primary_indices]
+ keep = valid_queries[query_ids] & (scores >= thresholds)
+ return sample[keep]
+
def _run_session(self, pixel_values: np.ndarray, target_sizes: Sequence[Tuple[int, int]]) -> List[Dict[str, np.ndarray]]:
"""跑一次 ONNX 推理,解析输出为内部 prediction dict。
@@ -140,9 +162,7 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):
end = offset + int(count)
sample = preds[offset:end]
offset = end
- scores = sample[:, 1]
- keep = scores >= self.conf
- sample = sample[keep]
+ sample = self._filter_by_class_thresholds(sample)
if sample.shape[1] >= 8:
order_idx = np.lexsort((-sample[:, 7], sample[:, 6]))
diff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.py
index 697d7a2f..aa04d202 100644
--- a/mineru/model/layout/pp_doclayoutv2.py
+++ b/mineru/model/layout/pp_doclayoutv2.py
@@ -58,11 +58,10 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
weight: str,
device: Optional[str] = "cuda",
imgsz: Tuple[int, int] = DEFAULT_IMAGE_SIZE,
- conf: float = 0.45,
use_paddlex_filter_boxes: bool = True,
- ):
+ ) -> None:
+ """加载官方模型配置,检测筛选与阅读顺序均使用模型分类阈值。"""
self.device = device or "cpu"
- self.conf = conf
self.use_paddlex_filter_boxes = use_paddlex_filter_boxes
self.model_dir = weight
self.preprocess_config = load_preprocess_config(self.model_dir)
@@ -127,6 +126,7 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
outputs: PPDocLayoutV2ForObjectDetectionOutput,
target_sizes: Sequence[Tuple[int, int]],
) -> List[Dict[str, torch.Tensor]]:
+ """按模型分类阈值筛选有效候选,防止排序时的无效框重新进入输出。"""
boxes = outputs.pred_boxes
logits = outputs.logits
order_logits = outputs.order_logits
@@ -141,16 +141,22 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
num_top_queries = logits.shape[1]
num_classes = logits.shape[2]
+ class_thresholds = torch.as_tensor(self.config.class_thresholds, dtype=torch.float32, device=logits.device)
+ # 与官方阅读顺序网络一致:用最高分所属类别判断候选框是否有效。
+ max_logits, class_ids = logits.max(dim=-1)
+ valid_queries = max_logits.sigmoid() >= class_thresholds[class_ids]
scores = torch.sigmoid(logits)
scores, index = torch.topk(scores.flatten(1), num_top_queries, dim=-1)
labels = index % num_classes
index = index // num_classes
boxes = boxes.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, boxes.shape[-1]))
order_seqs = order_seqs.gather(dim=1, index=index)
+ valid_candidates = valid_queries.gather(dim=1, index=index)
results = []
- for score, label, box, order_seq in zip(scores, labels, boxes, order_seqs):
- keep = score >= self.conf
+ for score, label, box, order_seq, valid_candidate in zip(scores, labels, boxes, order_seqs, valid_candidates):
+ # 次高分标签既要达到自身阈值,也不能重新放行排序阶段已排除的候选框。
+ keep = valid_candidate & (score >= class_thresholds[label])
order_seq = order_seq[keep]
order_seq, indices = torch.sort(order_seq)
results.append(
diff --git a/tests/unittest/test_onnx_detection_batching.py b/tests/unittest/test_onnx_detection_batching.py
index 0c350dac..189be3ee 100644
--- a/tests/unittest/test_onnx_detection_batching.py
+++ b/tests/unittest/test_onnx_detection_batching.py
@@ -14,7 +14,6 @@ def layout_model(counts: np.ndarray) -> PPDocLayoutV2LayoutModelONNX:
"""构造含零框页、低置信框和阅读顺序的受控版面模型。"""
model = object.__new__(PPDocLayoutV2LayoutModelONNX)
model.imgsz = (800, 800)
- model.conf = 0.5
model._input_names = ["image", "im_shape", "scale_factor"]
rows = np.array(
[[1, 0.9, 1, 2, 3, 4, 2, 0], [2, 0.8, 5, 6, 7, 8, 1, 0], [9, 0.1, 1, 1, 2, 2, 0, 0], [3, 0.7, 10, 11, 12, 13, 0, 0]],
diff --git a/tests/unittest/test_pp_doclayoutv2_thresholds.py b/tests/unittest/test_pp_doclayoutv2_thresholds.py
new file mode 100644
index 00000000..2bab049a
--- /dev/null
+++ b/tests/unittest/test_pp_doclayoutv2_thresholds.py
@@ -0,0 +1,200 @@
+"""验证模型分类阈值与阅读顺序有效候选在两种推理后端保持一致。"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import Mock
+
+import numpy as np
+import pytest
+
+from mineru.model.layout.pp_doclayout_v2_base import DEFAULT_CLASS_THRESHOLDS, PP_DOCLAYOUT_V2_LABELS
+
+
+def _torch_predictions(
+ probabilities: np.ndarray,
+ *,
+ class_thresholds: Sequence[float] = DEFAULT_CLASS_THRESHOLDS,
+) -> list[dict[str, Any]]:
+ """以受控检测分数和排序张量调用真实 Torch 后处理,不加载模型权重。"""
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("transformers", minversion="5.10.1")
+ from mineru.model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
+
+ model = object.__new__(PPDocLayoutV2LayoutModel)
+ model.config = SimpleNamespace(class_thresholds=list(class_thresholds))
+ batch_size, query_count, _ = probabilities.shape
+ outputs = SimpleNamespace(
+ logits=torch.logit(torch.as_tensor(probabilities, dtype=torch.float32)),
+ pred_boxes=torch.tensor([[[0.5, 0.5, 0.2, 0.1]]]).expand(batch_size, query_count, 4),
+ order_logits=torch.full((batch_size, query_count, query_count), 20.0),
+ )
+ return model._post_process_object_detection(outputs, [(200, 100)] * batch_size)
+
+
+def _onnx_predictions(rows: np.ndarray, counts: Sequence[int]) -> list[dict[str, np.ndarray]]:
+ """通过模拟 ORT 输出验证逐页拆分、分类筛选和阅读顺序的完整路径。"""
+ pytest.importorskip("onnxruntime")
+ from mineru.model.layout.pp_doclayout_v2_onnx import PPDocLayoutV2LayoutModelONNX
+
+ model = object.__new__(PPDocLayoutV2LayoutModelONNX)
+ model.imgsz = (800, 800)
+ model._input_names = ["image", "im_shape", "scale_factor"]
+ model.session = SimpleNamespace(run=Mock(return_value=[rows, np.asarray(counts, dtype=np.int32)]))
+ return model._run_session(np.zeros((len(counts), 3, 4, 4), dtype=np.float32), [(200, 100)] * len(counts))
+
+
+def _predict(backend: str, probabilities: np.ndarray) -> dict[str, Any]:
+ """将同一组多标签候选输入两种后端,反转 ONNX 行序以排除顺序依赖。"""
+ if backend == "torch":
+ return _torch_predictions(probabilities[None])[0]
+ rows = np.asarray(
+ [
+ [cls_id, score, query * 10, 2, query * 10 + 4, 8, query, query]
+ for query, scores in enumerate(probabilities)
+ for cls_id, score in enumerate(scores)
+ ],
+ dtype=np.float32,
+ ).reshape(-1, 8)
+ return _onnx_predictions(rows[::-1], [len(rows)])[0]
+
+
[email protected]("backend", ["torch", "onnx"])
[email protected]("cls_id", range(len(PP_DOCLAYOUT_V2_LABELS)), ids=PP_DOCLAYOUT_V2_LABELS)
+def test_class_threshold_boundaries(backend: str, cls_id: int) -> None:
+ """逐类验证低于阈值拒绝,等于阈值和高于阈值均可保留。"""
+ threshold = DEFAULT_CLASS_THRESHOLDS[cls_id]
+ probabilities = np.full((3, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
+ probabilities[:, cls_id] = [threshold - 0.001, threshold, threshold + 0.001]
+
+ result = _predict(backend, probabilities)
+
+ assert result["labels"].tolist() == [cls_id, cls_id]
+ np.testing.assert_allclose(result["scores"], [threshold, threshold + 0.001], rtol=0, atol=1e-7)
+
+
[email protected]("backend", ["torch", "onnx"])
+def test_invalid_primary_class_cannot_be_reintroduced_by_secondary_label(backend: str) -> None:
+ """摘要主类别未达标时,即使次高正文类别达标也不能重新进入输出。"""
+ probabilities = np.full((4, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
+ probabilities[0, 17] = 0.9
+ probabilities[1, 0] = 0.49
+ probabilities[1, 22] = 0.44
+
+ result = _predict(backend, probabilities)
+
+ assert result["labels"].tolist() == [17]
+
+
[email protected]("backend", ["torch", "onnx"])
+def test_summary_page_scores_restore_title_and_four_paragraphs(backend: str) -> None:
+ """用第八页实测分数复现大摘要框抢序和低分第二段丢失,验证分类筛选修复。"""
+ probabilities = np.full((10, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
+ for query, (cls_id, score) in enumerate(
+ [(0, 0.4740), (17, 0.8968), (22, 0.4426), (22, 0.5669), (22, 0.6167), (22, 0.5063), (8, 0.6086), (8, 0.5270)]
+ ):
+ probabilities[query, cls_id] = score
+ probabilities[6, 9] = 0.4692
+
+ result = _predict(backend, probabilities)
+
+ assert result["labels"].tolist() == [17, 22, 22, 22, 22, 8, 8]
+ np.testing.assert_allclose(result["scores"][1], 0.4426, rtol=0, atol=1e-7)
+
+
[email protected]("backend", ["torch", "onnx"])
+def test_valid_primary_keeps_only_secondary_labels_above_their_own_threshold(backend: str) -> None:
+ """有效候选保留达到自身阈值的次高正文标签,拒绝未达标的页眉标签。"""
+ probabilities = np.full((4, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
+ probabilities[0, 0] = 0.6
+ probabilities[0, 22] = 0.44
+ probabilities[0, 12] = 0.49
+
+ result = _predict(backend, probabilities)
+
+ assert set(result["labels"].tolist()) == {0, 22}
+
+
[email protected]("backend", ["torch", "onnx"])
[email protected](("first_cls", "second_cls", "expected"), [(0, 22, []), (6, 8, [6])])
+def test_primary_class_ties_use_the_smallest_class_id(
+ backend: str, first_cls: int, second_cls: int, expected: list[int]
+) -> None:
+ """最高分同分时按较小类别编号判断有效性,与模型 argmax 规则一致。"""
+ probabilities = np.full((4, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
+ probabilities[0, first_cls] = probabilities[0, second_cls] = 0.45
+
+ result = _predict(backend, probabilities)
+
+ assert result["labels"].tolist() == expected
+
+
+def test_torch_uses_loaded_model_thresholds() -> None:
+ """Torch 按已加载模型配置筛选,不以共享默认常量覆盖模型自带阈值。"""
+ probabilities = np.full((1, 1, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
+ probabilities[0, 0, 22] = 0.6
+ thresholds = list(DEFAULT_CLASS_THRESHOLDS)
+ thresholds[22] = 0.7
+
+ result = _torch_predictions(probabilities, class_thresholds=thresholds)[0]
+
+ assert result["labels"].tolist() == []
+
+
[email protected]("query_count", [0, 2])
+def test_torch_empty_and_all_rejected_candidates(query_count: int) -> None:
+ """无候选和全部未达标的批次均保留逐页空结果与框数组形状。"""
+ probabilities = np.full((2, query_count, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
+
+ results = _torch_predictions(probabilities)
+
+ assert len(results) == 2
+ assert all(result["labels"].numel() == 0 and result["boxes"].shape == (0, 4) for result in results)
+
+
+def test_onnx_groups_candidates_with_coordinates_and_both_order_keys() -> None:
+ """坐标相同而排序键不同或排序键相同而坐标不同的候选必须独立判断。"""
+ rows = np.asarray(
+ [
+ [0, 0.49, 1, 2, 3, 4, 0, 0],
+ [22, 0.44, 1, 2, 3, 4, 0, 0],
+ [22, 0.44, 1, 2, 3, 4, 0, 1],
+ [22, 0.44, 10, 2, 30, 4, 0, 0],
+ ],
+ dtype=np.float32,
+ )
+
+ result = _onnx_predictions(rows, [4])[0]
+
+ assert result["labels"].tolist() == [22, 22]
+ np.testing.assert_array_equal(result["boxes"], [[1, 2, 3, 4], [10, 2, 30, 4]])
+
+
+def test_onnx_candidate_validity_is_isolated_by_page() -> None:
+ """相同框和排序键跨页出现时独立筛选,同时保留零框页和全过滤页。"""
+ rows = np.asarray(
+ [[0, 0.49, 1, 2, 3, 4, 0, 0], [22, 0.44, 1, 2, 3, 4, 0, 0], [22, 0.44, 1, 2, 3, 4, 0, 0]],
+ dtype=np.float32,
+ )
+
+ results = _onnx_predictions(rows, [2, 0, 1])
+
+ assert [result["labels"].tolist() for result in results] == [[], [], [22]]
+ assert all(result["boxes"].shape == (0, 4) for result in results[:2])
+
+
[email protected]("backend", ["torch", "onnx"])
+def test_layout_constructor_rejects_removed_uniform_conf(backend: str) -> None:
+ """包装类明确移除统一 conf 参数,禁止调用方再次覆盖分类阈值。"""
+ if backend == "torch":
+ pytest.importorskip("torch")
+ pytest.importorskip("transformers", minversion="5.10.1")
+ from mineru.model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel as model_type
+ else:
+ pytest.importorskip("onnxruntime")
+ from mineru.model.layout.pp_doclayout_v2_onnx import PPDocLayoutV2LayoutModelONNX as model_type
+
+ with pytest.raises(TypeError, match="conf"):
+ model_type("unused-checkpoint", conf=0.45)
diff --git a/tests/unittest/test_transformers5_models.py b/tests/unittest/test_transformers5_models.py
index 966d7497..e743eca2 100644
--- a/tests/unittest/test_transformers5_models.py
+++ b/tests/unittest/test_transformers5_models.py
@@ -233,9 +233,7 @@ def test_layout_position_embedding_preserves_native_math(device: str) -> None:
@pytest.mark.parametrize("device", ["cpu", "cuda", "cuda:1", "mps", "xpu", "xpu:1"])
-def test_layout_loader_adapts_position_embeddings_for_mps_and_xpu(
- monkeypatch: pytest.MonkeyPatch, device: str
-) -> None:
+def test_layout_loader_adapts_position_embeddings_for_mps_and_xpu(monkeypatch: pytest.MonkeyPatch, device: str) -> None:
"""覆盖真实加载入口的设备分支,验证 XPU 编号设备也采用 CPU 正弦编码。"""
from types import SimpleNamespace
from unittest.mock import Mock
@@ -247,14 +245,16 @@ def test_layout_loader_adapts_position_embeddings_for_mps_and_xpu(
layer = SimpleNamespace(position_embedding=native)
model = Mock()
model.model.encoder.aifi = [layer]
- config = Mock()
+ config = SimpleNamespace(class_thresholds=list(layout.DEFAULT_CLASS_THRESHOLDS))
load = Mock(return_value=model)
monkeypatch.setattr(layout, "load_preprocess_config", lambda _path: {})
monkeypatch.setattr(layout.PPDocLayoutV2Config, "from_pretrained", Mock(return_value=config))
monkeypatch.setattr(layout.PPDocLayoutV2ForObjectDetection, "from_pretrained", load)
- layout.PPDocLayoutV2LayoutModel("local-checkpoint", device=device)
+ loaded = layout.PPDocLayoutV2LayoutModel("local-checkpoint", device=device)
+ assert loaded.config.class_thresholds == layout.DEFAULT_CLASS_THRESHOLDS
+ assert not hasattr(loaded, "conf")
assert load.call_args.kwargs["device_map"] == {"": device}
model.to.assert_called_once_with(device)
model.eval.assert_called_once_with()