first commit
Some checks failed
Self-hosted runner (nightly-past-ci-caller) / Get number (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.11 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.10 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.9 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.8 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.7 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.6 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.5 (push) Has been cancelled
Self-hosted runner (benchmark) / Benchmark (aws-g5-4xlarge-cache) (push) Has been cancelled
Build documentation / build (push) Has been cancelled
Build documentation / build_other_lang (push) Has been cancelled
CodeQL Security Analysis / CodeQL Analysis (push) Has been cancelled
New model PR merged notification / Notify new model (push) Has been cancelled
PR CI / pr-ci (push) Has been cancelled
Slow tests on important models (on Push - A10) / Get all modified files (push) Has been cancelled
Secret Leaks / trufflehog (push) Has been cancelled
Update Transformers metadata / build_and_package (push) Has been cancelled
Slow tests on important models (on Push - A10) / Model CI (push) Has been cancelled
Check Tiny Models / Check tiny models (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Model CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Pipeline CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Example CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / DeepSpeed CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI - Flash Attn / Setup (push) Has been cancelled
Nvidia CI - Flash Attn / Model CI (push) Has been cancelled
Nvidia CI / Setup (push) Has been cancelled
Nvidia CI / Model CI (push) Has been cancelled
Nvidia CI / Torch pipeline CI (push) Has been cancelled
Nvidia CI / Example CI (push) Has been cancelled
Nvidia CI / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI / DeepSpeed CI (push) Has been cancelled
Nvidia CI / Quantization CI (push) Has been cancelled
Nvidia CI / Kernels CI (push) Has been cancelled
Doctests / Setup (push) Has been cancelled
Doctests / Call doctest jobs (push) Has been cancelled
Doctests / Send results to webhook (push) Has been cancelled
Extras Smoke Test / Get supported Python versions (push) Has been cancelled
Extras Smoke Test / Test extras on Python ${{ matrix.python-version }} (push) Has been cancelled
Extras Smoke Test / Check Slack token availability (push) Has been cancelled
Extras Smoke Test / Notify failures to Slack (push) Has been cancelled
Self-hosted runner (AMD scheduled CI caller) / Trigger Scheduled AMD CI (push) Has been cancelled
Stale Bot / Close Stale Issues (push) Has been cancelled

This commit is contained in:
陈赣
2026-06-05 16:53:03 +08:00
commit 06f1fd69a6
6047 changed files with 1895387 additions and 0 deletions

View File

@@ -0,0 +1,194 @@
# Copyright 2026 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.
import unittest
import numpy as np
from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision
from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
if is_vision_available():
from PIL import Image
if is_torch_available():
import torch
class PPOCRV5ServerDetImageProcessingTester:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=10,
max_resolution=400,
limit_side_len=960,
limit_type="max",
max_side_limit=4000,
do_resize=True,
size=None,
do_rescale=True,
rescale_factor=1 / 255,
do_normalize=True,
image_mean=[0.485, 0.456, 0.406],
image_std=[0.229, 0.224, 0.225],
):
size = size if size is not None else {"height": 512, "width": 512}
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.min_resolution = min_resolution
self.max_resolution = max_resolution
self.limit_side_len = limit_side_len
self.limit_type = limit_type
self.max_side_limit = max_side_limit
self.do_resize = do_resize
self.size = size
self.do_rescale = do_rescale
self.rescale_factor = rescale_factor
self.do_normalize = do_normalize
self.image_mean = image_mean
self.image_std = image_std
def prepare_image_processor_dict(self):
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
"keep_aspect_ratio": False,
"do_pad": False,
}
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
return prepare_image_inputs(
batch_size=self.batch_size,
num_channels=self.num_channels,
min_resolution=self.min_resolution,
max_resolution=self.max_resolution,
equal_resolution=equal_resolution,
numpify=numpify,
torchify=torchify,
)
def get_expected_value(self, image_inputs):
image = image_inputs[0]
if isinstance(image, Image.Image):
width, height = image.size
elif isinstance(image, np.ndarray):
height, width = image.shape[0], image.shape[1]
else:
height, width = image.shape[1], image.shape[2]
if max(height, width) > self.limit_side_len:
ratio = float(self.limit_side_len) / max(height, width)
else:
ratio = 1.0
resize_height = int(height * ratio)
resize_width = int(width * ratio)
if self.max_side_limit is not None and max(resize_height, resize_width) > self.max_side_limit:
ratio = float(self.max_side_limit) / max(resize_height, resize_width)
resize_height = int(resize_height * ratio)
resize_width = int(resize_width * ratio)
resize_height = max(int(round(resize_height / 32) * 32), 32)
resize_width = max(int(round(resize_width / 32) * 32), 32)
if resize_height == height and resize_width == width:
return resize_height, resize_width
if resize_width <= 0 or resize_height <= 0:
return None, None
return resize_height, resize_width
def expected_output_image_shape(self, images):
height, width = self.get_expected_value(images)
return self.num_channels, height, width
@require_torch
@require_vision
class PPOCRV5ServerDetImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
def setUp(self):
super().setUp()
self.image_processor_tester = PPOCRV5ServerDetImageProcessingTester(self)
@property
def image_processor_dict(self):
return self.image_processor_tester.prepare_image_processor_dict()
# PPOCRV5ServerDet cant stack the images into a batch because the image processor resizes them adaptively, leading to inconsistent output sizes."
# Skip Test batched
def test_call_pytorch(self):
for image_processing_class in self.image_processing_classes.values():
# Initialize image_processing
image_processing = image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
for image in image_inputs:
self.assertIsInstance(image, torch.Tensor)
# Test not batched input
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))
# PPOCRV5ServerDet cant stack the images into a batch because the image processor resizes them adaptively, leading to inconsistent output sizes.
# Skip Test batched
def test_call_numpy(self):
for image_processing_class in self.image_processing_classes.values():
# Initialize image_processing
image_processing = image_processing_class(**self.image_processor_dict)
# create random numpy tensors
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
for image in image_inputs:
self.assertIsInstance(image, np.ndarray)
# Test not batched input
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))
# PPOCRV5ServerDet cant stack the images into a batch because the image processor resizes them adaptively, leading to inconsistent output sizes.
# Skip Test batched
def test_call_pil(self):
for image_processing_class in self.image_processing_classes.values():
# Initialize image_processing
image_processing = image_processing_class(**self.image_processor_dict)
# create random PIL images
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
for image in image_inputs:
self.assertIsInstance(image, Image.Image)
# Test not batched input
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))
@unittest.skip(reason="PPOCRV5ServerDetImageProcessor does not support 4 channel images yet")
def test_call_numpy_4_channels():
pass

View File

@@ -0,0 +1,311 @@
# coding = utf-8
# Copyright 2026 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.
"""Testing suite for the PP-OCRV5ServerDet model."""
import inspect
import unittest
from parameterized import parameterized
from transformers import (
PPOCRV5ServerDetConfig,
PPOCRV5ServerDetForObjectDetection,
PPOCRV5ServerDetImageProcessor,
PPOCRV5ServerDetModel,
is_torch_available,
is_vision_available,
)
from transformers.image_utils import load_image
from transformers.testing_utils import (
require_cv2,
require_torch,
require_torch_accelerator,
require_vision,
slow,
torch_device,
)
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
from ...test_processing_common import url_to_local_path
if is_torch_available():
import torch
class PPOCRV5ServerDetModelTester:
def __init__(
self,
parent,
batch_size=3,
image_size=128,
num_channels=3,
num_stages=5,
is_training=False,
scale=1.0,
divisor=16,
):
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.is_training = is_training
self.num_stages = num_stages
self.scale = scale
self.divisor = divisor
def prepare_config_and_inputs_for_common(self):
config, pixel_values = self.prepare_config_and_inputs()
inputs_dict = {"pixel_values": pixel_values}
return config, inputs_dict
def prepare_config_and_inputs(self):
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
config = self.get_config()
return config, pixel_values
def get_config(self) -> PPOCRV5ServerDetConfig:
# Minimal backbone config for fast tests (< 1M params for test_model_is_small)
backbone_config = {
"model_type": "hgnet_v2",
"out_features": ["stage1", "stage2", "stage3", "stage4"],
"out_indices": [1, 2, 3, 4],
"depths": [1, 1, 1, 1],
"hidden_sizes": [16, 32, 64, 128],
"stage_in_channels": [16, 16, 32, 64],
"stage_mid_channels": [16, 16, 32, 64],
"stage_out_channels": [16, 32, 64, 128],
"stage_num_blocks": [1, 1, 1, 1],
"stage_downsample": [False, True, True, True],
"stage_light_block": [False, False, True, True],
"stage_kernel_size": [3, 3, 5, 5],
"stage_numb_of_layers": [1, 1, 1, 1],
"stem_channels": [3, 8, 16],
"embedding_size": 16,
}
intraclass_block_config = {
"reduce_channel": [1, 1, 0],
"return_channel": [1, 1, 0],
"vertical_long_to_small_conv_longratio": [[7, 1], [1, 1], [3, 0]],
"vertical_long_to_small_conv_midratio": [[5, 1], [1, 1], [2, 0]],
"vertical_long_to_small_conv_shortratio": [[3, 1], [1, 1], [1, 0]],
"horizontal_small_to_long_conv_longratio": [[1, 7], [1, 1], [0, 3]],
"horizontal_small_to_long_conv_midratio": [[1, 5], [1, 1], [0, 2]],
"horizontal_small_to_long_conv_shortratio": [[1, 3], [1, 1], [0, 1]],
"symmetric_conv_long_longratio": [[7, 7], [1, 1], [3, 3]],
"symmetric_conv_long_midratio": [[5, 5], [1, 1], [2, 2]],
"symmetric_conv_long_shortratio": [[3, 3], [1, 1], [1, 1]],
}
config = PPOCRV5ServerDetConfig(
backbone_config=backbone_config,
interpolate_mode="nearest",
neck_out_channels=32,
reduce_factor=2,
intraclass_block_number=4,
intraclass_block_config=intraclass_block_config,
mode="large",
scale_factor=2,
scale_factor_list=[1, 2, 4, 8],
hidden_act="relu",
kernel_list=[3, 2, 2],
)
return config
def create_and_check_pp_ocrv5_server_det_object_detection(self, config, pixel_values):
model = PPOCRV5ServerDetForObjectDetection(config=config)
model.to(torch_device)
model.eval()
result = model(pixel_values)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 1, self.image_size, self.image_size))
@require_torch
class PPOCRV5ServerDetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (PPOCRV5ServerDetModel, PPOCRV5ServerDetForObjectDetection) if is_torch_available() else ()
pipeline_model_mapping = {"object-detection": PPOCRV5ServerDetForObjectDetection} if is_torch_available() else {}
test_resize_embeddings = False
has_attentions = False
def setUp(self):
self.model_tester = PPOCRV5ServerDetModelTester(
self,
batch_size=3,
is_training=False,
image_size=128,
)
self.model_tester.parent = self
self.config_tester = ConfigTester(
self,
config_class=PPOCRV5ServerDetConfig,
has_text_modality=False,
common_properties=[],
)
def test_config(self):
# Skip create_and_test_config_with_num_labels: PP-OCRV5 has fixed single class (text)
self.config_tester.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_from_and_save_pretrained_subfolder()
self.config_tester.create_and_test_config_from_and_save_pretrained_composite()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
self.config_tester.create_and_test_config_from_pretrained_custom_kwargs()
def test_pp_ocrv5_server_det_object_detection(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_pp_ocrv5_server_det_object_detection(*config_and_inputs)
@unittest.skip(reason="PPOCRV5ServerDet does not support input and output embeddings")
def test_model_get_set_embeddings(self):
pass
def test_hidden_states_output(self):
# PP-OCRV5 uses HGNetV2 backbone: hidden_states = (embedding, stage1, ..., stageN) = num_stages + 1
config = self.model_tester.get_config()
num_expected_hidden_states = len(config.backbone_config.depths) + 1
def check_hidden_states_output(inputs_dict, config, model_class):
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
hidden_states = outputs.hidden_states
self.assertIsNotNone(hidden_states)
self.assertEqual(len(hidden_states), num_expected_hidden_states)
# First hidden state (embedding output) is 4x downsampled
self.assertListEqual(
list(hidden_states[0].shape[-2:]),
[self.model_tester.image_size // 4, self.model_tester.image_size // 4],
)
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
inputs_dict["output_hidden_states"] = True
check_hidden_states_output(inputs_dict.copy(), config, model_class)
# Check that output_hidden_states also works via config (including backbone subconfig)
del inputs_dict["output_hidden_states"]
config.output_hidden_states = True
if config.backbone_config is not None:
config.backbone_config.output_hidden_states = True
check_hidden_states_output(inputs_dict.copy(), config, model_class)
def test_forward_signature(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
signature = inspect.signature(model.forward)
arg_names = [*signature.parameters.keys()]
expected_arg_names = ["pixel_values"]
self.assertListEqual(arg_names[:1], expected_arg_names)
@parameterized.expand(["float32", "float16", "bfloat16"])
@require_torch_accelerator
@slow
def test_inference_with_different_dtypes(self, dtype_str):
dtype = {
"float32": torch.float32,
"float16": torch.float16,
"bfloat16": torch.bfloat16,
}[dtype_str]
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
model.to(torch_device).to(dtype)
model.eval()
for key, tensor in inputs_dict.items():
if tensor.dtype == torch.float32:
inputs_dict[key] = tensor.to(dtype)
with torch.no_grad():
_ = model(**self._prepare_for_class(inputs_dict, model_class))
@require_torch
@require_vision
@require_cv2
@slow
class PPOCRV5ServerDetModelIntegrationTest(unittest.TestCase):
def setUp(self):
model_path = "PaddlePaddle/PP-OCRv5_server_det_safetensors"
self.model = PPOCRV5ServerDetForObjectDetection.from_pretrained(model_path).to(torch_device)
self.image_processor = (
PPOCRV5ServerDetImageProcessor.from_pretrained(model_path) if is_vision_available() else None
)
img_url = url_to_local_path(
"https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_001.png"
)
self.image = load_image(img_url)
def test_inference_object_detection_head(self):
inputs = self.image_processor(images=self.image, return_tensors="pt").to(torch_device)
bs, c, h, w = inputs["pixel_values"].shape
with torch.no_grad():
outputs = self.model(**inputs)
results = self.image_processor.post_process_object_detection(outputs, target_sizes=inputs["target_sizes"])
expected_shape_logits = torch.Size((bs, c // 3, h, w))
expected_logits = torch.tensor(
[
[0.0004, 0.0003, 0.0002],
[0.0003, 0.0002, 0.0002],
[0.0006, 0.0003, 0.0003],
],
device=torch_device,
)
self.assertEqual(outputs.last_hidden_state.shape, expected_shape_logits)
torch.testing.assert_close(outputs.last_hidden_state[0, 0, :3, :3], expected_logits, rtol=2e-4, atol=2e-4)
expected_shape_boxes = torch.Size((4, 4, 2))
expected_boxes = torch.tensor(
[
[[76, 550], [399, 538], [400, 575], [77, 587]],
[[14, 505], [517, 484], [519, 532], [16, 553]],
[[193, 452], [401, 443], [403, 483], [195, 492]],
[[32, 406], [488, 384], [491, 434], [34, 456]],
],
dtype=torch.short,
device=torch_device,
)
self.assertEqual(results[0]["boxes"].shape, expected_shape_boxes)
torch.testing.assert_close(results[0]["boxes"], expected_boxes, rtol=2e-2, atol=2e-2)
expected_scores = torch.tensor([0.9023, 0.8941, 0.8937, 0.8781], device=torch_device)
self.assertEqual(results[0]["scores"].shape, (4,))
torch.testing.assert_close(results[0]["scores"], expected_scores, rtol=2e-2, atol=2e-2)
self.assertEqual(results[0]["labels"].shape, (4,))
self.assertTrue((results[0]["labels"] == 0).all()) # Single class: text