


import inspect
import unittest

import requests

from transformers import MgpstrConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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


if is_torch_available():
					import torch
					from torch import nn

					from transformers import MgpstrForSceneTextRecognition


if is_vision_available():
					from PIL import Image

					from transformers import MgpstrProcessor

class      __snake_case				:
					def __init__(						self       :						Any	,      _lowerCAmelCase       :						Any	,      _lowerCAmelCase       :						str=False	,      _lowerCAmelCase       :						Tuple=1_3	,      _lowerCAmelCase       :						Any=(3_2, 1_2_8)	,      _lowerCAmelCase       :						Optional[int]=4	,      _lowerCAmelCase       :						str=3	,      _lowerCAmelCase       :						int=2_7	,      _lowerCAmelCase       :						Optional[Any]=3_8	,      _lowerCAmelCase       :						Union[str, Any]=9_9	,      _lowerCAmelCase       :						List[Any]=9_9	,      _lowerCAmelCase       :						str=3_2	,      _lowerCAmelCase       :						Any=5	,      _lowerCAmelCase       :						Dict=4	,      _lowerCAmelCase       :						Optional[Any]=4.0	,      _lowerCAmelCase       :						str=2_5_7	,      _lowerCAmelCase       :						Union[str, Any]=None	,      )							->					Any:



											'''simple docstring'''





											__magic_name__					=      parent
											__magic_name__					=      is_training
											__magic_name__					=      batch_size
											__magic_name__					=      image_size
											__magic_name__					=      patch_size
											__magic_name__					=      num_channels
											__magic_name__					=      max_token_length
											__magic_name__					=      num_character_labels
											__magic_name__					=      num_bpe_labels
											__magic_name__					=      num_wordpiece_labels
											__magic_name__					=      hidden_size
											__magic_name__					=      num_hidden_layers
											__magic_name__					=      num_attention_heads
											__magic_name__					=      mlp_ratio
											__magic_name__					=      patch_embeds_hidden_size
											__magic_name__					=      output_hidden_states
					def 	a			(						self       :						Union[str, Any]  )							->					int:



											'''simple docstring'''





											__magic_name__					=      floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]  )
											__magic_name__					=      self.get_config()
											return config, pixel_values
					def 	a			(						self       :						List[str]  )							->					List[str]:



											'''simple docstring'''





											return MgpstrConfig(
											    image_size=self.image_size	,      patch_size=self.patch_size	,      num_channels=self.num_channels	,      max_token_length=self.max_token_length	,      num_character_labels=self.num_character_labels	,      num_bpe_labels=self.num_bpe_labels	,      num_wordpiece_labels=self.num_wordpiece_labels	,      hidden_size=self.hidden_size	,      num_hidden_layers=self.num_hidden_layers	,      num_attention_heads=self.num_attention_heads	,      mlp_ratio=self.mlp_ratio	,      output_hidden_states=self.output_hidden_states	,      )
					def 	a			(						self       :						Any	,      _lowerCAmelCase       :						Optional[int]	,      _lowerCAmelCase       :						List[Any]  )							->					List[Any]:



											'''simple docstring'''





											__magic_name__					=      MgpstrForSceneTextRecognition(_lowerCAmelCase  )
											model.to(_lowerCAmelCase  )
											model.eval()
											with torch.no_grad():
																	__magic_name__					=      model(_lowerCAmelCase  )
											self.parent.assertEqual(
											    generated_ids[0][0].shape	,      (self.batch_size, self.max_token_length, self.num_character_labels)  )







					def 	a			(						self       :						List[Any]  )							->					Any:



											'''simple docstring'''





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







@require_torch
class      __snake_case				(   __a	,      __a	,      unittest.TestCase):
					SCREAMING_SNAKE_CASE_		:       Optional[Any]								=			(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
					SCREAMING_SNAKE_CASE_		:       Any								=			{"""feature-extraction""": MgpstrForSceneTextRecognition} if is_torch_available() else {}
					SCREAMING_SNAKE_CASE_		:       List[str]								=			False

					SCREAMING_SNAKE_CASE_		:       Union[str, Any]								=			False
					SCREAMING_SNAKE_CASE_		:       List[str]								=			False
					SCREAMING_SNAKE_CASE_		:       Optional[Any]								=			False
					SCREAMING_SNAKE_CASE_		:       List[str]								=			False
					def 	a			(						self       :						Dict  )							->					Union[str, Any]:



											'''simple docstring'''





											__magic_name__					=      MgpstrModelTester(self  )
											__magic_name__					=      ConfigTester(self	,      config_class=_lowerCAmelCase	,      has_text_modality=_lowerCAmelCase  )
					def 	a			(						self       :						List[str]  )							->					Optional[int]:



											'''simple docstring'''





											self.config_tester.run_common_tests()
					def 	a			(						self       :						int  )							->					int:



											'''simple docstring'''





											__magic_name__					=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowerCAmelCase  )
					@unittest.skip(reason='MgpstrModel does not use inputs_embeds'  )
					def 	a			(						self       :						int  )							->					Optional[int]:



											'''simple docstring'''





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



											'''simple docstring'''





											__magic_name__		,      __magic_name__					=      self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__magic_name__					=      model_class(_lowerCAmelCase  )
																	self.assertIsInstance(model.get_input_embeddings()	,      (nn.Module)  )
																	__magic_name__					=      model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(_lowerCAmelCase	,      nn.Linear  )  )
					def 	a			(						self       :						str  )							->					Any:



											'''simple docstring'''





											__magic_name__		,      __magic_name__					=      self.model_tester.prepare_config_and_inputs_for_common()

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

																	__magic_name__					=      ['pixel_values']
																	self.assertListEqual(arg_names[:1]	,      _lowerCAmelCase  )
					@unittest.skip(reason='MgpstrModel does not support feedforward chunking'  )
					def 	a			(						self       :						Tuple  )							->					Tuple:



											'''simple docstring'''





											pass
					def 	a			(						self       :						int  )							->					Dict:



											'''simple docstring'''





											__magic_name__		,      __magic_name__					=      self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	if not model_class.supports_gradient_checkpointing:
																							continue

																	__magic_name__					=      True
																	__magic_name__					=      model_class(_lowerCAmelCase  )
																	self.assertTrue(model.is_gradient_checkpointing  )
					def 	a			(						self       :						List[Any]  )							->					Dict:



											'''simple docstring'''





											def check_hidden_states_output(_lowerCAmelCase       :						int	,      _lowerCAmelCase       :						Tuple	,      _lowerCAmelCase       :						Optional[Any]  ):
																	__magic_name__					=      model_class(_lowerCAmelCase  )
																	model.to(_lowerCAmelCase  )
																	model.eval()

																	with torch.no_grad():
																							__magic_name__					=      model(**self._prepare_for_class(_lowerCAmelCase	,      _lowerCAmelCase  )  )

																	__magic_name__					=      outputs.hidden_states

																	__magic_name__					=      getattr(
																	    self.model_tester	,      'expected_num_hidden_layers'	,      self.model_tester.num_hidden_layers + 1  )
																	self.assertEqual(len(_lowerCAmelCase  )	,      _lowerCAmelCase  )

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

											__magic_name__		,      __magic_name__					=      self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__magic_name__					=      True
																	check_hidden_states_output(_lowerCAmelCase	,      _lowerCAmelCase	,      _lowerCAmelCase  )

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

																	check_hidden_states_output(_lowerCAmelCase	,      _lowerCAmelCase	,      _lowerCAmelCase  )
					def 	a			(						self       :						Optional[int]  )							->					Union[str, Any]:



											'''simple docstring'''





											__magic_name__		,      __magic_name__					=      self.model_tester.prepare_config_and_inputs_for_common()

											__magic_name__					=      _config_zero_init(_lowerCAmelCase  )
											for model_class in self.all_model_classes:
																	__magic_name__					=      model_class(config=_lowerCAmelCase  )
																	for name, param in model.named_parameters():
																							if isinstance(_lowerCAmelCase	,      (nn.Linear, nn.Convad, nn.LayerNorm)  ):
																													if 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'''	,      )







					@unittest.skip(reason='Retain_grad is tested in individual model tests'  )
					def 	a			(						self       :						Union[str, Any]  )							->					int:



											'''simple docstring'''





											pass







def 				UpperCamelCase_	(					)->   Optional[int]:




						'''simple docstring'''
						__magic_name__					=      'https://i.postimg.cc/ZKwLg2Gw/367-14.png'
						__magic_name__					=      Image.open(requests.get(_a						,      stream=_a  ).raw  ).convert('RGB'  )
						return im




@require_vision
@require_torch
class      __snake_case				(   unittest.TestCase):
					@slow
					def 	a			(						self       :						Union[str, Any]  )							->					Tuple:



											'''simple docstring'''





											__magic_name__					=      'alibaba-damo/mgp-str-base'
											__magic_name__					=      MgpstrForSceneTextRecognition.from_pretrained(_lowerCAmelCase  ).to(_lowerCAmelCase  )
											__magic_name__					=      MgpstrProcessor.from_pretrained(_lowerCAmelCase  )

											__magic_name__					=      prepare_img()
											__magic_name__					=      processor(images=_lowerCAmelCase	,      return_tensors='pt'  ).pixel_values.to(_lowerCAmelCase  )

											# forward pass
											with torch.no_grad():
																	__magic_name__					=      model(_lowerCAmelCase  )

											# verify the logits
											self.assertEqual(outputs.logits[0].shape	,      torch.Size((1, 2_7, 3_8)  )  )

											__magic_name__					=      processor.batch_decode(outputs.logits  )
											__magic_name__					=      'ticket'

											self.assertEqual(out_strs['generated_text'][0]	,      _lowerCAmelCase  )

											__magic_name__					=      torch.tensor(
											    [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]	,      device=_lowerCAmelCase	,      )

											self.assertTrue(torch.allclose(outputs.logits[0][:, 1:4, 1:4]	,      _lowerCAmelCase	,      atol=1E-4  )  )







'''simple docstring'''







import inspect
import unittest

from transformers import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
   import torch

   from transformers import MODEL_MAPPING, PoolFormerConfig, PoolFormerForImageClassification, PoolFormerModel
   from transformers.models.poolformer.modeling_poolformer import POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import PoolFormerImageProcessor


class      _a    (      __a					):
       def        A (      self		:      Tuple							):



           '''simple docstring'''

           UpperCAmelCase     			=						self.config_class(**self.inputs_dict							)
           self.parent.assertTrue(hasattr(lowercase  ,							'''hidden_sizes'''							)							)
           self.parent.assertTrue(hasattr(lowercase  ,							'''num_encoder_blocks'''							)							)






class      _a    :
       def __init__(      self		:      Any  ,							lowercase		:      Any  ,							lowercase		:      Optional[Any]=13  ,							lowercase		:      List[str]=64  ,							lowercase		:      Optional[Any]=3  ,							lowercase		:      List[str]=4  ,							lowercase		:      Optional[int]=[2, 2, 2, 2]  ,							lowercase		:      Tuple=[8, 4, 2, 1]  ,							lowercase		:      Optional[int]=[16, 32, 64, 128]  ,							lowercase		:      Tuple=[1, 4, 8, 16]  ,							lowercase		:      List[Any]=False  ,							lowercase		:      List[Any]=True  ,							lowercase		:      List[str]="gelu"  ,							lowercase		:      Any=0.1  ,							lowercase		:      Dict=0.02  ,							lowercase		:      str=3  ,							lowercase		:      Optional[Any]=None  ,							):



           '''simple docstring'''

           UpperCAmelCase     			=						parent
           UpperCAmelCase     			=						batch_size
           UpperCAmelCase     			=						image_size
           UpperCAmelCase     			=						num_channels
           UpperCAmelCase     			=						num_encoder_blocks
           UpperCAmelCase     			=						sr_ratios
           UpperCAmelCase     			=						depths
           UpperCAmelCase     			=						hidden_sizes
           UpperCAmelCase     			=						downsampling_rates
           UpperCAmelCase     			=						is_training
           UpperCAmelCase     			=						use_labels
           UpperCAmelCase     			=						hidden_act
           UpperCAmelCase     			=						hidden_dropout_prob
           UpperCAmelCase     			=						initializer_range
           UpperCAmelCase     			=						num_labels
           UpperCAmelCase     			=						scope
       def        A (      self		:      Union[str, Any]							):



           '''simple docstring'''

           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.image_size, self.image_size]  ,							self.num_labels							)

           UpperCAmelCase     			=						PoolFormerConfig(
               image_size=self.image_size  ,							num_channels=self.num_channels  ,							num_encoder_blocks=self.num_encoder_blocks  ,							depths=self.depths  ,							hidden_sizes=self.hidden_sizes  ,							hidden_act=self.hidden_act  ,							hidden_dropout_prob=self.hidden_dropout_prob  ,							initializer_range=self.initializer_range  ,							)

           return config, pixel_values, labels
       def        A (      self		:      Optional[Any]  ,							lowercase		:      List[Any]  ,							lowercase		:      Dict  ,							lowercase		:      Union[str, Any]							):



           '''simple docstring'''

           UpperCAmelCase     			=						PoolFormerModel(config=lowercase							)
           model.to(lowercase							)
           model.eval()
           UpperCAmelCase     			=						model(lowercase							)
           UpperCAmelCase     			=						UpperCAmelCase     			=						self.image_size // 32.0
           self.parent.assertEqual(
               result.last_hidden_state.shape  ,							(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)							)







       def        A (      self		:      Union[str, Any]							):



           '''simple docstring'''

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






@require_torch
class      _a    (      __a				,				__a				,				unittest.TestCase					):
       __a							:	Optional[int]  							=   (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
       __a							:	Dict  							=   (
           {"""feature-extraction""": PoolFormerModel, """image-classification""": PoolFormerForImageClassification}
           if is_torch_available()
           else {}
       )

       __a							:	str  							=   False
       __a							:	Optional[int]  							=   False
       __a							:	Tuple  							=   False
       __a							:	Union[str, Any]  							=   False
       __a							:	Dict  							=   False
       def        A (      self		:      Any							):



           '''simple docstring'''

           UpperCAmelCase     			=						PoolFormerModelTester(self							)
           UpperCAmelCase     			=						PoolFormerConfigTester(self  ,							config_class=lowercase							)
       def        A (      self		:      Any							):



           '''simple docstring'''

           self.config_tester.run_common_tests()
       def        A (      self		:      Optional[int]							):



           '''simple docstring'''

           UpperCAmelCase     			=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase							)
       @unittest.skip('''PoolFormer does not use inputs_embeds'''							)
       def        A (      self		:      Dict							):



           '''simple docstring'''

           pass
       @unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'''							)
       def        A (      self		:      Union[str, Any]							):



           '''simple docstring'''

           pass
       def        A (      self		:      Dict							):



           '''simple docstring'''

           def check_hidden_states_output(lowercase		:      int  ,							lowercase		:      Any  ,							lowercase		:      Union[str, 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     			=						self.model_tester.num_encoder_blocks
               self.assertEqual(len(lowercase							)  ,							lowercase							)

               # verify the first hidden states (first block)
               self.assertListEqual(
                   list(hidden_states[0].shape[-3:]							)  ,							[
                       self.model_tester.hidden_sizes[0],
                       self.model_tester.image_size // 4,
                       self.model_tester.image_size // 4,
                   ]  ,							)

           UpperCAmelCase			,	UpperCAmelCase     			=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               UpperCAmelCase     			=						True
               check_hidden_states_output(lowercase  ,							lowercase  ,							lowercase							)

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

               check_hidden_states_output(lowercase  ,							lowercase  ,							lowercase							)
       def        A (      self		:      Optional[Any]							):



           '''simple docstring'''

           if not self.model_tester.is_training:
               return

           UpperCAmelCase			,	UpperCAmelCase     			=						self.model_tester.prepare_config_and_inputs_for_common()
           UpperCAmelCase     			=						True

           for model_class in self.all_model_classes:
               if model_class in get_values(lowercase							):
                   continue
               UpperCAmelCase     			=						model_class(lowercase							)
               model.to(lowercase							)
               model.train()
               UpperCAmelCase     			=						self._prepare_for_class(lowercase  ,							lowercase  ,							return_labels=lowercase							)
               UpperCAmelCase     			=						model(**lowercase							).loss
               loss.backward()
       def        A (      self		:      str							):



           '''simple docstring'''

           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							)







       @slow
       def        A (      self		:      Union[str, Any]							):



           '''simple docstring'''

           for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase     			=						PoolFormerModel.from_pretrained(lowercase							)
               self.assertIsNotNone(lowercase							)






def 		snake_case_				():
    UpperCAmelCase     			=						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
    return image







@require_torch
class      _a    (      unittest.TestCase					):
       @slow
       def        A (      self		:      str							):



           '''simple docstring'''

           UpperCAmelCase     			=						PoolFormerImageProcessor()
           UpperCAmelCase     			=						PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12'''							).to(lowercase							)

           UpperCAmelCase     			=						image_processor(images=prepare_img()  ,							return_tensors='''pt'''							).to(lowercase							)

           # forward pass
           with torch.no_grad():
               UpperCAmelCase     			=						model(**lowercase							)

           # verify the logits
           UpperCAmelCase     			=						torch.Size((1, 1_000)							)
           self.assertEqual(outputs.logits.shape  ,							lowercase							)

           UpperCAmelCase     			=						torch.tensor([-0.6113, 0.1685, -0.0492]							).to(lowercase							)
           self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,							lowercase  ,							atol=1E-4							)							)




