
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   (						__SCREAMING_SNAKE_CASE						):




	'''simple docstring'''





	def        UpperCamelCase_						( self      :				Any				):
					__A         =				self.config_class(**self.inputs_dict				)
					self.parent.assertTrue(hasattr(A							,"hidden_sizes"				)				)
					self.parent.assertTrue(hasattr(A							,"num_encoder_blocks"				)				)





class 							UpperCAmelCase   :




	'''simple docstring'''





	def __init__( self      :				int							,A      :				str							,A      :				Optional[int]=13							,A      :				Optional[int]=64							,A      :				Union[str, Any]=3							,A      :				int=4							,A      :				str=[2, 2, 2, 2]							,A      :				Dict=[8, 4, 2, 1]							,A      :				List[str]=[16, 32, 64, 1_28]							,A      :				Optional[Any]=[1, 4, 8, 16]							,A      :				int=False							,A      :				Optional[Any]=True							,A      :				Union[str, Any]="gelu"							,A      :				Dict=0.1							,A      :				Optional[int]=0.02							,A      :				List[Any]=3							,A      :				Any=None							,):
					__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        UpperCamelCase_						( self      :				List[str]				):
					__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        UpperCamelCase_						( self      :				List[str]							,A      :				Any							,A      :				Union[str, Any]							,A      :				Dict				):
					__A         =				PoolFormerModel(config=A				)
					model.to(A				)
					model.eval()
					__A         =				model(A				)
					__A         =				__A         =				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        UpperCamelCase_						( self      :				str				):
					__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   (						__SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    unittest.TestCase						):




	'''simple docstring'''





	snake_case_      					=  (PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
	snake_case_      					=  (
	    {"feature-extraction": PoolFormerModel, "image-classification": PoolFormerForImageClassification}
	    if is_torch_available()
	    else {}
	)

	snake_case_      					=  False
	snake_case_      					=  False
	snake_case_      					=  False
	snake_case_      					=  False
	snake_case_      					=  False






	def        UpperCamelCase_						( self      :				Optional[int]				):
					__A         =				PoolFormerModelTester(self				)
					__A         =				PoolFormerConfigTester(self							,config_class=A				)






	def        UpperCamelCase_						( self      :				str				):
					self.config_tester.run_common_tests()






	def        UpperCamelCase_						( self      :				Tuple				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*A				)






	@unittest.skip("PoolFormer does not use inputs_embeds"				)
	def        UpperCamelCase_						( self      :				List[str]				):
					pass






	@unittest.skip("PoolFormer does not have get_input_embeddings method and get_output_embeddings methods"				)
	def        UpperCamelCase_						( self      :				Tuple				):
					pass






	def        UpperCamelCase_						( self      :				Optional[Any]				):
					def check_hidden_states_output(A      :				Optional[Any]							,A      :				Tuple							,A      :				int				):
									__A         =				model_class(A				)
									model.to(A				)
									model.eval()

									with torch.no_grad():
													__A         =				model(**self._prepare_for_class(A							,A				)				)

									__A         =				outputs.hidden_states

									__A         =				self.model_tester.num_encoder_blocks
									self.assertEqual(len(A				)							,A				)

									# 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(A							,A							,A				)

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

									check_hidden_states_output(A							,A							,A				)






	def        UpperCamelCase_						( self      :				Optional[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(A				):
													continue
									__A         =				model_class(A				)
									model.to(A				)
									model.train()
									__A         =				self._prepare_for_class(A							,A							,return_labels=A				)
									__A         =				model(**A				).loss
									loss.backward()






	def        UpperCamelCase_						( self      :				str				):
					__A    ,							__A         =				self.model_tester.prepare_config_and_inputs_for_common()

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







	@slow
	def        UpperCamelCase_						( self      :				Any				):
					for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__A         =				PoolFormerModel.from_pretrained(A				)
									self.assertIsNotNone(A				)





def 		UpperCAmelCase    (			)	->			List[Any]:







				"""simple docstring"""



				__A         =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
				return image





@require_torch
class 							UpperCAmelCase   (						unittest.TestCase						):




	'''simple docstring'''





	@slow
	def        UpperCamelCase_						( self      :				Optional[Any]				):
					__A         =				PoolFormerImageProcessor()
					__A         =				PoolFormerForImageClassification.from_pretrained("sail/poolformer_s12"				).to(A				)

					__A         =				image_processor(images=prepare_img()							,return_tensors="pt"				).to(A				)

					# forward pass
					with torch.no_grad():
									__A         =				model(**A				)

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

					__A         =				torch.tensor([-0.61_13, 0.16_85, -0.04_92]				).to(A				)
					self.assertTrue(torch.allclose(outputs.logits[0, :3]							,A							,atol=1E-4				)				)


import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers.models.speech_to_text_a.modeling_speech_to_text_a import (
					    SpeechaTextaDecoder,
					    SpeechaTextaForCausalLM,
					)





@require_torch
class 							UpperCAmelCase   :




	'''simple docstring'''





	def __init__( self      :				Dict							,A      :				Tuple							,A      :				Union[str, Any]=99							,A      :				Dict=13							,A      :				int=16							,A      :				int=7							,A      :				Optional[int]=True							,A      :				str=True							,A      :				Optional[Any]=True							,A      :				Optional[int]=False							,A      :				Dict=True							,A      :				Any=2							,A      :				List[Any]=32							,A      :				Optional[Any]=4							,A      :				Tuple=4							,A      :				List[Any]=30							,A      :				Optional[Any]=0							,A      :				str=1							,A      :				List[Any]=2							,A      :				List[Any]=None							,):
					__A         =				parent
					__A         =				batch_size
					__A         =				decoder_seq_length
					# For common tests
					__A         =				self.decoder_seq_length
					__A         =				is_training
					__A         =				use_attention_mask
					__A         =				use_labels

					__A         =				vocab_size
					__A         =				d_model
					__A         =				d_model
					__A         =				decoder_layers
					__A         =				decoder_layers
					__A         =				decoder_ffn_dim
					__A         =				decoder_attention_heads
					__A         =				decoder_attention_heads
					__A         =				eos_token_id
					__A         =				bos_token_id
					__A         =				pad_token_id
					__A         =				decoder_start_token_id
					__A         =				use_cache
					__A         =				max_position_embeddings

					__A         =				None
					__A         =				decoder_seq_length
					__A         =				2
					__A         =				1






	def        UpperCamelCase_						( self      :				Tuple				):
					__A         =				ids_tensor([self.batch_size, self.decoder_seq_length]							,self.vocab_size				)

					__A         =				None
					if self.use_attention_mask:
									__A         =				ids_tensor([self.batch_size, self.decoder_seq_length]							,vocab_size=2				)

					__A         =				None
					if self.use_labels:
									__A         =				ids_tensor([self.batch_size, self.decoder_seq_length]							,self.vocab_size				)

					__A         =				SpeechaTextaConfig(
					    vocab_size=self.vocab_size							,d_model=self.d_model							,decoder_layers=self.decoder_layers							,decoder_ffn_dim=self.decoder_ffn_dim							,decoder_attention_heads=self.decoder_attention_heads							,eos_token_id=self.eos_token_id							,bos_token_id=self.bos_token_id							,use_cache=self.use_cache							,pad_token_id=self.pad_token_id							,decoder_start_token_id=self.decoder_start_token_id							,max_position_embeddings=self.max_position_embeddings							,)

					return (
					    config,
					    input_ids,
					    attention_mask,
					    lm_labels,
					)






	def        UpperCamelCase_						( self      :				Tuple							,A      :				List[str]							,A      :				Tuple							,A      :				Optional[int]							,A      :				List[str]							,):
					__A         =				True
					__A         =				SpeechaTextaDecoder(config=A				).to(A				).eval()
					__A         =				input_ids[:2]

					input_ids[input_ids == 0] += 1
					# first forward pass
					__A         =				model(A							,use_cache=A				)
					__A         =				model(A				)
					__A         =				model(A							,use_cache=A				)

					self.parent.assertTrue(len(A				) == len(A				)				)
					self.parent.assertTrue(len(A				) == len(A				) + 1				)

					__A         =				outputs["past_key_values"]

					# create hypothetical next token and extent to next_input_ids
					__A         =				ids_tensor((2, 1)							,config.vocab_size - 1				) + 1

					# append to next input_ids and
					__A         =				torch.cat([input_ids, next_tokens]							,dim=-1				)

					print(A				)

					__A         =				model(A				)["last_hidden_state"]
					__A         =				model(A							,past_key_values=A				)["last_hidden_state"]

					# select random slice
					__A         =				ids_tensor((1,)							,output_from_past.shape[-1]				).item()
					__A         =				output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
					__A         =				output_from_past[:, 0, random_slice_idx].detach()

					# test that outputs are equal for slice
					assert torch.allclose(A							,A							,atol=1E-3				)







	def        UpperCamelCase_						( self      :				Any				):
					__A         =				self.prepare_config_and_inputs()
					(
					    (
					    __A
					)    ,							(
					    __A
					)    ,							(
					    __A
					)    ,							(
					    __A
					)    ,							
					)         =				config_and_inputs

					__A         =				{
					    "input_ids": input_ids,
					    "attention_mask": attention_mask,
					}
					return config, inputs_dict





@require_torch
class 							UpperCAmelCase   (						__SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    unittest.TestCase						):




	'''simple docstring'''





	snake_case_      					=  (SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
	snake_case_      					=  (SpeechaTextaForCausalLM,) if is_torch_available() else ()
	snake_case_      					=  {"text-generation": SpeechaTextaForCausalLM} if is_torch_available() else {}
	snake_case_      					=  True
	snake_case_      					=  False






	def        UpperCamelCase_						( self      :				Any							,):
					__A         =				SpeechaTextaStandaloneDecoderModelTester(self							,is_training=A				)
					__A         =				ConfigTester(self							,config_class=A				)






	def        UpperCamelCase_						( self      :				Optional[Any]				):
					pass






	def        UpperCamelCase_						( self      :				int				):
					pass






	def        UpperCamelCase_						( self      :				Tuple				):
					pass






	def        UpperCamelCase_						( self      :				str				):
					self.config_tester.run_common_tests()






	def        UpperCamelCase_						( self      :				Dict				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_decoder_model_past(*A				)







	def        UpperCamelCase_						( self      :				str				):
					return
