

import colorsys
import io

import cva
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import numpy as np
import torch
from matplotlib.backends.backend_agg import FigureCanvasAgg

from utils import img_tensorize


SCREAMING_SNAKE_CASE						:Union[str, Any]      =			1000






class 		__magic_name__ :






     def __init__(							self						,		_lowercase						,		_lowercase=1.2						,		_lowercase="g"						,		_lowercase=0.5						,		_lowercase="-"						,		_lowercase="test_out.jpg"						,		_lowercase=True						,		_lowercase=False						,		_lowercase=None						,		_lowercase=None						,		_lowercase=0.7						,		)->			Dict:
         if isinstance(_lowercase						,		torch.Tensor     ):
             UpperCamelCase_          =		img.numpy().astype("np.uint8"     )
         if isinstance(_lowercase						,		_lowercase     ):
             UpperCamelCase_          =		img_tensorize(_lowercase     )
         assert isinstance(_lowercase						,		np.ndarray     )

         UpperCamelCase_   ,    UpperCamelCase_          =		img.shape[1], img.shape[0]
         UpperCamelCase_          =		mplfigure.Figure(frameon=_lowercase     )
         UpperCamelCase_          =		fig.get_dpi()
         UpperCamelCase_          =		(width * scale + 1e-2) / dpi
         UpperCamelCase_          =		(height * scale + 1e-2) / dpi
         fig.set_size_inches(_lowercase						,		_lowercase     )
         UpperCamelCase_          =		fig.add_axes([0.0, 0.0, 1.0, 1.0]     )
         ax.axis("off"     )
         ax.set_xlim(0.0						,		_lowercase     )
         ax.set_ylim(_lowercase     )

         UpperCamelCase_          =		saveas
         UpperCamelCase_          =		rgb
         UpperCamelCase_          =		pynb
         UpperCamelCase_          =		img
         UpperCamelCase_          =		edgecolor
         UpperCamelCase_          =		0.5
         UpperCamelCase_          =		linestyle
         UpperCamelCase_          =		int(np.sqrt(min(_lowercase						,		_lowercase     )     ) * scale // 3     )
         UpperCamelCase_          =		width
         UpperCamelCase_          =		height
         UpperCamelCase_          =		scale
         UpperCamelCase_          =		fig
         UpperCamelCase_          =		ax
         UpperCamelCase_          =		pad
         UpperCamelCase_          =		idaobj
         UpperCamelCase_          =		idaattr
         UpperCamelCase_          =		FigureCanvasAgg(_lowercase     )






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase=None     )->			List[str]:
         if color is None:
             UpperCamelCase_          =		self.edgecolor
         ((UpperCamelCase_)   ,    (UpperCamelCase_)   ,    (UpperCamelCase_)   ,    (UpperCamelCase_))          =		box
         UpperCamelCase_          =		xa - xa
         UpperCamelCase_          =		ya - ya
         self.ax.add_patch(
             mpl.patches.Rectangle(
                 (xa, ya)						,		_lowercase						,		_lowercase						,		fill=_lowercase						,		edgecolor=_lowercase						,		linewidth=self.font_size // 3						,		alpha=self.alpha						,		linestyle=self.linestyle						,		)     )






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase=None						,		_lowercase=None						,		_lowercase=None						,		_lowercase=None     )->			Any:
         if len(boxes.shape     ) > 2:
             UpperCamelCase_          =		boxes[0]
         if len(obj_ids.shape     ) > 1:
             UpperCamelCase_          =		obj_ids[0]
         if len(obj_scores.shape     ) > 1:
             UpperCamelCase_          =		obj_scores[0]
         if len(attr_ids.shape     ) > 1:
             UpperCamelCase_          =		attr_ids[0]
         if len(attr_scores.shape     ) > 1:
             UpperCamelCase_          =		attr_scores[0]
         if isinstance(_lowercase						,		torch.Tensor     ):
             UpperCamelCase_          =		boxes.numpy()
         if isinstance(_lowercase						,		_lowercase     ):
             UpperCamelCase_          =		np.array(_lowercase     )
         assert isinstance(_lowercase						,		np.ndarray     )
         UpperCamelCase_          =		np.prod(boxes[:, 2:] - boxes[:, :2]						,		axis=1     )
         UpperCamelCase_          =		np.argsort(-areas     ).tolist()
         UpperCamelCase_          =		boxes[sorted_idxs] if boxes is not None else None
         UpperCamelCase_          =		obj_ids[sorted_idxs] if obj_ids is not None else None
         UpperCamelCase_          =		obj_scores[sorted_idxs] if obj_scores is not None else None
         UpperCamelCase_          =		attr_ids[sorted_idxs] if attr_ids is not None else None
         UpperCamelCase_          =		attr_scores[sorted_idxs] if attr_scores is not None else None

         UpperCamelCase_          =		[self._random_color(maximum=1     ) for _ in range(len(_lowercase     )     )]
         UpperCamelCase_          =		[assigned_colors[idx] for idx in sorted_idxs]
         if obj_ids is not None:
             UpperCamelCase_          =		self._create_text_labels_attr(_lowercase						,		_lowercase						,		_lowercase						,		_lowercase     )
             for i in range(len(_lowercase     )     ):
                 UpperCamelCase_          =		assigned_colors[i]
                 self.add_box(boxes[i]						,		_lowercase     )
                 self.draw_labels(labels[i]						,		boxes[i]						,		_lowercase     )






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase						,		_lowercase     )->			Union[str, Any]:
         UpperCamelCase_   ,    UpperCamelCase_   ,    UpperCamelCase_   ,    UpperCamelCase_          =		box
         UpperCamelCase_          =		(xa, ya)
         UpperCamelCase_          =		(ya - ya) * (xa - xa)
         UpperCamelCase_          =		_SMALL_OBJ * self.scale
         if instance_area < small or ya - ya < 40 * self.scale:
             if ya >= self.height - 5:
                 UpperCamelCase_          =		(xa, ya)
             else:
                 UpperCamelCase_          =		(xa, ya)

         UpperCamelCase_          =		(ya - ya) / np.sqrt(self.height * self.width     )
         UpperCamelCase_          =		self._change_color_brightness(_lowercase						,		brightness_factor=0.7     )
         UpperCamelCase_          =		np.clip((height_ratio - 0.02) / 0.08 + 1						,		1.2						,		2     )
         font_size *= 0.75 * self.font_size

         self.draw_text(
             text=_lowercase						,		position=_lowercase						,		color=_lowercase						,		)






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase						,		_lowercase="g"						,		_lowercase="left"						,		)->			str:
         UpperCamelCase_          =		0
         UpperCamelCase_          =		self.font_size
         UpperCamelCase_          =		np.maximum(list(mplc.to_rgb(_lowercase     )     )						,		0.2     )
         UpperCamelCase_          =		max(0.8						,		np.max(_lowercase     )     )
         UpperCamelCase_          =		{
             "facecolor": "black",
             "alpha": self.alpha,
             "pad": self.pad,
             "edgecolor": "none",
         }
         UpperCamelCase_   ,    UpperCamelCase_          =		position
         self.ax.text(
             _lowercase						,		_lowercase						,		_lowercase						,		size=font_size * self.scale						,		family="sans-serif"						,		bbox=_lowercase						,		verticalalignment="top"						,		horizontalalignment=_lowercase						,		color=_lowercase						,		zorder=10						,		rotation=_lowercase						,		)






     def      UpperCAmelCase_							(							self						,		_lowercase=None     )->			int:
         if saveas is None:
             UpperCamelCase_          =		self.saveas
         if saveas.lower().endswith(".jpg"     ) or saveas.lower().endswith(".png"     ):
             cva.imwrite(
                 _lowercase						,		self._get_buffer()[:, :, ::-1]						,		)
         else:
             self.fig.savefig(_lowercase     )






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase     )->			Tuple:
         UpperCamelCase_          =		[self.idaobj[i] for i in classes]
         UpperCamelCase_          =		[self.idaattr[i] for i in attr_classes]
         UpperCamelCase_          =		[
             F"{label} {score:.2f} {attr} {attr_score:.2f}"
             for label, score, attr, attr_score in zip(_lowercase						,		_lowercase						,		_lowercase						,		_lowercase     )
         ]
         return labels






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase     )->			int:
         UpperCamelCase_          =		[self.idaobj[i] for i in classes]
         if scores is not None:
             if labels is None:
                 UpperCamelCase_          =		["{:.0f}%".format(s * 100     ) for s in scores]
             else:
                 UpperCamelCase_          =		["{} {:.0f}%".format(_lowercase						,		s * 100     ) for li, s in zip(_lowercase						,		_lowercase     )]
         return labels






     def      UpperCAmelCase_							(							self						,		_lowercase=255     )->			Optional[Any]:
         UpperCamelCase_          =		np.random.randint(0						,		len(_COLORS     )     )
         UpperCamelCase_          =		_COLORS[idx] * maximum
         if not self.rgb:
             UpperCamelCase_          =		ret[::-1]
         return ret






     def      UpperCAmelCase_							(							self     )->			int:
         if not self.pynb:
             UpperCamelCase_   ,    UpperCamelCase_          =		self.canvas.print_to_buffer()
             if (width, height) != (self.width, self.height):
                 UpperCamelCase_          =		cva.resize(self.img						,		(width, height)     )
             else:
                 UpperCamelCase_          =		self.img
         else:
             UpperCamelCase_          =		io.BytesIO()  # works for cairo backend
             self.canvas.print_rgba(_lowercase     )
             UpperCamelCase_   ,    UpperCamelCase_          =		self.width, self.height
             UpperCamelCase_          =		buf.getvalue()
             UpperCamelCase_          =		self.img

         UpperCamelCase_          =		np.frombuffer(_lowercase						,		dtype="uint8"     )
         UpperCamelCase_          =		buffer.reshape(_lowercase						,		_lowercase						,		4     )
         UpperCamelCase_   ,    UpperCamelCase_          =		np.split(_lowercase						,		[3]						,		axis=2     )

         try:
             import numexpr as ne  # fuse them with numexpr

             UpperCamelCase_          =		ne.evaluate("img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)"     )
         except ImportError:
             UpperCamelCase_          =		alpha.astype("float32"     ) / 255.0
             UpperCamelCase_          =		img * (1 - alpha) + rgb * alpha

         return visualized_image.astype("uint8"     )






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase     )->			List[str]:
         assert brightness_factor >= -1.0 and brightness_factor <= 1.0
         UpperCamelCase_          =		mplc.to_rgb(_lowercase     )
         UpperCamelCase_          =		colorsys.rgb_to_hls(*mplc.to_rgb(_lowercase     )     )
         UpperCamelCase_          =		polygon_color[1] + (brightness_factor * polygon_color[1])
         UpperCamelCase_          =		0.0 if modified_lightness < 0.0 else modified_lightness
         UpperCamelCase_          =		1.0 if modified_lightness > 1.0 else modified_lightness
         UpperCamelCase_          =		colorsys.hls_to_rgb(polygon_color[0]						,		_lowercase						,		polygon_color[2]     )
         return modified_color
SCREAMING_SNAKE_CASE						:str      =			(
    np.array(
        [
            0.0_0_0,
            0.4_4_7,
            0.7_4_1,
            0.8_5_0,
            0.3_2_5,
            0.0_9_8,
            0.9_2_9,
            0.6_9_4,
            0.1_2_5,
            0.4_9_4,
            0.1_8_4,
            0.5_5_6,
            0.4_6_6,
            0.6_7_4,
            0.1_8_8,
            0.3_0_1,
            0.7_4_5,
            0.9_3_3,
            0.6_3_5,
            0.0_7_8,
            0.1_8_4,
            0.3_0_0,
            0.3_0_0,
            0.3_0_0,
            0.6_0_0,
            0.6_0_0,
            0.6_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.7_4_9,
            0.7_4_9,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.6_6_7,
            0.0_0_0,
            1.0_0_0,
            0.3_3_3,
            0.3_3_3,
            0.0_0_0,
            0.3_3_3,
            0.6_6_7,
            0.0_0_0,
            0.3_3_3,
            1.0_0_0,
            0.0_0_0,
            0.6_6_7,
            0.3_3_3,
            0.0_0_0,
            0.6_6_7,
            0.6_6_7,
            0.0_0_0,
            0.6_6_7,
            1.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.3_3_3,
            0.0_0_0,
            1.0_0_0,
            0.6_6_7,
            0.0_0_0,
            1.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.3_3_3,
            0.5_0_0,
            0.0_0_0,
            0.6_6_7,
            0.5_0_0,
            0.0_0_0,
            1.0_0_0,
            0.5_0_0,
            0.3_3_3,
            0.0_0_0,
            0.5_0_0,
            0.3_3_3,
            0.3_3_3,
            0.5_0_0,
            0.3_3_3,
            0.6_6_7,
            0.5_0_0,
            0.3_3_3,
            1.0_0_0,
            0.5_0_0,
            0.6_6_7,
            0.0_0_0,
            0.5_0_0,
            0.6_6_7,
            0.3_3_3,
            0.5_0_0,
            0.6_6_7,
            0.6_6_7,
            0.5_0_0,
            0.6_6_7,
            1.0_0_0,
            0.5_0_0,
            1.0_0_0,
            0.0_0_0,
            0.5_0_0,
            1.0_0_0,
            0.3_3_3,
            0.5_0_0,
            1.0_0_0,
            0.6_6_7,
            0.5_0_0,
            1.0_0_0,
            1.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.3_3_3,
            1.0_0_0,
            0.0_0_0,
            0.6_6_7,
            1.0_0_0,
            0.0_0_0,
            1.0_0_0,
            1.0_0_0,
            0.3_3_3,
            0.0_0_0,
            1.0_0_0,
            0.3_3_3,
            0.3_3_3,
            1.0_0_0,
            0.3_3_3,
            0.6_6_7,
            1.0_0_0,
            0.3_3_3,
            1.0_0_0,
            1.0_0_0,
            0.6_6_7,
            0.0_0_0,
            1.0_0_0,
            0.6_6_7,
            0.3_3_3,
            1.0_0_0,
            0.6_6_7,
            0.6_6_7,
            1.0_0_0,
            0.6_6_7,
            1.0_0_0,
            1.0_0_0,
            1.0_0_0,
            0.0_0_0,
            1.0_0_0,
            1.0_0_0,
            0.3_3_3,
            1.0_0_0,
            1.0_0_0,
            0.6_6_7,
            1.0_0_0,
            0.3_3_3,
            0.0_0_0,
            0.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.0_0_0,
            0.6_6_7,
            0.0_0_0,
            0.0_0_0,
            0.8_3_3,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.1_6_7,
            0.0_0_0,
            0.0_0_0,
            0.3_3_3,
            0.0_0_0,
            0.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.0_0_0,
            0.6_6_7,
            0.0_0_0,
            0.0_0_0,
            0.8_3_3,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.1_6_7,
            0.0_0_0,
            0.0_0_0,
            0.3_3_3,
            0.0_0_0,
            0.0_0_0,
            0.5_0_0,
            0.0_0_0,
            0.0_0_0,
            0.6_6_7,
            0.0_0_0,
            0.0_0_0,
            0.8_3_3,
            0.0_0_0,
            0.0_0_0,
            1.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.0_0_0,
            0.1_4_3,
            0.1_4_3,
            0.1_4_3,
            0.8_5_7,
            0.8_5_7,
            0.8_5_7,
            1.0_0_0,
            1.0_0_0,
            1.0_0_0,
        ]
    )
    .astype(np.floataa)
    .reshape(-1, 3)
)



import collections
import inspect
import unittest

from transformers import DonutSwinConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import DonutSwinModel
 from transformers.models.donut.modeling_donut_swin import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST






class 		__magic_name__ :






     def __init__(							self						,		_lowercase						,		_lowercase=13						,		_lowercase=32						,		_lowercase=2						,		_lowercase=3						,		_lowercase=16						,		_lowercase=[1, 2, 1]						,		_lowercase=[2, 2, 4]						,		_lowercase=2						,		_lowercase=2.0						,		_lowercase=True						,		_lowercase=0.0						,		_lowercase=0.0						,		_lowercase=0.1						,		_lowercase="gelu"						,		_lowercase=False						,		_lowercase=True						,		_lowercase=0.02						,		_lowercase=1e-5						,		_lowercase=True						,		_lowercase=None						,		_lowercase=True						,		_lowercase=10						,		_lowercase=8						,		)->			Tuple:
         UpperCamelCase_          =		parent
         UpperCamelCase_          =		batch_size
         UpperCamelCase_          =		image_size
         UpperCamelCase_          =		patch_size
         UpperCamelCase_          =		num_channels
         UpperCamelCase_          =		embed_dim
         UpperCamelCase_          =		depths
         UpperCamelCase_          =		num_heads
         UpperCamelCase_          =		window_size
         UpperCamelCase_          =		mlp_ratio
         UpperCamelCase_          =		qkv_bias
         UpperCamelCase_          =		hidden_dropout_prob
         UpperCamelCase_          =		attention_probs_dropout_prob
         UpperCamelCase_          =		drop_path_rate
         UpperCamelCase_          =		hidden_act
         UpperCamelCase_          =		use_absolute_embeddings
         UpperCamelCase_          =		patch_norm
         UpperCamelCase_          =		layer_norm_eps
         UpperCamelCase_          =		initializer_range
         UpperCamelCase_          =		is_training
         UpperCamelCase_          =		scope
         UpperCamelCase_          =		use_labels
         UpperCamelCase_          =		type_sequence_label_size
         UpperCamelCase_          =		encoder_stride






     def      UpperCAmelCase_							(							self     )->			Dict:
         UpperCamelCase_          =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

         UpperCamelCase_          =		None
         if self.use_labels:
             UpperCamelCase_          =		ids_tensor([self.batch_size]						,		self.type_sequence_label_size     )

         UpperCamelCase_          =		self.get_config()

         return config, pixel_values, labels






     def      UpperCAmelCase_							(							self     )->			Union[str, Any]:
         return DonutSwinConfig(
             image_size=self.image_size						,		patch_size=self.patch_size						,		num_channels=self.num_channels						,		embed_dim=self.embed_dim						,		depths=self.depths						,		num_heads=self.num_heads						,		window_size=self.window_size						,		mlp_ratio=self.mlp_ratio						,		qkv_bias=self.qkv_bias						,		hidden_dropout_prob=self.hidden_dropout_prob						,		attention_probs_dropout_prob=self.attention_probs_dropout_prob						,		drop_path_rate=self.drop_path_rate						,		hidden_act=self.hidden_act						,		use_absolute_embeddings=self.use_absolute_embeddings						,		path_norm=self.patch_norm						,		layer_norm_eps=self.layer_norm_eps						,		initializer_range=self.initializer_range						,		encoder_stride=self.encoder_stride						,		)






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase						,		_lowercase     )->			Optional[Any]:
         UpperCamelCase_          =		DonutSwinModel(config=_lowercase     )
         model.to(_lowercase     )
         model.eval()
         UpperCamelCase_          =		model(_lowercase     )

         UpperCamelCase_          =		((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths     ) - 1))
         UpperCamelCase_          =		int(config.embed_dim * 2 ** (len(config.depths     ) - 1)     )

         self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, expected_seq_len, expected_dim)     )






     def      UpperCAmelCase_							(							self     )->			Tuple:
         UpperCamelCase_          =		self.prepare_config_and_inputs()
         (
             (
             UpperCamelCase_
         )   ,    (
             UpperCamelCase_
         )   ,    (
             UpperCamelCase_
         )   ,    
         )          =		config_and_inputs
         UpperCamelCase_          =		{"pixel_values": pixel_values}
         return config, inputs_dict






@require_torch
class 		__magic_name__ (				snake_case       ,	snake_case       ,	unittest.TestCase							):
     UpperCamelCase_     :List[str]									=	(DonutSwinModel,) if is_torch_available() else ()
     UpperCamelCase_     :Optional[Any]									=	{"""feature-extraction""": DonutSwinModel} if is_torch_available() else {}
     UpperCamelCase_     :Any									=	True

     UpperCamelCase_     :Tuple									=	False
     UpperCamelCase_     :List[str]									=	False
     UpperCamelCase_     :List[str]									=	False






     def      UpperCAmelCase_							(							self     )->			Union[str, Any]:
         UpperCamelCase_          =		DonutSwinModelTester(self     )
         UpperCamelCase_          =		ConfigTester(self						,		config_class=_lowercase						,		embed_dim=37     )






     def      UpperCAmelCase_							(							self     )->			Optional[int]:
         self.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_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()






     def      UpperCAmelCase_							(							self     )->			Optional[int]:
         return






     def      UpperCAmelCase_							(							self     )->			Tuple:
         UpperCamelCase_          =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowercase     )






     def      UpperCAmelCase_							(							self     )->			int:
         # DonutSwin does not use inputs_embeds
         pass






     def      UpperCAmelCase_							(							self     )->			Union[str, Any]:
         UpperCamelCase_   ,    UpperCamelCase_          =		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             UpperCamelCase_          =		model_class(_lowercase     )
             self.assertIsInstance(model.get_input_embeddings()						,		(nn.Module)     )
             UpperCamelCase_          =		model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(_lowercase						,		nn.Linear     )     )






     def      UpperCAmelCase_							(							self     )->			Union[str, Any]:
         UpperCamelCase_   ,    UpperCamelCase_          =		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             UpperCamelCase_          =		model_class(_lowercase     )
             UpperCamelCase_          =		inspect.signature(model.forward     )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             UpperCamelCase_          =		[*signature.parameters.keys()]

             UpperCamelCase_          =		["pixel_values"]
             self.assertListEqual(arg_names[:1]						,		_lowercase     )






     def      UpperCAmelCase_							(							self     )->			List[Any]:
         UpperCamelCase_   ,    UpperCamelCase_          =		self.model_tester.prepare_config_and_inputs_for_common()
         UpperCamelCase_          =		True

         for model_class in self.all_model_classes:
             UpperCamelCase_          =		True
             UpperCamelCase_          =		False
             UpperCamelCase_          =		True
             UpperCamelCase_          =		model_class(_lowercase     )
             model.to(_lowercase     )
             model.eval()
             with torch.no_grad():
                 UpperCamelCase_          =		model(**self._prepare_for_class(_lowercase						,		_lowercase     )     )
             UpperCamelCase_          =		outputs.attentions
             UpperCamelCase_          =		len(self.model_tester.depths     )
             self.assertEqual(len(_lowercase     )						,		_lowercase     )

             # check that output_attentions also work using config
             del inputs_dict["output_attentions"]
             UpperCamelCase_          =		True
             UpperCamelCase_          =		config.window_size**2
             UpperCamelCase_          =		model_class(_lowercase     )
             model.to(_lowercase     )
             model.eval()
             with torch.no_grad():
                 UpperCamelCase_          =		model(**self._prepare_for_class(_lowercase						,		_lowercase     )     )
             UpperCamelCase_          =		outputs.attentions
             self.assertEqual(len(_lowercase     )						,		_lowercase     )

             self.assertListEqual(
                 list(attentions[0].shape[-3:]     )						,		[self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,		)
             UpperCamelCase_          =		len(_lowercase     )

             # Check attention is always last and order is fine
             UpperCamelCase_          =		True
             UpperCamelCase_          =		True
             UpperCamelCase_          =		model_class(_lowercase     )
             model.to(_lowercase     )
             model.eval()
             with torch.no_grad():
                 UpperCamelCase_          =		model(**self._prepare_for_class(_lowercase						,		_lowercase     )     )

             if hasattr(self.model_tester						,		"num_hidden_states_types"     ):
                 UpperCamelCase_          =		self.model_tester.num_hidden_states_types
             else:
                 # also another +1 for reshaped_hidden_states
                 UpperCamelCase_          =		2
             self.assertEqual(out_len + added_hidden_states						,		len(_lowercase     )     )

             UpperCamelCase_          =		outputs.attentions

             self.assertEqual(len(_lowercase     )						,		_lowercase     )

             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]     )						,		[self.model_tester.num_heads[0], window_size_squared, window_size_squared]						,		)






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase     )->			List[Any]:
         UpperCamelCase_          =		model_class(_lowercase     )
         model.to(_lowercase     )
         model.eval()

         with torch.no_grad():
             UpperCamelCase_          =		model(**self._prepare_for_class(_lowercase						,		_lowercase     )     )

         UpperCamelCase_          =		outputs.hidden_states

         UpperCamelCase_          =		getattr(
             self.model_tester						,		"expected_num_hidden_layers"						,		len(self.model_tester.depths     ) + 1     )
         self.assertEqual(len(_lowercase     )						,		_lowercase     )

         # DonutSwin has a different seq_length
         UpperCamelCase_          =		(
             config.patch_size
             if isinstance(config.patch_size						,		collections.abc.Iterable     )
             else (config.patch_size, config.patch_size)
         )

         UpperCamelCase_          =		(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

         self.assertListEqual(
             list(hidden_states[0].shape[-2:]     )						,		[num_patches, self.model_tester.embed_dim]						,		)

         UpperCamelCase_          =		outputs.reshaped_hidden_states
         self.assertEqual(len(_lowercase     )						,		_lowercase     )

         UpperCamelCase_   ,    UpperCamelCase_   ,    UpperCamelCase_   ,    UpperCamelCase_          =		reshaped_hidden_states[0].shape
         UpperCamelCase_          =		(
             reshaped_hidden_states[0].view(_lowercase						,		_lowercase						,		height * width     ).permute(0						,		2						,		1     )
         )
         self.assertListEqual(
             list(reshaped_hidden_states.shape[-2:]     )						,		[num_patches, self.model_tester.embed_dim]						,		)






     def      UpperCAmelCase_							(							self     )->			List[str]:
         UpperCamelCase_   ,    UpperCamelCase_          =		self.model_tester.prepare_config_and_inputs_for_common()

         UpperCamelCase_          =		(
             self.model_tester.image_size
             if isinstance(self.model_tester.image_size						,		collections.abc.Iterable     )
             else (self.model_tester.image_size, self.model_tester.image_size)
         )

         for model_class in self.all_model_classes:
             UpperCamelCase_          =		True
             self.check_hidden_states_output(_lowercase						,		_lowercase						,		_lowercase						,		_lowercase     )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             UpperCamelCase_          =		True

             self.check_hidden_states_output(_lowercase						,		_lowercase						,		_lowercase						,		_lowercase     )






     def      UpperCAmelCase_							(							self     )->			Any:
         UpperCamelCase_   ,    UpperCamelCase_          =		self.model_tester.prepare_config_and_inputs_for_common()
         UpperCamelCase_          =		3

         UpperCamelCase_          =		(
             self.model_tester.image_size
             if isinstance(self.model_tester.image_size						,		collections.abc.Iterable     )
             else (self.model_tester.image_size, self.model_tester.image_size)
         )
         UpperCamelCase_          =		(
             config.patch_size
             if isinstance(config.patch_size						,		collections.abc.Iterable     )
             else (config.patch_size, config.patch_size)
         )

         UpperCamelCase_          =		image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
         UpperCamelCase_          =		image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

         for model_class in self.all_model_classes:
             UpperCamelCase_          =		True
             self.check_hidden_states_output(_lowercase						,		_lowercase						,		_lowercase						,		(padded_height, padded_width)     )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             UpperCamelCase_          =		True
             self.check_hidden_states_output(_lowercase						,		_lowercase						,		_lowercase						,		(padded_height, padded_width)     )






     @slow
     def      UpperCAmelCase_							(							self     )->			List[str]:
         for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase_          =		DonutSwinModel.from_pretrained(_lowercase     )
             self.assertIsNotNone(_lowercase     )






     def      UpperCAmelCase_							(							self     )->			Any:
         UpperCamelCase_   ,    UpperCamelCase_          =		self.model_tester.prepare_config_and_inputs_for_common()

         UpperCamelCase_          =		_config_zero_init(_lowercase     )
         for model_class in self.all_model_classes:
             UpperCamelCase_          =		model_class(config=_lowercase     )
             for name, param in model.named_parameters():
                 if "embeddings" not in name and param.requires_grad:
                     self.assertIn(
                         ((param.data.mean() * 1e9).round() / 1e9).item()						,		[0.0, 1.0]						,		msg=F"Parameter {name} of model {model_class} seems not properly initialized"						,		)
