Skip to content

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

refactor(mfr): remove retired HF UniMERNet implementation and tests

myhloli70912ee7afb6
diff --git a/mineru/model/mfr/pp_formulanet_plus_m_onnx.py b/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
index 259ab8a2..53d2e5ec 100644
--- a/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
+++ b/mineru/model/mfr/pp_formulanet_plus_m_onnx.py
@@ -1,7 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
"""ONNX 后端的 PP-FormulaNet-Plus-M 推理封装。
-与 ``UnimernetModel``(torch/transformers 后端)公开接口完全一致,
+与 ``FormulaRecognizer``(torch/transformers 后端)公开接口完全一致,
内部用 ONNX Runtime 推理从 MinerU Torch 权重导出的 PP-FormulaNet_plus-M ONNX 模型。
ONNX 模型输出 token IDs(int64),不是 logits——自回归循环已 bake 进计算图,
@@ -35,7 +35,7 @@ _EOS_TOKEN_ID = 2
class PPFormulaNetPlusMONNX:
"""PP-FormulaNet-Plus-M 的 ONNX 推理封装。
- 与 ``UnimernetModel`` 的 ``predict`` / ``batch_predict`` 接口完全一致。
+ 与 ``FormulaRecognizer`` 的 ``predict`` / ``batch_predict`` 接口完全一致。
差异:
- 构造函数接收 onnx 文件路径 + yml 配置路径,而非 HF 模型目录
@@ -78,7 +78,7 @@ class PPFormulaNetPlusMONNX:
)
# ------------------------------------------------------------------
- # bbox 工具(与 UnimernetModel._normalize_bbox 一致)
+ # bbox 工具(与 FormulaRecognizer._normalize_bbox 一致)
# ------------------------------------------------------------------
@staticmethod
def _normalize_bbox(bbox: Any, image: np.ndarray) -> Optional[Tuple[int, int, int, int]]:
@@ -201,7 +201,7 @@ class PPFormulaNetPlusMONNX:
return results
# ------------------------------------------------------------------
- # 公开接口(与 UnimernetModel 一致)
+ # 公开接口(与 FormulaRecognizer 一致)
# ------------------------------------------------------------------
def predict(
self,
diff --git a/mineru/model/mfr/unimernet/Unimernet.py b/mineru/model/mfr/unimernet/Unimernet.py
deleted file mode 100644
index 017dc063..00000000
--- a/mineru/model/mfr/unimernet/Unimernet.py
+++ /dev/null
@@ -1,195 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import math
-
-import torch
-from torch.utils.data import DataLoader, Dataset
-from tqdm import tqdm
-
-from ..utils import build_mfr_batch_groups
-
-
-class MathDataset(Dataset):
- def __init__(self, image_paths, transform=None):
- self.image_paths = image_paths
- self.transform = transform
-
- def __len__(self):
- return len(self.image_paths)
-
- def __getitem__(self, idx):
- raw_image = self.image_paths[idx]
- if self.transform:
- image = self.transform(raw_image)
- return image
-
-
-class UnimernetModel(object):
- def __init__(self, weight_dir: str, _device_: str = "cpu") -> None:
- """按目标精度加载权重;MPS 先在 CPU 物化 FP16,再串行转移,避开并行加载的原生崩溃。"""
- from .unimernet_hf import UnimernetModel
-
- self.device = torch.device(_device_)
- load_device = torch.device("cpu") if self.device.type == "mps" else self.device
- self.model = UnimernetModel.from_pretrained(
- weight_dir,
- device_map={"": load_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,
- )
- if self.device.type == "mps":
- self.model.to(self.device)
- self.model.eval()
-
- @staticmethod
- def _should_pin_memory(device) -> bool:
- """判断 DataLoader 是否需要启用 pinned memory,仅 CUDA 搬运受益。"""
- return str(device).startswith("cuda")
-
- @staticmethod
- def _should_non_blocking_transfer(device) -> bool:
- """判断 tensor 搬运是否使用 non_blocking,需与 pinned memory 保持一致。"""
- return UnimernetModel._should_pin_memory(device)
-
- @staticmethod
- def _normalize_bbox(bbox, image):
- if bbox is None:
- return None
-
- xmin, ymin, xmax, ymax = [float(v) for v in bbox]
- xmin = math.floor(xmin)
- ymin = math.floor(ymin)
- xmax = math.ceil(xmax)
- ymax = math.ceil(ymax)
- height, width = image.shape[:2]
- xmin = max(0, min(width, xmin))
- xmax = max(0, min(width, xmax))
- ymin = max(0, min(height, ymin))
- ymax = max(0, min(height, ymax))
- if xmax <= xmin or ymax <= ymin:
- return None
- return xmin, ymin, xmax, ymax
-
- @staticmethod
- def _item_to_bbox(item, image):
- return UnimernetModel._normalize_bbox(item.get("bbox"), image)
-
- def _build_formula_items(self, mfd_res, image, interline_enable=True):
- formula_list = []
- crop_targets = []
-
- for item in mfd_res or []:
- if not isinstance(item, dict):
- continue
- label = item.get("label")
- if label not in ["inline_formula", "display_formula"]:
- continue
- if not interline_enable and label == "display_formula":
- continue
-
- new_item = dict(item)
- new_item.setdefault("latex", "")
- formula_list.append(new_item)
-
- bbox = self._item_to_bbox(new_item, image)
- if bbox is not None:
- crop_targets.append((new_item, bbox))
-
- return formula_list, crop_targets
-
- def predict(
- self,
- mfd_res,
- image,
- batch_size: int = 64,
- interline_enable: bool = True,
- ) -> list:
- return self.batch_predict(
- [mfd_res],
- [image],
- batch_size=batch_size,
- interline_enable=interline_enable,
- )[0]
-
- def batch_predict(
- self,
- images_mfd_res: list,
- images: list,
- batch_size: int = 64,
- interline_enable: bool = True,
- ) -> list:
- if not images_mfd_res:
- return []
-
- if len(images_mfd_res) != len(images):
- raise ValueError("images_mfd_res and images must have the same length.")
-
- images_formula_list = []
- mf_image_list = []
- backfill_list = []
- image_info = []
-
- for mfd_res, image in zip(images_mfd_res, images):
- formula_list, crop_targets = self._build_formula_items(
- mfd_res,
- image,
- interline_enable=interline_enable,
- )
-
- for formula_item, (xmin, ymin, xmax, ymax) in crop_targets:
- bbox_img = image[ymin:ymax, xmin:xmax]
- area = (xmax - xmin) * (ymax - ymin)
-
- curr_idx = len(mf_image_list)
- image_info.append((area, curr_idx, bbox_img))
- mf_image_list.append(bbox_img)
- backfill_list.append(formula_item)
-
- images_formula_list.append(formula_list)
-
- if not image_info:
- return images_formula_list
-
- image_info.sort(key=lambda x: x[0])
- sorted_areas = [x[0] for x in image_info]
- sorted_indices = [x[1] for x in image_info]
- sorted_images = [x[2] for x in image_info]
- index_mapping = {new_idx: old_idx for new_idx, old_idx in enumerate(sorted_indices)}
-
- batch_groups = build_mfr_batch_groups(sorted_areas, batch_size)
- dataset = MathDataset(sorted_images, transform=self.model.transform)
- pin_memory = self._should_pin_memory(self.device)
- non_blocking = self._should_non_blocking_transfer(self.device)
- dataloader = DataLoader(
- dataset,
- batch_sampler=batch_groups,
- num_workers=0,
- pin_memory=pin_memory,
- )
-
- mfr_res = []
- with tqdm(total=len(sorted_images), desc="MFR Predict") as pbar:
- with torch.inference_mode():
- for batch_group, mf_img in zip(batch_groups, dataloader):
- current_batch_size = len(batch_group)
- mf_img = mf_img.to(
- device=self.device,
- dtype=self.model.dtype,
- non_blocking=non_blocking,
- )
- output = self.model.generate(
- {"image": mf_img},
- batch_size=current_batch_size,
- return_full_result=False,
- )
- mfr_res.extend(output["fixed_str"])
- pbar.update(current_batch_size)
-
- unsorted_results = [""] * len(mfr_res)
- for new_idx, latex in enumerate(mfr_res):
- original_idx = index_mapping[new_idx]
- unsorted_results[original_idx] = latex
-
- for res, latex in zip(backfill_list, unsorted_results):
- res["latex"] = latex
-
- return images_formula_list
diff --git a/mineru/model/mfr/unimernet/__init__.py b/mineru/model/mfr/unimernet/__init__.py
deleted file mode 100644
index 818730ae..00000000
--- a/mineru/model/mfr/unimernet/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-__all__: list[str] = []
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/__init__.py b/mineru/model/mfr/unimernet/unimernet_hf/__init__.py
deleted file mode 100644
index dd75d495..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/__init__.py
+++ /dev/null
@@ -1,16 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-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",
- "UnimerSwinModel",
- "UnimerSwinImageProcessor",
- "UnimerMBartConfig",
- "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
deleted file mode 100644
index 3aad7664..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/configuration_unimernet.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# 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
deleted file mode 100644
index 353e3c02..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/modeling_unimernet.py
+++ /dev/null
@@ -1,195 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-import os
-import warnings
-from typing import Optional
-
-import torch
-from ftfy import fix_text
-
-from transformers import AutoTokenizer, PretrainedConfig, PreTrainedModel, VisionEncoderDecoderModel
-
-from .unimer_swin import UnimerSwinModel, UnimerSwinImageProcessor
-from .unimer_mbart import UnimerMBartForCausalLM
-from .configuration_unimernet import UnimernetConfig
-from ...utils import fix_unimernet_latex
-
-
-# TODO: rewrite tokenizer
-class TokenizerWrapper:
- def __init__(self, tokenizer):
- self.tokenizer = tokenizer
- self.pad_token_id = self.tokenizer.pad_token_id
- self.bos_token_id = self.tokenizer.bos_token_id
- self.eos_token_id = self.tokenizer.eos_token_id
-
- def __len__(self):
- return len(self.tokenizer)
-
- def tokenize(self, text, **kwargs):
- return self.tokenizer(
- text,
- return_token_type_ids=False,
- return_tensors="pt",
- padding="longest",
- truncation=True,
- **kwargs,
- )
-
- def token2str(self, tokens) -> list:
- generated_text = self.tokenizer.batch_decode(tokens, skip_special_tokens=True)
- generated_text = [fix_text(text) for text in generated_text]
- return generated_text
-
- def detokenize(self, tokens):
- toks = [self.tokenizer.convert_ids_to_tokens(tok) for tok in tokens]
- 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()
- 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,
- ):
- 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, 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}."
- )
- tokenizer.tokenizer.model_max_length = self.config.decoder.max_position_embeddings
-
- assert self.config.decoder.vocab_size == len(tokenizer)
- assert self.config.decoder_start_token_id == tokenizer.bos_token_id
- 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 = UnimernetConfig.from_pretrained(model_path)
- config._name_or_path = model_path
-
- encoder = UnimerSwinModel(config.encoder)
- decoder = UnimerMBartForCausalLM(config.decoder)
- model = cls(config, encoder, decoder)
-
- # load model weights
- model_file_path = os.path.join(model_path, model_filename)
- checkpoint = torch.load(model_file_path, map_location="cpu", weights_only=True)
- state_dict = checkpoint["model"] if "model" in checkpoint else checkpoint
- if not state_dict:
- 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
- for k, v in state_dict.items()
- }
- missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
- if len(unexpected_keys) > 0:
- warnings.warn("Unexpected key(s) in state_dict: {}.".format(", ".join(f'"{k}"' for k in unexpected_keys)))
- if len(missing_keys) > 0:
- raise RuntimeError("Missing key(s) in state_dict: {}.".format(", ".join(f'"{k}"' for k in missing_keys)))
- return model
-
- def forward_bak(self, samples):
- pixel_values, text = samples["image"], samples["text_input"]
-
- text_inputs = self.tokenizer.tokenize(text).to(pixel_values.device)
- decoder_input_ids, decoder_attention_mask = text_inputs["input_ids"], text_inputs["attention_mask"]
-
- num_channels = pixel_values.shape[1]
- if num_channels == 1:
- pixel_values = pixel_values.repeat(1, 3, 1, 1)
-
- labels = decoder_input_ids * 1
- labels = labels.masked_fill(labels == self.tokenizer.pad_token_id, -100)
-
- loss = self.model(
- pixel_values=pixel_values,
- decoder_input_ids=decoder_input_ids[:, :-1],
- decoder_attention_mask=decoder_attention_mask[:, :-1],
- labels=labels[:, 1:],
- ).loss
- return {"loss": loss}
-
- def _decode_generate_outputs(self, outputs, return_full_result: bool = True):
- """统一解码生成结果,轻量路径只保留调用方实际消费的公式文本。"""
- token_ids = outputs[:, 1:].cpu()
- result_tokens = token_ids.numpy() if return_full_result else token_ids
- pred_str = self.tokenizer.token2str(result_tokens)
- fixed_str = [fix_unimernet_latex(s) for s in pred_str]
-
- if not return_full_result:
- return {"fixed_str": fixed_str}
-
- return {
- "pred_ids": result_tokens,
- "pred_tokens": self.tokenizer.detokenize(result_tokens),
- "pred_str": pred_str,
- "fixed_str": fixed_str,
- }
-
- def generate(
- self,
- samples,
- do_sample: bool = False,
- temperature: float = 0.2,
- top_p: float = 0.95,
- batch_size=64,
- return_full_result: bool = True,
- ):
- pixel_values = samples["image"]
- 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
- kwargs["top_p"] = top_p
-
- if self.tokenizer.tokenizer.model_max_length > 1152:
- if batch_size <= 32:
- self.tokenizer.tokenizer.model_max_length = 1152 # 6g
- else:
- self.tokenizer.tokenizer.model_max_length = 1344 # 8g
-
- outputs = super().generate(
- pixel_values=pixel_values,
- 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,
- )
-
- return self._decode_generate_outputs(
- outputs,
- return_full_result=return_full_result,
- )
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/__init__.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/__init__.py
deleted file mode 100644
index f62e8e0e..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from .configuration_unimer_mbart import UnimerMBartConfig
-from .modeling_unimer_mbart import UnimerMBartModel, UnimerMBartForCausalLM
-
-__all__ = [
- "UnimerMBartConfig",
- "UnimerMBartModel",
- "UnimerMBartForCausalLM",
-]
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
deleted file mode 100644
index a7c7d96c..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/configuration_unimer_mbart.py
+++ /dev/null
@@ -1,167 +0,0 @@
-# coding=utf-8
-# Copyright 2021, The Facebook AI Research Team and The HuggingFace Inc. team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""UnimerMBART model configuration"""
-
-from transformers.configuration_utils import PretrainedConfig
-from transformers.utils import logging
-
-
-logger = logging.get_logger(__name__)
-
-
-class UnimerMBartConfig(PretrainedConfig):
- r"""
- This is the configuration class to store the configuration of a [`MBartModel`]. It is used to instantiate an MBART
- model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
- defaults will yield a similar configuration to that of the MBART
- [facebook/mbart-large-cc25](https://huggingface.co/facebook/mbart-large-cc25) architecture.
-
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
- documentation from [`PretrainedConfig`] for more information.
-
-
- Args:
- vocab_size (`int`, *optional*, defaults to 50265):
- Vocabulary size of the MBART model. Defines the number of different tokens that can be represented by the
- `inputs_ids` passed when calling [`MBartModel`] or [`TFMBartModel`].
- d_model (`int`, *optional*, defaults to 1024):
- Dimensionality of the layers and the pooler layer.
- qk_squeeze (`int`, *optional*, defaults to 2):
- Squeeze ratio for query/key's output dimension. See the [UniMERNet paper](https://arxiv.org/abs/2404.15254).
- Squeeze Attention maps the query and key to a lower-dimensional space without excessive loss of information,
- thereby accelerating the computation of attention.
- encoder_layers (`int`, *optional*, defaults to 12):
- Number of encoder layers.
- decoder_layers (`int`, *optional*, defaults to 12):
- Number of decoder layers.
- encoder_attention_heads (`int`, *optional*, defaults to 16):
- Number of attention heads for each attention layer in the Transformer encoder.
- decoder_attention_heads (`int`, *optional*, defaults to 16):
- Number of attention heads for each attention layer in the Transformer decoder.
- decoder_ffn_dim (`int`, *optional*, defaults to 4096):
- Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
- encoder_ffn_dim (`int`, *optional*, defaults to 4096):
- Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
- activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
- The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
- `"relu"`, `"silu"` and `"gelu_new"` are supported.
- dropout (`float`, *optional*, defaults to 0.1):
- The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
- attention_dropout (`float`, *optional*, defaults to 0.0):
- The dropout ratio for the attention probabilities.
- activation_dropout (`float`, *optional*, defaults to 0.0):
- The dropout ratio for activations inside the fully connected layer.
- classifier_dropout (`float`, *optional*, defaults to 0.0):
- The dropout ratio for classifier.
- max_position_embeddings (`int`, *optional*, defaults to 1024):
- The maximum sequence length that this model might ever be used with. Typically set this to something large
- just in case (e.g., 512 or 1024 or 2048).
- init_std (`float`, *optional*, defaults to 0.02):
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
- encoder_layerdrop (`float`, *optional*, defaults to 0.0):
- The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
- for more details.
- decoder_layerdrop (`float`, *optional*, defaults to 0.0):
- The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
- for more details.
- scale_embedding (`bool`, *optional*, defaults to `False`):
- Scale embeddings by diving by sqrt(d_model).
- use_cache (`bool`, *optional*, defaults to `True`):
- Whether or not the model should return the last key/values attentions (not used by all models)
- forced_eos_token_id (`int`, *optional*, defaults to 2):
- The id of the token to force as the last generated token when `max_length` is reached. Usually set to
- `eos_token_id`.
-
- Example:
-
- ```python
- >>> from transformers import MBartConfig, MBartModel
-
- >>> # Initializing a MBART facebook/mbart-large-cc25 style configuration
- >>> configuration = MBartConfig()
-
- >>> # Initializing a model (with random weights) from the facebook/mbart-large-cc25 style configuration
- >>> model = MBartModel(configuration)
-
- >>> # Accessing the model configuration
- >>> configuration = model.config
- ```"""
-
- model_type = "unimer-mbart"
- keys_to_ignore_at_inference = ["past_key_values"]
- attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
-
- def __init__(
- self,
- vocab_size=50265,
- max_position_embeddings=1024,
- encoder_layers=12,
- encoder_ffn_dim=4096,
- encoder_attention_heads=16,
- decoder_layers=12,
- decoder_ffn_dim=4096,
- decoder_attention_heads=16,
- encoder_layerdrop=0.0,
- decoder_layerdrop=0.0,
- use_cache=True,
- is_encoder_decoder=True,
- is_decoder=False,
- activation_function="gelu",
- d_model=1024,
- qk_squeeze=2,
- dropout=0.1,
- attention_dropout=0.0,
- activation_dropout=0.0,
- init_std=0.02,
- classifier_dropout=0.0,
- scale_embedding=False,
- pad_token_id=1,
- bos_token_id=0,
- eos_token_id=2,
- forced_eos_token_id=2,
- **kwargs,
- ):
- self.vocab_size = vocab_size
- self.max_position_embeddings = max_position_embeddings
- self.d_model = d_model
- self.qk_squeeze = qk_squeeze
- self.encoder_ffn_dim = encoder_ffn_dim
- self.encoder_layers = encoder_layers
- self.encoder_attention_heads = encoder_attention_heads
- self.decoder_ffn_dim = decoder_ffn_dim
- self.decoder_layers = decoder_layers
- self.decoder_attention_heads = decoder_attention_heads
- self.dropout = dropout
- self.attention_dropout = attention_dropout
- self.activation_dropout = activation_dropout
- self.activation_function = activation_function
- self.init_std = init_std
- self.encoder_layerdrop = encoder_layerdrop
- self.decoder_layerdrop = decoder_layerdrop
- self.classifier_dropout = classifier_dropout
- self.use_cache = use_cache
- self.num_hidden_layers = encoder_layers
- self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
- super().__init__(
- pad_token_id=pad_token_id,
- 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
deleted file mode 100644
index ced72b88..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/modeling_unimer_mbart.py
+++ /dev/null
@@ -1,2142 +0,0 @@
-# coding=utf-8
-# Copyright 2021, The Facebook AI Research Team and The HuggingFace Inc. team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""PyTorch UnimerMBART model."""
-
-import copy
-import math
-from dataclasses import dataclass
-from typing import List, Optional, Tuple, Union
-
-import torch
-import torch.nn.functional as F
-import torch.utils.checkpoint
-from torch import nn
-from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
-
-from transformers.activations import ACT2FN
-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,
- CausalLMOutputWithCrossAttentions,
- Seq2SeqLMOutput,
- Seq2SeqModelOutput,
- Seq2SeqQuestionAnsweringModelOutput,
- Seq2SeqSequenceClassifierOutput,
-)
-from transformers import GenerationMixin, PreTrainedModel
-from transformers.utils import (
- add_code_sample_docstrings,
- add_end_docstrings,
- add_start_docstrings,
- add_start_docstrings_to_model_forward,
- is_flash_attn_2_available,
- is_flash_attn_greater_or_equal_2_10,
- logging,
- replace_return_docstrings,
-)
-from .configuration_unimer_mbart import UnimerMBartConfig
-
-
-if is_flash_attn_2_available():
- from flash_attn import flash_attn_func, flash_attn_varlen_func
- from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
-
-
-logger = logging.get_logger(__name__)
-
-_CHECKPOINT_FOR_DOC = "facebook/mbart-large-cc25"
-_CONFIG_FOR_DOC = "MBartConfig"
-
-# Base model docstring
-_EXPECTED_OUTPUT_SHAPE = [1, 8, 1024]
-
-
-# Copied from transformers.models.llama.modeling_llama._get_unpad_data
-def _get_unpad_data(attention_mask):
- seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
- indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
- max_seqlen_in_batch = seqlens_in_batch.max().item()
- cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
- return (
- indices,
- cu_seqlens,
- max_seqlen_in_batch,
- )
-
-
-def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int):
- """
- Shift input ids one token to the right, and wrap the last non pad token (the <LID> token) Note that MBart does not
- have a single `decoder_start_token_id` in contrast to other Bart-like models.
- """
- prev_output_tokens = input_ids.clone()
-
- if pad_token_id is None:
- raise ValueError("self.model.config.pad_token_id has to be defined.")
- # replace possible -100 values in labels by `pad_token_id`
- prev_output_tokens.masked_fill_(prev_output_tokens == -100, pad_token_id)
-
- index_of_eos = (prev_output_tokens.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1)
- decoder_start_tokens = prev_output_tokens.gather(1, index_of_eos).squeeze()
- prev_output_tokens[:, 1:] = prev_output_tokens[:, :-1].clone()
- prev_output_tokens[:, 0] = decoder_start_tokens
-
- return prev_output_tokens
-
-
-@dataclass
-class CausalLMOutputWithCrossAttentionsAndCounting(CausalLMOutputWithCrossAttentions):
- """
- Base class for causal language model (or autoregressive) outputs.
-
- Args:
- loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
- Language modeling loss (for next-token prediction).
- logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
- one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
-
- Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
- attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
- sequence_length)`.
-
- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
- heads.
- cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
- sequence_length)`.
-
- Cross attentions weights after the attention softmax, used to compute the weighted average in the
- cross-attention heads.
- past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- Tuple of `torch.FloatTensor` tuples of length `config.n_layers`, with each tuple containing the cached key,
- value states of the self-attention and the cross-attention layers if model is used in encoder-decoder
- setting. Only relevant if `config.is_decoder = True`.
-
- Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
- `past_key_values` input) to speed up sequential decoding.
- counting:
- Counting
- """
-
- counting: Optional[torch.FloatTensor] = None
-
-
-# Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->MBart
-class UnimerMBartLearnedPositionalEmbedding(nn.Embedding):
- """
- This module learns positional embeddings up to a fixed maximum size.
- """
-
- def __init__(self, num_embeddings: int, embedding_dim: int):
- # MBart is set up so that if padding_idx is specified then offset the embedding ids by 2
- # and adjust num_embeddings appropriately. Other models don't have this hack
- self.offset = 2
- super().__init__(num_embeddings + self.offset, embedding_dim)
-
- def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
- """`input_ids' shape is expected to be [bsz x seqlen]."""
-
- bsz, seq_len = input_ids.shape[:2]
- positions = torch.arange(
- past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
- ).expand(bsz, -1)
-
- return super().forward(positions + self.offset)
-
-
-# Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->MBart
-class UnimerMBartScaledWordEmbedding(nn.Embedding):
- """
- This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
- """
-
- def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
- super().__init__(num_embeddings, embedding_dim, padding_idx)
- self.embed_scale = embed_scale
-
- def forward(self, input_ids: torch.Tensor):
- return super().forward(input_ids) * self.embed_scale
-
-
-# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->MBart
-class UnimerMBartAttention(nn.Module):
- """Multi-headed attention from 'Attention Is All You Need' paper, with qk_squeeze"""
-
- def __init__(
- self,
- embed_dim: int,
- num_heads: int,
- dropout: float = 0.0,
- is_decoder: bool = False,
- bias: bool = True,
- is_causal: bool = False,
- layer_idx: Optional[int] = None,
- *,
- config: UnimerMBartConfig,
- ):
- super().__init__()
- self.embed_dim = embed_dim
- self.num_heads = num_heads
- self.dropout = dropout
- self.head_dim = embed_dim // num_heads
- self.config = config
-
- 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} 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)
- self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
- self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
-
- def _shape_qk(self, tensor: torch.Tensor, seq_len: int, bsz: int):
- return tensor.view(bsz, seq_len, self.num_heads, self.squeeze_head_dim).transpose(1, 2).contiguous()
-
- 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[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[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
-
- bsz, tgt_len, _ = hidden_states.size()
-
- # get query proj
- query_states = self.q_proj(hidden_states) * self.scaling
- 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)
- query_states = self._shape_qk(query_states, tgt_len, bsz).view(*proj_shape)
- key_states = key_states.reshape(*proj_shape)
- value_states = value_states.reshape(*value_shape)
-
- src_len = key_states.size(1)
- attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
-
- 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 {attn_weights.size()}"
- )
-
- if attention_mask is not None:
- if attention_mask.size() != (bsz, 1, tgt_len, src_len):
- raise ValueError(
- f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
- )
- attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
- attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
-
- attn_weights = nn.functional.softmax(attn_weights, dim=-1)
-
- 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 {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)
-
- if output_attentions:
- # this operation is a bit awkward, but it's required to
- # make sure that attn_weights keeps its gradient.
- # In order to do so, attn_weights have to be reshaped
- # twice and have to be reused in the following
- attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
- attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
- else:
- attn_weights_reshaped = None
-
- attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
- attn_output = torch.bmm(attn_probs, value_states)
-
- 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 {attn_output.size()}"
- )
-
- attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
- attn_output = attn_output.transpose(1, 2)
-
- # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
- # partitioned across GPUs when using tensor-parallelism.
- attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
-
- attn_output = self.out_proj(attn_output)
-
- return attn_output, attn_weights_reshaped, past_key_value
-
-
-# Copied from transformers.models.bart.modeling_bart.BartFlashAttention2 with Bart->MBart
-class UnimerMBartFlashAttention2(UnimerMBartAttention):
- """
- MBart flash attention module. This module inherits from `MBartSqueezeAttention` as the weights of the module stays
- untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
- flash attention and deal with padding tokens in case the input contains any of them.
- """
-
- # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
-
- # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
- # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
- # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
- self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
-
- # def _reshape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
- # return tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
-
- def _shape_qk(self, tensor: torch.Tensor, seq_len: int, bsz: int):
- return tensor.view(bsz, seq_len, self.num_heads, self.squeeze_head_dim)
-
- def _shape_v(self, tensor: torch.Tensor, seq_len: int, bsz: int):
- return tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- key_value_states: Optional[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[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
-
- bsz, q_len, _ = hidden_states.size()
-
- # get query proj
- query_states = self._shape_qk(self.q_proj(hidden_states), -1, bsz)
-
- 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
- # cast them back in the correct dtype just to be sure everything works as expected.
- # This might slowdown training & inference so it is recommended to not cast the LayerNorms
- # in fp32. (LlamaRMSNorm handles it correctly)
-
- input_dtype = query_states.dtype
- if input_dtype == torch.float32:
- if torch.is_autocast_enabled():
- target_dtype = torch.get_autocast_gpu_dtype()
- # Handle the case where the model is quantized
- elif hasattr(self.config, "_pre_quantization_dtype"):
- target_dtype = self.config._pre_quantization_dtype
- else:
- target_dtype = self.q_proj.weight.dtype
-
- logger.warning_once(
- f"The input hidden states seems to be silently casted in float32, this might be related to"
- f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
- f" {target_dtype}."
- )
-
- query_states = query_states.to(target_dtype)
- key_states = key_states.to(target_dtype)
- value_states = value_states.to(target_dtype)
-
- attn_output = self._flash_attention_forward(
- query_states, key_states, value_states, attention_mask, q_len, dropout=self.dropout
- )
-
- attn_output = attn_output.reshape(bsz, q_len, -1)
- attn_output = self.out_proj(attn_output)
-
- if not output_attentions:
- attn_weights = None
-
- return attn_output, attn_weights, past_key_value
-
- # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
- def _flash_attention_forward(
- self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
- ):
- """
- Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
- first unpad the input, then computes the attention scores and pad the final attention scores.
-
- Args:
- query_states (`torch.Tensor`):
- Input query states to be passed to Flash Attention API
- key_states (`torch.Tensor`):
- Input key states to be passed to Flash Attention API
- value_states (`torch.Tensor`):
- Input value states to be passed to Flash Attention API
- attention_mask (`torch.Tensor`):
- The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
- position of padding tokens and 1 for the position of non-padding tokens.
- dropout (`float`):
- Attention dropout
- softmax_scale (`float`, *optional*):
- The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
- """
- if not self._flash_attn_uses_top_left_mask:
- causal = self.is_causal
- else:
- # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
- causal = self.is_causal and query_length != 1
-
- # Contains at least one padding token in the sequence
- if attention_mask is not None:
- batch_size = query_states.shape[0]
-
- query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
- query_states, key_states, value_states, attention_mask, query_length
- )
-
- cu_seqlens_q, cu_seqlens_k = cu_seq_lens
- max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
-
- attn_output_unpad = flash_attn_varlen_func(
- query_states,
- key_states,
- value_states,
- cu_seqlens_q=cu_seqlens_q,
- cu_seqlens_k=cu_seqlens_k,
- max_seqlen_q=max_seqlen_in_batch_q,
- max_seqlen_k=max_seqlen_in_batch_k,
- dropout_p=dropout,
- softmax_scale=softmax_scale,
- causal=causal,
- )
-
- attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
- else:
- attn_output = flash_attn_func(
- query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
- )
-
- return attn_output
-
- # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
- def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
- 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)
- 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)
- cu_seqlens_q = cu_seqlens_k
- max_seqlen_in_batch_q = max_seqlen_in_batch_k
- indices_q = indices_k
- elif query_length == 1:
- max_seqlen_in_batch_q = 1
- cu_seqlens_q = torch.arange(
- batch_size + 1, dtype=torch.int32, device=query_layer.device
- ) # There is a memcpy here, that is very bad.
- indices_q = cu_seqlens_q[:-1]
- query_layer = query_layer.squeeze(1)
- else:
- # The -q_len: slice assumes left padding.
- attention_mask = attention_mask[:, -query_length:]
- query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
-
- return (
- query_layer,
- key_layer,
- value_layer,
- indices_q,
- (cu_seqlens_q, cu_seqlens_k),
- (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[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[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.
- logger.warning(
- "BartModel is using BartSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention"
- ' implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
- )
- return super().forward(
- hidden_states,
- key_value_states=key_value_states,
- past_key_value=past_key_value,
- attention_mask=attention_mask,
- layer_head_mask=layer_head_mask,
- output_attentions=output_attentions,
- )
-
- # if key_value_states are provided this layer is used as a cross-attention layer
- # for the decoder
-
- bsz, tgt_len, _ = hidden_states.size()
-
- # get query proj
- query_states = self.q_proj(hidden_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)
-
- # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
- # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
- # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1.
- is_causal = True if self.is_causal and attention_mask is None and tgt_len > 1 else False
-
- # NOTE: SDPA with memory-efficient backend is currently (torch==2.1.2) bugged when using non-contiguous inputs and a custom attn_mask,
- # but we are fine here as `_shape` do call `.contiguous()`. Reference: https://github.com/pytorch/pytorch/issues/112577
- attn_output = torch.nn.functional.scaled_dot_product_attention(
- query_states,
- key_states,
- value_states,
- attn_mask=attention_mask,
- dropout_p=self.dropout if self.training else 0.0,
- is_causal=is_causal,
- )
-
- 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 {attn_output.size()}"
- )
-
- attn_output = attn_output.transpose(1, 2)
-
- # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
- # partitioned across GPUs when using tensor-parallelism.
- attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
-
- attn_output = self.out_proj(attn_output)
-
- return attn_output, None, past_key_value
-
-
-UNIMER_MBART_ATTENTION_CLASSES = {
- "eager": UnimerMBartAttention,
- "flash_attention_2": UnimerMBartFlashAttention2,
- "sdpa": UnimerMBartSdpaAttention,
-}
-
-
-class UnimerMBartEncoderLayer(nn.Module):
- def __init__(self, config: UnimerMBartConfig):
- super().__init__()
- self.embed_dim = config.d_model
-
- self.self_attn = UNIMER_MBART_ATTENTION_CLASSES[config._attn_implementation](
- embed_dim=self.embed_dim,
- num_heads=config.encoder_attention_heads,
- dropout=config.attention_dropout,
- config=config,
- )
- self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
- self.dropout = config.dropout
- self.activation_fn = ACT2FN[config.activation_function]
- self.activation_dropout = config.activation_dropout
- self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
- self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
- self.final_layer_norm = nn.LayerNorm(self.embed_dim)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: torch.Tensor,
- layer_head_mask: torch.Tensor,
- output_attentions: bool = False,
- ) -> torch.Tensor:
- """
- Args:
- hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
- attention_mask (`torch.FloatTensor`): attention mask of size
- `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
- layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
- `(encoder_attention_heads,)`.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- """
- residual = hidden_states
- hidden_states = self.self_attn_layer_norm(hidden_states)
- hidden_states, attn_weights, _ = self.self_attn(
- hidden_states=hidden_states,
- attention_mask=attention_mask,
- layer_head_mask=layer_head_mask,
- output_attentions=output_attentions,
- )
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
-
- residual = hidden_states
- hidden_states = self.final_layer_norm(hidden_states)
- hidden_states = self.activation_fn(self.fc1(hidden_states))
- hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
- hidden_states = self.fc2(hidden_states)
- 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()):
- clamp_value = torch.finfo(hidden_states.dtype).max - 1000
- hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
-
- outputs = (hidden_states,)
-
- if output_attentions:
- outputs += (attn_weights,)
-
- return outputs
-
-
-class UnimerMBartDecoderLayer(nn.Module):
- def __init__(self, config: UnimerMBartConfig, layer_idx: int):
- super().__init__()
- self.embed_dim = config.d_model
-
- self.self_attn = UNIMER_MBART_ATTENTION_CLASSES[config._attn_implementation](
- embed_dim=self.embed_dim,
- num_heads=config.decoder_attention_heads,
- dropout=config.attention_dropout,
- is_decoder=True,
- is_causal=True,
- config=config,
- layer_idx=layer_idx,
- )
- self.dropout = config.dropout
- self.activation_fn = ACT2FN[config.activation_function]
- self.activation_dropout = config.activation_dropout
-
- self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
- self.encoder_attn = UNIMER_MBART_ATTENTION_CLASSES[config._attn_implementation](
- self.embed_dim,
- config.decoder_attention_heads,
- 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)
- self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
- self.final_layer_norm = nn.LayerNorm(self.embed_dim)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: Optional[torch.Tensor] = None,
- encoder_hidden_states: Optional[torch.Tensor] = None,
- 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[Cache] = None,
- output_attentions: Optional[bool] = False,
- use_cache: Optional[bool] = True,
- ) -> torch.Tensor:
- """
- Args:
- hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
- attention_mask (`torch.FloatTensor`): attention mask of size
- `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
- encoder_hidden_states (`torch.FloatTensor`):
- cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
- encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
- `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
- layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
- `(encoder_attention_heads,)`.
- cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
- size `(decoder_attention_heads,)`.
- past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- """
- residual = hidden_states
- hidden_states = self.self_attn_layer_norm(hidden_states)
-
- # Self Attention
- # 自注意力和交叉注意力共享同一个 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,
- attention_mask=attention_mask,
- layer_head_mask=layer_head_mask,
- output_attentions=output_attentions,
- )
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
-
- # Cross-Attention Block
- cross_attn_present_key_value = None
- cross_attn_weights = None
- if encoder_hidden_states is not None:
- residual = hidden_states
- hidden_states = self.encoder_attn_layer_norm(hidden_states)
-
- 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,
- attention_mask=encoder_attention_mask,
- layer_head_mask=cross_attn_layer_head_mask,
- past_key_value=cross_attn_past_key_value,
- output_attentions=output_attentions,
- )
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
-
- # Cache 已由注意力层原地更新。
- present_key_value = past_key_value
-
- # Fully Connected
- residual = hidden_states
- hidden_states = self.final_layer_norm(hidden_states)
- hidden_states = self.activation_fn(self.fc1(hidden_states))
- hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
- hidden_states = self.fc2(hidden_states)
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
-
- outputs = (hidden_states,)
-
- if output_attentions:
- outputs += (self_attn_weights, cross_attn_weights)
-
- if use_cache:
- outputs += (present_key_value,)
-
- return outputs
-
-
-# Copied from transformers.models.bart.modeling_bart.BartClassificationHead with Bart->MBart
-class UnimerMBartClassificationHead(nn.Module):
- """Head for sentence-level classification tasks."""
-
- def __init__(
- self,
- input_dim: int,
- inner_dim: int,
- num_classes: int,
- pooler_dropout: float,
- ):
- super().__init__()
- self.dense = nn.Linear(input_dim, inner_dim)
- self.dropout = nn.Dropout(p=pooler_dropout)
- self.out_proj = nn.Linear(inner_dim, num_classes)
-
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
- hidden_states = self.dropout(hidden_states)
- hidden_states = self.dense(hidden_states)
- hidden_states = torch.tanh(hidden_states)
- hidden_states = self.dropout(hidden_states)
- hidden_states = self.out_proj(hidden_states)
- return hidden_states
-
-
-class UnimerMBartPreTrainedModel(PreTrainedModel):
- config_class = UnimerMBartConfig
- base_model_prefix = "model"
- supports_gradient_checkpointing = True
- _no_split_modules = ["UnimerMBartDecoderLayer", "UnimerMBartEncoderLayer"]
- _supports_flash_attn = True
- _supports_sdpa = True
-
- @torch.no_grad()
- def _init_weights(self, module: nn.Module) -> None:
- """只初始化尚未加载的参数,避免 Transformers 5 的加载后初始化覆盖真实权重。"""
- std = self.config.init_std
- if isinstance(module, nn.Linear):
- init.normal_(module.weight, mean=0.0, std=std)
- if module.bias is not None:
- init.zeros_(module.bias)
- elif isinstance(module, nn.Embedding):
- 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):
- pad_token = self.config.pad_token_id
- input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
- dummy_inputs = {
- "attention_mask": input_ids.ne(pad_token),
- "input_ids": input_ids,
- }
- return dummy_inputs
-
-
-MBART_START_DOCSTRING = r"""
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
- etc.)
-
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
- and behavior.
-
- Parameters:
- config ([`MBartConfig`]):
- Model configuration class with all the parameters of the model. Initializing with a config file does not
- load the weights associated with the model, only the configuration. Check out the
- [`~PreTrainedModel.from_pretrained`] method to load the model weights.
-"""
-
-MBART_GENERATION_EXAMPLE = r"""
- Translation example:
-
- ```python
- >>> from transformers import AutoTokenizer, MBartForConditionalGeneration
-
- >>> model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-en-ro")
- >>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-en-ro")
-
- >>> example_english_phrase = "42 is the answer"
- >>> inputs = tokenizer(example_english_phrase, return_tensors="pt")
-
- >>> # Translate
- >>> generated_ids = model.generate(**inputs, num_beams=4, max_length=5)
- >>> tokenizer.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
- '42 este răspuns'
- ```
-
- Mask filling example:
-
- ```python
- >>> from transformers import AutoTokenizer, MBartForConditionalGeneration
-
- >>> model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-cc25")
- >>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25")
-
- >>> # de_DE is the language symbol id <LID> for German
- >>> TXT = "</s> Meine Freunde sind <mask> nett aber sie essen zu viel Kuchen. </s> de_DE"
-
- >>> input_ids = tokenizer([TXT], add_special_tokens=False, return_tensors="pt")["input_ids"]
- >>> logits = model(input_ids).logits
-
- >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
- >>> probs = logits[0, masked_index].softmax(dim=0)
- >>> values, predictions = probs.topk(5)
-
- >>> tokenizer.decode(predictions).split()
- ['nett', 'sehr', 'ganz', 'nicht', 'so']
- ```
-"""
-
-MBART_INPUTS_DOCSTRING = r"""
- Args:
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
- it.
-
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
-
- [What are input IDs?](../glossary#input-ids)
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
-
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
-
- [What are attention masks?](../glossary#attention-mask)
- decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Indices of decoder input sequence tokens in the vocabulary.
-
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
-
- [What are decoder input IDs?](../glossary#decoder-input-ids)
-
- MBart uses a specific language id token as the starting token for `decoder_input_ids` generation that
- varies according to source and target language, *e.g.* 25004 for *en_XX*, and 25003 for *de_DE*. If
- `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
- `past_key_values`).
-
- For translation and summarization training, `decoder_input_ids` should be provided. If no
- `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
- for denoising pre-training following the paper.
- decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
- be used by default.
- head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
- Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
- Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
- Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
- 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
- Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
- `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
- hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
- past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
- `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
- `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
-
- Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
- blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
-
- If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
- don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
- `decoder_input_ids` of shape `(batch_size, sequence_length)`.
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
- This is useful if you want more control over how to convert `input_ids` indices into associated vectors
- than the model's internal embedding lookup matrix.
- decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
- Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
- representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
- input (see `past_key_values`). This is useful if you want more control over how to convert
- `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
-
- If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
- of `inputs_embeds`.
- use_cache (`bool`, *optional*):
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
- `past_key_values`).
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
- tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
- more detail.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
-"""
-
-
-class UnimerMBartEncoder(UnimerMBartPreTrainedModel):
- """
- Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
- [`MBartEncoderLayer`].
-
- Args:
- config: MBartConfig
- embed_tokens (nn.Embedding): output embedding
- """
-
- def __init__(self, config: UnimerMBartConfig, embed_tokens: Optional[nn.Embedding] = None):
- super().__init__(config)
-
- self.dropout = config.dropout
- self.layerdrop = config.encoder_layerdrop
-
- embed_dim = config.d_model
- self.padding_idx = config.pad_token_id
- self.max_source_positions = config.max_position_embeddings
- embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
-
- self.embed_tokens = UnimerMBartScaledWordEmbedding(
- config.vocab_size, embed_dim, self.padding_idx, embed_scale=embed_scale
- )
-
- if embed_tokens is not None:
- self.embed_tokens.weight = embed_tokens.weight
-
- self.embed_positions = UnimerMBartLearnedPositionalEmbedding(
- config.max_position_embeddings,
- embed_dim,
- )
- self.layers = nn.ModuleList([UnimerMBartEncoderLayer(config) for _ in range(config.encoder_layers)])
- self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
- self._use_sdpa = config._attn_implementation == "sdpa"
- self.layernorm_embedding = nn.LayerNorm(embed_dim)
- self.layer_norm = nn.LayerNorm(config.d_model)
-
- self.gradient_checkpointing = False
- # Initialize weights and apply final processing
- self.post_init()
-
- def _backward_compatibility_gradient_checkpointing(self):
- # Override to not delete the attribute from the config
- if self.supports_gradient_checkpointing and getattr(self.config, "gradient_checkpointing", False):
- self.gradient_checkpointing_enable()
-
- def forward(
- self,
- input_ids: torch.LongTensor = None,
- attention_mask: Optional[torch.Tensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- inputs_embeds: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ) -> Union[Tuple, BaseModelOutput]:
- r"""
- Args:
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
- provide it.
-
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
-
- [What are input IDs?](../glossary#input-ids)
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
-
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
-
- [What are attention masks?](../glossary#attention-mask)
- head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
- Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
- This is useful if you want more control over how to convert `input_ids` indices into associated vectors
- than the model's internal embedding lookup matrix.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
- for more detail.
- return_dict (`bool`, *optional*):
- 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
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- # retrieve input_ids and inputs_embeds
- if input_ids is not None and inputs_embeds is not None:
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
- elif input_ids is not None:
- input = input_ids
- input_shape = input.shape
- input_ids = input_ids.view(-1, input_shape[-1])
- elif inputs_embeds is not None:
- input = inputs_embeds[:, :, -1]
- else:
- raise ValueError("You have to specify either input_ids or inputs_embeds")
-
- if inputs_embeds is None:
- inputs_embeds = self.embed_tokens(input_ids)
-
- embed_pos = self.embed_positions(input)
-
- hidden_states = inputs_embeds + embed_pos.to(inputs_embeds.device)
- hidden_states = self.layernorm_embedding(hidden_states)
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
-
- # 新版 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
-
- # check if head_mask has a correct number of layers specified if desired
- 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 {head_mask.size()[0]}."
- )
- for idx, encoder_layer in enumerate(self.layers):
- if output_hidden_states:
- encoder_states = encoder_states + (hidden_states,)
- # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
- to_drop = False
- if self.training:
- dropout_probability = torch.rand([])
- if dropout_probability < self.layerdrop: # skip the layer
- to_drop = True
-
- if to_drop:
- layer_outputs = (None, None)
- else:
- if self.gradient_checkpointing and self.training:
- layer_outputs = self._gradient_checkpointing_func(
- encoder_layer.__call__,
- hidden_states,
- attention_mask,
- (head_mask[idx] if head_mask is not None else None),
- output_attentions,
- )
- else:
- layer_outputs = encoder_layer(
- hidden_states,
- attention_mask,
- layer_head_mask=(head_mask[idx] if head_mask is not None else None),
- output_attentions=output_attentions,
- )
-
- hidden_states = layer_outputs[0]
-
- if output_attentions:
- all_attentions = all_attentions + (layer_outputs[1],)
-
- hidden_states = self.layer_norm(hidden_states)
-
- if output_hidden_states:
- encoder_states = encoder_states + (hidden_states,)
-
- 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)
-
-
-class UnimerMBartDecoder(UnimerMBartPreTrainedModel):
- """
- Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MBartDecoderLayer`]
-
- Args:
- config: MBartConfig
- embed_tokens (nn.Embedding): output embedding
- """
-
- def __init__(self, config: UnimerMBartConfig, embed_tokens: Optional[nn.Embedding] = None):
- super().__init__(config)
- self.dropout = config.dropout
- self.layerdrop = config.decoder_layerdrop
- self.padding_idx = config.pad_token_id
- self.max_target_positions = config.max_position_embeddings
- embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
-
- self.embed_tokens = UnimerMBartScaledWordEmbedding(
- config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
- )
-
- if embed_tokens is not None:
- self.embed_tokens.weight = embed_tokens.weight
-
- self.embed_positions = UnimerMBartLearnedPositionalEmbedding(
- config.max_position_embeddings,
- config.d_model,
- )
- 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)
- self.layer_norm = nn.LayerNorm(config.d_model)
-
- self.gradient_checkpointing = False
- # Initialize weights and apply final processing
- self.post_init()
-
- def get_input_embeddings(self):
- return self.embed_tokens
-
- def set_input_embeddings(self, value):
- self.embed_tokens = value
-
- def forward(
- self,
- input_ids: torch.LongTensor = None,
- attention_mask: Optional[torch.Tensor] = None,
- count_pred: Optional[torch.FloatTensor] = None,
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
- 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[Cache] = None,
- inputs_embeds: Optional[torch.FloatTensor] = None,
- use_cache: Optional[bool] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
- r"""
- Args:
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
- provide it.
-
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
-
- [What are input IDs?](../glossary#input-ids)
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
-
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
-
- [What are attention masks?](../glossary#attention-mask)
- encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
- Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
- of the decoder.
- encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
- Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
- selected in `[0, 1]`:
-
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
-
- [What are attention masks?](../glossary#attention-mask)
- head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
- Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
- Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
- cross-attention on hidden heads. Mask values selected in `[0, 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
- shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
- shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
-
- Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
- cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
-
- If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
- that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
- all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
- This is useful if you want more control over how to convert `input_ids` indices into associated vectors
- than the model's internal embedding lookup matrix.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
- for more detail.
- return_dict (`bool`, *optional*):
- 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
- 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
-
- # retrieve input_ids and inputs_embeds
- if input_ids is not None and inputs_embeds is not None:
- raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
- elif input_ids is not None:
- input = input_ids
- input_shape = input.size()
- input_ids = input_ids.view(-1, input_shape[-1])
- elif inputs_embeds is not None:
- input_shape = inputs_embeds.size()[:-1]
- input = inputs_embeds[:, :, -1]
- else:
- raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
-
- 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)
-
- # 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:
- 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)
-
- hidden_states = inputs_embeds + positions.to(inputs_embeds.device)
-
- # TODO: add counting context weight to hidden_states
- if count_pred is not None:
- count_context_weight = self.counting_context_weight(count_pred)
- hidden_states = hidden_states + 0.5 * count_context_weight.unsqueeze(1)
-
- hidden_states = self.layernorm_embedding(hidden_states)
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
-
- if self.gradient_checkpointing and self.training:
- if use_cache:
- logger.warning_once(
- "`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`..."
- )
- use_cache = False
-
- # decoder layers
- 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
- # 不传配置创建动态缓存,以保留 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"]):
- if attn_mask is not None:
- if attn_mask.size()[0] != len(self.layers):
- raise ValueError(
- f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
- f" {attn_mask.size()[0]}."
- )
- for idx, decoder_layer in enumerate(self.layers):
- # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
- if output_hidden_states:
- all_hidden_states += (hidden_states,)
- if self.training:
- dropout_probability = torch.rand([])
- if dropout_probability < self.layerdrop:
- continue
-
- if self.gradient_checkpointing and self.training:
- layer_outputs = self._gradient_checkpointing_func(
- decoder_layer.__call__,
- hidden_states,
- attention_mask,
- encoder_hidden_states,
- encoder_attention_mask,
- head_mask[idx] if head_mask is not None else None,
- cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
- None,
- output_attentions,
- use_cache,
- )
- else:
- layer_outputs = decoder_layer(
- hidden_states,
- attention_mask=attention_mask,
- 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_values,
- output_attentions=output_attentions,
- use_cache=use_cache,
- )
- hidden_states = layer_outputs[0]
-
- if output_attentions:
- all_self_attns += (layer_outputs[1],)
-
- if encoder_hidden_states is not None:
- all_cross_attentions += (layer_outputs[2],)
-
- hidden_states = self.layer_norm(hidden_states)
-
- # add hidden states from the last decoder layer
- if output_hidden_states:
- all_hidden_states += (hidden_states,)
-
- 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
- )
- return BaseModelOutputWithPastAndCrossAttentions(
- last_hidden_state=hidden_states,
- past_key_values=next_cache,
- hidden_states=all_hidden_states,
- attentions=all_self_attns,
- cross_attentions=all_cross_attentions,
- )
-
-
-@add_start_docstrings(
- "The bare MBART Model outputting raw hidden-states without any specific head on top.",
- MBART_START_DOCSTRING,
-)
-class UnimerMBartModel(UnimerMBartPreTrainedModel):
- _tied_weights_keys = {"encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight"}
-
- def __init__(self, config: UnimerMBartConfig):
- super().__init__(config)
-
- padding_idx, vocab_size = config.pad_token_id, config.vocab_size
- self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
-
- self.encoder = UnimerMBartEncoder(config, self.shared)
- self.decoder = UnimerMBartDecoder(config, self.shared)
-
- # Initialize weights and apply final processing
- self.post_init()
-
- def get_input_embeddings(self):
- return self.shared
-
- def set_input_embeddings(self, value):
- self.shared = value
- self.encoder.embed_tokens = self.shared
- self.decoder.embed_tokens = self.shared
-
- def get_encoder(self):
- return self.encoder
-
- def get_decoder(self):
- return self.decoder
-
- @add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING)
- @add_code_sample_docstrings(
- checkpoint=_CHECKPOINT_FOR_DOC,
- output_type=Seq2SeqModelOutput,
- config_class=_CONFIG_FOR_DOC,
- expected_output=_EXPECTED_OUTPUT_SHAPE,
- )
- def forward(
- self,
- input_ids: torch.LongTensor = None,
- attention_mask: Optional[torch.Tensor] = None,
- decoder_input_ids: Optional[torch.LongTensor] = None,
- decoder_attention_mask: Optional[torch.LongTensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- 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[Cache] = None,
- inputs_embeds: Optional[torch.FloatTensor] = None,
- decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
- use_cache: Optional[bool] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- 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
- 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
-
- # different to other models, MBart automatically creates decoder_input_ids from
- # input_ids if no decoder_input_ids are provided
- if decoder_input_ids is None and decoder_inputs_embeds is None:
- decoder_input_ids = shift_tokens_right(input_ids, self.config.pad_token_id)
-
- if encoder_outputs is None:
- encoder_outputs = self.encoder(
- input_ids=input_ids,
- attention_mask=attention_mask,
- head_mask=head_mask,
- inputs_embeds=inputs_embeds,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
- elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
- encoder_outputs = BaseModelOutput(
- last_hidden_state=encoder_outputs[0],
- hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
- attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
- )
-
- # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
- decoder_outputs = self.decoder(
- input_ids=decoder_input_ids,
- attention_mask=decoder_attention_mask,
- encoder_hidden_states=encoder_outputs[0],
- encoder_attention_mask=attention_mask,
- head_mask=decoder_head_mask,
- cross_attn_head_mask=cross_attn_head_mask,
- past_key_values=past_key_values,
- inputs_embeds=decoder_inputs_embeds,
- use_cache=use_cache,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
-
- if not return_dict:
- return decoder_outputs + encoder_outputs
-
- return Seq2SeqModelOutput(
- last_hidden_state=decoder_outputs.last_hidden_state,
- past_key_values=decoder_outputs.past_key_values,
- decoder_hidden_states=decoder_outputs.hidden_states,
- decoder_attentions=decoder_outputs.attentions,
- cross_attentions=decoder_outputs.cross_attentions,
- encoder_last_hidden_state=encoder_outputs.last_hidden_state,
- encoder_hidden_states=encoder_outputs.hidden_states,
- encoder_attentions=encoder_outputs.attentions,
- )
-
-
-@add_start_docstrings(
- "The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.",
- MBART_START_DOCSTRING,
-)
-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.shared.weight",
- "model.decoder.embed_tokens.weight": "model.shared.weight",
- "lm_head.weight": "model.shared.weight",
- }
-
- def __init__(self, config: UnimerMBartConfig):
- super().__init__(config)
- self.model = UnimerMBartModel(config)
- self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
- self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
-
- # Initialize weights and apply final processing
- self.post_init()
-
- def get_encoder(self):
- return self.model.get_encoder()
-
- def get_decoder(self):
- return self.model.get_decoder()
-
- def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
- new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
- self._resize_final_logits_bias(new_embeddings.weight.shape[0])
- return new_embeddings
-
- def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
- old_num_tokens = self.final_logits_bias.shape[-1]
- if new_num_tokens <= old_num_tokens:
- new_bias = self.final_logits_bias[:, :new_num_tokens]
- else:
- extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
- new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
- self.register_buffer("final_logits_bias", new_bias)
-
- def get_output_embeddings(self):
- return self.lm_head
-
- def set_output_embeddings(self, new_embeddings):
- self.lm_head = new_embeddings
-
- @add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING)
- @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
- @add_end_docstrings(MBART_GENERATION_EXAMPLE)
- def forward(
- self,
- input_ids: torch.LongTensor = None,
- attention_mask: Optional[torch.Tensor] = None,
- decoder_input_ids: Optional[torch.LongTensor] = None,
- decoder_attention_mask: Optional[torch.LongTensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- 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[Cache] = None,
- inputs_embeds: Optional[torch.FloatTensor] = None,
- decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
- labels: Optional[torch.LongTensor] = None,
- use_cache: Optional[bool] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ) -> Union[Seq2SeqLMOutput, Tuple[torch.FloatTensor]]:
- r"""
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
-
- Returns:
-
- """
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- if labels is not None:
- if use_cache:
- logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
- use_cache = False
- if decoder_input_ids is None and decoder_inputs_embeds is None:
- decoder_input_ids = shift_tokens_right(labels, self.config.pad_token_id)
-
- outputs = self.model(
- input_ids,
- attention_mask=attention_mask,
- decoder_input_ids=decoder_input_ids,
- encoder_outputs=encoder_outputs,
- decoder_attention_mask=decoder_attention_mask,
- head_mask=head_mask,
- decoder_head_mask=decoder_head_mask,
- cross_attn_head_mask=cross_attn_head_mask,
- past_key_values=past_key_values,
- inputs_embeds=inputs_embeds,
- decoder_inputs_embeds=decoder_inputs_embeds,
- use_cache=use_cache,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
-
- masked_lm_loss = None
- if labels is not None:
- loss_fct = CrossEntropyLoss()
- masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
-
- if not return_dict:
- output = (lm_logits,) + outputs[1:]
- return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
-
- return Seq2SeqLMOutput(
- loss=masked_lm_loss,
- logits=lm_logits,
- past_key_values=outputs.past_key_values,
- 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,
- )
-
- def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
- return shift_tokens_right(labels, self.config.pad_token_id)
-
-
-@add_start_docstrings(
- """
- MBart model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
- tasks.
- """,
- MBART_START_DOCSTRING,
-)
-class UnimerMBartForSequenceClassification(UnimerMBartPreTrainedModel):
- _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)
- self.model = UnimerMBartModel(config)
- self.classification_head = UnimerMBartClassificationHead(
- config.d_model,
- config.d_model,
- config.num_labels,
- config.classifier_dropout,
- )
-
- # Initialize weights and apply final processing
- self.post_init()
-
- @add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING)
- @add_code_sample_docstrings(
- checkpoint=_CHECKPOINT_FOR_DOC,
- output_type=Seq2SeqSequenceClassifierOutput,
- config_class=_CONFIG_FOR_DOC,
- )
- # Copied from transformers.models.bart.modeling_bart.BartForSequenceClassification.forward
- def forward(
- self,
- input_ids: torch.LongTensor = None,
- attention_mask: Optional[torch.Tensor] = None,
- decoder_input_ids: Optional[torch.LongTensor] = None,
- decoder_attention_mask: Optional[torch.LongTensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- decoder_head_mask: Optional[torch.Tensor] = None,
- cross_attn_head_mask: Optional[torch.Tensor] = None,
- encoder_outputs: Optional[List[torch.FloatTensor]] = None,
- inputs_embeds: Optional[torch.FloatTensor] = None,
- decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
- labels: Optional[torch.LongTensor] = None,
- use_cache: Optional[bool] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ) -> Union[Tuple, Seq2SeqSequenceClassifierOutput]:
- r"""
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
- config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
- """
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
- if labels is not None:
- 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__}")
-
- outputs = self.model(
- input_ids,
- attention_mask=attention_mask,
- decoder_input_ids=decoder_input_ids,
- decoder_attention_mask=decoder_attention_mask,
- head_mask=head_mask,
- decoder_head_mask=decoder_head_mask,
- cross_attn_head_mask=cross_attn_head_mask,
- encoder_outputs=encoder_outputs,
- inputs_embeds=inputs_embeds,
- decoder_inputs_embeds=decoder_inputs_embeds,
- use_cache=use_cache,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- hidden_states = outputs[0] # last hidden state
-
- eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)
-
- 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, :]
- logits = self.classification_head(sentence_representation)
-
- loss = None
- if labels is not None:
- labels = labels.to(logits.device)
- if self.config.problem_type is None:
- if self.config.num_labels == 1:
- self.config.problem_type = "regression"
- elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
- self.config.problem_type = "single_label_classification"
- else:
- self.config.problem_type = "multi_label_classification"
-
- if self.config.problem_type == "regression":
- loss_fct = MSELoss()
- if self.config.num_labels == 1:
- loss = loss_fct(logits.squeeze(), labels.squeeze())
- else:
- loss = loss_fct(logits, labels)
- elif self.config.problem_type == "single_label_classification":
- loss_fct = CrossEntropyLoss()
- loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
- elif self.config.problem_type == "multi_label_classification":
- loss_fct = BCEWithLogitsLoss()
- loss = loss_fct(logits, labels)
- if not return_dict:
- output = (logits,) + outputs[1:]
- return ((loss,) + output) if loss is not None else output
-
- return Seq2SeqSequenceClassifierOutput(
- loss=loss,
- logits=logits,
- past_key_values=outputs.past_key_values,
- 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,
- )
-
-
-@add_start_docstrings(
- """
- MBART Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
- layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
- """,
- MBART_START_DOCSTRING,
-)
-class UnimerMBartForQuestionAnswering(UnimerMBartPreTrainedModel):
- _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)
-
- config.num_labels = 2
- self.num_labels = config.num_labels
-
- self.model = UnimerMBartModel(config)
- self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
-
- # Initialize weights and apply final processing
- self.post_init()
-
- @add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING)
- @add_code_sample_docstrings(
- checkpoint=_CHECKPOINT_FOR_DOC,
- output_type=Seq2SeqQuestionAnsweringModelOutput,
- config_class=_CONFIG_FOR_DOC,
- )
- # Copied from transformers.models.bart.modeling_bart.BartForQuestionAnswering.forward
- def forward(
- self,
- input_ids: torch.Tensor = None,
- attention_mask: Optional[torch.Tensor] = None,
- decoder_input_ids: Optional[torch.LongTensor] = None,
- decoder_attention_mask: Optional[torch.LongTensor] = None,
- head_mask: Optional[torch.Tensor] = None,
- decoder_head_mask: Optional[torch.Tensor] = None,
- cross_attn_head_mask: Optional[torch.Tensor] = None,
- encoder_outputs: Optional[List[torch.FloatTensor]] = None,
- start_positions: Optional[torch.LongTensor] = None,
- end_positions: Optional[torch.LongTensor] = None,
- inputs_embeds: Optional[torch.FloatTensor] = None,
- decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
- use_cache: Optional[bool] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- ) -> Union[Tuple, Seq2SeqQuestionAnsweringModelOutput]:
- r"""
- start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
- Labels for position (index) of the start of the labelled span for computing the token classification loss.
- Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
- are not taken into account for computing the loss.
- end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
- Labels for position (index) of the end of the labelled span for computing the token classification loss.
- Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
- are not taken into account for computing the loss.
- """
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
- if start_positions is not None and end_positions is not None:
- use_cache = False
-
- outputs = self.model(
- input_ids,
- attention_mask=attention_mask,
- decoder_input_ids=decoder_input_ids,
- decoder_attention_mask=decoder_attention_mask,
- head_mask=head_mask,
- decoder_head_mask=decoder_head_mask,
- cross_attn_head_mask=cross_attn_head_mask,
- encoder_outputs=encoder_outputs,
- inputs_embeds=inputs_embeds,
- decoder_inputs_embeds=decoder_inputs_embeds,
- use_cache=use_cache,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
-
- sequence_output = outputs[0]
-
- logits = self.qa_outputs(sequence_output)
- start_logits, end_logits = logits.split(1, dim=-1)
- start_logits = start_logits.squeeze(-1).contiguous()
- end_logits = end_logits.squeeze(-1).contiguous()
-
- total_loss = None
- if start_positions is not None and end_positions is not None:
- # If we are on multi-GPU, split add a dimension
- if len(start_positions.size()) > 1:
- start_positions = start_positions.squeeze(-1)
- if len(end_positions.size()) > 1:
- end_positions = end_positions.squeeze(-1)
- # sometimes the start/end positions are outside our model inputs, we ignore these terms
- ignored_index = start_logits.size(1)
- start_positions = start_positions.clamp(0, ignored_index)
- end_positions = end_positions.clamp(0, ignored_index)
-
- loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
- start_loss = loss_fct(start_logits, start_positions)
- end_loss = loss_fct(end_logits, end_positions)
- total_loss = (start_loss + end_loss) / 2
-
- if not return_dict:
- output = (
- start_logits,
- end_logits,
- ) + outputs[1:]
- return ((total_loss,) + output) if total_loss is not None else output
-
- return Seq2SeqQuestionAnsweringModelOutput(
- loss=total_loss,
- start_logits=start_logits,
- end_logits=end_logits,
- past_key_values=outputs.past_key_values,
- 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,
- )
-
-
-# Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->MBart
-class UnimerMBartDecoderWrapper(UnimerMBartPreTrainedModel):
- """
- This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
- used in combination with the [`EncoderDecoderModel`] framework.
- """
-
- def __init__(self, config):
- super().__init__(config)
- self.decoder = UnimerMBartDecoder(config)
-
- def forward(self, *args, **kwargs):
- return self.decoder(*args, **kwargs)
-
-
-# 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": "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)
-
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
-
- # Initialize weights and apply final processing
- self.post_init()
-
- def get_input_embeddings(self):
- return self.model.decoder.embed_tokens
-
- def set_input_embeddings(self, value):
- self.model.decoder.embed_tokens = value
-
- def get_output_embeddings(self):
- return self.lm_head
-
- def set_output_embeddings(self, new_embeddings):
- self.lm_head = new_embeddings
-
- def set_decoder(self, decoder):
- self.model.decoder = decoder
-
- def get_decoder(self):
- return self.model.decoder
-
- @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentionsAndCounting, config_class=_CONFIG_FOR_DOC)
- def forward(
- self,
- input_ids: torch.LongTensor = None,
- attention_mask: Optional[torch.Tensor] = None,
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
- 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[Cache] = None,
- inputs_embeds: Optional[torch.FloatTensor] = None,
- labels: Optional[torch.LongTensor] = None,
- use_cache: Optional[bool] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- return_dict: Optional[bool] = None,
- count_gt: Optional[torch.LongTensor] = None,
- **kwargs,
- ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
- r"""
- Args:
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
- provide it.
-
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
-
- [What are input IDs?](../glossary#input-ids)
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
-
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
-
- [What are attention masks?](../glossary#attention-mask)
- encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
- Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
- if the model is configured as a decoder.
- encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
- in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
- Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
- Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
- shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
- shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
- tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
-
- Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
- cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
-
- If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
- that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
- all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
- use_cache (`bool`, *optional*):
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
- (see `past_key_values`).
-
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
- for more detail.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
-
- Returns:
-
- Example:
-
- ```python
- >>> from transformers import AutoTokenizer, MBartForCausalLM
-
- >>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25")
- >>> model = MBartForCausalLM.from_pretrained("facebook/mbart-large-cc25", add_cross_attention=False)
- >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
- >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
- >>> outputs = model(**inputs)
-
- >>> logits = outputs.logits
- >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
- >>> list(logits.shape) == expected_shape
- True
- ```"""
-
- 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
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- count_pred = None
-
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
- outputs = self.model.decoder(
- input_ids=input_ids,
- attention_mask=attention_mask,
- count_pred=count_pred,
- encoder_hidden_states=encoder_hidden_states,
- encoder_attention_mask=encoder_attention_mask,
- head_mask=head_mask,
- cross_attn_head_mask=cross_attn_head_mask,
- past_key_values=past_key_values,
- inputs_embeds=inputs_embeds,
- use_cache=use_cache,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
-
- logits = self.lm_head(outputs[0])
-
- loss = None
- if labels is not None:
- labels = labels.to(logits.device)
- loss_fct = CrossEntropyLoss()
- loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
-
- if not return_dict:
- output = (logits,) + outputs[1:]
- return (loss,) + output if loss is not None else output
-
- return CausalLMOutputWithCrossAttentionsAndCounting(
- loss=loss,
- logits=logits,
- past_key_values=outputs.past_key_values,
- hidden_states=outputs.hidden_states,
- attentions=outputs.attentions,
- cross_attentions=outputs.cross_attentions,
- counting=count_pred,
- )
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/tokenization_unimer_mbart.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/tokenization_unimer_mbart.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_mbart/tokenization_unimer_mbart.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/__init__.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/__init__.py
deleted file mode 100644
index df37a121..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/__init__.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-from .configuration_unimer_swin import UnimerSwinConfig
-from .modeling_unimer_swin import UnimerSwinModel
-from .image_processing_unimer_swin import UnimerSwinImageProcessor
-
-__all__ = [
- "UnimerSwinConfig",
- "UnimerSwinModel",
- "UnimerSwinImageProcessor",
-]
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/configuration_unimer_swin.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/configuration_unimer_swin.py
deleted file mode 100644
index 6c577e7c..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/configuration_unimer_swin.py
+++ /dev/null
@@ -1,132 +0,0 @@
-# coding=utf-8
-# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""Donut Swin Transformer model configuration"""
-
-from transformers.configuration_utils import PretrainedConfig
-from transformers.utils import logging
-
-
-logger = logging.get_logger(__name__)
-
-
-class UnimerSwinConfig(PretrainedConfig):
- r"""
- This is the configuration class to store the configuration of a [`UnimerSwinModel`]. It is used to instantiate a
- Donut model according to the specified arguments, defining the model architecture. Instantiating a configuration
- with the defaults will yield a similar configuration to that of the Donut
- [naver-clova-ix/donut-base](https://huggingface.co/naver-clova-ix/donut-base) architecture.
-
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
- documentation from [`PretrainedConfig`] for more information.
-
- Args:
- image_size (`int`, *optional*, defaults to 224):
- The size (resolution) of each image.
- patch_size (`int`, *optional*, defaults to 4):
- The size (resolution) of each patch.
- num_channels (`int`, *optional*, defaults to 3):
- The number of input channels.
- embed_dim (`int`, *optional*, defaults to 96):
- Dimensionality of patch embedding.
- depths (`list(int)`, *optional*, defaults to `[2, 2, 6, 2]`):
- Depth of each layer in the Transformer encoder.
- num_heads (`list(int)`, *optional*, defaults to `[3, 6, 12, 24]`):
- Number of attention heads in each layer of the Transformer encoder.
- window_size (`int`, *optional*, defaults to 7):
- Size of windows.
- mlp_ratio (`float`, *optional*, defaults to 4.0):
- Ratio of MLP hidden dimensionality to embedding dimensionality.
- qkv_bias (`bool`, *optional*, defaults to `True`):
- Whether or not a learnable bias should be added to the queries, keys and values.
- hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
- The dropout probability for all fully connected layers in the embeddings and encoder.
- attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
- The dropout ratio for the attention probabilities.
- drop_path_rate (`float`, *optional*, defaults to 0.1):
- Stochastic depth rate.
- hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
- The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
- `"selu"` and `"gelu_new"` are supported.
- use_absolute_embeddings (`bool`, *optional*, defaults to `False`):
- Whether or not to add absolute position embeddings to the patch embeddings.
- initializer_range (`float`, *optional*, defaults to 0.02):
- The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
- layer_norm_eps (`float`, *optional*, defaults to 1e-05):
- The epsilon used by the layer normalization layers.
-
- Example:
-
- ```python
- >>> from transformers import UnimerSwinConfig, UnimerSwinModel
-
- >>> # Initializing a Donut naver-clova-ix/donut-base style configuration
- >>> configuration = UnimerSwinConfig()
-
- >>> # Randomly initializing a model from the naver-clova-ix/donut-base style configuration
- >>> model = UnimerSwinModel(configuration)
-
- >>> # Accessing the model configuration
- >>> configuration = model.config
- ```"""
-
- model_type = "unimer-swin"
-
- attribute_map = {
- "num_attention_heads": "num_heads",
- "num_hidden_layers": "num_layers",
- }
-
- def __init__(
- self,
- image_size=224,
- patch_size=4,
- num_channels=3,
- embed_dim=96,
- depths=[2, 2, 6, 2],
- num_heads=[3, 6, 12, 24],
- window_size=7,
- mlp_ratio=4.0,
- qkv_bias=True,
- hidden_dropout_prob=0.0,
- attention_probs_dropout_prob=0.0,
- drop_path_rate=0.1,
- hidden_act="gelu",
- use_absolute_embeddings=False,
- initializer_range=0.02,
- layer_norm_eps=1e-5,
- **kwargs,
- ):
- super().__init__(**kwargs)
-
- self.image_size = image_size
- self.patch_size = patch_size
- self.num_channels = num_channels
- self.embed_dim = embed_dim
- self.depths = depths
- self.num_layers = len(depths)
- self.num_heads = num_heads
- self.window_size = window_size
- self.mlp_ratio = mlp_ratio
- self.qkv_bias = qkv_bias
- self.hidden_dropout_prob = hidden_dropout_prob
- self.attention_probs_dropout_prob = attention_probs_dropout_prob
- self.drop_path_rate = drop_path_rate
- self.hidden_act = hidden_act
- self.use_absolute_embeddings = use_absolute_embeddings
- self.layer_norm_eps = layer_norm_eps
- self.initializer_range = initializer_range
- # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
- # this indicates the channel dimension after the last stage of the model
- self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))
diff --git a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py b/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py
deleted file mode 100644
index 31cdb4d9..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/image_processing_unimer_swin.py
+++ /dev/null
@@ -1,177 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
-
-from docvortex.image import gray_image, resize_image
-from PIL import Image, ImageOps
-from transformers.image_processing_utils import BaseImageProcessor
-import numpy as np
-import torch
-from torchvision.transforms.functional import resize
-
-
-class UnimerSwinImageProcessor(BaseImageProcessor):
- def __init__(
- self,
- image_size = (192, 672),
- ):
- self.input_size = [int(_) for _ in image_size]
- assert len(self.input_size) == 2
-
- def __call__(self, item):
- image = self.prepare_input(item)
- return self.to_normalized_gray_tensor(image)
-
- @staticmethod
- def to_normalized_gray_tensor(image: np.ndarray) -> torch.Tensor:
- """将图像确定性转灰度、按 UniMERNet 参数归一化,并转为单通道 tensor。"""
- if image.ndim == 2:
- gray = image
- elif image.ndim == 3 and image.shape[2] == 1:
- gray = image[:, :, 0]
- elif image.ndim == 3 and image.shape[2] == 3:
-
- gray = gray_image(image, color_order='rgb')
- else:
- raise ValueError(f"Unsupported image shape for UnimerSwinImageProcessor: {image.shape}")
-
- normalized = (gray.astype(np.float32) - 0.7931 * 255.0) / (0.1738 * 255.0)
- return torch.from_numpy(normalized[None, :, :])
-
- @staticmethod
- def crop_margin(img: Image.Image) -> Image.Image:
- data = np.array(img.convert("L"))
- data = data.astype(np.uint8)
- max_val = data.max()
- min_val = data.min()
- if max_val == min_val:
- return img
- data = (data - min_val) / (max_val - min_val) * 255
- gray = 255 * (data < 200).astype(np.uint8)
-
- ys, xs = np.nonzero(gray)
- if xs.size == 0:
- return img.crop((0, 0, 0, 0))
- return img.crop((int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1))
-
- @staticmethod
- def crop_margin_numpy(img: np.ndarray) -> np.ndarray:
- """Crop margins of image using NumPy operations"""
- # Convert to grayscale if it's a color image
- if len(img.shape) == 3 and img.shape[2] == 3:
-
- gray = gray_image(img, color_order='rgb')
- else:
- gray = img.copy()
-
- # Normalize and threshold
- if gray.max() == gray.min():
- return img
-
- normalized = (((gray - gray.min()) / (gray.max() - gray.min())) * 255).astype(np.uint8)
- binary = 255 * (normalized < 200).astype(np.uint8)
-
- # Find bounding box
- mask = binary[:, :, 0] if binary.ndim == 3 and binary.shape[2] == 1 else binary
- ys, xs = np.nonzero(mask)
- if xs.size == 0:
- return img[0:0, 0:0]
- return img[int(ys.min()):int(ys.max()) + 1, int(xs.min()):int(xs.max()) + 1]
-
- def prepare_input(self, img, random_padding: bool = False):
- """
- Convert PIL Image or numpy array to properly sized and padded image after:
- - crop margins
- - resize while maintaining aspect ratio
- - pad to target size
- """
- if img is None:
- return None
-
- # Handle numpy array
- elif isinstance(img, np.ndarray):
- try:
- img = self.crop_margin_numpy(img)
- except Exception:
- # might throw an error for broken files
- return None
-
- if img.shape[0] == 0 or img.shape[1] == 0:
- return None
-
- # Get current dimensions
- h, w = img.shape[:2]
- target_h, target_w = self.input_size
-
- # Calculate scale to preserve aspect ratio (equivalent to resize + thumbnail)
- scale = min(target_h / h, target_w / w)
-
- # Calculate new dimensions
- new_h, new_w = int(h * scale), int(w * scale)
-
- # Resize the image while preserving aspect ratio
-
- resized_img = resize_image(img, (new_w, new_h))
-
- # Calculate padding values using the existing method
- delta_width = target_w - new_w
- delta_height = target_h - new_h
-
- pad_width, pad_height = self._get_padding_values(new_w, new_h, random_padding)
-
- # 常量零填充无需 OpenCV,保持缩放结果的维度和位深。
- padding = [(pad_height, delta_height - pad_height), (pad_width, delta_width - pad_width)]
- if resized_img.ndim == 3:
- padding.append((0, 0))
- padded_img = np.pad(resized_img, padding, mode="constant")
-
- return padded_img
-
- # Handle PIL Image
- elif isinstance(img, Image.Image):
- try:
- img = self.crop_margin(img.convert("RGB"))
- except OSError:
- # might throw an error for broken files
- return None
-
- if img.height == 0 or img.width == 0:
- return None
-
- # Resize while preserving aspect ratio
- img = resize(img, min(self.input_size))
- img.thumbnail((self.input_size[1], self.input_size[0]))
- new_w, new_h = img.width, img.height
-
- # Calculate and apply padding
- padding = self._calculate_padding(new_w, new_h, random_padding)
- return np.array(ImageOps.expand(img, padding))
-
- else:
- return None
-
- def _calculate_padding(self, new_w, new_h, random_padding):
- """Calculate padding values for PIL images"""
- delta_width = self.input_size[1] - new_w
- delta_height = self.input_size[0] - new_h
-
- pad_width, pad_height = self._get_padding_values(new_w, new_h, random_padding)
-
- return (
- pad_width,
- pad_height,
- delta_width - pad_width,
- delta_height - pad_height,
- )
-
- def _get_padding_values(self, new_w, new_h, random_padding):
- """Get padding values based on image dimensions and padding strategy"""
- delta_width = self.input_size[1] - new_w
- delta_height = self.input_size[0] - new_h
-
- if random_padding:
- pad_width = np.random.randint(low=0, high=delta_width + 1)
- pad_height = np.random.randint(low=0, high=delta_height + 1)
- else:
- pad_width = delta_width // 2
- pad_height = delta_height // 2
-
- return pad_width, pad_height
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
deleted file mode 100644
index 2c5ec90e..00000000
--- a/mineru/model/mfr/unimernet/unimernet_hf/unimer_swin/modeling_unimer_swin.py
+++ /dev/null
@@ -1,1044 +0,0 @@
-# coding=utf-8
-# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-"""PyTorch UnimerSwin Transformer model.
-
-This implementation is identical to a regular Swin Transformer, without final layer norm on top of the final hidden
-states."""
-
-import collections.abc
-import math
-from dataclasses import dataclass
-from typing import Optional, Tuple, Union
-
-import torch
-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.utils import (
- ModelOutput,
- add_code_sample_docstrings,
- add_start_docstrings,
- add_start_docstrings_to_model_forward,
- logging,
- torch_int,
-)
-from .configuration_unimer_swin import UnimerSwinConfig
-
-
-logger = logging.get_logger(__name__)
-
-# General docstring
-_CONFIG_FOR_DOC = "UnimerSwinConfig"
-
-# Base docstring
-_CHECKPOINT_FOR_DOC = "https://huggingface.co/naver-clova-ix/donut-base"
-_EXPECTED_OUTPUT_SHAPE = [1, 49, 768]
-
-
-@dataclass
-# Copied from transformers.models.swin.modeling_swin.SwinEncoderOutput with Swin->UnimerSwin
-class UnimerSwinEncoderOutput(ModelOutput):
- """
- UnimerSwin encoder's outputs, with potential hidden states and attentions.
-
- Args:
- last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
- Sequence of hidden-states at the output of the last layer of the model.
- hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
- shape `(batch_size, sequence_length, hidden_size)`.
-
- Hidden-states of the model at the output of each layer plus the initial embedding outputs.
- attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
- sequence_length)`.
-
- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
- heads.
- reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
- shape `(batch_size, hidden_size, height, width)`.
-
- Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
- include the spatial dimensions.
- """
-
- last_hidden_state: torch.FloatTensor = None
- hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
- attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
- reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
-
-
-@dataclass
-# Copied from transformers.models.swin.modeling_swin.SwinModelOutput with Swin->UnimerSwin
-class UnimerSwinModelOutput(ModelOutput):
- """
- UnimerSwin model's outputs that also contains a pooling of the last hidden states.
-
- Args:
- last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
- Sequence of hidden-states at the output of the last layer of the model.
- pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
- Average pooling of the last layer hidden-state.
- hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
- shape `(batch_size, sequence_length, hidden_size)`.
-
- Hidden-states of the model at the output of each layer plus the initial embedding outputs.
- attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
- sequence_length)`.
-
- Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
- heads.
- reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
- Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
- shape `(batch_size, hidden_size, height, width)`.
-
- Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
- include the spatial dimensions.
- """
-
- last_hidden_state: torch.FloatTensor = None
- pooler_output: Optional[torch.FloatTensor] = None
- hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
- attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
- reshaped_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
-
-
-# Copied from transformers.models.swin.modeling_swin.window_partition
-def window_partition(input_feature, window_size):
- """
- Partitions the given input into windows.
- """
- batch_size, height, width, num_channels = input_feature.shape
- input_feature = input_feature.view(
- batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
- )
- windows = input_feature.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
- return windows
-
-
-# Copied from transformers.models.swin.modeling_swin.window_reverse
-def window_reverse(windows, window_size, height, width):
- """
- Merges windows to produce higher resolution features.
- """
- num_channels = windows.shape[-1]
- windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
- windows = windows.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, height, width, num_channels)
- return windows
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinEmbeddings with Swin->UnimerSwin
-class UnimerSwinEmbeddings(nn.Module):
- """
- Construct the patch and position embeddings. Optionally, also the mask token.
- """
-
- def __init__(self, config, use_mask_token=False):
- super().__init__()
-
- self.patch_embeddings = UnimerSwinPatchEmbeddings(config)
- num_patches = self.patch_embeddings.num_patches
- self.patch_grid = self.patch_embeddings.grid_size
- self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
-
- if config.use_absolute_embeddings:
- self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.embed_dim))
- else:
- self.position_embeddings = None
-
- ### code added. ###
- if config.use_2d_embeddings:
- self.row_embeddings = nn.Parameter(torch.zeros(1, self.patch_grid[0] + 1, config.embed_dim))
- self.column_embeddings = nn.Parameter(torch.zeros(1, self.patch_grid[1] + 1, config.embed_dim))
- else:
- self.row_embeddings = None
- self.column_embeddings = None
- ######
-
- self.norm = nn.LayerNorm(config.embed_dim)
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
-
- def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
- """
- This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
- resolution images.
-
- Source:
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
- """
-
- num_patches = embeddings.shape[1] - 1
- num_positions = self.position_embeddings.shape[1] - 1
- if num_patches == num_positions and height == width:
- return self.position_embeddings
- class_pos_embed = self.position_embeddings[:, 0]
- patch_pos_embed = self.position_embeddings[:, 1:]
- dim = embeddings.shape[-1]
- h0 = height // self.config.patch_size
- w0 = width // self.config.patch_size
- # we add a small number to avoid floating point error in the interpolation
- # see discussion at https://github.com/facebookresearch/dino/issues/8
- h0, w0 = h0 + 0.1, w0 + 0.1
- patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
- patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
- patch_pos_embed = nn.functional.interpolate(
- patch_pos_embed,
- scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
- mode="bicubic",
- align_corners=False,
- )
- patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
- return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
-
- def forward(
- self,
- pixel_values: Optional[torch.FloatTensor],
- bool_masked_pos: Optional[torch.BoolTensor] = None,
- interpolate_pos_encoding: bool = False,
- ) -> Tuple[torch.Tensor]:
- _, num_channels, height, width = pixel_values.shape
- embeddings, output_dimensions = self.patch_embeddings(pixel_values)
- embeddings = self.norm(embeddings)
- batch_size, seq_len, _ = embeddings.size()
-
- if bool_masked_pos is not None:
- mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
- # replace the masked visual tokens by mask_tokens
- mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
- embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
-
- if self.position_embeddings is not None:
- # if interpolate_pos_encoding:
- # embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
- # else:
- # embeddings = embeddings + self.position_embeddings
- 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)
- embeddings = embeddings + row_embeddings + column_embeddings
- ######
-
- embeddings = self.dropout(embeddings)
-
- return embeddings, output_dimensions
-
-
-class StemLayer(nn.Module):
- r"""Stem layer of InternImage
- Args:
- in_chans (int): number of input channels
- out_chans (int): number of output channels
- act_layer (str): activation layer
- norm_layer (str): normalization layer
- """
-
- 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)
- self.act = act_layer()
- self.conv2 = nn.Conv2d(out_chans // 2, out_chans, kernel_size=3, stride=2, padding=1)
-
- def build_norm_layer(self, dim, norm_layer):
- layers = []
- if norm_layer == "BN":
- layers.append(nn.BatchNorm2d(dim))
- else:
- raise NotImplementedError(f"build_norm_layer does not support {norm_layer}")
- return nn.Sequential(*layers)
-
- def forward(self, x):
- x = self.conv1(x)
- x = self.norm1(x)
- x = self.act(x)
- x = self.conv2(x)
- return x
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinPatchEmbeddings with Swin->UnimerSwin
-class UnimerSwinPatchEmbeddings(nn.Module):
- """
- This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
- `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
- Transformer.
- """
-
- def __init__(self, config):
- super().__init__()
- image_size, patch_size = config.image_size, config.patch_size
- num_channels, hidden_size = config.num_channels, config.embed_dim
- image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
- patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
- num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
- self.image_size = image_size
- self.patch_size = patch_size
- self.num_channels = num_channels
- self.num_patches = num_patches
- self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
-
- ### code edited. ###
- # self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
- self.projection = StemLayer(in_chans=num_channels, out_chans=hidden_size)
- ###
-
- def maybe_pad(self, pixel_values, height, width):
- if width % self.patch_size[1] != 0:
- pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
- pixel_values = nn.functional.pad(pixel_values, pad_values)
- if height % self.patch_size[0] != 0:
- pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
- pixel_values = nn.functional.pad(pixel_values, pad_values)
- return pixel_values
-
- def forward(self, pixel_values: Optional[torch.FloatTensor]) -> Tuple[torch.Tensor, Tuple[int]]:
- _, num_channels, height, width = pixel_values.shape
- # pad the input to be divisible by self.patch_size, if needed
- pixel_values = self.maybe_pad(pixel_values, height, width)
- embeddings = self.projection(pixel_values)
- _, _, height, width = embeddings.shape
- output_dimensions = (height, width)
- embeddings = embeddings.flatten(2).transpose(1, 2)
-
- return embeddings, output_dimensions
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinPatchMerging
-class UnimerSwinPatchMerging(nn.Module):
- """
- Patch Merging Layer.
-
- Args:
- input_resolution (`Tuple[int]`):
- Resolution of input feature.
- dim (`int`):
- Number of input channels.
- norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
- Normalization layer class.
- """
-
- def __init__(self, input_resolution: Tuple[int], dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
- super().__init__()
- self.input_resolution = input_resolution
- self.dim = dim
- self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
- self.norm = norm_layer(4 * dim)
-
- def maybe_pad(self, input_feature, height, width):
- should_pad = (height % 2 == 1) or (width % 2 == 1)
- if should_pad:
- pad_values = (0, 0, 0, width % 2, 0, height % 2)
- input_feature = nn.functional.pad(input_feature, pad_values)
-
- return input_feature
-
- def forward(self, input_feature: torch.Tensor, input_dimensions: Tuple[int, int]) -> torch.Tensor:
- height, width = input_dimensions
- # `dim` is height * width
- batch_size, dim, num_channels = input_feature.shape
-
- input_feature = input_feature.view(batch_size, height, width, num_channels)
- # pad input to be disible by width and height, if needed
- input_feature = self.maybe_pad(input_feature, height, width)
- # [batch_size, height/2, width/2, num_channels]
- input_feature_0 = input_feature[:, 0::2, 0::2, :]
- # [batch_size, height/2, width/2, num_channels]
- input_feature_1 = input_feature[:, 1::2, 0::2, :]
- # [batch_size, height/2, width/2, num_channels]
- input_feature_2 = input_feature[:, 0::2, 1::2, :]
- # [batch_size, height/2, width/2, num_channels]
- input_feature_3 = input_feature[:, 1::2, 1::2, :]
- # batch_size height/2 width/2 4*num_channels
- input_feature = torch.cat([input_feature_0, input_feature_1, input_feature_2, input_feature_3], -1)
- input_feature = input_feature.view(batch_size, -1, 4 * num_channels) # batch_size height/2*width/2 4*C
-
- input_feature = self.norm(input_feature)
- input_feature = self.reduction(input_feature)
-
- return input_feature
-
-
-# Copied from transformers.models.beit.modeling_beit.drop_path
-def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
- """
- Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
-
- Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
- however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
- See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
- layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
- argument.
- """
- if drop_prob == 0.0 or not training:
- return input
- keep_prob = 1 - drop_prob
- shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
- random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
- random_tensor.floor_() # binarize
- output = input.div(keep_prob) * random_tensor
- return output
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinDropPath
-class UnimerSwinDropPath(nn.Module):
- """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
-
- def __init__(self, drop_prob: Optional[float] = None) -> None:
- super().__init__()
- self.drop_prob = drop_prob
-
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
- return drop_path(hidden_states, self.drop_prob, self.training)
-
- def extra_repr(self) -> str:
- return "p={}".format(self.drop_prob)
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinSelfAttention with Swin->UnimerSwin
-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})")
-
- 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.relative_position_bias_table = nn.Parameter(
- torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), num_heads)
- )
-
- # 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(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()
- relative_coords[:, :, 0] += self.window_size[0] - 1
- relative_coords[:, :, 1] += self.window_size[1] - 1
- relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
- relative_position_index = relative_coords.sum(-1)
- self.register_buffer("relative_position_index", relative_position_index)
-
- self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
- self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
- self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
-
- self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
-
- def transpose_for_scores(self, x):
- new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
- x = x.view(new_x_shape)
- return x.permute(0, 2, 1, 3)
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: Optional[torch.FloatTensor] = None,
- head_mask: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = False,
- ) -> Tuple[torch.Tensor]:
- batch_size, dim, num_channels = hidden_states.shape
- mixed_query_layer = self.query(hidden_states)
-
- key_layer = self.transpose_for_scores(self.key(hidden_states))
- value_layer = self.transpose_for_scores(self.value(hidden_states))
- query_layer = self.transpose_for_scores(mixed_query_layer)
-
- # Take the dot product between "query" and "key" to get the raw attention scores.
- attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
-
- attention_scores = attention_scores / math.sqrt(self.attention_head_size)
-
- relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)]
- relative_position_bias = relative_position_bias.view(
- self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
- )
-
- relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
- attention_scores = attention_scores + relative_position_bias.unsqueeze(0)
-
- 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 + attention_mask.unsqueeze(1).unsqueeze(0)
- attention_scores = attention_scores.view(-1, self.num_attention_heads, dim, dim)
-
- # Normalize the attention scores to probabilities.
- attention_probs = nn.functional.softmax(attention_scores, dim=-1)
-
- # This is actually dropping out entire tokens to attend to, which might
- # seem a bit unusual, but is taken from the original Transformer paper.
- attention_probs = self.dropout(attention_probs)
-
- # Mask heads if we want to
- 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()
- new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
- context_layer = context_layer.view(new_context_layer_shape)
-
- outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
-
- return outputs
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinSelfOutput
-class UnimerSwinSelfOutput(nn.Module):
- def __init__(self, config, dim):
- super().__init__()
- self.dense = nn.Linear(dim, dim)
- self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
-
- 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 hidden_states
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinAttention with Swin->UnimerSwin
-class UnimerSwinAttention(nn.Module):
- def __init__(self, config, dim, num_heads, window_size):
- super().__init__()
- self.self = UnimerSwinSelfAttention(config, dim, num_heads, window_size)
- self.output = UnimerSwinSelfOutput(config, dim)
- self.pruned_heads = set()
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: Optional[torch.FloatTensor] = None,
- head_mask: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = False,
- ) -> Tuple[torch.Tensor]:
- self_outputs = self.self(hidden_states, attention_mask, head_mask, output_attentions)
- attention_output = self.output(self_outputs[0], hidden_states)
- outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
- return outputs
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinIntermediate
-class UnimerSwinIntermediate(nn.Module):
- def __init__(self, config, dim):
- super().__init__()
- self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
- 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:
- hidden_states = self.dense(hidden_states)
- hidden_states = self.intermediate_act_fn(hidden_states)
- return hidden_states
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinOutput
-class UnimerSwinOutput(nn.Module):
- def __init__(self, config, dim):
- super().__init__()
- self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
- self.dropout = nn.Dropout(config.hidden_dropout_prob)
-
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
- hidden_states = self.dense(hidden_states)
- hidden_states = self.dropout(hidden_states)
- return hidden_states
-
-
-class ConvEnhance(nn.Module):
- """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.act_fn = ACT2FN[config.hidden_act]
-
- def forward(self, x, size: Tuple[int, int]):
- B, N, C = x.shape
- H, W = size
- assert N == H * W
-
- feat = x.transpose(1, 2).view(B, C, H, W)
- feat = self.proj(feat)
- feat = self.act_fn(feat)
- feat = feat.flatten(2).transpose(1, 2)
-
- x = x + feat
- return x
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinLayer with Swin->UnimerSwin
-class UnimerSwinLayer(nn.Module):
- def __init__(self, config, dim, input_resolution, num_heads, shift_size=0):
- super().__init__()
- self.chunk_size_feed_forward = config.chunk_size_feed_forward
- self.shift_size = shift_size
- self.window_size = config.window_size
- 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.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()
- self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
- self.intermediate = UnimerSwinIntermediate(config, dim)
- self.output = UnimerSwinOutput(config, dim)
-
- def set_shift_and_window_size(self, input_resolution):
- 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)
-
- def get_attn_mask(self, height, width, dtype, device):
- if self.shift_size > 0:
- # calculate attention mask for SW-MSA
- img_mask = torch.zeros((1, height, width, 1), dtype=dtype, device=device)
- height_slices = (
- slice(0, -self.window_size),
- slice(-self.window_size, -self.shift_size),
- slice(-self.shift_size, None),
- )
- width_slices = (
- slice(0, -self.window_size),
- slice(-self.window_size, -self.shift_size),
- slice(-self.shift_size, None),
- )
- count = 0
- for height_slice in height_slices:
- for width_slice in width_slices:
- img_mask[:, height_slice, width_slice, :] = count
- count += 1
-
- mask_windows = window_partition(img_mask, self.window_size)
- mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
- attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
- attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
- else:
- attn_mask = None
- return attn_mask
-
- def maybe_pad(self, hidden_states, height, width):
- pad_right = (self.window_size - width % self.window_size) % self.window_size
- pad_bottom = (self.window_size - height % self.window_size) % self.window_size
- pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
- hidden_states = nn.functional.pad(hidden_states, pad_values)
- return hidden_states, pad_values
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- input_dimensions: Tuple[int, int],
- head_mask: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = False,
- always_partition: Optional[bool] = False,
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- if not always_partition:
- self.set_shift_and_window_size(input_dimensions)
- else:
- 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)
-
- # pad hidden_states to multiples of window size
- hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
-
- _, height_pad, width_pad, _ = hidden_states.shape
- # cyclic shift
- if self.shift_size > 0:
- shifted_hidden_states = torch.roll(hidden_states, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
- else:
- shifted_hidden_states = hidden_states
-
- # 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)
-
- attention_outputs = self.attention(hidden_states_windows, attn_mask, head_mask, output_attentions=output_attentions)
-
- attention_output = attention_outputs[0]
-
- attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
- shifted_windows = window_reverse(attention_windows, self.window_size, height_pad, width_pad)
-
- # reverse cyclic shift
- if self.shift_size > 0:
- attention_windows = torch.roll(shifted_windows, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
- else:
- attention_windows = shifted_windows
-
- was_padded = pad_values[3] > 0 or pad_values[5] > 0
- if was_padded:
- attention_windows = attention_windows[:, :height, :width, :].contiguous()
-
- attention_windows = attention_windows.view(batch_size, height * width, channels)
-
- 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)
- layer_output = hidden_states + self.output(layer_output)
-
- layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
- return layer_outputs
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinStage with Swin->UnimerSwin
-class UnimerSwinStage(nn.Module):
- def __init__(self, config, dim, input_resolution, depth, num_heads, drop_path, downsample):
- super().__init__()
- self.config = config
- self.dim = dim
- self.blocks = nn.ModuleList(
- [
- UnimerSwinLayer(
- config=config,
- dim=dim,
- input_resolution=input_resolution,
- num_heads=num_heads,
- shift_size=0,
- )
- for i in range(depth)
- ]
- )
-
- # patch merging layer
- if downsample is not None:
- self.downsample = downsample(input_resolution, dim=dim, norm_layer=nn.LayerNorm)
- else:
- self.downsample = None
-
- self.pointing = False
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- input_dimensions: Tuple[int, int],
- head_mask: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = False,
- always_partition: Optional[bool] = False,
- ) -> Tuple[torch.Tensor]:
- height, width = input_dimensions
- 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)
-
- hidden_states = layer_outputs[0]
-
- hidden_states_before_downsampling = hidden_states
- if self.downsample is not None:
- height_downsampled, width_downsampled = (height + 1) // 2, (width + 1) // 2
- output_dimensions = (height, width, height_downsampled, width_downsampled)
- hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
- else:
- output_dimensions = (height, width, height, width)
-
- stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
-
- if output_attentions:
- stage_outputs += layer_outputs[1:]
- return stage_outputs
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinEncoder with Swin->UnimerSwin
-class UnimerSwinEncoder(nn.Module):
- def __init__(self, config, grid_size):
- super().__init__()
- self.num_layers = len(config.depths)
- self.config = config
- dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths))]
- self.layers = nn.ModuleList(
- [
- UnimerSwinStage(
- config=config,
- dim=int(config.embed_dim * 2**i_layer),
- input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
- depth=config.depths[i_layer],
- num_heads=config.num_heads[i_layer],
- drop_path=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
- downsample=UnimerSwinPatchMerging if (i_layer < self.num_layers - 1) else None,
- )
- for i_layer in range(self.num_layers)
- ]
- )
-
- self.gradient_checkpointing = False
-
- def forward(
- self,
- hidden_states: torch.Tensor,
- input_dimensions: Tuple[int, int],
- head_mask: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = False,
- output_hidden_states: Optional[bool] = False,
- output_hidden_states_before_downsampling: Optional[bool] = False,
- always_partition: Optional[bool] = False,
- return_dict: Optional[bool] = True,
- ) -> Union[Tuple, UnimerSwinEncoderOutput]:
- all_hidden_states = () if output_hidden_states else None
- all_reshaped_hidden_states = () if output_hidden_states else None
- all_self_attentions = () if output_attentions else None
-
- if output_hidden_states:
- batch_size, _, hidden_size = hidden_states.shape
- # rearrange b (h w) c -> b c h w
- reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
- reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
- all_hidden_states += (hidden_states,)
- all_reshaped_hidden_states += (reshaped_hidden_state,)
-
- for i, layer_module in enumerate(self.layers):
- layer_head_mask = head_mask[i] if head_mask is not None else None
-
- if self.gradient_checkpointing and self.training:
- layer_outputs = self._gradient_checkpointing_func(
- layer_module.__call__,
- hidden_states,
- input_dimensions,
- layer_head_mask,
- output_attentions,
- always_partition,
- )
- else:
- layer_outputs = layer_module(
- hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
- )
-
- hidden_states = layer_outputs[0]
- hidden_states_before_downsampling = layer_outputs[1]
- output_dimensions = layer_outputs[2]
-
- input_dimensions = (output_dimensions[-2], output_dimensions[-1])
-
- if output_hidden_states and output_hidden_states_before_downsampling:
- batch_size, _, hidden_size = hidden_states_before_downsampling.shape
- # rearrange b (h w) c -> b c h w
- # here we use the original (not downsampled) height and width
- reshaped_hidden_state = hidden_states_before_downsampling.view(
- batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
- )
- reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
- all_hidden_states += (hidden_states_before_downsampling,)
- all_reshaped_hidden_states += (reshaped_hidden_state,)
- elif output_hidden_states and not output_hidden_states_before_downsampling:
- batch_size, _, hidden_size = hidden_states.shape
- # rearrange b (h w) c -> b c h w
- reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
- reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
- all_hidden_states += (hidden_states,)
- all_reshaped_hidden_states += (reshaped_hidden_state,)
-
- if output_attentions:
- all_self_attentions += layer_outputs[3:]
-
- if not return_dict:
- return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
-
- return UnimerSwinEncoderOutput(
- last_hidden_state=hidden_states,
- hidden_states=all_hidden_states,
- attentions=all_self_attentions,
- reshaped_hidden_states=all_reshaped_hidden_states,
- )
-
-
-# Copied from transformers.models.swin.modeling_swin.SwinPreTrainedModel with Swin->UnimerSwin
-class UnimerSwinPreTrainedModel(PreTrainedModel):
- """
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
- models.
- """
-
- config_class = UnimerSwinConfig
- base_model_prefix = "unimer-swin"
- main_input_name = "pixel_values"
- supports_gradient_checkpointing = True
- _no_split_modules = ["UnimerSwinStage"]
-
- @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
- init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
- if module.bias is not None:
- init.zeros_(module.bias)
- elif isinstance(module, nn.LayerNorm):
- init.zeros_(module.bias)
- init.ones_(module.weight)
-
-
-SWIN_START_DOCSTRING = r"""
- This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
- it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
- behavior.
-
- Parameters:
- config ([`UnimerSwinConfig`]): Model configuration class with all the parameters of the model.
- Initializing with a config file does not load the weights associated with the model, only the
- configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
-"""
-
-SWIN_INPUTS_DOCSTRING = r"""
- Args:
- pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
- Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
- [`DonutImageProcessor.__call__`] for details.
- head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
- Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
-
- - 1 indicates the head is **not masked**,
- - 0 indicates the head is **masked**.
-
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
- tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
- more detail.
- interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
- Whether to interpolate the pre-trained position encodings.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
-"""
-
-
-@add_start_docstrings(
- "The bare UnimerSwin Model transformer outputting raw hidden-states without any specific head on top.",
- SWIN_START_DOCSTRING,
-)
-class UnimerSwinModel(UnimerSwinPreTrainedModel):
- def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
- super().__init__(config)
- self.config = config
- self.num_layers = len(config.depths)
- self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1))
-
- self.embeddings = UnimerSwinEmbeddings(config, use_mask_token=use_mask_token)
- self.encoder = UnimerSwinEncoder(config, self.embeddings.patch_grid)
- self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
-
- # Initialize weights and apply final processing
- self.post_init()
-
- def get_input_embeddings(self):
- return self.embeddings.patch_embeddings
-
- @add_start_docstrings_to_model_forward(SWIN_INPUTS_DOCSTRING)
- @add_code_sample_docstrings(
- checkpoint=_CHECKPOINT_FOR_DOC,
- output_type=UnimerSwinModelOutput,
- config_class=_CONFIG_FOR_DOC,
- modality="vision",
- expected_output=_EXPECTED_OUTPUT_SHAPE,
- )
- def forward(
- self,
- pixel_values: Optional[torch.FloatTensor] = None,
- bool_masked_pos: Optional[torch.BoolTensor] = None,
- head_mask: Optional[torch.FloatTensor] = None,
- output_attentions: Optional[bool] = None,
- output_hidden_states: Optional[bool] = None,
- interpolate_pos_encoding: bool = False,
- return_dict: Optional[bool] = None,
- ) -> Union[Tuple, UnimerSwinModelOutput]:
- r"""
- bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
- 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
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
-
- if pixel_values is None:
- raise ValueError("You have to specify pixel_values")
-
- # Prepare head mask if needed
- # 1.0 in head_mask indicate we keep the head
- # 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]
- # 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
- )
-
- encoder_outputs = self.encoder(
- embedding_output,
- input_dimensions,
- head_mask=head_mask,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
-
- sequence_output = encoder_outputs[0]
-
- pooled_output = None
- if self.pooler is not None:
- pooled_output = self.pooler(sequence_output.transpose(1, 2))
- pooled_output = torch.flatten(pooled_output, 1)
-
- if not return_dict:
- output = (sequence_output, pooled_output) + encoder_outputs[1:]
-
- return output
-
- return UnimerSwinModelOutput(
- last_hidden_state=sequence_output,
- pooler_output=pooled_output,
- hidden_states=encoder_outputs.hidden_states,
- attentions=encoder_outputs.attentions,
- reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
- )
diff --git a/mineru/model/mfr/utils.py b/mineru/model/mfr/utils.py
index cae05547..99028cae 100644
--- a/mineru/model/mfr/utils.py
+++ b/mineru/model/mfr/utils.py
@@ -160,90 +160,6 @@ def is_escaped(text, pos):
return backslash_count % 2 == 1
-def fix_unbalanced_braces(latex_formula):
- """
- 检测LaTeX公式中的花括号是否闭合,并删除无法配对的花括号
-
- Args:
- latex_formula (str): 输入的LaTeX公式
-
- Returns:
- str: 删除无法配对的花括号后的LaTeX公式
- """
- stack = [] # 存储左括号的索引
- unmatched = set() # 存储不匹配括号的索引
- i = 0
-
- while i < len(latex_formula):
- # 检查是否是转义的花括号
- if latex_formula[i] in ['{', '}']:
- # 计算前面连续的反斜杠数量
- backslash_count = 0
- j = i - 1
- while j >= 0 and latex_formula[j] == '\\':
- backslash_count += 1
- j -= 1
-
- # 如果前面有奇数个反斜杠,则该花括号是转义的,不参与匹配
- if backslash_count % 2 == 1:
- i += 1
- continue
-
- # 否则,该花括号参与匹配
- if latex_formula[i] == '{':
- stack.append(i)
- else: # latex_formula[i] == '}'
- if stack: # 有对应的左括号
- stack.pop()
- else: # 没有对应的左括号
- unmatched.add(i)
-
- i += 1
-
- # 所有未匹配的左括号
- unmatched.update(stack)
-
- # 构建新字符串,删除不匹配的括号
- return ''.join(char for i, char in enumerate(latex_formula) if i not in unmatched)
-
-
-def process_latex(input_string):
- """
- 处理LaTeX公式中的反斜杠:
- 1. 如果\后跟特殊字符(#$%&~_^\\{})或空格,保持不变
- 2. 如果\后跟两个小写字母,保持不变
- 3. 其他情况,在\后添加空格
-
- Args:
- input_string (str): 输入的LaTeX公式
-
- Returns:
- str: 处理后的LaTeX公式
- """
-
- def replace_func(match):
- # 获取\后面的字符
- next_char = match.group(1)
-
- # 如果是特殊字符或空格,保持不变
- if next_char in "#$%&~_^|\\{} \t\n\r\v\f":
- return match.group(0)
-
- # 如果是字母,检查下一个字符
- if 'a' <= next_char <= 'z' or 'A' <= next_char <= 'Z':
- pos = match.start() + 2 # \x后的位置
- if pos < len(input_string) and ('a' <= input_string[pos] <= 'z' or 'A' <= input_string[pos] <= 'Z'):
- # 下一个字符也是字母,保持不变
- return match.group(0)
-
- # 其他情况,在\后添加空格
- return '\\' + ' ' + next_char
-
- # 匹配\后面跟一个字符的情况
- pattern = r'\\(.)'
-
- return re.sub(pattern, replace_func, input_string)
-
# 常见的在KaTeX/MathJax中可用的数学环境
ENV_TYPES = ['array', 'matrix', 'pmatrix', 'bmatrix', 'vmatrix',
'Bmatrix', 'Vmatrix', 'cases', 'aligned', 'gathered', 'align', 'align*']
@@ -290,26 +206,6 @@ def fix_mathring_font_arguments(s: str) -> str:
return MATHRING_FONT_ARGUMENT_PATTERN.sub(_replace, s)
-REPLACEMENTS_PATTERNS = {
- re.compile(r'\\underbar'): r'\\underline',
- re.compile(r'\\Bar'): r'\\hat',
- re.compile(r'\\Hat'): r'\\hat',
- re.compile(r'\\Tilde'): r'\\tilde',
- re.compile(r'\\slash'): r'/',
- re.compile(r'\\textperthousand'): r'‰',
- re.compile(r'\\sun'): r'☉',
- re.compile(r'\\textunderscore'): r'\\_',
- re.compile(r'\\fint'): r'⨏',
- re.compile(r'\\up '): r'\\ ',
- re.compile(r'\\vline = '): r'\\models ',
- re.compile(r'\\vDash '): r'\\models ',
- re.compile(r'\\sq \\sqcup '): r'\\square ',
- re.compile(r'\\copyright'): r'©',
- re.compile(r'\\Dot'): r'\\dot',
-}
-QQUAD_PATTERN = re.compile(r'\\qquad(?!\s)')
-
-
def remove_up_commands(s: str):
"""Remove unnecessary up commands from LaTeX code."""
UP_PATTERN = re.compile(r'\\up([a-zA-Z]+)')
@@ -328,7 +224,7 @@ def remove_unsupported_commands(s: str):
def _apply_shared_latex_repairs(s: str, *, fix_delimiter: bool) -> str:
- """执行 PP-FormulaNet 与 UniMERNet 共有的 LaTeX 修复步骤。"""
+ """执行公式识别所需的通用 LaTeX 修复步骤。"""
s = fix_latex_left_right(s, fix_delimiter=fix_delimiter)
s = fix_latex_environments(s)
s = fix_mathring_font_arguments(s)
@@ -341,28 +237,6 @@ def fix_pp_formulanet_latex(s: str) -> str:
return _apply_shared_latex_repairs(s, fix_delimiter=False)
-def fix_unimernet_latex(s: str) -> str:
- """执行 UniMERNet 专用 LaTeX 后处理与输出规范化。"""
- s = fix_unbalanced_braces(s)
- s = _apply_shared_latex_repairs(s, fix_delimiter=True)
-
- # 应用所有替换
- for pattern, replacement in REPLACEMENTS_PATTERNS.items():
- s = pattern.sub(replacement, s)
-
- # 处理LaTeX中的反斜杠和空格
- s = process_latex(s)
-
- # \qquad后补空格
- s = QQUAD_PATTERN.sub(r'\\qquad ', s)
-
- # 如果字符串以反斜杠结尾,去掉最后的反斜杠
- while s.endswith('\\'):
- s = s[:-1]
-
- return s
-
-
def largest_power_of_two_leq(value: int) -> int:
if value < 1:
return 0
diff --git a/tests/unittest/test_mfr_latex_utils.py b/tests/unittest/test_mfr_latex_utils.py
index f003242b..16175187 100644
--- a/tests/unittest/test_mfr_latex_utils.py
+++ b/tests/unittest/test_mfr_latex_utils.py
@@ -1,20 +1,12 @@
from __future__ import annotations
-# 可选依赖检测必须先于模型模块导入。
-# ruff: noqa: E402
-
-import pytest
-import numpy as np
from types import SimpleNamespace
-pytestmark = pytest.mark.torch
-
-torch = pytest.importorskip("torch")
-pytest.importorskip("transformers", minversion="5.10.1")
+import numpy as np
+import pytest
from mineru.model.mfr import utils as mfr_utils
from mineru.model.mfr.pp_formulanet.processors import UniMERNetDecode
-from mineru.model.mfr.unimernet.unimernet_hf.modeling_unimernet import UnimernetModel
@pytest.mark.parametrize(
@@ -44,22 +36,17 @@ def test_fix_mathring_font_arguments_repairs_multiple_occurrences() -> None:
@pytest.mark.parametrize(
- ("source", "pp_expected", "unimernet_expected"),
+ ("source", "expected"),
[
- (r"\left x \right y", r"\left x \right y", r"\left. x \right. y"),
- (r"\Dot{x}", r"\Dot{x}", r"\dot{x}"),
- (r"{x", r"{x", r"x"),
- (r"\upalpha + \emph{x}", r"\alpha + {x}", r"\alpha + {x}"),
+ (r"\left x \right y", r"\left x \right y"),
+ (r"\Dot{x}", r"\Dot{x}"),
+ (r"{x", r"{x"),
+ (r"\upalpha + \emph{x}", r"\alpha + {x}"),
],
)
-def test_model_specific_latex_repairs_keep_existing_differences(
- source: str,
- pp_expected: str,
- unimernet_expected: str,
-) -> None:
- """验证共享重构不会把任一模型的专属修复带入另一模型。"""
- assert mfr_utils.fix_pp_formulanet_latex(source) == pp_expected
- assert mfr_utils.fix_unimernet_latex(source) == unimernet_expected
+def test_pp_formulanet_latex_repairs_preserve_current_output(source: str, expected: str) -> None:
+ """验证 PP-FormulaNet 保留分隔符、命令和大括号的既有修复行为。"""
+ assert mfr_utils.fix_pp_formulanet_latex(source) == expected
def test_pp_formulanet_fix_latex_uses_shared_mathring_repair() -> None:
@@ -71,31 +58,6 @@ def test_pp_formulanet_fix_latex_uses_shared_mathring_repair() -> None:
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:
- """验证 UniMERNet 解码入口通过新名称应用共享修复。"""
-
- class _TokenizerStub:
- """为轻量解码入口返回固定 LaTeX 文本。"""
-
- @staticmethod
- def token2str(_token_ids: object) -> list[str]:
- """返回含未分组 mathring 参数的模型文本。"""
- return [r"R , { \mathring \mathrm { A } }"]
-
- class _ModelStub:
- """仅提供解码方法实际访问的 tokenizer。"""
-
- tokenizer = _TokenizerStub()
-
- result = UnimernetModel._decode_generate_outputs(
- _ModelStub(),
- torch.tensor([[0, 1, 2]]),
- return_full_result=False,
- )
-
- assert result == {"fixed_str": [r"R , { \mathring{\mathrm { A }} }"]}
-
-
def test_latex_rm_whitespace_name_is_removed() -> None:
"""验证旧职责不符名称不再作为兼容入口保留。"""
assert not hasattr(mfr_utils, "latex_rm_whitespace")
diff --git a/tests/unittest/test_opencv_boundaries.py b/tests/unittest/test_opencv_boundaries.py
index 6849353b..3f59beab 100644
--- a/tests/unittest/test_opencv_boundaries.py
+++ b/tests/unittest/test_opencv_boundaries.py
@@ -216,23 +216,6 @@ def test_table_classifier_tensor_keeps_channel_calculation_order() -> None:
_assert_model_reference(classifier.batch_preprocess([image]), "table_classifier", 1)
[email protected]("channels", [None, 1, 3])
-def test_unimer_crop_and_zero_padding_keep_shape(channels: int | None) -> None:
- """单通道和 RGB 公式图沿用冻结裁边、缩放和零填充像素。"""
- pytest.importorskip("torch")
- pytest.importorskip("torchvision")
- pytest.importorskip("transformers")
- from mineru.model.mfr.unimernet.unimernet_hf.unimer_swin.image_processing_unimer_swin import UnimerSwinImageProcessor
-
- shape = (17, 29) if channels is None else (17, 29, channels)
- image = np.full(shape, 255, dtype=np.uint8)
- image[3:15, 5:24] = 0
- _assert_model_reference(UnimerSwinImageProcessor.crop_margin_numpy(image), f"unimer:{channels}", 0)
- processor = UnimerSwinImageProcessor(image_size=(32, 64))
- _assert_model_reference(processor.prepare_input(image), f"unimer:{channels}", 1)
-
-
def test_unet_input_tensor_keeps_inplace_channel_exchange() -> None:
"""UNet 预处理使用独立冻结输入,验证通道交换和浮点减乘顺序。"""
from mineru.model.table.rec.unet_table.table_structure_unet import TSRUnet
diff --git a/tests/unittest/test_transformers5_models.py b/tests/unittest/test_transformers5_models.py
index 08dc5b8e..6f2e0794 100644
--- a/tests/unittest/test_transformers5_models.py
+++ b/tests/unittest/test_transformers5_models.py
@@ -1,11 +1,9 @@
-"""使用真实的小型网络验证 Transformers 5 的缓存、生成和权重加载契约。"""
+"""验证当前 PP-DocLayoutV2 在 Transformers 5 下的构图、设备加载和位置编码契约。"""
# 可选依赖检测必须先于模型模块导入。
# ruff: noqa: E402
from __future__ import annotations
-from pathlib import Path
-
import pytest
pytestmark = pytest.mark.torch
@@ -13,197 +11,7 @@ pytestmark = pytest.mark.torch
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:
@@ -221,6 +29,7 @@ def test_layout_configuration_constructs_the_inference_graph() -> None:
def test_layout_position_embedding_preserves_native_math(device: str) -> None:
"""CPU/MPS/XPU 包装保持官方位置编码数值,且没有新增或改名的模型权重。"""
from transformers.models.pp_doclayout_v2.modeling_pp_doclayout_v2 import PPDocLayoutV2SinePositionEmbedding
+
from mineru.model.layout.pp_doclayoutv2 import _CpuSinePositionEmbedding
if device == "mps" and not torch.backends.mps.is_available():
@@ -243,6 +52,7 @@ def test_layout_loader_adapts_position_embeddings_for_mps_and_xpu(monkeypatch: p
from unittest.mock import Mock
from transformers.models.pp_doclayout_v2.modeling_pp_doclayout_v2 import PPDocLayoutV2SinePositionEmbedding
+
from mineru.model.layout import pp_doclayoutv2 as layout
native = PPDocLayoutV2SinePositionEmbedding(embed_dim=16)
@@ -279,27 +89,3 @@ def test_layout_loader_adapts_position_embeddings_for_mps_and_xpu(monkeypatch: p
embedding_forward.assert_called_once_with(width=7, height=5, device=torch.device("cpu"), dtype=torch.float16)
else:
assert layer.position_embedding is native
-
-
[email protected]("device", ["cpu", "mps", "cuda"])
-def test_unimernet_stages_only_mps_weights_on_cpu(monkeypatch: pytest.MonkeyPatch, device: str) -> None:
- """MPS 在目标精度下经 CPU 物化后串行搬运,CPU/CUDA 保持直接加载。"""
- from types import SimpleNamespace
-
- from mineru.model.mfr.unimernet.Unimernet import UnimernetModel as Wrapper
- from mineru.model.mfr.unimernet.unimernet_hf import UnimernetModel as Model
-
- calls = []
- moves = []
- model = SimpleNamespace(to=lambda target: moves.append(str(target)), eval=lambda: None)
-
- def load(*args: object, **kwargs: object) -> object:
- """只记录公开加载协议,测试不分配真实设备或模型权重。"""
- calls.append(kwargs)
- return model
-
- monkeypatch.setattr(Model, "from_pretrained", load)
- Wrapper("local-checkpoint", device)
- assert str(calls[0]["device_map"][""]) == ("cpu" if device == "mps" else device)
- assert calls[0]["dtype"] == (torch.float32 if device == "cpu" else torch.float16)
- assert moves == (["mps"] if device == "mps" else [])