




'''simple docstring'''







import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
						import os

						# The slow tests are often failing with OOM error on GPU
						# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
						# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
						_lowerCamelCase				:		str				      =    'platform'

						import jax
						import jax.numpy as jnp

						from transformers import MarianTokenizer
						from transformers.models.marian.modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, shift_tokens_right






def 						_lowercase						(      lowercase_		,				lowercase_		,				lowercase_=None		,				lowercase_=None		,				lowercase_=None		,				lowercase_=None		,				lowercase_=None		,				lowercase_=None		,				):



		'''simple docstring'''







		if attention_mask is None:
				_snake_case      			=			np.where(input_ids != config.pad_token_id		,				1		,				0    )
		if decoder_attention_mask is None:
				_snake_case      			=			np.where(decoder_input_ids != config.pad_token_id		,				1		,				0    )
		if head_mask is None:
				_snake_case      			=			np.ones((config.encoder_layers, config.encoder_attention_heads)    )
		if decoder_head_mask is None:
				_snake_case      			=			np.ones((config.decoder_layers, config.decoder_attention_heads)    )
		if cross_attn_head_mask is None:
				_snake_case      			=			np.ones((config.decoder_layers, config.decoder_attention_heads)    )
		return {
		    "input_ids": input_ids,
		    "decoder_input_ids": decoder_input_ids,
		    "attention_mask": attention_mask,
		    "decoder_attention_mask": attention_mask,
		}





class 	lowerCamelCase_				:




					'''simple docstring'''






					def __init__(       self,    __UpperCamelCase,    __UpperCamelCase=13,    __UpperCamelCase=7,    __UpperCamelCase=True,    __UpperCamelCase=False,    __UpperCamelCase=99,    __UpperCamelCase=16,    __UpperCamelCase=2,    __UpperCamelCase=4,    __UpperCamelCase=4,    __UpperCamelCase="gelu",    __UpperCamelCase=0.1,    __UpperCamelCase=0.1,    __UpperCamelCase=32,    __UpperCamelCase=2,    __UpperCamelCase=1,    __UpperCamelCase=0,    __UpperCamelCase=0.02,    ):
							_snake_case      			=			parent
							_snake_case      			=			batch_size
							_snake_case      			=			seq_length
							_snake_case      			=			is_training
							_snake_case      			=			use_labels
							_snake_case      			=			vocab_size
							_snake_case      			=			hidden_size
							_snake_case      			=			num_hidden_layers
							_snake_case      			=			num_attention_heads
							_snake_case      			=			intermediate_size
							_snake_case      			=			hidden_act
							_snake_case      			=			hidden_dropout_prob
							_snake_case      			=			attention_probs_dropout_prob
							_snake_case      			=			max_position_embeddings
							_snake_case      			=			eos_token_id
							_snake_case      			=			pad_token_id
							_snake_case      			=			bos_token_id
							_snake_case      			=			initializer_range






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			np.clip(ids_tensor([self.batch_size, self.seq_length - 1],    self.vocab_size					),    3,    self.vocab_size					)
							_snake_case      			=			np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1),    dtype=np.intaa					)),    -1					)

							_snake_case      			=			shift_tokens_right(__UpperCAmelCase,    1,    2					)

							_snake_case      			=			MarianConfig(
							    vocab_size=self.vocab_size,    d_model=self.hidden_size,    encoder_layers=self.num_hidden_layers,    decoder_layers=self.num_hidden_layers,    encoder_attention_heads=self.num_attention_heads,    decoder_attention_heads=self.num_attention_heads,    encoder_ffn_dim=self.intermediate_size,    decoder_ffn_dim=self.intermediate_size,    dropout=self.hidden_dropout_prob,    attention_dropout=self.attention_probs_dropout_prob,    max_position_embeddings=self.max_position_embeddings,    eos_token_id=self.eos_token_id,    bos_token_id=self.bos_token_id,    pad_token_id=self.pad_token_id,    initializer_range=self.initializer_range,    use_cache=__UpperCAmelCase,    )
							_snake_case      			=			prepare_marian_inputs_dict(__UpperCAmelCase,    __UpperCAmelCase,    __UpperCAmelCase					)
							return config, inputs_dict






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			self.prepare_config_and_inputs()
							return config, inputs_dict






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					):
							_snake_case      			=			20
							_snake_case      			=			model_class_name(__UpperCAmelCase					)

							_snake_case      			=			model.encode(inputs_dict["input_ids"]					)

							_snake_case			,       _snake_case      			=			(
							    inputs_dict["decoder_input_ids"],
							    inputs_dict["decoder_attention_mask"],
							)

							_snake_case      			=			model.init_cache(decoder_input_ids.shape[0],    __UpperCAmelCase,    __UpperCAmelCase					)
							_snake_case      			=			jnp.ones((decoder_input_ids.shape[0], max_decoder_length),    dtype="i4"					)

							_snake_case      			=			jnp.broadcast_to(
							    jnp.arange(decoder_input_ids.shape[-1] - 1					)[None, :],    (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1),    )
							_snake_case      			=			model.decode(
							    decoder_input_ids[:, :-1],    __UpperCAmelCase,    decoder_attention_mask=__UpperCAmelCase,    past_key_values=__UpperCAmelCase,    decoder_position_ids=__UpperCAmelCase,    )

							_snake_case      			=			jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]],    dtype="i4"					)
							_snake_case      			=			model.decode(
							    decoder_input_ids[:, -1:],    __UpperCAmelCase,    decoder_attention_mask=__UpperCAmelCase,    past_key_values=outputs_cache.past_key_values,    decoder_position_ids=__UpperCAmelCase,    )

							_snake_case      			=			model.decode(__UpperCAmelCase,    __UpperCAmelCase					)

							_snake_case      			=			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])					)					)
							self.parent.assertTrue(diff < 1E-3,    msg=f'''Max diff is {diff}'''					)






					def 							__SCREAMING_SNAKE_CASE      (       self,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					):
							_snake_case      			=			20
							_snake_case      			=			model_class_name(__UpperCAmelCase					)

							_snake_case      			=			model.encode(inputs_dict["input_ids"]					)

							_snake_case			,       _snake_case      			=			(
							    inputs_dict["decoder_input_ids"],
							    inputs_dict["decoder_attention_mask"],
							)

							_snake_case      			=			jnp.concatenate(
							    [
							        decoder_attention_mask,
							        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])					),
							    ],    axis=-1,    )

							_snake_case      			=			model.init_cache(decoder_input_ids.shape[0],    __UpperCAmelCase,    __UpperCAmelCase					)
							_snake_case      			=			jnp.broadcast_to(
							    jnp.arange(decoder_input_ids.shape[-1] - 1					)[None, :],    (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1),    )

							_snake_case      			=			model.decode(
							    decoder_input_ids[:, :-1],    __UpperCAmelCase,    decoder_attention_mask=__UpperCAmelCase,    past_key_values=__UpperCAmelCase,    decoder_position_ids=__UpperCAmelCase,    )
							_snake_case      			=			jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]],    dtype="i4"					)
							_snake_case      			=			model.decode(
							    decoder_input_ids[:, -1:],    __UpperCAmelCase,    past_key_values=outputs_cache.past_key_values,    decoder_attention_mask=__UpperCAmelCase,    decoder_position_ids=__UpperCAmelCase,    )

							_snake_case      			=			model.decode(__UpperCAmelCase,    __UpperCAmelCase,    decoder_attention_mask=__UpperCAmelCase					)

							_snake_case      			=			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])					)					)
							self.parent.assertTrue(diff < 1E-3,    msg=f'''Max diff is {diff}'''					)





@require_flax
class 	lowerCamelCase_				(			__A,			unittest.TestCase,			__A				):




					'''simple docstring'''






					lowercase__       =					True
					lowercase__       =					(FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
					lowercase__       =					(FlaxMarianMTModel,) if is_flax_available() else ()






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			FlaxMarianModelTester(self					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
									self.model_tester.check_use_cache_forward(__UpperCAmelCase,    __UpperCAmelCase,    __UpperCAmelCase					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
									self.model_tester.check_use_cache_forward_with_attn_mask(__UpperCAmelCase,    __UpperCAmelCase,    __UpperCAmelCase					)






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__					):
											_snake_case      			=			self._prepare_for_class(__UpperCAmelCase,    __UpperCAmelCase					)
											_snake_case      			=			model_class(__UpperCAmelCase					)

											@jax.jit
											def encode_jitted(__UpperCamelCase,    __UpperCamelCase=None,    **__UpperCamelCase					):
													return model.encode(input_ids=__UpperCAmelCase,    attention_mask=__UpperCAmelCase					)

											with self.subTest("JIT Enabled"					):
													_snake_case      			=			encode_jitted(**__UpperCAmelCase					).to_tuple()

											with self.subTest("JIT Disabled"					):
													with jax.disable_jit():
															_snake_case      			=			encode_jitted(**__UpperCAmelCase					).to_tuple()

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






					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case			,       _snake_case      			=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__					):
											_snake_case      			=			model_class(__UpperCAmelCase					)
											_snake_case      			=			model.encode(inputs_dict["input_ids"],    inputs_dict["attention_mask"]					)

											_snake_case      			=			{
											    "decoder_input_ids": inputs_dict["decoder_input_ids"],
											    "decoder_attention_mask": inputs_dict["decoder_attention_mask"],
											    "encoder_outputs": encoder_outputs,
											}

											@jax.jit
											def decode_jitted(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase					):
													return model.decode(
													    decoder_input_ids=__UpperCAmelCase,    decoder_attention_mask=__UpperCAmelCase,    encoder_outputs=__UpperCAmelCase,    )

											with self.subTest("JIT Enabled"					):
													_snake_case      			=			decode_jitted(**__UpperCAmelCase					).to_tuple()

											with self.subTest("JIT Disabled"					):
													with jax.disable_jit():
															_snake_case      			=			decode_jitted(**__UpperCAmelCase					).to_tuple()

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






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							for model_class_name in self.all_model_classes:
									_snake_case      			=			model_class_name.from_pretrained("Helsinki-NLP/opus-mt-en-de"					)
									# FlaxMarianForSequenceClassification expects eos token in input_ids
									_snake_case      			=			np.ones((1, 1)					) * model.config.eos_token_id
									_snake_case      			=			model(__UpperCAmelCase					)
									self.assertIsNotNone(__UpperCAmelCase					)





@require_flax
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_				(			unittest.TestCase				):




					'''simple docstring'''






					lowercase__       =					None
					lowercase__       =					None






					@classmethod
					def 							__SCREAMING_SNAKE_CASE      (       cls					):
							_snake_case      			=			f'''Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'''
							return cls






					@cached_property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return MarianTokenizer.from_pretrained(self.model_name					)






					@property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							return self.tokenizer.eos_token_id






					@cached_property
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							_snake_case      			=			FlaxMarianMTModel.from_pretrained(self.model_name					)
							self.assertEqual(model.config.decoder_start_token_id,    model.config.pad_token_id					)
							return model






					def 							__SCREAMING_SNAKE_CASE      (       self,    **__UpperCamelCase					):
							_snake_case      			=			self.translate_src_text(**__UpperCAmelCase					)
							self.assertListEqual(self.expected_text,    __UpperCAmelCase					)






					def 							__SCREAMING_SNAKE_CASE      (       self,    **__UpperCamelCase					):
							_snake_case      			=			self.tokenizer(self.src_text,    padding=__UpperCAmelCase,    return_tensors="np",    **__UpperCAmelCase					)
							_snake_case      			=			self.model.generate(
							    model_inputs.input_ids,    attention_mask=model_inputs.attention_mask,    num_beams=2,    max_length=128,    ).sequences
							_snake_case      			=			self.tokenizer.batch_decode(__UpperCAmelCase,    skip_special_tokens=__UpperCAmelCase					)
							return generated_words





@require_flax
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_				(			__A				):




					'''simple docstring'''






					lowercase__       =					'en'
					lowercase__       =					'fr'
					lowercase__       =					[
					    'I am a small frog.',
					    'Now I can forget the 100 words of german that I know.',
					]
					lowercase__       =					[
					    'Je suis une petite grenouille.',
					    'Maintenant, je peux oublier les 100 mots d\'allemand que je connais.',
					]






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_				(			__A				):




					'''simple docstring'''






					lowercase__       =					'fr'
					lowercase__       =					'en'
					lowercase__       =					[
					    'Donnez moi le micro.',
					    'Tom et Mary étaient assis à une table.',  # Accents
					]
					lowercase__       =					[
					    'Give me the microphone.',
					    'Tom and Mary were sitting at a table.',
					]






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_				(			__A				):




					'''simple docstring'''






					lowercase__       =					'mt'
					lowercase__       =					'en'
					lowercase__       =					['Billi messu b\'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem.']
					lowercase__       =					['Touching gently, Jesus healed a man who was affected by the sad disease of leprosy.']






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_				(			__A				):




					'''simple docstring'''






					lowercase__       =					'en'
					lowercase__       =					'de'
					lowercase__       =					[
					    'I am a small frog.',
					    'Now I can forget the 100 words of german that I know.',
					    'Tom asked his teacher for advice.',
					    'That\'s how I would do it.',
					    'Tom really admired Mary\'s courage.',
					    'Turn around and close your eyes.',
					]
					lowercase__       =					[
					    'Ich bin ein kleiner Frosch.',
					    'Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.',
					    'Tom bat seinen Lehrer um Rat.',
					    'So würde ich das machen.',
					    'Tom bewunderte Marias Mut wirklich.',
					    'Drehen Sie sich um und schließen Sie die Augen.',
					]






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_				(			__A				):




					'''simple docstring'''






					lowercase__       =					'en'
					lowercase__       =					'zh'
					lowercase__       =					['My name is Wolfgang and I live in Berlin']
					lowercase__       =					['我叫沃尔夫冈 我住在柏林']






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_				(			__A				):




					'''simple docstring'''






					lowercase__       =					'ru'
					lowercase__       =					'fr'
					lowercase__       =					['Он показал мне рукопись своей новой пьесы.']
					lowercase__       =					['Il m\'a montré le manuscrit de sa nouvelle pièce.']






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							self._assert_generated_batch_equal_expected()





@require_flax
@require_sentencepiece
@require_tokenizers
class 	lowerCamelCase_				(			__A				):




					'''simple docstring'''






					lowercase__       =					'en'
					lowercase__       =					'ROMANCE'
					lowercase__       =					[
					    '>>fr<< Don\'t spend so much time watching TV.',
					    '>>pt<< Your message has been sent.',
					    '>>es<< He\'s two years older than me.',
					]
					lowercase__       =					[
					    'Ne passez pas autant de temps à regarder la télé.',
					    'A sua mensagem foi enviada.',
					    'Es dos años más viejo que yo.',
					]






					@slow
					def 							__SCREAMING_SNAKE_CASE      (       self					):
							self._assert_generated_batch_equal_expected()






"""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      UpperCamelCase__(      __A			):





						def 					snake_case__						(							self  )       ->					int:
													A__						  =				self.config_class(**self.inputs_dict  )
													self.parent.assertTrue(hasattr(__UpperCAmelCase		,'hidden_sizes'  )  )
													self.parent.assertTrue(hasattr(__UpperCAmelCase		,'num_encoder_blocks'  )  )






class      UpperCamelCase__:





						def __init__(							self		,__UpperCAmelCase		,__UpperCAmelCase=13		,__UpperCAmelCase=64		,__UpperCAmelCase=3		,__UpperCAmelCase=4		,__UpperCAmelCase=[2, 2, 2, 2]		,__UpperCAmelCase=[8, 4, 2, 1]		,__UpperCAmelCase=[16, 32, 64, 1_28]		,__UpperCAmelCase=[1, 4, 8, 16]		,__UpperCAmelCase=False		,__UpperCAmelCase=True		,__UpperCAmelCase="gelu"		,__UpperCAmelCase=0.1		,__UpperCAmelCase=0.0_2		,__UpperCAmelCase=3		,__UpperCAmelCase=None		,)       ->					Tuple:
													A__						  =				parent
													A__						  =				batch_size
													A__						  =				image_size
													A__						  =				num_channels
													A__						  =				num_encoder_blocks
													A__						  =				sr_ratios
													A__						  =				depths
													A__						  =				hidden_sizes
													A__						  =				downsampling_rates
													A__						  =				is_training
													A__						  =				use_labels
													A__						  =				hidden_act
													A__						  =				hidden_dropout_prob
													A__						  =				initializer_range
													A__						  =				num_labels
													A__						  =				scope





						def 					snake_case__						(							self  )       ->					Tuple:
													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.image_size, self.image_size]		,self.num_labels  )

													A__						  =				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 					snake_case__						(							self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )       ->					Union[str, Any]:
													A__						  =				PoolFormerModel(config=__UpperCAmelCase  )
													model.to(__UpperCAmelCase  )
													model.eval()
													A__						  =				model(__UpperCAmelCase  )
													A__						  =				A__						  =				self.image_size // 3_2.0
													self.parent.assertEqual(
													    result.last_hidden_state.shape		,(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)  )





						def 					snake_case__						(							self  )       ->					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      UpperCamelCase__(      __A		,    __A		,    unittest.TestCase			):
						lowerCAmelCase__	:    Optional[int]    				=		(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
						lowerCAmelCase__	:    Optional[Any]    				=		(
						    {'feature-extraction': PoolFormerModel, 'image-classification': PoolFormerForImageClassification}
						    if is_torch_available()
						    else {}
						)

						lowerCAmelCase__	:    Any    				=		False
						lowerCAmelCase__	:    str    				=		False
						lowerCAmelCase__	:    Any    				=		False
						lowerCAmelCase__	:    str    				=		False
						lowerCAmelCase__	:    Optional[int]    				=		False





						def 					snake_case__						(							self  )       ->					Any:
													A__						  =				PoolFormerModelTester(self  )
													A__						  =				PoolFormerConfigTester(self		,config_class=__UpperCAmelCase  )





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





						def 					snake_case__						(							self  )       ->					Tuple:
													A__						  =				self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*__UpperCAmelCase  )





						@unittest.skip('PoolFormer does not use inputs_embeds'  )
						def 					snake_case__						(							self  )       ->					int:
													pass





						@unittest.skip('PoolFormer does not have get_input_embeddings method and get_output_embeddings methods'  )
						def 					snake_case__						(							self  )       ->					List[str]:
													pass





						def 					snake_case__						(							self  )       ->					List[Any]:
													def check_hidden_states_output(__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  ):
																				A__						  =				model_class(__UpperCAmelCase  )
																				model.to(__UpperCAmelCase  )
																				model.eval()

																				with torch.no_grad():
																											A__						  =				model(**self._prepare_for_class(__UpperCAmelCase		,__UpperCAmelCase  )  )

																				A__						  =				outputs.hidden_states

																				A__						  =				self.model_tester.num_encoder_blocks
																				self.assertEqual(len(__UpperCAmelCase  )		,__UpperCAmelCase  )

																				# 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,
																				    ]		,)

													A__  ,	A__						  =				self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				A__						  =				True
																				check_hidden_states_output(__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )

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

																				check_hidden_states_output(__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase  )





						def 					snake_case__						(							self  )       ->					Union[str, Any]:
													if not self.model_tester.is_training:
																				return

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

													for model_class in self.all_model_classes:
																				if model_class in get_values(__UpperCAmelCase  ):
																											continue
																				A__						  =				model_class(__UpperCAmelCase  )
																				model.to(__UpperCAmelCase  )
																				model.train()
																				A__						  =				self._prepare_for_class(__UpperCAmelCase		,__UpperCAmelCase		,return_labels=__UpperCAmelCase  )
																				A__						  =				model(**__UpperCAmelCase  ).loss
																				loss.backward()





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

													for model_class in self.all_model_classes:
																				A__						  =				model_class(__UpperCAmelCase  )
																				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]		,__UpperCAmelCase  )





						@slow
						def 					snake_case__						(							self  )       ->					Union[str, Any]:
													for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				A__						  =				PoolFormerModel.from_pretrained(__UpperCAmelCase  )
																				self.assertIsNotNone(__UpperCAmelCase  )






def 	UpperCAmelCase       (						):






							"""simple docstring"""





							A__						  =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
							return image


@require_torch
class      UpperCamelCase__(      unittest.TestCase			):





						@slow
						def 					snake_case__						(							self  )       ->					Union[str, Any]:
													A__						  =				PoolFormerImageProcessor()
													A__						  =				PoolFormerForImageClassification.from_pretrained('sail/poolformer_s12'  ).to(__UpperCAmelCase  )

													A__						  =				image_processor(images=prepare_img()		,return_tensors='pt'  ).to(__UpperCAmelCase  )

													# forward pass
													with torch.no_grad():
																				A__						  =				model(**__UpperCAmelCase  )

													# verify the logits
													A__						  =				torch.Size((1, 10_00)  )
													self.assertEqual(outputs.logits.shape		,__UpperCAmelCase  )

													A__						  =				torch.tensor([-0.6_1_1_3, 0.1_6_8_5, -0.0_4_9_2]  ).to(__UpperCAmelCase  )
													self.assertTrue(torch.allclose(outputs.logits[0, :3]		,__UpperCAmelCase		,atol=1e-4  )  )





