




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        snake_case__				:
				"""simple docstring"""



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





				def 				__UpperCAmelCase				( self							:	Optional[Any]				)   ->	Dict:
							a       =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

							a       =     self.get_config()

							return config, pixel_values, labels





				def 				__UpperCAmelCase				( self							:	Any				)   ->	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							:	int   , __lowerCamelCase							:	Union[str, Any]   , __lowerCamelCase							:	Union[str, Any]   , __lowerCamelCase							:	Union[str, Any]				)   ->	List[str]:
							a       =     DonutSwinModel(config=__lowerCamelCase				)
							model.to(__lowerCamelCase				)
							model.eval()
							a       =     model(__lowerCamelCase				)

							a       =     ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths				) - 1))
							a       =     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							:	Optional[int]				)   ->	Union[str, Any]:
							a       =     self.prepare_config_and_inputs()
							(
							    (
							    a	
							)       ,						(
							    a	
							)       ,						(
							    a	
							)       ,							
							)       =     config_and_inputs
							a       =     {"pixel_values": pixel_values}
							return config, inputs_dict




@require_torch
class        snake_case__				(_UpperCamelCase       ,			_UpperCamelCase       ,			unittest.TestCase  ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_			:				Any									=   (DonutSwinModel,) if is_torch_available() else ()
				SCREAMING_SNAKE_CASE_			:				Dict									=   {"""feature-extraction""": DonutSwinModel} if is_torch_available() else {}
				SCREAMING_SNAKE_CASE_			:				List[Any]									=   True

				SCREAMING_SNAKE_CASE_			:				Dict									=   False
				SCREAMING_SNAKE_CASE_			:				str									=   False
				SCREAMING_SNAKE_CASE_			:				Any									=   False





				def 				__UpperCAmelCase				( self							:	Optional[int]				)   ->	Tuple:
							a       =     DonutSwinModelTester(self				)
							a       =     ConfigTester(self   , config_class=__lowerCamelCase   , embed_dim=37				)





				def 				__UpperCAmelCase				( self							:	List[Any]				)   ->	str:
							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							:	int				)   ->	int:
							return





				def 				__UpperCAmelCase				( self							:	int				)   ->	str:
							a       =     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowerCamelCase				)





				def 				__UpperCAmelCase				( self							:	Any				)   ->	List[str]:
							pass





				def 				__UpperCAmelCase				( self							:	Dict				)   ->	int:
							a       ,						a       =     self.model_tester.prepare_config_and_inputs_for_common()

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





				def 				__UpperCAmelCase				( self							:	Optional[Any]				)   ->	Optional[int]:
							a       ,						a       =     self.model_tester.prepare_config_and_inputs_for_common()

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

										a       =     ["pixel_values"]
										self.assertListEqual(arg_names[:1]   , __lowerCamelCase				)





				def 				__UpperCAmelCase				( self							:	Optional[int]				)   ->	Any:
							a       ,						a       =     self.model_tester.prepare_config_and_inputs_for_common()
							a       =     True

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

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

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

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

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

										a       =     outputs.attentions

										self.assertEqual(len(__lowerCamelCase				)   , __lowerCamelCase				)

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





				def 				__UpperCAmelCase				( self							:	Tuple   , __lowerCamelCase							:	str   , __lowerCamelCase							:	List[str]   , __lowerCamelCase							:	List[Any]   , __lowerCamelCase							:	List[Any]				)   ->	int:
							a       =     model_class(__lowerCamelCase				)
							model.to(__lowerCamelCase				)
							model.eval()

							with torch.no_grad():
										a       =     model(**self._prepare_for_class(__lowerCamelCase   , __lowerCamelCase				)				)

							a       =     outputs.hidden_states

							a       =     getattr(
							    self.model_tester   , "expected_num_hidden_layers"   , len(self.model_tester.depths				) + 1				)
							self.assertEqual(len(__lowerCamelCase				)   , __lowerCamelCase				)

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

							a       =     (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]   , )

							a       =     outputs.reshaped_hidden_states
							self.assertEqual(len(__lowerCamelCase				)   , __lowerCamelCase				)

							a       ,						a       ,						a       ,						a       =     reshaped_hidden_states[0].shape
							a       =     (
							    reshaped_hidden_states[0].view(__lowerCamelCase   , __lowerCamelCase   , 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]				)   ->	Optional[int]:
							a       ,						a       =     self.model_tester.prepare_config_and_inputs_for_common()

							a       =     (
							    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:
										a       =     True
										self.check_hidden_states_output(__lowerCamelCase   , __lowerCamelCase   , __lowerCamelCase   , __lowerCamelCase				)

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

										self.check_hidden_states_output(__lowerCamelCase   , __lowerCamelCase   , __lowerCamelCase   , __lowerCamelCase				)





				def 				__UpperCAmelCase				( self							:	Dict				)   ->	Any:
							a       ,						a       =     self.model_tester.prepare_config_and_inputs_for_common()
							a       =     3

							a       =     (
							    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)
							)
							a       =     (
							    config.patch_size
							    if isinstance(config.patch_size   , collections.abc.Iterable				)
							    else (config.patch_size, config.patch_size)
							)

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

							for model_class in self.all_model_classes:
										a       =     True
										self.check_hidden_states_output(__lowerCamelCase   , __lowerCamelCase   , __lowerCamelCase   , (padded_height, padded_width)				)

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





				@slow
				def 				__UpperCAmelCase				( self							:	List[Any]				)   ->	List[Any]:

							for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										a       =     DonutSwinModel.from_pretrained(__lowerCamelCase				)
										self.assertIsNotNone(__lowerCamelCase				)





				def 				__UpperCAmelCase				( self							:	List[Any]				)   ->	List[str]:
							a       ,						a       =     self.model_tester.prepare_config_and_inputs_for_common()

							a       =     _config_zero_init(__lowerCamelCase				)
							for model_class in self.all_model_classes:
										a       =     model_class(config=__lowerCamelCase				)
										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"""   , )











"""simple docstring"""







import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
							import jax
							import jax.numpy as jnp

							from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor






class   UpperCAmelCase__		(   unittest.TestCase  ):



		def __init__(			self	:     Dict   ,				snake_case	:     Dict   ,				snake_case	:     Optional[Any]=3   ,				snake_case	:     Union[str, Any]=32   ,				snake_case	:     int=3   ,				snake_case	:     Any=10   ,				snake_case	:     int=[10, 20, 30, 40]   ,				snake_case	:     List[Any]=[1, 1, 2, 1]   ,				snake_case	:     List[str]=True   ,				snake_case	:     Any=True   ,				snake_case	:     str="relu"   ,				snake_case	:     List[str]=3   ,				snake_case	:     List[str]=None   ,				)      ->    int:






									'''simple docstring'''

									A    =       parent
									A    =       batch_size
									A    =       image_size
									A    =       num_channels
									A    =       embeddings_size
									A    =       hidden_sizes
									A    =       depths
									A    =       is_training
									A    =       use_labels
									A    =       hidden_act
									A    =       num_labels
									A    =       scope
									A    =       len(snake_case					)



		def        A_		(			self	:     Optional[int]					)      ->    Any:






									'''simple docstring'''

									A    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

									A    =       self.get_config()

									return config, pixel_values



		def        A_		(			self	:     int					)      ->    List[Any]:






									'''simple docstring'''

									return ResNetConfig(
									    num_channels=self.num_channels   ,				embeddings_size=self.embeddings_size   ,				hidden_sizes=self.hidden_sizes   ,				depths=self.depths   ,				hidden_act=self.hidden_act   ,				num_labels=self.num_labels   ,				image_size=self.image_size   ,				)



		def        A_		(			self	:     Optional[Any]   ,				snake_case	:     str   ,				snake_case	:     Any					)      ->    int:






									'''simple docstring'''

									A    =       FlaxResNetModel(config=snake_case					)
									A    =       model(snake_case					)

									# Output shape (b, c, h, w)
									self.parent.assertEqual(
									    result.last_hidden_state.shape   ,				(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)   ,				)



		def        A_		(			self	:     Dict   ,				snake_case	:     Tuple   ,				snake_case	:     Optional[Any]					)      ->    Tuple:






									'''simple docstring'''

									A    =       self.num_labels
									A    =       FlaxResNetForImageClassification(config=snake_case					)
									A    =       model(snake_case					)
									self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels)					)



		def        A_		(			self	:     List[str]					)      ->    Optional[Any]:






									'''simple docstring'''

									A    =       self.prepare_config_and_inputs()
									A   ,	A    =       config_and_inputs
									A    =       {'pixel_values': pixel_values}
									return config, inputs_dict






@require_flax
class   UpperCAmelCase__		(   UpperCamelCase ,unittest.TestCase  ):
		lowerCAmelCase_							:						List[str]							=  (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

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



		def        A_		(			self	:     Optional[Any]					)      ->    None:






									'''simple docstring'''

									A    =       FlaxResNetModelTester(self					)
									A    =       ConfigTester(self   ,				config_class=snake_case   ,				has_text_modality=snake_case					)



		def        A_		(			self	:     List[str]					)      ->    Dict:






									'''simple docstring'''

									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        A_		(			self	:     Dict					)      ->    List[Any]:






									'''simple docstring'''

									return



		def        A_		(			self	:     str					)      ->    List[str]:






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*snake_case					)



		def        A_		(			self	:     Optional[int]					)      ->    List[str]:






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*snake_case					)



		@unittest.skip(reason='ResNet does not use inputs_embeds'					)
		def        A_		(			self	:     Tuple					)      ->    str:






									'''simple docstring'''

									pass



		@unittest.skip(reason='ResNet does not support input and output embeddings'					)
		def        A_		(			self	:     Tuple					)      ->    Any:






									'''simple docstring'''

									pass



		def        A_		(			self	:     Optional[Any]					)      ->    int:






									'''simple docstring'''

									A   ,	A    =       self.model_tester.prepare_config_and_inputs_for_common()

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

																A    =       ['pixel_values']
																self.assertListEqual(arg_names[:1]   ,				snake_case					)



		def        A_		(			self	:     Any					)      ->    Tuple:






									'''simple docstring'''

									def check_hidden_states_output(snake_case	:     Tuple   ,				snake_case	:     Union[str, Any]   ,				snake_case	:     Optional[int]					):
																A    =       model_class(snake_case					)

																A    =       model(**self._prepare_for_class(snake_case   ,				snake_case					)					)

																A    =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																A    =       self.model_tester.num_stages
																self.assertEqual(len(snake_case					)   ,				expected_num_stages + 1					)



		@unittest.skip(reason='ResNet does not use feedforward chunking'					)
		def        A_		(			self	:     Optional[int]					)      ->    List[Any]:






									'''simple docstring'''

									pass



		def        A_		(			self	:     Union[str, Any]					)      ->    Union[str, Any]:






									'''simple docstring'''

									A   ,	A    =       self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
																with self.subTest(model_class.__name__					):
																							A    =       self._prepare_for_class(snake_case   ,				snake_case					)
																							A    =       model_class(snake_case					)

																							@jax.jit
																							def model_jitted(snake_case	:     Any   ,				**snake_case	:     int					):
																														return model(pixel_values=snake_case   ,				**snake_case					)

																							with self.subTest('JIT Enabled'					):
																														A    =       model_jitted(**snake_case					).to_tuple()

																							with self.subTest('JIT Disabled'					):
																														with jax.disable_jit():
																																					A    =       model_jitted(**snake_case					).to_tuple()

																							self.assertEqual(len(snake_case					)   ,				len(snake_case					)					)
																							for jitted_output, output in zip(snake_case   ,				snake_case					):
																														self.assertEqual(jitted_output.shape   ,				output.shape					)



def 	lowerCAmelCase__      (  )			->				int:
							A    =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
							return image






@require_flax
class   UpperCAmelCase__		(   unittest.TestCase  ):



		@cached_property
		def        A_		(			self	:     Union[str, Any]					)      ->    int:






									'''simple docstring'''

									return AutoImageProcessor.from_pretrained('microsoft/resnet-50'					) if is_vision_available() else None



		@slow
		def        A_		(			self	:     Any					)      ->    Tuple:






									'''simple docstring'''

									A    =       FlaxResNetForImageClassification.from_pretrained('microsoft/resnet-50'					)

									A    =       self.default_image_processor
									A    =       prepare_img()
									A    =       image_processor(images=snake_case   ,				return_tensors='np'					)

									A    =       model(**snake_case					)

									# verify the logits
									A    =       (1, 1_000)
									self.assertEqual(outputs.logits.shape   ,				snake_case					)

									A    =       jnp.array([-11.1069, -9.7877, -8.3777]					)

									self.assertTrue(jnp.allclose(outputs.logits[0, :3]   ,				snake_case   ,				atol=1E-4					)					)



