Skip to content

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

Upgrade inference stack to Transformers 5.10+

myhloli74c6db5a4917
diff --git a/.github/workflows/transformers5.yml b/.github/workflows/transformers5.yml
new file mode 100644
index 00000000..84945261
--- /dev/null
+++ b/.github/workflows/transformers5.yml
@@ -0,0 +1,105 @@
+name: Transformers 5 compatibility
+
+on:
+ pull_request:
+ branches: [next]
+ push:
+ branches: [next]
+ workflow_dispatch:
+ inputs:
+ utils-wheel-url:
+ description: Optional mineru-vl-utils 2.x wheel URL for joint pre-release validation
+ required: false
+ type: string
+
+permissions:
+ contents: read
+
+jobs:
+ compatibility:
+ name: ${{ matrix.os }} / Python ${{ matrix.python }} / Transformers ${{ matrix.transformers }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest]
+ python: ['3.10', '3.11', '3.12', '3.13']
+ transformers: ['5.10.1', '5.16.1']
+ include:
+ - {os: ubuntu-latest, python: '3.10', transformers: '5.10.1', torch: '2.6.0', torchvision: '0.21.0'}
+ - {os: windows-latest, python: '3.12', transformers: '5.10.1'}
+ - {os: windows-latest, python: '3.12', transformers: '5.16.1'}
+ - {os: macos-latest, python: '3.12', transformers: '5.10.1'}
+ - {os: macos-latest, python: '3.12', transformers: '5.16.1'}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-python@v6
+ with:
+ python-version: ${{ matrix.python }}
+ - uses: astral-sh/setup-uv@v7
+ - name: Install dependencies and optional joint-validation wheel
+ env:
+ UTILS_WHEEL_URL: ${{ inputs.utils-wheel-url }}
+ TRANSFORMERS_VERSION: ${{ matrix.transformers }}
+ TORCH_VERSION: ${{ matrix.torch }}
+ TORCHVISION_VERSION: ${{ matrix.torchvision }}
+ run: |
+ uv venv
+ if [[ -n "$UTILS_WHEEL_URL" ]]; then
+ uv pip install "$UTILS_WHEEL_URL"
+ fi
+ if [[ -n "$TORCH_VERSION" ]]; then
+ uv pip install "torch==$TORCH_VERSION" "torchvision==$TORCHVISION_VERSION"
+ fi
+ uv pip install '.[torch,test]' "transformers==$TRANSFORMERS_VERSION"
+ uv pip check
+ - name: Check real model graphs, cache and public import boundaries
+ run: |
+ if [[ -f .venv/Scripts/activate ]]; then source .venv/Scripts/activate; else source .venv/bin/activate; fi
+ python -m pytest -q -o addopts='' \
+ tests/unittest/test_transformers5_models.py \
+ tests/unittest/test_transformers5_runtime.py \
+ tests/unittest/test_pp_doclayoutv2_postprocess.py \
+ tests/unittest/test_mfr_latex_utils.py \
+ tests/unittest/test_vlm_config.py \
+ tests/unittest/test_vlm_remote.py \
+ tests/unittest/test_parser_model_preload.py \
+ tests/unittest/test_models_download_utils.py \
+ tests/unittest/test_pdf_memory_lifecycle.py
+
+ dependency-resolution:
+ name: Installation matrix / ${{ matrix.platform }} / Transformers ${{ matrix.transformers }}
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ platform: [linux, windows, macos]
+ transformers: ['5.10.1', '5.16.1']
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-python@v6
+ with:
+ python-version: '3.12'
+ - uses: astral-sh/setup-uv@v7
+ - name: Build wheels for metadata validation
+ env:
+ UTILS_WHEEL_URL: ${{ inputs.utils-wheel-url }}
+ run: |
+ python -m pip install build
+ python -m build --wheel
+ mkdir -p dependency-wheels
+ python -m pip download --no-deps --dest dependency-wheels "${UTILS_WHEEL_URL:-mineru-vl-utils>=2,<3}"
+ - name: Resolve base, torch, full and all on Python 3.10 through 3.13
+ run: |
+ python scripts/check_transformers5_dependencies.py \
+ --mineru-wheel dist/*.whl --utils-wheel dependency-wheels/*.whl \
+ --platform '${{ matrix.platform }}' --transformers '${{ matrix.transformers }}' \
+ --output dependency-matrix.json
+ - uses: actions/upload-artifact@v6
+ if: always()
+ with:
+ name: dependencies-${{ matrix.platform }}-${{ matrix.transformers }}
+ path: dependency-matrix.json
diff --git a/docs/next/transformers5-migration.md b/docs/next/transformers5-migration.md
new file mode 100644
index 00000000..8e505008
--- /dev/null
+++ b/docs/next/transformers5-migration.md
@@ -0,0 +1,79 @@
+# Transformers 5 推理栈
+
+本分支只支持 `transformers>=5.10.1,<6`,回归锚点为 5.10.1 与 5.16.1。
+`mineru-vl-utils` 配套版本为 2.0.0;该版本提高框架最低版本,并将 LMDeploy 参数契约更新为公开的 `Pipeline`。
+基础安装仍使用轻量模型栈,不安装或提前导入 Torch/Transformers。
+
+## 依赖和实现边界
+
+| 组件 | 范围 |
+| --- | --- |
+| Transformers | `>=5.10.1,<6` |
+| Tokenizers | `>=0.22.0,<0.24`;5.10.1 与 5.16.1 由解析器选择不同兼容版本 |
+| PyTorch | `>=2.6,<3`,TorchVision 与其配套 |
+| vLLM | `>=0.21.0,<0.22` |
+| LMDeploy | `>=0.17.0,<0.18` |
+| MLX-VLM | `>=0.3.12,<0.4`,MLX 保留 `<=0.31.1` |
+| mineru-vl-utils | `>=2.0.0,<3` |
+
+- UniMERNet 保留现有权重、词表、Q/K 压缩、token 上限及分批规则。组合配置显式构造 Swin/MBart,不修改全局 Auto 注册表。
+- 自注意力和交叉注意力使用 `Cache`/`EncoderDecoderCache`;权重初始化使用 Transformers 5 的保护机制,防止已加载参数被重新随机初始化。
+- PP-DocLayoutV2 复用官方模型,保留 MinerU 的预处理、阈值、类别、阅读顺序和后处理。MPS 的正弦位置编码在 CPU 调用官方实现,然后送回模型设备,避开 float64 限制。
+- Qwen2-VL 从文本子配置读取上下文长度,并合并生成配置、文本配置及 tokenizer 的特殊 token。
+- LMDeploy 同步/异步客户端使用同一个 `Pipeline.infer`。异步调用在线程中执行;取消时等待在途同步调用结束后再释放名额,防止共享引擎被提前卸载。
+- vLLM 客户端不再安装依赖已删除 `AnyTokenizer` 的导入时全局 logprobs 补丁。
+
+## 本地联合验证
+
+utils 2.0.0 正式发布前,先构建两个工作树的 wheel,并在独立环境中一起安装,避免解析到旧版 utils:
+
+```bash
+# 在 mineru-vl-utils 工作树中
+uv build --wheel
+
+# 在 MinerU 工作树中
+uv build --wheel
+uv venv .venv-validation
+uv pip install --python .venv-validation/bin/python \
+ /path/to/mineru-vl-utils/dist/mineru_vl_utils-2.0.0-py3-none-any.whl \
+ './dist/mineru-4.0.0b1-py3-none-any.whl[torch]' \
+ 'transformers==5.16.1' pytest
+uv pip check --python .venv-validation/bin/python
+```
+
+安装矩阵直接读取已构建 wheel 的元数据,覆盖三个平台、Python 3.10–3.13 与基础/torch/full/all 模式:
+
+```bash
+python scripts/check_transformers5_dependencies.py \
+ --mineru-wheel dist/mineru-4.0.0b1-py3-none-any.whl \
+ --utils-wheel /path/to/mineru_vl_utils-2.0.0-py3-none-any.whl \
+ --platform linux --transformers 5.10.1 --output dependency-matrix.json
+```
+
+Linux 解析目标使用 glibc 2.34,Apple Silicon 使用 macOS 14;这是所选二进制依赖的安装基线。
+元数据可解不代表 GPU 推理已通过。
+
+真实模型验证工具为 `scripts/validate_transformers_migration.py`。输入清单包含
+`pages`(每项有 `name`、`pdf`、一基 `page`、渲染后 `image` 路径)及 `formulas`(固定公式裁剪路径列表)。
+同一清单分别交给保存的 4.57.6 基线源码和迁移源码,输出模型结果、Markdown/MiddleJson、耗时及内存采样:
+
+```bash
+python scripts/validate_transformers_migration.py \
+ --repo . --manifest /path/to/inputs.json --kind parse --tier basic \
+ --device mps --rounds 3 --output validation/parse-basic.json
+```
+
+`layout`/`mfr` 验证独立模型;`vlm-transformers`/`vlm-mlx` 验证真实 VLM 的短生成链路。
+VLM 组件 smoke 将图像最长边限制为 448 像素,不代替 `parse` 场景的原分辨率整页质量验收。
+内存报告中的 `rss_bytes` 为主进程 RSS,`torch_device_bytes` 为每 20ms 采样的 Torch 活跃设备内存。
+Transformers 5.16 使用 safetensors 的 MPS `pread` 路径,框架 allocator 计数不包含所有权重存储;RSS 与 GPU allocator 数值不能直接跨加载方式比较。
+macOS 同时记录系统 `proc_pid_rusage` 的 `physical_footprint_bytes`,用于统一内存的真实占用比较。保留 RSS 和框架计数供诊断,不把它们误报为 MLX 或外部 MPS 存储的 GPU 峰值。
+
+## CI 与发布门槛
+
+`transformers5.yml` 对 next/PR 运行模型图、增量缓存、重载、惰性导入、HTTP VLM 与生命周期回归,并解析安装矩阵。
+手动触发时可传入 `utils-wheel-url` 验证未发布的联合构建。utils 仓库也提供客户端双版本回归。
+
+发布前需要:固定权重和输入的内容回归通过;同一设备预热后三轮耗时、内存/显存无超过 10% 的回退;Linux CUDA、Windows GPU、macOS 实机推理有对应证据。
+单元测试替身和安装解析不替代实机结果。旧国产硬件镜像继续使用旧发布系列,单独迁移。
+当前工作按用户要求暂缓发布,不据此文档声明所有平台已经通过。
diff --git a/mineru/kit/commands/vlm_server.py b/mineru/kit/commands/vlm_server.py
index abb9074a..07a47dce 100644
--- a/mineru/kit/commands/vlm_server.py
+++ b/mineru/kit/commands/vlm_server.py
@@ -28,7 +28,7 @@ def _module_available(module_name: str) -> bool:
def _mlx_server_available() -> bool:
- if not is_mac_os_version_supported():
+ if not is_mac_os_version_supported("14.0"):
return False
try:
return importlib.util.find_spec("mlx_vlm.server") is not None
diff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.py
index c9a7e2ae..786b512e 100644
--- a/mineru/model/layout/pp_doclayoutv2.py
+++ b/mineru/model/layout/pp_doclayoutv2.py
@@ -1,8 +1,9 @@
# Copyright (c) Opendatalab. All rights reserved.
+"""复用 Transformers 的官方 PP-DocLayoutV2,保留 MinerU 的预处理和版面后处理。"""
+
import argparse
import json
import math
-from dataclasses import dataclass
from typing import Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
@@ -12,14 +13,12 @@ from PIL import Image
from torch import nn
from torchvision.transforms import InterpolationMode
from tqdm import tqdm
-from transformers import AutoConfig
-from transformers.activations import ACT2FN
-from transformers.configuration_utils import PretrainedConfig
-from transformers.modeling_outputs import BaseModelOutput
-from transformers.models.layoutlmv3.modeling_layoutlmv3 import LayoutLMv3TextEmbeddings
-from transformers.models.rt_detr.configuration_rt_detr import RTDetrConfig
-from transformers.models.rt_detr.modeling_rt_detr import RTDetrForObjectDetection, RTDetrModel, RTDetrPreTrainedModel
-from transformers.utils import ModelOutput
+from transformers import PPDocLayoutV2Config, PPDocLayoutV2ForObjectDetection
+from transformers.models.pp_doclayout_v2.configuration_pp_doclayout_v2 import PPDocLayoutV2ReadingOrderConfig
+from transformers.models.pp_doclayout_v2.modeling_pp_doclayout_v2 import (
+ PPDocLayoutV2ForObjectDetectionOutput,
+ PPDocLayoutV2ReadingOrder,
+)
from .pp_doclayout_v2_base import (
DEFAULT_CLASS_ORDER,
@@ -34,747 +33,23 @@ from .pp_doclayout_v2_base import (
)
-def _build_default_backbone_config():
- return AutoConfig.for_model(
- "hgnet_v2",
- arch="L",
- return_idx=[1, 2, 3],
- freeze_stem_only=True,
- freeze_at=0,
- freeze_norm=True,
- lr_mult_list=[0, 0.05, 0.05, 0.05, 0.05],
- out_features=["stage2", "stage3", "stage4"],
- )
-
-
-def _create_bidirectional_mask(
- inputs_embeds: torch.Tensor,
- attention_mask: Optional[torch.Tensor],
- encoder_hidden_states: Optional[torch.Tensor] = None,
-) -> Optional[torch.Tensor]:
- if attention_mask is None:
- return None
- if attention_mask.ndim == 4:
- return attention_mask
- if attention_mask.ndim != 2:
- raise ValueError(f"PP-DocLayoutV2 reading-order mask must be 2D or 4D, got shape {tuple(attention_mask.shape)}")
-
- embeds = encoder_hidden_states if encoder_hidden_states is not None else inputs_embeds
- batch_size, query_length = inputs_embeds.shape[:2]
- key_length = attention_mask.shape[1]
-
- if attention_mask.shape[0] != batch_size:
- raise ValueError(
- f"Attention mask batch size {attention_mask.shape[0]} does not match embeddings batch size {batch_size}"
- )
-
- expanded_mask = attention_mask[:, None, None, :].expand(batch_size, 1, query_length, key_length)
- expanded_mask = expanded_mask.to(device=embeds.device, dtype=embeds.dtype)
- min_value = torch.finfo(embeds.dtype).min
- return torch.where(
- expanded_mask > 0,
- torch.zeros(1, dtype=embeds.dtype, device=embeds.device),
- torch.full((1,), min_value, dtype=embeds.dtype, device=embeds.device),
- )
-
-
-@dataclass
-class PPDocLayoutV2ForObjectDetectionOutput(ModelOutput):
- logits: torch.FloatTensor | None = None
- pred_boxes: torch.FloatTensor | None = None
- order_logits: torch.FloatTensor | None = None
- last_hidden_state: torch.FloatTensor | None = None
- intermediate_hidden_states: torch.FloatTensor | None = None
- intermediate_logits: torch.FloatTensor | None = None
- intermediate_reference_points: torch.FloatTensor | None = None
- intermediate_predicted_corners: torch.FloatTensor | None = None
- initial_reference_points: torch.FloatTensor | None = None
- decoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- decoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- cross_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_last_hidden_state: torch.FloatTensor | None = None
- encoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- encoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- init_reference_points: torch.FloatTensor | None = None
- enc_topk_logits: torch.FloatTensor | None = None
- enc_topk_bboxes: torch.FloatTensor | None = None
- enc_outputs_class: torch.FloatTensor | None = None
- enc_outputs_coord_logits: torch.FloatTensor | None = None
- denoising_meta_values: dict | None = None
-
-
-class PPDocLayoutV2ReadingOrderConfig(PretrainedConfig):
- model_type = "pp_doclayout_v2_reading_order"
-
- def __init__(
- self,
- hidden_size=512,
- num_attention_heads=8,
- attention_probs_dropout_prob=0.1,
- has_relative_attention_bias=False,
- has_spatial_attention_bias=True,
- layer_norm_eps=1e-5,
- hidden_dropout_prob=0.1,
- intermediate_size=2048,
- hidden_act="gelu",
- num_hidden_layers=6,
- rel_pos_bins=32,
- max_rel_pos=128,
- rel_2d_pos_bins=64,
- max_rel_2d_pos=256,
- max_position_embeddings=514,
- max_2d_position_embeddings=1024,
- type_vocab_size=1,
- vocab_size=4,
- initializer_range=0.01,
- start_token_id=0,
- pad_token_id=1,
- end_token_id=2,
- pred_token_id=3,
- coordinate_size=171,
- shape_size=170,
- num_classes=20,
- relation_bias_embed_dim=16,
- relation_bias_theta=10000,
- relation_bias_scale=100,
- global_pointer_head_size=64,
- gp_dropout_value=0.0,
- **kwargs,
- ):
- self.hidden_size = hidden_size
- self.num_attention_heads = num_attention_heads
- self.attention_probs_dropout_prob = attention_probs_dropout_prob
- self.has_relative_attention_bias = has_relative_attention_bias
- self.has_spatial_attention_bias = has_spatial_attention_bias
- self.layer_norm_eps = layer_norm_eps
- self.hidden_dropout_prob = hidden_dropout_prob
- self.intermediate_size = intermediate_size
- self.hidden_act = hidden_act
- self.num_hidden_layers = num_hidden_layers
- self.rel_pos_bins = rel_pos_bins
- self.max_rel_pos = max_rel_pos
- self.rel_2d_pos_bins = rel_2d_pos_bins
- self.max_rel_2d_pos = max_rel_2d_pos
- self.max_position_embeddings = max_position_embeddings
- self.max_2d_position_embeddings = max_2d_position_embeddings
- self.type_vocab_size = type_vocab_size
- self.vocab_size = vocab_size
- self.initializer_range = initializer_range
- self.start_token_id = start_token_id
- self.pad_token_id = pad_token_id
- self.end_token_id = end_token_id
- self.pred_token_id = pred_token_id
- self.coordinate_size = coordinate_size
- self.shape_size = shape_size
- self.num_classes = num_classes
- self.relation_bias_embed_dim = relation_bias_embed_dim
- self.relation_bias_theta = relation_bias_theta
- self.relation_bias_scale = relation_bias_scale
- self.global_pointer_head_size = global_pointer_head_size
- self.gp_dropout_value = gp_dropout_value
- super().__init__(pad_token_id=pad_token_id, **kwargs)
-
-
-class PPDocLayoutV2Config(RTDetrConfig):
- model_type = "pp_doclayout_v2"
- sub_configs = {"backbone_config": AutoConfig, "reading_order_config": PPDocLayoutV2ReadingOrderConfig}
-
- def __init__(
- self,
- backbone_config=None,
- class_thresholds: Optional[List[float]] = None,
- class_order: Optional[List[int]] = None,
- reading_order_config: Optional[Union[PPDocLayoutV2ReadingOrderConfig, Dict]] = None,
- **kwargs,
- ):
- if backbone_config is None:
- backbone_config = _build_default_backbone_config()
- if isinstance(reading_order_config, PPDocLayoutV2ReadingOrderConfig):
- reading_order = reading_order_config
- else:
- reading_order = PPDocLayoutV2ReadingOrderConfig(**(reading_order_config or {}))
-
- super().__init__(
- backbone_config=backbone_config,
- class_thresholds=class_thresholds or list(DEFAULT_CLASS_THRESHOLDS),
- class_order=class_order or list(DEFAULT_CLASS_ORDER),
- **kwargs,
- )
- self.class_thresholds = list(class_thresholds or DEFAULT_CLASS_THRESHOLDS)
- self.class_order = list(class_order or DEFAULT_CLASS_ORDER)
- self.reading_order_config = reading_order
-
- def to_dict(self):
- output = super().to_dict()
- output["reading_order_config"] = self.reading_order_config.to_dict()
- return output
-
-
-class PPDocLayoutV2GlobalPointer(nn.Module):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__()
- self.head_size = config.global_pointer_head_size
- self.dense = nn.Linear(config.hidden_size, self.head_size * 2)
- self.dropout = nn.Dropout(config.gp_dropout_value)
-
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
- batch_size, sequence_length, _ = inputs.shape
- projection = self.dense(inputs).reshape(batch_size, sequence_length, 2, self.head_size)
- projection = self.dropout(projection)
- queries, keys = torch.unbind(projection, dim=2)
- logits = (queries @ keys.transpose(-2, -1)) / (self.head_size**0.5)
- mask = torch.tril(torch.ones(sequence_length, sequence_length, device=logits.device)).bool()
- return logits.masked_fill(mask.unsqueeze(0), -1e4)
-
-
-class PPDocLayoutV2PositionRelationEmbedding(nn.Module):
- inv_freq: torch.Tensor
-
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig, device=None):
- super().__init__()
- self.config = config
- self.embed_dim = config.relation_bias_embed_dim
- self.scale = config.relation_bias_scale
- self.pos_proj = nn.Conv2d(
- in_channels=self.embed_dim * 4,
- out_channels=config.num_attention_heads,
- kernel_size=1,
- )
- inv_freq, _ = self.compute_default_rope_parameters(config, device)
- self.register_buffer("inv_freq", inv_freq, persistent=False)
-
- @staticmethod
- def compute_default_rope_parameters(
- config: PPDocLayoutV2ReadingOrderConfig,
- device: Optional[torch.device] = None,
- ) -> Tuple[torch.Tensor, float]:
- base = config.relation_bias_theta
- dim = config.relation_bias_embed_dim
- half_dim = dim // 2
- inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / half_dim))
- return inv_freq, 1.0
-
- def box_relative_encoding(
- self,
- source_boxes: torch.Tensor,
- target_boxes: Optional[torch.Tensor] = None,
- epsilon: float = 1e-5,
- ) -> torch.Tensor:
- source_boxes = source_boxes.unsqueeze(-2)
- target_boxes = source_boxes if target_boxes is None else target_boxes.unsqueeze(-3)
- source_coordinates, source_dim = source_boxes[..., :2], source_boxes[..., 2:]
- target_coordinates, target_dim = target_boxes[..., :2], target_boxes[..., 2:]
- coordinate_difference = torch.abs(source_coordinates - target_coordinates)
- relative_coordinates = torch.log(coordinate_difference / (source_dim + epsilon) + 1.0)
- relative_dim = torch.log((source_dim + epsilon) / (target_dim + epsilon))
- return torch.cat([relative_coordinates, relative_dim], dim=-1)
-
- def get_position_embedding(self, x: torch.Tensor, scale: float = 100.0) -> torch.Tensor:
- embedding = (x * scale).unsqueeze(-1) * self.inv_freq
- return torch.cat((embedding.sin(), embedding.cos()), dim=-1).flatten(start_dim=-2).to(x.dtype)
-
- def forward(self, source_boxes: torch.Tensor, target_boxes: Optional[torch.Tensor] = None) -> torch.Tensor:
- target_boxes = source_boxes if target_boxes is None else target_boxes
- with torch.no_grad():
- relative_encoding = self.box_relative_encoding(source_boxes, target_boxes)
- position_embedding = self.get_position_embedding(relative_encoding, self.scale).permute(0, 3, 1, 2)
- return self.pos_proj(position_embedding)
-
+class _CpuSinePositionEmbedding(nn.Module):
+ """在 CPU 计算官方实现所需的 float64 频率,再把位置编码送回模型设备。"""
-class PPDocLayoutV2ReadingOrderSelfAttention(nn.Module):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
+ def __init__(self, embedding: nn.Module) -> None:
+ """组合无参数的位置编码模块,保持预训练权重名称和数学实现不变。"""
super().__init__()
- if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
- raise ValueError(
- f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention heads "
- f"({config.num_attention_heads})"
- )
-
- self.num_attention_heads = config.num_attention_heads
- self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
- self.all_head_size = self.num_attention_heads * self.attention_head_size
- self.query = nn.Linear(config.hidden_size, self.all_head_size)
- self.key = nn.Linear(config.hidden_size, self.all_head_size)
- self.value = nn.Linear(config.hidden_size, self.all_head_size)
- self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
- self.has_relative_attention_bias = config.has_relative_attention_bias
- self.has_spatial_attention_bias = config.has_spatial_attention_bias
-
- @staticmethod
- def cogview_attention(attention_scores: torch.Tensor, alpha: float = 32.0) -> torch.Tensor:
- scaled_attention_scores = attention_scores / alpha
- max_value = scaled_attention_scores.amax(dim=-1, keepdim=True)
- return nn.Softmax(dim=-1)((scaled_attention_scores - max_value) * alpha)
+ self.embedding = embedding
def forward(
self,
- hidden_states: torch.Tensor,
- attention_mask: Optional[torch.Tensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- output_attentions: bool = False,
- rel_pos: Optional[torch.Tensor] = None,
- rel_2d_pos: Optional[torch.Tensor] = None,
- ):
- batch_size, _, _ = hidden_states.shape
- query_layer = (
- self.query(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
- )
- key_layer = (
- self.key(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
- )
- value_layer = (
- self.value(hidden_states).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
- )
-
- attention_scores = torch.matmul(query_layer / (self.attention_head_size**0.5), key_layer.transpose(-1, -2))
- if rel_2d_pos is not None:
- attention_scores = attention_scores + rel_2d_pos
- elif self.has_relative_attention_bias and rel_pos is not None:
- attention_scores = attention_scores + rel_pos / (self.attention_head_size**0.5)
-
- if attention_mask is not None:
- attention_scores = attention_scores + attention_mask
-
- attention_probs = self.cogview_attention(attention_scores)
- attention_probs = self.dropout(attention_probs)
- if head_mask is not None:
- attention_probs = attention_probs * head_mask
-
- context_layer = torch.matmul(attention_probs, value_layer)
- context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
- context_layer = context_layer.view(*context_layer.size()[:-2], self.all_head_size)
- outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
- return outputs
-
-
-class PPDocLayoutV2ReadingOrderSelfOutput(nn.Module):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__()
- self.dense = nn.Linear(config.hidden_size, config.hidden_size)
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
- self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
-
- def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
- hidden_states = self.dense(hidden_states)
- hidden_states = self.dropout(hidden_states)
- return self.norm(hidden_states + input_tensor)
-
-
-class PPDocLayoutV2ReadingOrderIntermediate(nn.Module):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__()
- self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
- if isinstance(config.hidden_act, str):
- self.intermediate_act_fn = ACT2FN[config.hidden_act]
- else:
- self.intermediate_act_fn = config.hidden_act
-
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
- return self.intermediate_act_fn(self.dense(hidden_states))
-
-
-class PPDocLayoutV2ReadingOrderOutput(nn.Module):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__()
- self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
- self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
-
- def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
- hidden_states = self.dense(hidden_states)
- hidden_states = self.dropout(hidden_states)
- return self.norm(hidden_states + input_tensor)
-
-
-class PPDocLayoutV2ReadingOrderAttention(nn.Module):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__()
- self.self = PPDocLayoutV2ReadingOrderSelfAttention(config)
- self.output = PPDocLayoutV2ReadingOrderSelfOutput(config)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: Optional[torch.Tensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- output_attentions: bool = False,
- rel_pos: Optional[torch.Tensor] = None,
- rel_2d_pos: Optional[torch.Tensor] = None,
- ):
- self_outputs = self.self(
- hidden_states,
- attention_mask=attention_mask,
- head_mask=head_mask,
- output_attentions=output_attentions,
- rel_pos=rel_pos,
- rel_2d_pos=rel_2d_pos,
- )
- attention_output = self.output(self_outputs[0], hidden_states)
- return (attention_output,) + self_outputs[1:]
-
-
-class PPDocLayoutV2ReadingOrderLayer(nn.Module):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__()
- self.attention = PPDocLayoutV2ReadingOrderAttention(config)
- self.intermediate = PPDocLayoutV2ReadingOrderIntermediate(config)
- self.output = PPDocLayoutV2ReadingOrderOutput(config)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: Optional[torch.Tensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- output_attentions: bool = False,
- rel_pos: Optional[torch.Tensor] = None,
- rel_2d_pos: Optional[torch.Tensor] = None,
- ):
- attention_outputs = self.attention(
- hidden_states,
- attention_mask=attention_mask,
- head_mask=head_mask,
- output_attentions=output_attentions,
- rel_pos=rel_pos,
- rel_2d_pos=rel_2d_pos,
- )
- attention_output = attention_outputs[0]
- layer_output = self.output(self.intermediate(attention_output), attention_output)
- return (layer_output,) + attention_outputs[1:]
-
-
-class PPDocLayoutV2ReadingOrderEncoder(nn.Module):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__()
- self.config = config
- self.layer = nn.ModuleList([PPDocLayoutV2ReadingOrderLayer(config) for _ in range(config.num_hidden_layers)])
- self.has_relative_attention_bias = config.has_relative_attention_bias
- self.has_spatial_attention_bias = config.has_spatial_attention_bias
- self.gradient_checkpointing = False
-
- if self.has_relative_attention_bias:
- self.rel_pos_bins = config.rel_pos_bins
- self.max_rel_pos = config.max_rel_pos
- self.rel_pos_bias = nn.Linear(self.rel_pos_bins, config.num_attention_heads, bias=False)
-
- self.rel_bias_module = PPDocLayoutV2PositionRelationEmbedding(config)
-
- @staticmethod
- def relative_position_bucket(
- relative_position: torch.Tensor,
- bidirectional: bool = True,
- num_buckets: int = 32,
- max_distance: int = 128,
+ width: int,
+ height: int,
+ device: torch.device | None = None,
+ dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
- ret = 0
- if bidirectional:
- num_buckets //= 2
- ret += (relative_position > 0).long() * num_buckets
- relative_position = torch.abs(relative_position)
- else:
- relative_position = torch.max(-relative_position, torch.zeros_like(relative_position))
-
- max_exact = num_buckets // 2
- is_small = relative_position < max_exact
- val_if_large = max_exact + (
- torch.log(relative_position.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact)
- ).to(torch.long)
- val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1))
- return ret + torch.where(is_small, relative_position, val_if_large)
-
- def _cal_1d_pos_emb(self, position_ids: torch.Tensor) -> torch.Tensor:
- rel_pos_mat = position_ids.unsqueeze(-2) - position_ids.unsqueeze(-1)
- rel_pos = self.relative_position_bucket(
- rel_pos_mat,
- num_buckets=self.rel_pos_bins,
- max_distance=self.max_rel_pos,
- )
- with torch.no_grad():
- rel_pos = self.rel_pos_bias.weight.t()[rel_pos].permute(0, 3, 1, 2)
- return rel_pos.contiguous()
-
- def _cal_2d_pos_emb(self, bbox: torch.Tensor) -> torch.Tensor:
- x_min, y_min, x_max, y_max = bbox[..., 0], bbox[..., 1], bbox[..., 2], bbox[..., 3]
- width = (x_max - x_min).clamp(min=1e-3)
- height = (y_max - y_min).clamp(min=1e-3)
- center_x = (x_min + x_max) * 0.5
- center_y = (y_min + y_max) * 0.5
- boxes = torch.stack([center_x, center_y, width, height], dim=-1)
- return self.rel_bias_module(boxes)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- bbox: Optional[torch.Tensor] = None,
- attention_mask: Optional[torch.Tensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- output_attentions: bool = False,
- output_hidden_states: bool = False,
- return_dict: bool = True,
- position_ids: Optional[torch.Tensor] = None,
- ):
- all_hidden_states = () if output_hidden_states else None
- all_self_attentions = () if output_attentions else None
-
- rel_pos = self._cal_1d_pos_emb(position_ids) if self.has_relative_attention_bias and position_ids is not None else None
- rel_2d_pos = self._cal_2d_pos_emb(bbox) if self.has_spatial_attention_bias and bbox is not None else None
-
- for i, layer_module in enumerate(self.layer):
- if output_hidden_states:
- all_hidden_states = all_hidden_states + (hidden_states,)
- layer_head_mask = head_mask[i] if head_mask is not None else None
- layer_outputs = layer_module(
- hidden_states,
- attention_mask=attention_mask,
- head_mask=layer_head_mask,
- output_attentions=output_attentions,
- rel_pos=rel_pos,
- rel_2d_pos=rel_2d_pos,
- )
- hidden_states = layer_outputs[0]
- if output_attentions:
- all_self_attentions = all_self_attentions + (layer_outputs[1],)
-
- if output_hidden_states:
- all_hidden_states = all_hidden_states + (hidden_states,)
-
- if not return_dict:
- return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
-
- return BaseModelOutput(
- last_hidden_state=hidden_states,
- hidden_states=all_hidden_states,
- attentions=all_self_attentions,
- )
-
-
-class PPDocLayoutV2TextEmbeddings(LayoutLMv3TextEmbeddings):
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__(config)
- del self.LayerNorm
- self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
- spatial_embed_dim = 4 * config.coordinate_size + 2 * config.shape_size
- self.spatial_proj = nn.Linear(spatial_embed_dim, config.hidden_size)
-
- def forward(
- self,
- input_ids: Optional[torch.Tensor] = None,
- bbox: Optional[torch.Tensor] = None,
- token_type_ids: Optional[torch.Tensor] = None,
- position_ids: Optional[torch.Tensor] = None,
- inputs_embeds: Optional[torch.Tensor] = None,
- ) -> torch.Tensor:
- if position_ids is None:
- if input_ids is not None:
- position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx).to(input_ids.device)
- else:
- position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
-
- if input_ids is not None:
- input_shape = input_ids.size()
- else:
- input_shape = inputs_embeds.size()[:-1]
-
- if token_type_ids is None:
- token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
-
- if inputs_embeds is None:
- inputs_embeds = self.word_embeddings(input_ids)
-
- embeddings = inputs_embeds + self.token_type_embeddings(token_type_ids)
- embeddings = embeddings + self.position_embeddings(position_ids)
- spatial_position_embeddings = self.spatial_proj(self.calculate_spatial_position_embeddings(bbox))
- return embeddings + spatial_position_embeddings
-
-
-class PPDocLayoutV2PreTrainedModel(RTDetrPreTrainedModel):
- config_class = PPDocLayoutV2Config
-
- @torch.no_grad()
- def _init_weights(self, module):
- super()._init_weights(module)
- if isinstance(module, PPDocLayoutV2TextEmbeddings):
- module.position_ids.copy_(torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
- if isinstance(module, nn.Embedding):
- nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
- if module.padding_idx is not None:
- module.weight.data[module.padding_idx].zero_()
- if isinstance(module, PPDocLayoutV2PositionRelationEmbedding):
- inv_freq, _ = module.compute_default_rope_parameters(module.config, module.inv_freq.device)
- module.register_buffer("inv_freq", inv_freq, persistent=False)
-
-
-class PPDocLayoutV2ReadingOrder(PPDocLayoutV2PreTrainedModel):
- config_class = PPDocLayoutV2ReadingOrderConfig
-
- def __init__(self, config: PPDocLayoutV2ReadingOrderConfig):
- super().__init__(config)
- self.embeddings = PPDocLayoutV2TextEmbeddings(config)
- self.label_embeddings = nn.Embedding(config.num_classes, config.hidden_size)
- self.label_features_projection = nn.Linear(config.hidden_size, config.hidden_size)
- self.encoder = PPDocLayoutV2ReadingOrderEncoder(config)
- self.relative_head = PPDocLayoutV2GlobalPointer(config)
- self.post_init()
-
- def forward(
- self,
- boxes: torch.Tensor,
- labels: Optional[torch.Tensor] = None,
- mask: Optional[torch.Tensor] = None,
- ) -> torch.Tensor:
- if mask is None:
- raise ValueError("PP-DocLayoutV2 reading-order inference requires a mask tensor.")
-
- device = mask.device
- batch_size, seq_len = mask.shape
- num_pred = mask.sum(dim=1)
-
- input_ids = torch.full((batch_size, seq_len + 2), self.config.pad_token_id, dtype=torch.long, device=device)
- input_ids[:, 0] = self.config.start_token_id
- pred_col_idx = torch.arange(seq_len + 2, device=device).unsqueeze(0)
- pred_mask = (pred_col_idx >= 1) & (pred_col_idx <= num_pred.unsqueeze(1))
- input_ids[pred_mask] = self.config.pred_token_id
- input_ids[torch.arange(batch_size, device=device), num_pred + 1] = self.config.end_token_id
-
- pad_box = torch.zeros((batch_size, 1, boxes.shape[-1]), dtype=boxes.dtype, device=device)
- pad_boxes = torch.cat([pad_box, boxes, pad_box], dim=1)
- bbox_embedding = self.embeddings(input_ids=input_ids, bbox=pad_boxes.long())
-
- if labels is not None:
- label_proj = self.label_features_projection(self.label_embeddings(labels))
- pad_label = torch.zeros((batch_size, 1, label_proj.shape[-1]), dtype=label_proj.dtype, device=device)
- label_proj = torch.cat([pad_label, label_proj, pad_label], dim=1)
- else:
- label_proj = torch.zeros_like(bbox_embedding)
-
- final_embeddings = self.embeddings.norm(bbox_embedding + label_proj)
- final_embeddings = self.embeddings.dropout(final_embeddings)
-
- attention_mask = pred_col_idx < (num_pred + 2).unsqueeze(1)
- attention_mask = _create_bidirectional_mask(final_embeddings, attention_mask)
- position_ids = self.embeddings.create_position_ids_from_input_ids(input_ids, self.embeddings.padding_idx)
- encoder_output = self.encoder(
- hidden_states=final_embeddings,
- bbox=pad_boxes,
- attention_mask=attention_mask,
- position_ids=position_ids,
- )
- token = encoder_output.last_hidden_state[:, 1 : 1 + seq_len, :]
- return self.relative_head(token)
-
-
-class PPDocLayoutV2Model(RTDetrModel):
- def __init__(self, config: PPDocLayoutV2Config):
- super().__init__(config)
- self.denoising_class_embed = nn.Embedding(config.num_labels, config.d_model)
- nn.init.xavier_uniform_(self.denoising_class_embed.weight)
-
-
-class PPDocLayoutV2ForObjectDetection(RTDetrForObjectDetection):
- config_class = PPDocLayoutV2Config
- _keys_to_ignore_on_load_missing = ["num_batches_tracked", "rel_pos_y_bias", "rel_pos_x_bias"]
-
- def __init__(self, config: PPDocLayoutV2Config):
- super().__init__(config)
- self.model = PPDocLayoutV2Model(config)
- self.model.decoder.class_embed = self.class_embed
- self.model.decoder.bbox_embed = self.bbox_embed
- self.reading_order = PPDocLayoutV2ReadingOrder(config.reading_order_config)
- self.num_queries = config.num_queries
- self.config = config
- self.register_buffer(
- "_class_thresholds_tensor",
- torch.tensor(config.class_thresholds, dtype=torch.float32),
- persistent=False,
- )
- self.register_buffer(
- "_class_order_tensor",
- torch.tensor(config.class_order, dtype=torch.long),
- persistent=False,
- )
- self.post_init()
-
- def forward(
- self,
- pixel_values: torch.FloatTensor,
- pixel_mask: Optional[torch.LongTensor] = None,
- encoder_outputs: Optional[torch.FloatTensor] = None,
- inputs_embeds: Optional[torch.FloatTensor] = None,
- decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
- labels: Optional[list[dict]] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- **kwargs,
- ):
- if labels is not None:
- raise ValueError("PPDocLayoutV2ForObjectDetection only supports inference.")
-
- use_return_dict = return_dict if return_dict is not None else self.config.use_return_dict
- outputs = self.model(
- pixel_values,
- pixel_mask=pixel_mask,
- encoder_outputs=encoder_outputs,
- inputs_embeds=inputs_embeds,
- decoder_inputs_embeds=decoder_inputs_embeds,
- labels=None,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=True,
- )
-
- raw_bboxes = outputs.intermediate_reference_points[:, -1]
- logits = outputs.intermediate_logits[:, -1]
-
- box_centers, box_sizes = raw_bboxes.split(2, dim=-1)
- bboxes = torch.cat([box_centers - 0.5 * box_sizes, box_centers + 0.5 * box_sizes], dim=-1) * 1000.0
- bboxes = bboxes.clamp_(0.0, 1000.0)
-
- max_logits, class_ids = logits.max(dim=-1)
- max_probs = max_logits.sigmoid()
- thresholds = self._class_thresholds_tensor[class_ids]
- mask = max_probs >= thresholds
- indices = torch.argsort(mask.to(torch.int8), dim=1, descending=True)
-
- sorted_class_ids = torch.take_along_dim(class_ids, indices, dim=1)
- sorted_boxes = torch.take_along_dim(bboxes, indices[..., None].expand(-1, -1, 4), dim=1)
- pred_boxes = torch.take_along_dim(raw_bboxes, indices[..., None].expand(-1, -1, 4), dim=1)
- logits = torch.take_along_dim(logits, indices[..., None].expand(-1, -1, logits.size(-1)), dim=1)
- sorted_mask = torch.take_along_dim(mask, indices, dim=1)
-
- pad_boxes = torch.where(sorted_mask[..., None], sorted_boxes, torch.zeros_like(sorted_boxes))
- pad_class_ids = torch.where(sorted_mask, sorted_class_ids, torch.zeros_like(sorted_class_ids))
- pad_class_ids = self._class_order_tensor[pad_class_ids]
-
- order_logits = self.reading_order(
- boxes=pad_boxes,
- labels=pad_class_ids,
- mask=mask,
- )[:, :, : self.num_queries]
-
- result = PPDocLayoutV2ForObjectDetectionOutput(
- logits=logits,
- pred_boxes=pred_boxes,
- order_logits=order_logits,
- last_hidden_state=outputs.last_hidden_state,
- intermediate_hidden_states=outputs.intermediate_hidden_states,
- intermediate_logits=outputs.intermediate_logits,
- intermediate_reference_points=outputs.intermediate_reference_points,
- intermediate_predicted_corners=outputs.intermediate_predicted_corners,
- initial_reference_points=outputs.initial_reference_points,
- decoder_hidden_states=outputs.decoder_hidden_states,
- decoder_attentions=outputs.decoder_attentions,
- cross_attentions=outputs.cross_attentions,
- encoder_last_hidden_state=outputs.encoder_last_hidden_state,
- encoder_hidden_states=outputs.encoder_hidden_states,
- encoder_attentions=outputs.encoder_attentions,
- init_reference_points=outputs.init_reference_points,
- enc_topk_logits=outputs.enc_topk_logits,
- enc_topk_bboxes=outputs.enc_topk_bboxes,
- enc_outputs_class=outputs.enc_outputs_class,
- enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
- denoising_meta_values=outputs.denoising_meta_values,
- )
- return result if use_return_dict else result.to_tuple()
+ """避开 MPS 不支持的 float64 运算,复用官方 CPU 位置编码缓存。"""
+ return self.embedding(width=width, height=height, device=torch.device("cpu"), dtype=dtype).to(device=device)
class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
@@ -786,7 +61,7 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
conf: float = 0.45,
use_paddlex_filter_boxes: bool = True,
):
- self.device = device
+ self.device = device or "cpu"
self.conf = conf
self.use_paddlex_filter_boxes = use_paddlex_filter_boxes
self.model_dir = weight
@@ -798,7 +73,19 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
)
self.rescale_factor = float(self.preprocess_config.get("rescale_factor", DEFAULT_RESCALE_FACTOR))
self.config = PPDocLayoutV2Config.from_pretrained(self.model_dir)
- self.model = PPDocLayoutV2ForObjectDetection.from_pretrained(self.model_dir, config=self.config)
+ # 保留原有 FP32 推理精度,直接加载到目标设备以减少 CPU 权重中转。
+ self.model = PPDocLayoutV2ForObjectDetection.from_pretrained(
+ self.model_dir,
+ config=self.config,
+ device_map={"": self.device},
+ dtype=torch.float32,
+ attn_implementation="eager" if torch.device(self.device).type == "mps" else None,
+ )
+ if torch.device(self.device).type == "mps":
+ # 官方正弦编码内部使用 float64;只适配这个无参数模块,不切换整个模型的设备。
+ for layer in self.model.model.encoder.aifi:
+ layer.position_embedding = _CpuSinePositionEmbedding(layer.position_embedding)
+ # 同步加载器生成的非持久化 buffer;已经位于目标设备的参数不会再次复制。
self.model.to(self.device)
self.model.eval()
diff --git a/mineru/model/mfr/unimernet/Unimernet.py b/mineru/model/mfr/unimernet/Unimernet.py
index 841e1151..6cfa1154 100644
--- a/mineru/model/mfr/unimernet/Unimernet.py
+++ b/mineru/model/mfr/unimernet/Unimernet.py
@@ -24,20 +24,17 @@ class MathDataset(Dataset):
class UnimernetModel(object):
- def __init__(self, weight_dir, _device_="cpu"):
+ def __init__(self, weight_dir: str, _device_: str = "cpu") -> None:
+ """直接按目标设备和精度加载权重,避免保留一次完整的 CPU FP32 中转分配。"""
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",
- )
- else:
- self.model = UnimernetModel.from_pretrained(weight_dir)
self.device = torch.device(_device_)
- self.model.to(self.device)
- if not _device_.startswith("cpu"):
- self.model = self.model.to(dtype=torch.float16)
+ self.model = UnimernetModel.from_pretrained(
+ weight_dir,
+ device_map={"": self.device},
+ dtype=torch.float32 if self.device.type == "cpu" else torch.float16,
+ attn_implementation="eager" if self.device.type in {"mps", "npu", "musa"} else None,
+ )
self.model.eval()
@staticmethod
@@ -153,9 +150,7 @@ class UnimernetModel(object):
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)
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/__init__.py b/mineru/model/mfr/unimernet/unimernet_hf/__init__.py
index b1071a4f..dd75d495 100644
--- a/mineru/model/mfr/unimernet/unimernet_hf/__init__.py
+++ b/mineru/model/mfr/unimernet/unimernet_hf/__init__.py
@@ -2,6 +2,7 @@
from .unimer_swin import UnimerSwinConfig, UnimerSwinModel, UnimerSwinImageProcessor
from .unimer_mbart import UnimerMBartConfig, UnimerMBartModel, UnimerMBartForCausalLM
from .modeling_unimernet import UnimernetModel
+from .configuration_unimernet import UnimernetConfig
__all__ = [
"UnimerSwinConfig",
@@ -11,4 +12,5 @@ __all__ = [
"UnimerMBartModel",
"UnimerMBartForCausalLM",
"UnimernetModel",
+ "UnimernetConfig",
]
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/configuration_unimernet.py b/mineru/model/mfr/unimernet/unimernet_hf/configuration_unimernet.py
new file mode 100644
index 00000000..3aad7664
--- /dev/null
+++ b/mineru/model/mfr/unimernet/unimernet_hf/configuration_unimernet.py
@@ -0,0 +1,31 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""显式解析 UniMERNet 子配置,避免修改 Transformers 的全局 Auto 注册表。"""
+
+from copy import deepcopy
+from typing import Any
+
+from transformers import PretrainedConfig, VisionEncoderDecoderConfig
+
+from .unimer_mbart.configuration_unimer_mbart import UnimerMBartConfig
+from .unimer_swin.configuration_unimer_swin import UnimerSwinConfig
+
+
+class UnimernetConfig(VisionEncoderDecoderConfig):
+ """保留现有组合配置的 JSON 标识,并固定编码器和解码器的实现归属。"""
+
+ model_type = "vision-encoder-decoder"
+ has_no_defaults_at_init = True
+ sub_configs = {"encoder": UnimerSwinConfig, "decoder": UnimerMBartConfig}
+
+ def __post_init__(self, **kwargs: Any) -> None:
+ """复制并构造两个子配置,保留原始模型文件及调用方字典。"""
+ encoder = kwargs.pop("encoder", None)
+ decoder = kwargs.pop("decoder", None)
+ if encoder is None or decoder is None:
+ raise ValueError("UniMERNet requires both encoder and decoder configurations")
+ self.encoder = encoder if isinstance(encoder, UnimerSwinConfig) else UnimerSwinConfig(**deepcopy(encoder))
+ self.decoder = decoder if isinstance(decoder, UnimerMBartConfig) else UnimerMBartConfig(**deepcopy(decoder))
+ PretrainedConfig.__post_init__(self, **kwargs)
+
+
+__all__ = ["UnimernetConfig"]
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py b/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py
index 6e480091..353e3c02 100644
--- a/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py
+++ b/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py
@@ -5,21 +5,14 @@ from typing import Optional
import torch
from ftfy import fix_text
-from loguru import logger
-from transformers import AutoConfig, AutoModel, AutoModelForCausalLM, AutoTokenizer, PretrainedConfig, PreTrainedModel
-from transformers import VisionEncoderDecoderConfig, VisionEncoderDecoderModel
-from transformers.models.vision_encoder_decoder.modeling_vision_encoder_decoder import logger as base_model_logger
+from transformers import AutoTokenizer, PretrainedConfig, PreTrainedModel, VisionEncoderDecoderModel
-from .unimer_swin import UnimerSwinConfig, UnimerSwinModel, UnimerSwinImageProcessor
-from .unimer_mbart import UnimerMBartConfig, UnimerMBartForCausalLM
+from .unimer_swin import UnimerSwinModel, UnimerSwinImageProcessor
+from .unimer_mbart import UnimerMBartForCausalLM
+from .configuration_unimernet import UnimernetConfig
from ...utils import fix_unimernet_latex
-AutoConfig.register(UnimerSwinConfig.model_type, UnimerSwinConfig)
-AutoConfig.register(UnimerMBartConfig.model_type, UnimerMBartConfig)
-AutoModel.register(UnimerSwinConfig, UnimerSwinModel)
-AutoModelForCausalLM.register(UnimerMBartConfig, UnimerMBartForCausalLM)
-
# TODO: rewrite tokenizer
class TokenizerWrapper:
@@ -52,42 +45,44 @@ class TokenizerWrapper:
for b in range(len(toks)):
for i in reversed(range(len(toks[b]))):
if toks[b][i] is None:
- toks[b][i] = ''
- toks[b][i] = toks[b][i].replace('Ġ', ' ').strip()
+ toks[b][i] = ""
+ toks[b][i] = toks[b][i].replace("Ġ", " ").strip()
if toks[b][i] in ([self.tokenizer.bos_token, self.tokenizer.eos_token, self.tokenizer.pad_token]):
del toks[b][i]
return toks
+
class UnimernetModel(VisionEncoderDecoderModel):
+ config_class = UnimernetConfig
+
def __init__(
self,
config: Optional[PretrainedConfig] = None,
encoder: Optional[PreTrainedModel] = None,
decoder: Optional[PreTrainedModel] = None,
):
- # VisionEncoderDecoderModel's checking log has bug, disable for temp.
- base_model_logger.disabled = True
- try:
- super().__init__(config, encoder, decoder)
- finally:
- base_model_logger.disabled = False
-
if not config or not hasattr(config, "_name_or_path"):
raise RuntimeError("config._name_or_path is required by UnimernetModel.")
+ # 显式构造子模型;加载本地权重不依赖进程级 Auto 注册副作用。
+ encoder = encoder if encoder is not None else UnimerSwinModel(config.encoder)
+ decoder = decoder if decoder is not None else UnimerMBartForCausalLM(config.decoder)
+ super().__init__(config, encoder, decoder)
+
model_path = config._name_or_path
self.transform = UnimerSwinImageProcessor()
- self.tokenizer = TokenizerWrapper(AutoTokenizer.from_pretrained(model_path))
+ self.tokenizer = TokenizerWrapper(AutoTokenizer.from_pretrained(model_path, config=config.decoder))
self._post_check()
-
+
def _post_check(self):
tokenizer = self.tokenizer
if tokenizer.tokenizer.model_max_length != self.config.decoder.max_position_embeddings:
warnings.warn(
- f"decoder.max_position_embeddings={self.config.decoder.max_position_embeddings}," +
- f" but tokenizer.model_max_length={tokenizer.tokenizer.model_max_length}, will set" +
- f" tokenizer.model_max_length to {self.config.decoder.max_position_embeddings}.")
+ f"decoder.max_position_embeddings={self.config.decoder.max_position_embeddings},"
+ + f" but tokenizer.model_max_length={tokenizer.tokenizer.model_max_length}, will set"
+ + f" tokenizer.model_max_length to {self.config.decoder.max_position_embeddings}."
+ )
tokenizer.tokenizer.model_max_length = self.config.decoder.max_position_embeddings
assert self.config.decoder.vocab_size == len(tokenizer)
@@ -95,11 +90,11 @@ class UnimernetModel(VisionEncoderDecoderModel):
assert self.config.pad_token_id == tokenizer.pad_token_id
@classmethod
- def from_checkpoint(cls, model_path: str, model_filename: str = "pytorch_model.pth", state_dict_strip_prefix="model.model."):
- config = VisionEncoderDecoderConfig.from_pretrained(model_path)
+ def from_checkpoint(
+ cls, model_path: str, model_filename: str = "pytorch_model.pth", state_dict_strip_prefix="model.model."
+ ):
+ config = UnimernetConfig.from_pretrained(model_path)
config._name_or_path = model_path
- config.encoder = UnimerSwinConfig(**vars(config.encoder))
- config.decoder = UnimerMBartConfig(**vars(config.decoder))
encoder = UnimerSwinModel(config.encoder)
decoder = UnimerMBartForCausalLM(config.decoder)
@@ -113,7 +108,7 @@ class UnimernetModel(VisionEncoderDecoderModel):
raise RuntimeError("state_dict is empty.")
if state_dict_strip_prefix:
state_dict = {
- k[len(state_dict_strip_prefix):] if k.startswith(state_dict_strip_prefix) else k: v
+ k[len(state_dict_strip_prefix) :] if k.startswith(state_dict_strip_prefix) else k: v
for k, v in state_dict.items()
}
missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
@@ -174,7 +169,7 @@ class UnimernetModel(VisionEncoderDecoderModel):
num_channels = pixel_values.shape[1]
if num_channels == 1:
pixel_values = pixel_values.repeat(1, 3, 1, 1)
-
+
kwargs = {}
if do_sample:
kwargs["temperature"] = temperature
@@ -188,7 +183,7 @@ class UnimernetModel(VisionEncoderDecoderModel):
outputs = super().generate(
pixel_values=pixel_values,
- max_new_tokens=self.tokenizer.tokenizer.model_max_length, # required
+ max_new_tokens=self.tokenizer.tokenizer.model_max_length, # required
decoder_start_token_id=self.tokenizer.tokenizer.bos_token_id,
do_sample=do_sample,
**kwargs,
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py
index eef4a57d..a7c7d96c 100644
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py
+++ b/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py
@@ -117,6 +117,7 @@ class UnimerMBartConfig(PretrainedConfig):
decoder_layerdrop=0.0,
use_cache=True,
is_encoder_decoder=True,
+ is_decoder=False,
activation_function="gelu",
d_model=1024,
qk_squeeze=2,
@@ -158,6 +159,9 @@ class UnimerMBartConfig(PretrainedConfig):
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
is_encoder_decoder=is_encoder_decoder,
+ is_decoder=is_decoder,
forced_eos_token_id=forced_eos_token_id,
**kwargs,
)
+ # 动态缓存根据实际文本解码层数分配层槽位。
+ self.num_hidden_layers = decoder_layers if is_decoder else encoder_layers
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py
index 7f503f91..ced72b88 100644
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py
+++ b/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py
@@ -26,12 +26,9 @@ from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FN
-from transformers.modeling_attn_mask_utils import (
- _prepare_4d_attention_mask,
- _prepare_4d_attention_mask_for_sdpa,
- _prepare_4d_causal_attention_mask,
- _prepare_4d_causal_attention_mask_for_sdpa,
-)
+from transformers import initialization as init
+from transformers.cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from transformers.masking_utils import create_bidirectional_mask, create_causal_mask
from transformers.modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPastAndCrossAttentions,
@@ -101,6 +98,7 @@ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int):
return prev_output_tokens
+
@dataclass
class CausalLMOutputWithCrossAttentionsAndCounting(CausalLMOutputWithCrossAttentions):
"""
@@ -138,8 +136,10 @@ class CausalLMOutputWithCrossAttentionsAndCounting(CausalLMOutputWithCrossAttent
counting:
Counting
"""
+
counting: Optional[torch.FloatTensor] = None
+
# Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->MBart
class UnimerMBartLearnedPositionalEmbedding(nn.Embedding):
"""
@@ -189,6 +189,7 @@ class UnimerMBartAttention(nn.Module):
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
+ layer_idx: Optional[int] = None,
*,
config: UnimerMBartConfig,
):
@@ -201,15 +202,15 @@ class UnimerMBartAttention(nn.Module):
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
- f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
- f" and `num_heads`: {num_heads})."
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})."
)
-
+
self.squeeze_dim = embed_dim // config.qk_squeeze
self.squeeze_head_dim = self.squeeze_dim // num_heads
self.scaling = self.squeeze_head_dim**-0.5
self.is_decoder = is_decoder
self.is_causal = is_causal
+ self.layer_idx = layer_idx
self.q_proj = nn.Linear(embed_dim, self.squeeze_dim, bias=bias)
self.k_proj = nn.Linear(embed_dim, self.squeeze_dim, bias=bias)
@@ -222,61 +223,56 @@ class UnimerMBartAttention(nn.Module):
def _shape_v(self, tensor: torch.Tensor, seq_len: int, bsz: int):
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+ def _project_key_value_states(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: Optional[torch.Tensor],
+ past_key_value: Optional[Cache],
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """保留压缩后的 Q/K 维度,并以 Transformers Cache 管理逐层 KV 与交叉注意力复用。"""
+ is_cross_attention = key_value_states is not None
+ cache = past_key_value
+ if isinstance(past_key_value, EncoderDecoderCache):
+ cache = past_key_value.cross_attention_cache if is_cross_attention else past_key_value.self_attention_cache
+ if is_cross_attention and past_key_value.is_updated.get(self.layer_idx, False):
+ layer = cache.layers[self.layer_idx]
+ return layer.keys, layer.values
+ elif is_cross_attention and cache is not None:
+ raise TypeError("Cross attention requires EncoderDecoderCache")
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ batch_size = current_states.shape[0]
+ keys = self.k_proj(current_states).view(batch_size, -1, self.num_heads, self.squeeze_head_dim)
+ values = self.v_proj(current_states).view(batch_size, -1, self.num_heads, self.head_dim)
+ keys = keys.transpose(1, 2).contiguous()
+ values = values.transpose(1, 2).contiguous()
+ if cache is not None:
+ if self.layer_idx is None:
+ raise ValueError("Cached attention requires a layer index")
+ keys, values = cache.update(keys, values, self.layer_idx)
+ if is_cross_attention:
+ past_key_value.is_updated[self.layer_idx] = True
+ return keys, values
+
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
+ past_key_value: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
- is_cross_attention = key_value_states is not None
bsz, tgt_len, _ = hidden_states.size()
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
- # get key, value proj
- # `past_key_value[0].shape[2] == key_value_states.shape[1]`
- # is checking that the `sequence_length` of the `past_key_value` is the same as
- # the provided `key_value_states` to support prefix tuning
- if (
- is_cross_attention
- and past_key_value is not None
- and past_key_value[0].shape[2] == key_value_states.shape[1]
- ):
- # reuse k,v, cross_attentions
- key_states = past_key_value[0]
- value_states = past_key_value[1]
- elif is_cross_attention:
- # cross_attentions
- key_states = self._shape_qk(self.k_proj(key_value_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(key_value_states), -1, bsz)
- elif past_key_value is not None:
- # reuse k, v, self_attention
- key_states = self._shape_qk(self.k_proj(hidden_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(hidden_states), -1, bsz)
- key_states = torch.cat([past_key_value[0], key_states], dim=2)
- value_states = torch.cat([past_key_value[1], value_states], dim=2)
- else:
- # self_attention
- key_states = self._shape_qk(self.k_proj(hidden_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(hidden_states), -1, bsz)
-
- if self.is_decoder:
- # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
- # Further calls to cross_attention layer can then reuse all cross-attention
- # key/value_states (first "if" case)
- # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
- # all previous decoder key/value_states. Further calls to uni-directional self-attention
- # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
- # if encoder bi-directional self-attention `past_key_value` is always `None`
- past_key_value = (key_states, value_states)
+ key_states, value_states = self._project_key_value_states(hidden_states, key_value_states, past_key_value)
proj_shape = (bsz * self.num_heads, -1, self.squeeze_head_dim)
value_shape = (bsz * self.num_heads, -1, self.head_dim)
@@ -289,8 +285,7 @@ class UnimerMBartAttention(nn.Module):
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
raise ValueError(
- f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
- f" {attn_weights.size()}"
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
)
if attention_mask is not None:
@@ -306,8 +301,7 @@ class UnimerMBartAttention(nn.Module):
if layer_head_mask is not None:
if layer_head_mask.size() != (self.num_heads,):
raise ValueError(
- f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
- f" {layer_head_mask.size()}"
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
)
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
@@ -327,8 +321,7 @@ class UnimerMBartAttention(nn.Module):
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
raise ValueError(
- f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
- f" {attn_output.size()}"
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}"
)
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
@@ -373,64 +366,26 @@ class UnimerMBartFlashAttention2(UnimerMBartAttention):
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
+ past_key_value: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
# MBartFlashAttention2 attention does not support output_attentions
if output_attentions:
raise ValueError("MBartFlashAttention2 attention does not support output_attentions")
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
- is_cross_attention = key_value_states is not None
bsz, q_len, _ = hidden_states.size()
# get query proj
query_states = self._shape_qk(self.q_proj(hidden_states), -1, bsz)
- # get key, value proj
- # `past_key_value[0].shape[2] == key_value_states.shape[1]`
- # is checking that the `sequence_length` of the `past_key_value` is the same as
- # the provided `key_value_states` to support prefix tuning
- if (
- is_cross_attention
- and past_key_value is not None
- and past_key_value[0].shape[2] == key_value_states.shape[1]
- ):
- # reuse k,v, cross_attentions
- key_states = past_key_value[0].transpose(1, 2)
- value_states = past_key_value[1].transpose(1, 2)
- elif is_cross_attention:
- # cross_attentions
- key_states = self._shape_qk(self.k_proj(key_value_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(key_value_states), -1, bsz)
- elif past_key_value is not None:
- # reuse k, v, self_attention
- key_states = self._shape_qk(self.k_proj(hidden_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(hidden_states), -1, bsz)
- key_states = torch.cat([past_key_value[0].transpose(1, 2), key_states], dim=1)
- value_states = torch.cat([past_key_value[1].transpose(1, 2), value_states], dim=1)
- else:
- # self_attention
- key_states = self._shape_qk(self.k_proj(hidden_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(hidden_states), -1, bsz)
-
- if self.is_decoder:
- # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
- # Further calls to cross_attention layer can then reuse all cross-attention
- # key/value_states (first "if" case)
- # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
- # all previous decoder key/value_states. Further calls to uni-directional self-attention
- # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
- # if encoder bi-directional self-attention `past_key_value` is always `None`
- past_key_value = (key_states.transpose(1, 2), value_states.transpose(1, 2))
-
- kv_seq_len = key_states.shape[-2]
- if past_key_value is not None:
- kv_seq_len += past_key_value[0].shape[-2]
+ key_states, value_states = self._project_key_value_states(hidden_states, key_value_states, past_key_value)
+ key_states = key_states.transpose(1, 2)
+ value_states = value_states.transpose(1, 2)
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
# therefore the input hidden states gets silently casted in float32. Hence, we need
@@ -536,16 +491,10 @@ class UnimerMBartFlashAttention2(UnimerMBartAttention):
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
- key_layer = index_first_axis(
- key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
- )
- value_layer = index_first_axis(
- value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
- )
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k)
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k)
if query_length == kv_seq_len:
- query_layer = index_first_axis(
- query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
- )
+ query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k)
cu_seqlens_q = cu_seqlens_k
max_seqlen_in_batch_q = max_seqlen_in_batch_k
indices_q = indices_k
@@ -570,16 +519,17 @@ class UnimerMBartFlashAttention2(UnimerMBartAttention):
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
)
+
class UnimerMBartSdpaAttention(UnimerMBartAttention):
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
+ past_key_value: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
"""Input shape: Batch x Time x Channel"""
if output_attentions or layer_head_mask is not None:
# TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once this is implemented.
@@ -598,48 +548,12 @@ class UnimerMBartSdpaAttention(UnimerMBartAttention):
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
- is_cross_attention = key_value_states is not None
bsz, tgt_len, _ = hidden_states.size()
# get query proj
query_states = self.q_proj(hidden_states)
- # get key, value proj
- # `past_key_value[0].shape[2] == key_value_states.shape[1]`
- # is checking that the `sequence_length` of the `past_key_value` is the same as
- # the provided `key_value_states` to support prefix tuning
- if (
- is_cross_attention
- and past_key_value is not None
- and past_key_value[0].shape[2] == key_value_states.shape[1]
- ):
- # reuse k,v, cross_attentions
- key_states = past_key_value[0]
- value_states = past_key_value[1]
- elif is_cross_attention:
- # cross_attentions
- key_states = self._shape_qk(self.k_proj(key_value_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(key_value_states), -1, bsz)
- elif past_key_value is not None:
- # reuse k, v, self_attention
- key_states = self._shape_qk(self.k_proj(hidden_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(hidden_states), -1, bsz)
- key_states = torch.cat([past_key_value[0], key_states], dim=2)
- value_states = torch.cat([past_key_value[1], value_states], dim=2)
- else:
- # self_attention
- key_states = self._shape_qk(self.k_proj(hidden_states), -1, bsz)
- value_states = self._shape_v(self.v_proj(hidden_states), -1, bsz)
-
- if self.is_decoder:
- # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
- # Further calls to cross_attention layer can then reuse all cross-attention
- # key/value_states (first "if" case)
- # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
- # all previous decoder key/value_states. Further calls to uni-directional self-attention
- # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
- # if encoder bi-directional self-attention `past_key_value` is always `None`
- past_key_value = (key_states, value_states)
+ key_states, value_states = self._project_key_value_states(hidden_states, key_value_states, past_key_value)
query_states = self._shape_qk(query_states, tgt_len, bsz)
@@ -661,8 +575,7 @@ class UnimerMBartSdpaAttention(UnimerMBartAttention):
if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
raise ValueError(
- f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
- f" {attn_output.size()}"
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}"
)
attn_output = attn_output.transpose(1, 2)
@@ -675,6 +588,7 @@ class UnimerMBartSdpaAttention(UnimerMBartAttention):
return attn_output, None, past_key_value
+
UNIMER_MBART_ATTENTION_CLASSES = {
"eager": UnimerMBartAttention,
"flash_attention_2": UnimerMBartFlashAttention2,
@@ -738,9 +652,7 @@ class UnimerMBartEncoderLayer(nn.Module):
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
- if hidden_states.dtype == torch.float16 and (
- torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
- ):
+ if hidden_states.dtype == torch.float16 and (torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()):
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
@@ -753,7 +665,7 @@ class UnimerMBartEncoderLayer(nn.Module):
class UnimerMBartDecoderLayer(nn.Module):
- def __init__(self, config: UnimerMBartConfig):
+ def __init__(self, config: UnimerMBartConfig, layer_idx: int):
super().__init__()
self.embed_dim = config.d_model
@@ -764,6 +676,7 @@ class UnimerMBartDecoderLayer(nn.Module):
is_decoder=True,
is_causal=True,
config=config,
+ layer_idx=layer_idx,
)
self.dropout = config.dropout
self.activation_fn = ACT2FN[config.activation_function]
@@ -776,6 +689,7 @@ class UnimerMBartDecoderLayer(nn.Module):
dropout=config.attention_dropout,
is_decoder=True,
config=config,
+ layer_idx=layer_idx,
)
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
@@ -790,7 +704,7 @@ class UnimerMBartDecoderLayer(nn.Module):
encoder_attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
+ past_key_value: Optional[Cache] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = True,
) -> torch.Tensor:
@@ -816,9 +730,9 @@ class UnimerMBartDecoderLayer(nn.Module):
hidden_states = self.self_attn_layer_norm(hidden_states)
# Self Attention
- # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
- self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
- # add present self-attn cache to positions 1,2 of present_key_value tuple
+ # 自注意力和交叉注意力共享同一个 EncoderDecoderCache,按 layer_idx 分开存储。
+ self_attn_past_key_value = past_key_value
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states=hidden_states,
past_key_value=self_attn_past_key_value,
@@ -836,8 +750,7 @@ class UnimerMBartDecoderLayer(nn.Module):
residual = hidden_states
hidden_states = self.encoder_attn_layer_norm(hidden_states)
- # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
- cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
+ cross_attn_past_key_value = past_key_value
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
hidden_states=hidden_states,
key_value_states=encoder_hidden_states,
@@ -849,8 +762,8 @@ class UnimerMBartDecoderLayer(nn.Module):
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
- # add cross-attn to positions 3,4 of present_key_value tuple
- present_key_value = present_key_value + cross_attn_present_key_value
+ # Cache 已由注意力层原地更新。
+ present_key_value = past_key_value
# Fully Connected
residual = hidden_states
@@ -901,20 +814,23 @@ class UnimerMBartPreTrainedModel(PreTrainedModel):
config_class = UnimerMBartConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
- _no_split_modules = ["MBartDecoderLayer", "MBartSqueezeAttention"]
- _supports_flash_attn_2 = True
+ _no_split_modules = ["UnimerMBartDecoderLayer", "UnimerMBartEncoderLayer"]
+ _supports_flash_attn = True
_supports_sdpa = True
- def _init_weights(self, module):
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module) -> None:
+ """只初始化尚未加载的参数,避免 Transformers 5 的加载后初始化覆盖真实权重。"""
std = self.config.init_std
if isinstance(module, nn.Linear):
- module.weight.data.normal_(mean=0.0, std=std)
+ init.normal_(module.weight, mean=0.0, std=std)
if module.bias is not None:
- module.bias.data.zero_()
+ init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
- module.weight.data.normal_(mean=0.0, std=std)
- if module.padding_idx is not None:
- module.weight.data[module.padding_idx].zero_()
+ init.normal_(module.weight, mean=0.0, std=std)
+ # 切片不携带已加载标记,因此在清零 padding 行之前检查原始参数。
+ if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
+ init.zeros_(module.weight[module.padding_idx])
@property
def dummy_inputs(self):
@@ -1174,9 +1090,7 @@ class UnimerMBartEncoder(UnimerMBartPreTrainedModel):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = (
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- )
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# retrieve input_ids and inputs_embeds
@@ -1200,19 +1114,12 @@ class UnimerMBartEncoder(UnimerMBartPreTrainedModel):
hidden_states = self.layernorm_embedding(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- # expand attention_mask
- if attention_mask is not None:
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
- if self._use_flash_attention_2:
- attention_mask = attention_mask if 0 in attention_mask else None
- elif self._use_sdpa and head_mask is None and not output_attentions:
- # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
- # the manual implementation that requires a 4D causal mask in all cases.
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
- attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
- else:
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
- attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
+ # 新版 mask API 在 SDPA 回退时保持加性 mask 的语义。
+ mask_config = self.config
+ if self._use_sdpa and (head_mask is not None or output_attentions):
+ mask_config = copy.copy(self.config)
+ mask_config._attn_implementation = "eager"
+ attention_mask = create_bidirectional_mask(mask_config, inputs_embeds, attention_mask)
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
@@ -1221,8 +1128,7 @@ class UnimerMBartEncoder(UnimerMBartPreTrainedModel):
if head_mask is not None:
if head_mask.size()[0] != len(self.layers):
raise ValueError(
- f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
- f" {head_mask.size()[0]}."
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
)
for idx, encoder_layer in enumerate(self.layers):
if output_hidden_states:
@@ -1265,9 +1171,7 @@ class UnimerMBartEncoder(UnimerMBartPreTrainedModel):
if not return_dict:
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
- return BaseModelOutput(
- last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
- )
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)
class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
@@ -1298,7 +1202,7 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
config.max_position_embeddings,
config.d_model,
)
- self.layers = nn.ModuleList([UnimerMBartDecoderLayer(config) for _ in range(config.decoder_layers)])
+ self.layers = nn.ModuleList([UnimerMBartDecoderLayer(config, layer_idx) for layer_idx in range(config.decoder_layers)])
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
self._use_sdpa = config._attn_implementation == "sdpa"
self.layernorm_embedding = nn.LayerNorm(config.d_model)
@@ -1323,7 +1227,7 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
encoder_attention_mask: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] = None,
- past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
+ past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
@@ -1396,9 +1300,7 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = (
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- )
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
@@ -1415,52 +1317,25 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
else:
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
- # past_key_values_length
- # past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
- past_key_values_length = 0
- if past_key_values is not None:
- if isinstance(past_key_values, (list, tuple)) and past_key_values:
- past_key_values_length = past_key_values[0][0].shape[2]
+ if past_key_values is not None and not isinstance(past_key_values, Cache):
+ raise TypeError("past_key_values must be a Transformers Cache instance")
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
- if self._use_flash_attention_2:
- # 2d mask is passed through the layers
- attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
- elif self._use_sdpa and not output_attentions and cross_attn_head_mask is None:
- # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on
- # the manual implementation that requires a 4D causal mask in all cases.
- attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
- attention_mask,
- input_shape,
- inputs_embeds,
- past_key_values_length,
- )
- else:
- # 4d mask is passed through the layers
- attention_mask = _prepare_4d_causal_attention_mask(
- attention_mask, input_shape, inputs_embeds, past_key_values_length
- )
-
- # expand encoder attention mask
+ # SDPA 回退到 eager 时也显式生成加性 mask,保持因果关系和 padding 语义。
+ mask_config = self.config
+ if self._use_sdpa and (output_attentions or head_mask is not None or cross_attn_head_mask is not None):
+ mask_config = copy.copy(self.config)
+ mask_config._attn_implementation = "eager"
+ # 单 token 解码没有未来位置;无 padding 时沿用原有的无 mask 快速路径。
+ if input_shape[-1] > 1 or attention_mask is not None:
+ attention_mask = create_causal_mask(mask_config, inputs_embeds, attention_mask, past_key_values)
if encoder_hidden_states is not None and encoder_attention_mask is not None:
- if self._use_flash_attention_2:
- encoder_attention_mask = encoder_attention_mask if 0 in encoder_attention_mask else None
- elif self._use_sdpa and cross_attn_head_mask is None and not output_attentions:
- # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on
- # the manual implementation that requires a 4D causal mask in all cases.
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
- encoder_attention_mask = _prepare_4d_attention_mask_for_sdpa(
- encoder_attention_mask,
- inputs_embeds.dtype,
- tgt_len=input_shape[-1],
- )
- else:
- # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
- encoder_attention_mask = _prepare_4d_attention_mask(
- encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
- )
+ encoder_attention_mask = create_bidirectional_mask(
+ mask_config, inputs_embeds, encoder_attention_mask, encoder_hidden_states=encoder_hidden_states
+ )
# embed positions
positions = self.embed_positions(input, past_key_values_length)
@@ -1486,7 +1361,12 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
- next_decoder_cache = () if use_cache else None
+ # 不传配置创建动态缓存,以保留 UniMERNet 不相等的 key/value head 维度。
+ if use_cache and past_key_values is None:
+ past_key_values = DynamicCache()
+ if past_key_values is not None and encoder_hidden_states is not None:
+ if not isinstance(past_key_values, EncoderDecoderCache):
+ past_key_values = EncoderDecoderCache(past_key_values, DynamicCache())
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
@@ -1505,13 +1385,6 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
if dropout_probability < self.layerdrop:
continue
- # past_key_value = past_key_values[idx] if past_key_values is not None else None
- past_key_value = past_key_values[idx] if (
- past_key_values is not None and
- isinstance(past_key_values, (list, tuple)) and
- idx < len(past_key_values)
- ) else None
-
if self.gradient_checkpointing and self.training:
layer_outputs = self._gradient_checkpointing_func(
decoder_layer.__call__,
@@ -1532,18 +1405,13 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
- cross_attn_layer_head_mask=(
- cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
- ),
- past_key_value=past_key_value,
+ cross_attn_layer_head_mask=(cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None),
+ past_key_value=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
)
hidden_states = layer_outputs[0]
- if use_cache:
- next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
-
if output_attentions:
all_self_attns += (layer_outputs[1],)
@@ -1556,12 +1424,10 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
if output_hidden_states:
all_hidden_states += (hidden_states,)
- next_cache = next_decoder_cache if use_cache else None
+ next_cache = past_key_values if use_cache else None
if not return_dict:
return tuple(
- v
- for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
- if v is not None
+ v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions] if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
@@ -1577,7 +1443,7 @@ class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
MBART_START_DOCSTRING,
)
class UnimerMBartModel(UnimerMBartPreTrainedModel):
- _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
+ _tied_weights_keys = {"encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight"}
def __init__(self, config: UnimerMBartConfig):
super().__init__(config)
@@ -1605,11 +1471,6 @@ class UnimerMBartModel(UnimerMBartPreTrainedModel):
def get_decoder(self):
return self.decoder
- def _tie_weights(self):
- if self.config.tie_word_embeddings:
- self._tie_or_clone_weights(self.encoder.embed_tokens, self.get_input_embeddings())
- self._tie_or_clone_weights(self.decoder.embed_tokens, self.get_input_embeddings())
-
@add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
@@ -1627,7 +1488,7 @@ class UnimerMBartModel(UnimerMBartPreTrainedModel):
decoder_head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
- past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
+ past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
@@ -1636,9 +1497,7 @@ class UnimerMBartModel(UnimerMBartPreTrainedModel):
return_dict: Optional[bool] = None,
) -> Union[Seq2SeqModelOutput, Tuple[torch.FloatTensor]]:
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = (
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- )
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
@@ -1703,7 +1562,11 @@ class UnimerMBartModel(UnimerMBartPreTrainedModel):
class UnimerMBartForConditionalGeneration(UnimerMBartPreTrainedModel, GenerationMixin):
base_model_prefix = "model"
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
- _tied_weights_keys = ["model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight"]
+ _tied_weights_keys = {
+ "model.encoder.embed_tokens.weight": "model.shared.weight",
+ "model.decoder.embed_tokens.weight": "model.shared.weight",
+ "lm_head.weight": "model.shared.weight",
+ }
def __init__(self, config: UnimerMBartConfig):
super().__init__(config)
@@ -1753,7 +1616,7 @@ class UnimerMBartForConditionalGeneration(UnimerMBartPreTrainedModel, Generation
decoder_head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
- past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
+ past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
@@ -1820,57 +1683,9 @@ class UnimerMBartForConditionalGeneration(UnimerMBartPreTrainedModel, Generation
encoder_attentions=outputs.encoder_attentions,
)
- def prepare_inputs_for_generation(
- self,
- decoder_input_ids,
- past_key_values=None,
- attention_mask=None,
- head_mask=None,
- decoder_head_mask=None,
- cross_attn_head_mask=None,
- use_cache=None,
- encoder_outputs=None,
- **kwargs,
- ):
- # cut decoder_input_ids if past is used
- if past_key_values is not None:
- past_length = past_key_values[0][0].shape[2]
-
- # Some generation methods already pass only the last input ID
- if decoder_input_ids.shape[1] > past_length:
- remove_prefix_length = past_length
- else:
- # Default to old behavior: keep only final ID
- remove_prefix_length = decoder_input_ids.shape[1] - 1
-
- decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]
-
- return {
- "input_ids": None, # encoder_outputs is defined. input_ids not needed
- "encoder_outputs": encoder_outputs,
- "past_key_values": past_key_values,
- "decoder_input_ids": decoder_input_ids,
- "attention_mask": attention_mask,
- "head_mask": head_mask,
- "decoder_head_mask": decoder_head_mask,
- "cross_attn_head_mask": cross_attn_head_mask,
- "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
- }
-
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
return shift_tokens_right(labels, self.config.pad_token_id)
- @staticmethod
- def _reorder_cache(past_key_values, beam_idx):
- reordered_past = ()
- for layer_past in past_key_values:
- # cached cross_attention states don't have to be reordered -> they are always the same
- reordered_past += (
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
- + layer_past[2:],
- )
- return reordered_past
-
@add_start_docstrings(
"""
@@ -1880,7 +1695,10 @@ class UnimerMBartForConditionalGeneration(UnimerMBartPreTrainedModel, Generation
MBART_START_DOCSTRING,
)
class UnimerMBartForSequenceClassification(UnimerMBartPreTrainedModel):
- _tied_weights_keys = ["model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight"]
+ _tied_weights_keys = {
+ "model.encoder.embed_tokens.weight": "model.shared.weight",
+ "model.decoder.embed_tokens.weight": "model.shared.weight",
+ }
def __init__(self, config: UnimerMBartConfig, **kwargs):
super().__init__(config, **kwargs)
@@ -1930,9 +1748,7 @@ class UnimerMBartForSequenceClassification(UnimerMBartPreTrainedModel):
use_cache = False
if input_ids is None and inputs_embeds is not None:
- raise NotImplementedError(
- f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
- )
+ raise NotImplementedError(f"Passing input embeddings is currently not supported for {self.__class__.__name__}")
outputs = self.model(
input_ids,
@@ -1956,9 +1772,7 @@ class UnimerMBartForSequenceClassification(UnimerMBartPreTrainedModel):
if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
raise ValueError("All examples must have the same number of <eos> tokens.")
- sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
- :, -1, :
- ]
+ sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[:, -1, :]
logits = self.classification_head(sentence_representation)
loss = None
@@ -2009,7 +1823,10 @@ class UnimerMBartForSequenceClassification(UnimerMBartPreTrainedModel):
MBART_START_DOCSTRING,
)
class UnimerMBartForQuestionAnswering(UnimerMBartPreTrainedModel):
- _tied_weights_keys = ["model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight"]
+ _tied_weights_keys = {
+ "model.encoder.embed_tokens.weight": "model.shared.weight",
+ "model.decoder.embed_tokens.weight": "model.shared.weight",
+ }
def __init__(self, config):
super().__init__(config)
@@ -2142,11 +1959,12 @@ class UnimerMBartDecoderWrapper(UnimerMBartPreTrainedModel):
# Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->MBart, facebook/bart-base->facebook/mbart-large-cc25
class UnimerMBartForCausalLM(UnimerMBartPreTrainedModel, GenerationMixin):
- _tied_weights_keys = ["lm_head.weight"]
+ _tied_weights_keys = {"lm_head.weight": "model.decoder.embed_tokens.weight"}
def __init__(self, config):
config = copy.deepcopy(config)
config.is_decoder = True
+ config.num_hidden_layers = config.decoder_layers
config.is_encoder_decoder = False
super().__init__(config)
self.model = UnimerMBartDecoderWrapper(config)
@@ -2183,7 +2001,7 @@ class UnimerMBartForCausalLM(UnimerMBartPreTrainedModel, GenerationMixin):
encoder_attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] = None,
- past_key_values: Optional[List[torch.FloatTensor]] = None,
+ past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
@@ -2279,9 +2097,7 @@ class UnimerMBartForCausalLM(UnimerMBartPreTrainedModel, GenerationMixin):
```"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = (
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- )
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
count_pred = None
@@ -2324,38 +2140,3 @@ class UnimerMBartForCausalLM(UnimerMBartPreTrainedModel, GenerationMixin):
cross_attentions=outputs.cross_attentions,
counting=count_pred,
)
-
- def prepare_inputs_for_generation(
- self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
- ):
- # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
- if attention_mask is None:
- attention_mask = input_ids.new_ones(input_ids.shape)
-
- if past_key_values:
- past_length = past_key_values[0][0].shape[2]
-
- # Some generation methods already pass only the last input ID
- if input_ids.shape[1] > past_length:
- remove_prefix_length = past_length
- else:
- # Default to old behavior: keep only final ID
- remove_prefix_length = input_ids.shape[1] - 1
-
- input_ids = input_ids[:, remove_prefix_length:]
- # first step, decoder_cached_states are empty
- return {
- "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
- "attention_mask": attention_mask,
- "past_key_values": past_key_values,
- "use_cache": use_cache,
- }
-
- @staticmethod
- def _reorder_cache(past_key_values, beam_idx):
- reordered_past = ()
- for layer_past in past_key_values:
- reordered_past += (
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
- )
- return reordered_past
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py
index 1b808e8b..2c5ec90e 100644
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py
+++ b/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py
@@ -27,8 +27,8 @@ import torch.utils.checkpoint
from torch import nn
from transformers.activations import ACT2FN
+from transformers import initialization as init
from transformers.modeling_utils import PreTrainedModel
-from transformers.pytorch_utils import find_pruneable_heads_and_indices, meshgrid, prune_linear_layer
from transformers.utils import (
ModelOutput,
add_code_sample_docstrings,
@@ -230,13 +230,13 @@ class UnimerSwinEmbeddings(nn.Module):
# embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
# else:
# embeddings = embeddings + self.position_embeddings
- embeddings = embeddings + self.position_embeddings[:, :seq_len, :] # code edited.
+ embeddings = embeddings + self.position_embeddings[:, :seq_len, :] # code edited.
### code added. ###
if self.row_embeddings is not None and self.column_embeddings is not None:
# Repeat the x position embeddings across the y axis like 0, 1, 2, 3, 0, 1, 2, 3, ...
- row_embeddings = self.row_embeddings[:, :output_dimensions[0], :].repeat_interleave(output_dimensions[1], dim=1)
- column_embeddings = self.column_embeddings[:, :output_dimensions[1], :].repeat(1, output_dimensions[0], 1)
+ row_embeddings = self.row_embeddings[:, : output_dimensions[0], :].repeat_interleave(output_dimensions[1], dim=1)
+ column_embeddings = self.column_embeddings[:, : output_dimensions[1], :].repeat(1, output_dimensions[0], 1)
embeddings = embeddings + row_embeddings + column_embeddings
######
@@ -244,8 +244,9 @@ class UnimerSwinEmbeddings(nn.Module):
return embeddings, output_dimensions
+
class StemLayer(nn.Module):
- r""" Stem layer of InternImage
+ r"""Stem layer of InternImage
Args:
in_chans (int): number of input channels
out_chans (int): number of output channels
@@ -253,7 +254,7 @@ class StemLayer(nn.Module):
norm_layer (str): normalization layer
"""
- def __init__(self, in_chans=3, out_chans=96, act_layer=nn.GELU, norm_layer='BN'):
+ def __init__(self, in_chans=3, out_chans=96, act_layer=nn.GELU, norm_layer="BN"):
super().__init__()
self.conv1 = nn.Conv2d(in_chans, out_chans // 2, kernel_size=3, stride=2, padding=1)
self.norm1 = self.build_norm_layer(out_chans // 2, norm_layer)
@@ -262,10 +263,10 @@ class StemLayer(nn.Module):
def build_norm_layer(self, dim, norm_layer):
layers = []
- if norm_layer == 'BN':
+ if norm_layer == "BN":
layers.append(nn.BatchNorm2d(dim))
else:
- raise NotImplementedError(f'build_norm_layer does not support {norm_layer}')
+ raise NotImplementedError(f"build_norm_layer does not support {norm_layer}")
return nn.Sequential(*layers)
def forward(self, x):
@@ -275,6 +276,7 @@ class StemLayer(nn.Module):
x = self.conv2(x)
return x
+
# Copied from transformers.models.swin.modeling_swin.SwinPatchEmbeddings with Swin->UnimerSwin
class UnimerSwinPatchEmbeddings(nn.Module):
"""
@@ -418,16 +420,12 @@ class UnimerSwinSelfAttention(nn.Module):
def __init__(self, config, dim, num_heads, window_size):
super().__init__()
if dim % num_heads != 0:
- raise ValueError(
- f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
- )
+ raise ValueError(f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})")
self.num_attention_heads = num_heads
self.attention_head_size = int(dim / num_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
- self.window_size = (
- window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
- )
+ self.window_size = window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
self.relative_position_bias_table = nn.Parameter(
torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), num_heads)
@@ -436,7 +434,7 @@ class UnimerSwinSelfAttention(nn.Module):
# get pair-wise relative position index for each token inside the window
coords_h = torch.arange(self.window_size[0])
coords_w = torch.arange(self.window_size[1])
- coords = torch.stack(meshgrid([coords_h, coords_w], indexing="ij"))
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w], indexing="ij"))
coords_flatten = torch.flatten(coords, 1)
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
relative_coords = relative_coords.permute(1, 2, 0).contiguous()
@@ -487,9 +485,7 @@ class UnimerSwinSelfAttention(nn.Module):
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in UnimerSwinModel forward() function)
mask_shape = attention_mask.shape[0]
- attention_scores = attention_scores.view(
- batch_size // mask_shape, mask_shape, self.num_attention_heads, dim, dim
- )
+ attention_scores = attention_scores.view(batch_size // mask_shape, mask_shape, self.num_attention_heads, dim, dim)
attention_scores = attention_scores + attention_mask.unsqueeze(1).unsqueeze(0)
attention_scores = attention_scores.view(-1, self.num_attention_heads, dim, dim)
@@ -536,24 +532,6 @@ class UnimerSwinAttention(nn.Module):
self.output = UnimerSwinSelfOutput(config, dim)
self.pruned_heads = set()
- def prune_heads(self, heads):
- if len(heads) == 0:
- return
- heads, index = find_pruneable_heads_and_indices(
- heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
- )
-
- # Prune linear layers
- self.self.query = prune_linear_layer(self.self.query, index)
- self.self.key = prune_linear_layer(self.self.key, index)
- self.self.value = prune_linear_layer(self.self.value, index)
- self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
-
- # Update hyper params and store pruned heads
- self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
- self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
- self.pruned_heads = self.pruned_heads.union(heads)
-
def forward(
self,
hidden_states: torch.Tensor,
@@ -597,16 +575,11 @@ class UnimerSwinOutput(nn.Module):
class ConvEnhance(nn.Module):
- """Depth-wise convolution to get the positional information.
- """
+ """Depth-wise convolution to get the positional information."""
+
def __init__(self, config, dim, k=3):
super(ConvEnhance, self).__init__()
- self.proj = nn.Conv2d(dim,
- dim,
- (k,k),
- (1,1),
- (k // 2,k // 2),
- groups=dim)
+ self.proj = nn.Conv2d(dim, dim, (k, k), (1, 1), (k // 2, k // 2), groups=dim)
self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x, size: Tuple[int, int]):
@@ -633,8 +606,7 @@ class UnimerSwinLayer(nn.Module):
self.input_resolution = input_resolution
self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
- self.ce = nn.ModuleList([ConvEnhance(config, dim=dim, k=3),
- ConvEnhance(config, dim=dim, k=3)])
+ self.ce = nn.ModuleList([ConvEnhance(config, dim=dim, k=3), ConvEnhance(config, dim=dim, k=3)])
self.attention = UnimerSwinAttention(config, dim, num_heads, window_size=self.window_size)
self.drop_path = UnimerSwinDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
@@ -646,9 +618,7 @@ class UnimerSwinLayer(nn.Module):
if min(input_resolution) <= self.window_size:
# if window size is larger than input resolution, we don't partition windows
self.shift_size = torch_int(0)
- self.window_size = (
- torch.min(torch.tensor(input_resolution)) if torch.jit.is_tracing() else min(input_resolution)
- )
+ self.window_size = torch.min(torch.tensor(input_resolution)) if torch.jit.is_tracing() else min(input_resolution)
def get_attn_mask(self, height, width, dtype, device):
if self.shift_size > 0:
@@ -699,13 +669,10 @@ class UnimerSwinLayer(nn.Module):
pass
height, width = input_dimensions
batch_size, _, channels = hidden_states.size()
-
-
hidden_states = self.ce[0](hidden_states, input_dimensions)
shortcut = hidden_states
-
hidden_states = self.layernorm_before(hidden_states)
hidden_states = hidden_states.view(batch_size, height, width, channels)
@@ -722,13 +689,9 @@ class UnimerSwinLayer(nn.Module):
# partition windows
hidden_states_windows = window_partition(shifted_hidden_states, self.window_size)
hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
- attn_mask = self.get_attn_mask(
- height_pad, width_pad, dtype=hidden_states.dtype, device=hidden_states_windows.device
- )
+ attn_mask = self.get_attn_mask(height_pad, width_pad, dtype=hidden_states.dtype, device=hidden_states_windows.device)
- attention_outputs = self.attention(
- hidden_states_windows, attn_mask, head_mask, output_attentions=output_attentions
- )
+ attention_outputs = self.attention(hidden_states_windows, attn_mask, head_mask, output_attentions=output_attentions)
attention_output = attention_outputs[0]
@@ -749,8 +712,6 @@ class UnimerSwinLayer(nn.Module):
hidden_states = shortcut + self.drop_path(attention_windows)
-
-
hidden_states = self.ce[1](hidden_states, input_dimensions)
layer_output = self.layernorm_after(hidden_states)
layer_output = self.intermediate(layer_output)
@@ -799,9 +760,7 @@ class UnimerSwinStage(nn.Module):
for i, layer_module in enumerate(self.blocks):
layer_head_mask = head_mask[i] if head_mask is not None else None
- layer_outputs = layer_module(
- hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
- )
+ layer_outputs = layer_module(hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition)
hidden_states = layer_outputs[0]
@@ -935,17 +894,18 @@ class UnimerSwinPreTrainedModel(PreTrainedModel):
supports_gradient_checkpointing = True
_no_split_modules = ["UnimerSwinStage"]
- def _init_weights(self, module):
- """Initialize the weights"""
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module) -> None:
+ """仅初始化未加载的 Swin 参数,保留 safetensors 中的预训练值。"""
if isinstance(module, (nn.Linear, nn.Conv2d)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
- module.bias.data.zero_()
+ init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
- module.bias.data.zero_()
- module.weight.data.fill_(1.0)
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
SWIN_START_DOCSTRING = r"""
@@ -1004,14 +964,6 @@ class UnimerSwinModel(UnimerSwinPreTrainedModel):
def get_input_embeddings(self):
return self.embeddings.patch_embeddings
- def _prune_heads(self, heads_to_prune):
- """
- Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
- class PreTrainedModel
- """
- for layer, heads in heads_to_prune.items():
- self.encoder.layer[layer].attention.prune_heads(heads)
-
@add_start_docstrings_to_model_forward(SWIN_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
@@ -1035,9 +987,7 @@ class UnimerSwinModel(UnimerSwinPreTrainedModel):
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = (
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- )
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
@@ -1048,7 +998,17 @@ class UnimerSwinModel(UnimerSwinPreTrainedModel):
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
- head_mask = self.get_head_mask(head_mask, len(self.config.depths))
+ # Transformers 5 已移除通用 get_head_mask,按原有广播规则显式处理。
+ if head_mask is None:
+ head_mask = [None] * len(self.config.depths)
+ else:
+ if head_mask.ndim == 1:
+ head_mask = head_mask[None, None, :, None, None].expand(len(self.config.depths), -1, -1, -1, -1)
+ elif head_mask.ndim == 2:
+ head_mask = head_mask[:, None, :, None, None]
+ elif head_mask.ndim != 5:
+ raise ValueError("head_mask must have 1, 2 or 5 dimensions")
+ head_mask = head_mask.to(dtype=self.dtype)
embedding_output, input_dimensions = self.embeddings(
pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
diff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.py
index d23a9bfc..064208c8 100644
--- a/mineru/model/vlm/runtime.py
+++ b/mineru/model/vlm/runtime.py
@@ -14,7 +14,6 @@ from typing import Any, AsyncIterator, Generator, Iterator, Literal
from loguru import logger
from mineru_vl_utils import MinerUClient
-from packaging import version
from docvortex.foundation.platform import is_mac_os_version_supported
from ..runtime.device import get_device
@@ -125,34 +124,21 @@ class ModelSingleton:
elif backend == "transformers":
try:
- from transformers import (
- AutoProcessor,
- Qwen2VLForConditionalGeneration,
+ from mineru_vl_utils.transformers_loading import (
+ load_transformers_model,
+ load_transformers_processor,
)
- from transformers import __version__ as transformers_version
- except ImportError:
- raise ImportError("Please install transformers to use the transformers backend.")
-
- if version.parse(transformers_version) >= version.parse("4.56.0"):
- dtype_key = "dtype"
- else:
- dtype_key = "torch_dtype"
- device = get_device()
- model = Qwen2VLForConditionalGeneration.from_pretrained(
- model_path,
- device_map={"": device},
- **{dtype_key: "auto"}, # type: ignore
- )
- processor = AutoProcessor.from_pretrained(
- model_path,
- use_fast=True,
- )
+
+ model = load_transformers_model(model_path, device_map={"": get_device()})
+ processor = load_transformers_processor(model_path)
+ except ImportError as exc:
+ raise ImportError("Please install transformers to use the transformers backend.") from exc
if batch_size == 0:
batch_size = set_default_batch_size()
elif backend == "mlx-engine":
- mlx_supported = is_mac_os_version_supported()
+ mlx_supported = is_mac_os_version_supported("14.0")
if not mlx_supported:
- raise EnvironmentError("mlx-engine backend is only supported on macOS 13.5+ with Apple Silicon.")
+ raise EnvironmentError("mlx-engine backend is only supported on macOS 14.0+ with Apple Silicon.")
from mineru_vl_utils.mlx_compat import load_mlx_model
model, processor = load_mlx_model(model_path)
@@ -223,8 +209,7 @@ class ModelSingleton:
vllm_async_llm = AsyncLLM.from_engine_args(AsyncEngineArgs(**kwargs))
elif backend == "lmdeploy-engine":
try:
- from lmdeploy import PytorchEngineConfig, TurbomindEngineConfig
- from lmdeploy.serve.vl_async_engine import VLAsyncEngine
+ from lmdeploy import PytorchEngineConfig, TurbomindEngineConfig, pipeline
except ImportError:
raise ImportError("Please install lmdeploy to use the lmdeploy-engine backend.")
if "cache_max_entry_count" not in kwargs:
@@ -264,10 +249,10 @@ class ModelSingleton:
if os.getenv("TM_LOG_LEVEL") is None:
os.environ["TM_LOG_LEVEL"] = log_level
- lmdeploy_engine = VLAsyncEngine(
+ lmdeploy_engine = pipeline(
model_path,
- backend=lm_backend,
backend_config=backend_config,
+ log_level=log_level,
)
predictor = MinerUClient(
backend=backend,
diff --git a/mineru/model/vlm/selector.py b/mineru/model/vlm/selector.py
index dffbc73f..f1fdf2b1 100644
--- a/mineru/model/vlm/selector.py
+++ b/mineru/model/vlm/selector.py
@@ -82,7 +82,7 @@ def _select_linux_engine(is_async: bool) -> VlmEngine:
def _select_mac_engine() -> VlmEngine:
"""macOS 平台引擎选择"""
try:
- if is_mac_os_version_supported():
+ if is_mac_os_version_supported("14.0"):
import mlx_vlm as _mlx_vlm # type: ignore
del _mlx_vlm
diff --git a/pyproject.toml b/pyproject.toml
index 709ea7fb..bfd670de 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -39,7 +39,7 @@ classifiers = [
]
dependencies = [
"docvortex>=0.2.2,<1.0.0",
- "mineru-vl-utils>=1.2.1,<2",
+ "mineru-vl-utils>=2.0.0,<3",
"metafile-render>=0.3.0,<1.0.0",
"mineru-llama-cpp>=0.1.0,<1",
"click>=8.1.7",
@@ -88,7 +88,7 @@ dependencies = [
"fonttools>=4.0.0,<5",
"shapely>=2.0.7,<3",
"pyclipper>=1.3.0,<2",
- "tokenizers>=0.22.0,<0.23.1",
+ "tokenizers>=0.22.0,<0.24",
]
[project.optional-dependencies]
@@ -106,17 +106,17 @@ torch = [
"six>=1.17.0,<2",
"torch>=2.6.0,<3",
"torchvision",
- "transformers>=4.57.3,<5.0.0",
+ "transformers>=5.10.1,<6",
"accelerate>=1.5.1",
"safetensors>=0.4.0,<1",
]
full = [
"mineru[torch]",
- "vllm>=0.10.1.1,<0.22.0 ; sys_platform == 'linux'",
- "lmdeploy>=0.10.2,<0.12 ; sys_platform == 'win32'",
+ "vllm>=0.21.0,<0.22 ; sys_platform == 'linux'",
+ "lmdeploy>=0.17.0,<0.18 ; sys_platform == 'win32'",
"qwen-vl-utils>=0.0.14,<1 ; sys_platform == 'win32'",
"mlx<=0.31.1 ; sys_platform == 'darwin' and platform_machine == 'arm64'",
- "mlx-vlm>=0.3.3,<0.4 ; sys_platform == 'darwin' and platform_machine == 'arm64'",
+ "mlx-vlm>=0.3.12,<0.4 ; sys_platform == 'darwin' and platform_machine == 'arm64'",
]
gradio = [
"gradio>=5.49.1,!=6.0.0,!=6.0.1,!=6.0.2,!=6.1.0,!=6.2.0,!=6.3.0,!=6.4.0,!=6.5.0,!=6.5.1,!=6.6.0,!=6.7.0,<6.9.0",
diff --git a/scripts/check_transformers5_dependencies.py b/scripts/check_transformers5_dependencies.py
new file mode 100644
index 00000000..a48c5964
--- /dev/null
+++ b/scripts/check_transformers5_dependencies.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python3
+"""从已构建 wheel 验证跨平台依赖可解性,不安装 GPU 引擎或修改目标环境。"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import subprocess
+from pathlib import Path
+
+
+def main() -> None:
+ """在四个 Python 版本和基础/可选安装模式下解析真实发布元数据。"""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--mineru-wheel", type=Path, required=True)
+ parser.add_argument("--utils-wheel", type=Path, required=True)
+ parser.add_argument("--platform", choices=("linux", "windows", "macos"), required=True)
+ parser.add_argument("--transformers", choices=("5.10.1", "5.16.1"), required=True)
+ parser.add_argument("--python", nargs="+", default=["3.10", "3.11", "3.12", "3.13"])
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ platforms = {"linux": "x86_64-manylinux_2_34", "windows": "x86_64-pc-windows-msvc", "macos": "aarch64-apple-darwin"}
+ mineru = args.mineru_wheel.resolve().as_uri()
+ utils = args.utils_wheel.resolve().as_uri()
+ records = []
+ failed = False
+ for python in args.python:
+ for extra in ("", "torch", "full", "all"):
+ requirement = f"mineru[{extra}]" if extra else "mineru"
+ source = f"{requirement} @ {mineru}\nmineru-vl-utils @ {utils}\n"
+ if extra:
+ source += f"transformers=={args.transformers}\n"
+ process = subprocess.run(
+ [
+ "uv",
+ "pip",
+ "compile",
+ "-",
+ "--python-version",
+ python,
+ "--python-platform",
+ platforms[args.platform],
+ "--no-header",
+ "--no-annotate",
+ "--no-progress",
+ ],
+ input=source,
+ text=True,
+ capture_output=True,
+ check=False,
+ env={**os.environ, "MACOSX_DEPLOYMENT_TARGET": "14.0"},
+ )
+ # 基础安装的解析结果也必须保持无 Torch/Transformers 依赖。
+ heavy_in_base = not extra and any(
+ line.startswith(("torch==", "transformers==")) for line in process.stdout.splitlines()
+ )
+ success = process.returncode == 0 and not heavy_in_base
+ failed |= not success
+ records.append(
+ {
+ "python": python,
+ "extra": extra or "base",
+ "success": success,
+ "resolution": process.stdout,
+ "diagnostics": process.stderr,
+ }
+ )
+ print(f"{args.platform} Python {python} {extra or 'base'}: {'PASS' if success else 'FAIL'}", flush=True)
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(
+ json.dumps({"platform": args.platform, "transformers": args.transformers, "results": records}, indent=2) + "\n"
+ )
+ raise SystemExit(1 if failed else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/validate_transformers_migration.py b/scripts/validate_transformers_migration.py
new file mode 100644
index 00000000..c3ed7b2f
--- /dev/null
+++ b/scripts/validate_transformers_migration.py
@@ -0,0 +1,231 @@
+#!/usr/bin/env python3
+"""在指定 checkout 和真实模型上保存 Transformers 迁移的输出、耗时及内存证据。"""
+
+from __future__ import annotations
+
+import argparse
+import importlib.metadata
+import json
+import os
+import statistics
+import sys
+import threading
+import time
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+
+def _arguments() -> argparse.Namespace:
+ """解析只读输入、模型目录和独立结果目录,不改变用户配置。"""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", type=Path, required=True)
+ parser.add_argument("--manifest", type=Path, required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--model-root", type=Path, default=Path.home() / ".mineru/models")
+ parser.add_argument("--kind", choices=("layout", "mfr", "parse", "vlm-transformers", "vlm-mlx"), required=True)
+ parser.add_argument("--device", default="cpu")
+ parser.add_argument("--tier", choices=("basic", "standard"), default="basic")
+ parser.add_argument("--rounds", type=int, default=3)
+ parser.add_argument("--warmup", type=int, default=1)
+ args = parser.parse_args()
+ if args.rounds < 1 or args.warmup < 0:
+ parser.error("rounds must be positive and warmup must be nonnegative")
+ return args
+
+
+def _synchronize(device: str) -> None:
+ """等待设备完成计算,避免把异步提交时间误认为推理耗时。"""
+ import torch
+
+ if device.startswith("cuda"):
+ torch.cuda.synchronize(device)
+ elif device.startswith("mps"):
+ torch.mps.synchronize()
+
+
+def _physical_footprint_reader() -> Callable[[], int] | None:
+ """读取 macOS 统一内存的物理占用,避免 MPS 外部存储改变 RSS/框架计数口径。"""
+ if sys.platform != "darwin":
+ return None
+ import ctypes
+
+ class UsageInfo(ctypes.Structure):
+ """对应系统 sys/resource.h 中稳定的 rusage_info_v0 结构。"""
+
+ _fields_ = [("uuid", ctypes.c_uint8 * 16)] + [
+ (name, ctypes.c_uint64)
+ for name in (
+ "user_time",
+ "system_time",
+ "pkg_idle_wkups",
+ "interrupt_wkups",
+ "pageins",
+ "wired_size",
+ "resident_size",
+ "phys_footprint",
+ "proc_start_abstime",
+ "proc_exit_abstime",
+ )
+ ]
+
+ function = ctypes.CDLL("/usr/lib/libproc.dylib", use_errno=True).proc_pid_rusage
+ function.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p]
+ function.restype = ctypes.c_int
+ pid = os.getpid()
+
+ def read() -> int:
+ """只读取当前进程统计,系统调用失败时使本次测量明确失败。"""
+ info = UsageInfo()
+ if function(pid, 0, ctypes.byref(info)) != 0:
+ raise OSError(ctypes.get_errno(), "proc_pid_rusage failed")
+ return info.phys_footprint
+
+ return read
+
+
+def _measure(operation: Callable[[], Any], device: str, rounds: int, warmup: int) -> tuple[Any, dict[str, Any]]:
+ """预热后测量三轮,并每 20ms 采样进程 RSS 与 Torch 设备占用。"""
+ import psutil
+ import torch
+
+ for _ in range(warmup):
+ operation()
+ _synchronize(device)
+ process = psutil.Process()
+ peaks = {"rss_bytes": 0, "torch_device_bytes": 0}
+ footprint_reader = _physical_footprint_reader()
+ if footprint_reader is not None:
+ peaks["physical_footprint_bytes"] = 0
+ sampling_errors = []
+ stop = threading.Event()
+
+ def sample() -> None:
+ """持续采样同一进程,所有后端使用相同的采样间隔。"""
+ while not stop.is_set():
+ peaks["rss_bytes"] = max(peaks["rss_bytes"], process.memory_info().rss)
+ if footprint_reader is not None:
+ try:
+ peaks["physical_footprint_bytes"] = max(peaks["physical_footprint_bytes"], footprint_reader())
+ except OSError as exc:
+ sampling_errors.append(exc)
+ return
+ allocated = 0
+ if device.startswith("mps"):
+ allocated = torch.mps.current_allocated_memory()
+ elif device.startswith("cuda"):
+ allocated = torch.cuda.memory_allocated(device)
+ peaks["torch_device_bytes"] = max(peaks["torch_device_bytes"], allocated)
+ stop.wait(0.02)
+
+ sampler = threading.Thread(target=sample, daemon=True)
+ sampler.start()
+ durations = []
+ result = None
+ try:
+ for _ in range(rounds):
+ started = time.perf_counter()
+ result = operation()
+ _synchronize(device)
+ durations.append(time.perf_counter() - started)
+ finally:
+ stop.set()
+ sampler.join()
+ if sampling_errors:
+ raise sampling_errors[0]
+ return result, {"seconds": durations, "median_seconds": statistics.median(durations), **peaks}
+
+
+def _operation(args: argparse.Namespace, manifest: dict[str, Any]) -> Callable[[], Any]:
+ """通过实际产品模型和解析器构造测量操作,保留默认生成与分批策略。"""
+ from PIL import Image
+ import torch
+
+ model_root = args.model_root.expanduser()
+ if args.kind in {"vlm-transformers", "vlm-mlx"}:
+ from mineru.model.vlm.runtime import ModelSingleton
+ from mineru_vl_utils.vlm_client.base_client import SamplingParams
+
+ backend = "transformers" if args.kind == "vlm-transformers" else "mlx-engine"
+ predictor = ModelSingleton().get_model(backend, str(model_root / "MinerU2.5-Pro-2605-1.2B"), None, batch_size=2)
+ predictor.client.use_tqdm = False
+ images = [Image.open(item["image"]).convert("RGB") for item in manifest["pages"][:2]]
+ # 组件 smoke 只验证真实模型的协议链路;整页质量另由 parse 场景在原始分辨率验收。
+ for image in images:
+ image.thumbnail((448, 448))
+ return lambda: predictor.client.batch_predict(
+ images, "Read the text in this image.", SamplingParams(max_new_tokens=16, temperature=0)
+ )
+ if args.kind == "layout":
+ from mineru.model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
+
+ model = PPDocLayoutV2LayoutModel(str(model_root / "PDF-Extract-Kit-1.0/models/Layout/PP-DocLayoutV2"), args.device)
+ images = [Image.open(item["image"]).convert("RGB") for item in manifest["pages"]]
+ return lambda: model.batch_predict(images, batch_size=2)
+ if args.kind == "mfr":
+ from mineru.model.mfr.unimernet.Unimernet import UnimernetModel
+
+ model = UnimernetModel(str(model_root / "PDF-Extract-Kit-1.0/models/MFR/unimernet_hf_small_2503"), args.device)
+ images = [Image.open(path).convert("RGB") for path in manifest["formulas"]]
+ if not images:
+ raise ValueError("The manifest must contain at least one formula crop")
+ pixels = torch.stack([model.model.transform(image) for image in images]).to(device=args.device, dtype=model.model.dtype)
+
+ def recognize() -> Any:
+ """使用模型原有 generate 包装,输出 token、原文和修复后的公式文本。"""
+ with torch.inference_mode():
+ return model.model.generate({"image": pixels}, batch_size=len(images))
+
+ return recognize
+
+ from mineru.config import VlmConfig, config
+ from mineru.parser.mineru_parser import MinerUParser
+
+ config.model.stack = "full"
+ config.llm_aided.features.title_leveling = False
+ config.llm_aided.features.cross_page_table_cell_merge = False
+ parser = MinerUParser(tier=args.tier, parse_mode="ocr", vlm_config=VlmConfig())
+
+ def parse() -> list[dict[str, Any]]:
+ """按清单页码解析真实 PDF,保存完整语义树与最终 Markdown。"""
+ results = []
+ for item in manifest["pages"]:
+ result = parser.parse(item["pdf"], page_range=str(item["page"]))
+ results.append({"name": item["name"], "markdown": result.markdown(), "middle": result.to_dict(skip_defaults=False)})
+ return results
+
+ return parse
+
+
+def _json_value(value: Any) -> Any:
+ """将模型返回的 NumPy/Torch 数据转换成可比较的 JSON。"""
+ if hasattr(value, "tolist"):
+ return value.tolist()
+ raise TypeError(f"Unsupported JSON value: {type(value).__name__}")
+
+
+def main() -> None:
+ """保存版本、测量口径和推理结果,便于在两个版本之间复核。"""
+ args = _arguments()
+ sys.path.insert(0, str(args.repo.resolve()))
+ os.environ["MINERU_DEVICE_MODE"] = args.device
+ manifest = json.loads(args.manifest.read_text())
+ operation = _operation(args, manifest)
+ result, metrics = _measure(operation, args.device, args.rounds, args.warmup)
+ versions = {name: importlib.metadata.version(name) for name in ("transformers", "torch", "tokenizers", "docvortex")}
+ report = {
+ "versions": versions,
+ "kind": args.kind,
+ "device": args.device,
+ "sample_interval_ms": 20,
+ "warmup_rounds": args.warmup,
+ "metrics": metrics,
+ "result": result,
+ }
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2, default=_json_value) + "\n")
+ print(json.dumps({"output": str(args.output), **metrics}, ensure_ascii=False), flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.py
index 46922a29..68bfcb51 100644
--- a/tests/unittest/test_doclib_app_startup.py
+++ b/tests/unittest/test_doclib_app_startup.py
@@ -1,7 +1,11 @@
import asyncio
import logging
import subprocess
-import tomllib
+
+try:
+ import tomllib
+except ModuleNotFoundError:
+ import tomli as tomllib
import uuid
from logging.handlers import RotatingFileHandler
from pathlib import Path
@@ -66,11 +70,12 @@ def test_huggingface_hub_base_dependency_enables_xet() -> None:
assert huggingface_hub.extras == {"hf_xet"}
-def test_basic_extra_includes_preflight_runtime_dependencies() -> None:
+def test_torch_extra_includes_preflight_runtime_dependencies(monkeypatch: pytest.MonkeyPatch) -> None:
+ """完整模型栈的预检依赖由 torch extra 提供,不依赖已删除的 basic extra。"""
pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"
pyproject = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
- basic_dependencies = pyproject["project"]["optional-dependencies"]["basic"]
- dependency_names = {dependency.split(">", 1)[0].split("=", 1)[0].lower() for dependency in basic_dependencies}
+ torch_dependencies = pyproject["project"]["optional-dependencies"]["torch"]
+ dependency_names = {Requirement(dependency).name for dependency in torch_dependencies}
module_to_distribution = {
"six": "six",
"torch": "torch",
@@ -78,31 +83,27 @@ def test_basic_extra_includes_preflight_runtime_dependencies() -> None:
"transformers": "transformers",
}
- # light backend 跳过所有模块检查,只验证 full backend 的依赖完整性
- import os
- os.environ["MINERU_MODEL_STACK"] = "full"
- import mineru.config as cfg
- import importlib
- importlib.reload(cfg)
- cfg._loaded_config = cfg._load_effective_config()
- cfg.config = cfg._loaded_config.config
+ monkeypatch.setattr(mineru_config.model, "stack", "full")
missing = [
module_name
for module_name in parser_tier.required_modules_for_tier("basic")
- if module_to_distribution[module_name] not in dependency_names
+ if module_to_distribution.get(module_name, module_name) not in dependency_names
]
assert missing == []
-def test_standard_is_the_highest_model_runtime_extra() -> None:
+def test_full_extra_composes_torch_and_platform_engines() -> None:
+ """full extra 组合 Torch 和平台引擎,普通 test extra 保持独立。"""
pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"
pyproject = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
extras = pyproject["project"]["optional-dependencies"]
assert "advanced" not in extras
- assert "mineru[standard]" in extras["test"]
+ assert "mineru[torch]" in extras["full"]
+ assert {"vllm", "lmdeploy", "mlx-vlm"} <= {Requirement(item).name for item in extras["full"]}
+ assert not any(Requirement(item).name == "mineru" for item in extras["test"])
@pytest.mark.parametrize(
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index e498589e..e6eaacab 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -747,7 +747,7 @@ def test_vlm_server_auto_treats_missing_mlx_as_unavailable(monkeypatch: Any) ->
def _missing_spec(_module_name: str) -> None:
raise ModuleNotFoundError("No module named 'mlx_vlm'")
- monkeypatch.setattr(vlm_server, "is_mac_os_version_supported", lambda: True)
+ monkeypatch.setattr(vlm_server, "is_mac_os_version_supported", lambda min_version: min_version == "14.0")
monkeypatch.setattr(vlm_server.importlib.util, "find_spec", _missing_spec)
assert vlm_server._mlx_server_available() is False
diff --git a/tests/unittest/test_mfr_latex_utils.py b/tests/unittest/test_mfr_latex_utils.py
index 17399a4b..43778094 100644
--- a/tests/unittest/test_mfr_latex_utils.py
+++ b/tests/unittest/test_mfr_latex_utils.py
@@ -2,6 +2,8 @@ from __future__ import annotations
import pytest
import torch
+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
@@ -31,9 +33,7 @@ def test_fix_mathring_font_arguments_repairs_multiple_occurrences() -> None:
"""验证同一公式中的多个未分组 mathring 参数均会修复。"""
source = r"\mathring \mathrm{A} + \mathring\mathrm { B }"
- assert mfr_utils.fix_mathring_font_arguments(source) == (
- r"\mathring{\mathrm{A}} + \mathring{\mathrm { B }}"
- )
+ assert mfr_utils.fix_mathring_font_arguments(source) == (r"\mathring{\mathrm{A}} + \mathring{\mathrm { B }}")
@pytest.mark.parametrize(
@@ -59,7 +59,9 @@ def test_pp_formulanet_fix_latex_uses_shared_mathring_repair() -> None:
"""验证 PP-FormulaNet 的真实 processor 入口应用共享修复。"""
source = r"R , { \mathring \mathrm { A } }"
- assert UniMERNetDecode.fix_latex(None, source) == r"R , { \mathring{\mathrm { A }} }"
+ tokenizer = SimpleNamespace(decode=lambda token_ids, skip_special_tokens: source)
+ processor = SimpleNamespace(tokenizer=tokenizer)
+ assert UniMERNetDecode.token2str(processor, [np.array([0, 7, 2, 1])]) == [r"R , { \mathring{\mathrm { A }} }"]
def test_unimernet_decode_entry_uses_renamed_latex_repair() -> None:
diff --git a/tests/unittest/test_transformers5_models.py b/tests/unittest/test_transformers5_models.py
new file mode 100644
index 00000000..d304b3e0
--- /dev/null
+++ b/tests/unittest/test_transformers5_models.py
@@ -0,0 +1,228 @@
+"""使用真实的小型网络验证 Transformers 5 的缓存、生成和权重加载契约。"""
+# 可选依赖检测必须先于模型模块导入。
+# ruff: noqa: E402
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+torch = pytest.importorskip("torch")
+transformers = pytest.importorskip("transformers", minversion="5.10.1")
+
+from transformers import AutoConfig, PreTrainedTokenizerFast, VisionEncoderDecoderModel
+from transformers.cache_utils import EncoderDecoderCache
+
+from mineru.model.layout.pp_doclayoutv2 import PPDocLayoutV2Config, PPDocLayoutV2ForObjectDetection
+from mineru.model.mfr.unimernet.unimernet_hf import (
+ UnimerMBartConfig,
+ UnimerMBartForCausalLM,
+ UnimernetConfig,
+ UnimernetModel,
+ UnimerSwinConfig,
+)
+
+
+def _decoder(attention: str = "eager", *, tied: bool = False) -> UnimerMBartForCausalLM:
+ """构造保留 Q/K 压缩、交叉注意力与两层缓存的最小解码器。"""
+ config = UnimerMBartConfig(
+ vocab_size=19,
+ d_model=32,
+ qk_squeeze=2,
+ encoder_layers=1,
+ decoder_layers=2,
+ encoder_attention_heads=4,
+ decoder_attention_heads=4,
+ encoder_ffn_dim=64,
+ decoder_ffn_dim=64,
+ max_position_embeddings=64,
+ dropout=0.0,
+ attention_dropout=0.0,
+ activation_dropout=0.0,
+ is_encoder_decoder=False,
+ tie_word_embeddings=tied,
+ )
+ config._attn_implementation = attention
+ torch.manual_seed(17)
+ return UnimerMBartForCausalLM(config).eval()
+
+
[email protected]("attention", ["eager", "sdpa"])
[email protected]("batch_size", [1, 2])
+def test_incremental_cache_matches_full_forward(attention: str, batch_size: int) -> None:
+ """逐 token 生成必须与完整前向一致,交叉注意力只物化一次且 K/V 维度不同。"""
+ model = _decoder(attention)
+ tokens = torch.tensor([[0, 5, 7, 8, 9], [0, 6, 4, 5, 3]])[:batch_size]
+ encoder = torch.randn(batch_size, 6, 32)
+ mask = torch.ones_like(tokens)
+ cross_mask = torch.ones(batch_size, 6, dtype=torch.long)
+ cross_mask[:, -1] = 0
+ cache = None
+ parts = []
+ cross_keys = None
+ with torch.inference_mode():
+ expected = model(
+ tokens, encoder_hidden_states=encoder, encoder_attention_mask=cross_mask, attention_mask=mask, use_cache=False
+ ).logits
+ for index in range(tokens.shape[1]):
+ output = model(
+ tokens[:, index : index + 1],
+ encoder_hidden_states=encoder,
+ encoder_attention_mask=cross_mask,
+ attention_mask=mask[:, : index + 1],
+ past_key_values=cache,
+ use_cache=True,
+ )
+ if cache is not None:
+ assert output.past_key_values is cache
+ cache = output.past_key_values
+ assert isinstance(cache, EncoderDecoderCache)
+ assert cache.get_seq_length() == index + 1
+ keys = cache.cross_attention_cache.layers[0].keys
+ if cross_keys is None:
+ cross_keys = keys
+ assert keys is cross_keys
+ parts.append(output.logits)
+ torch.testing.assert_close(torch.cat(parts, dim=1), expected, rtol=1e-4, atol=1e-5)
+ assert cache.self_attention_cache.layers[0].keys.shape[-1] == 4
+ assert cache.self_attention_cache.layers[0].values.shape[-1] == 8
+
+
[email protected]("attention", ["eager", "sdpa"])
+def test_chunked_prefill_and_reordered_cache(attention: str) -> None:
+ """多 token 前缀和重排后的 batch 必须保留位置偏移及正确的交叉注意力缓存。"""
+ model = _decoder(attention)
+ tokens = torch.tensor([[0, 3, 4, 5, 6], [0, 7, 8, 9, 10]])
+ encoder = torch.randn(2, 4, 32)
+ order = torch.tensor([1, 0])
+ with torch.inference_mode():
+ prefix = model(tokens[:, :3], encoder_hidden_states=encoder, use_cache=True)
+ prefix.past_key_values.reorder_cache(order)
+ suffix = model(
+ tokens[order, 3:], encoder_hidden_states=encoder[order], past_key_values=prefix.past_key_values, use_cache=True
+ )
+ expected = model(tokens[order], encoder_hidden_states=encoder[order], use_cache=False)
+ torch.testing.assert_close(suffix.logits, expected.logits[:, 3:], rtol=1e-4, atol=1e-5)
+
+
[email protected]("attention", ["eager", "sdpa"])
+def test_generate_matches_without_cache_and_stops_at_eos(attention: str) -> None:
+ """实际 GenerationMixin 的批量生成须保持 token 序列一致,并在强制 EOS 处停止。"""
+ model = _decoder(attention)
+ tokens = torch.tensor([[0, 4, 5], [0, 6, 7]])
+ with torch.inference_mode():
+ cached = model.generate(
+ tokens, max_new_tokens=48, do_sample=False, use_cache=True, eos_token_id=None, forced_eos_token_id=2
+ )
+ uncached = model.generate(
+ tokens, max_new_tokens=48, do_sample=False, use_cache=False, eos_token_id=None, forced_eos_token_id=2
+ )
+ assert torch.equal(cached, uncached)
+ assert torch.all(cached[:, -1] == model.config.eos_token_id)
+
+
[email protected]("tied", [False, True])
+def test_decoder_save_reload_preserves_weight_tying(tmp_path: Path, tied: bool) -> None:
+ """新版权重映射不得将原本独立的 lm_head 与词嵌入意外绑定。"""
+ model = _decoder(tied=tied)
+ model.save_pretrained(tmp_path)
+ restored, info = UnimerMBartForCausalLM.from_pretrained(tmp_path, output_loading_info=True)
+ assert not info["missing_keys"] and not info["unexpected_keys"] and not info["mismatched_keys"]
+ assert (restored.lm_head.weight is restored.model.decoder.embed_tokens.weight) is tied
+ with torch.inference_mode():
+ torch.testing.assert_close(model(torch.tensor([[0, 4]])).logits, restored(torch.tensor([[0, 4]])).logits)
+
+
+def test_composite_model_round_trip_without_auto_registration(tmp_path: Path) -> None:
+ """完整组合模型须显式读取子配置、保存权重并恢复生成,且不污染全局 Auto 映射。"""
+ from tokenizers import Tokenizer
+ from tokenizers.models import WordLevel
+
+ vocabulary = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, "x": 4, "+": 5, "1": 6}
+ tokenizer = PreTrainedTokenizerFast(
+ tokenizer_object=Tokenizer(WordLevel(vocabulary, unk_token="<unk>")),
+ bos_token="<s>",
+ eos_token="</s>",
+ pad_token="<pad>",
+ unk_token="<unk>",
+ model_max_length=16,
+ )
+ tokenizer.save_pretrained(tmp_path)
+ encoder = UnimerSwinConfig(
+ image_size=(16, 16),
+ patch_size=2,
+ embed_dim=8,
+ depths=[1, 1],
+ num_heads=[2, 4],
+ window_size=2,
+ use_2d_embeddings=False,
+ path_norm=True,
+ )
+ decoder = UnimerMBartConfig(
+ vocab_size=len(tokenizer),
+ d_model=16,
+ encoder_layers=1,
+ decoder_layers=2,
+ encoder_attention_heads=2,
+ decoder_attention_heads=2,
+ encoder_ffn_dim=32,
+ decoder_ffn_dim=32,
+ max_position_embeddings=16,
+ is_decoder=True,
+ is_encoder_decoder=False,
+ tie_word_embeddings=False,
+ )
+ config = UnimernetConfig(
+ encoder=encoder.to_dict(),
+ decoder=decoder.to_dict(),
+ decoder_start_token_id=0,
+ pad_token_id=1,
+ tie_word_embeddings=False,
+ _name_or_path=str(tmp_path),
+ )
+ model = UnimernetModel(config).eval()
+ model.save_pretrained(tmp_path)
+ restored, info = UnimernetModel.from_pretrained(tmp_path, output_loading_info=True)
+ assert restored.config.model_type == "vision-encoder-decoder"
+ assert isinstance(restored.config.encoder, UnimerSwinConfig)
+ assert isinstance(restored.config.decoder, UnimerMBartConfig)
+ assert not info["missing_keys"] and not info["unexpected_keys"] and not info["mismatched_keys"]
+ with pytest.raises(ValueError):
+ AutoConfig.for_model("unimer-swin")
+ # 既有带 model.model. 前缀的 PyTorch checkpoint 入口也使用显式子配置。
+ torch.save(
+ {"model": {"model.model." + key: value for key, value in model.state_dict().items()}}, tmp_path / "checkpoint.pth"
+ )
+ checkpoint_model = UnimernetModel.from_checkpoint(str(tmp_path), model_filename="checkpoint.pth").eval()
+ pixels = torch.randn(1, 3, 16, 16)
+ with torch.inference_mode():
+ expected = VisionEncoderDecoderModel.generate(model, pixel_values=pixels, max_new_tokens=4)
+ actual = VisionEncoderDecoderModel.generate(restored, pixel_values=pixels, max_new_tokens=4)
+ checkpoint_result = VisionEncoderDecoderModel.generate(checkpoint_model, pixel_values=pixels, max_new_tokens=4)
+ assert torch.equal(actual, expected)
+ assert torch.equal(checkpoint_result, expected)
+
+
+def test_layout_configuration_constructs_the_inference_graph() -> None:
+ """构造真实版面模型图,覆盖仅运行后处理测试无法发现的配置校验错误。"""
+ config = PPDocLayoutV2Config()
+ with torch.device("meta"):
+ model = PPDocLayoutV2ForObjectDetection(config)
+ assert model.config.reading_order_config.hidden_size > 0
+ assert any(True for _ in model.parameters())
+
+
[email protected](not torch.backends.mps.is_available(), reason="requires Apple Silicon MPS")
+def test_layout_position_embedding_preserves_native_math_on_mps() -> None:
+ """MPS 路径仍使用官方位置编码数值,并且没有新增或改名的模型权重。"""
+ from transformers.models.pp_doclayout_v2.modeling_pp_doclayout_v2 import PPDocLayoutV2SinePositionEmbedding
+ from mineru.model.layout.pp_doclayoutv2 import _CpuSinePositionEmbedding
+
+ native = PPDocLayoutV2SinePositionEmbedding(embed_dim=16)
+ adapter = _CpuSinePositionEmbedding(native)
+ actual = adapter(width=3, height=2, device=torch.device("mps"))
+ expected = native(width=3, height=2, device=torch.device("cpu"), dtype=torch.float32)
+ assert actual.device.type == "mps"
+ torch.testing.assert_close(actual.cpu(), expected, rtol=0, atol=0)
+ assert not adapter.state_dict()
diff --git a/tests/unittest/test_transformers5_runtime.py b/tests/unittest/test_transformers5_runtime.py
new file mode 100644
index 00000000..54a04f73
--- /dev/null
+++ b/tests/unittest/test_transformers5_runtime.py
@@ -0,0 +1,76 @@
+"""验证新推理栈的惰性加载边界及 LMDeploy Pipeline 生命周期。"""
+
+from __future__ import annotations
+
+import logging
+import subprocess
+import sys
+from pathlib import Path
+from types import ModuleType, SimpleNamespace
+from typing import Any
+
+import pytest
+
+
+def test_public_imports_keep_optional_model_dependencies_lazy() -> None:
+ """新进程中的公共入口导入不得尝试加载任何可选推理引擎。"""
+ code = """
+import importlib.abc
+import sys
+
+class RejectModelImports(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ # 显式阻止重依赖,检查公共导入是否越过模型加载边界。
+ if fullname.split('.')[0] in {'torch', 'transformers', 'vllm', 'lmdeploy', 'mlx', 'mlx_vlm'}:
+ raise AssertionError('Eager optional dependency: ' + fullname)
+
+sys.meta_path.insert(0, RejectModelImports())
+import mineru
+import mineru.parser
+import mineru.cli.main
+"""
+ process = subprocess.run(
+ [sys.executable, "-c", code], capture_output=True, text=True, cwd=Path(__file__).resolve().parents[2], check=False
+ )
+ assert process.returncode == 0, process.stderr
+
+
+def test_runtime_constructs_caches_and_closes_pipeline(monkeypatch: pytest.MonkeyPatch) -> None:
+ """模型门面须缓存公开 Pipeline 句柄,并通过其 close 方法释放资源。"""
+ from mineru.model.vlm import runtime
+
+ calls: list[dict[str, Any]] = []
+
+ class Pipeline:
+ """记录工厂参数和关闭次数的引擎替身。"""
+
+ def __init__(self, model_path: str, **kwargs: Any) -> None:
+ """捕获设备配置,不触发实际 GPU 分配。"""
+ calls.append({"model_path": model_path, **kwargs})
+ self.closed = 0
+
+ def close(self) -> None:
+ """模拟公开的资源释放接口。"""
+ self.closed += 1
+
+ module = ModuleType("lmdeploy")
+ module.PytorchEngineConfig = SimpleNamespace
+ module.TurbomindEngineConfig = SimpleNamespace
+ module.pipeline = Pipeline
+ utilities = ModuleType("lmdeploy.utils")
+ utilities.get_logger = logging.getLogger
+ monkeypatch.setitem(sys.modules, "lmdeploy", module)
+ monkeypatch.setitem(sys.modules, "lmdeploy.utils", utilities)
+ monkeypatch.setattr(runtime, "MinerUClient", lambda **kwargs: SimpleNamespace(**kwargs))
+ monkeypatch.setattr(runtime.ModelSingleton, "_models", {})
+ singleton = runtime.ModelSingleton()
+ kwargs = {"lmdeploy_backend": "pytorch", "lmdeploy_device": "cuda", "cache_max_entry_count": 0.2}
+ client = singleton.get_model("lmdeploy-engine", "local-model", None, **kwargs)
+ assert singleton.get_model("lmdeploy-engine", "local-model", None, **kwargs) is client
+ assert len(calls) == 1
+ assert calls[0]["backend_config"].device_type == "cuda"
+ assert calls[0]["backend_config"].cache_max_entry_count == 0.2
+ assert calls[0]["log_level"] == "ERROR"
+ handle = client._mineru_runtime_handles["lmdeploy_engine"]
+ runtime._shutdown_runtime_handle(handle)
+ assert handle.closed == 1